untitled-pixi-live2d-engine 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -108,7 +108,7 @@ var __async = (__this, __arguments, generator) => {
108
108
  preserveExpressionOnMotion: true,
109
109
  cubism: CubismFrameworkConfig
110
110
  };
111
- const VERSION = "1.1.0";
111
+ const VERSION = "1.2.1";
112
112
  const logger = {
113
113
  log(tag, ...messages) {
114
114
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -2179,114 +2179,6 @@ var __async = (__this, __arguments, generator) => {
2179
2179
  }
2180
2180
  throw new TypeError("Missing settings.");
2181
2181
  });
2182
- const _ZipLoader = class _ZipLoader {
2183
- static unzip(reader, settings) {
2184
- return __async(this, null, function* () {
2185
- const filePaths = yield _ZipLoader.getFilePaths(reader);
2186
- const requiredFilePaths = [];
2187
- for (const definedFile of settings.getDefinedFiles()) {
2188
- const actualPath = decodeURI(resolveURL(settings.url, definedFile));
2189
- if (filePaths.includes(actualPath)) {
2190
- requiredFilePaths.push(actualPath);
2191
- }
2192
- }
2193
- const files = yield _ZipLoader.getFiles(reader, requiredFilePaths);
2194
- for (let i = 0; i < files.length; i++) {
2195
- const path = requiredFilePaths[i];
2196
- const file = files[i];
2197
- Object.defineProperty(file, "webkitRelativePath", {
2198
- value: path
2199
- });
2200
- }
2201
- return files;
2202
- });
2203
- }
2204
- static createSettings(reader) {
2205
- return __async(this, null, function* () {
2206
- const filePaths = yield _ZipLoader.getFilePaths(reader);
2207
- const settingsFilePath = filePaths.find(
2208
- (path) => path.endsWith("model.json") || path.endsWith("model3.json")
2209
- );
2210
- if (!settingsFilePath) {
2211
- throw new Error("Settings file not found");
2212
- }
2213
- const settingsText = yield _ZipLoader.readText(reader, settingsFilePath);
2214
- if (!settingsText) {
2215
- throw new Error("Empty settings file: " + settingsFilePath);
2216
- }
2217
- const settingsJSON = JSON.parse(settingsText);
2218
- settingsJSON.url = settingsFilePath;
2219
- const runtime = _ZipLoader.live2dFactory.findRuntime(settingsJSON);
2220
- if (!runtime) {
2221
- throw new Error("Unknown settings JSON");
2222
- }
2223
- return runtime.createModelSettings(settingsJSON);
2224
- });
2225
- }
2226
- static zipReader(data, url) {
2227
- return Promise.reject(new Error("Not implemented"));
2228
- }
2229
- static getFilePaths(reader) {
2230
- return Promise.reject(new Error("Not implemented"));
2231
- }
2232
- static getFiles(reader, paths) {
2233
- return Promise.reject(new Error("Not implemented"));
2234
- }
2235
- static readText(reader, path) {
2236
- return Promise.reject(new Error("Not implemented"));
2237
- }
2238
- static releaseReader(reader) {
2239
- }
2240
- };
2241
- // will be set by Live2DFactory
2242
- __publicField(_ZipLoader, "live2dFactory");
2243
- __publicField(_ZipLoader, "ZIP_PROTOCOL", "zip://");
2244
- __publicField(_ZipLoader, "uid", 0);
2245
- __publicField(_ZipLoader, "factory", (context, next) => __async(null, null, function* () {
2246
- const source = context.source;
2247
- let sourceURL;
2248
- let zipBlob;
2249
- let settings;
2250
- if (typeof source === "string" && (source.endsWith(".zip") || source.startsWith(_ZipLoader.ZIP_PROTOCOL))) {
2251
- if (source.startsWith(_ZipLoader.ZIP_PROTOCOL)) {
2252
- sourceURL = source.slice(_ZipLoader.ZIP_PROTOCOL.length);
2253
- } else {
2254
- sourceURL = source;
2255
- }
2256
- zipBlob = yield Live2DLoader.load({
2257
- url: sourceURL,
2258
- type: "blob",
2259
- target: context.live2dModel
2260
- });
2261
- } else if (Array.isArray(source) && source.length === 1 && source[0] instanceof File && source[0].name.endsWith(".zip")) {
2262
- zipBlob = source[0];
2263
- sourceURL = URL.createObjectURL(zipBlob);
2264
- settings = source.settings;
2265
- }
2266
- if (zipBlob) {
2267
- if (!zipBlob.size) {
2268
- throw new Error("Empty zip file");
2269
- }
2270
- const reader = yield _ZipLoader.zipReader(zipBlob, sourceURL);
2271
- if (!settings) {
2272
- settings = yield _ZipLoader.createSettings(reader);
2273
- }
2274
- settings._objectURL = _ZipLoader.ZIP_PROTOCOL + _ZipLoader.uid + "/" + settings.url;
2275
- const files = yield _ZipLoader.unzip(reader, settings);
2276
- files.settings = settings;
2277
- context.source = files;
2278
- if (sourceURL.startsWith("blob:")) {
2279
- context.live2dModel.once("modelLoaded", (internalModel) => {
2280
- internalModel.once("destroy", function() {
2281
- URL.revokeObjectURL(sourceURL);
2282
- });
2283
- });
2284
- }
2285
- _ZipLoader.releaseReader(reader);
2286
- }
2287
- return next();
2288
- }));
2289
- let ZipLoader = _ZipLoader;
2290
2182
  const _FileLoader = class _FileLoader {
2291
2183
  /**
2292
2184
  * Resolves the path of a resource file to the object URL.
@@ -2567,7 +2459,6 @@ var __async = (__this, __arguments, generator) => {
2567
2459
  * Middlewares to run through when setting up a Live2DModel.
2568
2460
  */
2569
2461
  __publicField(_Live2DFactory, "live2DModelMiddlewares", [
2570
- ZipLoader.factory,
2571
2462
  FileLoader.factory,
2572
2463
  urlToJSON,
2573
2464
  jsonToSettings,
@@ -2593,7 +2484,6 @@ var __async = (__this, __arguments, generator) => {
2593
2484
  return Live2DFactory.loadExpression(this, index);
2594
2485
  };
2595
2486
  FileLoader["live2dFactory"] = Live2DFactory;
2596
- ZipLoader["live2dFactory"] = Live2DFactory;
2597
2487
  const _Automator = class _Automator {
2598
2488
  constructor(model, {
2599
2489
  autoUpdate = true,
@@ -2747,10 +2637,17 @@ var __async = (__this, __arguments, generator) => {
2747
2637
  const tempWorldMatrix = new pixi_js.Matrix();
2748
2638
  const tempDrawableBounds = { x: 0, y: 0, width: 0, height: 0 };
2749
2639
  const tempModelBounds = new pixi_js.Bounds();
2640
+ let live2DPluginFallbackWarned = false;
2750
2641
  class Live2DPipe {
2751
2642
  constructor(renderer) {
2752
2643
  this.renderer = renderer;
2753
2644
  }
2645
+ addRenderable(model, instructionSet) {
2646
+ var _a, _b;
2647
+ const renderPipes = this.renderer.renderPipes;
2648
+ (_b = (_a = renderPipes.batch) == null ? void 0 : _a.break) == null ? void 0 : _b.call(_a, instructionSet);
2649
+ instructionSet.add(model);
2650
+ }
2754
2651
  execute(model) {
2755
2652
  if (!model.visible || model.alpha <= 0) {
2756
2653
  return;
@@ -2759,12 +2656,28 @@ var __async = (__this, __arguments, generator) => {
2759
2656
  }
2760
2657
  updateRenderable() {
2761
2658
  }
2659
+ destroyRenderable() {
2660
+ }
2661
+ validateRenderable() {
2662
+ return false;
2663
+ }
2762
2664
  destroy() {
2763
2665
  }
2764
2666
  }
2667
+ __publicField(Live2DPipe, "extension", {
2668
+ type: [pixi_js.ExtensionType.WebGLPipes],
2669
+ name: "live2d"
2670
+ });
2671
+ const Live2DPlugin = Live2DPipe;
2765
2672
  function ensureLive2DPipe(renderer) {
2766
2673
  const r = renderer;
2767
2674
  if (!r.renderPipes.live2d) {
2675
+ if (!live2DPluginFallbackWarned) {
2676
+ live2DPluginFallbackWarned = true;
2677
+ console.warn(
2678
+ "[untitled-pixi-live2d-engine] Lazy Live2D render pipe registration is deprecated. Register Live2DPlugin explicitly with `extensions.add(Live2DPlugin)` before creating the Pixi renderer."
2679
+ );
2680
+ }
2768
2681
  r.renderPipes.live2d = new Live2DPipe(renderer);
2769
2682
  }
2770
2683
  }
@@ -3114,9 +3027,7 @@ var __async = (__this, __arguments, generator) => {
3114
3027
  ensureLive2DPipe(renderer);
3115
3028
  const renderPipes = renderer.renderPipes;
3116
3029
  const addRenderable = () => {
3117
- var _a2, _b2;
3118
- (_b2 = (_a2 = renderPipes.batch) == null ? void 0 : _a2.break) == null ? void 0 : _b2.call(_a2, instructionSet);
3119
- instructionSet.add(this);
3030
+ renderPipes.live2d.addRenderable(this, instructionSet);
3120
3031
  };
3121
3032
  const collectChildren = () => {
3122
3033
  const children = this.children;
@@ -4435,6 +4346,7 @@ var __async = (__this, __arguments, generator) => {
4435
4346
  exports2.Live2DLoader = Live2DLoader;
4436
4347
  exports2.Live2DModel = Live2DModel;
4437
4348
  exports2.Live2DPhysics = Live2DPhysics;
4349
+ exports2.Live2DPlugin = Live2DPlugin;
4438
4350
  exports2.Live2DPose = Live2DPose;
4439
4351
  exports2.Live2DTransform = Live2DTransform;
4440
4352
  exports2.MBToByte = MBToByte;
@@ -4447,7 +4359,6 @@ var __async = (__this, __arguments, generator) => {
4447
4359
  exports2.VERSION = VERSION;
4448
4360
  exports2.VOLUME = VOLUME;
4449
4361
  exports2.XHRLoader = XHRLoader;
4450
- exports2.ZipLoader = ZipLoader;
4451
4362
  exports2.applyMixins = applyMixins;
4452
4363
  exports2.clamp = clamp$1;
4453
4364
  exports2.config = config;
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("pixi.js"),require("@pixi/sound")):"function"==typeof define&&define.amd?define(["exports","pixi.js","@pixi/sound"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI,t.PIXI)}(this,function(t,e,i){"use strict";var s=Object.defineProperty,r=Object.defineProperties,o=Object.getOwnPropertyDescriptors,n=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable,h=Math.pow,d=(t,e,i)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,u=(t,e)=>{for(var i in e||(e={}))a.call(e,i)&&d(t,i,e[i]);if(n)for(var i of n(e))l.call(e,i)&&d(t,i,e[i]);return t},c=(t,e,i)=>d(t,"symbol"!=typeof e?e+"":e,i),p=(t,e,i)=>new Promise((s,r)=>{var o=t=>{try{a(i.next(t))}catch(e){r(e)}},n=t=>{try{a(i.throw(t))}catch(e){r(e)}},a=t=>t.done?s(t.value):Promise.resolve(t.value).then(o,n);a((i=i.apply(t,e)).next())});const g={LOG_LEVEL_VERBOSE:0,LOG_LEVEL_WARNING:1,LOG_LEVEL_ERROR:2,LOG_LEVEL_NONE:999,logLevel:1,sound:!0,fftSize:512,motionSync:!0,motionFadingDuration:500,idleMotionFadingDuration:2e3,expressionFadingDuration:500,preserveExpressionOnMotion:!0,cubism:Object.freeze(Object.defineProperty({__proto__:null,CSM_LOG_LEVEL:0,CSM_LOG_LEVEL_DEBUG:1,CSM_LOG_LEVEL_ERROR:4,CSM_LOG_LEVEL_INFO:2,CSM_LOG_LEVEL_OFF:5,CSM_LOG_LEVEL_VERBOSE:0,CSM_LOG_LEVEL_WARNING:3},Symbol.toStringTag,{value:"Module"}))},m={log(t,...e){g.logLevel<=g.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){g.logLevel<=g.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){g.logLevel<=g.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function f(t,e,i){return t<e?e:t>i?i:t}function M(t,e){return Math.random()*(e-t)+t}function y(t,e,i,s,r){const o=e[s];null!==o&&typeof o===t&&(i[r]=o)}function x(t,e,i,s,r){const o=e[s];Array.isArray(o)&&(i[r]=o.filter(e=>null!==e&&typeof e===t))}function v(t){let e=t.lastIndexOf("/");return-1!=e&&(t=t.slice(0,e)),e=t.lastIndexOf("/"),-1!==e&&(t=t.slice(e+1)),t}function E(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}const b=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function P(t,e){if(!e)return t;if(b.test(e))return e;if(e.startsWith("/"))return b.test(t)?new URL(e,t).toString():e;if(b.test(t))return new URL(e,t).toString();const i="http://example.com",s=t.startsWith("/")?i+t:`${i}/${t}`,r=new URL(e,s);let o=r.pathname+r.search+r.hash;return!t.startsWith("/")&&o.startsWith("/")&&(o=o.slice(1)),o}class w extends e.EventEmitter{constructor(t,e){super(),c(this,"expressionDataType","json"),c(this,"tag"),c(this,"settings"),c(this,"expressions",[]),c(this,"defaultExpression"),c(this,"currentExpression"),c(this,"reserveExpressionIndex",-1),c(this,"destroyed",!1),this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createDefaultExpression(),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}createDefaultExpression(){return this.createExpression({},void 0)}loadExpression(t){return p(this,null,function*(){if(!this.definitions[t])return void m.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void m.warn(this.tag,`Cannot set expression at [${t}] because it's already failed in loading.`);if(this.expressions[t])return this.expressions[t];const e=yield this._loadExpression(t);return this.expressions[t]=e,e})}_loadExpression(t){throw new Error("Not implemented.")}setRandomExpression(){return p(this,null,function*(){if(this.definitions.length){const t=[];for(let e=0;e<this.definitions.length;e++)null!==this.expressions[e]&&this.expressions[e]!==this.currentExpression&&e!==this.reserveExpressionIndex&&t.push(e);if(t.length){const e=Math.floor(Math.random()*t.length);return this.setExpression(e)}}return!1})}resetExpression(){this._setExpression(this.defaultExpression)}restoreExpression(){this._setExpression(this.currentExpression)}setExpression(t){return p(this,null,function*(){if("number"!=typeof t&&(t=this.getExpressionIndex(t)),!(t>-1&&t<this.definitions.length))return!1;if(t===this.expressions.indexOf(this.currentExpression))return!1;this.reserveExpressionIndex=t;const e=yield this.loadExpression(t);return!(!e||this.reserveExpressionIndex!==t)&&(this.reserveExpressionIndex=-1,this.currentExpression=e,this._setExpression(e),!0)})}update(t,e){return!this.isFinished()&&this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy");this.definitions=void 0,this.expressions=void 0}}const L=40/7.5,I=1/150;class _{constructor(){c(this,"targetX",0),c(this,"targetY",0),c(this,"x",0),c(this,"y",0),c(this,"vx",0),c(this,"vy",0)}focus(t,e,i=!1){this.targetX=f(t,-1,1),this.targetY=f(e,-1,1),i&&(this.x=this.targetX,this.y=this.targetY)}update(t){const e=this.targetX-this.x,i=this.targetY-this.y;if(Math.abs(e)<.01&&Math.abs(i)<.01)return;const s=Math.sqrt(h(e,2)+h(i,2)),r=L/(1e3/t);let o=r*(e/s)-this.vx,n=r*(i/s)-this.vy;const a=Math.sqrt(h(o,2)+h(n,2)),l=r*I*t;a>l&&(o*=l/a,n*=l/a),this.vx+=o,this.vy+=n;const d=Math.sqrt(h(this.vx,2)+h(this.vy,2)),u=.5*(Math.sqrt(h(l,2)+8*l*s)-l);d>u&&(this.vx*=u/d,this.vy*=u/d),this.x+=this.vx,this.y+=this.vy}}class O{constructor(t){c(this,"json"),c(this,"name"),c(this,"url"),c(this,"pose"),c(this,"physics"),this.json=t,this.url=t.url,this.name=v(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=v(this.url))}setModelName(...t){for(const e of t){const t="string"==typeof e?e.trim():"";if(t&&"name"!==t.toLowerCase())return void(this.name=t)}this.normalizeName()}getFileStem(t){if(!t)return;const e=t.split(/[/\\]/).filter(Boolean).pop();return null==e?void 0:e.replace(/\.[^.]+$/,"")}resolveURL(t){return P(this.url,t)}replaceFiles(t){this.moc=t(this.moc,"moc"),void 0!==this.pose&&(this.pose=t(this.pose,"pose")),void 0!==this.physics&&(this.physics=t(this.physics,"physics"));for(let e=0;e<this.textures.length;e++)this.textures[e]=t(this.textures[e],`textures[${e}]`)}getDefinedFiles(){const t=[];return this.replaceFiles(e=>(t.push(e),e)),t}validateFiles(t){const e=(e,i)=>{const s=this.resolveURL(e);if(!t.includes(s)){if(i)throw new Error(`File "${e}" is defined in settings, but doesn't exist in given files`);return!1}return!0};[this.moc,...this.textures].forEach(t=>e(t,!0));return this.getDefinedFiles().filter(t=>e(t,!1))}}var F=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(F||{});class A{constructor(){c(this,"tag"),c(this,"debug",!1),c(this,"currentPriority",0),c(this,"reservePriority",0),c(this,"currentGroup"),c(this,"currentIndex"),c(this,"reservedGroup"),c(this,"reservedIndex"),c(this,"reservedIdleGroup"),c(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return m.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return m.log(this.tag,"Motion is already playing.",this.dump(t,e)),!1;if(t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex)return m.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return m.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return m.log(this.tag,"Cannot start idle motion because another idle motion has reserved.",this.dump(t,e)),!1;this.setReservedIdle(t,e)}else{if(i<3){if(i<=this.currentPriority)return m.log(this.tag,"Cannot start motion because another motion is playing as an equivalent or higher priority.",this.dump(t,e)),!1;if(i<=this.reservePriority)return m.log(this.tag,"Cannot start motion because another motion has reserved as an equivalent or higher priority.",this.dump(t,e)),!1}this.setReserved(t,e,i)}return!0}start(t,e,i,s){if(1===s){if(this.setReservedIdle(void 0,void 0),0!==this.currentPriority)return m.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(e,i)),!1}else{if(e!==this.reservedGroup||i!==this.reservedIndex)return m.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(e,i)),!1;this.setReserved(void 0,void 0,0)}return!!t&&(this.setCurrent(e,i,s),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(t,e,i){this.currentPriority=i,this.currentGroup=t,this.currentIndex=e}setReserved(t,e,i){this.reservePriority=i,this.reservedGroup=t,this.reservedIndex=e}setReservedIdle(t,e){this.reservedIdleGroup=t,this.reservedIdleIndex=e}isActive(t,e){return t===this.currentGroup&&e===this.currentIndex||t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex}reset(){this.setCurrent(void 0,void 0,0),this.setReserved(void 0,void 0,0),this.setReservedIdle(void 0,void 0)}shouldRequestIdleMotion(){return void 0===this.currentGroup&&void 0===this.reservedIdleGroup}shouldOverrideExpression(){return!g.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n<Requested> group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map(t=>"["+t+"] "+this[t]).join("\n")}return""}}const T="SoundManager",D=.5;i.sound.disableAutoPause=!0;class R{static get volume(){return this._volume}static set volume(t){this._volume=(t>1?1:t<0?0:t)||0,this.audios.forEach(t=>t.volume=this._volume)}static add(t,e){return p(this,null,function*(){try{const e=new Promise((e,s)=>{const r=i.Sound.from({url:t,volume:this._volume,preload:!0,loaded:()=>{r.media instanceof i.webaudio.WebAudioMedia||s(new Error(`Error: ${t} is not WebAudioMedia`)),e(r)}})});return yield e}catch(s){return m.warn(T,`Error occurred on "${t}"`,s),null==e||e(s),null}})}static play(t,e){t.play({singleInstance:!0,complete:()=>{null==e||e(),t.destroy()}})}static addAnalyzer(t,e){const i=t.media,s=e.createBufferSource();s.buffer=i.buffer;const r=e.createAnalyser();return r.fftSize=g.fftSize,r.minDecibels=-90,r.maxDecibels=-10,r.smoothingTimeConstant=.85,s.connect(r),s.start(0),this.analysers.push(r),r}static analyze(t){if(!t)return parseFloat(Math.random().toFixed(1));const e=new Float32Array(t.fftSize);t.getFloatTimeDomainData(e);let i=0;for(let n=0;n<e.length;n++)i+=h(e[n],2);const s=Math.sqrt(i/e.length),r=20*Math.log10(s||h(10,-5)),o=Math.min(Math.max((r-t.minDecibels)/(t.maxDecibels-t.minDecibels),0),1);return parseFloat(o.toFixed(1))}static dispose(t){t.pause(),E(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--){const e=this.contexts[t];null==e||e.close().catch(t=>{m.warn(T,"Failed to close AudioContext.",t)})}for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}c(R,"audios",[]),c(R,"analysers",[]),c(R,"contexts",[]),c(R,"_volume",D);var S=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(S||{});class C extends e.EventEmitter{constructor(t){super(),c(this,"tag"),c(this,"settings"),c(this,"motionGroups",{}),c(this,"state",new A),c(this,"currentAudio"),c(this,"currentAnalyzer"),c(this,"currentContext"),c(this,"playing",!1),c(this,"destroyed",!1),c(this,"parent"),this.settings=t.settings,this.tag=`MotionManager(${this.settings.name})`,this.state.tag=this.tag,this.parent=t}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){if(!this.definitions)return void m.warn(this.tag,"Motion definitions are not initialized.");for(const i of Object.keys(this.definitions))this.motionGroups[i]=[];let e;switch(null==t?void 0:t.motionPreload){case"NONE":return;case"ALL":e=Object.keys(this.definitions);break;default:e=[this.groups.idle]}for(const i of e){const t=this.definitions[i];if(t)for(let e=0;e<t.length;e++)this.loadMotion(i,e)}}loadMotion(t,e){return p(this,null,function*(){var i,s;if(this.destroyed)return;if(!this.getMotionDefinition(t,e))return;const r=null!=(s=(i=this.motionGroups)[t])?s:i[t]=[];if(null===r[e])return void m.warn(this.tag,`Cannot start motion at "${t}"[${e}] because it's already failed in loading.`);if(r[e])return r[e];const o=yield this._loadMotion(t,e);return this.destroyed?void 0:(r[e]=null!=o?o:null,o)})}_loadMotion(t,e){throw new Error("Not implemented.")}initializeAudio(t,e){this.currentAudio=t,R.volume=e,this.currentContext=t.context.audioContext,this.currentAnalyzer=R.addAnalyzer(this.currentAudio,this.currentContext)}speak(t){return p(this,arguments,function*(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:o}={}){if(!g.sound)return!1;let n,a;if(this.currentAudio&&this.currentAudio.isPlaying)return!1;const l=t&&t.startsWith("data:");if(t&&!l){const e=document.createElement("a");e.href=t,a=t=e.href}else a="data:audio/";const h=t;if(h)try{n=yield R.add(h,(t,e=this)=>{m.error(this.tag,"Error during audio playback:",t),null==o||o(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),this.initializeAudio(n,e)}catch(d){return m.warn(this.tag,"Failed to create audio",a,d),!1}if(n){let t=!0;try{g.motionSync&&R.play(n,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(d){m.warn(this.tag,"Failed to play audio",n.url,d),t=!1}if(!t)return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&(yield this.expressionManager.setExpression(i)),this.playing=!0,!0})}startMotion(t,e){return p(this,arguments,function*(t,e,i=F.NORMAL,{sound:s,volume:r=.5,expression:o,resetExpression:n=!0,onFinish:a,onError:l,ignoreParamIds:h=[]}={}){if(this.destroyed)return!1;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=F.FORCE)return!1;const d=this.getMotionDefinition(t,e);if(!d)return!1;let u,c;this.currentAudio&&R.dispose(this.currentAudio);const p=s&&s.startsWith("data:");if(s&&!p){const t=document.createElement("a");t.href=s,c=s=t.href}else c=this.getSoundFile(d),c&&(c=this.settings.resolveURL(c));const f=c;if(f)try{u=yield R.add(f,(t,e=this)=>{m.error(this.tag,"Error during audio playback:",t),null==l||l(t),n&&o&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),this.initializeAudio(u,r)}catch(y){m.warn(this.tag,"Failed to create audio",c,y)}const M=yield this.loadMotion(t,e);if(u&&g.motionSync)try{R.play(u,(t=this)=>{null==a||a(),n&&o&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0})}catch(y){m.warn(this.tag,"Failed to play audio",u.url,y)}return this.state.start(M,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),m.log(this.tag,"Start motion:",this.getMotionName(d)),this.emit("motionStart",t,e,u),o&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(o)),this.playing=!0,M&&this._startMotion(M,void 0,h),!0):(u&&(R.dispose(u),this.currentAudio=void 0),!1)})}startRandomMotion(t,e){return p(this,arguments,function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:o=!0,onFinish:n,onError:a}={}){var l,h;if(this.destroyed)return!1;const d=null==(l=this.definitions)?void 0:l[t];if(null==d?void 0:d.length){const l=[],u=null!=(h=this.motionGroups[t])?h:[];for(let e=0;e<d.length;e++)null===u[e]||this.state.isActive(t,e)||l.push(e);if(l.length){const h=l[Math.floor(Math.random()*l.length)];return this.startMotion(t,h,e,{sound:i,volume:s,expression:r,resetExpression:o,onFinish:n,onError:a})}}return!1})}stopSpeaking(){this.currentAudio&&(R.dispose(this.currentAudio),this.currentAudio=void 0)}stopAllMotions(){this._stopAllMotions(),this.state.reset(),this.stopSpeaking()}update(t,e){var i;return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.shouldOverrideExpression()&&(null==(i=this.expressionManager)||i.restoreExpression()),this.state.complete(),this.state.shouldRequestIdleMotion()&&this.startRandomMotion(this.groups.idle,F.IDLE)),this.updateParameters(t,e)}mouthSync(){return this.currentAnalyzer?R.analyze(this.currentAnalyzer):0}destroy(){var t;this.destroyed=!0,this.emit("destroy"),this.stopAllMotions(),null==(t=this.expressionManager)||t.destroy();this.definitions=void 0,this.motionGroups=void 0}getMotionAndApplyExpression(t,e,i){return p(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(t,e,F.FORCE))return null;const s=this.getMotionDefinition(t,e);if(!s)return null;this.currentAudio&&R.dispose(this.currentAudio);const r=yield this.loadMotion(t,e);return this.state.start(r,t,e,F.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),m.log(this.tag,"Start motion:",this.getMotionName(s)),this.emit("motionStart",t,e,void 0),i&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(i)),r):null})}getMotionDefinition(t,e){var i,s;const r=null==(s=null==(i=this.definitions)?void 0:i[t])?void 0:s[e];return r||m.warn(this.tag,`Undefined motion at "${t}"[${e}]`),r}}function k(t,e){if(!Array.isArray(t))return[];const i=[];for(const s of t){if(!s||"object"!=typeof s)continue;const t=s,r="string"==typeof t.id?t.id:"string"==typeof t.Id?t.Id:void 0,o="string"==typeof t.name?t.name:"string"==typeof t.Name?t.Name:void 0;r&&o&&i.push({id:r,name:o,index:e(r)})}return i}const N={x:0,y:0,width:0,height:0};class j extends e.EventEmitter{constructor(){super(...arguments),c(this,"focusController",new _),c(this,"pose"),c(this,"physics"),c(this,"originalWidth",0),c(this,"originalHeight",0),c(this,"width",0),c(this,"height",0),c(this,"localTransform",new e.Matrix),c(this,"drawingMatrix",new e.Matrix),c(this,"hitAreas",{}),c(this,"textureFlipY",!1),c(this,"viewport",[0,0,0,0]),c(this,"destroyed",!1)}init(){this.setupLayout(),this.setupHitAreas()}setupLayout(){const t=this,e=this.getSize();t.originalWidth=e[0],t.originalHeight=e[1];const i=Object.assign({width:2,height:2},this.getLayout());this.localTransform.scale(i.width/2,i.height/2),t.width=this.originalWidth*this.localTransform.a,t.height=this.originalHeight*this.localTransform.d;const s=void 0!==i.x&&i.x-i.width/2||void 0!==i.centerX&&i.centerX||void 0!==i.left&&i.left-i.width/2||void 0!==i.right&&i.right+i.width/2||0,r=void 0!==i.y&&i.y-i.height/2||void 0!==i.centerY&&i.centerY||void 0!==i.top&&i.top-i.height/2||void 0!==i.bottom&&i.bottom+i.height/2||0;this.localTransform.translate(this.width*s,-this.height*r)}setupHitAreas(){const t=this.getHitAreaDefs();this.hitAreas={};for(const e of t)e.name&&(this.hitAreas[e.name]=e)}hitTest(t,e){return Object.keys(this.hitAreas).filter(i=>this.isHit(i,t,e))}isHit(t,e,i){const s=this.hitAreas[t];if(!s)return!1;let r=s.index;if(r<0){if(!s.id)return!1;if(r=this.getDrawableIndex(s.id),r<0)return!1;s.index=r}const o=this.getDrawableBounds(r,N);return o.x<=e&&e<=o.x+o.width&&o.y<=i&&i<=o.y+o.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],o=i[1],n=i[1];for(let a=0;a<i.length;a+=2){const t=i[a],e=i[a+1];s=Math.min(t,s),r=Math.max(t,r),o=Math.min(e,o),n=Math.max(e,n)}return null!=e||(e={}),e.x=s,e.y=o,e.width=r-s,e.height=n-o,e}updateTransform(t){this.drawingMatrix.copyFrom(t).append(this.localTransform)}update(t,e){this.focusController.update(t)}destroy(){this.destroyed=!0,this.emit("destroy"),this.motionManager.destroy(),this.motionManager=void 0,this.parallelMotionManager.forEach(t=>t.destroy()),this.parallelMotionManager=[]}updateMotions(t,e){this.emit("beforeMotionUpdate");const i=this.motionManager.update(t,e),s=this.parallelMotionManager.map(i=>i.update(t,e)),r=i||s.reduce((t,e)=>t||e,!1);return this.emit("afterMotionUpdate"),r}}class G extends Error{constructor(t,e,i,s=!1){super(t),this.url=e,this.status=i,this.aborted=s}}const H=class t{static createXHR(e,i,s,r,o){const n=new XMLHttpRequest;if(t.allXhrSet.add(n),e){let i=t.xhrMap.get(e);i?i.add(n):(i=new Set([n]),t.xhrMap.set(e,i))}return n.open("GET",i),n.responseType=s,n.onload=()=>{var t;200!==n.status&&0!==n.status||!n.response?null==(t=n.onerror)||t.call(n,new ProgressEvent("error")):r(n.response)},n.onerror=()=>{m.warn("XHRLoader",`Failed to load resource as ${n.responseType} (Status ${n.status}): ${i}`),o(new G("Network error.",i,n.status))},n.onabort=()=>o(new G("Aborted.",i,n.status,!0)),n.onloadend=()=>{var i;t.allXhrSet.delete(n),e&&(null==(i=t.xhrMap.get(e))||i.delete(n))},n}static cancelXHRs(){var e;null==(e=t.xhrMap.get(this))||e.forEach(e=>{e.abort(),t.allXhrSet.delete(e)}),t.xhrMap.delete(this)}static release(){t.allXhrSet.forEach(t=>t.abort()),t.allXhrSet.clear(),t.xhrMap=new WeakMap}};c(H,"xhrMap",new WeakMap),c(H,"allXhrSet",new Set),c(H,"loader",t=>new Promise((e,i)=>{const s=t.target,r=t.target&&"function"==typeof H.cancelXHRs?H.cancelXHRs.bind(t.target):void 0,o=H.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,i=>{t.result=i,e()},i);if(t.target&&r&&"function"==typeof s.listeners&&"function"==typeof s.once){const t=s.listeners("destroy");Array.isArray(t)&&t.includes(r)||s.once("destroy",r)}o.send()}));let U=H;function X(t,e){let i=-1;return function s(r,o){if(o)return Promise.reject(o);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const n=t[r];if(!n)return Promise.resolve();try{return Promise.resolve(n(e,s.bind(null,r+1)))}catch(a){const t=a instanceof Error?a:new Error(String(a));return Promise.reject(t)}}(0)}class W{static load(t){return p(this,null,function*(){return yield X(this.middlewares,t),t.result})}}c(W,"middlewares",[U.loader]);class B extends O{constructor(t){if(super(t),c(this,"moc"),c(this,"textures"),c(this,"layout"),c(this,"hitAreas"),c(this,"initParams"),c(this,"initOpacities"),c(this,"expressions"),c(this,"motions",{}),!B.isValidJSON(t))throw new TypeError("Invalid JSON.");this.moc=t.model,x("string",t,this,"textures","textures"),this.copy(t)}static isValidJSON(t){if(!t||"object"!=typeof t)return!1;const e=!!Array.isArray(t.textures)&&t.textures.every(t=>"string"==typeof t);return"string"==typeof t.model&&e}copy(t){y("string",t,this,"name","name"),y("string",t,this,"pose","pose"),y("string",t,this,"physics","physics"),y("object",t,this,"layout","layout"),y("object",t,this,"motions","motions"),x("object",t,this,"hit_areas","hitAreas"),x("object",t,this,"expressions","expressions"),x("object",t,this,"init_params","initParams"),x("object",t,this,"init_opacities","initOpacities");const e=this.getFileStem(this.moc);this.setModelName(this.name,e)}replaceFiles(t){super.replaceFiles(t);for(const[e,i]of Object.entries(this.motions))for(let s=0;s<i.length;s++)i[s].file=t(i[s].file,`motions.${e}[${s}].file`),void 0!==i[s].sound&&(i[s].sound=t(i[s].sound,`motions.${e}[${s}].sound`));if(this.expressions)for(let e=0;e<this.expressions.length;e++)this.expressions[e].file=t(this.expressions[e].file,`expressions[${e}].file`)}}function $({lod:t,effectiveScale:e,textureWidth:i,textureHeight:s,lodScaleThreshold:r,lodTextureSizeThreshold:o,lodMaxLevel:n}){if("single-auto"!==z(t))return;if(!Number.isFinite(e)||e<=0)return;const a=Math.floor(i),l=Math.floor(s);if(a<=1||l<=1)return;if(e>=V(r,.5))return;const d=V(o,4096);if(Math.max(a,l)<d)return;const u=Math.round(Math.log2(1/e)),c=Math.max(1,Math.floor(Math.log2(Math.max(a,l)))),p=Math.min(c,(m=c,void 0!==(g=n)&&Number.isFinite(g)&&g>=1?Math.floor(g):m));var g,m;const f=function(t,e,i){return Math.min(i,Math.max(e,t))}(Math.max(1,u),1,p),M=h(2,f);return{level:f,width:Math.max(1,Math.round(a/M)),height:Math.max(1,Math.round(l/M))}}function z(t){return!1===t||"single-auto"===t?t:"full"}function q(t){return"nearest"===t?"nearest":"linear"}function V(t,e){return void 0!==t&&Number.isFinite(t)&&t>0?t:e}function Y(){}const J="Live2DFactory",Z=(t,e)=>p(null,null,function*(){if("string"==typeof t.source){const e=yield W.load({url:t.source,type:"json",target:t.live2dModel});e.url="string"==typeof e.url?e.url:t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()}),Q=(t,e)=>p(null,null,function*(){if(t.source instanceof O)return t.settings=t.source,e();if("object"==typeof t.source){const i=lt.findRuntime(t.source);if(i){const s=i.createModelSettings(t.source);return t.settings=s,t.live2dModel.emit("settingsLoaded",s),e()}}const i=t.source&&"string"==typeof t.source.url?t.source.url:void 0,s=lt.runtimes.map(t=>t.version).join(", ");if(0===lt.runtimes.length)throw new TypeError(["Unknown settings format: no Live2D runtimes registered.",'Import a published runtime entry before loading models (e.g. "<package>/cubism" for Cubism 3/4/5, "<package>/cubism-legacy" for Cubism 2).',i?`Settings URL: ${i}`:void 0].filter(Boolean).join("\n"));const r=(()=>{try{if(!t.source||"object"!=typeof t.source||Array.isArray(t.source))return;return Object.keys(t.source).slice(0,30).join(", ")}catch(e){return}})();throw new TypeError(["Unknown settings format: no matching runtime found for the loaded settings JSON.",s?`Registered runtimes (versions): ${s}`:void 0,r?`Settings JSON keys: ${r}`:void 0,i?`Settings URL: ${i}`:void 0].filter(Boolean).join("\n"))}),K=(t,e)=>{if(t.settings){const i=lt.findRuntime(t.settings);if(i)return i.ready().then(()=>e())}return e()},tt=(t,e)=>p(null,null,function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=lt.findRuntime(e);if(s){const r=[],o=e instanceof B?"json":"arraybuffer";e.pose&&r.push(W.load({settings:e,url:e.pose,type:o,target:i}).then(e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)}).catch(e=>{t.live2dModel.emit("poseLoadError",e),m.warn(J,"Failed to load pose.",e)})),e.physics&&r.push(W.load({settings:e,url:e.physics,type:o,target:i}).then(e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)}).catch(e=>{t.live2dModel.emit("physicsLoadError",e),m.warn(J,"Failed to load physics.",e)})),r.length&&(yield Promise.all(r))}}}),et=(t,i)=>p(null,null,function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=u({crossOrigin:t.options.crossOrigin},t.options.textureOptions);t.settings instanceof B&&(r.preferCreateImageBitmap=!1);const o=Promise.all(t.settings.textures.map(i=>function(t,i={}){const s=e.loadTextures.config,r=null==s?void 0:s.crossOrigin,o=null==s?void 0:s.preferCreateImageBitmap,n=null==s?void 0:s.preferWorkers;return void 0!==i.crossOrigin&&s&&(s.crossOrigin=i.crossOrigin),!1===i.preferCreateImageBitmap&&s&&(s.preferCreateImageBitmap=!1,s.preferWorkers=!1),e.Assets.load({src:t,data:{autoGenerateMipmaps:"full"===z(i.lod)}}).catch(t=>{if(t instanceof Error)throw t;throw new Error("Texture loading error",{cause:t})}).finally(()=>{s&&(s.crossOrigin=null!=r?r:s.crossOrigin,!1===i.preferCreateImageBitmap&&(s.preferCreateImageBitmap=null!=o?o:s.preferCreateImageBitmap,s.preferWorkers=null!=n?n:s.preferWorkers))})}(t.settings.resolveURL(i),r)));if(o.catch(Y),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield o,s.emit("textureLoaded",s.textures)}}),it=(t,e)=>p(null,null,function*(){const i=t.settings;if(i instanceof O){const s=lt.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield W.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const o=s.createCoreModel(r);return t.internalModel=s.createInternalModel(o,i,t.options),e()}throw new TypeError("Missing settings.")}),st=class t{static unzip(e,i){return p(this,null,function*(){const s=yield t.getFilePaths(e),r=[];for(const t of i.getDefinedFiles()){const e=decodeURI(P(i.url,t));s.includes(e)&&r.push(e)}const o=yield t.getFiles(e,r);for(let t=0;t<o.length;t++){const e=r[t],i=o[t];Object.defineProperty(i,"webkitRelativePath",{value:e})}return o})}static createSettings(e){return p(this,null,function*(){const i=(yield t.getFilePaths(e)).find(t=>t.endsWith("model.json")||t.endsWith("model3.json"));if(!i)throw new Error("Settings file not found");const s=yield t.readText(e,i);if(!s)throw new Error("Empty settings file: "+i);const r=JSON.parse(s);r.url=i;const o=t.live2dFactory.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");return o.createModelSettings(r)})}static zipReader(t,e){return Promise.reject(new Error("Not implemented"))}static getFilePaths(t){return Promise.reject(new Error("Not implemented"))}static getFiles(t,e){return Promise.reject(new Error("Not implemented"))}static readText(t,e){return Promise.reject(new Error("Not implemented"))}static releaseReader(t){}};c(st,"live2dFactory"),c(st,"ZIP_PROTOCOL","zip://"),c(st,"uid",0),c(st,"factory",(t,e)=>p(null,null,function*(){const i=t.source;let s,r,o;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(st.ZIP_PROTOCOL))?(s=i.startsWith(st.ZIP_PROTOCOL)?i.slice(st.ZIP_PROTOCOL.length):i,r=yield W.load({url:s,type:"blob",target:t.live2dModel})):Array.isArray(i)&&1===i.length&&i[0]instanceof File&&i[0].name.endsWith(".zip")&&(r=i[0],s=URL.createObjectURL(r),o=i.settings),r){if(!r.size)throw new Error("Empty zip file");const e=yield st.zipReader(r,s);o||(o=yield st.createSettings(e)),o._objectURL=st.ZIP_PROTOCOL+st.uid+"/"+o.url;const i=yield st.unzip(e,o);i.settings=o,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",t=>{t.once("destroy",function(){URL.revokeObjectURL(s)})}),st.releaseReader(e)}return e()}));let rt=st;const ot=class t{static resolveURL(e,i){var s;const r=null==(s=t.filesMap[e])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(e,i){const s={};for(const t of i.getDefinedFiles()){const r=decodeURI(P(i.url,t)),o=e.find(t=>t.webkitRelativePath===r);o&&(s[t]=URL.createObjectURL(o))}t.filesMap[i._objectURL]=s}static createSettings(e){return p(this,null,function*(){const i=e.find(t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json"));if(!i)throw new TypeError("Settings file not found");const s=yield t.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const o=lt.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");const n=o.createModelSettings(r);return n._objectURL=URL.createObjectURL(i),n})}static readText(t){return p(this,null,function*(){return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")})})}};c(ot,"live2dFactory"),c(ot,"filesMap",{}),c(ot,"factory",(t,e)=>p(null,null,function*(){if(Array.isArray(t.source)&&t.source[0]instanceof File){const e=t.source;let i=e.settings;if(i){if(!i._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else i=yield ot.createSettings(e);i.validateFiles(e.map(t=>encodeURI(t.webkitRelativePath))),ot.upload(e,i),i.resolveURL=function(t){return ot.resolveURL(this._objectURL,t)},t.source=i,t.live2dModel.once("modelLoaded",t=>{t.once("destroy",function(){const t=this.settings._objectURL;if(URL.revokeObjectURL(t),ot.filesMap[t])for(const e of Object.values(ot.filesMap[t]))URL.revokeObjectURL(e);delete ot.filesMap[t]})})}return e()}));let nt=ot;const at=class t{static registerRuntime(e){t.runtimes.push(e),t.runtimes.sort((t,e)=>e.version-t.version)}static findRuntime(e){for(const i of t.runtimes)if(i.test(e))return i}static setupLive2DModel(e,i,s){return p(this,null,function*(){const r=new Promise(t=>e.once("textureLoaded",t)),o=new Promise(t=>e.once("modelLoaded",t)),n=Promise.all([r,o]).then(()=>e.emit("ready"));yield X(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield n,e.emit("load")})}static loadMotion(e,i,s){var r;const o=t=>e.emit("motionLoadError",i,s,t);try{const n=null==(r=e.definitions[i])?void 0:r[s];if(!n)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseMotionTasks(e));let a=t.motionTasksMap.get(e);a||(a={},t.motionTasksMap.set(e,a));let l=a[i];l||(l=[],a[i]=l);const h=e.getMotionFile(n);return null!=l[s]||(l[s]=W.load({url:h,settings:e.settings,type:e.motionDataType,target:e}).then(r=>{var o;const a=null==(o=t.motionTasksMap.get(e))?void 0:o[i];a&&(a[s]=void 0);const l=r,h=e.createMotion(l,i,n);return e.emit("motionLoaded",i,s,h),h}).catch(t=>{m.warn(e.tag,`Failed to load motion: ${h}\n`,t),o(t)})),l[s]}catch(n){m.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,n),o(n)}return Promise.resolve(void 0)}static loadExpression(e,i){var s;const r=t=>e.emit("expressionLoadError",i,t);try{const o=e.definitions[i];if(!o)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseExpressionTasks(e));let n=t.expressionTasksMap.get(e);n||(n=[],t.expressionTasksMap.set(e,n));const a=e.getExpressionFile(o),l=null!=(s=e.expressionDataType)?s:"json";return null!=n[i]||(n[i]=W.load({url:a,settings:e.settings,type:l,target:e}).then(s=>{const r=t.expressionTasksMap.get(e);r&&(r[i]=void 0);const n=s,a=e.createExpression(n,o);return e.emit("expressionLoaded",i,a),a}).catch(t=>{m.warn(e.tag,`Failed to load expression: ${a}\n`,t),r(t)})),n[i]}catch(o){m.warn(e.tag,`Failed to load expression at [${i}]\n`,o),r(o)}return Promise.resolve(void 0)}static releaseMotionTasks(e){t.motionTasksMap.delete(e)}static releaseExpressionTasks(e){t.expressionTasksMap.delete(e)}};c(at,"runtimes",[]),c(at,"urlToJSON",Z),c(at,"jsonToSettings",Q),c(at,"waitUntilReady",K),c(at,"setupOptionals",tt),c(at,"setupEssentials",et),c(at,"createInternalModel",it),c(at,"live2DModelMiddlewares",[rt.factory,nt.factory,Z,Q,K,tt,et,it]),c(at,"motionTasksMap",new WeakMap),c(at,"expressionTasksMap",new WeakMap);let lt=at;C.prototype._loadMotion=function(t,e){return lt.loadMotion(this,t,e)},w.prototype._loadExpression=function(t){return lt.loadExpression(this,t)},nt.live2dFactory=lt,rt.live2dFactory=lt;const ht=class t{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:o=!0,autoInteract:n,ticker:a}={}){var l;c(this,"model"),c(this,"destroyed",!1),c(this,"_ticker"),c(this,"_autoUpdate",!1),c(this,"_autoHitTest",!1),c(this,"_autoFocus",!1),null!=a||(a=null!=(l=t.defaultTicker)?l:"undefined"!=typeof PIXI?PIXI.Ticker.shared:e.Ticker.shared),void 0!==n&&(r=n,o=n,m.warn(i.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=i,this.ticker=a,this.autoUpdate=s,this.autoHitTest=r,this.autoFocus=o,(r||o)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e,i;this._ticker&&this._ticker.remove(ut,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(ut,this),null==(i=this._ticker)||i.start())}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;this.destroyed||(t?this._ticker?(this._ticker.add(ut,this),this._autoUpdate=!0):m.warn(this.model.tag,"No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."):(null==(e=this._ticker)||e.remove(ut,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",ct,this):this.model.off("pointertap",ct,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?(this.model.on("globalpointermove",pt,this),this.model.on("pointermove",pt,this)):(this.model.off("globalpointermove",pt,this),this.model.off("pointermove",pt,this)),this._autoFocus=t)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(t){this.autoHitTest=t,this.autoFocus=t}onTickerUpdate(){const t=this.ticker.deltaMS;this.model.update(t)}onTap(t){this.model.tap(t.global.x,t.global.y)}onPointerMove(t){this.model.focus(t.global.x,t.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};c(ht,"defaultTicker");let dt=ht;function ut(){this.onTickerUpdate()}function ct(t){this.onTap(t)}function pt(t){this.onPointerMove(t)}class gt extends e.Transform{}const mt=new e.Point,ft=new e.Matrix,Mt=new e.Matrix,yt={x:0,y:0,width:0,height:0},xt=new e.Bounds;class vt{constructor(t){this.renderer=t}execute(t){!t.visible||t.alpha<=0||t.renderLive2D(this.renderer)}updateRenderable(){}destroy(){}}class Et extends e.Container{constructor(t){super(),c(this,"renderPipeId","live2d"),c(this,"tag","Live2DModel(uninitialized)"),c(this,"internalModel"),c(this,"textures",[]),c(this,"textureOptions"),c(this,"textureLODStates",[]),c(this,"textureLODFailures",[]),c(this,"transform",new gt),c(this,"anchor"),c(this,"_bounds",new e.Bounds),c(this,"_boundsDirty",!0),c(this,"_boundsRetryAfterDraw",!1),c(this,"gl",null),c(this,"elapsedTime",0),c(this,"deltaTime",0),c(this,"automator"),c(this,"currentGlId",0),c(this,"renderLive2D",t=>{var i,s,r,o,n;if(!(t instanceof e.WebGLRenderer))throw new Error("Renderer is not supported");t.geometry.resetState(),t.shader.resetState(),t.texture.resetState();let a=!1;this.gl!==t.gl&&(this.gl=t.gl,this.internalModel.updateWebGLContext(t.gl,this.generateUID()),a=!0);const{projectionMatrix:l,offset:h,worldTransformMatrix:d}=t.globalUniforms.globalUniformData,u=Mt.copyFrom(d).append(this.groupTransform),c=(p=u,Math.max(Math.hypot(p.a,p.b),Math.hypot(p.c,p.d))*t.resolution);var p;for(let e=0;e<this.textures.length;e++){const i=this.textures[e];let s=this.resolveTextureForRender(e,i,c);try{this.uploadTextureForRender(t,s,a)}catch(E){if(s===i)throw new Error("Failed to upload Live2D texture.");const r=this.textureLODStates[e];(null==r?void 0:r.texture)===s&&(this.markTextureLODFailure(e,i,r.level),this.destroyTextureLODState(e)),s=i,this.uploadTextureForRender(t,s,a)}this.internalModel.bindTexture(e,t.texture.getGlSource(s.source).texture)}const g=t.renderTarget.viewport,m=t.renderTarget.renderTarget;let f=g.y;if(null==m?void 0:m.isRoot){f=m.colorTexture.source.pixelHeight-g.height-g.y}this.internalModel.viewport=[g.x,f,g.width,g.height];const M=this.deltaTime;this.deltaTime=0,M&&this.internalModel.update(M,this.elapsedTime),u.tx-=null!=(i=null==h?void 0:h.x)?i:0,u.ty-=null!=(s=null==h?void 0:h.y)?s:0;const y=ft.copyFrom(l).append(u);this.internalModel.updateTransform(y),this.internalModel.draw(t.gl),this._boundsRetryAfterDraw&&this.updateDrawableBounds(),t.state.resetState(),t.texture.resetState();const x=null==(r=t.renderTarget)?void 0:r.defaultClearColor,v=null==(n=null==(o=t.renderTarget)?void 0:o.adaptor)?void 0:n._clearColorCache;x&&(t.gl.clearColor(x[0],x[1],x[2],x[3]),v&&(v[0]=x[0],v[1]=x[1],v[2]=x[2],v[3]=x[3]))}),this.textureOptions=null==t?void 0:t.textureOptions,this.anchor=new e.ObservablePoint({_onUpdate:()=>this.onAnchorChange()},0,0),this.automator=new dt(this,t),this.once("modelLoaded",()=>this.initializeOnModelLoad(t))}get isRenderable(){return!0}get canBundle(){return!1}static from(t,e){return p(this,null,function*(){const i=new this(e);return yield lt.setupLive2DModel(i,t,e),i})}static fromSync(t,e){const i=new this(e);return lt.setupLive2DModel(i,t,e).then(()=>{var t;return null==(t=null==e?void 0:e.onLoad)?void 0:t.call(e)}).catch(t=>{var i;return null==(i=null==e?void 0:e.onError)?void 0:i.call(e,t)}),i}static registerTicker(t){dt.defaultTicker=t.shared}get bounds(){return this.internalModel?(this._boundsDirty&&this.updateDrawableBounds(),this._bounds):(this._bounds.set(0,0,0,0),this._bounds)}updateDrawableBounds(){if(!this.internalModel)return this._bounds.set(0,0,0,0),void(this._boundsDirty=!1);const t=this.internalModel.getDrawableIDs();xt.clear();for(let i=0;i<t.length;i++){const s=t[i],r=this.internalModel.getDrawableIndex(s);if(r<0)continue;const o=this.internalModel.getDrawableBounds(r,yt);Number.isFinite(o.x)&&Number.isFinite(o.y)&&Number.isFinite(o.width)&&Number.isFinite(o.height)&&xt.addFrame(o.x,o.y,o.x+o.width,o.y+o.height,e.Matrix.IDENTITY)}if(this._bounds.clear(),xt.isValid&&xt.isPositive)this._bounds.addFrame(xt.minX,xt.minY,xt.maxX,xt.maxY,this.internalModel.localTransform),this._boundsRetryAfterDraw=!1;else{const t=this.internalModel.originalWidth||this.internalModel.width,e=this.internalModel.originalHeight||this.internalModel.height;this._bounds.addFrame(0,0,t,e,this.internalModel.localTransform),this._boundsRetryAfterDraw=!0}this._boundsDirty=!1}generateUID(){return++this.currentGlId}collectRenderables(t,e,i){var s,r,o,n;if(this.parentRenderLayer&&this.parentRenderLayer!==i)return;if(this.globalDisplayStatus<7)return;if(!this.includeInBuild)return;this.sortableChildren&&this.sortChildren(),function(t){const e=t;e.renderPipes.live2d||(e.renderPipes.live2d=new vt(t))}(e);const a=e.renderPipes,l=()=>{var e,i;null==(i=null==(e=a.batch)?void 0:e.break)||i.call(e,t),t.add(this)},h=()=>{const s=this.children,r=s.length;for(let o=0;o<r;o++)s[o].collectRenderables(t,e,i)},d=this.effects;if(d){for(let e=0;e<d.length;e++){const i=d[e],o=i.filters;if(o)for(const t of o)t&&"number"==typeof t.resolution&&1===t.resolution&&(t.resolution="inherit");null==(r=null==(s=a[i.pipe])?void 0:s.push)||r.call(s,i,this,t)}l(),h();for(let e=d.length-1;e>=0;e--){const i=d[e];null==(n=null==(o=a[i.pipe])?void 0:o.pop)||n.call(o,i,this,t)}}else l(),h()}initializeOnModelLoad(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`,this.onAnchorChange(),this.updateDrawableBounds()}onAnchorChange(){this.internalModel&&this.pivot&&this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i){return p(this,arguments,function*(t,e,i,{sound:s,volume:r=.5,expression:o,resetExpression:n=!0,onFinish:a,onError:l}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:o,resetExpression:n,onFinish:a,onError:l}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:o,resetExpression:n,onFinish:a,onError:l})})}motionLastFrame(t,e){return p(this,arguments,function*(t,e,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(t,e,{expression:i})})}parallelMotion(t){return p(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].startMotion(t.group,t.index,t.priority)),i=[];for(const t of e)i.push(yield t);return i})}parallelLastFrame(t){return p(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].playMotionLastFrame(t.group,t.index)),i=[];for(const t of e)i.push(yield t);return i})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:o}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,onFinish:r,onError:o})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){mt.x=t,mt.y=e,this.toModelPosition(mt,mt,!0);const s=mt.x/this.internalModel.originalWidth*2-1,r=mt.y/this.internalModel.originalHeight*2-1,o=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(o),-Math.sin(o),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&this.emit("hit",i)}hitTest(t,e){return mt.x=t,mt.y=e,this.toModelPosition(mt,mt),this.internalModel.hitTest(mt.x,mt.y)}toModelPosition(t,e=t.clone(),i){return i||this.updateLocalTransform(),this.toLocal(t,void 0,e,i),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.bounds.containsPoint(t.x,t.y)}_calculateBounds(){if(!this.internalModel)return void this.getBounds().set(0,0,0,0);const t=this.internalModel.width,e=this.internalModel.height;this.getBounds().addFrame(0,0,t,e,this.transform.matrix)}update(t){this.deltaTime+=t,this.elapsedTime+=t}resolveTextureForRender(t,i,s){var n;const a=$((l=u({},this.textureOptions),h={effectiveScale:s,textureWidth:i.source.pixelWidth,textureHeight:i.source.pixelHeight},r(l,o(h))));var l,h;if(!a)return i;const d=this.textureLODFailures[t];if((null==d?void 0:d.source)===i&&d.levels.has(a.level))return i;const c=this.textureLODStates[t];if((null==c?void 0:c.source)===i&&c.level===a.level&&!c.texture.destroyed)return c.texture;this.destroyTextureLODState(t);const p=function(t,i,s,r,o){var n,a;const l=t.source.resource;if(!function(t){if(!t||"object"!=typeof t)return!1;const{width:e,height:i}=t;return"number"==typeof e&&e>0&&"number"==typeof i&&i>0}(l))return;const h=e.DOMAdapter.get().createCanvas(s,r),d=h.getContext("2d");if(!d)return;try{d.clearRect(0,0,s,r),d.imageSmoothingEnabled="nearest"!==o,"imageSmoothingQuality"in d&&"nearest"!==o&&(d.imageSmoothingQuality="high"),d.drawImage(l,0,0,t.source.pixelWidth,t.source.pixelHeight,0,0,s,r)}catch(c){return}const u=`${null!=(a=null!=(n=t.label)?n:t.source.label)?a:"Live2DTexture"} LOD ${i}`;return new e.Texture({label:u,source:new e.CanvasSource({resource:h,width:s,height:r,resolution:1,scaleMode:q(o),autoGenerateMipmaps:!1,label:u})})}(i,a.level,a.width,a.height,null==(n=this.textureOptions)?void 0:n.lodFilter);return p?(this.textureLODStates[t]={source:i,level:a.level,texture:p},p):(this.markTextureLODFailure(t,i,a.level),i)}markTextureLODFailure(t,e,i){let s=this.textureLODFailures[t];(null==s?void 0:s.source)!==e&&(s={source:e,levels:new Set},this.textureLODFailures[t]=s),s.levels.add(i)}destroyTextureLODState(t){const e=this.textureLODStates[t];e&&(e.texture.destroy(!0),this.textureLODStates[t]=void 0)}destroyTextureLODStates(){for(let t=0;t<this.textureLODStates.length;t++)this.destroyTextureLODState(t);this.textureLODFailures.length=0}uploadTextureForRender(t,e,i){const s=Boolean(e.source._gpuData[t.uid]);!i&&s||(t.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,this.internalModel.textureFlipY),t.texture.bind(e,0))}destroy(t){this.emit("destroy"),this.destroyTextureLODStates(),(null==t?void 0:t.texture)&&this.textures.forEach(e=>e.destroy(t.baseTexture)),this.automator.destroy(),this.internalModel.destroy(),super.destroy(t)}}if(!("Live2D"in window))throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const bt=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){bt.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class Pt extends AMotion{constructor(t){super(),c(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:g.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:g.expressionFadingDuration),Array.isArray(t.params)&&t.params.forEach(t=>{const e=t.calc||"add";if("add"===e){const e=t.def||0;t.val-=e}else if("mult"===e){const e=t.def||1;t.val/=e}this.params.push({calc:e,val:t.val,id:t.id})})}updateParamExe(t,e,i,s){this.params.forEach(e=>{t.setParamFloat(e.id,e.val*i)})}}class wt extends w{constructor(t,e){var i;super(t,e),c(this,"queueManager",new MotionQueueManager),c(this,"definitions"),this.definitions=null!=(i=this.settings.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex(e=>e.name===t)}getExpressionFile(t){return t.file}createExpression(t,e){return new Pt(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}function Lt(t,e,i){const s=i.getDurationMSec(),r=t.startMotion(i,!0),o=t.motions.find(t=>!!t&&t._$sr===r);return!!o&&(i.updateParamExe(e.coreModel,s,1,o),!0)}class It extends C{constructor(t){super(t),c(this,"definitions"),c(this,"groups",{idle:"idle"}),c(this,"motionDataType","arraybuffer"),c(this,"queueManager",new MotionQueueManager),c(this,"lipSyncIds"),c(this,"expressionManager"),this.definitions=this.settings.motions,this.init(t.options),this.lipSyncIds=["PARAM_MOUTH_OPEN_Y"]}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new wt(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(t,e,i){const s=Live2DMotion.loadMotion(t),r=e===this.groups.idle?g.idleMotionFadingDuration:g.motionFadingDuration;return s.setFadeIn(i.fade_in>0?i.fade_in:r),s.setFadeOut(i.fade_out>0?i.fade_out:r),s}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e,i){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}motionLastFrame(t,e){return p(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,Lt(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class _t extends e.EventEmitter{constructor(t){super(),c(this,"tag"),c(this,"manager"),c(this,"settings"),c(this,"state",new A),c(this,"playing",!1),c(this,"destroyed",!1),c(this,"parent"),this.settings=t.settings,this.tag=`ParallelMotionManager(${this.settings.name})`,this.state.tag=this.tag,this.manager=t.motionManager,this.parent=t}startMotion(t,e){return p(this,arguments,function*(t,e,i=F.NORMAL,s=[]){var r;if(!this.state.reserve(t,e,i))return!1;const o=null==(r=this.manager.definitions[t])?void 0:r[e];if(!o)return!1;const n=yield this.manager.loadMotion(t,e);return!!this.state.start(n,t,e,i)&&(m.log(this.tag,"Start motion:",this.getMotionName(o)),this.emit("motionStart",t,e,void 0),this.playing=!0,this._startMotion(n,void 0,s),!0)})}startRandomMotion(t,e){return p(this,null,function*(){var i;const s=this.manager.definitions[t];if(null==s?void 0:s.length){const r=[],o=null!=(i=this.manager.motionGroups[t])?i:[];for(let e=0;e<s.length;e++)null===o[e]||this.state.isActive(t,e)||r.push(e);if(r.length){const i=r[Math.floor(Math.random()*r.length)];return this.startMotion(t,i,e)}}return!1})}stopAllMotions(){this._stopAllMotions(),this.state.reset()}update(t,e){return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.complete()),this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy"),this.stopAllMotions()}}class Ot extends _t{constructor(t){super(t),c(this,"queueManager",new MotionQueueManager)}isFinished(){return this.queueManager.isFinished()}getMotionName(t){return t.file}_startMotion(t,e,i){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}playMotionLastFrame(t,e){return p(this,null,function*(){var i;if(!this.state.reserve(t,e,F.FORCE))return!1;const s=null==(i=this.manager.definitions[t])?void 0:i[e];if(!s)return!1;const r=yield this.manager.loadMotion(t,e);return!!this.state.start(r,t,e,F.FORCE)&&(m.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",t,e,void 0),this.playing=!0,!!Lt(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class Ft{constructor(t){c(this,"leftParam"),c(this,"rightParam"),c(this,"blinkInterval",4e3),c(this,"closingDuration",100),c(this,"closedDuration",50),c(this,"openingDuration",150),c(this,"eyeState",0),c(this,"eyeParamValue",1),c(this,"closedTimer",0),c(this,"nextBlinkTimeLeft",this.blinkInterval),this.coreModel=t,this.leftParam=t.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=t.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(t){this.eyeParamValue=f(t,0,1),this.coreModel.setParamFloat(this.leftParam,this.eyeParamValue),this.coreModel.setParamFloat(this.rightParam,this.eyeParamValue)}update(t){switch(this.eyeState){case 0:this.nextBlinkTimeLeft-=t,this.nextBlinkTimeLeft<0&&(this.eyeState=1,this.nextBlinkTimeLeft=this.blinkInterval+this.closingDuration+this.closedDuration+this.openingDuration+M(0,2e3));break;case 1:this.setEyeParams(this.eyeParamValue+t/this.closingDuration),this.eyeParamValue<=0&&(this.eyeState=2,this.closedTimer=0);break;case 2:this.closedTimer+=t,this.closedTimer>=this.closedDuration&&(this.eyeState=3);break;case 3:this.setEyeParams(this.eyeParamValue+t/this.openingDuration),this.eyeParamValue>=1&&(this.eyeState=0)}}}const At=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class Tt extends j{constructor(t,e,i){super(),c(this,"settings"),c(this,"options"),c(this,"coreModel"),c(this,"motionManager"),c(this,"parallelMotionManager"),c(this,"eyeBlink"),c(this,"eyeballXParamIndex"),c(this,"eyeballYParamIndex"),c(this,"angleXParamIndex"),c(this,"angleYParamIndex"),c(this,"angleZParamIndex"),c(this,"bodyAngleXParamIndex"),c(this,"breathParamIndex"),c(this,"textureFlipY",!0),c(this,"lipSync",!0),c(this,"drawDataCount",0),c(this,"disableCulling",!1),c(this,"hasDrawn",!1),c(this,"customHitAreas"),this.coreModel=t,this.settings=e,this.options=Object.assign({},{breathDepth:1,lipSyncGain:1.5,lipSyncWeight:.4},i),void 0!==(null==i?void 0:i.useHighPrecisionMask)&&!1!==i.useHighPrecisionMask&&m.warn("CubismLegacyInternalModel","`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."),this.motionManager=new It(this),this.parallelMotionManager=[],this.eyeBlink=new Ft(t),this.eyeballXParamIndex=t.getParamIndex("PARAM_EYE_BALL_X"),this.eyeballYParamIndex=t.getParamIndex("PARAM_EYE_BALL_Y"),this.angleXParamIndex=t.getParamIndex("PARAM_ANGLE_X"),this.angleYParamIndex=t.getParamIndex("PARAM_ANGLE_Y"),this.angleZParamIndex=t.getParamIndex("PARAM_ANGLE_Z"),this.bodyAngleXParamIndex=t.getParamIndex("PARAM_BODY_ANGLE_X"),this.breathParamIndex=t.getParamIndex("PARAM_BREATH"),this.init()}init(){super.init(),this.settings.initParams&&this.settings.initParams.forEach(({id:t,value:e})=>this.coreModel.setParamFloat(t,e)),this.settings.initOpacities&&this.settings.initOpacities.forEach(({id:t,value:e})=>this.coreModel.setPartsOpacity(t,e)),this.coreModel.saveParam();const t=this.coreModel.getModelContext()._$aS;(null==t?void 0:t.length)&&(this.drawDataCount=t.length);let e=this.coreModel.drawParamWebGL.culling;Object.defineProperty(this.coreModel.drawParamWebGL,"culling",{set:t=>e=t,get:()=>!this.disableCulling&&e});const i=this.coreModel.getModelContext().clipManager,s=i.setupClip.bind(i);i.setupClip=(t,e)=>{s.call(i,t,e),e.gl.viewport(...this.viewport)}}getSize(){return[this.coreModel.getCanvasWidth(),this.coreModel.getCanvasHeight()]}getLayout(){const t={};if(this.settings.layout)for(const[e,i]of Object.entries(this.settings.layout)){let s=e;"center_x"===e?s="centerX":"center_y"===e&&(s="centerY"),"number"==typeof i&&(t[s]=i)}return t}updateWebGLContext(t,e){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(t),i.glno=e,i._$NT=null,i._$no=null,i._$vS=null;const s=this.coreModel.getModelContext().clipManager;s.curFrameNo=e;const r=t.getParameter(t.FRAMEBUFFER_BINDING);s.getMaskRenderTexture(),t.bindFramebuffer(t.FRAMEBUFFER,r)}bindTexture(t,e){this.coreModel.setTexture(t,e)}getHitAreaDefs(){var t,e,i;const s=this.settings.json;return k(null!=(i=null!=(e=null!=(t=this.settings.hitAreas)?t:s.hit_areas)?e:s.HitAreas)?i:s.hitAreas,t=>this.coreModel.getDrawDataIndex(t))}getDrawableIDs(){const t=this.coreModel.getModelContext(),e=[];for(let i=0;i<this.drawDataCount;i++){const s=t.getDrawData(i);s&&e.push(s.getDrawDataID().id)}return e}getDrawableIndex(t){return this.coreModel.getDrawDataIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawDataIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);return this.coreModel.getTransformedPoints(t).slice()}hitTest(t,e){this.hasDrawn||m.warn("Trying to hit-test a Cubism 2 model that has not been rendered yet. Drawable hit areas may be empty until the first draw.");const i=super.hitTest(t,e),s=this.hitTestCustom(t,e);return s.length?i.length?[...new Set([...i,...s])]:s:i}update(t,e){var i,s,r,o;super.update(t,e);const n=this.coreModel,a=this.updateMotions(n,e);if(n.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(n,e),a||null==(s=this.eyeBlink)||s.update(t),this.updateFocus(),this.updateNaturalMovements(t,e),this.lipSync&&this.motionManager.currentAudio){let t=this.motionManager.mouthSync()*this.options.lipSyncGain;const e=1,i=t>0?.1:0;t=Math.pow(t,1.15),t=f(t,i,e);for(let s=0;s<this.motionManager.lipSyncIds.length;++s)this.coreModel.addToParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[s]),t,this.options.lipSyncWeight)}null==(r=this.physics)||r.update(e),null==(o=this.pose)||o.update(t),this.emit("beforeModelUpdate"),n.update(),n.loadParam()}updateFocus(){this.coreModel.addToParamFloat(this.eyeballXParamIndex,this.focusController.x),this.coreModel.addToParamFloat(this.eyeballYParamIndex,this.focusController.y),this.coreModel.addToParamFloat(this.angleXParamIndex,30*this.focusController.x),this.coreModel.addToParamFloat(this.angleYParamIndex,30*this.focusController.y),this.coreModel.addToParamFloat(this.angleZParamIndex,this.focusController.x*this.focusController.y*-30),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,10*this.focusController.x)}updateNaturalMovements(t,e){const i=e/1e3*2*Math.PI;this.coreModel.addToParamFloat(this.angleXParamIndex,15*this.options.breathDepth*Math.sin(i/6.5345)*.5),this.coreModel.addToParamFloat(this.angleYParamIndex,8*this.options.breathDepth*Math.sin(i/3.5345)*.5),this.coreModel.addToParamFloat(this.angleZParamIndex,10*this.options.breathDepth*Math.sin(i/5.5345)*.5),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,4*this.options.breathDepth*Math.sin(i/15.5345)*.5),this.coreModel.setParamFloat(this.breathParamIndex,.5+.5*Math.sin(i/3.2345))}draw(t){const e=this.disableCulling;t.getParameter(t.FRAMEBUFFER_BINDING)&&(this.disableCulling=!0);const i=this.drawingMatrix;At[0]=i.a,At[1]=i.b,At[4]=i.c,At[5]=i.d,At[12]=i.tx,At[13]=i.ty,this.coreModel.setMatrix(At),this.coreModel.draw(),this.hasDrawn=!0,this.disableCulling=e}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new Ot(this))}destroy(){super.destroy(),this.coreModel=void 0}hitTestCustom(t,e){const i=this.getCustomHitAreas();if(!i)return[];const s=this.originalWidth||this.width,r=this.originalHeight||this.height;if(!s||!r)return[];const o=t/s*2-1,n=1-e/r*2,a=[];for(const[l,h]of Object.entries(i))o>=h.minX&&o<=h.maxX&&n>=h.minY&&n<=h.maxY&&a.push(l);return a}getCustomHitAreas(){var t,e,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const o=this.settings.json,n=null!=(i=null!=(e=null!=(t=o.hit_areas_custom)?t:o.hitAreasCustom)?e:o.HitAreasCustom)?i:o.HitAreas_Custom;if(!n||"object"!=typeof n)return this.customHitAreas=null,null;const a=n,l={},h=(t,e,i)=>{if(!t||!Array.isArray(e)||!Array.isArray(i))return;if(e.length<2||i.length<2)return;const s=Number(e[0]),r=Number(e[1]),o=Number(i[0]),n=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(o)&&Number.isFinite(n)&&(l[t]={minX:Math.min(s,r),maxX:Math.max(s,r),minY:Math.min(o,n),maxY:Math.max(o,n)})};for(const[d,u]of Object.entries(a)){if(d.endsWith("_x")){const t=d.slice(0,-2);h(t,u,a[`${t}_y`]);continue}if(!d.endsWith("_y")&&(u&&"object"==typeof u)){const t=u;h(d,null!=(s=t.x)?s:t.X,null!=(r=t.y)?r:t.Y)}}return this.customHitAreas=Object.keys(l).length?l:null,this.customHitAreas}}const Dt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},Rt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class St{constructor(t,e){c(this,"physicsHairs",[]),this.coreModel=t,e.physics_hair&&(this.physicsHairs=e.physics_hair.map(t=>{const e=new PhysicsHair;return e.setup(t.setup.length,t.setup.regist,t.setup.mass),t.src.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const o=Dt[i];o&&e.addSrcParam(o,t,s,r)}),t.targets.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const o=Rt[i];o&&e.addTargetParam(o,t,s,r)}),e}))}update(t){this.physicsHairs.forEach(e=>e.update(this.coreModel,t))}}class Ct{constructor(t){c(this,"paramIndex",-1),c(this,"partsIndex",-1),c(this,"link",[]),this.id=t}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class kt{constructor(t,e){c(this,"opacityAnimDuration",500),c(this,"partsGroups",[]),this.coreModel=t,e.parts_visible&&(this.partsGroups=e.parts_visible.map(({group:t})=>t.map(({id:t,link:e})=>{const i=new Ct(t);return e&&(i.link=e.map(t=>new Ct(t))),i})),this.init())}init(){this.partsGroups.forEach(t=>{t.forEach(t=>{if(t.initIndex(this.coreModel),t.paramIndex>=0){const e=0!==this.coreModel.getParamFloat(t.paramIndex);this.coreModel.setPartsOpacity(t.partsIndex,e?1:0),this.coreModel.setParamFloat(t.paramIndex,e?1:0),t.link.length>0&&t.link.forEach(t=>t.initIndex(this.coreModel))}})})}normalizePartsOpacityGroup(t,e){const i=this.coreModel,s=.5;let r=1,o=t.findIndex(({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t));if(o>=0){const s=i.getPartsOpacity(t[o].partsIndex);r=f(s+e/this.opacityAnimDuration,0,1)}else o=0,r=1;t.forEach(({partsIndex:t},e)=>{if(t>=0)if(o==e)i.setPartsOpacity(t,r);else{let e,o=i.getPartsOpacity(t);e=r<s?-.5*r/s+1:(1-r)*s/.5;(1-e)*(1-r)>.15&&(e=1-.15/(1-r)),o>e&&(o=e),i.setPartsOpacity(t,o)}})}copyOpacity(t){const e=this.coreModel;t.forEach(({partsIndex:t,link:i})=>{if(t>=0&&i){const s=e.getPartsOpacity(t);i.forEach(({partsIndex:t})=>{t>=0&&e.setPartsOpacity(t,s)})}})}update(t){this.partsGroups.forEach(e=>{this.normalizePartsOpacityGroup(e,t),this.copyOpacity(e)})}}lt.registerRuntime({version:2,test:t=>t instanceof B||B.isValidJSON(t),ready:()=>Promise.resolve(),isValidMoc(t){if(t.byteLength<3)return!1;const e=new Int8Array(t,0,3);return"moc"===String.fromCharCode(...e)},createModelSettings:t=>new B(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),i=Live2D.getError();if(i){if(i instanceof Error)throw i;const t="string"==typeof i?i:`Live2D error: ${JSON.stringify(i)}`;throw new Error(t)}return e},createInternalModel:(t,e,i)=>new Tt(t,e,i),createPose:(t,e)=>new kt(t,e),createPhysics:(t,e)=>new St(t,e)}),t.CubismLegacyExpressionManager=wt,t.CubismLegacyInternalModel=Tt,t.CubismLegacyModelSettings=B,t.CubismLegacyMotionManager=It,t.CubismLegacyParallelMotionManager=Ot,t.ExpressionManager=w,t.FileLoader=nt,t.FocusController=_,t.InternalModel=j,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=Pt,t.Live2DEyeBlink=Ft,t.Live2DFactory=lt,t.Live2DLoader=W,t.Live2DModel=Et,t.Live2DPhysics=St,t.Live2DPose=kt,t.Live2DTransform=gt,t.MBToByte=function(t){return 1024*t*1024},t.ModelSettings=O,t.MotionManager=C,t.MotionPreloadStrategy=S,t.MotionPriority=F,t.MotionState=A,t.SoundManager=R,t.VERSION="1.1.0",t.VOLUME=D,t.XHRLoader=U,t.ZipLoader=rt,t.applyMixins=function(t,e){e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))})})},t.clamp=f,t.config=g,t.copyArray=x,t.copyProperty=y,t.folderName=v,t.logger=m,t.normalizeHitAreaDefs=k,t.rand=M,t.remove=E,t.resolveURL=P,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("pixi.js"),require("@pixi/sound")):"function"==typeof define&&define.amd?define(["exports","pixi.js","@pixi/sound"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI,t.PIXI)}(this,function(t,e,i){"use strict";var s=Object.defineProperty,r=Object.defineProperties,o=Object.getOwnPropertyDescriptors,n=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable,h=Math.pow,d=(t,e,i)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,u=(t,e)=>{for(var i in e||(e={}))a.call(e,i)&&d(t,i,e[i]);if(n)for(var i of n(e))l.call(e,i)&&d(t,i,e[i]);return t},c=(t,e,i)=>d(t,"symbol"!=typeof e?e+"":e,i),p=(t,e,i)=>new Promise((s,r)=>{var o=t=>{try{a(i.next(t))}catch(e){r(e)}},n=t=>{try{a(i.throw(t))}catch(e){r(e)}},a=t=>t.done?s(t.value):Promise.resolve(t.value).then(o,n);a((i=i.apply(t,e)).next())});const g={LOG_LEVEL_VERBOSE:0,LOG_LEVEL_WARNING:1,LOG_LEVEL_ERROR:2,LOG_LEVEL_NONE:999,logLevel:1,sound:!0,fftSize:512,motionSync:!0,motionFadingDuration:500,idleMotionFadingDuration:2e3,expressionFadingDuration:500,preserveExpressionOnMotion:!0,cubism:Object.freeze(Object.defineProperty({__proto__:null,CSM_LOG_LEVEL:0,CSM_LOG_LEVEL_DEBUG:1,CSM_LOG_LEVEL_ERROR:4,CSM_LOG_LEVEL_INFO:2,CSM_LOG_LEVEL_OFF:5,CSM_LOG_LEVEL_VERBOSE:0,CSM_LOG_LEVEL_WARNING:3},Symbol.toStringTag,{value:"Module"}))},m={log(t,...e){g.logLevel<=g.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){g.logLevel<=g.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){g.logLevel<=g.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function f(t,e,i){return t<e?e:t>i?i:t}function M(t,e){return Math.random()*(e-t)+t}function x(t,e,i,s,r){const o=e[s];null!==o&&typeof o===t&&(i[r]=o)}function y(t,e,i,s,r){const o=e[s];Array.isArray(o)&&(i[r]=o.filter(e=>null!==e&&typeof e===t))}function v(t){let e=t.lastIndexOf("/");return-1!=e&&(t=t.slice(0,e)),e=t.lastIndexOf("/"),-1!==e&&(t=t.slice(e+1)),t}function b(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}const E=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function w(t,e){if(!e)return t;if(E.test(e))return e;if(e.startsWith("/"))return E.test(t)?new URL(e,t).toString():e;if(E.test(t))return new URL(e,t).toString();const i="http://example.com",s=t.startsWith("/")?i+t:`${i}/${t}`,r=new URL(e,s);let o=r.pathname+r.search+r.hash;return!t.startsWith("/")&&o.startsWith("/")&&(o=o.slice(1)),o}class P extends e.EventEmitter{constructor(t,e){super(),c(this,"expressionDataType","json"),c(this,"tag"),c(this,"settings"),c(this,"expressions",[]),c(this,"defaultExpression"),c(this,"currentExpression"),c(this,"reserveExpressionIndex",-1),c(this,"destroyed",!1),this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createDefaultExpression(),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}createDefaultExpression(){return this.createExpression({},void 0)}loadExpression(t){return p(this,null,function*(){if(!this.definitions[t])return void m.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void m.warn(this.tag,`Cannot set expression at [${t}] because it's already failed in loading.`);if(this.expressions[t])return this.expressions[t];const e=yield this._loadExpression(t);return this.expressions[t]=e,e})}_loadExpression(t){throw new Error("Not implemented.")}setRandomExpression(){return p(this,null,function*(){if(this.definitions.length){const t=[];for(let e=0;e<this.definitions.length;e++)null!==this.expressions[e]&&this.expressions[e]!==this.currentExpression&&e!==this.reserveExpressionIndex&&t.push(e);if(t.length){const e=Math.floor(Math.random()*t.length);return this.setExpression(e)}}return!1})}resetExpression(){this._setExpression(this.defaultExpression)}restoreExpression(){this._setExpression(this.currentExpression)}setExpression(t){return p(this,null,function*(){if("number"!=typeof t&&(t=this.getExpressionIndex(t)),!(t>-1&&t<this.definitions.length))return!1;if(t===this.expressions.indexOf(this.currentExpression))return!1;this.reserveExpressionIndex=t;const e=yield this.loadExpression(t);return!(!e||this.reserveExpressionIndex!==t)&&(this.reserveExpressionIndex=-1,this.currentExpression=e,this._setExpression(e),!0)})}update(t,e){return!this.isFinished()&&this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy");this.definitions=void 0,this.expressions=void 0}}const L=40/7.5,I=1/150;class _{constructor(){c(this,"targetX",0),c(this,"targetY",0),c(this,"x",0),c(this,"y",0),c(this,"vx",0),c(this,"vy",0)}focus(t,e,i=!1){this.targetX=f(t,-1,1),this.targetY=f(e,-1,1),i&&(this.x=this.targetX,this.y=this.targetY)}update(t){const e=this.targetX-this.x,i=this.targetY-this.y;if(Math.abs(e)<.01&&Math.abs(i)<.01)return;const s=Math.sqrt(h(e,2)+h(i,2)),r=L/(1e3/t);let o=r*(e/s)-this.vx,n=r*(i/s)-this.vy;const a=Math.sqrt(h(o,2)+h(n,2)),l=r*I*t;a>l&&(o*=l/a,n*=l/a),this.vx+=o,this.vy+=n;const d=Math.sqrt(h(this.vx,2)+h(this.vy,2)),u=.5*(Math.sqrt(h(l,2)+8*l*s)-l);d>u&&(this.vx*=u/d,this.vy*=u/d),this.x+=this.vx,this.y+=this.vy}}class F{constructor(t){c(this,"json"),c(this,"name"),c(this,"url"),c(this,"pose"),c(this,"physics"),this.json=t,this.url=t.url,this.name=v(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=v(this.url))}setModelName(...t){for(const e of t){const t="string"==typeof e?e.trim():"";if(t&&"name"!==t.toLowerCase())return void(this.name=t)}this.normalizeName()}getFileStem(t){if(!t)return;const e=t.split(/[/\\]/).filter(Boolean).pop();return null==e?void 0:e.replace(/\.[^.]+$/,"")}resolveURL(t){return w(this.url,t)}replaceFiles(t){this.moc=t(this.moc,"moc"),void 0!==this.pose&&(this.pose=t(this.pose,"pose")),void 0!==this.physics&&(this.physics=t(this.physics,"physics"));for(let e=0;e<this.textures.length;e++)this.textures[e]=t(this.textures[e],`textures[${e}]`)}getDefinedFiles(){const t=[];return this.replaceFiles(e=>(t.push(e),e)),t}validateFiles(t){const e=(e,i)=>{const s=this.resolveURL(e);if(!t.includes(s)){if(i)throw new Error(`File "${e}" is defined in settings, but doesn't exist in given files`);return!1}return!0};[this.moc,...this.textures].forEach(t=>e(t,!0));return this.getDefinedFiles().filter(t=>e(t,!1))}}var A=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(A||{});class O{constructor(){c(this,"tag"),c(this,"debug",!1),c(this,"currentPriority",0),c(this,"reservePriority",0),c(this,"currentGroup"),c(this,"currentIndex"),c(this,"reservedGroup"),c(this,"reservedIndex"),c(this,"reservedIdleGroup"),c(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return m.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return m.log(this.tag,"Motion is already playing.",this.dump(t,e)),!1;if(t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex)return m.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return m.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return m.log(this.tag,"Cannot start idle motion because another idle motion has reserved.",this.dump(t,e)),!1;this.setReservedIdle(t,e)}else{if(i<3){if(i<=this.currentPriority)return m.log(this.tag,"Cannot start motion because another motion is playing as an equivalent or higher priority.",this.dump(t,e)),!1;if(i<=this.reservePriority)return m.log(this.tag,"Cannot start motion because another motion has reserved as an equivalent or higher priority.",this.dump(t,e)),!1}this.setReserved(t,e,i)}return!0}start(t,e,i,s){if(1===s){if(this.setReservedIdle(void 0,void 0),0!==this.currentPriority)return m.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(e,i)),!1}else{if(e!==this.reservedGroup||i!==this.reservedIndex)return m.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(e,i)),!1;this.setReserved(void 0,void 0,0)}return!!t&&(this.setCurrent(e,i,s),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(t,e,i){this.currentPriority=i,this.currentGroup=t,this.currentIndex=e}setReserved(t,e,i){this.reservePriority=i,this.reservedGroup=t,this.reservedIndex=e}setReservedIdle(t,e){this.reservedIdleGroup=t,this.reservedIdleIndex=e}isActive(t,e){return t===this.currentGroup&&e===this.currentIndex||t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex}reset(){this.setCurrent(void 0,void 0,0),this.setReserved(void 0,void 0,0),this.setReservedIdle(void 0,void 0)}shouldRequestIdleMotion(){return void 0===this.currentGroup&&void 0===this.reservedIdleGroup}shouldOverrideExpression(){return!g.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n<Requested> group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map(t=>"["+t+"] "+this[t]).join("\n")}return""}}const D="SoundManager",T=.5;i.sound.disableAutoPause=!0;class S{static get volume(){return this._volume}static set volume(t){this._volume=(t>1?1:t<0?0:t)||0,this.audios.forEach(t=>t.volume=this._volume)}static add(t,e){return p(this,null,function*(){try{const e=new Promise((e,s)=>{const r=i.Sound.from({url:t,volume:this._volume,preload:!0,loaded:()=>{r.media instanceof i.webaudio.WebAudioMedia||s(new Error(`Error: ${t} is not WebAudioMedia`)),e(r)}})});return yield e}catch(s){return m.warn(D,`Error occurred on "${t}"`,s),null==e||e(s),null}})}static play(t,e){t.play({singleInstance:!0,complete:()=>{null==e||e(),t.destroy()}})}static addAnalyzer(t,e){const i=t.media,s=e.createBufferSource();s.buffer=i.buffer;const r=e.createAnalyser();return r.fftSize=g.fftSize,r.minDecibels=-90,r.maxDecibels=-10,r.smoothingTimeConstant=.85,s.connect(r),s.start(0),this.analysers.push(r),r}static analyze(t){if(!t)return parseFloat(Math.random().toFixed(1));const e=new Float32Array(t.fftSize);t.getFloatTimeDomainData(e);let i=0;for(let n=0;n<e.length;n++)i+=h(e[n],2);const s=Math.sqrt(i/e.length),r=20*Math.log10(s||h(10,-5)),o=Math.min(Math.max((r-t.minDecibels)/(t.maxDecibels-t.minDecibels),0),1);return parseFloat(o.toFixed(1))}static dispose(t){t.pause(),b(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--){const e=this.contexts[t];null==e||e.close().catch(t=>{m.warn(D,"Failed to close AudioContext.",t)})}for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}c(S,"audios",[]),c(S,"analysers",[]),c(S,"contexts",[]),c(S,"_volume",T);var R=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(R||{});class C extends e.EventEmitter{constructor(t){super(),c(this,"tag"),c(this,"settings"),c(this,"motionGroups",{}),c(this,"state",new O),c(this,"currentAudio"),c(this,"currentAnalyzer"),c(this,"currentContext"),c(this,"playing",!1),c(this,"destroyed",!1),c(this,"parent"),this.settings=t.settings,this.tag=`MotionManager(${this.settings.name})`,this.state.tag=this.tag,this.parent=t}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){if(!this.definitions)return void m.warn(this.tag,"Motion definitions are not initialized.");for(const i of Object.keys(this.definitions))this.motionGroups[i]=[];let e;switch(null==t?void 0:t.motionPreload){case"NONE":return;case"ALL":e=Object.keys(this.definitions);break;default:e=[this.groups.idle]}for(const i of e){const t=this.definitions[i];if(t)for(let e=0;e<t.length;e++)this.loadMotion(i,e)}}loadMotion(t,e){return p(this,null,function*(){var i,s;if(this.destroyed)return;if(!this.getMotionDefinition(t,e))return;const r=null!=(s=(i=this.motionGroups)[t])?s:i[t]=[];if(null===r[e])return void m.warn(this.tag,`Cannot start motion at "${t}"[${e}] because it's already failed in loading.`);if(r[e])return r[e];const o=yield this._loadMotion(t,e);return this.destroyed?void 0:(r[e]=null!=o?o:null,o)})}_loadMotion(t,e){throw new Error("Not implemented.")}initializeAudio(t,e){this.currentAudio=t,S.volume=e,this.currentContext=t.context.audioContext,this.currentAnalyzer=S.addAnalyzer(this.currentAudio,this.currentContext)}speak(t){return p(this,arguments,function*(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:o}={}){if(!g.sound)return!1;let n,a;if(this.currentAudio&&this.currentAudio.isPlaying)return!1;const l=t&&t.startsWith("data:");if(t&&!l){const e=document.createElement("a");e.href=t,a=t=e.href}else a="data:audio/";const h=t;if(h)try{n=yield S.add(h,(t,e=this)=>{m.error(this.tag,"Error during audio playback:",t),null==o||o(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),this.initializeAudio(n,e)}catch(d){return m.warn(this.tag,"Failed to create audio",a,d),!1}if(n){let t=!0;try{g.motionSync&&S.play(n,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(d){m.warn(this.tag,"Failed to play audio",n.url,d),t=!1}if(!t)return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&(yield this.expressionManager.setExpression(i)),this.playing=!0,!0})}startMotion(t,e){return p(this,arguments,function*(t,e,i=A.NORMAL,{sound:s,volume:r=.5,expression:o,resetExpression:n=!0,onFinish:a,onError:l,ignoreParamIds:h=[]}={}){if(this.destroyed)return!1;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=A.FORCE)return!1;const d=this.getMotionDefinition(t,e);if(!d)return!1;let u,c;this.currentAudio&&S.dispose(this.currentAudio);const p=s&&s.startsWith("data:");if(s&&!p){const t=document.createElement("a");t.href=s,c=s=t.href}else c=this.getSoundFile(d),c&&(c=this.settings.resolveURL(c));const f=c;if(f)try{u=yield S.add(f,(t,e=this)=>{m.error(this.tag,"Error during audio playback:",t),null==l||l(t),n&&o&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),this.initializeAudio(u,r)}catch(x){m.warn(this.tag,"Failed to create audio",c,x)}const M=yield this.loadMotion(t,e);if(u&&g.motionSync)try{S.play(u,(t=this)=>{null==a||a(),n&&o&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0})}catch(x){m.warn(this.tag,"Failed to play audio",u.url,x)}return this.state.start(M,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),m.log(this.tag,"Start motion:",this.getMotionName(d)),this.emit("motionStart",t,e,u),o&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(o)),this.playing=!0,M&&this._startMotion(M,void 0,h),!0):(u&&(S.dispose(u),this.currentAudio=void 0),!1)})}startRandomMotion(t,e){return p(this,arguments,function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:o=!0,onFinish:n,onError:a}={}){var l,h;if(this.destroyed)return!1;const d=null==(l=this.definitions)?void 0:l[t];if(null==d?void 0:d.length){const l=[],u=null!=(h=this.motionGroups[t])?h:[];for(let e=0;e<d.length;e++)null===u[e]||this.state.isActive(t,e)||l.push(e);if(l.length){const h=l[Math.floor(Math.random()*l.length)];return this.startMotion(t,h,e,{sound:i,volume:s,expression:r,resetExpression:o,onFinish:n,onError:a})}}return!1})}stopSpeaking(){this.currentAudio&&(S.dispose(this.currentAudio),this.currentAudio=void 0)}stopAllMotions(){this._stopAllMotions(),this.state.reset(),this.stopSpeaking()}update(t,e){var i;return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.shouldOverrideExpression()&&(null==(i=this.expressionManager)||i.restoreExpression()),this.state.complete(),this.state.shouldRequestIdleMotion()&&this.startRandomMotion(this.groups.idle,A.IDLE)),this.updateParameters(t,e)}mouthSync(){return this.currentAnalyzer?S.analyze(this.currentAnalyzer):0}destroy(){var t;this.destroyed=!0,this.emit("destroy"),this.stopAllMotions(),null==(t=this.expressionManager)||t.destroy();this.definitions=void 0,this.motionGroups=void 0}getMotionAndApplyExpression(t,e,i){return p(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(t,e,A.FORCE))return null;const s=this.getMotionDefinition(t,e);if(!s)return null;this.currentAudio&&S.dispose(this.currentAudio);const r=yield this.loadMotion(t,e);return this.state.start(r,t,e,A.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),m.log(this.tag,"Start motion:",this.getMotionName(s)),this.emit("motionStart",t,e,void 0),i&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(i)),r):null})}getMotionDefinition(t,e){var i,s;const r=null==(s=null==(i=this.definitions)?void 0:i[t])?void 0:s[e];return r||m.warn(this.tag,`Undefined motion at "${t}"[${e}]`),r}}function k(t,e){if(!Array.isArray(t))return[];const i=[];for(const s of t){if(!s||"object"!=typeof s)continue;const t=s,r="string"==typeof t.id?t.id:"string"==typeof t.Id?t.Id:void 0,o="string"==typeof t.name?t.name:"string"==typeof t.Name?t.Name:void 0;r&&o&&i.push({id:r,name:o,index:e(r)})}return i}const N={x:0,y:0,width:0,height:0};class G extends e.EventEmitter{constructor(){super(...arguments),c(this,"focusController",new _),c(this,"pose"),c(this,"physics"),c(this,"originalWidth",0),c(this,"originalHeight",0),c(this,"width",0),c(this,"height",0),c(this,"localTransform",new e.Matrix),c(this,"drawingMatrix",new e.Matrix),c(this,"hitAreas",{}),c(this,"textureFlipY",!1),c(this,"viewport",[0,0,0,0]),c(this,"destroyed",!1)}init(){this.setupLayout(),this.setupHitAreas()}setupLayout(){const t=this,e=this.getSize();t.originalWidth=e[0],t.originalHeight=e[1];const i=Object.assign({width:2,height:2},this.getLayout());this.localTransform.scale(i.width/2,i.height/2),t.width=this.originalWidth*this.localTransform.a,t.height=this.originalHeight*this.localTransform.d;const s=void 0!==i.x&&i.x-i.width/2||void 0!==i.centerX&&i.centerX||void 0!==i.left&&i.left-i.width/2||void 0!==i.right&&i.right+i.width/2||0,r=void 0!==i.y&&i.y-i.height/2||void 0!==i.centerY&&i.centerY||void 0!==i.top&&i.top-i.height/2||void 0!==i.bottom&&i.bottom+i.height/2||0;this.localTransform.translate(this.width*s,-this.height*r)}setupHitAreas(){const t=this.getHitAreaDefs();this.hitAreas={};for(const e of t)e.name&&(this.hitAreas[e.name]=e)}hitTest(t,e){return Object.keys(this.hitAreas).filter(i=>this.isHit(i,t,e))}isHit(t,e,i){const s=this.hitAreas[t];if(!s)return!1;let r=s.index;if(r<0){if(!s.id)return!1;if(r=this.getDrawableIndex(s.id),r<0)return!1;s.index=r}const o=this.getDrawableBounds(r,N);return o.x<=e&&e<=o.x+o.width&&o.y<=i&&i<=o.y+o.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],o=i[1],n=i[1];for(let a=0;a<i.length;a+=2){const t=i[a],e=i[a+1];s=Math.min(t,s),r=Math.max(t,r),o=Math.min(e,o),n=Math.max(e,n)}return null!=e||(e={}),e.x=s,e.y=o,e.width=r-s,e.height=n-o,e}updateTransform(t){this.drawingMatrix.copyFrom(t).append(this.localTransform)}update(t,e){this.focusController.update(t)}destroy(){this.destroyed=!0,this.emit("destroy"),this.motionManager.destroy(),this.motionManager=void 0,this.parallelMotionManager.forEach(t=>t.destroy()),this.parallelMotionManager=[]}updateMotions(t,e){this.emit("beforeMotionUpdate");const i=this.motionManager.update(t,e),s=this.parallelMotionManager.map(i=>i.update(t,e)),r=i||s.reduce((t,e)=>t||e,!1);return this.emit("afterMotionUpdate"),r}}class H extends Error{constructor(t,e,i,s=!1){super(t),this.url=e,this.status=i,this.aborted=s}}const j=class t{static createXHR(e,i,s,r,o){const n=new XMLHttpRequest;if(t.allXhrSet.add(n),e){let i=t.xhrMap.get(e);i?i.add(n):(i=new Set([n]),t.xhrMap.set(e,i))}return n.open("GET",i),n.responseType=s,n.onload=()=>{var t;200!==n.status&&0!==n.status||!n.response?null==(t=n.onerror)||t.call(n,new ProgressEvent("error")):r(n.response)},n.onerror=()=>{m.warn("XHRLoader",`Failed to load resource as ${n.responseType} (Status ${n.status}): ${i}`),o(new H("Network error.",i,n.status))},n.onabort=()=>o(new H("Aborted.",i,n.status,!0)),n.onloadend=()=>{var i;t.allXhrSet.delete(n),e&&(null==(i=t.xhrMap.get(e))||i.delete(n))},n}static cancelXHRs(){var e;null==(e=t.xhrMap.get(this))||e.forEach(e=>{e.abort(),t.allXhrSet.delete(e)}),t.xhrMap.delete(this)}static release(){t.allXhrSet.forEach(t=>t.abort()),t.allXhrSet.clear(),t.xhrMap=new WeakMap}};c(j,"xhrMap",new WeakMap),c(j,"allXhrSet",new Set),c(j,"loader",t=>new Promise((e,i)=>{const s=t.target,r=t.target&&"function"==typeof j.cancelXHRs?j.cancelXHRs.bind(t.target):void 0,o=j.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,i=>{t.result=i,e()},i);if(t.target&&r&&"function"==typeof s.listeners&&"function"==typeof s.once){const t=s.listeners("destroy");Array.isArray(t)&&t.includes(r)||s.once("destroy",r)}o.send()}));let U=j;function X(t,e){let i=-1;return function s(r,o){if(o)return Promise.reject(o);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const n=t[r];if(!n)return Promise.resolve();try{return Promise.resolve(n(e,s.bind(null,r+1)))}catch(a){const t=a instanceof Error?a:new Error(String(a));return Promise.reject(t)}}(0)}class B{static load(t){return p(this,null,function*(){return yield X(this.middlewares,t),t.result})}}c(B,"middlewares",[U.loader]);class $ extends F{constructor(t){if(super(t),c(this,"moc"),c(this,"textures"),c(this,"layout"),c(this,"hitAreas"),c(this,"initParams"),c(this,"initOpacities"),c(this,"expressions"),c(this,"motions",{}),!$.isValidJSON(t))throw new TypeError("Invalid JSON.");this.moc=t.model,y("string",t,this,"textures","textures"),this.copy(t)}static isValidJSON(t){if(!t||"object"!=typeof t)return!1;const e=!!Array.isArray(t.textures)&&t.textures.every(t=>"string"==typeof t);return"string"==typeof t.model&&e}copy(t){x("string",t,this,"name","name"),x("string",t,this,"pose","pose"),x("string",t,this,"physics","physics"),x("object",t,this,"layout","layout"),x("object",t,this,"motions","motions"),y("object",t,this,"hit_areas","hitAreas"),y("object",t,this,"expressions","expressions"),y("object",t,this,"init_params","initParams"),y("object",t,this,"init_opacities","initOpacities");const e=this.getFileStem(this.moc);this.setModelName(this.name,e)}replaceFiles(t){super.replaceFiles(t);for(const[e,i]of Object.entries(this.motions))for(let s=0;s<i.length;s++)i[s].file=t(i[s].file,`motions.${e}[${s}].file`),void 0!==i[s].sound&&(i[s].sound=t(i[s].sound,`motions.${e}[${s}].sound`));if(this.expressions)for(let e=0;e<this.expressions.length;e++)this.expressions[e].file=t(this.expressions[e].file,`expressions[${e}].file`)}}function W({lod:t,effectiveScale:e,textureWidth:i,textureHeight:s,lodScaleThreshold:r,lodTextureSizeThreshold:o,lodMaxLevel:n}){if("single-auto"!==q(t))return;if(!Number.isFinite(e)||e<=0)return;const a=Math.floor(i),l=Math.floor(s);if(a<=1||l<=1)return;if(e>=Y(r,.5))return;const d=Y(o,4096);if(Math.max(a,l)<d)return;const u=Math.round(Math.log2(1/e)),c=Math.max(1,Math.floor(Math.log2(Math.max(a,l)))),p=Math.min(c,(m=c,void 0!==(g=n)&&Number.isFinite(g)&&g>=1?Math.floor(g):m));var g,m;const f=function(t,e,i){return Math.min(i,Math.max(e,t))}(Math.max(1,u),1,p),M=h(2,f);return{level:f,width:Math.max(1,Math.round(a/M)),height:Math.max(1,Math.round(l/M))}}function q(t){return!1===t||"single-auto"===t?t:"full"}function V(t){return"nearest"===t?"nearest":"linear"}function Y(t,e){return void 0!==t&&Number.isFinite(t)&&t>0?t:e}function z(){}const J="Live2DFactory",Z=(t,e)=>p(null,null,function*(){if("string"==typeof t.source){const e=yield B.load({url:t.source,type:"json",target:t.live2dModel});e.url="string"==typeof e.url?e.url:t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()}),Q=(t,e)=>p(null,null,function*(){if(t.source instanceof F)return t.settings=t.source,e();if("object"==typeof t.source){const i=nt.findRuntime(t.source);if(i){const s=i.createModelSettings(t.source);return t.settings=s,t.live2dModel.emit("settingsLoaded",s),e()}}const i=t.source&&"string"==typeof t.source.url?t.source.url:void 0,s=nt.runtimes.map(t=>t.version).join(", ");if(0===nt.runtimes.length)throw new TypeError(["Unknown settings format: no Live2D runtimes registered.",'Import a published runtime entry before loading models (e.g. "<package>/cubism" for Cubism 3/4/5, "<package>/cubism-legacy" for Cubism 2).',i?`Settings URL: ${i}`:void 0].filter(Boolean).join("\n"));const r=(()=>{try{if(!t.source||"object"!=typeof t.source||Array.isArray(t.source))return;return Object.keys(t.source).slice(0,30).join(", ")}catch(e){return}})();throw new TypeError(["Unknown settings format: no matching runtime found for the loaded settings JSON.",s?`Registered runtimes (versions): ${s}`:void 0,r?`Settings JSON keys: ${r}`:void 0,i?`Settings URL: ${i}`:void 0].filter(Boolean).join("\n"))}),K=(t,e)=>{if(t.settings){const i=nt.findRuntime(t.settings);if(i)return i.ready().then(()=>e())}return e()},tt=(t,e)=>p(null,null,function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=nt.findRuntime(e);if(s){const r=[],o=e instanceof $?"json":"arraybuffer";e.pose&&r.push(B.load({settings:e,url:e.pose,type:o,target:i}).then(e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)}).catch(e=>{t.live2dModel.emit("poseLoadError",e),m.warn(J,"Failed to load pose.",e)})),e.physics&&r.push(B.load({settings:e,url:e.physics,type:o,target:i}).then(e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)}).catch(e=>{t.live2dModel.emit("physicsLoadError",e),m.warn(J,"Failed to load physics.",e)})),r.length&&(yield Promise.all(r))}}}),et=(t,i)=>p(null,null,function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=u({crossOrigin:t.options.crossOrigin},t.options.textureOptions);t.settings instanceof $&&(r.preferCreateImageBitmap=!1);const o=Promise.all(t.settings.textures.map(i=>function(t,i={}){const s=e.loadTextures.config,r=null==s?void 0:s.crossOrigin,o=null==s?void 0:s.preferCreateImageBitmap,n=null==s?void 0:s.preferWorkers;return void 0!==i.crossOrigin&&s&&(s.crossOrigin=i.crossOrigin),!1===i.preferCreateImageBitmap&&s&&(s.preferCreateImageBitmap=!1,s.preferWorkers=!1),e.Assets.load({src:t,data:{autoGenerateMipmaps:"full"===q(i.lod)}}).catch(t=>{if(t instanceof Error)throw t;throw new Error("Texture loading error",{cause:t})}).finally(()=>{s&&(s.crossOrigin=null!=r?r:s.crossOrigin,!1===i.preferCreateImageBitmap&&(s.preferCreateImageBitmap=null!=o?o:s.preferCreateImageBitmap,s.preferWorkers=null!=n?n:s.preferWorkers))})}(t.settings.resolveURL(i),r)));if(o.catch(z),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield o,s.emit("textureLoaded",s.textures)}}),it=(t,e)=>p(null,null,function*(){const i=t.settings;if(i instanceof F){const s=nt.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield B.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const o=s.createCoreModel(r);return t.internalModel=s.createInternalModel(o,i,t.options),e()}throw new TypeError("Missing settings.")}),st=class t{static resolveURL(e,i){var s;const r=null==(s=t.filesMap[e])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(e,i){const s={};for(const t of i.getDefinedFiles()){const r=decodeURI(w(i.url,t)),o=e.find(t=>t.webkitRelativePath===r);o&&(s[t]=URL.createObjectURL(o))}t.filesMap[i._objectURL]=s}static createSettings(e){return p(this,null,function*(){const i=e.find(t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json"));if(!i)throw new TypeError("Settings file not found");const s=yield t.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const o=nt.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");const n=o.createModelSettings(r);return n._objectURL=URL.createObjectURL(i),n})}static readText(t){return p(this,null,function*(){return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")})})}};c(st,"live2dFactory"),c(st,"filesMap",{}),c(st,"factory",(t,e)=>p(null,null,function*(){if(Array.isArray(t.source)&&t.source[0]instanceof File){const e=t.source;let i=e.settings;if(i){if(!i._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else i=yield st.createSettings(e);i.validateFiles(e.map(t=>encodeURI(t.webkitRelativePath))),st.upload(e,i),i.resolveURL=function(t){return st.resolveURL(this._objectURL,t)},t.source=i,t.live2dModel.once("modelLoaded",t=>{t.once("destroy",function(){const t=this.settings._objectURL;if(URL.revokeObjectURL(t),st.filesMap[t])for(const e of Object.values(st.filesMap[t]))URL.revokeObjectURL(e);delete st.filesMap[t]})})}return e()}));let rt=st;const ot=class t{static registerRuntime(e){t.runtimes.push(e),t.runtimes.sort((t,e)=>e.version-t.version)}static findRuntime(e){for(const i of t.runtimes)if(i.test(e))return i}static setupLive2DModel(e,i,s){return p(this,null,function*(){const r=new Promise(t=>e.once("textureLoaded",t)),o=new Promise(t=>e.once("modelLoaded",t)),n=Promise.all([r,o]).then(()=>e.emit("ready"));yield X(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield n,e.emit("load")})}static loadMotion(e,i,s){var r;const o=t=>e.emit("motionLoadError",i,s,t);try{const n=null==(r=e.definitions[i])?void 0:r[s];if(!n)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseMotionTasks(e));let a=t.motionTasksMap.get(e);a||(a={},t.motionTasksMap.set(e,a));let l=a[i];l||(l=[],a[i]=l);const h=e.getMotionFile(n);return null!=l[s]||(l[s]=B.load({url:h,settings:e.settings,type:e.motionDataType,target:e}).then(r=>{var o;const a=null==(o=t.motionTasksMap.get(e))?void 0:o[i];a&&(a[s]=void 0);const l=r,h=e.createMotion(l,i,n);return e.emit("motionLoaded",i,s,h),h}).catch(t=>{m.warn(e.tag,`Failed to load motion: ${h}\n`,t),o(t)})),l[s]}catch(n){m.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,n),o(n)}return Promise.resolve(void 0)}static loadExpression(e,i){var s;const r=t=>e.emit("expressionLoadError",i,t);try{const o=e.definitions[i];if(!o)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseExpressionTasks(e));let n=t.expressionTasksMap.get(e);n||(n=[],t.expressionTasksMap.set(e,n));const a=e.getExpressionFile(o),l=null!=(s=e.expressionDataType)?s:"json";return null!=n[i]||(n[i]=B.load({url:a,settings:e.settings,type:l,target:e}).then(s=>{const r=t.expressionTasksMap.get(e);r&&(r[i]=void 0);const n=s,a=e.createExpression(n,o);return e.emit("expressionLoaded",i,a),a}).catch(t=>{m.warn(e.tag,`Failed to load expression: ${a}\n`,t),r(t)})),n[i]}catch(o){m.warn(e.tag,`Failed to load expression at [${i}]\n`,o),r(o)}return Promise.resolve(void 0)}static releaseMotionTasks(e){t.motionTasksMap.delete(e)}static releaseExpressionTasks(e){t.expressionTasksMap.delete(e)}};c(ot,"runtimes",[]),c(ot,"urlToJSON",Z),c(ot,"jsonToSettings",Q),c(ot,"waitUntilReady",K),c(ot,"setupOptionals",tt),c(ot,"setupEssentials",et),c(ot,"createInternalModel",it),c(ot,"live2DModelMiddlewares",[rt.factory,Z,Q,K,tt,et,it]),c(ot,"motionTasksMap",new WeakMap),c(ot,"expressionTasksMap",new WeakMap);let nt=ot;C.prototype._loadMotion=function(t,e){return nt.loadMotion(this,t,e)},P.prototype._loadExpression=function(t){return nt.loadExpression(this,t)},rt.live2dFactory=nt;const at=class t{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:o=!0,autoInteract:n,ticker:a}={}){var l;c(this,"model"),c(this,"destroyed",!1),c(this,"_ticker"),c(this,"_autoUpdate",!1),c(this,"_autoHitTest",!1),c(this,"_autoFocus",!1),null!=a||(a=null!=(l=t.defaultTicker)?l:"undefined"!=typeof PIXI?PIXI.Ticker.shared:e.Ticker.shared),void 0!==n&&(r=n,o=n,m.warn(i.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=i,this.ticker=a,this.autoUpdate=s,this.autoHitTest=r,this.autoFocus=o,(r||o)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e,i;this._ticker&&this._ticker.remove(ht,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(ht,this),null==(i=this._ticker)||i.start())}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;this.destroyed||(t?this._ticker?(this._ticker.add(ht,this),this._autoUpdate=!0):m.warn(this.model.tag,"No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."):(null==(e=this._ticker)||e.remove(ht,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",dt,this):this.model.off("pointertap",dt,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?(this.model.on("globalpointermove",ut,this),this.model.on("pointermove",ut,this)):(this.model.off("globalpointermove",ut,this),this.model.off("pointermove",ut,this)),this._autoFocus=t)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(t){this.autoHitTest=t,this.autoFocus=t}onTickerUpdate(){const t=this.ticker.deltaMS;this.model.update(t)}onTap(t){this.model.tap(t.global.x,t.global.y)}onPointerMove(t){this.model.focus(t.global.x,t.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};c(at,"defaultTicker");let lt=at;function ht(){this.onTickerUpdate()}function dt(t){this.onTap(t)}function ut(t){this.onPointerMove(t)}class ct extends e.Transform{}const pt=new e.Point,gt=new e.Matrix,mt=new e.Matrix,ft={x:0,y:0,width:0,height:0},Mt=new e.Bounds;let xt=!1;class yt{constructor(t){this.renderer=t}addRenderable(t,e){var i,s;null==(s=null==(i=this.renderer.renderPipes.batch)?void 0:i.break)||s.call(i,e),e.add(t)}execute(t){!t.visible||t.alpha<=0||t.renderLive2D(this.renderer)}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}destroy(){}}c(yt,"extension",{type:[e.ExtensionType.WebGLPipes],name:"live2d"});const vt=yt;class bt extends e.Container{constructor(t){super(),c(this,"renderPipeId","live2d"),c(this,"tag","Live2DModel(uninitialized)"),c(this,"internalModel"),c(this,"textures",[]),c(this,"textureOptions"),c(this,"textureLODStates",[]),c(this,"textureLODFailures",[]),c(this,"transform",new ct),c(this,"anchor"),c(this,"_bounds",new e.Bounds),c(this,"_boundsDirty",!0),c(this,"_boundsRetryAfterDraw",!1),c(this,"gl",null),c(this,"elapsedTime",0),c(this,"deltaTime",0),c(this,"automator"),c(this,"currentGlId",0),c(this,"renderLive2D",t=>{var i,s,r,o,n;if(!(t instanceof e.WebGLRenderer))throw new Error("Renderer is not supported");t.geometry.resetState(),t.shader.resetState(),t.texture.resetState();let a=!1;this.gl!==t.gl&&(this.gl=t.gl,this.internalModel.updateWebGLContext(t.gl,this.generateUID()),a=!0);const{projectionMatrix:l,offset:h,worldTransformMatrix:d}=t.globalUniforms.globalUniformData,u=mt.copyFrom(d).append(this.groupTransform),c=(p=u,Math.max(Math.hypot(p.a,p.b),Math.hypot(p.c,p.d))*t.resolution);var p;for(let e=0;e<this.textures.length;e++){const i=this.textures[e];let s=this.resolveTextureForRender(e,i,c);try{this.uploadTextureForRender(t,s,a)}catch(b){if(s===i)throw new Error("Failed to upload Live2D texture.");const r=this.textureLODStates[e];(null==r?void 0:r.texture)===s&&(this.markTextureLODFailure(e,i,r.level),this.destroyTextureLODState(e)),s=i,this.uploadTextureForRender(t,s,a)}this.internalModel.bindTexture(e,t.texture.getGlSource(s.source).texture)}const g=t.renderTarget.viewport,m=t.renderTarget.renderTarget;let f=g.y;if(null==m?void 0:m.isRoot){f=m.colorTexture.source.pixelHeight-g.height-g.y}this.internalModel.viewport=[g.x,f,g.width,g.height];const M=this.deltaTime;this.deltaTime=0,M&&this.internalModel.update(M,this.elapsedTime),u.tx-=null!=(i=null==h?void 0:h.x)?i:0,u.ty-=null!=(s=null==h?void 0:h.y)?s:0;const x=gt.copyFrom(l).append(u);this.internalModel.updateTransform(x),this.internalModel.draw(t.gl),this._boundsRetryAfterDraw&&this.updateDrawableBounds(),t.state.resetState(),t.texture.resetState();const y=null==(r=t.renderTarget)?void 0:r.defaultClearColor,v=null==(n=null==(o=t.renderTarget)?void 0:o.adaptor)?void 0:n._clearColorCache;y&&(t.gl.clearColor(y[0],y[1],y[2],y[3]),v&&(v[0]=y[0],v[1]=y[1],v[2]=y[2],v[3]=y[3]))}),this.textureOptions=null==t?void 0:t.textureOptions,this.anchor=new e.ObservablePoint({_onUpdate:()=>this.onAnchorChange()},0,0),this.automator=new lt(this,t),this.once("modelLoaded",()=>this.initializeOnModelLoad(t))}get isRenderable(){return!0}get canBundle(){return!1}static from(t,e){return p(this,null,function*(){const i=new this(e);return yield nt.setupLive2DModel(i,t,e),i})}static fromSync(t,e){const i=new this(e);return nt.setupLive2DModel(i,t,e).then(()=>{var t;return null==(t=null==e?void 0:e.onLoad)?void 0:t.call(e)}).catch(t=>{var i;return null==(i=null==e?void 0:e.onError)?void 0:i.call(e,t)}),i}static registerTicker(t){lt.defaultTicker=t.shared}get bounds(){return this.internalModel?(this._boundsDirty&&this.updateDrawableBounds(),this._bounds):(this._bounds.set(0,0,0,0),this._bounds)}updateDrawableBounds(){if(!this.internalModel)return this._bounds.set(0,0,0,0),void(this._boundsDirty=!1);const t=this.internalModel.getDrawableIDs();Mt.clear();for(let i=0;i<t.length;i++){const s=t[i],r=this.internalModel.getDrawableIndex(s);if(r<0)continue;const o=this.internalModel.getDrawableBounds(r,ft);Number.isFinite(o.x)&&Number.isFinite(o.y)&&Number.isFinite(o.width)&&Number.isFinite(o.height)&&Mt.addFrame(o.x,o.y,o.x+o.width,o.y+o.height,e.Matrix.IDENTITY)}if(this._bounds.clear(),Mt.isValid&&Mt.isPositive)this._bounds.addFrame(Mt.minX,Mt.minY,Mt.maxX,Mt.maxY,this.internalModel.localTransform),this._boundsRetryAfterDraw=!1;else{const t=this.internalModel.originalWidth||this.internalModel.width,e=this.internalModel.originalHeight||this.internalModel.height;this._bounds.addFrame(0,0,t,e,this.internalModel.localTransform),this._boundsRetryAfterDraw=!0}this._boundsDirty=!1}generateUID(){return++this.currentGlId}collectRenderables(t,e,i){var s,r,o,n;if(this.parentRenderLayer&&this.parentRenderLayer!==i)return;if(this.globalDisplayStatus<7)return;if(!this.includeInBuild)return;this.sortableChildren&&this.sortChildren(),function(t){const e=t;e.renderPipes.live2d||(xt||(xt=!0,console.warn("[untitled-pixi-live2d-engine] Lazy Live2D render pipe registration is deprecated. Register Live2DPlugin explicitly with `extensions.add(Live2DPlugin)` before creating the Pixi renderer.")),e.renderPipes.live2d=new yt(t))}(e);const a=e.renderPipes,l=()=>{a.live2d.addRenderable(this,t)},h=()=>{const s=this.children,r=s.length;for(let o=0;o<r;o++)s[o].collectRenderables(t,e,i)},d=this.effects;if(d){for(let e=0;e<d.length;e++){const i=d[e],o=i.filters;if(o)for(const t of o)t&&"number"==typeof t.resolution&&1===t.resolution&&(t.resolution="inherit");null==(r=null==(s=a[i.pipe])?void 0:s.push)||r.call(s,i,this,t)}l(),h();for(let e=d.length-1;e>=0;e--){const i=d[e];null==(n=null==(o=a[i.pipe])?void 0:o.pop)||n.call(o,i,this,t)}}else l(),h()}initializeOnModelLoad(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`,this.onAnchorChange(),this.updateDrawableBounds()}onAnchorChange(){this.internalModel&&this.pivot&&this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i){return p(this,arguments,function*(t,e,i,{sound:s,volume:r=.5,expression:o,resetExpression:n=!0,onFinish:a,onError:l}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:o,resetExpression:n,onFinish:a,onError:l}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:o,resetExpression:n,onFinish:a,onError:l})})}motionLastFrame(t,e){return p(this,arguments,function*(t,e,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(t,e,{expression:i})})}parallelMotion(t){return p(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].startMotion(t.group,t.index,t.priority)),i=[];for(const t of e)i.push(yield t);return i})}parallelLastFrame(t){return p(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].playMotionLastFrame(t.group,t.index)),i=[];for(const t of e)i.push(yield t);return i})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:o}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,onFinish:r,onError:o})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){pt.x=t,pt.y=e,this.toModelPosition(pt,pt,!0);const s=pt.x/this.internalModel.originalWidth*2-1,r=pt.y/this.internalModel.originalHeight*2-1,o=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(o),-Math.sin(o),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&this.emit("hit",i)}hitTest(t,e){return pt.x=t,pt.y=e,this.toModelPosition(pt,pt),this.internalModel.hitTest(pt.x,pt.y)}toModelPosition(t,e=t.clone(),i){return i||this.updateLocalTransform(),this.toLocal(t,void 0,e,i),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.bounds.containsPoint(t.x,t.y)}_calculateBounds(){if(!this.internalModel)return void this.getBounds().set(0,0,0,0);const t=this.internalModel.width,e=this.internalModel.height;this.getBounds().addFrame(0,0,t,e,this.transform.matrix)}update(t){this.deltaTime+=t,this.elapsedTime+=t}resolveTextureForRender(t,i,s){var n;const a=W((l=u({},this.textureOptions),h={effectiveScale:s,textureWidth:i.source.pixelWidth,textureHeight:i.source.pixelHeight},r(l,o(h))));var l,h;if(!a)return i;const d=this.textureLODFailures[t];if((null==d?void 0:d.source)===i&&d.levels.has(a.level))return i;const c=this.textureLODStates[t];if((null==c?void 0:c.source)===i&&c.level===a.level&&!c.texture.destroyed)return c.texture;this.destroyTextureLODState(t);const p=function(t,i,s,r,o){var n,a;const l=t.source.resource;if(!function(t){if(!t||"object"!=typeof t)return!1;const{width:e,height:i}=t;return"number"==typeof e&&e>0&&"number"==typeof i&&i>0}(l))return;const h=e.DOMAdapter.get().createCanvas(s,r),d=h.getContext("2d");if(!d)return;try{d.clearRect(0,0,s,r),d.imageSmoothingEnabled="nearest"!==o,"imageSmoothingQuality"in d&&"nearest"!==o&&(d.imageSmoothingQuality="high"),d.drawImage(l,0,0,t.source.pixelWidth,t.source.pixelHeight,0,0,s,r)}catch(c){return}const u=`${null!=(a=null!=(n=t.label)?n:t.source.label)?a:"Live2DTexture"} LOD ${i}`;return new e.Texture({label:u,source:new e.CanvasSource({resource:h,width:s,height:r,resolution:1,scaleMode:V(o),autoGenerateMipmaps:!1,label:u})})}(i,a.level,a.width,a.height,null==(n=this.textureOptions)?void 0:n.lodFilter);return p?(this.textureLODStates[t]={source:i,level:a.level,texture:p},p):(this.markTextureLODFailure(t,i,a.level),i)}markTextureLODFailure(t,e,i){let s=this.textureLODFailures[t];(null==s?void 0:s.source)!==e&&(s={source:e,levels:new Set},this.textureLODFailures[t]=s),s.levels.add(i)}destroyTextureLODState(t){const e=this.textureLODStates[t];e&&(e.texture.destroy(!0),this.textureLODStates[t]=void 0)}destroyTextureLODStates(){for(let t=0;t<this.textureLODStates.length;t++)this.destroyTextureLODState(t);this.textureLODFailures.length=0}uploadTextureForRender(t,e,i){const s=Boolean(e.source._gpuData[t.uid]);!i&&s||(t.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,this.internalModel.textureFlipY),t.texture.bind(e,0))}destroy(t){this.emit("destroy"),this.destroyTextureLODStates(),(null==t?void 0:t.texture)&&this.textures.forEach(e=>e.destroy(t.baseTexture)),this.automator.destroy(),this.internalModel.destroy(),super.destroy(t)}}if(!("Live2D"in window))throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const Et=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){Et.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class wt extends AMotion{constructor(t){super(),c(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:g.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:g.expressionFadingDuration),Array.isArray(t.params)&&t.params.forEach(t=>{const e=t.calc||"add";if("add"===e){const e=t.def||0;t.val-=e}else if("mult"===e){const e=t.def||1;t.val/=e}this.params.push({calc:e,val:t.val,id:t.id})})}updateParamExe(t,e,i,s){this.params.forEach(e=>{t.setParamFloat(e.id,e.val*i)})}}class Pt extends P{constructor(t,e){var i;super(t,e),c(this,"queueManager",new MotionQueueManager),c(this,"definitions"),this.definitions=null!=(i=this.settings.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex(e=>e.name===t)}getExpressionFile(t){return t.file}createExpression(t,e){return new wt(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}function Lt(t,e,i){const s=i.getDurationMSec(),r=t.startMotion(i,!0),o=t.motions.find(t=>!!t&&t._$sr===r);return!!o&&(i.updateParamExe(e.coreModel,s,1,o),!0)}class It extends C{constructor(t){super(t),c(this,"definitions"),c(this,"groups",{idle:"idle"}),c(this,"motionDataType","arraybuffer"),c(this,"queueManager",new MotionQueueManager),c(this,"lipSyncIds"),c(this,"expressionManager"),this.definitions=this.settings.motions,this.init(t.options),this.lipSyncIds=["PARAM_MOUTH_OPEN_Y"]}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new Pt(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(t,e,i){const s=Live2DMotion.loadMotion(t),r=e===this.groups.idle?g.idleMotionFadingDuration:g.motionFadingDuration;return s.setFadeIn(i.fade_in>0?i.fade_in:r),s.setFadeOut(i.fade_out>0?i.fade_out:r),s}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e,i){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}motionLastFrame(t,e){return p(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,Lt(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class _t extends e.EventEmitter{constructor(t){super(),c(this,"tag"),c(this,"manager"),c(this,"settings"),c(this,"state",new O),c(this,"playing",!1),c(this,"destroyed",!1),c(this,"parent"),this.settings=t.settings,this.tag=`ParallelMotionManager(${this.settings.name})`,this.state.tag=this.tag,this.manager=t.motionManager,this.parent=t}startMotion(t,e){return p(this,arguments,function*(t,e,i=A.NORMAL,s=[]){var r;if(!this.state.reserve(t,e,i))return!1;const o=null==(r=this.manager.definitions[t])?void 0:r[e];if(!o)return!1;const n=yield this.manager.loadMotion(t,e);return!!this.state.start(n,t,e,i)&&(m.log(this.tag,"Start motion:",this.getMotionName(o)),this.emit("motionStart",t,e,void 0),this.playing=!0,this._startMotion(n,void 0,s),!0)})}startRandomMotion(t,e){return p(this,null,function*(){var i;const s=this.manager.definitions[t];if(null==s?void 0:s.length){const r=[],o=null!=(i=this.manager.motionGroups[t])?i:[];for(let e=0;e<s.length;e++)null===o[e]||this.state.isActive(t,e)||r.push(e);if(r.length){const i=r[Math.floor(Math.random()*r.length)];return this.startMotion(t,i,e)}}return!1})}stopAllMotions(){this._stopAllMotions(),this.state.reset()}update(t,e){return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.complete()),this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy"),this.stopAllMotions()}}class Ft extends _t{constructor(t){super(t),c(this,"queueManager",new MotionQueueManager)}isFinished(){return this.queueManager.isFinished()}getMotionName(t){return t.file}_startMotion(t,e,i){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}playMotionLastFrame(t,e){return p(this,null,function*(){var i;if(!this.state.reserve(t,e,A.FORCE))return!1;const s=null==(i=this.manager.definitions[t])?void 0:i[e];if(!s)return!1;const r=yield this.manager.loadMotion(t,e);return!!this.state.start(r,t,e,A.FORCE)&&(m.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",t,e,void 0),this.playing=!0,!!Lt(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class At{constructor(t){c(this,"leftParam"),c(this,"rightParam"),c(this,"blinkInterval",4e3),c(this,"closingDuration",100),c(this,"closedDuration",50),c(this,"openingDuration",150),c(this,"eyeState",0),c(this,"eyeParamValue",1),c(this,"closedTimer",0),c(this,"nextBlinkTimeLeft",this.blinkInterval),this.coreModel=t,this.leftParam=t.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=t.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(t){this.eyeParamValue=f(t,0,1),this.coreModel.setParamFloat(this.leftParam,this.eyeParamValue),this.coreModel.setParamFloat(this.rightParam,this.eyeParamValue)}update(t){switch(this.eyeState){case 0:this.nextBlinkTimeLeft-=t,this.nextBlinkTimeLeft<0&&(this.eyeState=1,this.nextBlinkTimeLeft=this.blinkInterval+this.closingDuration+this.closedDuration+this.openingDuration+M(0,2e3));break;case 1:this.setEyeParams(this.eyeParamValue+t/this.closingDuration),this.eyeParamValue<=0&&(this.eyeState=2,this.closedTimer=0);break;case 2:this.closedTimer+=t,this.closedTimer>=this.closedDuration&&(this.eyeState=3);break;case 3:this.setEyeParams(this.eyeParamValue+t/this.openingDuration),this.eyeParamValue>=1&&(this.eyeState=0)}}}const Ot=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class Dt extends G{constructor(t,e,i){super(),c(this,"settings"),c(this,"options"),c(this,"coreModel"),c(this,"motionManager"),c(this,"parallelMotionManager"),c(this,"eyeBlink"),c(this,"eyeballXParamIndex"),c(this,"eyeballYParamIndex"),c(this,"angleXParamIndex"),c(this,"angleYParamIndex"),c(this,"angleZParamIndex"),c(this,"bodyAngleXParamIndex"),c(this,"breathParamIndex"),c(this,"textureFlipY",!0),c(this,"lipSync",!0),c(this,"drawDataCount",0),c(this,"disableCulling",!1),c(this,"hasDrawn",!1),c(this,"customHitAreas"),this.coreModel=t,this.settings=e,this.options=Object.assign({},{breathDepth:1,lipSyncGain:1.5,lipSyncWeight:.4},i),void 0!==(null==i?void 0:i.useHighPrecisionMask)&&!1!==i.useHighPrecisionMask&&m.warn("CubismLegacyInternalModel","`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."),this.motionManager=new It(this),this.parallelMotionManager=[],this.eyeBlink=new At(t),this.eyeballXParamIndex=t.getParamIndex("PARAM_EYE_BALL_X"),this.eyeballYParamIndex=t.getParamIndex("PARAM_EYE_BALL_Y"),this.angleXParamIndex=t.getParamIndex("PARAM_ANGLE_X"),this.angleYParamIndex=t.getParamIndex("PARAM_ANGLE_Y"),this.angleZParamIndex=t.getParamIndex("PARAM_ANGLE_Z"),this.bodyAngleXParamIndex=t.getParamIndex("PARAM_BODY_ANGLE_X"),this.breathParamIndex=t.getParamIndex("PARAM_BREATH"),this.init()}init(){super.init(),this.settings.initParams&&this.settings.initParams.forEach(({id:t,value:e})=>this.coreModel.setParamFloat(t,e)),this.settings.initOpacities&&this.settings.initOpacities.forEach(({id:t,value:e})=>this.coreModel.setPartsOpacity(t,e)),this.coreModel.saveParam();const t=this.coreModel.getModelContext()._$aS;(null==t?void 0:t.length)&&(this.drawDataCount=t.length);let e=this.coreModel.drawParamWebGL.culling;Object.defineProperty(this.coreModel.drawParamWebGL,"culling",{set:t=>e=t,get:()=>!this.disableCulling&&e});const i=this.coreModel.getModelContext().clipManager,s=i.setupClip.bind(i);i.setupClip=(t,e)=>{s.call(i,t,e),e.gl.viewport(...this.viewport)}}getSize(){return[this.coreModel.getCanvasWidth(),this.coreModel.getCanvasHeight()]}getLayout(){const t={};if(this.settings.layout)for(const[e,i]of Object.entries(this.settings.layout)){let s=e;"center_x"===e?s="centerX":"center_y"===e&&(s="centerY"),"number"==typeof i&&(t[s]=i)}return t}updateWebGLContext(t,e){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(t),i.glno=e,i._$NT=null,i._$no=null,i._$vS=null;const s=this.coreModel.getModelContext().clipManager;s.curFrameNo=e;const r=t.getParameter(t.FRAMEBUFFER_BINDING);s.getMaskRenderTexture(),t.bindFramebuffer(t.FRAMEBUFFER,r)}bindTexture(t,e){this.coreModel.setTexture(t,e)}getHitAreaDefs(){var t,e,i;const s=this.settings.json;return k(null!=(i=null!=(e=null!=(t=this.settings.hitAreas)?t:s.hit_areas)?e:s.HitAreas)?i:s.hitAreas,t=>this.coreModel.getDrawDataIndex(t))}getDrawableIDs(){const t=this.coreModel.getModelContext(),e=[];for(let i=0;i<this.drawDataCount;i++){const s=t.getDrawData(i);s&&e.push(s.getDrawDataID().id)}return e}getDrawableIndex(t){return this.coreModel.getDrawDataIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawDataIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);return this.coreModel.getTransformedPoints(t).slice()}hitTest(t,e){this.hasDrawn||m.warn("Trying to hit-test a Cubism 2 model that has not been rendered yet. Drawable hit areas may be empty until the first draw.");const i=super.hitTest(t,e),s=this.hitTestCustom(t,e);return s.length?i.length?[...new Set([...i,...s])]:s:i}update(t,e){var i,s,r,o;super.update(t,e);const n=this.coreModel,a=this.updateMotions(n,e);if(n.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(n,e),a||null==(s=this.eyeBlink)||s.update(t),this.updateFocus(),this.updateNaturalMovements(t,e),this.lipSync&&this.motionManager.currentAudio){let t=this.motionManager.mouthSync()*this.options.lipSyncGain;const e=1,i=t>0?.1:0;t=Math.pow(t,1.15),t=f(t,i,e);for(let s=0;s<this.motionManager.lipSyncIds.length;++s)this.coreModel.addToParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[s]),t,this.options.lipSyncWeight)}null==(r=this.physics)||r.update(e),null==(o=this.pose)||o.update(t),this.emit("beforeModelUpdate"),n.update(),n.loadParam()}updateFocus(){this.coreModel.addToParamFloat(this.eyeballXParamIndex,this.focusController.x),this.coreModel.addToParamFloat(this.eyeballYParamIndex,this.focusController.y),this.coreModel.addToParamFloat(this.angleXParamIndex,30*this.focusController.x),this.coreModel.addToParamFloat(this.angleYParamIndex,30*this.focusController.y),this.coreModel.addToParamFloat(this.angleZParamIndex,this.focusController.x*this.focusController.y*-30),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,10*this.focusController.x)}updateNaturalMovements(t,e){const i=e/1e3*2*Math.PI;this.coreModel.addToParamFloat(this.angleXParamIndex,15*this.options.breathDepth*Math.sin(i/6.5345)*.5),this.coreModel.addToParamFloat(this.angleYParamIndex,8*this.options.breathDepth*Math.sin(i/3.5345)*.5),this.coreModel.addToParamFloat(this.angleZParamIndex,10*this.options.breathDepth*Math.sin(i/5.5345)*.5),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,4*this.options.breathDepth*Math.sin(i/15.5345)*.5),this.coreModel.setParamFloat(this.breathParamIndex,.5+.5*Math.sin(i/3.2345))}draw(t){const e=this.disableCulling;t.getParameter(t.FRAMEBUFFER_BINDING)&&(this.disableCulling=!0);const i=this.drawingMatrix;Ot[0]=i.a,Ot[1]=i.b,Ot[4]=i.c,Ot[5]=i.d,Ot[12]=i.tx,Ot[13]=i.ty,this.coreModel.setMatrix(Ot),this.coreModel.draw(),this.hasDrawn=!0,this.disableCulling=e}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new Ft(this))}destroy(){super.destroy(),this.coreModel=void 0}hitTestCustom(t,e){const i=this.getCustomHitAreas();if(!i)return[];const s=this.originalWidth||this.width,r=this.originalHeight||this.height;if(!s||!r)return[];const o=t/s*2-1,n=1-e/r*2,a=[];for(const[l,h]of Object.entries(i))o>=h.minX&&o<=h.maxX&&n>=h.minY&&n<=h.maxY&&a.push(l);return a}getCustomHitAreas(){var t,e,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const o=this.settings.json,n=null!=(i=null!=(e=null!=(t=o.hit_areas_custom)?t:o.hitAreasCustom)?e:o.HitAreasCustom)?i:o.HitAreas_Custom;if(!n||"object"!=typeof n)return this.customHitAreas=null,null;const a=n,l={},h=(t,e,i)=>{if(!t||!Array.isArray(e)||!Array.isArray(i))return;if(e.length<2||i.length<2)return;const s=Number(e[0]),r=Number(e[1]),o=Number(i[0]),n=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(o)&&Number.isFinite(n)&&(l[t]={minX:Math.min(s,r),maxX:Math.max(s,r),minY:Math.min(o,n),maxY:Math.max(o,n)})};for(const[d,u]of Object.entries(a)){if(d.endsWith("_x")){const t=d.slice(0,-2);h(t,u,a[`${t}_y`]);continue}if(!d.endsWith("_y")&&(u&&"object"==typeof u)){const t=u;h(d,null!=(s=t.x)?s:t.X,null!=(r=t.y)?r:t.Y)}}return this.customHitAreas=Object.keys(l).length?l:null,this.customHitAreas}}const Tt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},St={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class Rt{constructor(t,e){c(this,"physicsHairs",[]),this.coreModel=t,e.physics_hair&&(this.physicsHairs=e.physics_hair.map(t=>{const e=new PhysicsHair;return e.setup(t.setup.length,t.setup.regist,t.setup.mass),t.src.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const o=Tt[i];o&&e.addSrcParam(o,t,s,r)}),t.targets.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const o=St[i];o&&e.addTargetParam(o,t,s,r)}),e}))}update(t){this.physicsHairs.forEach(e=>e.update(this.coreModel,t))}}class Ct{constructor(t){c(this,"paramIndex",-1),c(this,"partsIndex",-1),c(this,"link",[]),this.id=t}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class kt{constructor(t,e){c(this,"opacityAnimDuration",500),c(this,"partsGroups",[]),this.coreModel=t,e.parts_visible&&(this.partsGroups=e.parts_visible.map(({group:t})=>t.map(({id:t,link:e})=>{const i=new Ct(t);return e&&(i.link=e.map(t=>new Ct(t))),i})),this.init())}init(){this.partsGroups.forEach(t=>{t.forEach(t=>{if(t.initIndex(this.coreModel),t.paramIndex>=0){const e=0!==this.coreModel.getParamFloat(t.paramIndex);this.coreModel.setPartsOpacity(t.partsIndex,e?1:0),this.coreModel.setParamFloat(t.paramIndex,e?1:0),t.link.length>0&&t.link.forEach(t=>t.initIndex(this.coreModel))}})})}normalizePartsOpacityGroup(t,e){const i=this.coreModel,s=.5;let r=1,o=t.findIndex(({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t));if(o>=0){const s=i.getPartsOpacity(t[o].partsIndex);r=f(s+e/this.opacityAnimDuration,0,1)}else o=0,r=1;t.forEach(({partsIndex:t},e)=>{if(t>=0)if(o==e)i.setPartsOpacity(t,r);else{let e,o=i.getPartsOpacity(t);e=r<s?-.5*r/s+1:(1-r)*s/.5;(1-e)*(1-r)>.15&&(e=1-.15/(1-r)),o>e&&(o=e),i.setPartsOpacity(t,o)}})}copyOpacity(t){const e=this.coreModel;t.forEach(({partsIndex:t,link:i})=>{if(t>=0&&i){const s=e.getPartsOpacity(t);i.forEach(({partsIndex:t})=>{t>=0&&e.setPartsOpacity(t,s)})}})}update(t){this.partsGroups.forEach(e=>{this.normalizePartsOpacityGroup(e,t),this.copyOpacity(e)})}}nt.registerRuntime({version:2,test:t=>t instanceof $||$.isValidJSON(t),ready:()=>Promise.resolve(),isValidMoc(t){if(t.byteLength<3)return!1;const e=new Int8Array(t,0,3);return"moc"===String.fromCharCode(...e)},createModelSettings:t=>new $(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),i=Live2D.getError();if(i){if(i instanceof Error)throw i;const t="string"==typeof i?i:`Live2D error: ${JSON.stringify(i)}`;throw new Error(t)}return e},createInternalModel:(t,e,i)=>new Dt(t,e,i),createPose:(t,e)=>new kt(t,e),createPhysics:(t,e)=>new Rt(t,e)}),t.CubismLegacyExpressionManager=Pt,t.CubismLegacyInternalModel=Dt,t.CubismLegacyModelSettings=$,t.CubismLegacyMotionManager=It,t.CubismLegacyParallelMotionManager=Ft,t.ExpressionManager=P,t.FileLoader=rt,t.FocusController=_,t.InternalModel=G,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=wt,t.Live2DEyeBlink=At,t.Live2DFactory=nt,t.Live2DLoader=B,t.Live2DModel=bt,t.Live2DPhysics=Rt,t.Live2DPlugin=vt,t.Live2DPose=kt,t.Live2DTransform=ct,t.MBToByte=function(t){return 1024*t*1024},t.ModelSettings=F,t.MotionManager=C,t.MotionPreloadStrategy=R,t.MotionPriority=A,t.MotionState=O,t.SoundManager=S,t.VERSION="1.2.1",t.VOLUME=T,t.XHRLoader=U,t.applyMixins=function(t,e){e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))})})},t.clamp=f,t.config=g,t.copyArray=y,t.copyProperty=x,t.folderName=v,t.logger=m,t.normalizeHitAreaDefs=k,t.rand=M,t.remove=b,t.resolveURL=w,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});