live2d-widgets
Version:
Live2D widget for web pages
7 lines (6 loc) • 32.8 kB
JavaScript
/*!
* Live2D Widget
* https://github.com/stevenjoezhang/live2d-widget
*/
import{l as t}from"../waifu-tips.js";class e{constructor(){this.live2DModel=null,this.modelMatrix=null,this.eyeBlink=null,this.physics=null,this.pose=null,this.initialized=!1,this.updating=!1,this.alpha=1,this.accAlpha=0,this.lipSync=!1,this.lipSyncValue=0,this.accelX=0,this.accelY=0,this.accelZ=0,this.dragX=0,this.dragY=0,this.startTimeMSec=null,this.mainMotionManager=new l,this.expressionManager=new l,this.motions={},this.expressions={},this.isTexLoaded=!1}getModelMatrix(){return this.modelMatrix}setAlpha(t){t>.999&&(t=1),t<.001&&(t=0),this.alpha=t}getAlpha(){return this.alpha}isInitialized(){return this.initialized}setInitialized(t){this.initialized=t}isUpdating(){return this.updating}setUpdating(t){this.updating=t}getLive2DModel(){return this.live2DModel}setLipSync(t){this.lipSync=t}setLipSyncValue(t){this.lipSyncValue=t}setAccel(t,e,i){this.accelX=t,this.accelY=e,this.accelZ=i}setDrag(t,e){this.dragX=t,this.dragY=e}getMainMotionManager(){return this.mainMotionManager}getExpressionManager(){return this.expressionManager}loadModelData(e,i){const s=M.getPlatformManager();t.info("Load model : "+e),s.loadLive2DModel(e,(e=>{this.live2DModel=e,this.live2DModel.saveParam();0==Live2D.getError()?(this.modelMatrix=new h(this.live2DModel.getCanvasWidth(),this.live2DModel.getCanvasHeight()),this.modelMatrix.setWidth(2),this.modelMatrix.setCenterPosition(0,0),i(this.live2DModel)):t.error("Error : Failed to loadModelData().")}))}loadTexture(e,s,n){i++;const a=M.getPlatformManager();t.info("Load Texture : "+s),a.loadTexture(this.live2DModel,e,s,(()=>{i--,0==i&&(this.isTexLoaded=!0),"function"==typeof n&&n()}))}loadMotion(e,i,s){const n=M.getPlatformManager();t.trace("Load Motion : "+i);let a=null;n.loadBytes(i,(t=>{a=Live2DMotion.loadMotion(t),null!=e&&(this.motions[e]=a),s(a)}))}loadExpression(e,i,n){const a=M.getPlatformManager();t.trace("Load Expression : "+i),a.loadBytes(i,(t=>{null!=e&&(this.expressions[e]=s.loadJson(t)),"function"==typeof n&&n()}))}loadPose(e,i){const s=M.getPlatformManager();t.trace("Load Pose : "+e);try{s.loadBytes(e,(t=>{this.pose=d.load(t),"function"==typeof i&&i()}))}catch(e){t.warn(e)}}loadPhysics(e){const i=M.getPlatformManager();t.trace("Load Physics : "+e);try{i.loadBytes(e,(t=>{this.physics=c.load(t)}))}catch(e){t.warn(e)}}hitTestSimple(t,e,i){const s=this.live2DModel.getDrawDataIndex(t);if(s<0)return!1;const n=this.live2DModel.getTransformedPoints(s);let a=this.live2DModel.getCanvasWidth(),r=0,o=this.live2DModel.getCanvasHeight(),h=0;for(let t=0;t<n.length;t+=2){const e=n[t],i=n[t+1];e<a&&(a=e),e>r&&(r=e),i<o&&(o=i),i>h&&(h=i)}const l=this.modelMatrix.invertTransformX(e),c=this.modelMatrix.invertTransformY(i);return a<=l&&l<=r&&o<=c&&c<=h}}let i=0;class s extends AMotion{constructor(){super(),this.paramList=[]}static loadJson(t){const e=new s,i=M.getPlatformManager().jsonParseFromBytes(t);if(e.setFadeIn(parseInt(i.fade_in)>0?parseInt(i.fade_in):1e3),e.setFadeOut(parseInt(i.fade_out)>0?parseInt(i.fade_out):1e3),null==i.params)return e;const a=i.params,r=a.length;e.paramList=[];for(let t=0;t<r;t++){const i=a[t],r=i.id.toString();let o=parseFloat(i.val),h=s.TYPE_ADD;const l=null!=i.calc?i.calc.toString():"add";if(h="add"===l?s.TYPE_ADD:"mult"===l?s.TYPE_MULT:"set"===l?s.TYPE_SET:s.TYPE_ADD,h==s.TYPE_ADD){o-=null==i.def?0:parseFloat(i.def)}else if(h==s.TYPE_MULT){let t=null==i.def?1:parseFloat(i.def);0==t&&(t=1),o/=t}const c=new n;c.id=r,c.type=h,c.value=o,e.paramList.push(c)}return e}updateParamExe(t,e,i,n){for(let e=this.paramList.length-1;e>=0;--e){const n=this.paramList[e];n.type==s.TYPE_ADD?t.addToParamFloat(n.id,n.value,i):n.type==s.TYPE_MULT?t.multParamFloat(n.id,n.value,i):n.type==s.TYPE_SET&&t.setParamFloat(n.id,n.value,i)}}}function n(){this.id="",this.type=-1,this.value=null}s.EXPRESSION_DEFAULT="DEFAULT",s.TYPE_SET=0,s.TYPE_ADD=1,s.TYPE_MULT=2;class a{constructor(){this.nextBlinkTime=null,this.stateStartTime=null,this.blinkIntervalMsec=null,this.eyeState=r.STATE_FIRST,this.blinkIntervalMsec=4e3,this.closingMotionMsec=100,this.closedMotionMsec=50,this.openingMotionMsec=150,this.closeIfZero=!0,this.eyeID_L="PARAM_EYE_L_OPEN",this.eyeID_R="PARAM_EYE_R_OPEN"}calcNextBlink(){return UtSystem.getUserTimeMSec()+Math.random()*(2*this.blinkIntervalMsec-1)}setInterval(t){this.blinkIntervalMsec=t}setEyeMotion(t,e,i){this.closingMotionMsec=t,this.closedMotionMsec=e,this.openingMotionMsec=i}updateParam(t){const e=UtSystem.getUserTimeMSec();let i,s=0;switch(this.eyeState){case r.STATE_CLOSING:s=(e-this.stateStartTime)/this.closingMotionMsec,s>=1&&(s=1,this.eyeState=r.STATE_CLOSED,this.stateStartTime=e),i=1-s;break;case r.STATE_CLOSED:s=(e-this.stateStartTime)/this.closedMotionMsec,s>=1&&(this.eyeState=r.STATE_OPENING,this.stateStartTime=e),i=0;break;case r.STATE_OPENING:s=(e-this.stateStartTime)/this.openingMotionMsec,s>=1&&(s=1,this.eyeState=r.STATE_INTERVAL,this.nextBlinkTime=this.calcNextBlink()),i=s;break;case r.STATE_INTERVAL:this.nextBlinkTime<e&&(this.eyeState=r.STATE_CLOSING,this.stateStartTime=e),i=1;break;case r.STATE_FIRST:default:this.eyeState=r.STATE_INTERVAL,this.nextBlinkTime=this.calcNextBlink(),i=1}this.closeIfZero||(i=-i),t.setParamFloat(this.eyeID_L,i),t.setParamFloat(this.eyeID_R,i)}}const r=()=>{};r.STATE_FIRST="STATE_FIRST",r.STATE_INTERVAL="STATE_INTERVAL",r.STATE_CLOSING="STATE_CLOSING",r.STATE_CLOSED="STATE_CLOSED",r.STATE_OPENING="STATE_OPENING";class o{constructor(){this.tr=new Float32Array(16),this.identity()}static mul(t,e,i){const s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];let n,a,r;for(n=0;n<4;n++)for(a=0;a<4;a++)for(r=0;r<4;r++)s[n+4*a]+=t[n+4*r]*e[r+4*a];for(n=0;n<16;n++)i[n]=s[n]}identity(){for(let t=0;t<16;t++)this.tr[t]=t%5==0?1:0}getArray(){return this.tr}getCopyMatrix(){return new Float32Array(this.tr)}setMatrix(t){if(null!=this.tr&&this.tr.length==this.tr.length)for(let e=0;e<16;e++)this.tr[e]=t[e]}getScaleX(){return this.tr[0]}getScaleY(){return this.tr[5]}transformX(t){return this.tr[0]*t+this.tr[12]}transformY(t){return this.tr[5]*t+this.tr[13]}invertTransformX(t){return(t-this.tr[12])/this.tr[0]}invertTransformY(t){return(t-this.tr[13])/this.tr[5]}multTranslate(t,e){const i=[1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1];o.mul(i,this.tr,this.tr)}translate(t,e){this.tr[12]=t,this.tr[13]=e}translateX(t){this.tr[12]=t}translateY(t){this.tr[13]=t}multScale(t,e){const i=[t,0,0,0,0,e,0,0,0,0,1,0,0,0,0,1];o.mul(i,this.tr,this.tr)}scale(t,e){this.tr[0]=t,this.tr[5]=e}}class h extends o{constructor(t,e){super(),this.width=t,this.height=e}setPosition(t,e){this.translate(t,e)}setCenterPosition(t,e){const i=this.width*this.getScaleX(),s=this.height*this.getScaleY();this.translate(t-i/2,e-s/2)}top(t){this.setY(t)}bottom(t){const e=this.height*this.getScaleY();this.translateY(t-e)}left(t){this.setX(t)}right(t){const e=this.width*this.getScaleX();this.translateX(t-e)}centerX(t){const e=this.width*this.getScaleX();this.translateX(t-e/2)}centerY(t){const e=this.height*this.getScaleY();this.translateY(t-e/2)}setX(t){this.translateX(t)}setY(t){this.translateY(t)}setHeight(t){const e=t/this.height,i=-e;this.scale(e,i)}setWidth(t){const e=t/this.width,i=-e;this.scale(e,i)}}class l extends MotionQueueManager{constructor(){super(),this.currentPriority=null,this.reservePriority=null,this.super=MotionQueueManager.prototype}getCurrentPriority(){return this.currentPriority}getReservePriority(){return this.reservePriority}reserveMotion(t){return!(this.reservePriority>=t)&&(!(this.currentPriority>=t)&&(this.reservePriority=t,!0))}setReservePriority(t){this.reservePriority=t}updateParam(t){const e=MotionQueueManager.prototype.updateParam.call(this,t);return this.isFinished()&&(this.currentPriority=0),e}startMotionPrio(t,e){return e==this.reservePriority&&(this.reservePriority=0),this.currentPriority=e,this.startMotion(t,!1)}}class c{constructor(){this.physicsList=[],this.startTimeMSec=UtSystem.getUserTimeMSec()}static load(t){const e=new c,i=M.getPlatformManager().jsonParseFromBytes(t).physics_hair,s=i.length;for(let t=0;t<s;t++){const s=i[t],n=new PhysicsHair,a=s.setup,r=parseFloat(a.length),o=parseFloat(a.regist),h=parseFloat(a.mass);n.setup(r,o,h);const l=s.src,c=l.length;for(let t=0;t<c;t++){const e=l[t];let i=e.id,s=PhysicsHair.Src.SRC_TO_X,a=e.ptype;"x"===a?s=PhysicsHair.Src.SRC_TO_X:"y"===a?s=PhysicsHair.Src.SRC_TO_Y:"angle"===a?s=PhysicsHair.Src.SRC_TO_G_ANGLE:UtDebug.error("live2d","Invalid parameter:PhysicsHair.Src");let r=parseFloat(e.scale),o=parseFloat(e.weight);n.addSrcParam(s,i,r,o)}const d=s.targets,u=d.length;for(let t=0;t<u;t++){const e=d[t];let i=e.id,s=PhysicsHair.Target.TARGET_FROM_ANGLE,a=e.ptype;"angle"===a?s=PhysicsHair.Target.TARGET_FROM_ANGLE:"angle_v"===a?s=PhysicsHair.Target.TARGET_FROM_ANGLE_V:UtDebug.error("live2d","Invalid parameter:PhysicsHair.Target");let r=parseFloat(e.scale),o=parseFloat(e.weight);n.addTargetParam(s,i,r,o)}e.physicsList.push(n)}return e}updateParam(t){const e=UtSystem.getUserTimeMSec()-this.startTimeMSec;for(let i=0;i<this.physicsList.length;i++)this.physicsList[i].update(t,e)}}class d{constructor(){this.lastTime=0,this.lastModel=null,this.partsGroups=[]}static load(t){const e=new d,i=M.getPlatformManager().jsonParseFromBytes(t).parts_visible,s=i.length;for(let t=0;t<s;t++){const s=i[t].group,n=s.length,a=[];for(let t=0;t<n;t++){const e=s[t],i=new u(e.id);if(a[t]=i,null==e.link)continue;const n=e.link,r=n.length;i.link=[];for(let t=0;t<r;t++){const e=new u(n[t]);i.link.push(e)}}e.partsGroups.push(a)}return e}updateParam(t){if(null==t)return;t!=this.lastModel&&this.initParam(t),this.lastModel=t;const e=UtSystem.getUserTimeMSec();let i=0==this.lastTime?0:(e-this.lastTime)/1e3;this.lastTime=e,i<0&&(i=0);for(let e=0;e<this.partsGroups.length;e++)this.normalizePartsOpacityGroup(t,this.partsGroups[e],i),this.copyOpacityOtherParts(t,this.partsGroups[e])}initParam(t){if(null!=t)for(let e=0;e<this.partsGroups.length;e++){const i=this.partsGroups[e];for(let e=0;e<i.length;e++){i[e].initIndex(t);const s=i[e].partsIndex,n=i[e].paramIndex;if(s<0)continue;const a=0!=t.getParamFloat(n);if(t.setPartsOpacity(s,a?1:0),t.setParamFloat(n,a?1:0),null!=i[e].link)for(let s=0;s<i[e].link.length;s++)i[e].link[s].initIndex(t)}}}normalizePartsOpacityGroup(t,e,i){let s=-1,n=1;const a=.5;for(let a=0;a<e.length;a++){let r=e[a].partsIndex;const o=e[a].paramIndex;if(!(r<0)&&0!=t.getParamFloat(o)){if(s>=0)break;s=a,n=t.getPartsOpacity(r),n+=i/.5,n>1&&(n=1)}}s<0&&(s=0,n=1);for(let i=0;i<e.length;i++){let r=e[i].partsIndex;if(!(r<0))if(s==i)t.setPartsOpacity(r,n);else{let e,i=t.getPartsOpacity(r);e=n<a?-.5*n/a+1:(1-n)*a/.5;(1-e)*(1-n)>.15&&(e=1-.15/(1-n)),i>e&&(i=e),t.setPartsOpacity(r,i)}}}copyOpacityOtherParts(t,e){for(let i=0;i<e.length;i++){const s=e[i];if(null==s.link)continue;if(s.partsIndex<0)continue;const n=t.getPartsOpacity(s.partsIndex);for(let e=0;e<s.link.length;e++){const i=s.link[e];i.partsIndex<0||t.setPartsOpacity(i.partsIndex,n)}}}}class u{constructor(t){this.paramIndex=-1,this.partsIndex=-1,this.link=null,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 m{constructor(){this.EPSILON=.01,this.faceTargetX=0,this.faceTargetY=0,this.faceX=0,this.faceY=0,this.faceVX=0,this.faceVY=0,this.lastTimeSec=0}setPoint(t,e){this.faceTargetX=t,this.faceTargetY=e}getX(){return this.faceX}getY(){return this.faceY}update(){const t=40/7.5/m.FRAME_RATE;if(0==this.lastTimeSec)return void(this.lastTimeSec=UtSystem.getUserTimeMSec());const e=UtSystem.getUserTimeMSec(),i=(e-this.lastTimeSec)*m.FRAME_RATE/1e3;this.lastTimeSec=e;const s=i*t/(.15*m.FRAME_RATE),n=this.faceTargetX-this.faceX,a=this.faceTargetY-this.faceY;if(Math.abs(n)<=this.EPSILON&&Math.abs(a)<=this.EPSILON)return;const r=Math.sqrt(n*n+a*a),o=t*a/r;let h=t*n/r-this.faceVX,l=o-this.faceVY,c=Math.sqrt(h*h+l*l);(c<-s||c>s)&&(h*=s/c,l*=s/c,c=s),this.faceVX+=h,this.faceVY+=l;{const t=.5*(Math.sqrt(s*s+16*s*r-8*s*r)-s),e=Math.sqrt(this.faceVX*this.faceVX+this.faceVY*this.faceVY);e>t&&(this.faceVX*=t/e,this.faceVY*=t/e)}this.faceX+=this.faceVX,this.faceY+=this.faceVY}}m.FRAME_RATE=30;class g extends o{constructor(){super(),this.screenLeft=null,this.screenRight=null,this.screenTop=null,this.screenBottom=null,this.maxLeft=null,this.maxRight=null,this.maxTop=null,this.maxBottom=null,this.max=Number.MAX_VALUE,this.min=0}getMaxScale(){return this.max}getMinScale(){return this.min}setMaxScale(t){this.max=t}setMinScale(t){this.min=t}isMaxScale(){return this.getScaleX()==this.max}isMinScale(){return this.getScaleX()==this.min}adjustTranslate(t,e){this.tr[0]*this.maxLeft+(this.tr[12]+t)>this.screenLeft&&(t=this.screenLeft-this.tr[0]*this.maxLeft-this.tr[12]),this.tr[0]*this.maxRight+(this.tr[12]+t)<this.screenRight&&(t=this.screenRight-this.tr[0]*this.maxRight-this.tr[12]),this.tr[5]*this.maxTop+(this.tr[13]+e)<this.screenTop&&(e=this.screenTop-this.tr[5]*this.maxTop-this.tr[13]),this.tr[5]*this.maxBottom+(this.tr[13]+e)>this.screenBottom&&(e=this.screenBottom-this.tr[5]*this.maxBottom-this.tr[13]);const i=[1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1];o.mul(i,this.tr,this.tr)}adjustScale(t,e,i){const s=i*this.tr[0];s<this.min?this.tr[0]>0&&(i=this.min/this.tr[0]):s>this.max&&this.tr[0]>0&&(i=this.max/this.tr[0]);const n=[1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1],a=[i,0,0,0,0,i,0,0,0,0,1,0,0,0,0,1],r=[1,0,0,0,0,1,0,0,0,0,1,0,-t,-e,0,1];o.mul(r,this.tr,this.tr),o.mul(a,this.tr,this.tr),o.mul(n,this.tr,this.tr)}setScreenRect(t,e,i,s){this.screenLeft=t,this.screenRight=e,this.screenTop=s,this.screenBottom=i}setMaxScreenRect(t,e,i,s){this.maxLeft=t,this.maxRight=e,this.maxTop=s,this.maxBottom=i}getScreenLeft(){return this.screenLeft}getScreenRight(){return this.screenRight}getScreenBottom(){return this.screenBottom}getScreenTop(){return this.screenTop}getMaxLeft(){return this.maxLeft}getMaxRight(){return this.maxRight}getMaxBottom(){return this.maxBottom}getMaxTop(){return this.maxTop}}class M{static getPlatformManager(){return M.platformManager}static setPlatformManager(t){M.platformManager=t}}M.platformManager=null;const S=1.5,T=1,p=-1,E=1,v=-2,P=2,_=-2,I=2,x=1,f=2,A=3,y="idle",R="tap_body",O="pinch_in",D="pinch_out",L="head",N="body";class w{static reset(){this.depth=0}static loadIdentity(){for(let t=0;t<16;t++)this.currentMatrix[t]=t%5==0?1:0}static push(){this.depth;const t=16*(this.depth+1);this.matrixStack.length<t+16&&(this.matrixStack.length=t+16);for(let e=0;e<16;e++)this.matrixStack[t+e]=this.currentMatrix[e];this.depth++}static pop(){this.depth--,this.depth<0&&(this.depth=0);const t=16*this.depth;for(let e=0;e<16;e++)this.currentMatrix[e]=this.matrixStack[t+e]}static getMatrix(){return this.currentMatrix}static multMatrix(t){let e,i,s;for(e=0;e<16;e++)this.tmp[e]=0;for(e=0;e<4;e++)for(i=0;i<4;i++)for(s=0;s<4;s++)this.tmp[e+4*i]+=this.currentMatrix[e+4*s]*t[s+4*i];for(e=0;e<16;e++)this.currentMatrix[e]=this.tmp[e]}}w.matrixStack=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],w.depth=0,w.currentMatrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],w.tmp=new Array(16);class F{constructor(){this.NAME="name",this.ID="id",this.MODEL="model",this.TEXTURES="textures",this.HIT_AREAS="hit_areas",this.HIT_AREAS_CUSTOM="hit_areas_custom",this.PHYSICS="physics",this.POSE="pose",this.EXPRESSIONS="expressions",this.MOTION_GROUPS="motions",this.SOUND="sound",this.FADE_IN="fade_in",this.FADE_OUT="fade_out",this.LAYOUT="layout",this.INIT_PARAM="init_param",this.INIT_PARTS_VISIBLE="init_parts_visible",this.VALUE="val",this.FILE="file",this.json={}}loadModelSetting(t,e){M.getPlatformManager().loadBytes(t,(t=>{const i=String.fromCharCode.apply(null,new Uint8Array(t));this.json=JSON.parse(i),e()}))}getTextureFile(t){return null==this.json[this.TEXTURES]||null==this.json[this.TEXTURES][t]?null:this.json[this.TEXTURES][t]}getModelFile(){return this.json[this.MODEL]}getTextureNum(){return null==this.json[this.TEXTURES]?0:this.json[this.TEXTURES].length}getHitAreaNum(){return null==this.json[this.HIT_AREAS]?0:this.json[this.HIT_AREAS].length}getHitAreaCustom(){return this.json[this.HIT_AREAS_CUSTOM]}getHitAreaID(t){return null==this.json[this.HIT_AREAS]||null==this.json[this.HIT_AREAS][t]?null:this.json[this.HIT_AREAS][t][this.ID]}getHitAreaName(t){return null==this.json[this.HIT_AREAS]||null==this.json[this.HIT_AREAS][t]?null:this.json[this.HIT_AREAS][t][this.NAME]}getPhysicsFile(){return this.json[this.PHYSICS]}getPoseFile(){return this.json[this.POSE]}getExpressionNum(){return null==this.json[this.EXPRESSIONS]?0:this.json[this.EXPRESSIONS].length}getExpressionFile(t){return null==this.json[this.EXPRESSIONS]?null:this.json[this.EXPRESSIONS][t][this.FILE]}getExpressionName(t){return null==this.json[this.EXPRESSIONS]?null:this.json[this.EXPRESSIONS][t][this.NAME]}getLayout(){return this.json[this.LAYOUT]}getInitParamNum(){return null==this.json[this.INIT_PARAM]?0:this.json[this.INIT_PARAM].length}getMotionNum(t){return null==this.json[this.MOTION_GROUPS]||null==this.json[this.MOTION_GROUPS][t]?0:this.json[this.MOTION_GROUPS][t].length}getMotionFile(t,e){return null==this.json[this.MOTION_GROUPS]||null==this.json[this.MOTION_GROUPS][t]||null==this.json[this.MOTION_GROUPS][t][e]?null:this.json[this.MOTION_GROUPS][t][e][this.FILE]}getMotionSound(t,e){return null==this.json[this.MOTION_GROUPS]||null==this.json[this.MOTION_GROUPS][t]||null==this.json[this.MOTION_GROUPS][t][e]||null==this.json[this.MOTION_GROUPS][t][e][this.SOUND]?null:this.json[this.MOTION_GROUPS][t][e][this.SOUND]}getMotionFadeIn(t,e){return null==this.json[this.MOTION_GROUPS]||null==this.json[this.MOTION_GROUPS][t]||null==this.json[this.MOTION_GROUPS][t][e]||null==this.json[this.MOTION_GROUPS][t][e][this.FADE_IN]?1e3:this.json[this.MOTION_GROUPS][t][e][this.FADE_IN]}getMotionFadeOut(t,e){return null==this.json[this.MOTION_GROUPS]||null==this.json[this.MOTION_GROUPS][t]||null==this.json[this.MOTION_GROUPS][t][e]||null==this.json[this.MOTION_GROUPS][t][e][this.FADE_OUT]?1e3:this.json[this.MOTION_GROUPS][t][e][this.FADE_OUT]}getInitParamID(t){return null==this.json[this.INIT_PARAM]||null==this.json[this.INIT_PARAM][t]?null:this.json[this.INIT_PARAM][t][this.ID]}getInitParamValue(t){return null==this.json[this.INIT_PARAM]||null==this.json[this.INIT_PARAM][t]?NaN:this.json[this.INIT_PARAM][t][this.VALUE]}getInitPartsVisibleNum(){return null==this.json[this.INIT_PARTS_VISIBLE]?0:this.json[this.INIT_PARTS_VISIBLE].length}getInitPartsVisibleID(t){return null==this.json[this.INIT_PARTS_VISIBLE]||null==this.json[this.INIT_PARTS_VISIBLE][t]?null:this.json[this.INIT_PARTS_VISIBLE][t][this.ID]}getInitPartsVisibleValue(t){return null==this.json[this.INIT_PARTS_VISIBLE]||null==this.json[this.INIT_PARTS_VISIBLE][t]?NaN:this.json[this.INIT_PARTS_VISIBLE][t][this.VALUE]}}class U extends e{constructor(){super(),this.modelHomeDir="",this.modelSetting=null,this.tmpMatrix=[]}loadJSON(t){const e=this.modelHomeDir+this.modelSetting.getModelFile();this.loadModelData(e,(e=>{for(let e=0;e<this.modelSetting.getTextureNum();e++){const i=this.modelHomeDir+this.modelSetting.getTextureFile(e);this.loadTexture(e,i,(()=>{if(this.isTexLoaded){if(this.modelSetting.getExpressionNum()>0){this.expressions={};for(let t=0;t<this.modelSetting.getExpressionNum();t++){const e=this.modelSetting.getExpressionName(t),i=this.modelHomeDir+this.modelSetting.getExpressionFile(t);this.loadExpression(e,i)}}else this.expressionManager=null,this.expressions={};if(null==this.eyeBlink&&(this.eyeBlink=new a),null!=this.modelSetting.getPhysicsFile()?this.loadPhysics(this.modelHomeDir+this.modelSetting.getPhysicsFile()):this.physics=null,null!=this.modelSetting.getPoseFile()?this.loadPose(this.modelHomeDir+this.modelSetting.getPoseFile(),(()=>{this.pose.updateParam(this.live2DModel)})):this.pose=null,null!=this.modelSetting.getLayout()){const t=this.modelSetting.getLayout();null!=t.width&&this.modelMatrix.setWidth(t.width),null!=t.height&&this.modelMatrix.setHeight(t.height),null!=t.x&&this.modelMatrix.setX(t.x),null!=t.y&&this.modelMatrix.setY(t.y),null!=t.center_x&&this.modelMatrix.centerX(t.center_x),null!=t.center_y&&this.modelMatrix.centerY(t.center_y),null!=t.top&&this.modelMatrix.top(t.top),null!=t.bottom&&this.modelMatrix.bottom(t.bottom),null!=t.left&&this.modelMatrix.left(t.left),null!=t.right&&this.modelMatrix.right(t.right)}for(let t=0;t<this.modelSetting.getInitParamNum();t++)this.live2DModel.setParamFloat(this.modelSetting.getInitParamID(t),this.modelSetting.getInitParamValue(t));for(let t=0;t<this.modelSetting.getInitPartsVisibleNum();t++)this.live2DModel.setPartsOpacity(this.modelSetting.getInitPartsVisibleID(t),this.modelSetting.getInitPartsVisibleValue(t));this.live2DModel.saveParam(),this.preloadMotionGroup(y),this.mainMotionManager.stopAllMotions(),this.setUpdating(!1),this.setInitialized(!0),"function"==typeof t&&t()}}))}}))}async loadModelSetting(t,e){this.setUpdating(!0),this.setInitialized(!1),this.modelHomeDir=t.substring(0,t.lastIndexOf("/")+1),this.modelSetting=new F,this.modelSetting.json=e,await new Promise((t=>this.loadJSON(t)))}load(t,e,i){this.setUpdating(!0),this.setInitialized(!1),this.modelHomeDir=e.substring(0,e.lastIndexOf("/")+1),this.modelSetting=new F,this.modelSetting.loadModelSetting(e,(()=>{this.loadJSON(i)}))}release(t){const e=M.getPlatformManager();t.deleteTexture(e.texture)}preloadMotionGroup(t){for(let e=0;e<this.modelSetting.getMotionNum(t);e++){const i=this.modelSetting.getMotionFile(t,e);this.loadMotion(i,this.modelHomeDir+i,(i=>{i.setFadeIn(this.modelSetting.getMotionFadeIn(t,e)),i.setFadeOut(this.modelSetting.getMotionFadeOut(t,e))}))}}update(){if(null==this.live2DModel)return void t.error("Failed to update.");const e=2*((UtSystem.getUserTimeMSec()-this.startTimeMSec)/1e3)*Math.PI;this.mainMotionManager.isFinished()&&this.startRandomMotion(y,x),this.live2DModel.loadParam();this.mainMotionManager.updateParam(this.live2DModel)||null!=this.eyeBlink&&this.eyeBlink.updateParam(this.live2DModel),this.live2DModel.saveParam(),null==this.expressionManager||null==this.expressions||this.expressionManager.isFinished()||this.expressionManager.updateParam(this.live2DModel),this.live2DModel.addToParamFloat("PARAM_ANGLE_X",30*this.dragX,1),this.live2DModel.addToParamFloat("PARAM_ANGLE_Y",30*this.dragY,1),this.live2DModel.addToParamFloat("PARAM_ANGLE_Z",this.dragX*this.dragY*-30,1),this.live2DModel.addToParamFloat("PARAM_BODY_ANGLE_X",10*this.dragX,1),this.live2DModel.addToParamFloat("PARAM_EYE_BALL_X",this.dragX,1),this.live2DModel.addToParamFloat("PARAM_EYE_BALL_Y",this.dragY,1),this.live2DModel.addToParamFloat("PARAM_ANGLE_X",Number(15*Math.sin(e/6.5345)),.5),this.live2DModel.addToParamFloat("PARAM_ANGLE_Y",Number(8*Math.sin(e/3.5345)),.5),this.live2DModel.addToParamFloat("PARAM_ANGLE_Z",Number(10*Math.sin(e/5.5345)),.5),this.live2DModel.addToParamFloat("PARAM_BODY_ANGLE_X",Number(4*Math.sin(e/15.5345)),.5),this.live2DModel.setParamFloat("PARAM_BREATH",Number(.5+.5*Math.sin(e/3.2345)),1),null!=this.physics&&this.physics.updateParam(this.live2DModel),null==this.lipSync&&this.live2DModel.setParamFloat("PARAM_MOUTH_OPEN_Y",this.lipSyncValue),null!=this.pose&&this.pose.updateParam(this.live2DModel),this.live2DModel.update()}setRandomExpression(){const t=[];for(const e in this.expressions)t.push(e);const e=parseInt(Math.random()*t.length);this.setExpression(t[e])}startRandomMotion(t,e){const i=this.modelSetting.getMotionNum(t),s=parseInt(Math.random()*i);this.startMotion(t,s,e)}startMotion(e,i,s){const n=this.modelSetting.getMotionFile(e,i);if(null==n||""==n)return;if(s==A)this.mainMotionManager.setReservePriority(s);else if(!this.mainMotionManager.reserveMotion(s))return void t.trace("Motion is running.");let a;null==this.motions[e]?this.loadMotion(null,this.modelHomeDir+n,(t=>{a=t,this.setFadeInFadeOut(e,i,s,a)})):(a=this.motions[e],this.setFadeInFadeOut(e,i,s,a))}setFadeInFadeOut(e,i,s,n){const a=this.modelSetting.getMotionFile(e,i);if(n.setFadeIn(this.modelSetting.getMotionFadeIn(e,i)),n.setFadeOut(this.modelSetting.getMotionFadeOut(e,i)),t.trace("Start motion : "+a),null==this.modelSetting.getMotionSound(e,i))this.mainMotionManager.startMotionPrio(n,s);else{const a=this.modelSetting.getMotionSound(e,i),r=document.createElement("audio");r.src=this.modelHomeDir+a,t.trace("Start sound : "+a),r.play(),this.mainMotionManager.startMotionPrio(n,s)}}setExpression(e){var i;const s=this.expressions[e];t.trace("Expression : "+e),null===(i=this.expressionManager)||void 0===i||i.startMotion(s,!1)}draw(t){w.push(),w.multMatrix(this.modelMatrix.getArray()),this.tmpMatrix=w.getMatrix(),this.live2DModel.setMatrix(this.tmpMatrix),this.live2DModel.draw(),w.pop()}hitTest(t,e,i){const s=this.modelSetting.getHitAreaNum();if(0==s){const s=this.modelSetting.getHitAreaCustom();if(s){const n=s[t+"_x"],a=s[t+"_y"];if(e>Math.min(...n)&&e<Math.max(...n)&&i>Math.min(...a)&&i<Math.max(...a))return!0}}for(let n=0;n<s;n++)if(t==this.modelSetting.getHitAreaName(n)){const t=this.modelSetting.getHitAreaID(n);return this.hitTestSimple(t,e,i)}return!1}}class X{constructor(){this.cache={}}loadBytes(t,e){if(t in this.cache)return e(this.cache[t]);fetch(t).then((t=>t.arrayBuffer())).then((i=>{this.cache[t]=i,e(i)}))}loadLive2DModel(t,e){let i=null;this.loadBytes(t,(t=>{i=Live2DModelWebGL.loadModel(t),e(i)}))}loadTexture(e,i,s,n){const a=new Image;a.crossOrigin="anonymous",a.src=s,a.onload=()=>{const s=document.getElementById("live2d").getContext("webgl2",{premultipliedAlpha:!0,preserveDrawingBuffer:!0});let r=s.createTexture();if(!r)return t.error("Failed to generate gl texture name."),-1;0==e.isPremultipliedAlpha()&&s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,1),s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,r),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,a),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR_MIPMAP_NEAREST),s.generateMipmap(s.TEXTURE_2D),e.setTexture(i,r),r=null,"function"==typeof n&&n()},a.onerror=()=>{t.error("Failed to load image : "+s)}}jsonParseFromBytes(t){let e;const i=new Uint8Array(t,0,3);e=239==i[0]&&187==i[1]&&191==i[2]?String.fromCharCode.apply(null,new Uint8Array(t,3)):String.fromCharCode.apply(null,new Uint8Array(t));return JSON.parse(e)}}class Y{constructor(){this.model=null,this.reloading=!1,Live2D.init(),M.setPlatformManager(new X)}getModel(){return this.model}releaseModel(t){this.model&&(this.model.release(t),this.model=null)}async changeModel(t,e){return new Promise(((i,s)=>{if(this.reloading)return;this.reloading=!0;const n=this.model,a=new U;a.load(t,e,(()=>{n&&n.release(t),this.model=a,this.reloading=!1,i()}))}))}async changeModelWithJSON(t,e,i){if(this.reloading)return;this.reloading=!0;const s=this.model,n=new U;await n.loadModelSetting(e,i),s&&s.release(t),this.model=n,this.reloading=!1}setDrag(t,e){this.model&&this.model.setDrag(t,e)}maxScaleEvent(){t.trace("Max scale event."),this.model&&this.model.startRandomMotion(O,f)}minScaleEvent(){t.trace("Min scale event."),this.model&&this.model.startRandomMotion(D,f)}tapEvent(e,i){return t.trace("tapEvent view x:"+e+" y:"+i),!!this.model&&(this.model.hitTest(L,e,i)?(t.trace("Tap face."),this.model.setRandomExpression()):this.model.hitTest(N,e,i)&&(t.trace("Tap body."),this.model.startRandomMotion(R,f)),!0)}}function j(t,e,i,s,n,a){const r=t-i,o=e-s;let h=0,l=0;return h=r>=0?r/(n-i):r/i,l=o>=0?o/(a-s):o/s,{vx:h,vy:-l}}class G{constructor(){this.live2DMgr=new Y,this.isDrawStart=!1,this.gl=null,this.canvas=null,this.dragMgr=null,this.viewMatrix=null,this.projMatrix=null,this.deviceToScreen=null,this.oldLen=0,this._boundMouseEvent=this.mouseEvent.bind(this),this._boundTouchEvent=this.touchEvent.bind(this)}initL2dCanvas(t){this.canvas=document.getElementById(t),this.canvas.addEventListener&&(this.canvas.addEventListener("mousewheel",this._boundMouseEvent,!1),this.canvas.addEventListener("click",this._boundMouseEvent,!1),document.addEventListener("mousemove",this._boundMouseEvent,!1),document.addEventListener("mouseout",this._boundMouseEvent,!1),this.canvas.addEventListener("contextmenu",this._boundMouseEvent,!1),this.canvas.addEventListener("touchstart",this._boundTouchEvent,!1),this.canvas.addEventListener("touchend",this._boundTouchEvent,!1),this.canvas.addEventListener("touchmove",this._boundTouchEvent,!1))}async init(e,i,s){this.initL2dCanvas(e);const n=this.canvas.width,a=this.canvas.height;this.dragMgr=new m;const r=a/n,h=p,l=E,c=-r,d=r;this.viewMatrix=new g,this.viewMatrix.setScreenRect(h,l,c,d),this.viewMatrix.setMaxScreenRect(v,P,_,I),this.viewMatrix.setMaxScale(S),this.viewMatrix.setMinScale(T),this.projMatrix=new o,this.projMatrix.multScale(1,n/a),this.deviceToScreen=new o,this.deviceToScreen.multTranslate(-n/2,-a/2),this.deviceToScreen.multScale(2/n,-2/n),this.gl=this.canvas.getContext("webgl2",{premultipliedAlpha:!0,preserveDrawingBuffer:!0}),this.gl?(Live2D.setGL(this.gl),this.gl.clearColor(0,0,0,0),await this.changeModelWithJSON(i,s),this.startDraw()):t.error("Failed to create WebGL context.")}destroy(){this.canvas&&(this.canvas.removeEventListener("mousewheel",this._boundMouseEvent,!1),this.canvas.removeEventListener("click",this._boundMouseEvent,!1),document.removeEventListener("mousemove",this._boundMouseEvent,!1),document.removeEventListener("mouseout",this._boundMouseEvent,!1),this.canvas.removeEventListener("contextmenu",this._boundMouseEvent,!1),this.canvas.removeEventListener("touchstart",this._boundTouchEvent,!1),this.canvas.removeEventListener("touchend",this._boundTouchEvent,!1),this.canvas.removeEventListener("touchmove",this._boundTouchEvent,!1)),this._drawFrameId&&(window.cancelAnimationFrame(this._drawFrameId),this._drawFrameId=null),this.isDrawStart=!1,this.live2DMgr&&"function"==typeof this.live2DMgr.release&&this.live2DMgr.release(),this.gl,this.canvas=null,this.gl=null,this.dragMgr=null,this.viewMatrix=null,this.projMatrix=null,this.deviceToScreen=null}startDraw(){if(!this.isDrawStart){this.isDrawStart=!0;const t=()=>{this.draw(),this._drawFrameId=window.requestAnimationFrame(t,this.canvas)};t()}}draw(){w.reset(),w.loadIdentity(),this.dragMgr.update(),this.live2DMgr.setDrag(this.dragMgr.getX(),this.dragMgr.getY()),this.gl.clear(this.gl.COLOR_BUFFER_BIT),w.multMatrix(this.projMatrix.getArray()),w.multMatrix(this.viewMatrix.getArray()),w.push();const t=this.live2DMgr.getModel();null!=t&&(t.initialized&&!t.updating&&(t.update(),t.draw(this.gl)),w.pop())}async changeModel(t){await this.live2DMgr.changeModel(this.gl,t)}async changeModelWithJSON(t,e){await this.live2DMgr.changeModelWithJSON(this.gl,t,e)}modelScaling(t){const e=this.viewMatrix.isMaxScale(),i=this.viewMatrix.isMinScale();this.viewMatrix.adjustScale(0,0,t),e||this.viewMatrix.isMaxScale()&&this.live2DMgr.maxScaleEvent(),i||this.viewMatrix.isMinScale()&&this.live2DMgr.minScaleEvent()}modelTurnHead(e){var i;const s=this.canvas.getBoundingClientRect(),{vx:n,vy:a}=j(e.clientX,e.clientY,s.left+s.width/2,s.top+s.height/2,window.innerWidth,window.innerHeight);t.trace("onMouseDown device( x:"+e.clientX+" y:"+e.clientY+" ) view( x:"+n+" y:"+a+")"),this.dragMgr.setPoint(n,a),this.live2DMgr.tapEvent(n,a),(null===(i=this.live2DMgr)||void 0===i?void 0:i.model.hitTest(N,n,a))&&window.dispatchEvent(new Event("live2d:tapbody"))}followPointer(e){var i;const s=this.canvas.getBoundingClientRect(),{vx:n,vy:a}=j(e.clientX,e.clientY,s.left+s.width/2,s.top+s.height/2,window.innerWidth,window.innerHeight);t.trace("onMouseMove device( x:"+e.clientX+" y:"+e.clientY+" ) view( x:"+n+" y:"+a+")"),this.dragMgr.setPoint(n,a),(null===(i=this.live2DMgr)||void 0===i?void 0:i.model.hitTest(N,n,a))&&window.dispatchEvent(new Event("live2d:hoverbody"))}lookFront(){this.dragMgr.setPoint(0,0)}mouseEvent(t){t.preventDefault(),"mousewheel"==t.type?t.wheelDelta>0?this.modelScaling(1.1):this.modelScaling(.9):"click"==t.type||"contextmenu"==t.type?this.modelTurnHead(t):"mousemove"==t.type?this.followPointer(t):"mouseout"==t.type&&this.lookFront()}touchEvent(t){t.preventDefault();const e=t.touches[0];if("touchstart"==t.type)1==t.touches.length&&this.modelTurnHead(e);else if("touchmove"==t.type){if(this.followPointer(e),2==t.touches.length){const e=t.touches[0],i=t.touches[1],s=Math.pow(e.pageX-i.pageX,2)+Math.pow(e.pageY-i.pageY,2);this.oldLen-s<0?this.modelScaling(1.025):this.modelScaling(.975),this.oldLen=s}}else"touchend"==t.type&&this.lookFront()}transformViewX(t){const e=this.deviceToScreen.transformX(t);return this.viewMatrix.invertTransformX(e)}transformViewY(t){const e=this.deviceToScreen.transformY(t);return this.viewMatrix.invertTransformY(e)}transformScreenX(t){return this.deviceToScreen.transformX(t)}transformScreenY(t){return this.deviceToScreen.transformY(t)}}export{G as default};
//# sourceMappingURL=index.js.map