untitled-pixi-live2d-engine 1.0.2 → 1.2.0

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.
@@ -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=Math.pow,n=(t,e,i)=>((t,e,i)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,"symbol"!=typeof e?e+"":e,i),o=(t,e,i)=>new Promise((s,r)=>{var n=t=>{try{a(i.next(t))}catch(e){r(e)}},o=t=>{try{a(i.throw(t))}catch(e){r(e)}},a=t=>t.done?s(t.value):Promise.resolve(t.value).then(n,o);a((i=i.apply(t,e)).next())});const a={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"}))},l={log(t,...e){a.logLevel<=a.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){a.logLevel<=a.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){a.logLevel<=a.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function h(t,e,i){return t<e?e:t>i?i:t}function d(t,e){return Math.random()*(e-t)+t}function u(t,e,i,s,r){const n=e[s];null!==n&&typeof n===t&&(i[r]=n)}function c(t,e,i,s,r){const n=e[s];Array.isArray(n)&&(i[r]=n.filter(e=>null!==e&&typeof e===t))}function p(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 g(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}const m=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function f(t,e){if(!e)return t;if(m.test(e))return e;if(e.startsWith("/"))return m.test(t)?new URL(e,t).toString():e;if(m.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 n=r.pathname+r.search+r.hash;return!t.startsWith("/")&&n.startsWith("/")&&(n=n.slice(1)),n}class M extends e.EventEmitter{constructor(t,e){super(),n(this,"expressionDataType","json"),n(this,"tag"),n(this,"settings"),n(this,"expressions",[]),n(this,"defaultExpression"),n(this,"currentExpression"),n(this,"reserveExpressionIndex",-1),n(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 o(this,null,function*(){if(!this.definitions[t])return void l.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void l.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 o(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 o(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 y=40/7.5,x=1/150;class v{constructor(){n(this,"targetX",0),n(this,"targetY",0),n(this,"x",0),n(this,"y",0),n(this,"vx",0),n(this,"vy",0)}focus(t,e,i=!1){this.targetX=h(t,-1,1),this.targetY=h(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(r(e,2)+r(i,2)),n=y/(1e3/t);let o=n*(e/s)-this.vx,a=n*(i/s)-this.vy;const l=Math.sqrt(r(o,2)+r(a,2)),h=n*x*t;l>h&&(o*=h/l,a*=h/l),this.vx+=o,this.vy+=a;const d=Math.sqrt(r(this.vx,2)+r(this.vy,2)),u=.5*(Math.sqrt(r(h,2)+8*h*s)-h);d>u&&(this.vx*=u/d,this.vy*=u/d),this.x+=this.vx,this.y+=this.vy}}class E{constructor(t){n(this,"json"),n(this,"name"),n(this,"url"),n(this,"pose"),n(this,"physics"),this.json=t,this.url=t.url,this.name=p(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=p(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 f(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 P=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(P||{});class b{constructor(){n(this,"tag"),n(this,"debug",!1),n(this,"currentPriority",0),n(this,"reservePriority",0),n(this,"currentGroup"),n(this,"currentIndex"),n(this,"reservedGroup"),n(this,"reservedIndex"),n(this,"reservedIdleGroup"),n(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return l.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return l.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 l.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return l.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return l.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 l.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 l.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 l.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 l.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!a.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 w="SoundManager",I=.5;i.sound.disableAutoPause=!0;class L{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 o(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 l.warn(w,`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=a.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 a=0;a<e.length;a++)i+=r(e[a],2);const s=Math.sqrt(i/e.length),n=20*Math.log10(s||r(10,-5)),o=Math.min(Math.max((n-t.minDecibels)/(t.maxDecibels-t.minDecibels),0),1);return parseFloat(o.toFixed(1))}static dispose(t){t.pause(),g(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=>{l.warn(w,"Failed to close AudioContext.",t)})}for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}n(L,"audios",[]),n(L,"analysers",[]),n(L,"contexts",[]),n(L,"_volume",I);var _=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(_||{});class A extends e.EventEmitter{constructor(t){super(),n(this,"tag"),n(this,"settings"),n(this,"motionGroups",{}),n(this,"state",new b),n(this,"currentAudio"),n(this,"currentAnalyzer"),n(this,"currentContext"),n(this,"playing",!1),n(this,"destroyed",!1),n(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 l.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 o(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 l.warn(this.tag,`Cannot start motion at "${t}"[${e}] because it's already failed in loading.`);if(r[e])return r[e];const n=yield this._loadMotion(t,e);return this.destroyed?void 0:(r[e]=null!=n?n:null,n)})}_loadMotion(t,e){throw new Error("Not implemented.")}initializeAudio(t,e){this.currentAudio=t,L.volume=e,this.currentContext=t.context.audioContext,this.currentAnalyzer=L.addAnalyzer(this.currentAudio,this.currentContext)}speak(t){return o(this,arguments,function*(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:n}={}){if(!a.sound)return!1;let o,h;if(this.currentAudio&&this.currentAudio.isPlaying)return!1;const d=t&&t.startsWith("data:");if(t&&!d){const e=document.createElement("a");e.href=t,h=t=e.href}else h="data:audio/";const u=t;if(u)try{o=yield L.add(u,(t,e=this)=>{l.error(this.tag,"Error during audio playback:",t),null==n||n(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),this.initializeAudio(o,e)}catch(c){return l.warn(this.tag,"Failed to create audio",h,c),!1}if(o){let t=!0;try{a.motionSync&&L.play(o,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(c){l.warn(this.tag,"Failed to play audio",o.url,c),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 o(this,arguments,function*(t,e,i=P.NORMAL,{sound:s,volume:r=.5,expression:n,resetExpression:o=!0,onFinish:h,onError:d,ignoreParamIds:u=[]}={}){if(this.destroyed)return!1;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=P.FORCE)return!1;const c=this.getMotionDefinition(t,e);if(!c)return!1;let p,g;this.currentAudio&&L.dispose(this.currentAudio);const m=s&&s.startsWith("data:");if(s&&!m){const t=document.createElement("a");t.href=s,g=s=t.href}else g=this.getSoundFile(c),g&&(g=this.settings.resolveURL(g));const f=g;if(f)try{p=yield L.add(f,(t,e=this)=>{l.error(this.tag,"Error during audio playback:",t),null==d||d(t),o&&n&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),this.initializeAudio(p,r)}catch(y){l.warn(this.tag,"Failed to create audio",g,y)}const M=yield this.loadMotion(t,e);if(p&&a.motionSync)try{L.play(p,(t=this)=>{null==h||h(),o&&n&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0})}catch(y){l.warn(this.tag,"Failed to play audio",p.url,y)}return this.state.start(M,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),l.log(this.tag,"Start motion:",this.getMotionName(c)),this.emit("motionStart",t,e,p),n&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(n)),this.playing=!0,M&&this._startMotion(M,void 0,u),!0):(p&&(L.dispose(p),this.currentAudio=void 0),!1)})}startRandomMotion(t,e){return o(this,arguments,function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:n=!0,onFinish:o,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:n,onFinish:o,onError:a})}}return!1})}stopSpeaking(){this.currentAudio&&(L.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,P.IDLE)),this.updateParameters(t,e)}mouthSync(){return this.currentAnalyzer?L.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 o(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(t,e,P.FORCE))return null;const s=this.getMotionDefinition(t,e);if(!s)return null;this.currentAudio&&L.dispose(this.currentAudio);const r=yield this.loadMotion(t,e);return this.state.start(r,t,e,P.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),l.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||l.warn(this.tag,`Undefined motion at "${t}"[${e}]`),r}}function F(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,n="string"==typeof t.name?t.name:"string"==typeof t.Name?t.Name:void 0;r&&n&&i.push({id:r,name:n,index:e(r)})}return i}const O={x:0,y:0,width:0,height:0};class R extends e.EventEmitter{constructor(){super(...arguments),n(this,"focusController",new v),n(this,"pose"),n(this,"physics"),n(this,"originalWidth",0),n(this,"originalHeight",0),n(this,"width",0),n(this,"height",0),n(this,"localTransform",new e.Matrix),n(this,"drawingMatrix",new e.Matrix),n(this,"hitAreas",{}),n(this,"textureFlipY",!1),n(this,"viewport",[0,0,0,0]),n(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 n=this.getDrawableBounds(r,O);return n.x<=e&&e<=n.x+n.width&&n.y<=i&&i<=n.y+n.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],n=i[1],o=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),n=Math.min(e,n),o=Math.max(e,o)}return null!=e||(e={}),e.x=s,e.y=n,e.width=r-s,e.height=o-n,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 T extends Error{constructor(t,e,i,s=!1){super(t),this.url=e,this.status=i,this.aborted=s}}const D=class t{static createXHR(e,i,s,r,n){const o=new XMLHttpRequest;if(t.allXhrSet.add(o),e){let i=t.xhrMap.get(e);i?i.add(o):(i=new Set([o]),t.xhrMap.set(e,i))}return o.open("GET",i),o.responseType=s,o.onload=()=>{var t;200!==o.status&&0!==o.status||!o.response?null==(t=o.onerror)||t.call(o,new ProgressEvent("error")):r(o.response)},o.onerror=()=>{l.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${i}`),n(new T("Network error.",i,o.status))},o.onabort=()=>n(new T("Aborted.",i,o.status,!0)),o.onloadend=()=>{var i;t.allXhrSet.delete(o),e&&(null==(i=t.xhrMap.get(e))||i.delete(o))},o}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}};n(D,"xhrMap",new WeakMap),n(D,"allXhrSet",new Set),n(D,"loader",t=>new Promise((e,i)=>{const s=t.target,r=t.target&&"function"==typeof D.cancelXHRs?D.cancelXHRs.bind(t.target):void 0,n=D.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)}n.send()}));let S=D;function C(t,e){let i=-1;return function s(r,n){if(n)return Promise.reject(n);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const o=t[r];if(!o)return Promise.resolve();try{return Promise.resolve(o(e,s.bind(null,r+1)))}catch(a){const t=a instanceof Error?a:new Error(String(a));return Promise.reject(t)}}(0)}class k{static load(t){return o(this,null,function*(){return yield C(this.middlewares,t),t.result})}}n(k,"middlewares",[S.loader]);class N extends E{constructor(t){if(super(t),n(this,"moc"),n(this,"textures"),n(this,"layout"),n(this,"hitAreas"),n(this,"initParams"),n(this,"initOpacities"),n(this,"expressions"),n(this,"motions",{}),!N.isValidJSON(t))throw new TypeError("Invalid JSON.");this.moc=t.model,c("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){u("string",t,this,"name","name"),u("string",t,this,"pose","pose"),u("string",t,this,"physics","physics"),u("object",t,this,"layout","layout"),u("object",t,this,"motions","motions"),c("object",t,this,"hit_areas","hitAreas"),c("object",t,this,"expressions","expressions"),c("object",t,this,"init_params","initParams"),c("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 G(){}const j="Live2DFactory",U=(t,e)=>o(null,null,function*(){if("string"==typeof t.source){const e=yield k.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()}),H=(t,e)=>o(null,null,function*(){if(t.source instanceof E)return t.settings=t.source,e();if("object"==typeof t.source){const i=Z.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=Z.runtimes.map(t=>t.version).join(", ");if(0===Z.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"))}),X=(t,e)=>{if(t.settings){const i=Z.findRuntime(t.settings);if(i)return i.ready().then(()=>e())}return e()},B=(t,e)=>o(null,null,function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=Z.findRuntime(e);if(s){const r=[],n=e instanceof N?"json":"arraybuffer";e.pose&&r.push(k.load({settings:e,url:e.pose,type:n,target:i}).then(e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)}).catch(e=>{t.live2dModel.emit("poseLoadError",e),l.warn(j,"Failed to load pose.",e)})),e.physics&&r.push(k.load({settings:e,url:e.physics,type:n,target:i}).then(e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)}).catch(e=>{t.live2dModel.emit("physicsLoadError",e),l.warn(j,"Failed to load physics.",e)})),r.length&&(yield Promise.all(r))}}}),W=(t,i)=>o(null,null,function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r={crossOrigin:t.options.crossOrigin};t.settings instanceof N&&(r.preferCreateImageBitmap=!1);const n=Promise.all(t.settings.textures.map(i=>function(t,i={}){const s=e.loadTextures.config,r=null==s?void 0:s.crossOrigin,n=null==s?void 0:s.preferCreateImageBitmap,o=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(t).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!=n?n:s.preferCreateImageBitmap,s.preferWorkers=null!=o?o:s.preferWorkers))})}(t.settings.resolveURL(i),r)));if(n.catch(G),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield n,s.emit("textureLoaded",s.textures)}}),$=(t,e)=>o(null,null,function*(){const i=t.settings;if(i instanceof E){const s=Z.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield k.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const n=s.createCoreModel(r);return t.internalModel=s.createInternalModel(n,i,t.options),e()}throw new TypeError("Missing settings.")}),z=class t{static unzip(e,i){return o(this,null,function*(){const s=yield t.getFilePaths(e),r=[];for(const t of i.getDefinedFiles()){const e=decodeURI(f(i.url,t));s.includes(e)&&r.push(e)}const n=yield t.getFiles(e,r);for(let t=0;t<n.length;t++){const e=r[t],i=n[t];Object.defineProperty(i,"webkitRelativePath",{value:e})}return n})}static createSettings(e){return o(this,null,function*(){const i=(yield t.getFilePaths(e)).find(t=>t.endsWith("model.json")||t.endsWith("model3.json"));if(!i)throw new Error("Settings file not found");const s=yield t.readText(e,i);if(!s)throw new Error("Empty settings file: "+i);const r=JSON.parse(s);r.url=i;const n=t.live2dFactory.findRuntime(r);if(!n)throw new Error("Unknown settings JSON");return n.createModelSettings(r)})}static zipReader(t,e){return Promise.reject(new Error("Not implemented"))}static getFilePaths(t){return Promise.reject(new Error("Not implemented"))}static getFiles(t,e){return Promise.reject(new Error("Not implemented"))}static readText(t,e){return Promise.reject(new Error("Not implemented"))}static releaseReader(t){}};n(z,"live2dFactory"),n(z,"ZIP_PROTOCOL","zip://"),n(z,"uid",0),n(z,"factory",(t,e)=>o(null,null,function*(){const i=t.source;let s,r,n;if("string"==typeof i&&(i.endsWith(".zip")||i.startsWith(z.ZIP_PROTOCOL))?(s=i.startsWith(z.ZIP_PROTOCOL)?i.slice(z.ZIP_PROTOCOL.length):i,r=yield k.load({url:s,type:"blob",target:t.live2dModel})):Array.isArray(i)&&1===i.length&&i[0]instanceof File&&i[0].name.endsWith(".zip")&&(r=i[0],s=URL.createObjectURL(r),n=i.settings),r){if(!r.size)throw new Error("Empty zip file");const e=yield z.zipReader(r,s);n||(n=yield z.createSettings(e)),n._objectURL=z.ZIP_PROTOCOL+z.uid+"/"+n.url;const i=yield z.unzip(e,n);i.settings=n,t.source=i,s.startsWith("blob:")&&t.live2dModel.once("modelLoaded",t=>{t.once("destroy",function(){URL.revokeObjectURL(s)})}),z.releaseReader(e)}return e()}));let q=z;const V=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(f(i.url,t)),n=e.find(t=>t.webkitRelativePath===r);n&&(s[t]=URL.createObjectURL(n))}t.filesMap[i._objectURL]=s}static createSettings(e){return o(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 n=Z.findRuntime(r);if(!n)throw new Error("Unknown settings JSON");const o=n.createModelSettings(r);return o._objectURL=URL.createObjectURL(i),o})}static readText(t){return o(this,null,function*(){return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")})})}};n(V,"live2dFactory"),n(V,"filesMap",{}),n(V,"factory",(t,e)=>o(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 V.createSettings(e);i.validateFiles(e.map(t=>encodeURI(t.webkitRelativePath))),V.upload(e,i),i.resolveURL=function(t){return V.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),V.filesMap[t])for(const e of Object.values(V.filesMap[t]))URL.revokeObjectURL(e);delete V.filesMap[t]})})}return e()}));let Y=V;const J=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 o(this,null,function*(){const r=new Promise(t=>e.once("textureLoaded",t)),n=new Promise(t=>e.once("modelLoaded",t)),o=Promise.all([r,n]).then(()=>e.emit("ready"));yield C(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield o,e.emit("load")})}static loadMotion(e,i,s){var r;const n=t=>e.emit("motionLoadError",i,s,t);try{const o=null==(r=e.definitions[i])?void 0:r[s];if(!o)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 h=a[i];h||(h=[],a[i]=h);const d=e.getMotionFile(o);return null!=h[s]||(h[s]=k.load({url:d,settings:e.settings,type:e.motionDataType,target:e}).then(r=>{var n;const a=null==(n=t.motionTasksMap.get(e))?void 0:n[i];a&&(a[s]=void 0);const l=r,h=e.createMotion(l,i,o);return e.emit("motionLoaded",i,s,h),h}).catch(t=>{l.warn(e.tag,`Failed to load motion: ${d}\n`,t),n(t)})),h[s]}catch(o){l.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,o),n(o)}return Promise.resolve(void 0)}static loadExpression(e,i){var s;const r=t=>e.emit("expressionLoadError",i,t);try{const n=e.definitions[i];if(!n)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseExpressionTasks(e));let o=t.expressionTasksMap.get(e);o||(o=[],t.expressionTasksMap.set(e,o));const a=e.getExpressionFile(n),h=null!=(s=e.expressionDataType)?s:"json";return null!=o[i]||(o[i]=k.load({url:a,settings:e.settings,type:h,target:e}).then(s=>{const r=t.expressionTasksMap.get(e);r&&(r[i]=void 0);const o=s,a=e.createExpression(o,n);return e.emit("expressionLoaded",i,a),a}).catch(t=>{l.warn(e.tag,`Failed to load expression: ${a}\n`,t),r(t)})),o[i]}catch(n){l.warn(e.tag,`Failed to load expression at [${i}]\n`,n),r(n)}return Promise.resolve(void 0)}static releaseMotionTasks(e){t.motionTasksMap.delete(e)}static releaseExpressionTasks(e){t.expressionTasksMap.delete(e)}};n(J,"runtimes",[]),n(J,"urlToJSON",U),n(J,"jsonToSettings",H),n(J,"waitUntilReady",X),n(J,"setupOptionals",B),n(J,"setupEssentials",W),n(J,"createInternalModel",$),n(J,"live2DModelMiddlewares",[q.factory,Y.factory,U,H,X,B,W,$]),n(J,"motionTasksMap",new WeakMap),n(J,"expressionTasksMap",new WeakMap);let Z=J;A.prototype._loadMotion=function(t,e){return Z.loadMotion(this,t,e)},M.prototype._loadExpression=function(t){return Z.loadExpression(this,t)},Y.live2dFactory=Z,q.live2dFactory=Z;const Q=class t{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:o=!0,autoInteract:a,ticker:h}={}){var d;n(this,"model"),n(this,"destroyed",!1),n(this,"_ticker"),n(this,"_autoUpdate",!1),n(this,"_autoHitTest",!1),n(this,"_autoFocus",!1),null!=h||(h=null!=(d=t.defaultTicker)?d:"undefined"!=typeof PIXI?PIXI.Ticker.shared:e.Ticker.shared),void 0!==a&&(r=a,o=a,l.warn(i.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=i,this.ticker=h,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(tt,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(tt,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(tt,this),this._autoUpdate=!0):l.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(tt,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",et,this):this.model.off("pointertap",et,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?(this.model.on("globalpointermove",it,this),this.model.on("pointermove",it,this)):(this.model.off("globalpointermove",it,this),this.model.off("pointermove",it,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}};n(Q,"defaultTicker");let K=Q;function tt(){this.onTickerUpdate()}function et(t){this.onTap(t)}function it(t){this.onPointerMove(t)}class st extends e.Transform{}const rt=new e.Point,nt=new e.Matrix,ot=new e.Matrix,at={x:0,y:0,width:0,height:0},lt=new e.Bounds;class ht{constructor(t){this.renderer=t}execute(t){!t.visible||t.alpha<=0||t.renderLive2D(this.renderer)}updateRenderable(){}destroy(){}}class dt extends e.Container{constructor(t){super(),n(this,"renderPipeId","live2d"),n(this,"tag","Live2DModel(uninitialized)"),n(this,"internalModel"),n(this,"textures",[]),n(this,"transform",new st),n(this,"anchor"),n(this,"_bounds",new e.Bounds),n(this,"_boundsDirty",!0),n(this,"_boundsRetryAfterDraw",!1),n(this,"gl",null),n(this,"elapsedTime",0),n(this,"deltaTime",0),n(this,"automator"),n(this,"currentGlId",0),n(this,"renderLive2D",t=>{var i,s,r,n,o;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);for(let e=0;e<this.textures.length;e++){const i=this.textures[e],s=Boolean(i.source._gpuData[t.uid]);!a&&s||(t.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,this.internalModel.textureFlipY),t.texture.bind(i,0)),this.internalModel.bindTexture(e,t.texture.getGlSource(i.source).texture)}const l=t.renderTarget.viewport,h=t.renderTarget.renderTarget;let d=l.y;if(null==h?void 0:h.isRoot){d=h.colorTexture.source.pixelHeight-l.height-l.y}this.internalModel.viewport=[l.x,d,l.width,l.height];const u=this.deltaTime;this.deltaTime=0,u&&this.internalModel.update(u,this.elapsedTime);const{projectionMatrix:c,offset:p}=t.globalUniforms.globalUniformData,g=ot.copyFrom(this.worldTransform);g.tx-=null!=(i=null==p?void 0:p.x)?i:0,g.ty-=null!=(s=null==p?void 0:p.y)?s:0;const m=nt.copyFrom(c).append(g);this.internalModel.updateTransform(m),this.internalModel.draw(t.gl),this._boundsRetryAfterDraw&&this.updateDrawableBounds(),t.state.resetState(),t.texture.resetState();const f=null==(r=t.renderTarget)?void 0:r.defaultClearColor,M=null==(o=null==(n=t.renderTarget)?void 0:n.adaptor)?void 0:o._clearColorCache;f&&(t.gl.clearColor(f[0],f[1],f[2],f[3]),M&&(M[0]=f[0],M[1]=f[1],M[2]=f[2],M[3]=f[3]))}),this.anchor=new e.ObservablePoint({_onUpdate:()=>this.onAnchorChange()},0,0),this.automator=new K(this,t),this.once("modelLoaded",()=>this.initializeOnModelLoad(t))}get isRenderable(){return!0}get canBundle(){return!1}static from(t,e){return o(this,null,function*(){const i=new this(e);return yield Z.setupLive2DModel(i,t,e),i})}static fromSync(t,e){const i=new this(e);return Z.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){K.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();lt.clear();for(let i=0;i<t.length;i++){const s=t[i],r=this.internalModel.getDrawableIndex(s);if(r<0)continue;const n=this.internalModel.getDrawableBounds(r,at);Number.isFinite(n.x)&&Number.isFinite(n.y)&&Number.isFinite(n.width)&&Number.isFinite(n.height)&&lt.addFrame(n.x,n.y,n.x+n.width,n.y+n.height,e.Matrix.IDENTITY)}if(this._bounds.clear(),lt.isValid&&lt.isPositive)this._bounds.addFrame(lt.minX,lt.minY,lt.maxX,lt.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,n,o;if(this.parentRenderLayer&&this.parentRenderLayer!==i)return;if(this.globalDisplayStatus<7)return;if(!this.includeInBuild)return;this.sortableChildren&&this.sortChildren(),function(t){const e=t;e.renderPipes.live2d||(e.renderPipes.live2d=new ht(t))}(e);const a=e.renderPipes,l=()=>{var e,i;null==(i=null==(e=a.batch)?void 0:e.break)||i.call(e,t),t.add(this)},h=()=>{const s=this.children,r=s.length;for(let n=0;n<r;n++)s[n].collectRenderables(t,e,i)},d=this.effects;if(d){for(let e=0;e<d.length;e++){const i=d[e],n=i.filters;if(n)for(const t of n)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==(o=null==(n=a[i.pipe])?void 0:n.pop)||o.call(n,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 o(this,arguments,function*(t,e,i,{sound:s,volume:r=.5,expression:n,resetExpression:o=!0,onFinish:a,onError:l}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l})})}motionLastFrame(t,e){return o(this,arguments,function*(t,e,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(t,e,{expression:i})})}parallelMotion(t){return o(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 o(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:n}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,onFinish:r,onError:n})}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){rt.x=t,rt.y=e,this.toModelPosition(rt,rt,!0);const s=rt.x/this.internalModel.originalWidth*2-1,r=rt.y/this.internalModel.originalHeight*2-1,n=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(n),-Math.sin(n),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&this.emit("hit",i)}hitTest(t,e){return rt.x=t,rt.y=e,this.toModelPosition(rt,rt),this.internalModel.hitTest(rt.x,rt.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}destroy(t){this.emit("destroy"),(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 ut=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){ut.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class ct extends AMotion{constructor(t){super(),n(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:a.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:a.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 M{constructor(t,e){var i;super(t,e),n(this,"queueManager",new MotionQueueManager),n(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 ct(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}function gt(t,e,i){const s=i.getDurationMSec(),r=t.startMotion(i,!0),n=t.motions.find(t=>!!t&&t._$sr===r);return!!n&&(i.updateParamExe(e.coreModel,s,1,n),!0)}class mt extends A{constructor(t){super(t),n(this,"definitions"),n(this,"groups",{idle:"idle"}),n(this,"motionDataType","arraybuffer"),n(this,"queueManager",new MotionQueueManager),n(this,"lipSyncIds"),n(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?a.idleMotionFadingDuration:a.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 o(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,gt(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class ft extends e.EventEmitter{constructor(t){super(),n(this,"tag"),n(this,"manager"),n(this,"settings"),n(this,"state",new b),n(this,"playing",!1),n(this,"destroyed",!1),n(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 o(this,arguments,function*(t,e,i=P.NORMAL,s=[]){var r;if(!this.state.reserve(t,e,i))return!1;const n=null==(r=this.manager.definitions[t])?void 0:r[e];if(!n)return!1;const o=yield this.manager.loadMotion(t,e);return!!this.state.start(o,t,e,i)&&(l.log(this.tag,"Start motion:",this.getMotionName(n)),this.emit("motionStart",t,e,void 0),this.playing=!0,this._startMotion(o,void 0,s),!0)})}startRandomMotion(t,e){return o(this,null,function*(){var i;const s=this.manager.definitions[t];if(null==s?void 0:s.length){const r=[],n=null!=(i=this.manager.motionGroups[t])?i:[];for(let e=0;e<s.length;e++)null===n[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 Mt extends ft{constructor(t){super(t),n(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 o(this,null,function*(){var i;if(!this.state.reserve(t,e,P.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,P.FORCE)&&(l.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",t,e,void 0),this.playing=!0,!!gt(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class yt{constructor(t){n(this,"leftParam"),n(this,"rightParam"),n(this,"blinkInterval",4e3),n(this,"closingDuration",100),n(this,"closedDuration",50),n(this,"openingDuration",150),n(this,"eyeState",0),n(this,"eyeParamValue",1),n(this,"closedTimer",0),n(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=h(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+d(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 xt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class vt extends R{constructor(t,e,i){super(),n(this,"settings"),n(this,"options"),n(this,"coreModel"),n(this,"motionManager"),n(this,"parallelMotionManager"),n(this,"eyeBlink"),n(this,"eyeballXParamIndex"),n(this,"eyeballYParamIndex"),n(this,"angleXParamIndex"),n(this,"angleYParamIndex"),n(this,"angleZParamIndex"),n(this,"bodyAngleXParamIndex"),n(this,"breathParamIndex"),n(this,"textureFlipY",!0),n(this,"lipSync",!0),n(this,"drawDataCount",0),n(this,"disableCulling",!1),n(this,"hasDrawn",!1),n(this,"customHitAreas"),this.coreModel=t,this.settings=e,this.options=Object.assign({},{breathDepth:1,lipSyncGain:1.5,lipSyncWeight:.4},i),this.motionManager=new mt(this),this.parallelMotionManager=[],this.eyeBlink=new yt(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 F(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||l.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,n;super.update(t,e);const o=this.coreModel,a=this.updateMotions(o,e);if(o.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(o,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=h(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==(n=this.pose)||n.update(t),this.emit("beforeModelUpdate"),o.update(),o.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;xt[0]=i.a,xt[1]=i.b,xt[4]=i.c,xt[5]=i.d,xt[12]=i.tx,xt[13]=i.ty,this.coreModel.setMatrix(xt),this.coreModel.draw(),this.hasDrawn=!0,this.disableCulling=e}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new Mt(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 n=t/s*2-1,o=1-e/r*2,a=[];for(const[l,h]of Object.entries(i))n>=h.minX&&n<=h.maxX&&o>=h.minY&&o<=h.maxY&&a.push(l);return a}getCustomHitAreas(){var t,e,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const n=this.settings.json,o=null!=(i=null!=(e=null!=(t=n.hit_areas_custom)?t:n.hitAreasCustom)?e:n.HitAreasCustom)?i:n.HitAreas_Custom;if(!o||"object"!=typeof o)return this.customHitAreas=null,null;const a=o,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]),n=Number(i[0]),o=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(n)&&Number.isFinite(o)&&(l[t]={minX:Math.min(s,r),maxX:Math.max(s,r),minY:Math.min(n,o),maxY:Math.max(n,o)})};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 Et={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},Pt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class bt{constructor(t,e){n(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 n=Et[i];n&&e.addSrcParam(n,t,s,r)}),t.targets.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const n=Pt[i];n&&e.addTargetParam(n,t,s,r)}),e}))}update(t){this.physicsHairs.forEach(e=>e.update(this.coreModel,t))}}class wt{constructor(t){n(this,"paramIndex",-1),n(this,"partsIndex",-1),n(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 It{constructor(t,e){n(this,"opacityAnimDuration",500),n(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 wt(t);return e&&(i.link=e.map(t=>new wt(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,n=t.findIndex(({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t));if(n>=0){const s=i.getPartsOpacity(t[n].partsIndex);r=h(s+e/this.opacityAnimDuration,0,1)}else n=0,r=1;t.forEach(({partsIndex:t},e)=>{if(t>=0)if(n==e)i.setPartsOpacity(t,r);else{let e,n=i.getPartsOpacity(t);e=r<s?-.5*r/s+1:(1-r)*s/.5;(1-e)*(1-r)>.15&&(e=1-.15/(1-r)),n>e&&(n=e),i.setPartsOpacity(t,n)}})}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)})}}Z.registerRuntime({version:2,test:t=>t instanceof N||N.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 N(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 vt(t,e,i),createPose:(t,e)=>new It(t,e),createPhysics:(t,e)=>new bt(t,e)}),t.CubismLegacyExpressionManager=pt,t.CubismLegacyInternalModel=vt,t.CubismLegacyModelSettings=N,t.CubismLegacyMotionManager=mt,t.CubismLegacyParallelMotionManager=Mt,t.ExpressionManager=M,t.FileLoader=Y,t.FocusController=v,t.InternalModel=R,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=ct,t.Live2DEyeBlink=yt,t.Live2DFactory=Z,t.Live2DLoader=k,t.Live2DModel=dt,t.Live2DPhysics=bt,t.Live2DPose=It,t.Live2DTransform=st,t.MBToByte=function(t){return 1024*t*1024},t.ModelSettings=E,t.MotionManager=A,t.MotionPreloadStrategy=_,t.MotionPriority=P,t.MotionState=b,t.SoundManager=L,t.VERSION="1.0.2",t.VOLUME=I,t.XHRLoader=S,t.ZipLoader=q,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=h,t.config=a,t.copyArray=c,t.copyProperty=u,t.folderName=p,t.logger=l,t.normalizeHitAreaDefs=F,t.rand=d,t.remove=g,t.resolveURL=f,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.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"})});