untitled-pixi-live2d-engine 1.2.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.
@@ -106,7 +106,7 @@ const config = {
106
106
  preserveExpressionOnMotion: true,
107
107
  cubism: CubismFrameworkConfig
108
108
  };
109
- const VERSION = "1.2.0";
109
+ const VERSION = "1.2.1";
110
110
  const logger = {
111
111
  log(tag, ...messages) {
112
112
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -108,7 +108,7 @@ var __async = (__this, __arguments, generator) => {
108
108
  preserveExpressionOnMotion: true,
109
109
  cubism: CubismFrameworkConfig
110
110
  };
111
- const VERSION = "1.2.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) {
@@ -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 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.0",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"})});
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"})});
package/dist/cubism.es.js CHANGED
@@ -2760,7 +2760,7 @@ const config = {
2760
2760
  preserveExpressionOnMotion: true,
2761
2761
  cubism: CubismFrameworkConfig
2762
2762
  };
2763
- const VERSION = "1.2.0";
2763
+ const VERSION = "1.2.1";
2764
2764
  const logger = {
2765
2765
  log(tag, ...messages) {
2766
2766
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -11478,17 +11478,13 @@ class CubismInternalModel extends InternalModel {
11478
11478
  super.init();
11479
11479
  const eyeBlinkParameters = this.settings.getEyeBlinkParameters();
11480
11480
  if (eyeBlinkParameters.length) {
11481
- if (this.isCubismModelSetting(this.settings)) {
11482
- this.eyeBlink = CubismEyeBlink.create(this.settings);
11483
- } else {
11484
- const parameterIds = new csmVector();
11485
- for (const parameter of eyeBlinkParameters) {
11486
- parameterIds.pushBack(this.idManager.getId(parameter));
11487
- }
11488
- const eyeBlink = CubismEyeBlink.create();
11489
- (_a = eyeBlink.setParameterIds) == null ? void 0 : _a.call(eyeBlink, parameterIds);
11490
- this.eyeBlink = eyeBlink;
11481
+ const parameterIds = new csmVector();
11482
+ for (const parameter of eyeBlinkParameters) {
11483
+ parameterIds.pushBack(this.idManager.getId(parameter));
11491
11484
  }
11485
+ const eyeBlink = CubismEyeBlink.create();
11486
+ (_a = eyeBlink.setParameterIds) == null ? void 0 : _a.call(eyeBlink, parameterIds);
11487
+ this.eyeBlink = eyeBlink;
11492
11488
  }
11493
11489
  const breathParams = new csmVector();
11494
11490
  breathParams.pushBack(
@@ -11680,9 +11676,6 @@ class CubismInternalModel extends InternalModel {
11680
11676
  this.renderer = void 0;
11681
11677
  this.coreModel = void 0;
11682
11678
  }
11683
- isCubismModelSetting(settings) {
11684
- return typeof settings.getEyeBlinkParameterCount === "function" && typeof settings.getEyeBlinkParameterId === "function";
11685
- }
11686
11679
  }
11687
11680
  class ICubismModelSetting {
11688
11681
  }
@@ -12397,6 +12390,10 @@ var Live2DCubismFramework$6;
12397
12390
  Live2DCubismFramework2.CubismModelSettingJson = CubismModelSettingJson;
12398
12391
  Live2DCubismFramework2.FrequestNode = FrequestNode;
12399
12392
  })(Live2DCubismFramework$6 || (Live2DCubismFramework$6 = {}));
12393
+ const defaultEyeBlinkParameters = [
12394
+ CubismDefaultParameterId.ParamEyeLOpen,
12395
+ CubismDefaultParameterId.ParamEyeROpen
12396
+ ];
12400
12397
  class CubismModelSettings extends ModelSettings {
12401
12398
  constructor(json) {
12402
12399
  var _a, _b;
@@ -12496,7 +12493,7 @@ class CubismModelSettings extends ModelSettings {
12496
12493
  }
12497
12494
  }
12498
12495
  }
12499
- return parameters;
12496
+ return parameters.length ? parameters : [...defaultEyeBlinkParameters];
12500
12497
  }
12501
12498
  getLipSyncParameters() {
12502
12499
  var _a, _b, _c;
package/dist/cubism.js CHANGED
@@ -2762,7 +2762,7 @@ var __async = (__this, __arguments, generator) => {
2762
2762
  preserveExpressionOnMotion: true,
2763
2763
  cubism: CubismFrameworkConfig
2764
2764
  };
2765
- const VERSION = "1.2.0";
2765
+ const VERSION = "1.2.1";
2766
2766
  const logger = {
2767
2767
  log(tag, ...messages) {
2768
2768
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -11480,17 +11480,13 @@ var __async = (__this, __arguments, generator) => {
11480
11480
  super.init();
11481
11481
  const eyeBlinkParameters = this.settings.getEyeBlinkParameters();
11482
11482
  if (eyeBlinkParameters.length) {
11483
- if (this.isCubismModelSetting(this.settings)) {
11484
- this.eyeBlink = CubismEyeBlink.create(this.settings);
11485
- } else {
11486
- const parameterIds = new csmVector();
11487
- for (const parameter of eyeBlinkParameters) {
11488
- parameterIds.pushBack(this.idManager.getId(parameter));
11489
- }
11490
- const eyeBlink = CubismEyeBlink.create();
11491
- (_a = eyeBlink.setParameterIds) == null ? void 0 : _a.call(eyeBlink, parameterIds);
11492
- this.eyeBlink = eyeBlink;
11483
+ const parameterIds = new csmVector();
11484
+ for (const parameter of eyeBlinkParameters) {
11485
+ parameterIds.pushBack(this.idManager.getId(parameter));
11493
11486
  }
11487
+ const eyeBlink = CubismEyeBlink.create();
11488
+ (_a = eyeBlink.setParameterIds) == null ? void 0 : _a.call(eyeBlink, parameterIds);
11489
+ this.eyeBlink = eyeBlink;
11494
11490
  }
11495
11491
  const breathParams = new csmVector();
11496
11492
  breathParams.pushBack(
@@ -11682,9 +11678,6 @@ var __async = (__this, __arguments, generator) => {
11682
11678
  this.renderer = void 0;
11683
11679
  this.coreModel = void 0;
11684
11680
  }
11685
- isCubismModelSetting(settings) {
11686
- return typeof settings.getEyeBlinkParameterCount === "function" && typeof settings.getEyeBlinkParameterId === "function";
11687
- }
11688
11681
  }
11689
11682
  class ICubismModelSetting {
11690
11683
  }
@@ -12399,6 +12392,10 @@ var __async = (__this, __arguments, generator) => {
12399
12392
  Live2DCubismFramework2.CubismModelSettingJson = CubismModelSettingJson;
12400
12393
  Live2DCubismFramework2.FrequestNode = FrequestNode;
12401
12394
  })(Live2DCubismFramework$6 || (Live2DCubismFramework$6 = {}));
12395
+ const defaultEyeBlinkParameters = [
12396
+ CubismDefaultParameterId.ParamEyeLOpen,
12397
+ CubismDefaultParameterId.ParamEyeROpen
12398
+ ];
12402
12399
  class CubismModelSettings extends ModelSettings {
12403
12400
  constructor(json) {
12404
12401
  var _a, _b;
@@ -12498,7 +12495,7 @@ var __async = (__this, __arguments, generator) => {
12498
12495
  }
12499
12496
  }
12500
12497
  }
12501
- return parameters;
12498
+ return parameters.length ? parameters : [...defaultEyeBlinkParameters];
12502
12499
  }
12503
12500
  getLipSyncParameters() {
12504
12501
  var _a, _b, _c;