@pixiv/three-vrm 2.1.2 → 3.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,55 +1,959 @@
1
1
  /*! (c) 2019-2024 pixiv Inc. - https://github.com/pixiv/three-vrm/blob/release/LICENSE */
2
- import*as e from"three";import{BufferAttribute as t}from"three";
2
+ var me=(t,e,n)=>new Promise((i,r)=>{var s=o=>{try{l(n.next(o))}catch(u){r(u)}},a=o=>{try{l(n.throw(o))}catch(u){r(u)}},l=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);l((n=n.apply(t,e)).next())});import*as Mn from"three";import*as q from"three";import*as Xe from"three";import*as Pn from"three";import*as N from"three";import*as z from"three";import*as be from"three";import*as D from"three";import*as P from"three";import*as _e from"three";import*as X from"three";import*as b from"three";import*as Ke from"three";import*as S from"three";import*as Qe from"three";import*as On from"three";var y=(t,e,n)=>new Promise((i,r)=>{var s=o=>{try{l(n.next(o))}catch(u){r(u)}},a=o=>{try{l(n.throw(o))}catch(u){r(u)}},l=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);l((n=n.apply(t,e)).next())}),$t=class extends Mn.Object3D{constructor(t){super(),this.weight=0,this.isBinary=!1,this.overrideBlink="none",this.overrideLookAt="none",this.overrideMouth="none",this._binds=[],this.name=`VRMExpression_${t}`,this.expressionName=t,this.type="VRMExpression",this.visible=!1}get overrideBlinkAmount(){return this.overrideBlink==="block"?0<this.weight?1:0:this.overrideBlink==="blend"?this.weight:0}get overrideLookAtAmount(){return this.overrideLookAt==="block"?0<this.weight?1:0:this.overrideLookAt==="blend"?this.weight:0}get overrideMouthAmount(){return this.overrideMouth==="block"?0<this.weight?1:0:this.overrideMouth==="blend"?this.weight:0}addBind(t){this._binds.push(t)}applyWeight(t){var e;let n=this.isBinary?this.weight<=.5?0:1:this.weight;n*=(e=t==null?void 0:t.multiplier)!=null?e:1,this._binds.forEach(i=>i.applyWeight(n))}clearAppliedWeight(){this._binds.forEach(t=>t.clearAppliedWeight())}};function Rn(t,e,n){var i,r;let s=t.parser.json,a=(i=s.nodes)==null?void 0:i[e];if(a==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${e}] of glTF but the node doesn't exist`),null;let l=a.mesh;if(l==null)return null;let o=(r=s.meshes)==null?void 0:r[l];if(o==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${l}] of glTF but the mesh doesn't exist`),null;let u=o.primitives.length,d=[];return n.traverse(c=>{d.length<u&&c.isMesh&&d.push(c)}),d}function Zt(t,e){return y(this,null,function*(){let n=yield t.parser.getDependency("node",e);return Rn(t,e,n)})}function Jt(t){return y(this,null,function*(){let e=yield t.parser.getDependencies("node"),n=new Map;return e.forEach((i,r)=>{let s=Rn(t,r,i);s!=null&&n.set(r,s)}),n})}var ze={Aa:"aa",Ih:"ih",Ou:"ou",Ee:"ee",Oh:"oh",Blink:"blink",Happy:"happy",Angry:"angry",Sad:"sad",Relaxed:"relaxed",LookUp:"lookUp",Surprised:"surprised",LookDown:"lookDown",LookLeft:"lookLeft",LookRight:"lookRight",BlinkLeft:"blinkLeft",BlinkRight:"blinkRight",Neutral:"neutral"};function Tn(t){return Math.max(Math.min(t,1),0)}var Kt=class xn{constructor(){this.blinkExpressionNames=["blink","blinkLeft","blinkRight"],this.lookAtExpressionNames=["lookLeft","lookRight","lookUp","lookDown"],this.mouthExpressionNames=["aa","ee","ih","oh","ou"],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){let e={},n=new Set(Object.values(ze));return Object.entries(this._expressionMap).forEach(([i,r])=>{n.has(i)&&(e[i]=r)}),e}get customExpressionMap(){let e={},n=new Set(Object.values(ze));return Object.entries(this._expressionMap).forEach(([i,r])=>{n.has(i)||(e[i]=r)}),e}copy(e){return this._expressions.concat().forEach(i=>{this.unregisterExpression(i)}),e._expressions.forEach(i=>{this.registerExpression(i)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new xn().copy(this)}getExpression(e){var n;return(n=this._expressionMap[e])!=null?n:null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){let n=this._expressions.indexOf(e);n===-1&&console.warn("VRMExpressionManager: The specified expressions is not registered"),this._expressions.splice(n,1),delete this._expressionMap[e.expressionName]}getValue(e){var n;let i=this.getExpression(e);return(n=i==null?void 0:i.weight)!=null?n:null}setValue(e,n){let i=this.getExpression(e);i&&(i.weight=Tn(n))}getExpressionTrackName(e){let n=this.getExpression(e);return n?`${n.name}.weight`:null}update(){let e=this._calculateWeightMultipliers();this._expressions.forEach(n=>{n.clearAppliedWeight()}),this._expressions.forEach(n=>{let i=1,r=n.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(i*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(i*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(i*=e.mouth),n.applyWeight({multiplier:i})})}_calculateWeightMultipliers(){let e=1,n=1,i=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,n-=r.overrideLookAtAmount,i-=r.overrideMouthAmount}),e=Math.max(0,e),n=Math.max(0,n),i=Math.max(0,i),{blink:e,lookAt:n,mouth:i}}},pe={Color:"color",EmissionColor:"emissionColor",ShadeColor:"shadeColor",MatcapColor:"matcapColor",RimColor:"rimColor",OutlineColor:"outlineColor"},er={_Color:pe.Color,_EmissionColor:pe.EmissionColor,_ShadeColor:pe.ShadeColor,_RimColor:pe.RimColor,_OutlineColor:pe.OutlineColor},tr=new Xe.Color,yn=class wn{constructor({material:e,type:n,targetValue:i,targetAlpha:r}){this.material=e,this.type=n,this.targetValue=i,this.targetAlpha=r!=null?r:1;let s=this._initColorBindState(),a=this._initAlphaBindState();this._state={color:s,alpha:a}}applyWeight(e){let{color:n,alpha:i}=this._state;if(n!=null){let{propertyName:r,deltaValue:s}=n,a=this.material[r];a!=null&&a.add(tr.copy(s).multiplyScalar(e))}if(i!=null){let{propertyName:r,deltaValue:s}=i;this.material[r]!=null&&(this.material[r]+=s*e)}}clearAppliedWeight(){let{color:e,alpha:n}=this._state;if(e!=null){let{propertyName:i,initialValue:r}=e,s=this.material[i];s!=null&&s.copy(r)}if(n!=null){let{propertyName:i,initialValue:r}=n;this.material[i]!=null&&(this.material[i]=r)}}_initColorBindState(){var e,n,i;let{material:r,type:s,targetValue:a}=this,l=this._getPropertyNameMap(),o=(n=(e=l==null?void 0:l[s])==null?void 0:e[0])!=null?n:null;if(o==null)return console.warn(`Tried to add a material color bind to the material ${(i=r.name)!=null?i:"(no name)"}, the type ${s} but the material or the type is not supported.`),null;let d=r[o].clone(),c=new Xe.Color(a.r-d.r,a.g-d.g,a.b-d.b);return{propertyName:o,initialValue:d,deltaValue:c}}_initAlphaBindState(){var e,n,i;let{material:r,type:s,targetAlpha:a}=this,l=this._getPropertyNameMap(),o=(n=(e=l==null?void 0:l[s])==null?void 0:e[1])!=null?n:null;if(o==null&&a!==1)return console.warn(`Tried to add a material alpha bind to the material ${(i=r.name)!=null?i:"(no name)"}, the type ${s} but the material or the type does not support alpha.`),null;if(o==null)return null;let u=r[o],d=a-u;return{propertyName:o,initialValue:u,deltaValue:d}}_getPropertyNameMap(){var e,n;return(n=(e=Object.entries(wn._propertyNameMapMap).find(([i])=>this.material[i]===!0))==null?void 0:e[1])!=null?n:null}};yn._propertyNameMapMap={isMeshStandardMaterial:{color:["color","opacity"],emissionColor:["emissive",null]},isMeshBasicMaterial:{color:["color","opacity"]},isMToonMaterial:{color:["color","opacity"],emissionColor:["emissive",null],outlineColor:["outlineColorFactor",null],matcapColor:["matcapFactor",null],rimColor:["parametricRimColorFactor",null],shadeColor:["shadeColorFactor",null]}};var en=yn,tn=class{constructor({primitives:t,index:e,weight:n}){this.primitives=t,this.index=e,this.weight=n}applyWeight(t){this.primitives.forEach(e=>{var n;((n=e.morphTargetInfluences)==null?void 0:n[this.index])!=null&&(e.morphTargetInfluences[this.index]+=this.weight*t)})}clearAppliedWeight(){this.primitives.forEach(t=>{var e;((e=t.morphTargetInfluences)==null?void 0:e[this.index])!=null&&(t.morphTargetInfluences[this.index]=0)})}},nn=new Pn.Vector2,Sn=class An{constructor({material:e,scale:n,offset:i}){var r,s;this.material=e,this.scale=n,this.offset=i;let a=(r=Object.entries(An._propertyNamesMap).find(([l])=>e[l]===!0))==null?void 0:r[1];a==null?(console.warn(`Tried to add a texture transform bind to the material ${(s=e.name)!=null?s:"(no name)"} but the material is not supported.`),this._properties=[]):(this._properties=[],a.forEach(l=>{var o;let u=(o=e[l])==null?void 0:o.clone();if(!u)return null;e[l]=u;let d=u.offset.clone(),c=u.repeat.clone(),f=i.clone().sub(d),m=n.clone().sub(c);this._properties.push({name:l,initialOffset:d,deltaOffset:f,initialScale:c,deltaScale:m})}))}applyWeight(e){this._properties.forEach(n=>{let i=this.material[n.name];i!==void 0&&(i.offset.add(nn.copy(n.deltaOffset).multiplyScalar(e)),i.repeat.add(nn.copy(n.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{let n=this.material[e.name];n!==void 0&&(n.offset.copy(e.initialOffset),n.repeat.copy(e.initialScale))})}};Sn._propertyNamesMap={isMeshStandardMaterial:["map","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap"],isMeshBasicMaterial:["map","specularMap","alphaMap"],isMToonMaterial:["map","normalMap","emissiveMap","shadeMultiplyTexture","rimMultiplyTexture","outlineWidthMultiplyTexture","uvAnimationMaskTexture"]};var rn=Sn,nr=new Set(["1.0","1.0-beta"]),Ln=class Hn{get name(){return"VRMExpressionLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return y(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return y(this,null,function*(){let n=yield this._v1Import(e);if(n)return n;let i=yield this._v0Import(e);return i||null})}_v1Import(e){return y(this,null,function*(){var n,i;let r=this.parser.json;if(!(((n=r.extensionsUsed)==null?void 0:n.indexOf("VRMC_vrm"))!==-1))return null;let a=(i=r.extensions)==null?void 0:i.VRMC_vrm;if(!a)return null;let l=a.specVersion;if(!nr.has(l))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${l}"`),null;let o=a.expressions;if(!o)return null;let u=new Set(Object.values(ze)),d=new Map;o.preset!=null&&Object.entries(o.preset).forEach(([f,m])=>{if(m!=null){if(!u.has(f)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${f}" detected. Ignoring the expression`);return}d.set(f,m)}}),o.custom!=null&&Object.entries(o.custom).forEach(([f,m])=>{if(u.has(f)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${f}". Ignoring the expression`);return}d.set(f,m)});let c=new Kt;return yield Promise.all(Array.from(d.entries()).map(f=>y(this,[f],function*([m,p]){var h,_,g,x,T,v,R;let E=new $t(m);if(e.scene.add(E),E.isBinary=(h=p.isBinary)!=null?h:!1,E.overrideBlink=(_=p.overrideBlink)!=null?_:"none",E.overrideLookAt=(g=p.overrideLookAt)!=null?g:"none",E.overrideMouth=(x=p.overrideMouth)!=null?x:"none",(T=p.morphTargetBinds)==null||T.forEach(M=>y(this,null,function*(){var A;if(M.node===void 0||M.index===void 0)return;let I=yield Zt(e,M.node),L=M.index;if(!I.every(H=>Array.isArray(H.morphTargetInfluences)&&L<H.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${p.name} attempts to index morph #${L} but not found.`);return}E.addBind(new tn({primitives:I,index:L,weight:(A=M.weight)!=null?A:1}))})),p.materialColorBinds||p.textureTransformBinds){let M=[];e.scene.traverse(A=>{let I=A.material;I&&M.push(I)}),(v=p.materialColorBinds)==null||v.forEach(A=>y(this,null,function*(){M.filter(L=>{var H;let U=(H=this.parser.associations.get(L))==null?void 0:H.materials;return A.material===U}).forEach(L=>{E.addBind(new en({material:L,type:A.type,targetValue:new q.Color().fromArray(A.targetValue),targetAlpha:A.targetValue[3]}))})})),(R=p.textureTransformBinds)==null||R.forEach(A=>y(this,null,function*(){M.filter(L=>{var H;let U=(H=this.parser.associations.get(L))==null?void 0:H.materials;return A.material===U}).forEach(L=>{var H,U;E.addBind(new rn({material:L,offset:new q.Vector2().fromArray((H=A.offset)!=null?H:[0,0]),scale:new q.Vector2().fromArray((U=A.scale)!=null?U:[1,1])}))})}))}c.registerExpression(E)}))),c})}_v0Import(e){return y(this,null,function*(){var n;let i=this.parser.json,r=(n=i.extensions)==null?void 0:n.VRM;if(!r)return null;let s=r.blendShapeMaster;if(!s)return null;let a=new Kt,l=s.blendShapeGroups;if(!l)return a;let o=new Set;return yield Promise.all(l.map(u=>y(this,null,function*(){var d;let c=u.presetName,f=c!=null&&Hn.v0v1PresetNameMap[c]||null,m=f!=null?f:u.name;if(m==null){console.warn("VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression");return}if(o.has(m)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${c} has duplicated entries. Ignoring the expression`);return}o.add(m);let p=new $t(m);e.scene.add(p),p.isBinary=(d=u.isBinary)!=null?d:!1,u.binds&&u.binds.forEach(_=>y(this,null,function*(){var g;if(_.mesh===void 0||_.index===void 0)return;let x=[];(g=i.nodes)==null||g.forEach((v,R)=>{v.mesh===_.mesh&&x.push(R)});let T=_.index;yield Promise.all(x.map(v=>y(this,null,function*(){var R;let E=yield Zt(e,v);if(!E.every(M=>Array.isArray(M.morphTargetInfluences)&&T<M.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${u.name} attempts to index ${T}th morph but not found.`);return}p.addBind(new tn({primitives:E,index:T,weight:.01*((R=_.weight)!=null?R:100)}))})))}));let h=u.materialValues;h&&h.length!==0&&h.forEach(_=>{if(_.materialName===void 0||_.propertyName===void 0||_.targetValue===void 0)return;let g=[];e.scene.traverse(T=>{if(T.material){let v=T.material;Array.isArray(v)?g.push(...v.filter(R=>(R.name===_.materialName||R.name===_.materialName+" (Outline)")&&g.indexOf(R)===-1)):v.name===_.materialName&&g.indexOf(v)===-1&&g.push(v)}});let x=_.propertyName;g.forEach(T=>{if(x==="_MainTex_ST"){let R=new q.Vector2(_.targetValue[0],_.targetValue[1]),E=new q.Vector2(_.targetValue[2],_.targetValue[3]);E.y=1-E.y-R.y,p.addBind(new rn({material:T,scale:R,offset:E}));return}let v=er[x];if(v){p.addBind(new en({material:T,type:v,targetValue:new q.Color().fromArray(_.targetValue),targetAlpha:_.targetValue[3]}));return}console.warn(x+" is not supported")})}),a.registerExpression(p)}))),a})}};Ln.v0v1PresetNameMap={a:"aa",e:"ee",i:"ih",o:"oh",u:"ou",blink:"blink",joy:"happy",angry:"angry",sorrow:"sad",fun:"relaxed",lookup:"lookUp",lookdown:"lookDown",lookleft:"lookLeft",lookright:"lookRight",blink_l:"blinkLeft",blink_r:"blinkRight",neutral:"neutral"};var Ye=Ln,bo={None:"none",Block:"block",Blend:"blend"},$e=class ae{constructor(e,n){this._firstPersonOnlyLayer=ae.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=ae.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=e,this.meshAnnotations=n}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMFirstPerson: humanoid must be same in order to copy");return this.meshAnnotations=e.meshAnnotations.map(n=>({meshes:n.meshes.concat(),type:n.type})),this}clone(){return new ae(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:e=ae.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:n=ae.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||(this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=n,this.meshAnnotations.forEach(i=>{i.meshes.forEach(r=>{i.type==="firstPersonOnly"?(r.layers.set(this._firstPersonOnlyLayer),r.traverse(s=>s.layers.set(this._firstPersonOnlyLayer))):i.type==="thirdPersonOnly"?(r.layers.set(this._thirdPersonOnlyLayer),r.traverse(s=>s.layers.set(this._thirdPersonOnlyLayer))):i.type==="auto"&&this._createHeadlessModel(r)})}),this._initializedLayers=!0)}_excludeTriangles(e,n,i,r){let s=0;if(n!=null&&n.length>0)for(let a=0;a<e.length;a+=3){let l=e[a],o=e[a+1],u=e[a+2],d=n[l],c=i[l];if(d[0]>0&&r.includes(c[0])||d[1]>0&&r.includes(c[1])||d[2]>0&&r.includes(c[2])||d[3]>0&&r.includes(c[3]))continue;let f=n[o],m=i[o];if(f[0]>0&&r.includes(m[0])||f[1]>0&&r.includes(m[1])||f[2]>0&&r.includes(m[2])||f[3]>0&&r.includes(m[3]))continue;let p=n[u],h=i[u];p[0]>0&&r.includes(h[0])||p[1]>0&&r.includes(h[1])||p[2]>0&&r.includes(h[2])||p[3]>0&&r.includes(h[3])||(e[s++]=l,e[s++]=o,e[s++]=u)}return s}_createErasedMesh(e,n){let i=new N.SkinnedMesh(e.geometry.clone(),e.material);i.name=`${e.name}(erase)`,i.frustumCulled=e.frustumCulled,i.layers.set(this._firstPersonOnlyLayer);let r=i.geometry,s=r.getAttribute("skinIndex"),a=s instanceof N.GLBufferAttribute?[]:s.array,l=[];for(let h=0;h<a.length;h+=4)l.push([a[h],a[h+1],a[h+2],a[h+3]]);let o=r.getAttribute("skinWeight"),u=o instanceof N.GLBufferAttribute?[]:o.array,d=[];for(let h=0;h<u.length;h+=4)d.push([u[h],u[h+1],u[h+2],u[h+3]]);let c=r.getIndex();if(!c)throw new Error("The geometry doesn't have an index buffer");let f=Array.from(c.array),m=this._excludeTriangles(f,d,l,n),p=[];for(let h=0;h<m;h++)p[h]=f[h];return r.setIndex(p),e.onBeforeRender&&(i.onBeforeRender=e.onBeforeRender),i.bind(new N.Skeleton(e.skeleton.bones,e.skeleton.boneInverses),new N.Matrix4),i}_createHeadlessModelForSkinnedMesh(e,n){let i=[];if(n.skeleton.bones.forEach((s,a)=>{this._isEraseTarget(s)&&i.push(a)}),!i.length){n.layers.enable(this._thirdPersonOnlyLayer),n.layers.enable(this._firstPersonOnlyLayer);return}n.layers.set(this._thirdPersonOnlyLayer);let r=this._createErasedMesh(n,i);e.add(r)}_createHeadlessModel(e){if(e.type==="Group")if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(n=>n.layers.set(this._thirdPersonOnlyLayer));else{let n=new N.Group;n.name=`_headless_${e.name}`,n.layers.set(this._firstPersonOnlyLayer),e.parent.add(n),e.children.filter(i=>i.type==="SkinnedMesh").forEach(i=>{let r=i;this._createHeadlessModelForSkinnedMesh(n,r)})}else if(e.type==="SkinnedMesh"){let n=e;this._createHeadlessModelForSkinnedMesh(e.parent,n)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(n=>n.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode("head")?!0:e.parent?this._isEraseTarget(e.parent):!1}};$e.DEFAULT_FIRSTPERSON_ONLY_LAYER=9;$e.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var on=$e,ir=new Set(["1.0","1.0-beta"]),Ze=class{get name(){return"VRMFirstPersonLoaderPlugin"}constructor(t){this.parser=t}afterRoot(t){return y(this,null,function*(){let e=t.userData.vrmHumanoid;if(e!==null){if(e===void 0)throw new Error("VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");t.userData.vrmFirstPerson=yield this._import(t,e)}})}_import(t,e){return y(this,null,function*(){if(e==null)return null;let n=yield this._v1Import(t,e);if(n)return n;let i=yield this._v0Import(t,e);return i||null})}_v1Import(t,e){return y(this,null,function*(){var n,i;let r=this.parser.json;if(!(((n=r.extensionsUsed)==null?void 0:n.indexOf("VRMC_vrm"))!==-1))return null;let a=(i=r.extensions)==null?void 0:i.VRMC_vrm;if(!a)return null;let l=a.specVersion;if(!ir.has(l))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${l}"`),null;let o=a.firstPerson;if(!o)return null;let u=[],d=yield Jt(t);return Array.from(d.entries()).forEach(([c,f])=>{var m;let p=o.meshAnnotations?o.meshAnnotations.find(h=>h.node===c):void 0;u.push({meshes:f,type:(m=p==null?void 0:p.type)!=null?m:"both"})}),new on(e,u)})}_v0Import(t,e){return y(this,null,function*(){var n;let i=this.parser.json,r=(n=i.extensions)==null?void 0:n.VRM;if(!r)return null;let s=r.firstPerson;if(!s)return null;let a=[],l=yield Jt(t);return Array.from(l.entries()).forEach(([o,u])=>{let d=i.nodes[o],c=s.meshAnnotations?s.meshAnnotations.find(f=>f.mesh===d.mesh):void 0;a.push({meshes:u,type:this._convertV0FlagToV1Type(c==null?void 0:c.firstPersonFlag)})}),new on(e,a)})}_convertV0FlagToV1Type(t){return t==="FirstPersonOnly"?"firstPersonOnly":t==="ThirdPersonOnly"?"thirdPersonOnly":t==="Auto"?"auto":"both"}},Vo={Auto:"auto",Both:"both",ThirdPersonOnly:"thirdPersonOnly",FirstPersonOnly:"firstPersonOnly"},sn=new z.Vector3,an=new z.Vector3,rr=new z.Quaternion,ln=class extends z.Group{constructor(t){super(),this.vrmHumanoid=t,this._boneAxesMap=new Map,Object.values(t.humanBones).forEach(e=>{let n=new z.AxesHelper(1);n.matrixAutoUpdate=!1,n.material.depthTest=!1,n.material.depthWrite=!1,this.add(n),this._boneAxesMap.set(e,n)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(t=>{t.geometry.dispose(),t.material.dispose()})}updateMatrixWorld(t){Array.from(this._boneAxesMap.entries()).forEach(([e,n])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(sn,rr,an);let i=sn.set(.1,.1,.1).divide(an);n.matrix.copy(e.node.matrixWorld).scale(i)}),super.updateMatrixWorld(t)}},Be=["hips","spine","chest","upperChest","neck","head","leftEye","rightEye","jaw","leftUpperLeg","leftLowerLeg","leftFoot","leftToes","rightUpperLeg","rightLowerLeg","rightFoot","rightToes","leftShoulder","leftUpperArm","leftLowerArm","leftHand","rightShoulder","rightUpperArm","rightLowerArm","rightHand","leftThumbMetacarpal","leftThumbProximal","leftThumbDistal","leftIndexProximal","leftIndexIntermediate","leftIndexDistal","leftMiddleProximal","leftMiddleIntermediate","leftMiddleDistal","leftRingProximal","leftRingIntermediate","leftRingDistal","leftLittleProximal","leftLittleIntermediate","leftLittleDistal","rightThumbMetacarpal","rightThumbProximal","rightThumbDistal","rightIndexProximal","rightIndexIntermediate","rightIndexDistal","rightMiddleProximal","rightMiddleIntermediate","rightMiddleDistal","rightRingProximal","rightRingIntermediate","rightRingDistal","rightLittleProximal","rightLittleIntermediate","rightLittleDistal"],Io={Hips:"hips",Spine:"spine",Chest:"chest",UpperChest:"upperChest",Neck:"neck",Head:"head",LeftEye:"leftEye",RightEye:"rightEye",Jaw:"jaw",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",LeftToes:"leftToes",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",RightToes:"rightToes",LeftShoulder:"leftShoulder",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightShoulder:"rightShoulder",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand",LeftThumbMetacarpal:"leftThumbMetacarpal",LeftThumbProximal:"leftThumbProximal",LeftThumbDistal:"leftThumbDistal",LeftIndexProximal:"leftIndexProximal",LeftIndexIntermediate:"leftIndexIntermediate",LeftIndexDistal:"leftIndexDistal",LeftMiddleProximal:"leftMiddleProximal",LeftMiddleIntermediate:"leftMiddleIntermediate",LeftMiddleDistal:"leftMiddleDistal",LeftRingProximal:"leftRingProximal",LeftRingIntermediate:"leftRingIntermediate",LeftRingDistal:"leftRingDistal",LeftLittleProximal:"leftLittleProximal",LeftLittleIntermediate:"leftLittleIntermediate",LeftLittleDistal:"leftLittleDistal",RightThumbMetacarpal:"rightThumbMetacarpal",RightThumbProximal:"rightThumbProximal",RightThumbDistal:"rightThumbDistal",RightIndexProximal:"rightIndexProximal",RightIndexIntermediate:"rightIndexIntermediate",RightIndexDistal:"rightIndexDistal",RightMiddleProximal:"rightMiddleProximal",RightMiddleIntermediate:"rightMiddleIntermediate",RightMiddleDistal:"rightMiddleDistal",RightRingProximal:"rightRingProximal",RightRingIntermediate:"rightRingIntermediate",RightRingDistal:"rightRingDistal",RightLittleProximal:"rightLittleProximal",RightLittleIntermediate:"rightLittleIntermediate",RightLittleDistal:"rightLittleDistal"},or={hips:null,spine:"hips",chest:"spine",upperChest:"chest",neck:"upperChest",head:"neck",leftEye:"head",rightEye:"head",jaw:"head",leftUpperLeg:"hips",leftLowerLeg:"leftUpperLeg",leftFoot:"leftLowerLeg",leftToes:"leftFoot",rightUpperLeg:"hips",rightLowerLeg:"rightUpperLeg",rightFoot:"rightLowerLeg",rightToes:"rightFoot",leftShoulder:"upperChest",leftUpperArm:"leftShoulder",leftLowerArm:"leftUpperArm",leftHand:"leftLowerArm",rightShoulder:"upperChest",rightUpperArm:"rightShoulder",rightLowerArm:"rightUpperArm",rightHand:"rightLowerArm",leftThumbMetacarpal:"leftHand",leftThumbProximal:"leftThumbMetacarpal",leftThumbDistal:"leftThumbProximal",leftIndexProximal:"leftHand",leftIndexIntermediate:"leftIndexProximal",leftIndexDistal:"leftIndexIntermediate",leftMiddleProximal:"leftHand",leftMiddleIntermediate:"leftMiddleProximal",leftMiddleDistal:"leftMiddleIntermediate",leftRingProximal:"leftHand",leftRingIntermediate:"leftRingProximal",leftRingDistal:"leftRingIntermediate",leftLittleProximal:"leftHand",leftLittleIntermediate:"leftLittleProximal",leftLittleDistal:"leftLittleIntermediate",rightThumbMetacarpal:"rightHand",rightThumbProximal:"rightThumbMetacarpal",rightThumbDistal:"rightThumbProximal",rightIndexProximal:"rightHand",rightIndexIntermediate:"rightIndexProximal",rightIndexDistal:"rightIndexIntermediate",rightMiddleProximal:"rightHand",rightMiddleIntermediate:"rightMiddleProximal",rightMiddleDistal:"rightMiddleIntermediate",rightRingProximal:"rightHand",rightRingIntermediate:"rightRingProximal",rightRingDistal:"rightRingIntermediate",rightLittleProximal:"rightHand",rightLittleIntermediate:"rightLittleProximal",rightLittleDistal:"rightLittleIntermediate"};function bn(t){return t.invert?t.invert():t.inverse(),t}var K=new be.Vector3,ee=new be.Quaternion,je=class{constructor(t){this.humanBones=t,this.restPose=this.getAbsolutePose()}getAbsolutePose(){let t={};return Object.keys(this.humanBones).forEach(e=>{let n=e,i=this.getBoneNode(n);i&&(K.copy(i.position),ee.copy(i.quaternion),t[n]={position:K.toArray(),rotation:ee.toArray()})}),t}getPose(){let t={};return Object.keys(this.humanBones).forEach(e=>{let n=e,i=this.getBoneNode(n);if(!i)return;K.set(0,0,0),ee.identity();let r=this.restPose[n];r!=null&&r.position&&K.fromArray(r.position).negate(),r!=null&&r.rotation&&bn(ee.fromArray(r.rotation)),K.add(i.position),ee.premultiply(i.quaternion),t[n]={position:K.toArray(),rotation:ee.toArray()}}),t}setPose(t){Object.entries(t).forEach(([e,n])=>{let i=e,r=this.getBoneNode(i);if(!r)return;let s=this.restPose[i];s&&(n!=null&&n.position&&(r.position.fromArray(n.position),s.position&&r.position.add(K.fromArray(s.position))),n!=null&&n.rotation&&(r.quaternion.fromArray(n.rotation),s.rotation&&r.quaternion.multiply(ee.fromArray(s.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([t,e])=>{let n=this.getBoneNode(t);n&&(e!=null&&e.position&&n.position.fromArray(e.position),e!=null&&e.rotation&&n.quaternion.fromArray(e.rotation))})}getBone(t){var e;return(e=this.humanBones[t])!=null?e:void 0}getBoneNode(t){var e,n;return(n=(e=this.humanBones[t])==null?void 0:e.node)!=null?n:null}},Fe=new D.Vector3,sr=new D.Quaternion,ar=new D.Vector3,un=class Vn extends je{static _setupTransforms(e){let n=new D.Object3D;n.name="VRMHumanoidRig";let i={},r={},s={},a={};Be.forEach(o=>{var u;let d=e.getBoneNode(o);if(d){let c=new D.Vector3,f=new D.Quaternion;d.updateWorldMatrix(!0,!1),d.matrixWorld.decompose(c,f,Fe),i[o]=c,r[o]=f,s[o]=d.quaternion.clone();let m=new D.Quaternion;(u=d.parent)==null||u.matrixWorld.decompose(Fe,m,Fe),a[o]=m}});let l={};return Be.forEach(o=>{var u;let d=e.getBoneNode(o);if(d){let c=i[o],f=o,m;for(;m==null&&(f=or[f],f!=null);)m=i[f];let p=new D.Object3D;p.name="Normalized_"+d.name,(f?(u=l[f])==null?void 0:u.node:n).add(p),p.position.copy(c),m&&p.position.sub(m),l[o]={node:p}}}),{rigBones:l,root:n,parentWorldRotations:a,boneRotations:s}}constructor(e){let{rigBones:n,root:i,parentWorldRotations:r,boneRotations:s}=Vn._setupTransforms(e);super(n),this.original=e,this.root=i,this._parentWorldRotations=r,this._boneRotations=s}update(){Be.forEach(e=>{let n=this.original.getBoneNode(e);if(n!=null){let i=this.getBoneNode(e),r=this._parentWorldRotations[e],s=sr.copy(r).invert(),a=this._boneRotations[e];if(n.quaternion.copy(i.quaternion).multiply(r).premultiply(s).multiply(a),e==="hips"){let l=i.getWorldPosition(ar);n.parent.updateWorldMatrix(!0,!1);let o=n.parent.matrixWorld,u=l.applyMatrix4(o.invert());n.position.copy(u)}}})}},dn=class In{get restPose(){return console.warn("VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead."),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,n){var i;this.autoUpdateHumanBones=(i=n==null?void 0:n.autoUpdateHumanBones)!=null?i:!0,this._rawHumanBones=new je(e),this._normalizedHumanBones=new un(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new je(e.humanBones),this._normalizedHumanBones=new un(this._rawHumanBones),this}clone(){return new In(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn("VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead."),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn("VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead."),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn("VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead."),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn("VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead."),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn("VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead."),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn("VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead."),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},lr={Hips:"hips",Spine:"spine",Head:"head",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand"},ur=new Set(["1.0","1.0-beta"]),hn={leftThumbProximal:"leftThumbMetacarpal",leftThumbIntermediate:"leftThumbProximal",rightThumbProximal:"rightThumbMetacarpal",rightThumbIntermediate:"rightThumbProximal"},Je=class{get name(){return"VRMHumanoidLoaderPlugin"}constructor(t,e){this.parser=t,this.helperRoot=e==null?void 0:e.helperRoot,this.autoUpdateHumanBones=e==null?void 0:e.autoUpdateHumanBones}afterRoot(t){return y(this,null,function*(){t.userData.vrmHumanoid=yield this._import(t)})}_import(t){return y(this,null,function*(){let e=yield this._v1Import(t);if(e)return e;let n=yield this._v0Import(t);return n||null})}_v1Import(t){return y(this,null,function*(){var e,n;let i=this.parser.json;if(!(((e=i.extensionsUsed)==null?void 0:e.indexOf("VRMC_vrm"))!==-1))return null;let s=(n=i.extensions)==null?void 0:n.VRMC_vrm;if(!s)return null;let a=s.specVersion;if(!ur.has(a))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${a}"`),null;let l=s.humanoid;if(!l)return null;let o=l.humanBones.leftThumbIntermediate!=null||l.humanBones.rightThumbIntermediate!=null,u={};l.humanBones!=null&&(yield Promise.all(Object.entries(l.humanBones).map(c=>y(this,[c],function*([f,m]){let p=f,h=m.node;if(o){let g=hn[p];g!=null&&(p=g)}let _=yield this.parser.getDependency("node",h);if(_==null){console.warn(`A glTF node bound to the humanoid bone ${p} (index = ${h}) does not exist`);return}u[p]={node:_}}))));let d=new dn(this._ensureRequiredBonesExist(u),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(t.scene.add(d.normalizedHumanBonesRoot),this.helperRoot){let c=new ln(d);this.helperRoot.add(c),c.renderOrder=this.helperRoot.renderOrder}return d})}_v0Import(t){return y(this,null,function*(){var e;let i=(e=this.parser.json.extensions)==null?void 0:e.VRM;if(!i)return null;let r=i.humanoid;if(!r)return null;let s={};r.humanBones!=null&&(yield Promise.all(r.humanBones.map(l=>y(this,null,function*(){let o=l.bone,u=l.node;if(o==null||u==null)return;let d=yield this.parser.getDependency("node",u);if(d==null){console.warn(`A glTF node bound to the humanoid bone ${o} (index = ${u}) does not exist`);return}let c=hn[o],f=c!=null?c:o;if(s[f]!=null){console.warn(`Multiple bone entries for ${f} detected (index = ${u}), ignoring duplicated entries.`);return}s[f]={node:d}}))));let a=new dn(this._ensureRequiredBonesExist(s),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(t.scene.add(a.normalizedHumanBonesRoot),this.helperRoot){let l=new ln(a);this.helperRoot.add(l),l.renderOrder=this.helperRoot.renderOrder}return a})}_ensureRequiredBonesExist(t){let e=Object.values(lr).filter(n=>t[n]==null);if(e.length>0)throw new Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${e.join(", ")}`);return t}},cn=class extends _e.BufferGeometry{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new _e.BufferAttribute(new Float32Array(65*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new _e.BufferAttribute(new Uint16Array(3*63),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,t=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,t=!0),t&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let t=0;t<64;t++){let e=t/63*this._currentTheta;this._attrPos.setXYZ(t+1,this._currentRadius*Math.sin(e),0,this._currentRadius*Math.cos(e))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<63;t++)this._attrIndex.setXYZ(t*3,0,t+1,t+2);this._attrIndex.needsUpdate=!0}},dr=class extends X.BufferGeometry{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new X.Vector3,this._currentTail=new X.Vector3,this._attrPos=new X.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new X.BufferAttribute(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,t=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),t=!0),t&&this._buildPosition()}_buildPosition(){for(let t=0;t<32;t++){let e=t/16*Math.PI;this._attrPos.setXYZ(t,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+t,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+t,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<32;t++){let e=(t+1)%32;this._attrIndex.setXY(t*2,t,e),this._attrIndex.setXY(64+t*2,32+t,32+e),this._attrIndex.setXY(128+t*2,64+t,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},Se=new P.Quaternion,mn=new P.Quaternion,fe=new P.Vector3,pn=new P.Vector3,fn=Math.sqrt(2)/2,hr=new P.Quaternion(0,0,-fn,fn),cr=new P.Vector3(0,1,0),mr=class extends P.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=t;{let e=new cn;e.radius=.5;let n=new P.MeshBasicMaterial({color:65280,transparent:!0,opacity:.5,side:P.DoubleSide,depthTest:!1,depthWrite:!1});this._meshPitch=new P.Mesh(e,n),this.add(this._meshPitch)}{let e=new cn;e.radius=.5;let n=new P.MeshBasicMaterial({color:16711680,transparent:!0,opacity:.5,side:P.DoubleSide,depthTest:!1,depthWrite:!1});this._meshYaw=new P.Mesh(e,n),this.add(this._meshYaw)}{let e=new dr;e.radius=.1;let n=new P.LineBasicMaterial({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new P.LineSegments(e,n),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(t){let e=P.MathUtils.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=e,this._meshYaw.geometry.update();let n=P.MathUtils.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(fe),this.vrmLookAt.getLookAtWorldQuaternion(Se),Se.multiply(this.vrmLookAt.getFaceFrontQuaternion(mn)),this._meshYaw.position.copy(fe),this._meshYaw.quaternion.copy(Se),this._meshPitch.position.copy(fe),this._meshPitch.quaternion.copy(Se),this._meshPitch.quaternion.multiply(mn.setFromAxisAngle(cr,e)),this._meshPitch.quaternion.multiply(hr);let{target:i,autoUpdate:r}=this.vrmLookAt;i!=null&&r&&(i.getWorldPosition(pn).sub(fe),this._lineTarget.geometry.tail.copy(pn),this._lineTarget.geometry.update(),this._lineTarget.position.copy(fe)),super.updateMatrixWorld(t)}},pr=new Ke.Vector3,fr=new Ke.Vector3;function Ge(t,e){return t.matrixWorld.decompose(pr,e,fr),e}function Le(t){return[Math.atan2(-t.z,t.x),Math.atan2(t.y,Math.sqrt(t.x*t.x+t.z*t.z))]}function _n(t){let e=Math.round(t/2/Math.PI);return t-2*Math.PI*e}var gn=new b.Vector3(0,0,1),_r=new b.Vector3,gr=new b.Vector3,vr=new b.Vector3,Er=new b.Quaternion,We=new b.Quaternion,vn=new b.Quaternion,Mr=new b.Quaternion,ke=new b.Euler,Un=class Cn{constructor(e,n){this.offsetFromHeadBone=new b.Vector3,this.autoUpdate=!0,this.faceFront=new b.Vector3(0,0,1),this.humanoid=e,this.applier=n,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new b.Quaternion)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn("VRMLookAt: euler is deprecated. use getEuler() instead."),this.getEuler(new b.Euler)}getEuler(e){return e.set(b.MathUtils.DEG2RAD*this._pitch,b.MathUtils.DEG2RAD*this._yaw,0,"YXZ")}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMLookAt: humanoid must be same in order to copy");return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new Cn(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){let n=this.humanoid.getRawBoneNode("head");return e.copy(this.offsetFromHeadBone).applyMatrix4(n.matrixWorld)}getLookAtWorldQuaternion(e){let n=this.humanoid.getRawBoneNode("head");return Ge(n,e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(gn)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[n,i]=Le(this.faceFront);return ke.set(0,.5*Math.PI+n,i,"YZX"),e.setFromEuler(ke).premultiply(Mr.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(We),this.getFaceFrontQuaternion(vn),e.copy(gn).applyQuaternion(We).applyQuaternion(vn).applyEuler(this.getEuler(ke))}lookAt(e){let n=Er.copy(this._restHeadWorldQuaternion).multiply(bn(this.getLookAtWorldQuaternion(We))),i=this.getLookAtWorldPosition(gr),r=vr.copy(e).sub(i).applyQuaternion(n).normalize(),[s,a]=Le(this.faceFront),[l,o]=Le(r),u=_n(l-s),d=_n(a-o);this._yaw=b.MathUtils.RAD2DEG*u,this._pitch=b.MathUtils.RAD2DEG*d,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(_r)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};Un.EULER_ORDER="YXZ";var Rr=Un,Tr=new S.Vector3(0,0,1),B=new S.Quaternion,se=new S.Quaternion,O=new S.Euler(0,0,0,"YXZ"),He=class{constructor(t,e,n,i,r){this.humanoid=t,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=r,this.faceFront=new S.Vector3(0,0,1),this._restQuatLeftEye=new S.Quaternion,this._restQuatRightEye=new S.Quaternion,this._restLeftEyeParentWorldQuat=new S.Quaternion,this._restRightEyeParentWorldQuat=new S.Quaternion;let s=this.humanoid.getRawBoneNode("leftEye"),a=this.humanoid.getRawBoneNode("rightEye");s&&(this._restQuatLeftEye.copy(s.quaternion),Ge(s.parent,this._restLeftEyeParentWorldQuat)),a&&(this._restQuatRightEye.copy(a.quaternion),Ge(a.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(t,e){let n=this.humanoid.getRawBoneNode("leftEye"),i=this.humanoid.getRawBoneNode("rightEye"),r=this.humanoid.getNormalizedBoneNode("leftEye"),s=this.humanoid.getNormalizedBoneNode("rightEye");n&&(e<0?O.x=-S.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-e):O.x=S.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(e),t<0?O.y=-S.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(-t):O.y=S.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(t),B.setFromEuler(O),this._getWorldFaceFrontQuat(se),r.quaternion.copy(se).multiply(B).multiply(se.invert()),B.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(r.quaternion).multiply(B).premultiply(B.invert()).multiply(this._restQuatLeftEye)),i&&(e<0?O.x=-S.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-e):O.x=S.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(e),t<0?O.y=-S.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(-t):O.y=S.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(t),B.setFromEuler(O),this._getWorldFaceFrontQuat(se),s.quaternion.copy(se).multiply(B).multiply(se.invert()),B.copy(this._restRightEyeParentWorldQuat),i.quaternion.copy(s.quaternion).multiply(B).premultiply(B.invert()).multiply(this._restQuatRightEye))}lookAt(t){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");let e=S.MathUtils.RAD2DEG*t.y,n=S.MathUtils.RAD2DEG*t.x;this.applyYawPitch(e,n)}_getWorldFaceFrontQuat(t){if(this.faceFront.distanceToSquared(Tr)<.01)return t.identity();let[e,n]=Le(this.faceFront);return O.set(0,.5*Math.PI+e,n,"YZX"),t.setFromEuler(O)}};He.type="bone";var qe=class{constructor(t,e,n,i,r){this.expressions=t,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=r}applyYawPitch(t,e){e<0?(this.expressions.setValue("lookDown",0),this.expressions.setValue("lookUp",this.rangeMapVerticalUp.map(-e))):(this.expressions.setValue("lookUp",0),this.expressions.setValue("lookDown",this.rangeMapVerticalDown.map(e))),t<0?(this.expressions.setValue("lookLeft",0),this.expressions.setValue("lookRight",this.rangeMapHorizontalOuter.map(-t))):(this.expressions.setValue("lookRight",0),this.expressions.setValue("lookLeft",this.rangeMapHorizontalOuter.map(t)))}lookAt(t){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");let e=Qe.MathUtils.RAD2DEG*t.y,n=Qe.MathUtils.RAD2DEG*t.x;this.applyYawPitch(e,n)}};qe.type="expression";var En=class{constructor(t,e){this.inputMaxValue=t,this.outputScale=e}map(t){return this.outputScale*Tn(t/this.inputMaxValue)}},xr=new Set(["1.0","1.0-beta"]),Ae=.01,et=class{get name(){return"VRMLookAtLoaderPlugin"}constructor(t,e){this.parser=t,this.helperRoot=e==null?void 0:e.helperRoot}afterRoot(t){return y(this,null,function*(){let e=t.userData.vrmHumanoid;if(e===null)return;if(e===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");let n=t.userData.vrmExpressionManager;if(n!==null){if(n===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first");t.userData.vrmLookAt=yield this._import(t,e,n)}})}_import(t,e,n){return y(this,null,function*(){if(e==null||n==null)return null;let i=yield this._v1Import(t,e,n);if(i)return i;let r=yield this._v0Import(t,e,n);return r||null})}_v1Import(t,e,n){return y(this,null,function*(){var i,r,s;let a=this.parser.json;if(!(((i=a.extensionsUsed)==null?void 0:i.indexOf("VRMC_vrm"))!==-1))return null;let o=(r=a.extensions)==null?void 0:r.VRMC_vrm;if(!o)return null;let u=o.specVersion;if(!xr.has(u))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${u}"`),null;let d=o.lookAt;if(!d)return null;let c=d.type==="expression"?1:10,f=this._v1ImportRangeMap(d.rangeMapHorizontalInner,c),m=this._v1ImportRangeMap(d.rangeMapHorizontalOuter,c),p=this._v1ImportRangeMap(d.rangeMapVerticalDown,c),h=this._v1ImportRangeMap(d.rangeMapVerticalUp,c),_;d.type==="expression"?_=new qe(n,f,m,p,h):_=new He(e,f,m,p,h);let g=this._importLookAt(e,_);return g.offsetFromHeadBone.fromArray((s=d.offsetFromHeadBone)!=null?s:[0,.06,0]),g})}_v1ImportRangeMap(t,e){var n,i;let r=(n=t==null?void 0:t.inputMaxValue)!=null?n:90,s=(i=t==null?void 0:t.outputScale)!=null?i:e;return r<Ae&&(console.warn("VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!"),r=Ae),new En(r,s)}_v0Import(t,e,n){return y(this,null,function*(){var i,r,s,a;let o=(i=this.parser.json.extensions)==null?void 0:i.VRM;if(!o)return null;let u=o.firstPerson;if(!u)return null;let d=u.lookAtTypeName==="BlendShape"?1:10,c=this._v0ImportDegreeMap(u.lookAtHorizontalInner,d),f=this._v0ImportDegreeMap(u.lookAtHorizontalOuter,d),m=this._v0ImportDegreeMap(u.lookAtVerticalDown,d),p=this._v0ImportDegreeMap(u.lookAtVerticalUp,d),h;u.lookAtTypeName==="BlendShape"?h=new qe(n,c,f,m,p):h=new He(e,c,f,m,p);let _=this._importLookAt(e,h);return u.firstPersonBoneOffset?_.offsetFromHeadBone.set((r=u.firstPersonBoneOffset.x)!=null?r:0,(s=u.firstPersonBoneOffset.y)!=null?s:.06,-((a=u.firstPersonBoneOffset.z)!=null?a:0)):_.offsetFromHeadBone.set(0,.06,0),_.faceFront.set(0,0,-1),h instanceof He&&h.faceFront.set(0,0,-1),_})}_v0ImportDegreeMap(t,e){var n,i;let r=t==null?void 0:t.curve;JSON.stringify(r)!=="[0,0,0,1,1,1,1,0]"&&console.warn("Curves of LookAtDegreeMap defined in VRM 0.0 are not supported");let s=(n=t==null?void 0:t.xRange)!=null?n:90,a=(i=t==null?void 0:t.yRange)!=null?i:e;return s<Ae&&(console.warn("VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!"),s=Ae),new En(s,a)}_importLookAt(t,e){let n=new Rr(t,e);if(this.helperRoot){let i=new mr(n);this.helperRoot.add(i),i.renderOrder=this.helperRoot.renderOrder}return n}},Uo={Bone:"bone",Expression:"expression"};function yr(t,e){return typeof t!="string"||t===""?"":(/^https?:\/\//i.test(e)&&/^\//.test(t)&&(e=e.replace(/(^https?:\/\/[^/]+).*/i,"$1")),/^(https?:)?\/\//i.test(t)||/^data:.*,.*$/i.test(t)||/^blob:.*$/i.test(t)?t:e+t)}var wr=new Set(["1.0","1.0-beta"]),tt=class{get name(){return"VRMMetaLoaderPlugin"}constructor(t,e){var n,i,r;this.parser=t,this.needThumbnailImage=(n=e==null?void 0:e.needThumbnailImage)!=null?n:!1,this.acceptLicenseUrls=(i=e==null?void 0:e.acceptLicenseUrls)!=null?i:["https://vrm.dev/licenses/1.0/"],this.acceptV0Meta=(r=e==null?void 0:e.acceptV0Meta)!=null?r:!0}afterRoot(t){return y(this,null,function*(){t.userData.vrmMeta=yield this._import(t)})}_import(t){return y(this,null,function*(){let e=yield this._v1Import(t);if(e!=null)return e;let n=yield this._v0Import(t);return n!=null?n:null})}_v1Import(t){return y(this,null,function*(){var e,n,i;let r=this.parser.json;if(!(((e=r.extensionsUsed)==null?void 0:e.indexOf("VRMC_vrm"))!==-1))return null;let a=(n=r.extensions)==null?void 0:n.VRMC_vrm;if(a==null)return null;let l=a.specVersion;if(!wr.has(l))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${l}"`),null;let o=a.meta;if(!o)return null;let u=o.licenseUrl;if(!new Set(this.acceptLicenseUrls).has(u))throw new Error(`VRMMetaLoaderPlugin: The license url "${u}" is not accepted`);let c;return this.needThumbnailImage&&o.thumbnailImage!=null&&(c=(i=yield this._extractGLTFImage(o.thumbnailImage))!=null?i:void 0),{metaVersion:"1",name:o.name,version:o.version,authors:o.authors,copyrightInformation:o.copyrightInformation,contactInformation:o.contactInformation,references:o.references,thirdPartyLicenses:o.thirdPartyLicenses,thumbnailImage:c,licenseUrl:o.licenseUrl,avatarPermission:o.avatarPermission,allowExcessivelyViolentUsage:o.allowExcessivelyViolentUsage,allowExcessivelySexualUsage:o.allowExcessivelySexualUsage,commercialUsage:o.commercialUsage,allowPoliticalOrReligiousUsage:o.allowPoliticalOrReligiousUsage,allowAntisocialOrHateUsage:o.allowAntisocialOrHateUsage,creditNotation:o.creditNotation,allowRedistribution:o.allowRedistribution,modification:o.modification,otherLicenseUrl:o.otherLicenseUrl}})}_v0Import(t){return y(this,null,function*(){var e;let i=(e=this.parser.json.extensions)==null?void 0:e.VRM;if(!i)return null;let r=i.meta;if(!r)return null;if(!this.acceptV0Meta)throw new Error("VRMMetaLoaderPlugin: Attempted to load VRM0.0 meta but acceptV0Meta is false");let s;return this.needThumbnailImage&&r.texture!=null&&r.texture!==-1&&(s=yield this.parser.getDependency("texture",r.texture)),{metaVersion:"0",allowedUserName:r.allowedUserName,author:r.author,commercialUssageName:r.commercialUssageName,contactInformation:r.contactInformation,licenseName:r.licenseName,otherLicenseUrl:r.otherLicenseUrl,otherPermissionUrl:r.otherPermissionUrl,reference:r.reference,sexualUssageName:r.sexualUssageName,texture:s!=null?s:void 0,title:r.title,version:r.version,violentUssageName:r.violentUssageName}})}_extractGLTFImage(t){return y(this,null,function*(){var e;let i=(e=this.parser.json.images)==null?void 0:e[t];if(i==null)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${t}] of glTF as a thumbnail but the image doesn't exist`),null;let r=i.uri;if(i.bufferView!=null){let a=yield this.parser.getDependency("bufferView",i.bufferView),l=new Blob([a],{type:i.mimeType});r=URL.createObjectURL(l)}return r==null?(console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${t}] of glTF as a thumbnail but the image couldn't load properly`),null):yield new On.ImageLoader().loadAsync(yr(r,this.parser.options.path)).catch(a=>(console.error(a),console.warn("VRMMetaLoaderPlugin: Failed to load a thumbnail image"),null))})}},nt=class{constructor(t){this.scene=t.scene,this.meta=t.meta,this.humanoid=t.humanoid,this.expressionManager=t.expressionManager,this.firstPerson=t.firstPerson,this.lookAt=t.lookAt}update(t){this.humanoid.update(),this.lookAt&&this.lookAt.update(t),this.expressionManager&&this.expressionManager.update()}},Co=class{get name(){return"VRMC_vrm"}constructor(t,e){var n,i,r,s,a;this.parser=t;let l=e==null?void 0:e.helperRoot,o=e==null?void 0:e.autoUpdateHumanBones;this.expressionPlugin=(n=e==null?void 0:e.expressionPlugin)!=null?n:new Ye(t),this.firstPersonPlugin=(i=e==null?void 0:e.firstPersonPlugin)!=null?i:new Ze(t),this.humanoidPlugin=(r=e==null?void 0:e.humanoidPlugin)!=null?r:new Je(t,{helperRoot:l,autoUpdateHumanBones:o}),this.lookAtPlugin=(s=e==null?void 0:e.lookAtPlugin)!=null?s:new et(t,{helperRoot:l}),this.metaPlugin=(a=e==null?void 0:e.metaPlugin)!=null?a:new tt(t)}afterRoot(t){return y(this,null,function*(){yield this.metaPlugin.afterRoot(t),yield this.humanoidPlugin.afterRoot(t),yield this.expressionPlugin.afterRoot(t),yield this.lookAtPlugin.afterRoot(t),yield this.firstPersonPlugin.afterRoot(t);let e=t.userData.vrmMeta,n=t.userData.vrmHumanoid;if(e&&n){let i=new nt({scene:t.scene,expressionManager:t.userData.vrmExpressionManager,firstPerson:t.userData.vrmFirstPerson,humanoid:n,lookAt:t.userData.vrmLookAt,meta:e});t.userData.vrmCore=i}})}};var ge=class extends nt{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach(n=>{n.update&&n.update(e)})}};import*as Ie from"three";import*as Fn from"three";import*as Wn from"three";import*as w from"three";import*as kn from"three";var Pr=Object.defineProperty,Nn=Object.getOwnPropertySymbols,Sr=Object.prototype.hasOwnProperty,Ar=Object.prototype.propertyIsEnumerable,Dn=(t,e,n)=>e in t?Pr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Bn=(t,e)=>{for(var n in e||(e={}))Sr.call(e,n)&&Dn(t,n,e[n]);if(Nn)for(var n of Nn(e))Ar.call(e,n)&&Dn(t,n,e[n]);return t},te=(t,e,n)=>new Promise((i,r)=>{var s=o=>{try{l(n.next(o))}catch(u){r(u)}},a=o=>{try{l(n.throw(o))}catch(u){r(u)}},l=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);l((n=n.apply(t,e)).next())}),Lr={"":3e3,srgb:3001};function Hr(t,e){parseInt(Wn.REVISION,10)>=152?t.colorSpace=e:t.encoding=Lr[e]}var br=class{get pending(){return Promise.all(this._pendings)}constructor(t,e){this._parser=t,this._materialParams=e,this._pendings=[]}assignPrimitive(t,e){e!=null&&(this._materialParams[t]=e)}assignColor(t,e,n){e!=null&&(this._materialParams[t]=new Fn.Color().fromArray(e),n&&this._materialParams[t].convertSRGBToLinear())}assignTexture(t,e,n){return te(this,null,function*(){let i=te(this,null,function*(){e!=null&&(yield this._parser.assignTexture(this._materialParams,t,e),n&&Hr(this._materialParams[t],"srgb"))});return this._pendings.push(i),i})}assignTextureByIndex(t,e,n){return te(this,null,function*(){return this.assignTexture(t,e!=null?{index:e}:void 0,n)})}},Vr=`// #define PHONG
3
+
4
+ varying vec3 vViewPosition;
5
+
6
+ #ifndef FLAT_SHADED
7
+ varying vec3 vNormal;
8
+ #endif
9
+
10
+ #include <common>
11
+
12
+ // #include <uv_pars_vertex>
13
+ #ifdef MTOON_USE_UV
14
+ varying vec2 vUv;
15
+
16
+ // COMPAT: pre-r151 uses a common uvTransform
17
+ #if THREE_VRM_THREE_REVISION < 151
18
+ uniform mat3 uvTransform;
19
+ #endif
20
+ #endif
21
+
22
+ // #include <uv2_pars_vertex>
23
+ // COMAPT: pre-r151 uses uv2 for lightMap and aoMap
24
+ #if THREE_VRM_THREE_REVISION < 151
25
+ #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )
26
+ attribute vec2 uv2;
27
+ varying vec2 vUv2;
28
+ uniform mat3 uv2Transform;
29
+ #endif
30
+ #endif
31
+
32
+ // #include <displacementmap_pars_vertex>
33
+ // #include <envmap_pars_vertex>
34
+ #include <color_pars_vertex>
35
+ #include <fog_pars_vertex>
36
+ #include <morphtarget_pars_vertex>
37
+ #include <skinning_pars_vertex>
38
+ #include <shadowmap_pars_vertex>
39
+ #include <logdepthbuf_pars_vertex>
40
+ #include <clipping_planes_pars_vertex>
41
+
42
+ #ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE
43
+ uniform sampler2D outlineWidthMultiplyTexture;
44
+ uniform mat3 outlineWidthMultiplyTextureUvTransform;
45
+ #endif
46
+
47
+ uniform float outlineWidthFactor;
48
+
49
+ void main() {
50
+
51
+ // #include <uv_vertex>
52
+ #ifdef MTOON_USE_UV
53
+ // COMPAT: pre-r151 uses a common uvTransform
54
+ #if THREE_VRM_THREE_REVISION >= 151
55
+ vUv = uv;
56
+ #else
57
+ vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
58
+ #endif
59
+ #endif
60
+
61
+ // #include <uv2_vertex>
62
+ // COMAPT: pre-r151 uses uv2 for lightMap and aoMap
63
+ #if THREE_VRM_THREE_REVISION < 151
64
+ #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )
65
+ vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;
66
+ #endif
67
+ #endif
68
+
69
+ #include <color_vertex>
70
+
71
+ #include <beginnormal_vertex>
72
+ #include <morphnormal_vertex>
73
+ #include <skinbase_vertex>
74
+ #include <skinnormal_vertex>
75
+
76
+ // we need this to compute the outline properly
77
+ objectNormal = normalize( objectNormal );
78
+
79
+ #include <defaultnormal_vertex>
80
+
81
+ #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED
82
+ vNormal = normalize( transformedNormal );
83
+ #endif
84
+
85
+ #include <begin_vertex>
86
+
87
+ #include <morphtarget_vertex>
88
+ #include <skinning_vertex>
89
+ // #include <displacementmap_vertex>
90
+ #include <project_vertex>
91
+ #include <logdepthbuf_vertex>
92
+ #include <clipping_planes_vertex>
93
+
94
+ vViewPosition = - mvPosition.xyz;
95
+
96
+ float outlineTex = 1.0;
97
+
98
+ #ifdef OUTLINE
99
+ #ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE
100
+ vec2 outlineWidthMultiplyTextureUv = ( outlineWidthMultiplyTextureUvTransform * vec3( vUv, 1 ) ).xy;
101
+ outlineTex = texture2D( outlineWidthMultiplyTexture, outlineWidthMultiplyTextureUv ).g;
102
+ #endif
103
+
104
+ #ifdef OUTLINE_WIDTH_WORLD
105
+ float worldNormalLength = length( transformedNormal );
106
+ vec3 outlineOffset = outlineWidthFactor * outlineTex * worldNormalLength * objectNormal;
107
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 );
108
+ #endif
109
+
110
+ #ifdef OUTLINE_WIDTH_SCREEN
111
+ vec3 clipNormal = ( projectionMatrix * modelViewMatrix * vec4( objectNormal, 0.0 ) ).xyz;
112
+ vec2 projectedNormal = normalize( clipNormal.xy );
113
+ projectedNormal.x *= projectionMatrix[ 0 ].x / projectionMatrix[ 1 ].y;
114
+ gl_Position.xy += 2.0 * outlineWidthFactor * outlineTex * projectedNormal.xy;
115
+ #endif
116
+
117
+ gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic
118
+ #endif
119
+
120
+ #include <worldpos_vertex>
121
+ // #include <envmap_vertex>
122
+ #include <shadowmap_vertex>
123
+ #include <fog_vertex>
124
+
125
+ }`,Ir=`// #define PHONG
126
+
127
+ uniform vec3 litFactor;
128
+
129
+ uniform float opacity;
130
+
131
+ uniform vec3 shadeColorFactor;
132
+ #ifdef USE_SHADEMULTIPLYTEXTURE
133
+ uniform sampler2D shadeMultiplyTexture;
134
+ uniform mat3 shadeMultiplyTextureUvTransform;
135
+ #endif
136
+
137
+ uniform float shadingShiftFactor;
138
+ uniform float shadingToonyFactor;
139
+
140
+ #ifdef USE_SHADINGSHIFTTEXTURE
141
+ uniform sampler2D shadingShiftTexture;
142
+ uniform mat3 shadingShiftTextureUvTransform;
143
+ uniform float shadingShiftTextureScale;
144
+ #endif
145
+
146
+ uniform float giEqualizationFactor;
147
+
148
+ uniform vec3 parametricRimColorFactor;
149
+ #ifdef USE_RIMMULTIPLYTEXTURE
150
+ uniform sampler2D rimMultiplyTexture;
151
+ uniform mat3 rimMultiplyTextureUvTransform;
152
+ #endif
153
+ uniform float rimLightingMixFactor;
154
+ uniform float parametricRimFresnelPowerFactor;
155
+ uniform float parametricRimLiftFactor;
156
+
157
+ #ifdef USE_MATCAPTEXTURE
158
+ uniform vec3 matcapFactor;
159
+ uniform sampler2D matcapTexture;
160
+ uniform mat3 matcapTextureUvTransform;
161
+ #endif
162
+
163
+ uniform vec3 emissive;
164
+ uniform float emissiveIntensity;
165
+
166
+ uniform vec3 outlineColorFactor;
167
+ uniform float outlineLightingMixFactor;
168
+
169
+ #ifdef USE_UVANIMATIONMASKTEXTURE
170
+ uniform sampler2D uvAnimationMaskTexture;
171
+ uniform mat3 uvAnimationMaskTextureUvTransform;
172
+ #endif
173
+
174
+ uniform float uvAnimationScrollXOffset;
175
+ uniform float uvAnimationScrollYOffset;
176
+ uniform float uvAnimationRotationPhase;
177
+
178
+ #include <common>
179
+ #include <packing>
180
+ #include <dithering_pars_fragment>
181
+ #include <color_pars_fragment>
182
+
183
+ // #include <uv_pars_fragment>
184
+ #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )
185
+ varying vec2 vUv;
186
+ #endif
187
+
188
+ // #include <uv2_pars_fragment>
189
+ // COMAPT: pre-r151 uses uv2 for lightMap and aoMap
190
+ #if THREE_VRM_THREE_REVISION < 151
191
+ #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )
192
+ varying vec2 vUv2;
193
+ #endif
194
+ #endif
195
+
196
+ #include <map_pars_fragment>
197
+
198
+ #ifdef USE_MAP
199
+ uniform mat3 mapUvTransform;
200
+ #endif
201
+
202
+ // #include <alphamap_pars_fragment>
203
+
204
+ #include <alphatest_pars_fragment>
205
+
206
+ #include <aomap_pars_fragment>
207
+ // #include <lightmap_pars_fragment>
208
+ #include <emissivemap_pars_fragment>
209
+
210
+ #ifdef USE_EMISSIVEMAP
211
+ uniform mat3 emissiveMapUvTransform;
212
+ #endif
213
+
214
+ // #include <envmap_common_pars_fragment>
215
+ // #include <envmap_pars_fragment>
216
+ // #include <cube_uv_reflection_fragment>
217
+ #include <fog_pars_fragment>
218
+
219
+ // #include <bsdfs>
220
+ // COMPAT: pre-r151 doesn't have BRDF_Lambert in <common>
221
+ #if THREE_VRM_THREE_REVISION < 151
222
+ vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
223
+ return RECIPROCAL_PI * diffuseColor;
224
+ }
225
+ #endif
226
+
227
+ #include <lights_pars_begin>
228
+
229
+ #include <normal_pars_fragment>
230
+
231
+ // #include <lights_phong_pars_fragment>
232
+ varying vec3 vViewPosition;
233
+
234
+ struct MToonMaterial {
235
+ vec3 diffuseColor;
236
+ vec3 shadeColor;
237
+ float shadingShift;
238
+ };
239
+
240
+ float linearstep( float a, float b, float t ) {
241
+ return clamp( ( t - a ) / ( b - a ), 0.0, 1.0 );
242
+ }
243
+
244
+ /**
245
+ * Convert NdotL into toon shading factor using shadingShift and shadingToony
246
+ */
247
+ float getShading(
248
+ const in float dotNL,
249
+ const in float shadow,
250
+ const in float shadingShift
251
+ ) {
252
+ float shading = dotNL;
253
+ shading = shading + shadingShift;
254
+ shading = linearstep( -1.0 + shadingToonyFactor, 1.0 - shadingToonyFactor, shading );
255
+ shading *= shadow;
256
+ return shading;
257
+ }
258
+
259
+ /**
260
+ * Mix diffuseColor and shadeColor using shading factor and light color
261
+ */
262
+ vec3 getDiffuse(
263
+ const in MToonMaterial material,
264
+ const in float shading,
265
+ in vec3 lightColor
266
+ ) {
267
+ #ifdef DEBUG_LITSHADERATE
268
+ return vec3( BRDF_Lambert( shading * lightColor ) );
269
+ #endif
270
+
271
+ vec3 col = lightColor * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, shading ) );
272
+
273
+ // The "comment out if you want to PBR absolutely" line
274
+ #ifdef V0_COMPAT_SHADE
275
+ col = min( col, material.diffuseColor );
276
+ #endif
277
+
278
+ return col;
279
+ }
280
+
281
+ // COMPAT: pre-r156 uses a struct GeometricContext
282
+ #if THREE_VRM_THREE_REVISION >= 157
283
+ void RE_Direct_MToon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) {
284
+ float dotNL = clamp( dot( geometryNormal, directLight.direction ), -1.0, 1.0 );
285
+ vec3 irradiance = directLight.color;
286
+
287
+ // directSpecular will be used for rim lighting, not an actual specular
288
+ reflectedLight.directSpecular += irradiance;
289
+
290
+ irradiance *= dotNL;
291
+
292
+ float shading = getShading( dotNL, shadow, material.shadingShift );
293
+
294
+ // toon shaded diffuse
295
+ reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color );
296
+ }
297
+
298
+ void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, inout ReflectedLight reflectedLight ) {
299
+ // indirect diffuse will use diffuseColor, no shadeColor involved
300
+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
301
+
302
+ // directSpecular will be used for rim lighting, not an actual specular
303
+ reflectedLight.directSpecular += irradiance;
304
+ }
305
+ #else
306
+ void RE_Direct_MToon( const in IncidentLight directLight, const in GeometricContext geometry, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) {
307
+ float dotNL = clamp( dot( geometry.normal, directLight.direction ), -1.0, 1.0 );
308
+ vec3 irradiance = directLight.color;
309
+
310
+ // directSpecular will be used for rim lighting, not an actual specular
311
+ reflectedLight.directSpecular += irradiance;
312
+
313
+ irradiance *= dotNL;
314
+
315
+ float shading = getShading( dotNL, shadow, material.shadingShift );
316
+
317
+ // toon shaded diffuse
318
+ reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color );
319
+ }
320
+
321
+ void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in GeometricContext geometry, const in MToonMaterial material, inout ReflectedLight reflectedLight ) {
322
+ // indirect diffuse will use diffuseColor, no shadeColor involved
323
+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
324
+
325
+ // directSpecular will be used for rim lighting, not an actual specular
326
+ reflectedLight.directSpecular += irradiance;
327
+ }
328
+ #endif
329
+
330
+ #define RE_Direct RE_Direct_MToon
331
+ #define RE_IndirectDiffuse RE_IndirectDiffuse_MToon
332
+ #define Material_LightProbeLOD( material ) (0)
333
+
334
+ #include <shadowmap_pars_fragment>
335
+ // #include <bumpmap_pars_fragment>
336
+
337
+ // #include <normalmap_pars_fragment>
338
+ #ifdef USE_NORMALMAP
339
+
340
+ uniform sampler2D normalMap;
341
+ uniform mat3 normalMapUvTransform;
342
+ uniform vec2 normalScale;
343
+
344
+ #endif
345
+
346
+ // COMPAT: pre-r151
347
+ // USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151
348
+ #if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP )
349
+
350
+ uniform mat3 normalMatrix;
351
+
352
+ #endif
353
+
354
+ // COMPAT: pre-r151
355
+ // USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151
356
+ #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( TANGENTSPACE_NORMALMAP ) )
357
+
358
+ // Per-Pixel Tangent Space Normal Mapping
359
+ // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
360
+
361
+ // three-vrm specific change: it requires \`uv\` as an input in order to support uv scrolls
362
+
363
+ // Temporary compat against shader change @ Three.js r126, r151
364
+ #if THREE_VRM_THREE_REVISION >= 151
365
+
366
+ mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
367
+
368
+ vec3 q0 = dFdx( eye_pos.xyz );
369
+ vec3 q1 = dFdy( eye_pos.xyz );
370
+ vec2 st0 = dFdx( uv.st );
371
+ vec2 st1 = dFdy( uv.st );
372
+
373
+ vec3 N = surf_norm;
374
+
375
+ vec3 q1perp = cross( q1, N );
376
+ vec3 q0perp = cross( N, q0 );
377
+
378
+ vec3 T = q1perp * st0.x + q0perp * st1.x;
379
+ vec3 B = q1perp * st0.y + q0perp * st1.y;
380
+
381
+ float det = max( dot( T, T ), dot( B, B ) );
382
+ float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
383
+
384
+ return mat3( T * scale, B * scale, N );
385
+
386
+ }
387
+
388
+ #else
389
+
390
+ vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {
391
+
392
+ vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );
393
+ vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );
394
+ vec2 st0 = dFdx( uv.st );
395
+ vec2 st1 = dFdy( uv.st );
396
+
397
+ vec3 N = normalize( surf_norm );
398
+
399
+ vec3 q1perp = cross( q1, N );
400
+ vec3 q0perp = cross( N, q0 );
401
+
402
+ vec3 T = q1perp * st0.x + q0perp * st1.x;
403
+ vec3 B = q1perp * st0.y + q0perp * st1.y;
404
+
405
+ // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0
406
+ // TODO: Is this still required? Or shall I make a PR about it?
407
+ if ( length( T ) == 0.0 || length( B ) == 0.0 ) {
408
+ return surf_norm;
409
+ }
410
+
411
+ float det = max( dot( T, T ), dot( B, B ) );
412
+ float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );
413
+
414
+ return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );
415
+
416
+ }
417
+
418
+ #endif
419
+
420
+ #endif
421
+
422
+ // #include <specularmap_pars_fragment>
423
+ #include <logdepthbuf_pars_fragment>
424
+ #include <clipping_planes_pars_fragment>
425
+
426
+ // == post correction ==========================================================
427
+ void postCorrection() {
428
+ #include <tonemapping_fragment>
429
+ #include <colorspace_fragment>
430
+ #include <fog_fragment>
431
+ #include <premultiplied_alpha_fragment>
432
+ #include <dithering_fragment>
433
+ }
434
+
435
+ // == main procedure ===========================================================
436
+ void main() {
437
+ #include <clipping_planes_fragment>
438
+
439
+ vec2 uv = vec2(0.5, 0.5);
440
+
441
+ #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )
442
+ uv = vUv;
443
+
444
+ float uvAnimMask = 1.0;
445
+ #ifdef USE_UVANIMATIONMASKTEXTURE
446
+ vec2 uvAnimationMaskTextureUv = ( uvAnimationMaskTextureUvTransform * vec3( uv, 1 ) ).xy;
447
+ uvAnimMask = texture2D( uvAnimationMaskTexture, uvAnimationMaskTextureUv ).b;
448
+ #endif
449
+
450
+ float uvRotCos = cos( uvAnimationRotationPhase * uvAnimMask );
451
+ float uvRotSin = sin( uvAnimationRotationPhase * uvAnimMask );
452
+ uv = mat2( uvRotCos, -uvRotSin, uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5;
453
+ uv = uv + vec2( uvAnimationScrollXOffset, uvAnimationScrollYOffset ) * uvAnimMask;
454
+ #endif
455
+
456
+ #ifdef DEBUG_UV
457
+ gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
458
+ #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )
459
+ gl_FragColor = vec4( uv, 0.0, 1.0 );
460
+ #endif
461
+ return;
462
+ #endif
463
+
464
+ vec4 diffuseColor = vec4( litFactor, opacity );
465
+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
466
+ vec3 totalEmissiveRadiance = emissive * emissiveIntensity;
467
+
468
+ #include <logdepthbuf_fragment>
469
+
470
+ // #include <map_fragment>
471
+ #ifdef USE_MAP
472
+ vec2 mapUv = ( mapUvTransform * vec3( uv, 1 ) ).xy;
473
+ vec4 sampledDiffuseColor = texture2D( map, mapUv );
474
+ #ifdef DECODE_VIDEO_TEXTURE
475
+ sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );
476
+ #endif
477
+ diffuseColor *= sampledDiffuseColor;
478
+ #endif
479
+
480
+ // #include <color_fragment>
481
+ #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )
482
+ diffuseColor.rgb *= vColor;
483
+ #endif
484
+
485
+ // #include <alphamap_fragment>
486
+
487
+ #include <alphatest_fragment>
488
+
489
+ // #include <specularmap_fragment>
490
+
491
+ // #include <normal_fragment_begin>
492
+ float faceDirection = gl_FrontFacing ? 1.0 : -1.0;
493
+
494
+ #ifdef FLAT_SHADED
495
+
496
+ vec3 fdx = dFdx( vViewPosition );
497
+ vec3 fdy = dFdy( vViewPosition );
498
+ vec3 normal = normalize( cross( fdx, fdy ) );
499
+
500
+ #else
501
+
502
+ vec3 normal = normalize( vNormal );
503
+
504
+ #ifdef DOUBLE_SIDED
505
+
506
+ normal *= faceDirection;
507
+
508
+ #endif
509
+
510
+ #endif
511
+
512
+ #ifdef USE_NORMALMAP
513
+
514
+ vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy;
515
+
516
+ #endif
517
+
518
+ #ifdef USE_NORMALMAP_TANGENTSPACE
519
+
520
+ #ifdef USE_TANGENT
521
+
522
+ mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
523
+
524
+ #else
525
+
526
+ mat3 tbn = getTangentFrame( - vViewPosition, normal, normalMapUv );
527
+
528
+ #endif
529
+
530
+ #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
531
+
532
+ tbn[0] *= faceDirection;
533
+ tbn[1] *= faceDirection;
534
+
535
+ #endif
536
+
537
+ #endif
538
+
539
+ #ifdef USE_CLEARCOAT_NORMALMAP
540
+
541
+ #ifdef USE_TANGENT
542
+
543
+ mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
544
+
545
+ #else
546
+
547
+ mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
548
+
549
+ #endif
550
+
551
+ #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
552
+
553
+ tbn2[0] *= faceDirection;
554
+ tbn2[1] *= faceDirection;
555
+
556
+ #endif
557
+
558
+ #endif
559
+
560
+ // non perturbed normal for clearcoat among others
561
+
562
+ vec3 nonPerturbedNormal = normal;
563
+
564
+ #ifdef OUTLINE
565
+ normal *= -1.0;
566
+ #endif
567
+
568
+ // #include <normal_fragment_maps>
569
+
570
+ // COMPAT: pre-r151
571
+ // USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151
572
+ #if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP )
573
+
574
+ normal = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals
575
+
576
+ #ifdef FLIP_SIDED
577
+
578
+ normal = - normal;
579
+
580
+ #endif
581
+
582
+ #ifdef DOUBLE_SIDED
583
+
584
+ normal = normal * faceDirection;
585
+
586
+ #endif
587
+
588
+ normal = normalize( normalMatrix * normal );
589
+
590
+ // COMPAT: pre-r151
591
+ // USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151
592
+ #elif defined( USE_NORMALMAP_TANGENTSPACE ) || defined( TANGENTSPACE_NORMALMAP )
593
+
594
+ vec3 mapN = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0;
595
+ mapN.xy *= normalScale;
596
+
597
+ // COMPAT: pre-r151
598
+ #if THREE_VRM_THREE_REVISION >= 151 || defined( USE_TANGENT )
599
+
600
+ normal = normalize( tbn * mapN );
601
+
602
+ #else
603
+
604
+ normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection );
605
+
606
+ #endif
607
+
608
+ #endif
609
+
610
+ // #include <emissivemap_fragment>
611
+ #ifdef USE_EMISSIVEMAP
612
+ vec2 emissiveMapUv = ( emissiveMapUvTransform * vec3( uv, 1 ) ).xy;
613
+ totalEmissiveRadiance *= texture2D( emissiveMap, emissiveMapUv ).rgb;
614
+ #endif
615
+
616
+ #ifdef DEBUG_NORMAL
617
+ gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 );
618
+ return;
619
+ #endif
620
+
621
+ // -- MToon: lighting --------------------------------------------------------
622
+ // accumulation
623
+ // #include <lights_phong_fragment>
624
+ MToonMaterial material;
625
+
626
+ material.diffuseColor = diffuseColor.rgb;
627
+
628
+ material.shadeColor = shadeColorFactor;
629
+ #ifdef USE_SHADEMULTIPLYTEXTURE
630
+ vec2 shadeMultiplyTextureUv = ( shadeMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;
631
+ material.shadeColor *= texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv ).rgb;
632
+ #endif
633
+
634
+ #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )
635
+ material.shadeColor.rgb *= vColor;
636
+ #endif
637
+
638
+ material.shadingShift = shadingShiftFactor;
639
+ #ifdef USE_SHADINGSHIFTTEXTURE
640
+ vec2 shadingShiftTextureUv = ( shadingShiftTextureUvTransform * vec3( uv, 1 ) ).xy;
641
+ material.shadingShift += texture2D( shadingShiftTexture, shadingShiftTextureUv ).r * shadingShiftTextureScale;
642
+ #endif
643
+
644
+ // #include <lights_fragment_begin>
645
+
646
+ // MToon Specific changes:
647
+ // Since we want to take shadows into account of shading instead of irradiance,
648
+ // we had to modify the codes that multiplies the results of shadowmap into color of direct lights.
649
+
650
+ // COMPAT: pre-r156 uses a struct GeometricContext
651
+ #if THREE_VRM_THREE_REVISION >= 157
652
+ vec3 geometryPosition = - vViewPosition;
653
+ vec3 geometryNormal = normal;
654
+ vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
655
+
656
+ vec3 geometryClearcoatNormal;
657
+
658
+ #ifdef USE_CLEARCOAT
659
+
660
+ geometryClearcoatNormal = clearcoatNormal;
661
+
662
+ #endif
663
+ #else
664
+ GeometricContext geometry;
665
+
666
+ geometry.position = - vViewPosition;
667
+ geometry.normal = normal;
668
+ geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
669
+
670
+ #ifdef USE_CLEARCOAT
671
+
672
+ geometry.clearcoatNormal = clearcoatNormal;
673
+
674
+ #endif
675
+ #endif
676
+
677
+ IncidentLight directLight;
678
+
679
+ // since these variables will be used in unrolled loop, we have to define in prior
680
+ float shadow;
681
+
682
+ #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
683
+
684
+ PointLight pointLight;
685
+ #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
686
+ PointLightShadow pointLightShadow;
687
+ #endif
688
+
689
+ #pragma unroll_loop_start
690
+ for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
691
+
692
+ pointLight = pointLights[ i ];
693
+
694
+ // COMPAT: pre-r156 uses a struct GeometricContext
695
+ #if THREE_VRM_THREE_REVISION >= 157
696
+ getPointLightInfo( pointLight, geometryPosition, directLight );
697
+ #else
698
+ getPointLightInfo( pointLight, geometry, directLight );
699
+ #endif
700
+
701
+ shadow = 1.0;
702
+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
703
+ pointLightShadow = pointLightShadows[ i ];
704
+ shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
705
+ #endif
706
+
707
+ // COMPAT: pre-r156 uses a struct GeometricContext
708
+ #if THREE_VRM_THREE_REVISION >= 157
709
+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );
710
+ #else
711
+ RE_Direct( directLight, geometry, material, shadow, reflectedLight );
712
+ #endif
713
+
714
+ }
715
+ #pragma unroll_loop_end
716
+
717
+ #endif
718
+
719
+ #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
720
+
721
+ SpotLight spotLight;
722
+ #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
723
+ SpotLightShadow spotLightShadow;
724
+ #endif
725
+
726
+ #pragma unroll_loop_start
727
+ for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
728
+
729
+ spotLight = spotLights[ i ];
730
+
731
+ // COMPAT: pre-r156 uses a struct GeometricContext
732
+ #if THREE_VRM_THREE_REVISION >= 157
733
+ getSpotLightInfo( spotLight, geometryPosition, directLight );
734
+ #else
735
+ getSpotLightInfo( spotLight, geometry, directLight );
736
+ #endif
737
+
738
+ shadow = 1.0;
739
+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
740
+ spotLightShadow = spotLightShadows[ i ];
741
+ shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;
742
+ #endif
743
+
744
+ // COMPAT: pre-r156 uses a struct GeometricContext
745
+ #if THREE_VRM_THREE_REVISION >= 157
746
+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );
747
+ #else
748
+ RE_Direct( directLight, geometry, material, shadow, reflectedLight );
749
+ #endif
750
+
751
+ }
752
+ #pragma unroll_loop_end
753
+
754
+ #endif
755
+
756
+ #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
757
+
758
+ DirectionalLight directionalLight;
759
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
760
+ DirectionalLightShadow directionalLightShadow;
761
+ #endif
762
+
763
+ #pragma unroll_loop_start
764
+ for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
765
+
766
+ directionalLight = directionalLights[ i ];
767
+
768
+ // COMPAT: pre-r156 uses a struct GeometricContext
769
+ #if THREE_VRM_THREE_REVISION >= 157
770
+ getDirectionalLightInfo( directionalLight, directLight );
771
+ #else
772
+ getDirectionalLightInfo( directionalLight, geometry, directLight );
773
+ #endif
774
+
775
+ shadow = 1.0;
776
+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
777
+ directionalLightShadow = directionalLightShadows[ i ];
778
+ shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
779
+ #endif
780
+
781
+ // COMPAT: pre-r156 uses a struct GeometricContext
782
+ #if THREE_VRM_THREE_REVISION >= 157
783
+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );
784
+ #else
785
+ RE_Direct( directLight, geometry, material, shadow, reflectedLight );
786
+ #endif
787
+
788
+ }
789
+ #pragma unroll_loop_end
790
+
791
+ #endif
792
+
793
+ // #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
794
+
795
+ // RectAreaLight rectAreaLight;
796
+
797
+ // #pragma unroll_loop_start
798
+ // for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
799
+
800
+ // rectAreaLight = rectAreaLights[ i ];
801
+ // RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );
802
+
803
+ // }
804
+ // #pragma unroll_loop_end
805
+
806
+ // #endif
807
+
808
+ #if defined( RE_IndirectDiffuse )
809
+
810
+ vec3 iblIrradiance = vec3( 0.0 );
811
+
812
+ vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
813
+
814
+ // COMPAT: pre-r156 uses a struct GeometricContext
815
+ // COMPAT: pre-r156 doesn't have a define USE_LIGHT_PROBES
816
+ #if THREE_VRM_THREE_REVISION >= 157
817
+ #if defined( USE_LIGHT_PROBES )
818
+ irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
819
+ #endif
820
+ #else
821
+ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
822
+ #endif
823
+
824
+ #if ( NUM_HEMI_LIGHTS > 0 )
825
+
826
+ #pragma unroll_loop_start
827
+ for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
828
+
829
+ // COMPAT: pre-r156 uses a struct GeometricContext
830
+ #if THREE_VRM_THREE_REVISION >= 157
831
+ irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
832
+ #else
833
+ irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );
834
+ #endif
835
+
836
+ }
837
+ #pragma unroll_loop_end
838
+
839
+ #endif
840
+
841
+ #endif
842
+
843
+ // #if defined( RE_IndirectSpecular )
844
+
845
+ // vec3 radiance = vec3( 0.0 );
846
+ // vec3 clearcoatRadiance = vec3( 0.0 );
847
+
848
+ // #endif
849
+
850
+ #include <lights_fragment_maps>
851
+ #include <lights_fragment_end>
852
+
853
+ // modulation
854
+ #include <aomap_fragment>
855
+
856
+ vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
857
+
858
+ #ifdef DEBUG_LITSHADERATE
859
+ gl_FragColor = vec4( col, diffuseColor.a );
860
+ postCorrection();
861
+ return;
862
+ #endif
863
+
864
+ // -- MToon: rim lighting -----------------------------------------
865
+ vec3 viewDir = normalize( vViewPosition );
866
+
867
+ #ifndef PHYSICALLY_CORRECT_LIGHTS
868
+ reflectedLight.directSpecular /= PI;
869
+ #endif
870
+ vec3 rimMix = mix( vec3( 1.0 ), reflectedLight.directSpecular, 1.0 );
871
+
872
+ vec3 rim = parametricRimColorFactor * pow( saturate( 1.0 - dot( viewDir, normal ) + parametricRimLiftFactor ), parametricRimFresnelPowerFactor );
873
+
874
+ #ifdef USE_MATCAPTEXTURE
875
+ {
876
+ vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) );
877
+ vec3 y = cross( viewDir, x ); // guaranteed to be normalized
878
+ vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) );
879
+ sphereUv = ( matcapTextureUvTransform * vec3( sphereUv, 1 ) ).xy;
880
+ vec3 matcap = texture2D( matcapTexture, sphereUv ).rgb;
881
+ rim += matcapFactor * matcap;
882
+ }
883
+ #endif
884
+
885
+ #ifdef USE_RIMMULTIPLYTEXTURE
886
+ vec2 rimMultiplyTextureUv = ( rimMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;
887
+ rim *= texture2D( rimMultiplyTexture, rimMultiplyTextureUv ).rgb;
888
+ #endif
889
+
890
+ col += rimMix * rim;
891
+
892
+ // -- MToon: Emission --------------------------------------------------------
893
+ col += totalEmissiveRadiance;
894
+
895
+ // #include <envmap_fragment>
896
+
897
+ // -- Almost done! -----------------------------------------------------------
898
+ #if defined( OUTLINE )
899
+ col = outlineColorFactor.rgb * mix( vec3( 1.0 ), col, outlineLightingMixFactor );
900
+ #endif
901
+
902
+ #ifdef OPAQUE
903
+ diffuseColor.a = 1.0;
904
+ #endif
905
+
906
+ gl_FragColor = vec4( col, diffuseColor.a );
907
+ postCorrection();
908
+ }
909
+ `,Ur={None:"none",Normal:"normal",LitShadeRate:"litShadeRate",UV:"uv"},it={None:"none",WorldCoordinates:"worldCoordinates",ScreenCoordinates:"screenCoordinates"},Cr={3e3:"",3001:"srgb"};function rt(t){return parseInt(kn.REVISION,10)>=152?t.colorSpace:Cr[t.encoding]}var Or=class extends w.ShaderMaterial{constructor(t={}){var e;super({vertexShader:Vr,fragmentShader:Ir}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=w.TangentSpaceNormalMap,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=Ur.None,this._outlineWidthMode=it.None,this._isOutline=!1,t.transparentWithZWrite&&(t.depthWrite=!0),delete t.transparentWithZWrite,t.fog=!0,t.lights=!0,t.clipping=!0,this.uniforms=w.UniformsUtils.merge([w.UniformsLib.common,w.UniformsLib.normalmap,w.UniformsLib.emissivemap,w.UniformsLib.fog,w.UniformsLib.lights,{litFactor:{value:new w.Color(1,1,1)},mapUvTransform:{value:new w.Matrix3},colorAlpha:{value:1},normalMapUvTransform:{value:new w.Matrix3},shadeColorFactor:{value:new w.Color(0,0,0)},shadeMultiplyTexture:{value:null},shadeMultiplyTextureUvTransform:{value:new w.Matrix3},shadingShiftFactor:{value:0},shadingShiftTexture:{value:null},shadingShiftTextureUvTransform:{value:new w.Matrix3},shadingShiftTextureScale:{value:1},shadingToonyFactor:{value:.9},giEqualizationFactor:{value:.9},matcapFactor:{value:new w.Color(1,1,1)},matcapTexture:{value:null},matcapTextureUvTransform:{value:new w.Matrix3},parametricRimColorFactor:{value:new w.Color(0,0,0)},rimMultiplyTexture:{value:null},rimMultiplyTextureUvTransform:{value:new w.Matrix3},rimLightingMixFactor:{value:1},parametricRimFresnelPowerFactor:{value:5},parametricRimLiftFactor:{value:0},emissive:{value:new w.Color(0,0,0)},emissiveIntensity:{value:1},emissiveMapUvTransform:{value:new w.Matrix3},outlineWidthMultiplyTexture:{value:null},outlineWidthMultiplyTextureUvTransform:{value:new w.Matrix3},outlineWidthFactor:{value:0},outlineColorFactor:{value:new w.Color(0,0,0)},outlineLightingMixFactor:{value:1},uvAnimationMaskTexture:{value:null},uvAnimationMaskTextureUvTransform:{value:new w.Matrix3},uvAnimationScrollXOffset:{value:0},uvAnimationScrollYOffset:{value:0},uvAnimationRotationPhase:{value:0}},(e=t.uniforms)!=null?e:{}]),this.setValues(t),this._uploadUniformsWorkaround(),this.customProgramCacheKey=()=>[...Object.entries(this._generateDefines()).map(([n,i])=>`${n}:${i}`),this.matcapTexture?`matcapTextureColorSpace:${rt(this.matcapTexture)}`:"",this.shadeMultiplyTexture?`shadeMultiplyTextureColorSpace:${rt(this.shadeMultiplyTexture)}`:"",this.rimMultiplyTexture?`rimMultiplyTextureColorSpace:${rt(this.rimMultiplyTexture)}`:""].join(","),this.onBeforeCompile=n=>{let i=parseInt(w.REVISION,10),r=Object.entries(Bn(Bn({},this._generateDefines()),this.defines)).filter(([s,a])=>!!a).map(([s,a])=>`#define ${s} ${a}`).join(`
910
+ `)+`
911
+ `;n.vertexShader=r+n.vertexShader,n.fragmentShader=r+n.fragmentShader,i<154&&(n.fragmentShader=n.fragmentShader.replace("#include <colorspace_fragment>","#include <encodings_fragment>"))}}get color(){return this.uniforms.litFactor.value}set color(t){this.uniforms.litFactor.value=t}get map(){return this.uniforms.map.value}set map(t){this.uniforms.map.value=t}get normalMap(){return this.uniforms.normalMap.value}set normalMap(t){this.uniforms.normalMap.value=t}get normalScale(){return this.uniforms.normalScale.value}set normalScale(t){this.uniforms.normalScale.value=t}get emissive(){return this.uniforms.emissive.value}set emissive(t){this.uniforms.emissive.value=t}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(t){this.uniforms.emissiveIntensity.value=t}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(t){this.uniforms.emissiveMap.value=t}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(t){this.uniforms.shadeColorFactor.value=t}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(t){this.uniforms.shadeMultiplyTexture.value=t}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(t){this.uniforms.shadingShiftFactor.value=t}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(t){this.uniforms.shadingShiftTexture.value=t}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(t){this.uniforms.shadingShiftTextureScale.value=t}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(t){this.uniforms.shadingToonyFactor.value=t}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(t){this.uniforms.giEqualizationFactor.value=t}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(t){this.uniforms.matcapFactor.value=t}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(t){this.uniforms.matcapTexture.value=t}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(t){this.uniforms.parametricRimColorFactor.value=t}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(t){this.uniforms.rimMultiplyTexture.value=t}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(t){this.uniforms.rimLightingMixFactor.value=t}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(t){this.uniforms.parametricRimFresnelPowerFactor.value=t}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(t){this.uniforms.parametricRimLiftFactor.value=t}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(t){this.uniforms.outlineWidthMultiplyTexture.value=t}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(t){this.uniforms.outlineWidthFactor.value=t}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(t){this.uniforms.outlineColorFactor.value=t}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(t){this.uniforms.outlineLightingMixFactor.value=t}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(t){this.uniforms.uvAnimationMaskTexture.value=t}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(t){this.uniforms.uvAnimationScrollXOffset.value=t}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(t){this.uniforms.uvAnimationScrollYOffset.value=t}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(t){this.uniforms.uvAnimationRotationPhase.value=t}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(t){this._ignoreVertexColor=t,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(t){this._v0CompatShade=t,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(t){this._debugMode=t,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(t){this._outlineWidthMode=t,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(t){this._isOutline=t,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(t){this._uploadUniformsWorkaround(),this._updateUVAnimation(t)}copy(t){return super.copy(t),this.map=t.map,this.normalMap=t.normalMap,this.emissiveMap=t.emissiveMap,this.shadeMultiplyTexture=t.shadeMultiplyTexture,this.shadingShiftTexture=t.shadingShiftTexture,this.matcapTexture=t.matcapTexture,this.rimMultiplyTexture=t.rimMultiplyTexture,this.outlineWidthMultiplyTexture=t.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=t.uvAnimationMaskTexture,this.normalMapType=t.normalMapType,this.uvAnimationScrollXSpeedFactor=t.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=t.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=t.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=t.ignoreVertexColor,this.v0CompatShade=t.v0CompatShade,this.debugMode=t.debugMode,this.outlineWidthMode=t.outlineWidthMode,this.isOutline=t.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(t){this.uniforms.uvAnimationScrollXOffset.value+=t*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=t*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=t*this.uvAnimationRotationSpeedFactor,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform),this.uniformsNeedUpdate=!0}_generateDefines(){let t=parseInt(w.REVISION,10),e=this.outlineWidthMultiplyTexture!==null,n=this.map!==null||this.normalMap!==null||this.emissiveMap!==null||this.shadeMultiplyTexture!==null||this.shadingShiftTexture!==null||this.rimMultiplyTexture!==null||this.uvAnimationMaskTexture!==null;return{THREE_VRM_THREE_REVISION:t,OUTLINE:this._isOutline,MTOON_USE_UV:e||n,MTOON_UVS_VERTEX_ONLY:e&&!n,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:this.shadeMultiplyTexture!==null,USE_SHADINGSHIFTTEXTURE:this.shadingShiftTexture!==null,USE_MATCAPTEXTURE:this.matcapTexture!==null,USE_RIMMULTIPLYTEXTURE:this.rimMultiplyTexture!==null,USE_OUTLINEWIDTHMULTIPLYTEXTURE:this._isOutline&&this.outlineWidthMultiplyTexture!==null,USE_UVANIMATIONMASKTEXTURE:this.uvAnimationMaskTexture!==null,IGNORE_VERTEX_COLOR:this._ignoreVertexColor===!0,DEBUG_NORMAL:this._debugMode==="normal",DEBUG_LITSHADERATE:this._debugMode==="litShadeRate",DEBUG_UV:this._debugMode==="uv",OUTLINE_WIDTH_WORLD:this._isOutline&&this._outlineWidthMode===it.WorldCoordinates,OUTLINE_WIDTH_SCREEN:this._isOutline&&this._outlineWidthMode===it.ScreenCoordinates}}_updateTextureMatrix(t,e){t.value&&(t.value.matrixAutoUpdate&&t.value.updateMatrix(),e.value.copy(t.value.matrix))}},Nr=new Set(["1.0","1.0-beta"]),zn=class Ve{get name(){return Ve.EXTENSION_NAME}constructor(e,n={}){var i,r,s,a;this.parser=e,this.materialType=(i=n.materialType)!=null?i:Or,this.renderOrderOffset=(r=n.renderOrderOffset)!=null?r:0,this.v0CompatShade=(s=n.v0CompatShade)!=null?s:!1,this.debugMode=(a=n.debugMode)!=null?a:"none",this._mToonMaterialSet=new Set}beforeRoot(){return te(this,null,function*(){this._removeUnlitExtensionIfMToonExists()})}afterRoot(e){return te(this,null,function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)})}getMaterialType(e){return this._getMToonExtension(e)?this.materialType:null}extendMaterialParams(e,n){let i=this._getMToonExtension(e);return i?this._extendMaterialParams(i,n):null}loadMesh(e){return te(this,null,function*(){var n;let i=this.parser,s=(n=i.json.meshes)==null?void 0:n[e];if(s==null)throw new Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);let a=s.primitives,l=yield i.loadMesh(e);if(a.length===1){let o=l,u=a[0].material;u!=null&&this._setupPrimitive(o,u)}else{let o=l;for(let u=0;u<a.length;u++){let d=o.children[u],c=a[u].material;c!=null&&this._setupPrimitive(d,c)}}return l})}_removeUnlitExtensionIfMToonExists(){let i=this.parser.json.materials;i==null||i.map((r,s)=>{var a;this._getMToonExtension(s)&&((a=r.extensions)!=null&&a.KHR_materials_unlit)&&delete r.extensions.KHR_materials_unlit})}_getMToonExtension(e){var n,i;let a=(n=this.parser.json.materials)==null?void 0:n[e];if(a==null){console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);return}let l=(i=a.extensions)==null?void 0:i[Ve.EXTENSION_NAME];if(l==null)return;let o=l.specVersion;if(!Nr.has(o)){console.warn(`MToonMaterialLoaderPlugin: Unknown ${Ve.EXTENSION_NAME} specVersion "${o}"`);return}return l}_extendMaterialParams(e,n){return te(this,null,function*(){var i;delete n.metalness,delete n.roughness;let r=new br(this.parser,n);r.assignPrimitive("transparentWithZWrite",e.transparentWithZWrite),r.assignColor("shadeColorFactor",e.shadeColorFactor),r.assignTexture("shadeMultiplyTexture",e.shadeMultiplyTexture,!0),r.assignPrimitive("shadingShiftFactor",e.shadingShiftFactor),r.assignTexture("shadingShiftTexture",e.shadingShiftTexture,!0),r.assignPrimitive("shadingShiftTextureScale",(i=e.shadingShiftTexture)==null?void 0:i.scale),r.assignPrimitive("shadingToonyFactor",e.shadingToonyFactor),r.assignPrimitive("giEqualizationFactor",e.giEqualizationFactor),r.assignColor("matcapFactor",e.matcapFactor),r.assignTexture("matcapTexture",e.matcapTexture,!0),r.assignColor("parametricRimColorFactor",e.parametricRimColorFactor),r.assignTexture("rimMultiplyTexture",e.rimMultiplyTexture,!0),r.assignPrimitive("rimLightingMixFactor",e.rimLightingMixFactor),r.assignPrimitive("parametricRimFresnelPowerFactor",e.parametricRimFresnelPowerFactor),r.assignPrimitive("parametricRimLiftFactor",e.parametricRimLiftFactor),r.assignPrimitive("outlineWidthMode",e.outlineWidthMode),r.assignPrimitive("outlineWidthFactor",e.outlineWidthFactor),r.assignTexture("outlineWidthMultiplyTexture",e.outlineWidthMultiplyTexture,!1),r.assignColor("outlineColorFactor",e.outlineColorFactor),r.assignPrimitive("outlineLightingMixFactor",e.outlineLightingMixFactor),r.assignTexture("uvAnimationMaskTexture",e.uvAnimationMaskTexture,!1),r.assignPrimitive("uvAnimationScrollXSpeedFactor",e.uvAnimationScrollXSpeedFactor),r.assignPrimitive("uvAnimationScrollYSpeedFactor",e.uvAnimationScrollYSpeedFactor),r.assignPrimitive("uvAnimationRotationSpeedFactor",e.uvAnimationRotationSpeedFactor),r.assignPrimitive("v0CompatShade",this.v0CompatShade),r.assignPrimitive("debugMode",this.debugMode),yield r.pending})}_setupPrimitive(e,n){let i=this._getMToonExtension(n);if(i){let r=this._parseRenderOrder(i);e.renderOrder=r+this.renderOrderOffset,this._generateOutline(e),this._addToMaterialSet(e);return}}_shouldGenerateOutline(e){return typeof e.outlineWidthMode=="string"&&e.outlineWidthMode!=="none"&&typeof e.outlineWidthFactor=="number"&&e.outlineWidthFactor>0}_generateOutline(e){let n=e.material;if(!(n instanceof Ie.Material)||!this._shouldGenerateOutline(n))return;e.material=[n];let i=n.clone();i.name+=" (Outline)",i.isOutline=!0,i.side=Ie.BackSide,e.material.push(i);let r=e.geometry,s=r.index?r.index.count:r.attributes.position.count/3;r.addGroup(0,s,0),r.addGroup(0,s,1)}_addToMaterialSet(e){let n=e.material,i=new Set;Array.isArray(n)?n.forEach(r=>i.add(r)):i.add(n);for(let r of i)this._mToonMaterialSet.add(r)}_parseRenderOrder(e){var n;return(e.transparentWithZWrite?0:19)+((n=e.renderQueueOffsetNumber)!=null?n:0)}};zn.EXTENSION_NAME="VRMC_materials_mtoon";var jn=zn;var Dr=(t,e,n)=>new Promise((i,r)=>{var s=o=>{try{l(n.next(o))}catch(u){r(u)}},a=o=>{try{l(n.throw(o))}catch(u){r(u)}},l=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);l((n=n.apply(t,e)).next())}),Gn=class ot{get name(){return ot.EXTENSION_NAME}constructor(e){this.parser=e}extendMaterialParams(e,n){return Dr(this,null,function*(){let i=this._getHDREmissiveMultiplierExtension(e);if(i==null)return;console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead.");let r=i.emissiveMultiplier;n.emissiveIntensity=r})}_getHDREmissiveMultiplierExtension(e){var n,i;let a=(n=this.parser.json.materials)==null?void 0:n[e];if(a==null){console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);return}let l=(i=a.extensions)==null?void 0:i[ot.EXTENSION_NAME];if(l!=null)return l}};Gn.EXTENSION_NAME="VRMC_materials_hdr_emissiveMultiplier";var Qn=Gn;import*as $n from"three";var Br=Object.defineProperty,Fr=Object.defineProperties,Wr=Object.getOwnPropertyDescriptors,qn=Object.getOwnPropertySymbols,kr=Object.prototype.hasOwnProperty,zr=Object.prototype.propertyIsEnumerable,Xn=(t,e,n)=>e in t?Br(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,F=(t,e)=>{for(var n in e||(e={}))kr.call(e,n)&&Xn(t,n,e[n]);if(qn)for(var n of qn(e))zr.call(e,n)&&Xn(t,n,e[n]);return t},Yn=(t,e)=>Fr(t,Wr(e)),jr=(t,e,n)=>new Promise((i,r)=>{var s=o=>{try{l(n.next(o))}catch(u){r(u)}},a=o=>{try{l(n.throw(o))}catch(u){r(u)}},l=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);l((n=n.apply(t,e)).next())});function le(t){return Math.pow(t,2.2)}var Zn=class{get name(){return"VRMMaterialsV0CompatPlugin"}constructor(t){var e;this.parser=t,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;let n=this.parser.json;n.extensionsUsed=(e=n.extensionsUsed)!=null?e:[],n.extensionsUsed.indexOf("KHR_texture_transform")===-1&&n.extensionsUsed.push("KHR_texture_transform")}beforeRoot(){return jr(this,null,function*(){var t;let e=this.parser.json,n=(t=e.extensions)==null?void 0:t.VRM,i=n==null?void 0:n.materialProperties;i&&(this._populateRenderQueueMap(i),i.forEach((r,s)=>{var a,l;let o=(a=e.materials)==null?void 0:a[s];if(o==null){console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${s}] of glTF but the material doesn't exist`);return}if(r.shader==="VRM/MToon"){let u=this._parseV0MToonProperties(r,o);e.materials[s]=u}else if((l=r.shader)!=null&&l.startsWith("VRM/Unlit")){let u=this._parseV0UnlitProperties(r,o);e.materials[s]=u}else r.shader==="VRM_USE_GLTFSHADER"||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${r.shader}`)}))})}_parseV0MToonProperties(t,e){var n,i,r,s,a,l,o,u,d,c,f,m,p,h,_,g,x,T,v,R,E,M,A,I,L,H,U,ce,ct,mt,pt,ft,_t,gt,vt,Et,Mt,Rt,Tt,xt,yt,wt,Pt,St,At,Lt,Ht,bt,Vt,It,Ut,Ct,Ot,Nt,Dt;let Bt=(i=(n=t.keywordMap)==null?void 0:n._ALPHABLEND_ON)!=null?i:!1,yi=((r=t.floatProperties)==null?void 0:r._ZWrite)===1&&Bt,wi=this._v0ParseRenderQueue(t),Ft=(a=(s=t.keywordMap)==null?void 0:s._ALPHATEST_ON)!=null?a:!1,Pi=Bt?"BLEND":Ft?"MASK":"OPAQUE",Si=Ft?(o=(l=t.floatProperties)==null?void 0:l._Cutoff)!=null?o:.5:void 0,Ai=((d=(u=t.floatProperties)==null?void 0:u._CullMode)!=null?d:2)===0,J=this._portTextureTransform(t),Li=((f=(c=t.vectorProperties)==null?void 0:c._Color)!=null?f:[1,1,1,1]).map((Yt,Ki)=>Ki===3?Yt:le(Yt)),Wt=(m=t.textureProperties)==null?void 0:m._MainTex,Hi=Wt!=null?{index:Wt,extensions:F({},J)}:void 0,bi=(h=(p=t.floatProperties)==null?void 0:p._BumpScale)!=null?h:1,kt=(_=t.textureProperties)==null?void 0:_._BumpMap,Vi=kt!=null?{index:kt,scale:bi,extensions:F({},J)}:void 0,Ii=((x=(g=t.vectorProperties)==null?void 0:g._EmissionColor)!=null?x:[0,0,0,1]).map(le),zt=(T=t.textureProperties)==null?void 0:T._EmissionMap,Ui=zt!=null?{index:zt,extensions:F({},J)}:void 0,Ci=((R=(v=t.vectorProperties)==null?void 0:v._ShadeColor)!=null?R:[.97,.81,.86,1]).map(le),jt=(E=t.textureProperties)==null?void 0:E._ShadeTexture,Oi=jt!=null?{index:jt,extensions:F({},J)}:void 0,ye=(A=(M=t.floatProperties)==null?void 0:M._ShadeShift)!=null?A:0,we=(L=(I=t.floatProperties)==null?void 0:I._ShadeToony)!=null?L:.9;we=$n.MathUtils.lerp(we,1,.5+.5*ye),ye=-ye-(1-we);let Gt=(U=(H=t.floatProperties)==null?void 0:H._IndirectLightIntensity)!=null?U:.1,Ni=Gt?1-Gt:void 0,Ne=(ce=t.textureProperties)==null?void 0:ce._SphereAdd,Di=Ne!=null?[1,1,1]:void 0,Bi=Ne!=null?{index:Ne}:void 0,Fi=(mt=(ct=t.floatProperties)==null?void 0:ct._RimLightingMix)!=null?mt:0,Qt=(pt=t.textureProperties)==null?void 0:pt._RimTexture,Wi=Qt!=null?{index:Qt,extensions:F({},J)}:void 0,ki=((_t=(ft=t.vectorProperties)==null?void 0:ft._RimColor)!=null?_t:[0,0,0,1]).map(le),zi=(vt=(gt=t.floatProperties)==null?void 0:gt._RimFresnelPower)!=null?vt:1,ji=(Mt=(Et=t.floatProperties)==null?void 0:Et._RimLift)!=null?Mt:0,Gi=["none","worldCoordinates","screenCoordinates"][(Tt=(Rt=t.floatProperties)==null?void 0:Rt._OutlineWidthMode)!=null?Tt:0],De=(yt=(xt=t.floatProperties)==null?void 0:xt._OutlineWidth)!=null?yt:0;De=.01*De;let qt=(wt=t.textureProperties)==null?void 0:wt._OutlineWidthTexture,Qi=qt!=null?{index:qt,extensions:F({},J)}:void 0,qi=((St=(Pt=t.vectorProperties)==null?void 0:Pt._OutlineColor)!=null?St:[0,0,0]).map(le),Xi=((Lt=(At=t.floatProperties)==null?void 0:At._OutlineColorMode)!=null?Lt:0)===1?(bt=(Ht=t.floatProperties)==null?void 0:Ht._OutlineLightingMix)!=null?bt:1:0,Xt=(Vt=t.textureProperties)==null?void 0:Vt._UvAnimMaskTexture,Yi=Xt!=null?{index:Xt,extensions:F({},J)}:void 0,$i=(Ut=(It=t.floatProperties)==null?void 0:It._UvAnimScrollX)!=null?Ut:0,Pe=(Ot=(Ct=t.floatProperties)==null?void 0:Ct._UvAnimScrollY)!=null?Ot:0;Pe!=null&&(Pe=-Pe);let Zi=(Dt=(Nt=t.floatProperties)==null?void 0:Nt._UvAnimRotation)!=null?Dt:0,Ji={specVersion:"1.0",transparentWithZWrite:yi,renderQueueOffsetNumber:wi,shadeColorFactor:Ci,shadeMultiplyTexture:Oi,shadingShiftFactor:ye,shadingToonyFactor:we,giEqualizationFactor:Ni,matcapFactor:Di,matcapTexture:Bi,rimLightingMixFactor:Fi,rimMultiplyTexture:Wi,parametricRimColorFactor:ki,parametricRimFresnelPowerFactor:zi,parametricRimLiftFactor:ji,outlineWidthMode:Gi,outlineWidthFactor:De,outlineWidthMultiplyTexture:Qi,outlineColorFactor:qi,outlineLightingMixFactor:Xi,uvAnimationMaskTexture:Yi,uvAnimationScrollXSpeedFactor:$i,uvAnimationScrollYSpeedFactor:Pe,uvAnimationRotationSpeedFactor:Zi};return Yn(F({},e),{pbrMetallicRoughness:{baseColorFactor:Li,baseColorTexture:Hi},normalTexture:Vi,emissiveTexture:Ui,emissiveFactor:Ii,alphaMode:Pi,alphaCutoff:Si,doubleSided:Ai,extensions:{VRMC_materials_mtoon:Ji}})}_parseV0UnlitProperties(t,e){var n,i,r,s,a;let l=t.shader==="VRM/UnlitTransparentZWrite",o=t.shader==="VRM/UnlitTransparent"||l,u=this._v0ParseRenderQueue(t),d=t.shader==="VRM/UnlitCutout",c=o?"BLEND":d?"MASK":"OPAQUE",f=d?(i=(n=t.floatProperties)==null?void 0:n._Cutoff)!=null?i:.5:void 0,m=this._portTextureTransform(t),p=((s=(r=t.vectorProperties)==null?void 0:r._Color)!=null?s:[1,1,1,1]).map(le),h=(a=t.textureProperties)==null?void 0:a._MainTex,_=h!=null?{index:h,extensions:F({},m)}:void 0,g={specVersion:"1.0",transparentWithZWrite:l,renderQueueOffsetNumber:u,shadeColorFactor:p,shadeMultiplyTexture:_};return Yn(F({},e),{pbrMetallicRoughness:{baseColorFactor:p,baseColorTexture:_},alphaMode:c,alphaCutoff:f,extensions:{VRMC_materials_mtoon:g}})}_portTextureTransform(t){var e,n,i,r,s;let a=(e=t.vectorProperties)==null?void 0:e._MainTex;if(a==null)return{};let l=[(n=a==null?void 0:a[0])!=null?n:0,(i=a==null?void 0:a[1])!=null?i:0],o=[(r=a==null?void 0:a[2])!=null?r:1,(s=a==null?void 0:a[3])!=null?s:1];return l[1]=1-o[1]-l[1],{KHR_texture_transform:{offset:l,scale:o}}}_v0ParseRenderQueue(t){var e,n,i;let r=(n=(e=t.keywordMap)==null?void 0:e._ALPHABLEND_ON)!=null?n:!1,s=((i=t.floatProperties)==null?void 0:i._ZWrite)===1,a=0;if(r){let l=t.renderQueue;l!=null&&(s?a=this._renderQueueMapTransparentZWrite.get(l):a=this._renderQueueMapTransparent.get(l))}return a}_populateRenderQueueMap(t){let e=new Set,n=new Set;t.forEach(i=>{var r,s,a;let l=(s=(r=i.keywordMap)==null?void 0:r._ALPHABLEND_ON)!=null?s:!1,o=((a=i.floatProperties)==null?void 0:a._ZWrite)===1;if(l){let u=i.renderQueue;u!=null&&(o?n.add(u):e.add(u))}}),e.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${e.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),n.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${n.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(e).sort().forEach((i,r)=>{let s=Math.min(Math.max(r-e.size+1,-9),0);this._renderQueueMapTransparent.set(i,s)}),Array.from(n).sort().forEach((i,r)=>{let s=Math.min(Math.max(r,0),9);this._renderQueueMapTransparentZWrite.set(i,s)})}};import*as C from"three";import*as W from"three";import*as at from"three";import*as Ee from"three";import*as j from"three";var Jn=(t,e,n)=>new Promise((i,r)=>{var s=o=>{try{l(n.next(o))}catch(u){r(u)}},a=o=>{try{l(n.throw(o))}catch(u){r(u)}},l=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);l((n=n.apply(t,e)).next())}),Y=new C.Vector3,st=class extends C.Group{constructor(t){super(),this._attrPosition=new C.BufferAttribute(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(C.DynamicDrawUsage);let e=new C.BufferGeometry;e.setAttribute("position",this._attrPosition);let n=new C.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new C.Line(e,n),this.add(this._line),this.constraint=t}updateMatrixWorld(t){Y.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,Y.x,Y.y,Y.z),this.constraint.source&&Y.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,Y.x,Y.y,Y.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(t)}};function Kn(t,e){return e.set(t.elements[12],t.elements[13],t.elements[14])}var Gr=new at.Vector3,Qr=new at.Vector3;function qr(t,e){return t.decompose(Gr,e,Qr),e}function Ue(t){return t.invert?t.invert():t.inverse(),t}var lt=class{constructor(t,e){this.destination=t,this.source=e,this.weight=1}},Xr=new W.Vector3,Yr=new W.Vector3,$r=new W.Vector3,Zr=new W.Quaternion,Jr=new W.Quaternion,Kr=new W.Quaternion,eo=class extends lt{get aimAxis(){return this._aimAxis}set aimAxis(t){this._aimAxis=t,this._v3AimAxis.set(t==="PositiveX"?1:t==="NegativeX"?-1:0,t==="PositiveY"?1:t==="NegativeY"?-1:0,t==="PositiveZ"?1:t==="NegativeZ"?-1:0)}get dependencies(){let t=new Set([this.source]);return this.destination.parent&&t.add(this.destination.parent),t}constructor(t,e){super(t,e),this._aimAxis="PositiveX",this._v3AimAxis=new W.Vector3(1,0,0),this._dstRestQuat=new W.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);let t=Zr.identity(),e=Jr.identity();this.destination.parent&&(qr(this.destination.parent.matrixWorld,t),Ue(e.copy(t)));let n=Xr.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(t),i=Kn(this.source.matrixWorld,Yr).sub(Kn(this.destination.matrixWorld,$r)).normalize(),r=Kr.setFromUnitVectors(n,i).premultiply(e).multiply(t).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(r,this.weight)}};function to(t,e){let n=[t],i=t.parent;for(;i!==null;)n.unshift(i),i=i.parent;n.forEach(r=>{e(r)})}var no=class{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(t){this._constraints.add(t);let e=this._objectConstraintsMap.get(t.destination);e==null&&(e=new Set,this._objectConstraintsMap.set(t.destination,e)),e.add(t)}deleteConstraint(t){this._constraints.delete(t),this._objectConstraintsMap.get(t.destination).delete(t)}setInitState(){let t=new Set,e=new Set;for(let n of this._constraints)this._processConstraint(n,t,e,i=>i.setInitState())}update(){let t=new Set,e=new Set;for(let n of this._constraints)this._processConstraint(n,t,e,i=>i.update())}_processConstraint(t,e,n,i){if(n.has(t))return;if(e.has(t))throw new Error("VRMNodeConstraintManager: Circular dependency detected while updating constraints");e.add(t);let r=t.dependencies;for(let s of r)to(s,a=>{let l=this._objectConstraintsMap.get(a);if(l)for(let o of l)this._processConstraint(o,e,n,i)});i(t),n.add(t)}},io=new Ee.Quaternion,ro=new Ee.Quaternion,oo=class extends lt{get dependencies(){return new Set([this.source])}constructor(t,e){super(t,e),this._dstRestQuat=new Ee.Quaternion,this._invSrcRestQuat=new Ee.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Ue(this._invSrcRestQuat.copy(this.source.quaternion))}update(){let t=io.copy(this._invSrcRestQuat).multiply(this.source.quaternion),e=ro.copy(this._dstRestQuat).multiply(t);this.destination.quaternion.copy(this._dstRestQuat).slerp(e,this.weight)}},so=new j.Vector3,ao=new j.Quaternion,lo=new j.Quaternion,uo=class extends lt{get rollAxis(){return this._rollAxis}set rollAxis(t){this._rollAxis=t,this._v3RollAxis.set(t==="X"?1:0,t==="Y"?1:0,t==="Z"?1:0)}get dependencies(){return new Set([this.source])}constructor(t,e){super(t,e),this._rollAxis="X",this._v3RollAxis=new j.Vector3(1,0,0),this._dstRestQuat=new j.Quaternion,this._invDstRestQuat=new j.Quaternion,this._invSrcRestQuatMulDstRestQuat=new j.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Ue(this._invDstRestQuat.copy(this._dstRestQuat)),Ue(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){let t=ao.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),e=so.copy(this._v3RollAxis).applyQuaternion(t),i=lo.setFromUnitVectors(e,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(t);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}},ho=new Set(["1.0","1.0-beta"]),ei=class ve{get name(){return ve.EXTENSION_NAME}constructor(e,n){this.parser=e,this.helperRoot=n==null?void 0:n.helperRoot}afterRoot(e){return Jn(this,null,function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)})}_import(e){return Jn(this,null,function*(){var n;let i=this.parser.json;if(!(((n=i.extensionsUsed)==null?void 0:n.indexOf(ve.EXTENSION_NAME))!==-1))return null;let s=new no,a=yield this.parser.getDependencies("node");return a.forEach((l,o)=>{var u;let d=i.nodes[o],c=(u=d==null?void 0:d.extensions)==null?void 0:u[ve.EXTENSION_NAME];if(c==null)return;let f=c.specVersion;if(!ho.has(f)){console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${ve.EXTENSION_NAME} specVersion "${f}"`);return}let m=c.constraint;if(m.roll!=null){let p=this._importRollConstraint(l,a,m.roll);s.addConstraint(p)}else if(m.aim!=null){let p=this._importAimConstraint(l,a,m.aim);s.addConstraint(p)}else if(m.rotation!=null){let p=this._importRotationConstraint(l,a,m.rotation);s.addConstraint(p)}}),e.scene.updateMatrixWorld(),s.setInitState(),s})}_importRollConstraint(e,n,i){let{source:r,rollAxis:s,weight:a}=i,l=n[r],o=new uo(e,l);if(s!=null&&(o.rollAxis=s),a!=null&&(o.weight=a),this.helperRoot){let u=new st(o);this.helperRoot.add(u)}return o}_importAimConstraint(e,n,i){let{source:r,aimAxis:s,weight:a}=i,l=n[r],o=new eo(e,l);if(s!=null&&(o.aimAxis=s),a!=null&&(o.weight=a),this.helperRoot){let u=new st(o);this.helperRoot.add(u)}return o}_importRotationConstraint(e,n,i){let{source:r,weight:s}=i,a=n[r],l=new oo(e,a);if(s!=null&&(l.weight=s),this.helperRoot){let o=new st(l);this.helperRoot.add(o)}return l}};ei.EXTENSION_NAME="VRMC_node_constraint";var ti=ei;import*as $ from"three";import*as xe from"three";import*as ui from"three";import*as Q from"three";import*as re from"three";import*as Z from"three";import*as oe from"three";import*as hi from"three";import*as V from"three";import*as ci from"three";import*as pi from"three";import*as ie from"three";var Ce=(t,e,n)=>new Promise((i,r)=>{var s=o=>{try{l(n.next(o))}catch(u){r(u)}},a=o=>{try{l(n.throw(o))}catch(u){r(u)}},l=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);l((n=n.apply(t,e)).next())}),ai=class{},ut=new xe.Vector3,ne=new xe.Vector3,li=class extends ai{get type(){return"capsule"}constructor(t){var e,n,i;super(),this.offset=(e=t==null?void 0:t.offset)!=null?e:new xe.Vector3(0,0,0),this.tail=(n=t==null?void 0:t.tail)!=null?n:new xe.Vector3(0,0,0),this.radius=(i=t==null?void 0:t.radius)!=null?i:0}calculateCollision(t,e,n,i){ut.copy(this.offset).applyMatrix4(t),ne.copy(this.tail).applyMatrix4(t),ne.sub(ut);let r=ne.lengthSq();i.copy(e).sub(ut);let s=ne.dot(i);s<=0||(r<=s||ne.multiplyScalar(s/r),i.sub(ne));let a=n+this.radius,l=i.length()-a;return i.normalize(),l}},di=class extends ai{get type(){return"sphere"}constructor(t){var e,n;super(),this.offset=(e=t==null?void 0:t.offset)!=null?e:new ui.Vector3(0,0,0),this.radius=(n=t==null?void 0:t.radius)!=null?n:0}calculateCollision(t,e,n,i){i.copy(this.offset).applyMatrix4(t),i.negate().add(e);let r=n+this.radius,s=i.length()-r;return i.normalize(),s}},k=new Q.Vector3,co=class extends Q.BufferGeometry{constructor(t){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new Q.Vector3,this._currentTail=new Q.Vector3,this._shape=t,this._attrPos=new Q.BufferAttribute(new Float32Array(396),3),this.setAttribute("position",this._attrPos),this._attrIndex=new Q.BufferAttribute(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1,e=this._shape.radius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,t=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),t=!0);let n=k.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(n)>1e-10&&(this._currentTail.copy(n),t=!0),t&&this._buildPosition()}_buildPosition(){k.copy(this._currentTail).sub(this._currentOffset);let t=k.length()/this._currentRadius;for(let i=0;i<=16;i++){let r=i/16*Math.PI;this._attrPos.setXYZ(i,-Math.sin(r),-Math.cos(r),0),this._attrPos.setXYZ(17+i,t+Math.sin(r),Math.cos(r),0),this._attrPos.setXYZ(34+i,-Math.sin(r),0,-Math.cos(r)),this._attrPos.setXYZ(51+i,t+Math.sin(r),0,Math.cos(r))}for(let i=0;i<32;i++){let r=i/16*Math.PI;this._attrPos.setXYZ(68+i,0,Math.sin(r),Math.cos(r)),this._attrPos.setXYZ(100+i,t,Math.sin(r),Math.cos(r))}let e=Math.atan2(k.y,Math.sqrt(k.x*k.x+k.z*k.z)),n=-Math.atan2(k.z,k.x);this.rotateZ(e),this.rotateY(n),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<34;t++){let e=(t+1)%34;this._attrIndex.setXY(t*2,t,e),this._attrIndex.setXY(68+t*2,34+t,34+e)}for(let t=0;t<32;t++){let e=(t+1)%32;this._attrIndex.setXY(136+t*2,68+t,68+e),this._attrIndex.setXY(200+t*2,100+t,100+e)}this._attrIndex.needsUpdate=!0}},mo=class extends re.BufferGeometry{constructor(t){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new re.Vector3,this._shape=t,this._attrPos=new re.BufferAttribute(new Float32Array(32*3*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new re.BufferAttribute(new Uint16Array(64*3),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1,e=this._shape.radius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,t=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),t=!0),t&&this._buildPosition()}_buildPosition(){for(let t=0;t<32;t++){let e=t/16*Math.PI;this._attrPos.setXYZ(t,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+t,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+t,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<32;t++){let e=(t+1)%32;this._attrIndex.setXY(t*2,t,e),this._attrIndex.setXY(64+t*2,32+t,32+e),this._attrIndex.setXY(128+t*2,64+t,64+e)}this._attrIndex.needsUpdate=!0}},po=new $.Vector3,ni=class extends $.Group{constructor(t){if(super(),this.matrixAutoUpdate=!1,this.collider=t,this.collider.shape instanceof di)this._geometry=new mo(this.collider.shape);else if(this.collider.shape instanceof li)this._geometry=new co(this.collider.shape);else throw new Error("VRMSpringBoneColliderHelper: Unknown collider shape type detected");let e=new $.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new $.LineSegments(this._geometry,e),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(t){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);let e=this.matrix.elements;this._geometry.worldScale=po.set(e[0],e[1],e[2]).length(),this._geometry.update(),super.updateMatrixWorld(t)}},fo=class extends oe.BufferGeometry{constructor(t){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new oe.Vector3,this._springBone=t,this._attrPos=new oe.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new oe.BufferAttribute(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1,e=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,t=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),t=!0),t&&this._buildPosition()}_buildPosition(){for(let t=0;t<32;t++){let e=t/16*Math.PI;this._attrPos.setXYZ(t,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+t,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+t,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<32;t++){let e=(t+1)%32;this._attrIndex.setXY(t*2,t,e),this._attrIndex.setXY(64+t*2,32+t,32+e),this._attrIndex.setXY(128+t*2,64+t,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},_o=new Z.Vector3,go=class extends Z.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.springBone=t,this._geometry=new fo(this.springBone);let e=new Z.LineBasicMaterial({color:16776960,depthTest:!1,depthWrite:!1});this._line=new Z.LineSegments(this._geometry,e),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(t){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);let e=this.matrix.elements;this._geometry.worldScale=_o.set(e[0],e[1],e[2]).length(),this._geometry.update(),super.updateMatrixWorld(t)}},ii=class extends hi.Object3D{constructor(t){super(),this.shape=t}},vo=new ci.Matrix4;function mi(t){return t.invert?t.invert():t.getInverse(vo.copy(t)),t}var Eo=class{constructor(t){this._inverseCache=new pi.Matrix4,this._shouldUpdateInverse=!0,this.matrix=t;let e={set:(n,i,r)=>(this._shouldUpdateInverse=!0,n[i]=r,!0)};this._originalElements=t.elements,t.elements=new Proxy(t.elements,e)}get inverse(){return this._shouldUpdateInverse&&(this._inverseCache.copy(this.matrix),mi(this._inverseCache),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}},Mo=new V.Matrix4,G=new V.Vector3,Me=new V.Vector3,Ro=new V.Vector3,ue=new V.Vector3,ri=new V.Vector3,Re=new V.Vector3,oi=new V.Quaternion,de=new V.Matrix4,To=new V.Matrix4,xo=class{constructor(t,e,n={},i=[]){this._currentTail=new V.Vector3,this._prevTail=new V.Vector3,this._boneAxis=new V.Vector3,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new V.Matrix4,this._initialLocalRotation=new V.Quaternion,this._initialLocalChildPosition=new V.Vector3;var r,s,a,l,o,u;this.bone=t,this.bone.matrixAutoUpdate=!1,this.child=e,this.settings={hitRadius:(r=n.hitRadius)!=null?r:0,stiffness:(s=n.stiffness)!=null?s:1,gravityPower:(a=n.gravityPower)!=null?a:0,gravityDir:(o=(l=n.gravityDir)==null?void 0:l.clone())!=null?o:new V.Vector3(0,-1,0),dragForce:(u=n.dragForce)!=null?u:.4},this.colliderGroups=i}get center(){return this._center}set center(t){var e;(e=this._center)!=null&&e.userData.inverseCacheProxy&&(this._center.userData.inverseCacheProxy.revert(),delete this._center.userData.inverseCacheProxy),this._center=t,this._center&&(this._center.userData.inverseCacheProxy||(this._center.userData.inverseCacheProxy=new Eo(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:Mo}setInitState(){this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),this.child?this._initialLocalChildPosition.copy(this.child.position):this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);let t=this._getMatrixWorldToCenter(de);this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(t),this._prevTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix);let t=this._getMatrixWorldToCenter(de);this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(t),this._prevTail.copy(this._currentTail)}update(t){if(t<=0)return;this._calcWorldSpaceBoneLength(),ue.setFromMatrixPosition(this.bone.matrixWorld);let e=this._getMatrixWorldToCenter(de);ri.copy(ue).applyMatrix4(e);let n=oi.setFromRotationMatrix(e),i=To.copy(e).multiply(this._parentMatrixWorld),r=Me.copy(this._boneAxis).applyMatrix4(this._initialLocalMatrix).applyMatrix4(i).sub(ri).normalize(),s=Ro.copy(this.settings.gravityDir).applyQuaternion(n).normalize(),a=this._getMatrixCenterToWorld(de);Re.copy(this._currentTail).add(G.copy(this._currentTail).sub(this._prevTail).multiplyScalar(1-this.settings.dragForce)).add(G.copy(r).multiplyScalar(this.settings.stiffness*t)).add(G.copy(s).multiplyScalar(this.settings.gravityPower*t)).applyMatrix4(a),Re.sub(ue).normalize().multiplyScalar(this._worldSpaceBoneLength).add(ue),this._collision(Re),e=this._getMatrixWorldToCenter(de),this._prevTail.copy(this._currentTail),this._currentTail.copy(G.copy(Re).applyMatrix4(e));let l=mi(de.copy(this._parentMatrixWorld).multiply(this._initialLocalMatrix)),o=oi.setFromUnitVectors(this._boneAxis,G.copy(Re).applyMatrix4(l).normalize());this.bone.quaternion.copy(this._initialLocalRotation).multiply(o),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(t){this.colliderGroups.forEach(e=>{e.colliders.forEach(n=>{let i=n.shape.calculateCollision(n.matrixWorld,t,this.settings.hitRadius,G);i<0&&(t.add(G.multiplyScalar(-i)),t.sub(ue).normalize().multiplyScalar(this._worldSpaceBoneLength).add(ue))})})}_calcWorldSpaceBoneLength(){G.setFromMatrixPosition(this.bone.matrixWorld),this.child?Me.setFromMatrixPosition(this.child.matrixWorld):(Me.copy(this._initialLocalChildPosition),Me.applyMatrix4(this.bone.matrixWorld)),this._worldSpaceBoneLength=G.sub(Me).length()}_getMatrixCenterToWorld(t){return this._center?t.copy(this._center.matrixWorld):t.identity(),t}_getMatrixWorldToCenter(t){return this._center?t.copy(this._center.userData.inverseCacheProxy.inverse):t.identity(),t}};function yo(t,e){let n=[],i=t;for(;i!==null;)n.unshift(i),i=i.parent;n.forEach(r=>{e(r)})}function fi(t,e){t.children.forEach(n=>{e(n)||fi(n,e)})}var si=class{constructor(){this._joints=new Set,this._objectSpringBonesMap=new Map}get joints(){return this._joints}get springBones(){return console.warn("VRMSpringBoneManager: springBones is deprecated. use joints instead."),this._joints}get colliderGroups(){let t=new Set;return this._joints.forEach(e=>{e.colliderGroups.forEach(n=>{t.add(n)})}),Array.from(t)}get colliders(){let t=new Set;return this.colliderGroups.forEach(e=>{e.colliders.forEach(n=>{t.add(n)})}),Array.from(t)}addJoint(t){this._joints.add(t);let e=this._objectSpringBonesMap.get(t.bone);e==null&&(e=new Set,this._objectSpringBonesMap.set(t.bone,e)),e.add(t)}addSpringBone(t){console.warn("VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead."),this.addJoint(t)}deleteJoint(t){this._joints.delete(t),this._objectSpringBonesMap.get(t.bone).delete(t)}deleteSpringBone(t){console.warn("VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead."),this.deleteJoint(t)}setInitState(){let t=new Set,e=new Set,n=new Set;for(let i of this._joints)this._processSpringBone(i,t,e,n,r=>r.setInitState())}reset(){let t=new Set,e=new Set,n=new Set;for(let i of this._joints)this._processSpringBone(i,t,e,n,r=>r.reset())}update(t){let e=new Set,n=new Set,i=new Set;for(let r of this._joints)this._processSpringBone(r,e,n,i,s=>s.update(t)),fi(r.bone,s=>{var a,l;return((l=(a=this._objectSpringBonesMap.get(s))==null?void 0:a.size)!=null?l:0)>0?!0:(s.updateWorldMatrix(!1,!1),!1)})}_processSpringBone(t,e,n,i,r){if(n.has(t))return;if(e.has(t))throw new Error("VRMSpringBoneManager: Circular dependency detected while updating springbones");e.add(t);let s=this._getDependencies(t);for(let a of s)yo(a,l=>{let o=this._objectSpringBonesMap.get(l);if(o)for(let u of o)this._processSpringBone(u,e,n,i,r);else i.has(l)||(l.updateWorldMatrix(!1,!1),i.add(l))});t.bone.updateMatrix(),t.bone.updateWorldMatrix(!1,!1),r(t),i.add(t.bone),n.add(t)}_getDependencies(t){let e=new Set,n=t.bone.parent;return n&&e.add(n),t.colliderGroups.forEach(i=>{i.colliders.forEach(r=>{e.add(r)})}),e}},wo=new Set(["1.0","1.0-beta"]),_i=class Te{get name(){return Te.EXTENSION_NAME}constructor(e,n){this.parser=e,this.jointHelperRoot=n==null?void 0:n.jointHelperRoot,this.colliderHelperRoot=n==null?void 0:n.colliderHelperRoot}afterRoot(e){return Ce(this,null,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return Ce(this,null,function*(){let n=yield this._v1Import(e);if(n!=null)return n;let i=yield this._v0Import(e);return i!=null?i:null})}_v1Import(e){return Ce(this,null,function*(){var n,i,r,s,a;let l=e.parser.json;if(!(((n=l.extensionsUsed)==null?void 0:n.indexOf(Te.EXTENSION_NAME))!==-1))return null;let u=new si,d=yield e.parser.getDependencies("node"),c=(i=l.extensions)==null?void 0:i[Te.EXTENSION_NAME];if(!c)return null;let f=c.specVersion;if(!wo.has(f))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${Te.EXTENSION_NAME} specVersion "${f}"`),null;let m=(r=c.colliders)==null?void 0:r.map((h,_)=>{var g,x,T,v,R;let E=d[h.node],M=h.shape;if(M.sphere)return this._importSphereCollider(E,{offset:new ie.Vector3().fromArray((g=M.sphere.offset)!=null?g:[0,0,0]),radius:(x=M.sphere.radius)!=null?x:0});if(M.capsule)return this._importCapsuleCollider(E,{offset:new ie.Vector3().fromArray((T=M.capsule.offset)!=null?T:[0,0,0]),radius:(v=M.capsule.radius)!=null?v:0,tail:new ie.Vector3().fromArray((R=M.capsule.tail)!=null?R:[0,0,0])});throw new Error(`VRMSpringBoneLoaderPlugin: The collider #${_} has no valid shape`)}),p=(s=c.colliderGroups)==null?void 0:s.map((h,_)=>{var g;return{colliders:((g=h.colliders)!=null?g:[]).map(T=>{let v=m==null?void 0:m[T];if(v==null)throw new Error(`VRMSpringBoneLoaderPlugin: The colliderGroup #${_} attempted to use a collider #${T} but not found`);return v}),name:h.name}});return(a=c.springs)==null||a.forEach((h,_)=>{var g;let x=h.joints,T=(g=h.colliderGroups)==null?void 0:g.map(E=>{let M=p==null?void 0:p[E];if(M==null)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${_} attempted to use a colliderGroup ${E} but not found`);return M}),v=h.center!=null?d[h.center]:void 0,R;x.forEach(E=>{if(R){let M=R.node,A=d[M],I=E.node,L=d[I],H={hitRadius:R.hitRadius,dragForce:R.dragForce,gravityPower:R.gravityPower,stiffness:R.stiffness,gravityDir:R.gravityDir!=null?new ie.Vector3().fromArray(R.gravityDir):void 0},U=this._importJoint(A,L,H,T);v&&(U.center=v),u.addJoint(U)}R=E})}),u.setInitState(),u})}_v0Import(e){return Ce(this,null,function*(){var n,i,r;let s=e.parser.json;if(!(((n=s.extensionsUsed)==null?void 0:n.indexOf("VRM"))!==-1))return null;let l=(i=s.extensions)==null?void 0:i.VRM,o=l==null?void 0:l.secondaryAnimation;if(!o)return null;let u=o==null?void 0:o.boneGroups;if(!u)return null;let d=new si,c=yield e.parser.getDependencies("node"),f=(r=o.colliderGroups)==null?void 0:r.map(m=>{var p;let h=c[m.node];return{colliders:((p=m.colliders)!=null?p:[]).map((g,x)=>{var T,v,R;let E=new ie.Vector3(0,0,0);return g.offset&&E.set((T=g.offset.x)!=null?T:0,(v=g.offset.y)!=null?v:0,g.offset.z?-g.offset.z:0),this._importSphereCollider(h,{offset:E,radius:(R=g.radius)!=null?R:0})})}});return u==null||u.forEach((m,p)=>{let h=m.bones;h&&h.forEach(_=>{var g,x,T,v;let R=c[_],E=new ie.Vector3;m.gravityDir?E.set((g=m.gravityDir.x)!=null?g:0,(x=m.gravityDir.y)!=null?x:0,(T=m.gravityDir.z)!=null?T:0):E.set(0,-1,0);let M=m.center!=null?c[m.center]:void 0,A={hitRadius:m.hitRadius,dragForce:m.dragForce,gravityPower:m.gravityPower,stiffness:m.stiffiness,gravityDir:E},I=(v=m.colliderGroups)==null?void 0:v.map(L=>{let H=f==null?void 0:f[L];if(H==null)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${p} attempted to use a colliderGroup ${L} but not found`);return H});R.traverse(L=>{var H;let U=(H=L.children[0])!=null?H:null,ce=this._importJoint(L,U,A,I);M&&(ce.center=M),d.addJoint(ce)})})}),e.scene.updateMatrixWorld(),d.setInitState(),d})}_importJoint(e,n,i,r){let s=new xo(e,n,i,r);if(this.jointHelperRoot){let a=new go(s);this.jointHelperRoot.add(a),a.renderOrder=this.jointHelperRoot.renderOrder}return s}_importSphereCollider(e,n){let{offset:i,radius:r}=n,s=new di({offset:i,radius:r}),a=new ii(s);if(e.add(a),this.colliderHelperRoot){let l=new ni(a);this.colliderHelperRoot.add(l),l.renderOrder=this.colliderHelperRoot.renderOrder}return a}_importCapsuleCollider(e,n){let{offset:i,radius:r,tail:s}=n,a=new li({offset:i,radius:r,tail:s}),l=new ii(a);if(e.add(l),this.colliderHelperRoot){let o=new ni(l);this.colliderHelperRoot.add(o),o.renderOrder=this.colliderHelperRoot.renderOrder}return l}};_i.EXTENSION_NAME="VRMC_springBone";var gi=_i;var dt=class{get name(){return"VRMLoaderPlugin"}constructor(e,n){var s,a,l,o,u,d,c,f,m,p;this.parser=e;let i=n==null?void 0:n.helperRoot,r=n==null?void 0:n.autoUpdateHumanBones;this.expressionPlugin=(s=n==null?void 0:n.expressionPlugin)!=null?s:new Ye(e),this.firstPersonPlugin=(a=n==null?void 0:n.firstPersonPlugin)!=null?a:new Ze(e),this.humanoidPlugin=(l=n==null?void 0:n.humanoidPlugin)!=null?l:new Je(e,{helperRoot:i,autoUpdateHumanBones:r}),this.lookAtPlugin=(o=n==null?void 0:n.lookAtPlugin)!=null?o:new et(e,{helperRoot:i}),this.metaPlugin=(u=n==null?void 0:n.metaPlugin)!=null?u:new tt(e),this.mtoonMaterialPlugin=(d=n==null?void 0:n.mtoonMaterialPlugin)!=null?d:new jn(e),this.materialsHDREmissiveMultiplierPlugin=(c=n==null?void 0:n.materialsHDREmissiveMultiplierPlugin)!=null?c:new Qn(e),this.materialsV0CompatPlugin=(f=n==null?void 0:n.materialsV0CompatPlugin)!=null?f:new Zn(e),this.springBonePlugin=(m=n==null?void 0:n.springBonePlugin)!=null?m:new gi(e,{colliderHelperRoot:i,jointHelperRoot:i}),this.nodeConstraintPlugin=(p=n==null?void 0:n.nodeConstraintPlugin)!=null?p:new ti(e,{helperRoot:i})}beforeRoot(){return me(this,null,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(e){return me(this,null,function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)})}getMaterialType(e){let n=this.mtoonMaterialPlugin.getMaterialType(e);return n!=null?n:null}extendMaterialParams(e,n){return me(this,null,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,n),yield this.mtoonMaterialPlugin.extendMaterialParams(e,n)})}afterRoot(e){return me(this,null,function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);let n=e.userData.vrmMeta,i=e.userData.vrmHumanoid;if(n&&i){let r=new ge({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:i,lookAt:e.userData.vrmLookAt,meta:n,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=r}})}};function vi(t){if(Object.values(t).forEach(e=>{e!=null&&e.isTexture&&e.dispose()}),t.isShaderMaterial){let e=t.uniforms;e&&Object.values(e).forEach(n=>{let i=n.value;i!=null&&i.isTexture&&i.dispose()})}t.dispose()}function Po(t){let e=t.geometry;e&&e.dispose();let n=t.skeleton;n&&n.dispose();let i=t.material;i&&(Array.isArray(i)?i.forEach(r=>vi(r)):i&&vi(i))}function Ei(t){t.traverse(Po)}import*as Oe from"three";function Mi(t,e){var a;let n=(a=e==null?void 0:e.experimentalSameBoneCounts)!=null?a:!1,i=[];t.traverse(l=>{l.type==="SkinnedMesh"&&i.push(l)});let r=new Map,s=0;for(let l of i){let u=l.geometry.getAttribute("skinIndex"),d=[],c=[],f={},m=u.array;for(let p=0;p<m.length;p++){let h=m[p];f[h]==null&&(f[h]=d.length,d.push(l.skeleton.bones[h]),c.push(l.skeleton.boneInverses[h])),m[p]=f[h]}u.copyArray(m),u.needsUpdate=!0,r.set(l,{bones:d,boneInverses:c}),s=Math.max(s,d.length)}for(let l of i){let{bones:o,boneInverses:u}=r.get(l);if(n)for(let c=o.length;c<s;c++)o[c]=o[0],u[c]=u[0];let d=new Oe.Skeleton(o,u);l.bind(d,new Oe.Matrix4)}}import*as Ri from"three";import{BufferAttribute as ht}from"three";function Ti(t){let e=new Map;t.traverse(n=>{var c,f,m,p;if(!n.isMesh)return;let i=n,r=i.geometry,s=r.index;if(s==null)return;let a=e.get(r);if(a!=null){i.geometry=a;return}let l=new Ri.BufferGeometry;l.name=r.name,l.morphTargetsRelative=r.morphTargetsRelative,r.groups.forEach(h=>{l.addGroup(h.start,h.count,h.materialIndex)}),l.boundingBox=(f=(c=r.boundingBox)==null?void 0:c.clone())!=null?f:null,l.boundingSphere=(p=(m=r.boundingSphere)==null?void 0:m.clone())!=null?p:null,l.setDrawRange(r.drawRange.start,r.drawRange.count),l.userData=r.userData,e.set(r,l);let o=[],u=[];{let h=s.array,_=new h.constructor(h.length),g=0;for(let x=0;x<h.length;x++){let T=h[x],v=o[T];v==null&&(o[T]=g,u[g]=T,v=g,g++),_[x]=v}l.setIndex(new ht(_,1,!1))}Object.keys(r.attributes).forEach(h=>{let _=r.attributes[h];if(_.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");let g=_.array,{itemSize:x,normalized:T}=_,v=new g.constructor(u.length*x);u.forEach((R,E)=>{for(let M=0;M<x;M++)v[E*x+M]=g[R*x+M]}),l.setAttribute(h,new ht(v,x,T))});let d=!0;Object.keys(r.morphAttributes).forEach(h=>{l.morphAttributes[h]=[];let _=r.morphAttributes[h];for(let g=0;g<_.length;g++){let x=_[g];if(x.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");let T=x.array,{itemSize:v,normalized:R}=x,E=new T.constructor(u.length*v);u.forEach((M,A)=>{for(let I=0;I<v;I++)E[A*v+I]=T[M*v+I]}),d=d&&E.every(M=>M===0),l.morphAttributes[h][g]=new ht(E,v,R)}}),d&&(l.morphAttributes={}),i.geometry=l}),Array.from(e.keys()).forEach(n=>{n.dispose()})}function xi(t){var e;((e=t.meta)==null?void 0:e.metaVersion)==="0"&&(t.scene.rotation.y=Math.PI)}var he=class{constructor(){}};he.deepDispose=Ei,he.removeUnnecessaryJoints=Mi,he.removeUnnecessaryVertices=Ti,he.rotateVRM0=xi;export{Or as MToonMaterial,Ur as MToonMaterialDebugMode,jn as MToonMaterialLoaderPlugin,it as MToonMaterialOutlineWidthMode,ge as VRM,eo as VRMAimConstraint,nt as VRMCore,Co as VRMCoreLoaderPlugin,$t as VRMExpression,Ye as VRMExpressionLoaderPlugin,Kt as VRMExpressionManager,en as VRMExpressionMaterialColorBind,pe as VRMExpressionMaterialColorType,tn as VRMExpressionMorphTargetBind,bo as VRMExpressionOverrideType,ze as VRMExpressionPresetName,rn as VRMExpressionTextureTransformBind,on as VRMFirstPerson,Ze as VRMFirstPersonLoaderPlugin,Vo as VRMFirstPersonMeshAnnotationType,Be as VRMHumanBoneList,Io as VRMHumanBoneName,or as VRMHumanBoneParentMap,dn as VRMHumanoid,ln as VRMHumanoidHelper,Je as VRMHumanoidLoaderPlugin,dt as VRMLoaderPlugin,Rr as VRMLookAt,He as VRMLookAtBoneApplier,qe as VRMLookAtExpressionApplier,mr as VRMLookAtHelper,et as VRMLookAtLoaderPlugin,En as VRMLookAtRangeMap,Uo as VRMLookAtTypeName,tt as VRMMetaLoaderPlugin,lt as VRMNodeConstraint,st as VRMNodeConstraintHelper,ti as VRMNodeConstraintLoaderPlugin,no as VRMNodeConstraintManager,lr as VRMRequiredHumanBoneName,uo as VRMRollConstraint,oo as VRMRotationConstraint,ii as VRMSpringBoneCollider,ni as VRMSpringBoneColliderHelper,ai as VRMSpringBoneColliderShape,li as VRMSpringBoneColliderShapeCapsule,di as VRMSpringBoneColliderShapeSphere,xo as VRMSpringBoneJoint,go as VRMSpringBoneJointHelper,gi as VRMSpringBoneLoaderPlugin,si as VRMSpringBoneManager,he as VRMUtils};
3
912
  /*!
4
- * @pixiv/three-vrm-core v2.1.2
913
+ * @pixiv/three-vrm-core v3.0.0-beta.1
5
914
  * The implementation of core features of VRM, for @pixiv/three-vrm
6
915
  *
7
- * Copyright (c) 2020-2024 pixiv Inc.
916
+ * Copyright (c) 2019-2024 pixiv Inc.
8
917
  * @pixiv/three-vrm-core is distributed under MIT License
9
918
  * https://github.com/pixiv/three-vrm/blob/release/LICENSE
10
919
  */
11
- class i extends e.Object3D{get overrideBlinkAmount(){return"block"===this.overrideBlink?0<this.weight?1:0:"blend"===this.overrideBlink?this.weight:0}get overrideLookAtAmount(){return"block"===this.overrideLookAt?0<this.weight?1:0:"blend"===this.overrideLookAt?this.weight:0}get overrideMouthAmount(){return"block"===this.overrideMouth?0<this.weight?1:0:"blend"===this.overrideMouth?this.weight:0}constructor(e){super(),this.weight=0,this.isBinary=!1,this.overrideBlink="none",this.overrideLookAt="none",this.overrideMouth="none",this._binds=[],this.name=`VRMExpression_${e}`,this.expressionName=e,this.type="VRMExpression",this.visible=!1}addBind(e){this._binds.push(e)}applyWeight(e){var t;let i=this.isBinary?this.weight<=.5?0:1:this.weight;i*=null!==(t=null==e?void 0:e.multiplier)&&void 0!==t?t:1,this._binds.forEach((e=>e.applyWeight(i)))}clearAppliedWeight(){this._binds.forEach((e=>e.clearAppliedWeight()))}}function n(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))}function r(e,t,i){var n,r;const o=e.parser.json,s=null===(n=o.nodes)||void 0===n?void 0:n[t];if(null==s)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${t}] of glTF but the node doesn't exist`),null;const a=s.mesh;if(null==a)return null;const l=null===(r=o.meshes)||void 0===r?void 0:r[a];if(null==l)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${a}] of glTF but the mesh doesn't exist`),null;const u=l.primitives.length,d=[];return i.traverse((e=>{d.length<u&&e.isMesh&&d.push(e)})),d}function o(e,t){return n(this,void 0,void 0,(function*(){const i=yield e.parser.getDependency("node",t);return r(e,t,i)}))}function s(e){return n(this,void 0,void 0,(function*(){const t=yield e.parser.getDependencies("node"),i=new Map;return t.forEach(((t,n)=>{const o=r(e,n,t);null!=o&&i.set(n,o)})),i}))}function a(t,i){var n,r;let o=null;if(parseInt(e.REVISION,10)>=133)o=null!==(r=null===(n=t.associations.get(i))||void 0===n?void 0:n.materials)&&void 0!==r?r:null;else{const e=t.associations.get(i);"materials"===(null==e?void 0:e.type)&&(o=e.index)}return o}"function"==typeof SuppressedError&&SuppressedError;const l={Aa:"aa",Ih:"ih",Ou:"ou",Ee:"ee",Oh:"oh",Blink:"blink",Happy:"happy",Angry:"angry",Sad:"sad",Relaxed:"relaxed",LookUp:"lookUp",Surprised:"surprised",LookDown:"lookDown",LookLeft:"lookLeft",LookRight:"lookRight",BlinkLeft:"blinkLeft",BlinkRight:"blinkRight",Neutral:"neutral"};function u(e){return Math.max(Math.min(e,1),0)}class d{get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){const e={},t=new Set(Object.values(l));return Object.entries(this._expressionMap).forEach((([i,n])=>{t.has(i)&&(e[i]=n)})),e}get customExpressionMap(){const e={},t=new Set(Object.values(l));return Object.entries(this._expressionMap).forEach((([i,n])=>{t.has(i)||(e[i]=n)})),e}constructor(){this.blinkExpressionNames=["blink","blinkLeft","blinkRight"],this.lookAtExpressionNames=["lookLeft","lookRight","lookUp","lookDown"],this.mouthExpressionNames=["aa","ee","ih","oh","ou"],this._expressions=[],this._expressionMap={}}copy(e){return this._expressions.concat().forEach((e=>{this.unregisterExpression(e)})),e._expressions.forEach((e=>{this.registerExpression(e)})),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return(new d).copy(this)}getExpression(e){var t;return null!==(t=this._expressionMap[e])&&void 0!==t?t:null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){const t=this._expressions.indexOf(e);-1===t&&console.warn("VRMExpressionManager: The specified expressions is not registered"),this._expressions.splice(t,1),delete this._expressionMap[e.expressionName]}getValue(e){var t;const i=this.getExpression(e);return null!==(t=null==i?void 0:i.weight)&&void 0!==t?t:null}setValue(e,t){const i=this.getExpression(e);i&&(i.weight=u(t))}getExpressionTrackName(e){const t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){const e=this._calculateWeightMultipliers();this._expressions.forEach((e=>{e.clearAppliedWeight()})),this._expressions.forEach((t=>{let i=1;const n=t.expressionName;-1!==this.blinkExpressionNames.indexOf(n)&&(i*=e.blink),-1!==this.lookAtExpressionNames.indexOf(n)&&(i*=e.lookAt),-1!==this.mouthExpressionNames.indexOf(n)&&(i*=e.mouth),t.applyWeight({multiplier:i})}))}_calculateWeightMultipliers(){let e=1,t=1,i=1;return this._expressions.forEach((n=>{e-=n.overrideBlinkAmount,t-=n.overrideLookAtAmount,i-=n.overrideMouthAmount})),e=Math.max(0,e),t=Math.max(0,t),i=Math.max(0,i),{blink:e,lookAt:t,mouth:i}}}const h={Color:"color",EmissionColor:"emissionColor",ShadeColor:"shadeColor",MatcapColor:"matcapColor",RimColor:"rimColor",OutlineColor:"outlineColor"},c={_Color:h.Color,_EmissionColor:h.EmissionColor,_ShadeColor:h.ShadeColor,_RimColor:h.RimColor,_OutlineColor:h.OutlineColor},p=new e.Color;class m{constructor({material:e,type:t,targetValue:i,targetAlpha:n}){this.material=e,this.type=t,this.targetValue=i,this.targetAlpha=null!=n?n:1;const r=this._initColorBindState(),o=this._initAlphaBindState();this._state={color:r,alpha:o}}applyWeight(e){const{color:t,alpha:i}=this._state;if(null!=t){const{propertyName:i,deltaValue:n}=t,r=this.material[i];null!=r&&r.add(p.copy(n).multiplyScalar(e))}if(null!=i){const{propertyName:t,deltaValue:n}=i;null!=this.material[t]&&(this.material[t]+=n*e)}}clearAppliedWeight(){const{color:e,alpha:t}=this._state;if(null!=e){const{propertyName:t,initialValue:i}=e,n=this.material[t];null!=n&&n.copy(i)}if(null!=t){const{propertyName:e,initialValue:i}=t;null!=this.material[e]&&(this.material[e]=i)}}_initColorBindState(){var t,i,n;const{material:r,type:o,targetValue:s}=this,a=this._getPropertyNameMap(),l=null!==(i=null===(t=null==a?void 0:a[o])||void 0===t?void 0:t[0])&&void 0!==i?i:null;if(null==l)return console.warn(`Tried to add a material color bind to the material ${null!==(n=r.name)&&void 0!==n?n:"(no name)"}, the type ${o} but the material or the type is not supported.`),null;const u=r[l].clone();return{propertyName:l,initialValue:u,deltaValue:new e.Color(s.r-u.r,s.g-u.g,s.b-u.b)}}_initAlphaBindState(){var e,t,i;const{material:n,type:r,targetAlpha:o}=this,s=this._getPropertyNameMap(),a=null!==(t=null===(e=null==s?void 0:s[r])||void 0===e?void 0:e[1])&&void 0!==t?t:null;if(null==a&&1!==o)return console.warn(`Tried to add a material alpha bind to the material ${null!==(i=n.name)&&void 0!==i?i:"(no name)"}, the type ${r} but the material or the type does not support alpha.`),null;if(null==a)return null;const l=n[a];return{propertyName:a,initialValue:l,deltaValue:o-l}}_getPropertyNameMap(){var e,t;return null!==(t=null===(e=Object.entries(m._propertyNameMapMap).find((([e])=>!0===this.material[e])))||void 0===e?void 0:e[1])&&void 0!==t?t:null}}m._propertyNameMapMap={isMeshStandardMaterial:{color:["color","opacity"],emissionColor:["emissive",null]},isMeshBasicMaterial:{color:["color","opacity"]},isMToonMaterial:{color:["color","opacity"],emissionColor:["emissive",null],outlineColor:["outlineColorFactor",null],matcapColor:["matcapFactor",null],rimColor:["parametricRimColorFactor",null],shadeColor:["shadeColorFactor",null]}};class f{constructor({primitives:e,index:t,weight:i}){this.primitives=e,this.index=t,this.weight=i}applyWeight(e){this.primitives.forEach((t=>{var i;null!=(null===(i=t.morphTargetInfluences)||void 0===i?void 0:i[this.index])&&(t.morphTargetInfluences[this.index]+=this.weight*e)}))}clearAppliedWeight(){this.primitives.forEach((e=>{var t;null!=(null===(t=e.morphTargetInfluences)||void 0===t?void 0:t[this.index])&&(e.morphTargetInfluences[this.index]=0)}))}}const g=new e.Vector2;class v{constructor({material:e,scale:t,offset:i}){var n,r;this.material=e,this.scale=t,this.offset=i;const o=null===(n=Object.entries(v._propertyNamesMap).find((([t])=>!0===e[t])))||void 0===n?void 0:n[1];null==o?(console.warn(`Tried to add a texture transform bind to the material ${null!==(r=e.name)&&void 0!==r?r:"(no name)"} but the material is not supported.`),this._properties=[]):(this._properties=[],o.forEach((n=>{var r;const o=null===(r=e[n])||void 0===r?void 0:r.clone();if(!o)return null;e[n]=o;const s=o.offset.clone(),a=o.repeat.clone(),l=i.clone().sub(s),u=t.clone().sub(a);this._properties.push({name:n,initialOffset:s,deltaOffset:l,initialScale:a,deltaScale:u})})))}applyWeight(e){this._properties.forEach((t=>{const i=this.material[t.name];void 0!==i&&(i.offset.add(g.copy(t.deltaOffset).multiplyScalar(e)),i.repeat.add(g.copy(t.deltaScale).multiplyScalar(e)))}))}clearAppliedWeight(){this._properties.forEach((e=>{const t=this.material[e.name];void 0!==t&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))}))}}v._propertyNamesMap={isMeshStandardMaterial:["map","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap"],isMeshBasicMaterial:["map","specularMap","alphaMap"],isMToonMaterial:["map","normalMap","emissiveMap","shadeMultiplyTexture","rimMultiplyTexture","outlineWidthMultiplyTexture","uvAnimationMaskTexture"]};const _=new Set(["1.0","1.0-beta"]);class M{get name(){return"VRMExpressionLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return n(this,void 0,void 0,(function*(){e.userData.vrmExpressionManager=yield this._import(e)}))}_import(e){return n(this,void 0,void 0,(function*(){const t=yield this._v1Import(e);if(t)return t;const i=yield this._v0Import(e);return i||null}))}_v1Import(t){var r,s;return n(this,void 0,void 0,(function*(){const u=this.parser.json;if(!(-1!==(null===(r=u.extensionsUsed)||void 0===r?void 0:r.indexOf("VRMC_vrm"))))return null;const h=null===(s=u.extensions)||void 0===s?void 0:s.VRMC_vrm;if(!h)return null;const c=h.specVersion;if(!_.has(c))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${c}"`),null;const p=h.expressions;if(!p)return null;const g=new Set(Object.values(l)),M=new Map;null!=p.preset&&Object.entries(p.preset).forEach((([e,t])=>{null!=t&&(g.has(e)?M.set(e,t):console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${e}" detected. Ignoring the expression`))})),null!=p.custom&&Object.entries(p.custom).forEach((([e,t])=>{g.has(e)?console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${e}". Ignoring the expression`):M.set(e,t)}));const x=new d;return yield Promise.all(Array.from(M.entries()).map((([r,s])=>n(this,void 0,void 0,(function*(){var l,u,d,h,c,p,g;const _=new i(r);if(t.scene.add(_),_.isBinary=null!==(l=s.isBinary)&&void 0!==l&&l,_.overrideBlink=null!==(u=s.overrideBlink)&&void 0!==u?u:"none",_.overrideLookAt=null!==(d=s.overrideLookAt)&&void 0!==d?d:"none",_.overrideMouth=null!==(h=s.overrideMouth)&&void 0!==h?h:"none",null===(c=s.morphTargetBinds)||void 0===c||c.forEach((e=>n(this,void 0,void 0,(function*(){var i;if(void 0===e.node||void 0===e.index)return;const n=yield o(t,e.node),r=e.index;n.every((e=>Array.isArray(e.morphTargetInfluences)&&r<e.morphTargetInfluences.length))?_.addBind(new f({primitives:n,index:r,weight:null!==(i=e.weight)&&void 0!==i?i:1})):console.warn(`VRMExpressionLoaderPlugin: ${s.name} attempts to index morph #${r} but not found.`)})))),s.materialColorBinds||s.textureTransformBinds){const i=[];t.scene.traverse((e=>{const t=e.material;t&&i.push(t)})),null===(p=s.materialColorBinds)||void 0===p||p.forEach((t=>n(this,void 0,void 0,(function*(){i.filter((e=>{const i=a(this.parser,e);return t.material===i})).forEach((i=>{_.addBind(new m({material:i,type:t.type,targetValue:(new e.Color).fromArray(t.targetValue),targetAlpha:t.targetValue[3]}))}))})))),null===(g=s.textureTransformBinds)||void 0===g||g.forEach((t=>n(this,void 0,void 0,(function*(){i.filter((e=>{const i=a(this.parser,e);return t.material===i})).forEach((i=>{var n,r;_.addBind(new v({material:i,offset:(new e.Vector2).fromArray(null!==(n=t.offset)&&void 0!==n?n:[0,0]),scale:(new e.Vector2).fromArray(null!==(r=t.scale)&&void 0!==r?r:[1,1])}))}))}))))}x.registerExpression(_)}))))),x}))}_v0Import(t){var r;return n(this,void 0,void 0,(function*(){const s=this.parser.json,a=null===(r=s.extensions)||void 0===r?void 0:r.VRM;if(!a)return null;const l=a.blendShapeMaster;if(!l)return null;const u=new d,h=l.blendShapeGroups;if(!h)return u;const p=new Set;return yield Promise.all(h.map((r=>n(this,void 0,void 0,(function*(){var a;const l=r.presetName,d=null!=l&&M.v0v1PresetNameMap[l]||null,h=null!=d?d:r.name;if(null==h)return void console.warn("VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression");if(p.has(h))return void console.warn(`VRMExpressionLoaderPlugin: An expression preset ${l} has duplicated entries. Ignoring the expression`);p.add(h);const g=new i(h);t.scene.add(g),g.isBinary=null!==(a=r.isBinary)&&void 0!==a&&a,r.binds&&r.binds.forEach((e=>n(this,void 0,void 0,(function*(){var i;if(void 0===e.mesh||void 0===e.index)return;const a=[];null===(i=s.nodes)||void 0===i||i.forEach(((t,i)=>{t.mesh===e.mesh&&a.push(i)}));const l=e.index;yield Promise.all(a.map((i=>n(this,void 0,void 0,(function*(){var n;const s=yield o(t,i);s.every((e=>Array.isArray(e.morphTargetInfluences)&&l<e.morphTargetInfluences.length))?g.addBind(new f({primitives:s,index:l,weight:.01*(null!==(n=e.weight)&&void 0!==n?n:100)})):console.warn(`VRMExpressionLoaderPlugin: ${r.name} attempts to index ${l}th morph but not found.`)})))))}))));const _=r.materialValues;_&&0!==_.length&&_.forEach((i=>{if(void 0===i.materialName||void 0===i.propertyName||void 0===i.targetValue)return;const n=[];t.scene.traverse((e=>{if(e.material){const t=e.material;Array.isArray(t)?n.push(...t.filter((e=>(e.name===i.materialName||e.name===i.materialName+" (Outline)")&&-1===n.indexOf(e)))):t.name===i.materialName&&-1===n.indexOf(t)&&n.push(t)}}));const r=i.propertyName;n.forEach((t=>{if("_MainTex_ST"===r){const n=new e.Vector2(i.targetValue[0],i.targetValue[1]),r=new e.Vector2(i.targetValue[2],i.targetValue[3]);return r.y=1-r.y-n.y,void g.addBind(new v({material:t,scale:n,offset:r}))}const n=c[r];n?g.addBind(new m({material:t,type:n,targetValue:(new e.Color).fromArray(i.targetValue),targetAlpha:i.targetValue[3]})):console.warn(r+" is not supported")}))})),u.registerExpression(g)}))))),u}))}}M.v0v1PresetNameMap={a:"aa",e:"ee",i:"ih",o:"oh",u:"ou",blink:"blink",joy:"happy",angry:"angry",sorrow:"sad",fun:"relaxed",lookup:"lookUp",lookdown:"lookDown",lookleft:"lookLeft",lookright:"lookRight",blink_l:"blinkLeft",blink_r:"blinkRight",neutral:"neutral"};const x={None:"none",Block:"block",Blend:"blend"};class y{constructor(e,t){this._firstPersonOnlyLayer=y.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=y.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=e,this.meshAnnotations=t}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMFirstPerson: humanoid must be same in order to copy");return this.meshAnnotations=e.meshAnnotations.map((e=>({meshes:e.meshes.concat(),type:e.type}))),this}clone(){return new y(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:e=y.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=y.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||(this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=t,this.meshAnnotations.forEach((e=>{e.meshes.forEach((t=>{"firstPersonOnly"===e.type?(t.layers.set(this._firstPersonOnlyLayer),t.traverse((e=>e.layers.set(this._firstPersonOnlyLayer)))):"thirdPersonOnly"===e.type?(t.layers.set(this._thirdPersonOnlyLayer),t.traverse((e=>e.layers.set(this._thirdPersonOnlyLayer)))):"auto"===e.type&&this._createHeadlessModel(t)}))})),this._initializedLayers=!0)}_excludeTriangles(e,t,i,n){let r=0;if(null!=t&&t.length>0)for(let o=0;o<e.length;o+=3){const s=e[o],a=e[o+1],l=e[o+2],u=t[s],d=i[s];if(u[0]>0&&n.includes(d[0]))continue;if(u[1]>0&&n.includes(d[1]))continue;if(u[2]>0&&n.includes(d[2]))continue;if(u[3]>0&&n.includes(d[3]))continue;const h=t[a],c=i[a];if(h[0]>0&&n.includes(c[0]))continue;if(h[1]>0&&n.includes(c[1]))continue;if(h[2]>0&&n.includes(c[2]))continue;if(h[3]>0&&n.includes(c[3]))continue;const p=t[l],m=i[l];p[0]>0&&n.includes(m[0])||(p[1]>0&&n.includes(m[1])||p[2]>0&&n.includes(m[2])||p[3]>0&&n.includes(m[3])||(e[r++]=s,e[r++]=a,e[r++]=l))}return r}_createErasedMesh(t,i){const n=new e.SkinnedMesh(t.geometry.clone(),t.material);n.name=`${t.name}(erase)`,n.frustumCulled=t.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);const r=n.geometry,o=r.getAttribute("skinIndex"),s=o instanceof e.GLBufferAttribute?[]:o.array,a=[];for(let e=0;e<s.length;e+=4)a.push([s[e],s[e+1],s[e+2],s[e+3]]);const l=r.getAttribute("skinWeight"),u=l instanceof e.GLBufferAttribute?[]:l.array,d=[];for(let e=0;e<u.length;e+=4)d.push([u[e],u[e+1],u[e+2],u[e+3]]);const h=r.getIndex();if(!h)throw new Error("The geometry doesn't have an index buffer");const c=Array.from(h.array),p=this._excludeTriangles(c,d,a,i),m=[];for(let e=0;e<p;e++)m[e]=c[e];return r.setIndex(m),t.onBeforeRender&&(n.onBeforeRender=t.onBeforeRender),n.bind(new e.Skeleton(t.skeleton.bones,t.skeleton.boneInverses),new e.Matrix4),n}_createHeadlessModelForSkinnedMesh(e,t){const i=[];if(t.skeleton.bones.forEach(((e,t)=>{this._isEraseTarget(e)&&i.push(t)})),!i.length)return t.layers.enable(this._thirdPersonOnlyLayer),void t.layers.enable(this._firstPersonOnlyLayer);t.layers.set(this._thirdPersonOnlyLayer);const n=this._createErasedMesh(t,i);e.add(n)}_createHeadlessModel(t){if("Group"===t.type)if(t.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(t))t.traverse((e=>e.layers.set(this._thirdPersonOnlyLayer)));else{const i=new e.Group;i.name=`_headless_${t.name}`,i.layers.set(this._firstPersonOnlyLayer),t.parent.add(i),t.children.filter((e=>"SkinnedMesh"===e.type)).forEach((e=>{const t=e;this._createHeadlessModelForSkinnedMesh(i,t)}))}else if("SkinnedMesh"===t.type){const e=t;this._createHeadlessModelForSkinnedMesh(t.parent,e)}else this._isEraseTarget(t)&&(t.layers.set(this._thirdPersonOnlyLayer),t.traverse((e=>e.layers.set(this._thirdPersonOnlyLayer))))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode("head")||!!e.parent&&this._isEraseTarget(e.parent)}}y.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,y.DEFAULT_THIRDPERSON_ONLY_LAYER=10;const T=new Set(["1.0","1.0-beta"]);class R{get name(){return"VRMFirstPersonLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return n(this,void 0,void 0,(function*(){const t=e.userData.vrmHumanoid;if(null!==t){if(void 0===t)throw new Error("VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");e.userData.vrmFirstPerson=yield this._import(e,t)}}))}_import(e,t){return n(this,void 0,void 0,(function*(){if(null==t)return null;const i=yield this._v1Import(e,t);if(i)return i;const n=yield this._v0Import(e,t);return n||null}))}_v1Import(e,t){var i,r;return n(this,void 0,void 0,(function*(){const n=this.parser.json;if(!(-1!==(null===(i=n.extensionsUsed)||void 0===i?void 0:i.indexOf("VRMC_vrm"))))return null;const o=null===(r=n.extensions)||void 0===r?void 0:r.VRMC_vrm;if(!o)return null;const a=o.specVersion;if(!T.has(a))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${a}"`),null;const l=o.firstPerson;if(!l)return null;const u=[],d=yield s(e);return Array.from(d.entries()).forEach((([e,t])=>{var i;const n=l.meshAnnotations?l.meshAnnotations.find((t=>t.node===e)):void 0;u.push({meshes:t,type:null!==(i=null==n?void 0:n.type)&&void 0!==i?i:"both"})})),new y(t,u)}))}_v0Import(e,t){var i;return n(this,void 0,void 0,(function*(){const n=this.parser.json,r=null===(i=n.extensions)||void 0===i?void 0:i.VRM;if(!r)return null;const o=r.firstPerson;if(!o)return null;const a=[],l=yield s(e);return Array.from(l.entries()).forEach((([e,t])=>{const i=n.nodes[e],r=o.meshAnnotations?o.meshAnnotations.find((e=>e.mesh===i.mesh)):void 0;a.push({meshes:t,type:this._convertV0FlagToV1Type(null==r?void 0:r.firstPersonFlag)})})),new y(t,a)}))}_convertV0FlagToV1Type(e){return"FirstPersonOnly"===e?"firstPersonOnly":"ThirdPersonOnly"===e?"thirdPersonOnly":"Auto"===e?"auto":"both"}}const E={Auto:"auto",Both:"both",ThirdPersonOnly:"thirdPersonOnly",FirstPersonOnly:"firstPersonOnly"},w=new e.Vector3,P=new e.Vector3,S=new e.Quaternion;class A extends e.Group{constructor(t){super(),this.vrmHumanoid=t,this._boneAxesMap=new Map,Object.values(t.humanBones).forEach((t=>{const i=new e.AxesHelper(1);i.matrixAutoUpdate=!1,i.material.depthTest=!1,i.material.depthWrite=!1,this.add(i),this._boneAxesMap.set(t,i)}))}dispose(){Array.from(this._boneAxesMap.values()).forEach((e=>{e.geometry.dispose(),e.material.dispose()}))}updateMatrixWorld(e){Array.from(this._boneAxesMap.entries()).forEach((([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(w,S,P);const i=w.set(.1,.1,.1).divide(P);t.matrix.copy(e.node.matrixWorld).scale(i)})),super.updateMatrixWorld(e)}}const L=["hips","spine","chest","upperChest","neck","head","leftEye","rightEye","jaw","leftUpperLeg","leftLowerLeg","leftFoot","leftToes","rightUpperLeg","rightLowerLeg","rightFoot","rightToes","leftShoulder","leftUpperArm","leftLowerArm","leftHand","rightShoulder","rightUpperArm","rightLowerArm","rightHand","leftThumbMetacarpal","leftThumbProximal","leftThumbDistal","leftIndexProximal","leftIndexIntermediate","leftIndexDistal","leftMiddleProximal","leftMiddleIntermediate","leftMiddleDistal","leftRingProximal","leftRingIntermediate","leftRingDistal","leftLittleProximal","leftLittleIntermediate","leftLittleDistal","rightThumbMetacarpal","rightThumbProximal","rightThumbDistal","rightIndexProximal","rightIndexIntermediate","rightIndexDistal","rightMiddleProximal","rightMiddleIntermediate","rightMiddleDistal","rightRingProximal","rightRingIntermediate","rightRingDistal","rightLittleProximal","rightLittleIntermediate","rightLittleDistal"],I={Hips:"hips",Spine:"spine",Chest:"chest",UpperChest:"upperChest",Neck:"neck",Head:"head",LeftEye:"leftEye",RightEye:"rightEye",Jaw:"jaw",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",LeftToes:"leftToes",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",RightToes:"rightToes",LeftShoulder:"leftShoulder",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightShoulder:"rightShoulder",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand",LeftThumbMetacarpal:"leftThumbMetacarpal",LeftThumbProximal:"leftThumbProximal",LeftThumbDistal:"leftThumbDistal",LeftIndexProximal:"leftIndexProximal",LeftIndexIntermediate:"leftIndexIntermediate",LeftIndexDistal:"leftIndexDistal",LeftMiddleProximal:"leftMiddleProximal",LeftMiddleIntermediate:"leftMiddleIntermediate",LeftMiddleDistal:"leftMiddleDistal",LeftRingProximal:"leftRingProximal",LeftRingIntermediate:"leftRingIntermediate",LeftRingDistal:"leftRingDistal",LeftLittleProximal:"leftLittleProximal",LeftLittleIntermediate:"leftLittleIntermediate",LeftLittleDistal:"leftLittleDistal",RightThumbMetacarpal:"rightThumbMetacarpal",RightThumbProximal:"rightThumbProximal",RightThumbDistal:"rightThumbDistal",RightIndexProximal:"rightIndexProximal",RightIndexIntermediate:"rightIndexIntermediate",RightIndexDistal:"rightIndexDistal",RightMiddleProximal:"rightMiddleProximal",RightMiddleIntermediate:"rightMiddleIntermediate",RightMiddleDistal:"rightMiddleDistal",RightRingProximal:"rightRingProximal",RightRingIntermediate:"rightRingIntermediate",RightRingDistal:"rightRingDistal",RightLittleProximal:"rightLittleProximal",RightLittleIntermediate:"rightLittleIntermediate",RightLittleDistal:"rightLittleDistal"},b={hips:null,spine:"hips",chest:"spine",upperChest:"chest",neck:"upperChest",head:"neck",leftEye:"head",rightEye:"head",jaw:"head",leftUpperLeg:"hips",leftLowerLeg:"leftUpperLeg",leftFoot:"leftLowerLeg",leftToes:"leftFoot",rightUpperLeg:"hips",rightLowerLeg:"rightUpperLeg",rightFoot:"rightLowerLeg",rightToes:"rightFoot",leftShoulder:"upperChest",leftUpperArm:"leftShoulder",leftLowerArm:"leftUpperArm",leftHand:"leftLowerArm",rightShoulder:"upperChest",rightUpperArm:"rightShoulder",rightLowerArm:"rightUpperArm",rightHand:"rightLowerArm",leftThumbMetacarpal:"leftHand",leftThumbProximal:"leftThumbMetacarpal",leftThumbDistal:"leftThumbProximal",leftIndexProximal:"leftHand",leftIndexIntermediate:"leftIndexProximal",leftIndexDistal:"leftIndexIntermediate",leftMiddleProximal:"leftHand",leftMiddleIntermediate:"leftMiddleProximal",leftMiddleDistal:"leftMiddleIntermediate",leftRingProximal:"leftHand",leftRingIntermediate:"leftRingProximal",leftRingDistal:"leftRingIntermediate",leftLittleProximal:"leftHand",leftLittleIntermediate:"leftLittleProximal",leftLittleDistal:"leftLittleIntermediate",rightThumbMetacarpal:"rightHand",rightThumbProximal:"rightThumbMetacarpal",rightThumbDistal:"rightThumbProximal",rightIndexProximal:"rightHand",rightIndexIntermediate:"rightIndexProximal",rightIndexDistal:"rightIndexIntermediate",rightMiddleProximal:"rightHand",rightMiddleIntermediate:"rightMiddleProximal",rightMiddleDistal:"rightMiddleIntermediate",rightRingProximal:"rightHand",rightRingIntermediate:"rightRingProximal",rightRingDistal:"rightRingIntermediate",rightLittleProximal:"rightHand",rightLittleIntermediate:"rightLittleProximal",rightLittleDistal:"rightLittleIntermediate"};function U(e){return e.invert?e.invert():e.inverse(),e}const O=new e.Vector3,N=new e.Quaternion;class V{constructor(e){this.humanBones=e,this.restPose=this.getAbsolutePose()}getAbsolutePose(){const e={};return Object.keys(this.humanBones).forEach((t=>{const i=t,n=this.getBoneNode(i);n&&(O.copy(n.position),N.copy(n.quaternion),e[i]={position:O.toArray(),rotation:N.toArray()})})),e}getPose(){const e={};return Object.keys(this.humanBones).forEach((t=>{const i=t,n=this.getBoneNode(i);if(!n)return;O.set(0,0,0),N.identity();const r=this.restPose[i];(null==r?void 0:r.position)&&O.fromArray(r.position).negate(),(null==r?void 0:r.rotation)&&U(N.fromArray(r.rotation)),O.add(n.position),N.premultiply(n.quaternion),e[i]={position:O.toArray(),rotation:N.toArray()}})),e}setPose(e){Object.entries(e).forEach((([e,t])=>{const i=e,n=this.getBoneNode(i);if(!n)return;const r=this.restPose[i];r&&((null==t?void 0:t.position)&&(n.position.fromArray(t.position),r.position&&n.position.add(O.fromArray(r.position))),(null==t?void 0:t.rotation)&&(n.quaternion.fromArray(t.rotation),r.rotation&&n.quaternion.multiply(N.fromArray(r.rotation))))}))}resetPose(){Object.entries(this.restPose).forEach((([e,t])=>{const i=this.getBoneNode(e);i&&((null==t?void 0:t.position)&&i.position.fromArray(t.position),(null==t?void 0:t.rotation)&&i.quaternion.fromArray(t.rotation))}))}getBone(e){var t;return null!==(t=this.humanBones[e])&&void 0!==t?t:void 0}getBoneNode(e){var t,i;return null!==(i=null===(t=this.humanBones[e])||void 0===t?void 0:t.node)&&void 0!==i?i:null}}const C=new e.Vector3,D=new e.Quaternion,F=new e.Vector3;class H extends V{static _setupTransforms(t){const i=new e.Object3D;i.name="VRMHumanoidRig";const n={},r={},o={};L.forEach((i=>{var s;const a=t.getBoneNode(i);if(a){const t=new e.Vector3,l=new e.Quaternion;a.updateWorldMatrix(!0,!1),a.matrixWorld.decompose(t,l,C),n[i]=t,r[i]=a.quaternion.clone();const u=new e.Quaternion;null===(s=a.parent)||void 0===s||s.matrixWorld.decompose(C,u,C),o[i]=u}}));const s={};return L.forEach((r=>{var o;const a=t.getBoneNode(r);if(a){const t=n[r];let l,u=r;for(;null==l&&(u=b[u],null!=u);)l=n[u];const d=new e.Object3D;d.name="Normalized_"+a.name;(u?null===(o=s[u])||void 0===o?void 0:o.node:i).add(d),d.position.copy(t),l&&d.position.sub(l),s[r]={node:d}}})),{rigBones:s,root:i,parentWorldRotations:o,boneRotations:r}}constructor(e){const{rigBones:t,root:i,parentWorldRotations:n,boneRotations:r}=H._setupTransforms(e);super(t),this.original=e,this.root=i,this._parentWorldRotations=n,this._boneRotations=r}update(){L.forEach((e=>{const t=this.original.getBoneNode(e);if(null!=t){const i=this.getBoneNode(e),n=this._parentWorldRotations[e],r=D.copy(n).invert(),o=this._boneRotations[e];if(t.quaternion.copy(i.quaternion).multiply(n).premultiply(r).multiply(o),"hips"===e){const e=i.getWorldPosition(F);t.parent.updateWorldMatrix(!0,!1);const n=t.parent.matrixWorld,r=e.applyMatrix4(n.invert());t.position.copy(r)}}}))}}class B{get restPose(){return console.warn("VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead."),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,t){var i;this.autoUpdateHumanBones=null===(i=null==t?void 0:t.autoUpdateHumanBones)||void 0===i||i,this._rawHumanBones=new V(e),this._normalizedHumanBones=new H(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new V(e.humanBones),this._normalizedHumanBones=new H(this._rawHumanBones),this}clone(){return new B(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn("VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead."),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn("VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead."),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn("VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead."),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn("VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead."),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn("VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead."),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn("VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead."),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}}const k={Hips:"hips",Spine:"spine",Head:"head",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand"},W=new Set(["1.0","1.0-beta"]),z={leftThumbProximal:"leftThumbMetacarpal",leftThumbIntermediate:"leftThumbProximal",rightThumbProximal:"rightThumbMetacarpal",rightThumbIntermediate:"rightThumbProximal"};class G{get name(){return"VRMHumanoidLoaderPlugin"}constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot,this.autoUpdateHumanBones=null==t?void 0:t.autoUpdateHumanBones}afterRoot(e){return n(this,void 0,void 0,(function*(){e.userData.vrmHumanoid=yield this._import(e)}))}_import(e){return n(this,void 0,void 0,(function*(){const t=yield this._v1Import(e);if(t)return t;const i=yield this._v0Import(e);return i||null}))}_v1Import(e){var t,i;return n(this,void 0,void 0,(function*(){const r=this.parser.json;if(!(-1!==(null===(t=r.extensionsUsed)||void 0===t?void 0:t.indexOf("VRMC_vrm"))))return null;const o=null===(i=r.extensions)||void 0===i?void 0:i.VRMC_vrm;if(!o)return null;const s=o.specVersion;if(!W.has(s))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${s}"`),null;const a=o.humanoid;if(!a)return null;const l=null!=a.humanBones.leftThumbIntermediate||null!=a.humanBones.rightThumbIntermediate,u={};null!=a.humanBones&&(yield Promise.all(Object.entries(a.humanBones).map((([e,t])=>n(this,void 0,void 0,(function*(){let i=e;const n=t.node;if(l){const e=z[i];null!=e&&(i=e)}const r=yield this.parser.getDependency("node",n);null!=r?u[i]={node:r}:console.warn(`A glTF node bound to the humanoid bone ${i} (index = ${n}) does not exist`)}))))));const d=new B(this._ensureRequiredBonesExist(u),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(d.normalizedHumanBonesRoot),this.helperRoot){const e=new A(d);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return d}))}_v0Import(e){var t;return n(this,void 0,void 0,(function*(){const i=this.parser.json,r=null===(t=i.extensions)||void 0===t?void 0:t.VRM;if(!r)return null;const o=r.humanoid;if(!o)return null;const s={};null!=o.humanBones&&(yield Promise.all(o.humanBones.map((e=>n(this,void 0,void 0,(function*(){const t=e.bone,i=e.node;if(null==t||null==i)return;const n=yield this.parser.getDependency("node",i);if(null==n)return void console.warn(`A glTF node bound to the humanoid bone ${t} (index = ${i}) does not exist`);const r=z[t],o=null!=r?r:t;null==s[o]?s[o]={node:n}:console.warn(`Multiple bone entries for ${o} detected (index = ${i}), ignoring duplicated entries.`)}))))));const a=new B(this._ensureRequiredBonesExist(s),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(e.scene.add(a.normalizedHumanBonesRoot),this.helperRoot){const e=new A(a);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return a}))}_ensureRequiredBonesExist(e){const t=Object.values(k).filter((t=>null==e[t]));if(t.length>0)throw new Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${t.join(", ")}`);return e}}class Q extends e.BufferGeometry{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new e.BufferAttribute(new Float32Array(195),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(189),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,e=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),e&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let e=0;e<64;e++){const t=e/63*this._currentTheta;this._attrPos.setXYZ(e+1,this._currentRadius*Math.sin(t),0,this._currentRadius*Math.cos(t))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<63;e++)this._attrIndex.setXYZ(3*e,0,e+1,e+2);this._attrIndex.needsUpdate=!0}}class j extends e.BufferGeometry{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new e.Vector3,this._currentTail=new e.Vector3,this._attrPos=new e.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,e=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){const t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(2*e,e,t),this._attrIndex.setXY(64+2*e,32+e,32+t),this._attrIndex.setXY(128+2*e,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}}const X=new e.Quaternion,Y=new e.Quaternion,q=new e.Vector3,$=new e.Vector3,Z=Math.sqrt(2)/2,J=new e.Quaternion(0,0,-Z,Z),K=new e.Vector3(0,1,0);class ee extends e.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=t;{const t=new Q;t.radius=.5;const i=new e.MeshBasicMaterial({color:65280,transparent:!0,opacity:.5,side:e.DoubleSide,depthTest:!1,depthWrite:!1});this._meshPitch=new e.Mesh(t,i),this.add(this._meshPitch)}{const t=new Q;t.radius=.5;const i=new e.MeshBasicMaterial({color:16711680,transparent:!0,opacity:.5,side:e.DoubleSide,depthTest:!1,depthWrite:!1});this._meshYaw=new e.Mesh(t,i),this.add(this._meshYaw)}{const t=new j;t.radius=.1;const i=new e.LineBasicMaterial({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new e.LineSegments(t,i),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(t){const i=e.MathUtils.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=i,this._meshYaw.geometry.update();const n=e.MathUtils.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(q),this.vrmLookAt.getLookAtWorldQuaternion(X),X.multiply(this.vrmLookAt.getFaceFrontQuaternion(Y)),this._meshYaw.position.copy(q),this._meshYaw.quaternion.copy(X),this._meshPitch.position.copy(q),this._meshPitch.quaternion.copy(X),this._meshPitch.quaternion.multiply(Y.setFromAxisAngle(K,i)),this._meshPitch.quaternion.multiply(J);const{target:r,autoUpdate:o}=this.vrmLookAt;null!=r&&o&&(r.getWorldPosition($).sub(q),this._lineTarget.geometry.tail.copy($),this._lineTarget.geometry.update(),this._lineTarget.position.copy(q)),super.updateMatrixWorld(t)}}const te=new e.Vector3,ie=new e.Vector3;function ne(e,t){return e.matrixWorld.decompose(te,t,ie),t}function re(e){return[Math.atan2(-e.z,e.x),Math.atan2(e.y,Math.sqrt(e.x*e.x+e.z*e.z))]}function oe(e){const t=Math.round(e/2/Math.PI);return e-2*Math.PI*t}const se=new e.Vector3(0,0,1),ae=new e.Vector3,le=new e.Vector3,ue=new e.Vector3,de=new e.Quaternion,he=new e.Quaternion,ce=new e.Quaternion,pe=new e.Quaternion,me=new e.Euler;class fe{get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn("VRMLookAt: euler is deprecated. use getEuler() instead."),this.getEuler(new e.Euler)}constructor(t,i){this.offsetFromHeadBone=new e.Vector3,this.autoUpdate=!0,this.faceFront=new e.Vector3(0,0,1),this.humanoid=t,this.applier=i,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new e.Quaternion)}getEuler(t){return t.set(e.MathUtils.DEG2RAD*this._pitch,e.MathUtils.DEG2RAD*this._yaw,0,"YXZ")}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMLookAt: humanoid must be same in order to copy");return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new fe(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){const t=this.humanoid.getRawBoneNode("head");return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){return ne(this.humanoid.getRawBoneNode("head"),e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(se)<.01)return e.copy(this._restHeadWorldQuaternion).invert();const[t,i]=re(this.faceFront);return me.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(me).premultiply(pe.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(he),this.getFaceFrontQuaternion(ce),e.copy(se).applyQuaternion(he).applyQuaternion(ce).applyEuler(this.getEuler(me))}lookAt(t){const i=de.copy(this._restHeadWorldQuaternion).multiply(U(this.getLookAtWorldQuaternion(he))),n=this.getLookAtWorldPosition(le),r=ue.copy(t).sub(n).applyQuaternion(i).normalize(),[o,s]=re(this.faceFront),[a,l]=re(r),u=oe(a-o),d=oe(s-l);this._yaw=e.MathUtils.RAD2DEG*u,this._pitch=e.MathUtils.RAD2DEG*d,this._needsUpdate=!0}update(e){null!=this.target&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(ae)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}}fe.EULER_ORDER="YXZ";const ge=new e.Vector3(0,0,1),ve=new e.Quaternion,_e=new e.Quaternion,Me=new e.Euler(0,0,0,"YXZ");class xe{constructor(t,i,n,r,o){this.humanoid=t,this.rangeMapHorizontalInner=i,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=r,this.rangeMapVerticalUp=o,this.faceFront=new e.Vector3(0,0,1),this._restQuatLeftEye=new e.Quaternion,this._restQuatRightEye=new e.Quaternion,this._restLeftEyeParentWorldQuat=new e.Quaternion,this._restRightEyeParentWorldQuat=new e.Quaternion;const s=this.humanoid.getRawBoneNode("leftEye"),a=this.humanoid.getRawBoneNode("rightEye");s&&(this._restQuatLeftEye.copy(s.quaternion),ne(s.parent,this._restLeftEyeParentWorldQuat)),a&&(this._restQuatRightEye.copy(a.quaternion),ne(a.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(t,i){const n=this.humanoid.getRawBoneNode("leftEye"),r=this.humanoid.getRawBoneNode("rightEye"),o=this.humanoid.getNormalizedBoneNode("leftEye"),s=this.humanoid.getNormalizedBoneNode("rightEye");n&&(Me.x=i<0?-e.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-i):e.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(i),Me.y=t<0?-e.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(-t):e.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(t),ve.setFromEuler(Me),this._getWorldFaceFrontQuat(_e),o.quaternion.copy(_e).multiply(ve).multiply(_e.invert()),ve.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(o.quaternion).multiply(ve).premultiply(ve.invert()).multiply(this._restQuatLeftEye)),r&&(Me.x=i<0?-e.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-i):e.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(i),Me.y=t<0?-e.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(-t):e.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(t),ve.setFromEuler(Me),this._getWorldFaceFrontQuat(_e),s.quaternion.copy(_e).multiply(ve).multiply(_e.invert()),ve.copy(this._restRightEyeParentWorldQuat),r.quaternion.copy(s.quaternion).multiply(ve).premultiply(ve.invert()).multiply(this._restQuatRightEye))}lookAt(t){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const i=e.MathUtils.RAD2DEG*t.y,n=e.MathUtils.RAD2DEG*t.x;this.applyYawPitch(i,n)}_getWorldFaceFrontQuat(e){if(this.faceFront.distanceToSquared(ge)<.01)return e.identity();const[t,i]=re(this.faceFront);return Me.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(Me)}}xe.type="bone";class ye{constructor(e,t,i,n,r){this.expressions=e,this.rangeMapHorizontalInner=t,this.rangeMapHorizontalOuter=i,this.rangeMapVerticalDown=n,this.rangeMapVerticalUp=r}applyYawPitch(e,t){t<0?(this.expressions.setValue("lookDown",0),this.expressions.setValue("lookUp",this.rangeMapVerticalUp.map(-t))):(this.expressions.setValue("lookUp",0),this.expressions.setValue("lookDown",this.rangeMapVerticalDown.map(t))),e<0?(this.expressions.setValue("lookLeft",0),this.expressions.setValue("lookRight",this.rangeMapHorizontalOuter.map(-e))):(this.expressions.setValue("lookRight",0),this.expressions.setValue("lookLeft",this.rangeMapHorizontalOuter.map(e)))}lookAt(t){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const i=e.MathUtils.RAD2DEG*t.y,n=e.MathUtils.RAD2DEG*t.x;this.applyYawPitch(i,n)}}ye.type="expression";class Te{constructor(e,t){this.inputMaxValue=e,this.outputScale=t}map(e){return this.outputScale*u(e/this.inputMaxValue)}}const Re=new Set(["1.0","1.0-beta"]);class Ee{get name(){return"VRMLookAtLoaderPlugin"}constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot}afterRoot(e){return n(this,void 0,void 0,(function*(){const t=e.userData.vrmHumanoid;if(null===t)return;if(void 0===t)throw new Error("VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");const i=e.userData.vrmExpressionManager;if(null!==i){if(void 0===i)throw new Error("VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first");e.userData.vrmLookAt=yield this._import(e,t,i)}}))}_import(e,t,i){return n(this,void 0,void 0,(function*(){if(null==t||null==i)return null;const n=yield this._v1Import(e,t,i);if(n)return n;const r=yield this._v0Import(e,t,i);return r||null}))}_v1Import(e,t,i){var r,o,s;return n(this,void 0,void 0,(function*(){const e=this.parser.json;if(!(-1!==(null===(r=e.extensionsUsed)||void 0===r?void 0:r.indexOf("VRMC_vrm"))))return null;const n=null===(o=e.extensions)||void 0===o?void 0:o.VRMC_vrm;if(!n)return null;const a=n.specVersion;if(!Re.has(a))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${a}"`),null;const l=n.lookAt;if(!l)return null;const u="expression"===l.type?1:10,d=this._v1ImportRangeMap(l.rangeMapHorizontalInner,u),h=this._v1ImportRangeMap(l.rangeMapHorizontalOuter,u),c=this._v1ImportRangeMap(l.rangeMapVerticalDown,u),p=this._v1ImportRangeMap(l.rangeMapVerticalUp,u);let m;m="expression"===l.type?new ye(i,d,h,c,p):new xe(t,d,h,c,p);const f=this._importLookAt(t,m);return f.offsetFromHeadBone.fromArray(null!==(s=l.offsetFromHeadBone)&&void 0!==s?s:[0,.06,0]),f}))}_v1ImportRangeMap(e,t){var i,n;let r=null!==(i=null==e?void 0:e.inputMaxValue)&&void 0!==i?i:90;const o=null!==(n=null==e?void 0:e.outputScale)&&void 0!==n?n:t;return r<.01&&(console.warn("VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!"),r=.01),new Te(r,o)}_v0Import(e,t,i){var r,o,s,a;return n(this,void 0,void 0,(function*(){const e=this.parser.json,n=null===(r=e.extensions)||void 0===r?void 0:r.VRM;if(!n)return null;const l=n.firstPerson;if(!l)return null;const u="BlendShape"===l.lookAtTypeName?1:10,d=this._v0ImportDegreeMap(l.lookAtHorizontalInner,u),h=this._v0ImportDegreeMap(l.lookAtHorizontalOuter,u),c=this._v0ImportDegreeMap(l.lookAtVerticalDown,u),p=this._v0ImportDegreeMap(l.lookAtVerticalUp,u);let m;m="BlendShape"===l.lookAtTypeName?new ye(i,d,h,c,p):new xe(t,d,h,c,p);const f=this._importLookAt(t,m);return l.firstPersonBoneOffset?f.offsetFromHeadBone.set(null!==(o=l.firstPersonBoneOffset.x)&&void 0!==o?o:0,null!==(s=l.firstPersonBoneOffset.y)&&void 0!==s?s:.06,-(null!==(a=l.firstPersonBoneOffset.z)&&void 0!==a?a:0)):f.offsetFromHeadBone.set(0,.06,0),f.faceFront.set(0,0,-1),m instanceof xe&&m.faceFront.set(0,0,-1),f}))}_v0ImportDegreeMap(e,t){var i,n;const r=null==e?void 0:e.curve;"[0,0,0,1,1,1,1,0]"!==JSON.stringify(r)&&console.warn("Curves of LookAtDegreeMap defined in VRM 0.0 are not supported");let o=null!==(i=null==e?void 0:e.xRange)&&void 0!==i?i:90;const s=null!==(n=null==e?void 0:e.yRange)&&void 0!==n?n:t;return o<.01&&(console.warn("VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!"),o=.01),new Te(o,s)}_importLookAt(e,t){const i=new fe(e,t);if(this.helperRoot){const e=new ee(i);this.helperRoot.add(e),e.renderOrder=this.helperRoot.renderOrder}return i}}const we={Bone:"bone",Expression:"expression"};const Pe=new Set(["1.0","1.0-beta"]);class Se{get name(){return"VRMMetaLoaderPlugin"}constructor(e,t){var i,n,r;this.parser=e,this.needThumbnailImage=null===(i=null==t?void 0:t.needThumbnailImage)||void 0===i||i,this.acceptLicenseUrls=null!==(n=null==t?void 0:t.acceptLicenseUrls)&&void 0!==n?n:["https://vrm.dev/licenses/1.0/"],this.acceptV0Meta=null===(r=null==t?void 0:t.acceptV0Meta)||void 0===r||r}afterRoot(e){return n(this,void 0,void 0,(function*(){e.userData.vrmMeta=yield this._import(e)}))}_import(e){return n(this,void 0,void 0,(function*(){const t=yield this._v1Import(e);if(null!=t)return t;const i=yield this._v0Import(e);return null!=i?i:null}))}_v1Import(e){var t,i,r;return n(this,void 0,void 0,(function*(){const e=this.parser.json;if(!(-1!==(null===(t=e.extensionsUsed)||void 0===t?void 0:t.indexOf("VRMC_vrm"))))return null;const n=null===(i=e.extensions)||void 0===i?void 0:i.VRMC_vrm;if(null==n)return null;const o=n.specVersion;if(!Pe.has(o))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${o}"`),null;const s=n.meta;if(!s)return null;const a=s.licenseUrl;if(!new Set(this.acceptLicenseUrls).has(a))throw new Error(`VRMMetaLoaderPlugin: The license url "${a}" is not accepted`);let l;return this.needThumbnailImage&&null!=s.thumbnailImage&&(l=null!==(r=yield this._extractGLTFImage(s.thumbnailImage))&&void 0!==r?r:void 0),{metaVersion:"1",name:s.name,version:s.version,authors:s.authors,copyrightInformation:s.copyrightInformation,contactInformation:s.contactInformation,references:s.references,thirdPartyLicenses:s.thirdPartyLicenses,thumbnailImage:l,licenseUrl:s.licenseUrl,avatarPermission:s.avatarPermission,allowExcessivelyViolentUsage:s.allowExcessivelyViolentUsage,allowExcessivelySexualUsage:s.allowExcessivelySexualUsage,commercialUsage:s.commercialUsage,allowPoliticalOrReligiousUsage:s.allowPoliticalOrReligiousUsage,allowAntisocialOrHateUsage:s.allowAntisocialOrHateUsage,creditNotation:s.creditNotation,allowRedistribution:s.allowRedistribution,modification:s.modification,otherLicenseUrl:s.otherLicenseUrl}}))}_v0Import(e){var t;return n(this,void 0,void 0,(function*(){const e=this.parser.json,i=null===(t=e.extensions)||void 0===t?void 0:t.VRM;if(!i)return null;const n=i.meta;if(!n)return null;if(!this.acceptV0Meta)throw new Error("VRMMetaLoaderPlugin: Attempted to load VRM0.0 meta but acceptV0Meta is false");let r;return this.needThumbnailImage&&null!=n.texture&&-1!==n.texture&&(r=yield this.parser.getDependency("texture",n.texture)),{metaVersion:"0",allowedUserName:n.allowedUserName,author:n.author,commercialUssageName:n.commercialUssageName,contactInformation:n.contactInformation,licenseName:n.licenseName,otherLicenseUrl:n.otherLicenseUrl,otherPermissionUrl:n.otherPermissionUrl,reference:n.reference,sexualUssageName:n.sexualUssageName,texture:null!=r?r:void 0,title:n.title,version:n.version,violentUssageName:n.violentUssageName}}))}_extractGLTFImage(t){var i;return n(this,void 0,void 0,(function*(){const n=this.parser.json,r=null===(i=n.images)||void 0===i?void 0:i[t];if(null==r)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${t}] of glTF as a thumbnail but the image doesn't exist`),null;let o=r.uri;if(null!=r.bufferView){const e=yield this.parser.getDependency("bufferView",r.bufferView),t=new Blob([e],{type:r.mimeType});o=URL.createObjectURL(t)}if(null==o)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${t}] of glTF as a thumbnail but the image couldn't load properly`),null;const s=new e.ImageLoader;return yield s.loadAsync((a=o,l=this.parser.options.path,"string"!=typeof a||""===a?"":(/^https?:\/\//i.test(l)&&/^\//.test(a)&&(l=l.replace(/(^https?:\/\/[^/]+).*/i,"$1")),/^(https?:)?\/\//i.test(a)||/^data:.*,.*$/i.test(a)||/^blob:.*$/i.test(a)?a:l+a))).catch((e=>(console.error(e),console.warn("VRMMetaLoaderPlugin: Failed to load a thumbnail image"),null)));var a,l}))}}class Ae{constructor(e){this.scene=e.scene,this.meta=e.meta,this.humanoid=e.humanoid,this.expressionManager=e.expressionManager,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt}update(e){this.humanoid.update(),this.lookAt&&this.lookAt.update(e),this.expressionManager&&this.expressionManager.update()}}class Le{get name(){return"VRMC_vrm"}constructor(e,t){var i,n,r,o,s;this.parser=e;const a=null==t?void 0:t.helperRoot,l=null==t?void 0:t.autoUpdateHumanBones;this.expressionPlugin=null!==(i=null==t?void 0:t.expressionPlugin)&&void 0!==i?i:new M(e),this.firstPersonPlugin=null!==(n=null==t?void 0:t.firstPersonPlugin)&&void 0!==n?n:new R(e),this.humanoidPlugin=null!==(r=null==t?void 0:t.humanoidPlugin)&&void 0!==r?r:new G(e,{helperRoot:a,autoUpdateHumanBones:l}),this.lookAtPlugin=null!==(o=null==t?void 0:t.lookAtPlugin)&&void 0!==o?o:new Ee(e,{helperRoot:a}),this.metaPlugin=null!==(s=null==t?void 0:t.metaPlugin)&&void 0!==s?s:new Se(e)}afterRoot(e){return n(this,void 0,void 0,(function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e);const t=e.userData.vrmMeta,i=e.userData.vrmHumanoid;if(t&&i){const n=new Ae({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:i,lookAt:e.userData.vrmLookAt,meta:t});e.userData.vrmCore=n}}))}}class Ie extends Ae{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach((t=>{t.update&&t.update(e)}))}}function be(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))}
12
920
  /*!
13
- * @pixiv/three-vrm-materials-mtoon v2.1.2
921
+ * @pixiv/three-vrm-materials-mtoon v3.0.0-beta.1
14
922
  * MToon (toon material) module for @pixiv/three-vrm
15
923
  *
16
- * Copyright (c) 2020-2024 pixiv Inc.
924
+ * Copyright (c) 2019-2024 pixiv Inc.
17
925
  * @pixiv/three-vrm-materials-mtoon is distributed under MIT License
18
926
  * https://github.com/pixiv/three-vrm/blob/release/LICENSE
19
927
  */
20
- function Ue(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,"function"==typeof SuppressedError&&SuppressedError;const Oe={None:"none",Normal:"normal",LitShadeRate:"litShadeRate",UV:"uv"},Ne={None:"none",WorldCoordinates:"worldCoordinates",ScreenCoordinates:"screenCoordinates"},Ve={3e3:"",3001:"srgb"};function Ce(t){return parseInt(e.REVISION,10)>=152?t.colorSpace:Ve[t.encoding]}class De extends e.ShaderMaterial{get color(){return this.uniforms.litFactor.value}set color(e){this.uniforms.litFactor.value=e}get map(){return this.uniforms.map.value}set map(e){this.uniforms.map.value=e}get normalMap(){return this.uniforms.normalMap.value}set normalMap(e){this.uniforms.normalMap.value=e}get normalScale(){return this.uniforms.normalScale.value}set normalScale(e){this.uniforms.normalScale.value=e}get emissive(){return this.uniforms.emissive.value}set emissive(e){this.uniforms.emissive.value=e}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(e){this.uniforms.emissiveIntensity.value=e}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(e){this.uniforms.emissiveMap.value=e}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(e){this.uniforms.shadeColorFactor.value=e}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(e){this.uniforms.shadeMultiplyTexture.value=e}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(e){this.uniforms.shadingShiftFactor.value=e}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(e){this.uniforms.shadingShiftTexture.value=e}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(e){this.uniforms.shadingShiftTextureScale.value=e}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(e){this.uniforms.shadingToonyFactor.value=e}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(e){this.uniforms.giEqualizationFactor.value=e}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(e){this.uniforms.matcapFactor.value=e}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(e){this.uniforms.matcapTexture.value=e}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(e){this.uniforms.parametricRimColorFactor.value=e}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(e){this.uniforms.rimMultiplyTexture.value=e}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(e){this.uniforms.rimLightingMixFactor.value=e}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(e){this.uniforms.parametricRimFresnelPowerFactor.value=e}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(e){this.uniforms.parametricRimLiftFactor.value=e}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(e){this.uniforms.outlineWidthMultiplyTexture.value=e}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(e){this.uniforms.outlineWidthFactor.value=e}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(e){this.uniforms.outlineColorFactor.value=e}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(e){this.uniforms.outlineLightingMixFactor.value=e}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(e){this.uniforms.uvAnimationMaskTexture.value=e}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(e){this.uniforms.uvAnimationScrollXOffset.value=e}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(e){this.uniforms.uvAnimationScrollYOffset.value=e}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(e){this.uniforms.uvAnimationRotationPhase.value=e}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(e){this._ignoreVertexColor=e,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(e){this._v0CompatShade=e,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this.needsUpdate=!0}get isMToonMaterial(){return!0}constructor(t={}){var i;super({vertexShader:"// #define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n\n#include <common>\n\n// #include <uv_pars_vertex>\n#ifdef MTOON_USE_UV\n varying vec2 vUv;\n\n // COMPAT: pre-r151 uses a common uvTransform\n #if THREE_VRM_THREE_REVISION < 151\n uniform mat3 uvTransform;\n #endif\n#endif\n\n// #include <uv2_pars_vertex>\n// COMAPT: pre-r151 uses uv2 for lightMap and aoMap\n#if THREE_VRM_THREE_REVISION < 151\n #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n uniform mat3 uv2Transform;\n #endif\n#endif\n\n// #include <displacementmap_pars_vertex>\n// #include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\n#ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE\n uniform sampler2D outlineWidthMultiplyTexture;\n uniform mat3 outlineWidthMultiplyTextureUvTransform;\n#endif\n\nuniform float outlineWidthFactor;\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef MTOON_USE_UV\n // COMPAT: pre-r151 uses a common uvTransform\n #if THREE_VRM_THREE_REVISION >= 151\n vUv = uv;\n #else\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n #endif\n #endif\n\n // #include <uv2_vertex>\n // COMAPT: pre-r151 uses uv2 for lightMap and aoMap\n #if THREE_VRM_THREE_REVISION < 151\n #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n #endif\n #endif\n\n #include <color_vertex>\n\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n\n // we need this to compute the outline properly\n objectNormal = normalize( objectNormal );\n\n #include <defaultnormal_vertex>\n\n #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #endif\n\n #include <begin_vertex>\n\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n // #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n\n vViewPosition = - mvPosition.xyz;\n\n float outlineTex = 1.0;\n\n #ifdef OUTLINE\n #ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE\n vec2 outlineWidthMultiplyTextureUv = ( outlineWidthMultiplyTextureUvTransform * vec3( vUv, 1 ) ).xy;\n outlineTex = texture2D( outlineWidthMultiplyTexture, outlineWidthMultiplyTextureUv ).g;\n #endif\n\n #ifdef OUTLINE_WIDTH_WORLD\n float worldNormalLength = length( transformedNormal );\n vec3 outlineOffset = outlineWidthFactor * outlineTex * worldNormalLength * objectNormal;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 );\n #endif\n\n #ifdef OUTLINE_WIDTH_SCREEN\n vec3 clipNormal = ( projectionMatrix * modelViewMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n vec2 projectedNormal = normalize( clipNormal.xy );\n projectedNormal.x *= projectionMatrix[ 0 ].x / projectionMatrix[ 1 ].y;\n gl_Position.xy += 2.0 * outlineWidthFactor * outlineTex * projectedNormal.xy;\n #endif\n\n gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic\n #endif\n\n #include <worldpos_vertex>\n // #include <envmap_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n\n}",fragmentShader:"// #define PHONG\n\nuniform vec3 litFactor;\n\nuniform float opacity;\n\nuniform vec3 shadeColorFactor;\n#ifdef USE_SHADEMULTIPLYTEXTURE\n uniform sampler2D shadeMultiplyTexture;\n uniform mat3 shadeMultiplyTextureUvTransform;\n#endif\n\nuniform float shadingShiftFactor;\nuniform float shadingToonyFactor;\n\n#ifdef USE_SHADINGSHIFTTEXTURE\n uniform sampler2D shadingShiftTexture;\n uniform mat3 shadingShiftTextureUvTransform;\n uniform float shadingShiftTextureScale;\n#endif\n\nuniform float giEqualizationFactor;\n\nuniform vec3 parametricRimColorFactor;\n#ifdef USE_RIMMULTIPLYTEXTURE\n uniform sampler2D rimMultiplyTexture;\n uniform mat3 rimMultiplyTextureUvTransform;\n#endif\nuniform float rimLightingMixFactor;\nuniform float parametricRimFresnelPowerFactor;\nuniform float parametricRimLiftFactor;\n\n#ifdef USE_MATCAPTEXTURE\n uniform vec3 matcapFactor;\n uniform sampler2D matcapTexture;\n uniform mat3 matcapTextureUvTransform;\n#endif\n\nuniform vec3 emissive;\nuniform float emissiveIntensity;\n\nuniform vec3 outlineColorFactor;\nuniform float outlineLightingMixFactor;\n\n#ifdef USE_UVANIMATIONMASKTEXTURE\n uniform sampler2D uvAnimationMaskTexture;\n uniform mat3 uvAnimationMaskTextureUvTransform;\n#endif\n\nuniform float uvAnimationScrollXOffset;\nuniform float uvAnimationScrollYOffset;\nuniform float uvAnimationRotationPhase;\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n\n// #include <uv_pars_fragment>\n#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n varying vec2 vUv;\n#endif\n\n// #include <uv2_pars_fragment>\n// COMAPT: pre-r151 uses uv2 for lightMap and aoMap\n#if THREE_VRM_THREE_REVISION < 151\n #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n #endif\n#endif\n\n#include <map_pars_fragment>\n\n#ifdef USE_MAP\n uniform mat3 mapUvTransform;\n#endif\n\n// #include <alphamap_pars_fragment>\n\n#if THREE_VRM_THREE_REVISION >= 132\n #include <alphatest_pars_fragment>\n#endif\n\n#include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n\n#ifdef USE_EMISSIVEMAP\n uniform mat3 emissiveMapUvTransform;\n#endif\n\n// #include <envmap_common_pars_fragment>\n// #include <envmap_pars_fragment>\n// #include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n\n// #include <bsdfs>\n// COMPAT: pre-r151 doesn't have BRDF_Lambert in <common>\n#if THREE_VRM_THREE_REVISION < 151\n vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n }\n#endif\n\n#include <lights_pars_begin>\n\n#if THREE_VRM_THREE_REVISION >= 132\n #include <normal_pars_fragment>\n#endif\n\n// #include <lights_phong_pars_fragment>\nvarying vec3 vViewPosition;\n\n#if THREE_VRM_THREE_REVISION < 132\n #ifndef FLAT_SHADED\n varying vec3 vNormal;\n #endif\n#endif\n\nstruct MToonMaterial {\n vec3 diffuseColor;\n vec3 shadeColor;\n float shadingShift;\n};\n\nfloat linearstep( float a, float b, float t ) {\n return clamp( ( t - a ) / ( b - a ), 0.0, 1.0 );\n}\n\n/**\n * Convert NdotL into toon shading factor using shadingShift and shadingToony\n */\nfloat getShading(\n const in float dotNL,\n const in float shadow,\n const in float shadingShift\n) {\n float shading = dotNL;\n shading = shading + shadingShift;\n shading = linearstep( -1.0 + shadingToonyFactor, 1.0 - shadingToonyFactor, shading );\n shading *= shadow;\n return shading;\n}\n\n/**\n * Mix diffuseColor and shadeColor using shading factor and light color\n */\nvec3 getDiffuse(\n const in MToonMaterial material,\n const in float shading,\n in vec3 lightColor\n) {\n #ifdef DEBUG_LITSHADERATE\n return vec3( BRDF_Lambert( shading * lightColor ) );\n #endif\n\n #if THREE_VRM_THREE_REVISION < 132\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lightColor *= PI;\n #endif\n #endif\n\n vec3 col = lightColor * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, shading ) );\n\n // The \"comment out if you want to PBR absolutely\" line\n #ifdef V0_COMPAT_SHADE\n col = min( col, material.diffuseColor );\n #endif\n\n return col;\n}\n\n// COMPAT: pre-r156 uses a struct GeometricContext\n#if THREE_VRM_THREE_REVISION >= 157\n void RE_Direct_MToon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) {\n float dotNL = clamp( dot( geometryNormal, directLight.direction ), -1.0, 1.0 );\n vec3 irradiance = directLight.color;\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n\n irradiance *= dotNL;\n\n float shading = getShading( dotNL, shadow, material.shadingShift );\n\n // toon shaded diffuse\n reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color );\n }\n\n void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, inout ReflectedLight reflectedLight ) {\n // indirect diffuse will use diffuseColor, no shadeColor involved\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n }\n#else\n void RE_Direct_MToon( const in IncidentLight directLight, const in GeometricContext geometry, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) {\n float dotNL = clamp( dot( geometry.normal, directLight.direction ), -1.0, 1.0 );\n vec3 irradiance = directLight.color;\n\n #if THREE_VRM_THREE_REVISION < 132\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n #endif\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n\n irradiance *= dotNL;\n\n float shading = getShading( dotNL, shadow, material.shadingShift );\n\n // toon shaded diffuse\n reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color );\n }\n\n void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in GeometricContext geometry, const in MToonMaterial material, inout ReflectedLight reflectedLight ) {\n // indirect diffuse will use diffuseColor, no shadeColor involved\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\n // directSpecular will be used for rim lighting, not an actual specular\n reflectedLight.directSpecular += irradiance;\n }\n#endif\n\n#define RE_Direct RE_Direct_MToon\n#define RE_IndirectDiffuse RE_IndirectDiffuse_MToon\n#define Material_LightProbeLOD( material ) (0)\n\n#include <shadowmap_pars_fragment>\n// #include <bumpmap_pars_fragment>\n\n// #include <normalmap_pars_fragment>\n#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform mat3 normalMapUvTransform;\n uniform vec2 normalScale;\n\n#endif\n\n// COMPAT: USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151\n#if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP )\n\n uniform mat3 normalMatrix;\n\n#endif\n\n// COMPAT: USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( TANGENTSPACE_NORMALMAP ) )\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n // three-vrm specific change: it requires `uv` as an input in order to support uv scrolls\n\n // Temporary compat against shader change @ Three.js r126, r151\n #if THREE_VRM_THREE_REVISION >= 151\n\n mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n vec3 N = surf_norm;\n\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\n return mat3( T * scale, B * scale, N );\n\n }\n\n #elif THREE_VRM_THREE_REVISION >= 126\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n vec3 N = normalize( surf_norm );\n\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n if ( length( T ) == 0.0 || length( B ) == 0.0 ) {\n return surf_norm;\n }\n\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\n return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\n }\n\n #else\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\n // Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n float scale = sign( st1.t * st0.s - st0.t * st1.s ); // we do not care about the magnitude\n\n vec3 S = ( q0 * st1.t - q1 * st0.t ) * scale;\n vec3 T = ( - q0 * st1.s + q1 * st0.s ) * scale;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n\n if ( length( S ) == 0.0 || length( T ) == 0.0 ) {\n return surf_norm;\n }\n\n S = normalize( S );\n T = normalize( T );\n vec3 N = normalize( surf_norm );\n\n #ifdef DOUBLE_SIDED\n\n // Workaround for Adreno GPUs gl_FrontFacing bug. See #15850 and #10331\n\n bool frontFacing = dot( cross( S, T ), N ) > 0.0;\n\n mapN.xy *= ( float( frontFacing ) * 2.0 - 1.0 );\n\n #else\n\n mapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n #endif\n\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n #endif\n\n#endif\n\n// #include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\n// == post correction ==========================================================\nvoid postCorrection() {\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}\n\n// == main procedure ===========================================================\nvoid main() {\n #include <clipping_planes_fragment>\n\n vec2 uv = vec2(0.5, 0.5);\n\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n uv = vUv;\n\n float uvAnimMask = 1.0;\n #ifdef USE_UVANIMATIONMASKTEXTURE\n vec2 uvAnimationMaskTextureUv = ( uvAnimationMaskTextureUvTransform * vec3( uv, 1 ) ).xy;\n uvAnimMask = texture2D( uvAnimationMaskTexture, uvAnimationMaskTextureUv ).b;\n #endif\n\n float uvRotCos = cos( uvAnimationRotationPhase * uvAnimMask );\n float uvRotSin = sin( uvAnimationRotationPhase * uvAnimMask );\n uv = mat2( uvRotCos, -uvRotSin, uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5;\n uv = uv + vec2( uvAnimationScrollXOffset, uvAnimationScrollYOffset ) * uvAnimMask;\n #endif\n\n #ifdef DEBUG_UV\n gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n gl_FragColor = vec4( uv, 0.0, 1.0 );\n #endif\n return;\n #endif\n\n vec4 diffuseColor = vec4( litFactor, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive * emissiveIntensity;\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n vec2 mapUv = ( mapUvTransform * vec3( uv, 1 ) ).xy;\n vec4 sampledDiffuseColor = texture2D( map, mapUv );\n #ifdef DECODE_VIDEO_TEXTURE\n sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n #endif\n diffuseColor *= sampledDiffuseColor;\n #endif\n\n // #include <color_fragment>\n #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )\n diffuseColor.rgb *= vColor;\n #endif\n\n // #include <alphamap_fragment>\n\n #include <alphatest_fragment>\n\n // #include <specularmap_fragment>\n\n // #include <normal_fragment_begin>\n float faceDirection = gl_FrontFacing ? 1.0 : -1.0;\n\n #ifdef FLAT_SHADED\n\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n\n #else\n\n vec3 normal = normalize( vNormal );\n\n #ifdef DOUBLE_SIDED\n\n normal *= faceDirection;\n\n #endif\n\n #endif\n\n #ifdef USE_NORMALMAP\n\n vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy;\n\n #endif\n\n #ifdef USE_NORMALMAP_TANGENTSPACE\n\n #ifdef USE_TANGENT\n\n mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\n #else\n\n mat3 tbn = getTangentFrame( - vViewPosition, normal, normalMapUv );\n\n #endif\n\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\n tbn[0] *= faceDirection;\n tbn[1] *= faceDirection;\n\n #endif\n\n #endif\n\n #ifdef USE_CLEARCOAT_NORMALMAP\n\n #ifdef USE_TANGENT\n\n mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\n #else\n\n mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\n #endif\n\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\n tbn2[0] *= faceDirection;\n tbn2[1] *= faceDirection;\n\n #endif\n\n #endif\n\n // non perturbed normal for clearcoat among others\n\n vec3 nonPerturbedNormal = normal;\n\n #ifdef OUTLINE\n normal *= -1.0;\n #endif\n\n // #include <normal_fragment_maps>\n\n // COMPAT: USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151\n #if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP )\n\n normal = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals\n\n #ifdef FLIP_SIDED\n\n normal = - normal;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n normal = normal * faceDirection;\n\n #else\n\n normal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n #endif\n\n #endif\n\n normal = normalize( normalMatrix * normal );\n\n // COMPAT: USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151\n #elif defined( USE_NORMALMAP_TANGENTSPACE ) || defined( TANGENTSPACE_NORMALMAP )\n\n vec3 mapN = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n\n // COMPAT: pre-r151\n #if THREE_VRM_THREE_REVISION >= 151 || defined( USE_TANGENT )\n\n normal = normalize( tbn * mapN );\n\n #else\n\n // pre-r126\n #if THREE_VRM_THREE_REVISION >= 126\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection );\n\n #else\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN );\n\n #endif\n\n #endif\n\n #endif\n\n // #include <emissivemap_fragment>\n #ifdef USE_EMISSIVEMAP\n vec2 emissiveMapUv = ( emissiveMapUvTransform * vec3( uv, 1 ) ).xy;\n totalEmissiveRadiance *= texture2D( emissiveMap, emissiveMapUv ).rgb;\n #endif\n\n #ifdef DEBUG_NORMAL\n gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 );\n return;\n #endif\n\n // -- MToon: lighting --------------------------------------------------------\n // accumulation\n // #include <lights_phong_fragment>\n MToonMaterial material;\n\n material.diffuseColor = diffuseColor.rgb;\n\n material.shadeColor = shadeColorFactor;\n #ifdef USE_SHADEMULTIPLYTEXTURE\n vec2 shadeMultiplyTextureUv = ( shadeMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;\n material.shadeColor *= texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv ).rgb;\n #endif\n\n #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )\n material.shadeColor.rgb *= vColor;\n #endif\n\n material.shadingShift = shadingShiftFactor;\n #ifdef USE_SHADINGSHIFTTEXTURE\n vec2 shadingShiftTextureUv = ( shadingShiftTextureUvTransform * vec3( uv, 1 ) ).xy;\n material.shadingShift += texture2D( shadingShiftTexture, shadingShiftTextureUv ).r * shadingShiftTextureScale;\n #endif\n\n // #include <lights_fragment_begin>\n\n // MToon Specific changes:\n // Since we want to take shadows into account of shading instead of irradiance,\n // we had to modify the codes that multiplies the results of shadowmap into color of direct lights.\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n vec3 geometryPosition = - vViewPosition;\n vec3 geometryNormal = normal;\n vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n vec3 geometryClearcoatNormal;\n\n #ifdef USE_CLEARCOAT\n\n geometryClearcoatNormal = clearcoatNormal;\n\n #endif\n #else\n GeometricContext geometry;\n\n geometry.position = - vViewPosition;\n geometry.normal = normal;\n geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n #ifdef USE_CLEARCOAT\n\n geometry.clearcoatNormal = clearcoatNormal;\n\n #endif\n #endif\n\n IncidentLight directLight;\n\n // since these variables will be used in unrolled loop, we have to define in prior\n float shadow;\n\n #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\n PointLight pointLight;\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\n pointLight = pointLights[ i ];\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n getPointLightInfo( pointLight, geometryPosition, directLight );\n #elif THREE_VRM_THREE_REVISION >= 132\n getPointLightInfo( pointLight, geometry, directLight );\n #else\n getPointDirectLightIrradiance( pointLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );\n #else\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n #endif\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\n SpotLight spotLight;\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\n spotLight = spotLights[ i ];\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n getSpotLightInfo( spotLight, geometryPosition, directLight );\n #elif THREE_VRM_THREE_REVISION >= 132\n getSpotLightInfo( spotLight, geometry, directLight );\n #else\n getSpotDirectLightIrradiance( spotLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );\n #else\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n #endif\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\n DirectionalLight directionalLight;\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n directionalLight = directionalLights[ i ];\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n getDirectionalLightInfo( directionalLight, directLight );\n #elif THREE_VRM_THREE_REVISION >= 132\n getDirectionalLightInfo( directionalLight, geometry, directLight );\n #else\n getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n #endif\n\n shadow = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );\n #else\n RE_Direct( directLight, geometry, material, shadow, reflectedLight );\n #endif\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n // #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\n // RectAreaLight rectAreaLight;\n\n // #pragma unroll_loop_start\n // for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\n // rectAreaLight = rectAreaLights[ i ];\n // RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\n // }\n // #pragma unroll_loop_end\n\n // #endif\n\n #if defined( RE_IndirectDiffuse )\n\n vec3 iblIrradiance = vec3( 0.0 );\n\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n // COMPAT: pre-r156 doesn't have a define USE_LIGHT_PROBES\n #if THREE_VRM_THREE_REVISION >= 157\n #if defined( USE_LIGHT_PROBES )\n irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n #endif\n #elif THREE_VRM_THREE_REVISION >= 133\n irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n #else\n irradiance += getLightProbeIrradiance( lightProbe, geometry );\n #endif\n\n #if ( NUM_HEMI_LIGHTS > 0 )\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\n // COMPAT: pre-r156 uses a struct GeometricContext\n #if THREE_VRM_THREE_REVISION >= 157\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n #elif THREE_VRM_THREE_REVISION >= 133\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n #else\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n #endif\n\n }\n #pragma unroll_loop_end\n\n #endif\n\n #endif\n\n // #if defined( RE_IndirectSpecular )\n\n // vec3 radiance = vec3( 0.0 );\n // vec3 clearcoatRadiance = vec3( 0.0 );\n\n // #endif\n\n #include <lights_fragment_maps>\n #include <lights_fragment_end>\n\n // modulation\n #include <aomap_fragment>\n\n vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\n #ifdef DEBUG_LITSHADERATE\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n return;\n #endif\n\n // -- MToon: rim lighting -----------------------------------------\n vec3 viewDir = normalize( vViewPosition );\n\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n reflectedLight.directSpecular /= PI;\n #endif\n vec3 rimMix = mix( vec3( 1.0 ), reflectedLight.directSpecular, 1.0 );\n\n vec3 rim = parametricRimColorFactor * pow( saturate( 1.0 - dot( viewDir, normal ) + parametricRimLiftFactor ), parametricRimFresnelPowerFactor );\n\n #ifdef USE_MATCAPTEXTURE\n {\n vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) );\n vec3 y = cross( viewDir, x ); // guaranteed to be normalized\n vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) );\n sphereUv = ( matcapTextureUvTransform * vec3( sphereUv, 1 ) ).xy;\n vec3 matcap = texture2D( matcapTexture, sphereUv ).rgb;\n rim += matcapFactor * matcap;\n }\n #endif\n\n #ifdef USE_RIMMULTIPLYTEXTURE\n vec2 rimMultiplyTextureUv = ( rimMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;\n rim *= texture2D( rimMultiplyTexture, rimMultiplyTextureUv ).rgb;\n #endif\n\n col += rimMix * rim;\n\n // -- MToon: Emission --------------------------------------------------------\n col += totalEmissiveRadiance;\n\n // #include <envmap_fragment>\n\n // -- Almost done! -----------------------------------------------------------\n #if defined( OUTLINE )\n col = outlineColorFactor.rgb * mix( vec3( 1.0 ), col, outlineLightingMixFactor );\n #endif\n\n #ifdef OPAQUE\n diffuseColor.a = 1.0;\n #endif\n\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n}\n"}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=e.TangentSpaceNormalMap,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=Oe.None,this._outlineWidthMode=Ne.None,this._isOutline=!1,t.transparentWithZWrite&&(t.depthWrite=!0),delete t.transparentWithZWrite,t.fog=!0,t.lights=!0,t.clipping=!0,parseInt(e.REVISION,10)<129&&(t.skinning=t.skinning||!1),parseInt(e.REVISION,10)<131&&(t.morphTargets=t.morphTargets||!1,t.morphNormals=t.morphNormals||!1),this.uniforms=e.UniformsUtils.merge([e.UniformsLib.common,e.UniformsLib.normalmap,e.UniformsLib.emissivemap,e.UniformsLib.fog,e.UniformsLib.lights,{litFactor:{value:new e.Color(1,1,1)},mapUvTransform:{value:new e.Matrix3},colorAlpha:{value:1},normalMapUvTransform:{value:new e.Matrix3},shadeColorFactor:{value:new e.Color(0,0,0)},shadeMultiplyTexture:{value:null},shadeMultiplyTextureUvTransform:{value:new e.Matrix3},shadingShiftFactor:{value:0},shadingShiftTexture:{value:null},shadingShiftTextureUvTransform:{value:new e.Matrix3},shadingShiftTextureScale:{value:1},shadingToonyFactor:{value:.9},giEqualizationFactor:{value:.9},matcapFactor:{value:new e.Color(1,1,1)},matcapTexture:{value:null},matcapTextureUvTransform:{value:new e.Matrix3},parametricRimColorFactor:{value:new e.Color(0,0,0)},rimMultiplyTexture:{value:null},rimMultiplyTextureUvTransform:{value:new e.Matrix3},rimLightingMixFactor:{value:1},parametricRimFresnelPowerFactor:{value:5},parametricRimLiftFactor:{value:0},emissive:{value:new e.Color(0,0,0)},emissiveIntensity:{value:1},emissiveMapUvTransform:{value:new e.Matrix3},outlineWidthMultiplyTexture:{value:null},outlineWidthMultiplyTextureUvTransform:{value:new e.Matrix3},outlineWidthFactor:{value:0},outlineColorFactor:{value:new e.Color(0,0,0)},outlineLightingMixFactor:{value:1},uvAnimationMaskTexture:{value:null},uvAnimationMaskTextureUvTransform:{value:new e.Matrix3},uvAnimationScrollXOffset:{value:0},uvAnimationScrollYOffset:{value:0},uvAnimationRotationPhase:{value:0}},null!==(i=t.uniforms)&&void 0!==i?i:{}]),this.setValues(t),this._uploadUniformsWorkaround(),this.customProgramCacheKey=()=>[...Object.entries(this._generateDefines()).map((([e,t])=>`${e}:${t}`)),this.matcapTexture?`matcapTextureColorSpace:${Ce(this.matcapTexture)}`:"",this.shadeMultiplyTexture?`shadeMultiplyTextureColorSpace:${Ce(this.shadeMultiplyTexture)}`:"",this.rimMultiplyTexture?`rimMultiplyTextureColorSpace:${Ce(this.rimMultiplyTexture)}`:""].join(","),this.onBeforeCompile=t=>{const i=parseInt(e.REVISION,10),n=Object.entries(Object.assign(Object.assign({},this._generateDefines()),this.defines)).filter((([e,t])=>!!t)).map((([e,t])=>`#define ${e} ${t}`)).join("\n")+"\n";t.vertexShader=n+t.vertexShader,t.fragmentShader=n+t.fragmentShader,i<154&&(t.fragmentShader=t.fragmentShader.replace("#include <colorspace_fragment>","#include <encodings_fragment>")),i<132&&(t.fragmentShader=t.fragmentShader.replace("#include <normal_pars_fragment>",""),t.fragmentShader=t.fragmentShader.replace("#include <alphatest_pars_fragment>",""))}}update(e){this._uploadUniformsWorkaround(),this._updateUVAnimation(e)}copy(e){return super.copy(e),this.map=e.map,this.normalMap=e.normalMap,this.emissiveMap=e.emissiveMap,this.shadeMultiplyTexture=e.shadeMultiplyTexture,this.shadingShiftTexture=e.shadingShiftTexture,this.matcapTexture=e.matcapTexture,this.rimMultiplyTexture=e.rimMultiplyTexture,this.outlineWidthMultiplyTexture=e.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=e.uvAnimationMaskTexture,this.normalMapType=e.normalMapType,this.uvAnimationScrollXSpeedFactor=e.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=e.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=e.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=e.ignoreVertexColor,this.v0CompatShade=e.v0CompatShade,this.debugMode=e.debugMode,this.outlineWidthMode=e.outlineWidthMode,this.isOutline=e.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(e){this.uniforms.uvAnimationScrollXOffset.value+=e*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=e*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=e*this.uvAnimationRotationSpeedFactor,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform);parseInt(e.REVISION,10)>=132&&(this.uniforms.alphaTest.value=this.alphaTest),this.uniformsNeedUpdate=!0}_generateDefines(){const t=parseInt(e.REVISION,10),i=null!==this.outlineWidthMultiplyTexture,n=null!==this.map||null!==this.emissiveMap||null!==this.shadeMultiplyTexture||null!==this.shadingShiftTexture||null!==this.rimMultiplyTexture||null!==this.uvAnimationMaskTexture;return{THREE_VRM_THREE_REVISION:t,OUTLINE:this._isOutline,MTOON_USE_UV:i||n,MTOON_UVS_VERTEX_ONLY:i&&!n,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:null!==this.shadeMultiplyTexture,USE_SHADINGSHIFTTEXTURE:null!==this.shadingShiftTexture,USE_MATCAPTEXTURE:null!==this.matcapTexture,USE_RIMMULTIPLYTEXTURE:null!==this.rimMultiplyTexture,USE_OUTLINEWIDTHMULTIPLYTEXTURE:this._isOutline&&null!==this.outlineWidthMultiplyTexture,USE_UVANIMATIONMASKTEXTURE:null!==this.uvAnimationMaskTexture,IGNORE_VERTEX_COLOR:!0===this._ignoreVertexColor,DEBUG_NORMAL:"normal"===this._debugMode,DEBUG_LITSHADERATE:"litShadeRate"===this._debugMode,DEBUG_UV:"uv"===this._debugMode,OUTLINE_WIDTH_WORLD:this._isOutline&&this._outlineWidthMode===Ne.WorldCoordinates,OUTLINE_WIDTH_SCREEN:this._isOutline&&this._outlineWidthMode===Ne.ScreenCoordinates}}_updateTextureMatrix(e,t){e.value&&(e.value.matrixAutoUpdate&&e.value.updateMatrix(),t.value.copy(e.value.matrix))}}const Fe={"":3e3,srgb:3001};class He{get pending(){return Promise.all(this._pendings)}constructor(e,t){this._parser=e,this._materialParams=t,this._pendings=[]}assignPrimitive(e,t){null!=t&&(this._materialParams[e]=t)}assignColor(t,i,n){null!=i&&(this._materialParams[t]=(new e.Color).fromArray(i),n&&this._materialParams[t].convertSRGBToLinear())}assignTexture(t,i,n){return Ue(this,void 0,void 0,(function*(){const r=(()=>Ue(this,void 0,void 0,(function*(){null!=i&&(yield this._parser.assignTexture(this._materialParams,t,i),n&&function(t,i){parseInt(e.REVISION,10)>=152?t.colorSpace=i:t.encoding=Fe[i]}(this._materialParams[t],"srgb"))})))();return this._pendings.push(r),r}))}assignTextureByIndex(e,t,i){return Ue(this,void 0,void 0,(function*(){return this.assignTexture(e,null!=t?{index:t}:void 0,i)}))}}const Be=new Set(["1.0","1.0-beta"]);class ke{get name(){return ke.EXTENSION_NAME}constructor(e,t={}){var i,n,r;this.parser=e,this.renderOrderOffset=null!==(i=t.renderOrderOffset)&&void 0!==i?i:0,this.v0CompatShade=null!==(n=t.v0CompatShade)&&void 0!==n&&n,this.debugMode=null!==(r=t.debugMode)&&void 0!==r?r:"none",this._mToonMaterialSet=new Set}beforeRoot(){return Ue(this,void 0,void 0,(function*(){this._removeUnlitExtensionIfMToonExists()}))}afterRoot(e){return Ue(this,void 0,void 0,(function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)}))}getMaterialType(e){return this._getMToonExtension(e)?De:null}extendMaterialParams(e,t){const i=this._getMToonExtension(e);return i?this._extendMaterialParams(i,t):null}loadMesh(e){var t;return Ue(this,void 0,void 0,(function*(){const i=this.parser,n=i.json,r=null===(t=n.meshes)||void 0===t?void 0:t[e];if(null==r)throw new Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);const o=r.primitives,s=yield i.loadMesh(e);if(1===o.length){const e=s,t=o[0].material;null!=t&&this._setupPrimitive(e,t)}else{const e=s;for(let t=0;t<o.length;t++){const i=e.children[t],n=o[t].material;null!=n&&this._setupPrimitive(i,n)}}return s}))}_removeUnlitExtensionIfMToonExists(){const e=this.parser.json.materials;null==e||e.map(((e,t)=>{var i;this._getMToonExtension(t)&&(null===(i=e.extensions)||void 0===i?void 0:i.KHR_materials_unlit)&&delete e.extensions.KHR_materials_unlit}))}_getMToonExtension(e){var t,i;const n=null===(t=this.parser.json.materials)||void 0===t?void 0:t[e];if(null==n)return void console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);const r=null===(i=n.extensions)||void 0===i?void 0:i[ke.EXTENSION_NAME];if(null==r)return;const o=r.specVersion;if(Be.has(o))return r;console.warn(`MToonMaterialLoaderPlugin: Unknown ${ke.EXTENSION_NAME} specVersion "${o}"`)}_extendMaterialParams(e,t){var i;return Ue(this,void 0,void 0,(function*(){delete t.metalness,delete t.roughness;const n=new He(this.parser,t);n.assignPrimitive("transparentWithZWrite",e.transparentWithZWrite),n.assignColor("shadeColorFactor",e.shadeColorFactor),n.assignTexture("shadeMultiplyTexture",e.shadeMultiplyTexture,!0),n.assignPrimitive("shadingShiftFactor",e.shadingShiftFactor),n.assignTexture("shadingShiftTexture",e.shadingShiftTexture,!0),n.assignPrimitive("shadingShiftTextureScale",null===(i=e.shadingShiftTexture)||void 0===i?void 0:i.scale),n.assignPrimitive("shadingToonyFactor",e.shadingToonyFactor),n.assignPrimitive("giEqualizationFactor",e.giEqualizationFactor),n.assignColor("matcapFactor",e.matcapFactor),n.assignTexture("matcapTexture",e.matcapTexture,!0),n.assignColor("parametricRimColorFactor",e.parametricRimColorFactor),n.assignTexture("rimMultiplyTexture",e.rimMultiplyTexture,!0),n.assignPrimitive("rimLightingMixFactor",e.rimLightingMixFactor),n.assignPrimitive("parametricRimFresnelPowerFactor",e.parametricRimFresnelPowerFactor),n.assignPrimitive("parametricRimLiftFactor",e.parametricRimLiftFactor),n.assignPrimitive("outlineWidthMode",e.outlineWidthMode),n.assignPrimitive("outlineWidthFactor",e.outlineWidthFactor),n.assignTexture("outlineWidthMultiplyTexture",e.outlineWidthMultiplyTexture,!1),n.assignColor("outlineColorFactor",e.outlineColorFactor),n.assignPrimitive("outlineLightingMixFactor",e.outlineLightingMixFactor),n.assignTexture("uvAnimationMaskTexture",e.uvAnimationMaskTexture,!1),n.assignPrimitive("uvAnimationScrollXSpeedFactor",e.uvAnimationScrollXSpeedFactor),n.assignPrimitive("uvAnimationScrollYSpeedFactor",e.uvAnimationScrollYSpeedFactor),n.assignPrimitive("uvAnimationRotationSpeedFactor",e.uvAnimationRotationSpeedFactor),n.assignPrimitive("v0CompatShade",this.v0CompatShade),n.assignPrimitive("debugMode",this.debugMode),yield n.pending}))}_setupPrimitive(e,t){const i=this._getMToonExtension(t);if(i){const t=this._parseRenderOrder(i);return e.renderOrder=t+this.renderOrderOffset,this._generateOutline(e),void this._addToMaterialSet(e)}}_generateOutline(t){const i=t.material;if(!(i instanceof De))return;if("none"===i.outlineWidthMode||i.outlineWidthFactor<=0)return;t.material=[i];const n=i.clone();n.name+=" (Outline)",n.isOutline=!0,n.side=e.BackSide,t.material.push(n);const r=t.geometry,o=r.index?r.index.count:r.attributes.position.count/3;r.addGroup(0,o,0),r.addGroup(0,o,1)}_addToMaterialSet(e){const t=e.material,i=new Set;Array.isArray(t)?t.forEach((e=>i.add(e))):i.add(t);for(const e of i)e instanceof De&&this._mToonMaterialSet.add(e)}_parseRenderOrder(e){var t;return(e.transparentWithZWrite?0:19)+(null!==(t=e.renderQueueOffsetNumber)&&void 0!==t?t:0)}}
21
928
  /*!
22
- * @pixiv/three-vrm-materials-hdr-emissive-multiplier v2.1.2
929
+ * @pixiv/three-vrm-materials-hdr-emissive-multiplier v3.0.0-beta.1
23
930
  * Support VRMC_hdr_emissiveMultiplier for @pixiv/three-vrm
24
931
  *
25
- * Copyright (c) 2020-2024 pixiv Inc.
932
+ * Copyright (c) 2019-2024 pixiv Inc.
26
933
  * @pixiv/three-vrm-materials-hdr-emissive-multiplier is distributed under MIT License
27
934
  * https://github.com/pixiv/three-vrm/blob/release/LICENSE
28
935
  */
29
- function We(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))}ke.EXTENSION_NAME="VRMC_materials_mtoon","function"==typeof SuppressedError&&SuppressedError;class ze{get name(){return ze.EXTENSION_NAME}constructor(e){this.parser=e}extendMaterialParams(e,t){return We(this,void 0,void 0,(function*(){const i=this._getHDREmissiveMultiplierExtension(e);if(null==i)return;console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead.");const n=i.emissiveMultiplier;t.emissiveIntensity=n}))}_getHDREmissiveMultiplierExtension(e){var t,i;const n=null===(t=this.parser.json.materials)||void 0===t?void 0:t[e];if(null==n)return void console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);const r=null===(i=n.extensions)||void 0===i?void 0:i[ze.EXTENSION_NAME];return null!=r?r:void 0}}
30
936
  /*!
31
- * @pixiv/three-vrm-materials-v0compat v2.1.2
937
+ * @pixiv/three-vrm-materials-v0compat v3.0.0-beta.1
32
938
  * VRM0.0 materials compatibility layer plugin for @pixiv/three-vrm
33
939
  *
34
- * Copyright (c) 2020-2024 pixiv Inc.
940
+ * Copyright (c) 2019-2024 pixiv Inc.
35
941
  * @pixiv/three-vrm-materials-v0compat is distributed under MIT License
36
942
  * https://github.com/pixiv/three-vrm/blob/release/LICENSE
37
943
  */
38
- function Ge(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))}function Qe(e){return Math.pow(e,2.2)}ze.EXTENSION_NAME="VRMC_materials_hdr_emissiveMultiplier","function"==typeof SuppressedError&&SuppressedError;class je{get name(){return"VRMMaterialsV0CompatPlugin"}constructor(e){var t;this.parser=e,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;const i=this.parser.json;i.extensionsUsed=null!==(t=i.extensionsUsed)&&void 0!==t?t:[],-1===i.extensionsUsed.indexOf("KHR_texture_transform")&&i.extensionsUsed.push("KHR_texture_transform")}beforeRoot(){var e;return Ge(this,void 0,void 0,(function*(){const t=this.parser.json,i=null===(e=t.extensions)||void 0===e?void 0:e.VRM,n=null==i?void 0:i.materialProperties;n&&(this._populateRenderQueueMap(n),n.forEach(((e,i)=>{var n,r;const o=null===(n=t.materials)||void 0===n?void 0:n[i];if(null!=o)if("VRM/MToon"===e.shader){const n=this._parseV0MToonProperties(e,o);t.materials[i]=n}else if(null===(r=e.shader)||void 0===r?void 0:r.startsWith("VRM/Unlit")){const n=this._parseV0UnlitProperties(e,o);t.materials[i]=n}else"VRM_USE_GLTFSHADER"===e.shader||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${e.shader}`);else console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${i}] of glTF but the material doesn't exist`)})))}))}_parseV0MToonProperties(t,i){var n,r,o,s,a,l,u,d,h,c,p,m,f,g,v,_,M,x,y,T,R,E,w,P,S,A,L,I,b,U,O,N,V,C,D,F,H,B,k,W,z,G,Q,j,X,Y,q,$,Z,J,K,ee,te,ie,ne;const re=null!==(r=null===(n=t.keywordMap)||void 0===n?void 0:n._ALPHABLEND_ON)&&void 0!==r&&r,oe=1===(null===(o=t.floatProperties)||void 0===o?void 0:o._ZWrite)&&re,se=this._v0ParseRenderQueue(t),ae=null!==(a=null===(s=t.keywordMap)||void 0===s?void 0:s._ALPHATEST_ON)&&void 0!==a&&a,le=re?"BLEND":ae?"MASK":"OPAQUE",ue=ae?null!==(u=null===(l=t.floatProperties)||void 0===l?void 0:l._Cutoff)&&void 0!==u?u:.5:void 0,de=0===(null!==(h=null===(d=t.floatProperties)||void 0===d?void 0:d._CullMode)&&void 0!==h?h:2),he=this._portTextureTransform(t),ce=(null!==(p=null===(c=t.vectorProperties)||void 0===c?void 0:c._Color)&&void 0!==p?p:[1,1,1,1]).map(((e,t)=>3===t?e:Qe(e))),pe=null===(m=t.textureProperties)||void 0===m?void 0:m._MainTex,me=null!=pe?{index:pe,extensions:Object.assign({},he)}:void 0,fe=null!==(g=null===(f=t.floatProperties)||void 0===f?void 0:f._BumpScale)&&void 0!==g?g:1,ge=null===(v=t.textureProperties)||void 0===v?void 0:v._BumpMap,ve=null!=ge?{index:ge,scale:fe,extensions:Object.assign({},he)}:void 0,_e=(null!==(M=null===(_=t.vectorProperties)||void 0===_?void 0:_._EmissionColor)&&void 0!==M?M:[0,0,0,1]).map(Qe),Me=null===(x=t.textureProperties)||void 0===x?void 0:x._EmissionMap,xe=null!=Me?{index:Me,extensions:Object.assign({},he)}:void 0,ye=(null!==(T=null===(y=t.vectorProperties)||void 0===y?void 0:y._ShadeColor)&&void 0!==T?T:[.97,.81,.86,1]).map(Qe),Te=null===(R=t.textureProperties)||void 0===R?void 0:R._ShadeTexture,Re=null!=Te?{index:Te,extensions:Object.assign({},he)}:void 0;let Ee=null!==(w=null===(E=t.floatProperties)||void 0===E?void 0:E._ShadeShift)&&void 0!==w?w:0,we=null!==(S=null===(P=t.floatProperties)||void 0===P?void 0:P._ShadeToony)&&void 0!==S?S:.9;we=e.MathUtils.lerp(we,1,.5+.5*Ee),Ee=-Ee-(1-we);const Pe=null!==(L=null===(A=t.floatProperties)||void 0===A?void 0:A._IndirectLightIntensity)&&void 0!==L?L:.1,Se=Pe?1-Pe:void 0,Ae=null===(I=t.textureProperties)||void 0===I?void 0:I._SphereAdd,Le=null!=Ae?[1,1,1]:void 0,Ie=null!=Ae?{index:Ae}:void 0,be=null!==(U=null===(b=t.floatProperties)||void 0===b?void 0:b._RimLightingMix)&&void 0!==U?U:0,Ue=null===(O=t.textureProperties)||void 0===O?void 0:O._RimTexture,Oe=null!=Ue?{index:Ue,extensions:Object.assign({},he)}:void 0,Ne=(null!==(V=null===(N=t.vectorProperties)||void 0===N?void 0:N._RimColor)&&void 0!==V?V:[0,0,0,1]).map(Qe),Ve=null!==(D=null===(C=t.floatProperties)||void 0===C?void 0:C._RimFresnelPower)&&void 0!==D?D:1,Ce=null!==(H=null===(F=t.floatProperties)||void 0===F?void 0:F._RimLift)&&void 0!==H?H:0,De=["none","worldCoordinates","screenCoordinates"][null!==(k=null===(B=t.floatProperties)||void 0===B?void 0:B._OutlineWidthMode)&&void 0!==k?k:0];let Fe=null!==(z=null===(W=t.floatProperties)||void 0===W?void 0:W._OutlineWidth)&&void 0!==z?z:0;Fe*=.01;const He=null===(G=t.textureProperties)||void 0===G?void 0:G._OutlineWidthTexture,Be=null!=He?{index:He,extensions:Object.assign({},he)}:void 0,ke=(null!==(j=null===(Q=t.vectorProperties)||void 0===Q?void 0:Q._OutlineColor)&&void 0!==j?j:[0,0,0]).map(Qe),We=1===(null!==(Y=null===(X=t.floatProperties)||void 0===X?void 0:X._OutlineColorMode)&&void 0!==Y?Y:0)?null!==($=null===(q=t.floatProperties)||void 0===q?void 0:q._OutlineLightingMix)&&void 0!==$?$:1:0,ze=null===(Z=t.textureProperties)||void 0===Z?void 0:Z._UvAnimMaskTexture,Ge=null!=ze?{index:ze,extensions:Object.assign({},he)}:void 0,je=null!==(K=null===(J=t.floatProperties)||void 0===J?void 0:J._UvAnimScrollX)&&void 0!==K?K:0;let Xe=null!==(te=null===(ee=t.floatProperties)||void 0===ee?void 0:ee._UvAnimScrollY)&&void 0!==te?te:0;null!=Xe&&(Xe=-Xe);const Ye={specVersion:"1.0",transparentWithZWrite:oe,renderQueueOffsetNumber:se,shadeColorFactor:ye,shadeMultiplyTexture:Re,shadingShiftFactor:Ee,shadingToonyFactor:we,giEqualizationFactor:Se,matcapFactor:Le,matcapTexture:Ie,rimLightingMixFactor:be,rimMultiplyTexture:Oe,parametricRimColorFactor:Ne,parametricRimFresnelPowerFactor:Ve,parametricRimLiftFactor:Ce,outlineWidthMode:De,outlineWidthFactor:Fe,outlineWidthMultiplyTexture:Be,outlineColorFactor:ke,outlineLightingMixFactor:We,uvAnimationMaskTexture:Ge,uvAnimationScrollXSpeedFactor:je,uvAnimationScrollYSpeedFactor:Xe,uvAnimationRotationSpeedFactor:null!==(ne=null===(ie=t.floatProperties)||void 0===ie?void 0:ie._UvAnimRotation)&&void 0!==ne?ne:0};return Object.assign(Object.assign({},i),{pbrMetallicRoughness:{baseColorFactor:ce,baseColorTexture:me},normalTexture:ve,emissiveTexture:xe,emissiveFactor:_e,alphaMode:le,alphaCutoff:ue,doubleSided:de,extensions:{VRMC_materials_mtoon:Ye}})}_parseV0UnlitProperties(e,t){var i,n,r,o,s;const a="VRM/UnlitTransparentZWrite"===e.shader,l="VRM/UnlitTransparent"===e.shader||a,u=this._v0ParseRenderQueue(e),d="VRM/UnlitCutout"===e.shader,h=l?"BLEND":d?"MASK":"OPAQUE",c=d?null!==(n=null===(i=e.floatProperties)||void 0===i?void 0:i._Cutoff)&&void 0!==n?n:.5:void 0,p=this._portTextureTransform(e),m=(null!==(o=null===(r=e.vectorProperties)||void 0===r?void 0:r._Color)&&void 0!==o?o:[1,1,1,1]).map(Qe),f=null===(s=e.textureProperties)||void 0===s?void 0:s._MainTex,g=null!=f?{index:f,extensions:Object.assign({},p)}:void 0,v={specVersion:"1.0",transparentWithZWrite:a,renderQueueOffsetNumber:u,shadeColorFactor:m,shadeMultiplyTexture:g};return Object.assign(Object.assign({},t),{pbrMetallicRoughness:{baseColorFactor:m,baseColorTexture:g},alphaMode:h,alphaCutoff:c,extensions:{VRMC_materials_mtoon:v}})}_portTextureTransform(e){var t,i,n,r,o;const s=null===(t=e.vectorProperties)||void 0===t?void 0:t._MainTex;if(null==s)return{};const a=[null!==(i=null==s?void 0:s[0])&&void 0!==i?i:0,null!==(n=null==s?void 0:s[1])&&void 0!==n?n:0],l=[null!==(r=null==s?void 0:s[2])&&void 0!==r?r:1,null!==(o=null==s?void 0:s[3])&&void 0!==o?o:1];return a[1]=1-l[1]-a[1],{KHR_texture_transform:{offset:a,scale:l}}}_v0ParseRenderQueue(e){var t,i,n;const r=null!==(i=null===(t=e.keywordMap)||void 0===t?void 0:t._ALPHABLEND_ON)&&void 0!==i&&i,o=1===(null===(n=e.floatProperties)||void 0===n?void 0:n._ZWrite);let s=0;if(r){const t=e.renderQueue;null!=t&&(s=o?this._renderQueueMapTransparentZWrite.get(t):this._renderQueueMapTransparent.get(t))}return s}_populateRenderQueueMap(e){const t=new Set,i=new Set;e.forEach((e=>{var n,r,o;const s=null!==(r=null===(n=e.keywordMap)||void 0===n?void 0:n._ALPHABLEND_ON)&&void 0!==r&&r,a=1===(null===(o=e.floatProperties)||void 0===o?void 0:o._ZWrite);if(s){const n=e.renderQueue;null!=n&&(a?i.add(n):t.add(n))}})),t.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${t.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),i.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${i.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(t).sort().forEach(((e,i)=>{const n=Math.min(Math.max(i-t.size+1,-9),0);this._renderQueueMapTransparent.set(e,n)})),Array.from(i).sort().forEach(((e,t)=>{const i=Math.min(Math.max(t,0),9);this._renderQueueMapTransparentZWrite.set(e,i)}))}}
39
944
  /*!
40
- * @pixiv/three-vrm-node-constraint v2.1.2
945
+ * @pixiv/three-vrm-node-constraint v3.0.0-beta.1
41
946
  * Node constraint module for @pixiv/three-vrm
42
947
  *
43
- * Copyright (c) 2020-2024 pixiv Inc.
948
+ * Copyright (c) 2019-2024 pixiv Inc.
44
949
  * @pixiv/three-vrm-node-constraint is distributed under MIT License
45
950
  * https://github.com/pixiv/three-vrm/blob/release/LICENSE
46
- */const Xe=new e.Vector3;class Ye extends e.Group{constructor(t){super(),this._attrPosition=new e.BufferAttribute(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(e.DynamicDrawUsage);const i=new e.BufferGeometry;i.setAttribute("position",this._attrPosition);const n=new e.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new e.Line(i,n),this.add(this._line),this.constraint=t}updateMatrixWorld(e){Xe.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,Xe.x,Xe.y,Xe.z),this.constraint.source&&Xe.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,Xe.x,Xe.y,Xe.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(e)}}function qe(e,t){return t.set(e.elements[12],e.elements[13],e.elements[14])}const $e=new e.Vector3,Ze=new e.Vector3;function Je(e){return e.invert?e.invert():e.inverse(),e}class Ke{constructor(e,t){this.destination=e,this.source=t,this.weight=1}}const et=new e.Vector3,tt=new e.Vector3,it=new e.Vector3,nt=new e.Quaternion,rt=new e.Quaternion,ot=new e.Quaternion;class st extends Ke{get aimAxis(){return this._aimAxis}set aimAxis(e){this._aimAxis=e,this._v3AimAxis.set("PositiveX"===e?1:"NegativeX"===e?-1:0,"PositiveY"===e?1:"NegativeY"===e?-1:0,"PositiveZ"===e?1:"NegativeZ"===e?-1:0)}get dependencies(){const e=new Set([this.source]);return this.destination.parent&&e.add(this.destination.parent),e}constructor(t,i){super(t,i),this._aimAxis="PositiveX",this._v3AimAxis=new e.Vector3(1,0,0),this._dstRestQuat=new e.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);const e=nt.identity(),t=rt.identity();var i,n;this.destination.parent&&(i=this.destination.parent.matrixWorld,n=e,i.decompose($e,n,Ze),Je(t.copy(e)));const r=et.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(e),o=qe(this.source.matrixWorld,tt).sub(qe(this.destination.matrixWorld,it)).normalize(),s=ot.setFromUnitVectors(r,o).premultiply(t).multiply(e).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(s,this.weight)}}function at(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))}function lt(e,t){const i=[e];let n=e.parent;for(;null!==n;)i.unshift(n),n=n.parent;i.forEach((e=>{t(e)}))}"function"==typeof SuppressedError&&SuppressedError;class ut{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(e){this._constraints.add(e);let t=this._objectConstraintsMap.get(e.destination);null==t&&(t=new Set,this._objectConstraintsMap.set(e.destination,t)),t.add(e)}deleteConstraint(e){this._constraints.delete(e);this._objectConstraintsMap.get(e.destination).delete(e)}setInitState(){const e=new Set,t=new Set;for(const i of this._constraints)this._processConstraint(i,e,t,(e=>e.setInitState()))}update(){const e=new Set,t=new Set;for(const i of this._constraints)this._processConstraint(i,e,t,(e=>e.update()))}_processConstraint(e,t,i,n){if(i.has(e))return;if(t.has(e))throw new Error("VRMNodeConstraintManager: Circular dependency detected while updating constraints");t.add(e);const r=e.dependencies;for(const e of r)lt(e,(e=>{const r=this._objectConstraintsMap.get(e);if(r)for(const e of r)this._processConstraint(e,t,i,n)}));n(e),i.add(e)}}const dt=new e.Quaternion,ht=new e.Quaternion;class ct extends Ke{get dependencies(){return new Set([this.source])}constructor(t,i){super(t,i),this._dstRestQuat=new e.Quaternion,this._invSrcRestQuat=new e.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Je(this._invSrcRestQuat.copy(this.source.quaternion))}update(){const e=dt.copy(this._invSrcRestQuat).multiply(this.source.quaternion),t=ht.copy(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(t,this.weight)}}const pt=new e.Vector3,mt=new e.Quaternion,ft=new e.Quaternion;class gt extends Ke{get rollAxis(){return this._rollAxis}set rollAxis(e){this._rollAxis=e,this._v3RollAxis.set("X"===e?1:0,"Y"===e?1:0,"Z"===e?1:0)}get dependencies(){return new Set([this.source])}constructor(t,i){super(t,i),this._rollAxis="X",this._v3RollAxis=new e.Vector3(1,0,0),this._dstRestQuat=new e.Quaternion,this._invDstRestQuat=new e.Quaternion,this._invSrcRestQuatMulDstRestQuat=new e.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Je(this._invDstRestQuat.copy(this._dstRestQuat)),Je(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){const e=mt.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),t=pt.copy(this._v3RollAxis).applyQuaternion(e),i=ft.setFromUnitVectors(t,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(e);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}}const vt=new Set(["1.0","1.0-beta"]);class _t{get name(){return _t.EXTENSION_NAME}constructor(e,t){this.parser=e,this.helperRoot=null==t?void 0:t.helperRoot}afterRoot(e){return at(this,void 0,void 0,(function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)}))}_import(e){var t;return at(this,void 0,void 0,(function*(){const i=this.parser.json;if(!(-1!==(null===(t=i.extensionsUsed)||void 0===t?void 0:t.indexOf(_t.EXTENSION_NAME))))return null;const n=new ut,r=yield this.parser.getDependencies("node");return r.forEach(((e,t)=>{var o;const s=i.nodes[t],a=null===(o=null==s?void 0:s.extensions)||void 0===o?void 0:o[_t.EXTENSION_NAME];if(null==a)return;const l=a.specVersion;if(!vt.has(l))return void console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${_t.EXTENSION_NAME} specVersion "${l}"`);const u=a.constraint;if(null!=u.roll){const t=this._importRollConstraint(e,r,u.roll);n.addConstraint(t)}else if(null!=u.aim){const t=this._importAimConstraint(e,r,u.aim);n.addConstraint(t)}else if(null!=u.rotation){const t=this._importRotationConstraint(e,r,u.rotation);n.addConstraint(t)}})),e.scene.updateMatrixWorld(),n.setInitState(),n}))}_importRollConstraint(e,t,i){const{source:n,rollAxis:r,weight:o}=i,s=t[n],a=new gt(e,s);if(null!=r&&(a.rollAxis=r),null!=o&&(a.weight=o),this.helperRoot){const e=new Ye(a);this.helperRoot.add(e)}return a}_importAimConstraint(e,t,i){const{source:n,aimAxis:r,weight:o}=i,s=t[n],a=new st(e,s);if(null!=r&&(a.aimAxis=r),null!=o&&(a.weight=o),this.helperRoot){const e=new Ye(a);this.helperRoot.add(e)}return a}_importRotationConstraint(e,t,i){const{source:n,weight:r}=i,o=t[n],s=new ct(e,o);if(null!=r&&(s.weight=r),this.helperRoot){const e=new Ye(s);this.helperRoot.add(e)}return s}}_t.EXTENSION_NAME="VRMC_node_constraint";
951
+ */
47
952
  /*!
48
- * @pixiv/three-vrm-springbone v2.1.2
953
+ * @pixiv/three-vrm-springbone v3.0.0-beta.1
49
954
  * Spring bone module for @pixiv/three-vrm
50
955
  *
51
- * Copyright (c) 2020-2024 pixiv Inc.
956
+ * Copyright (c) 2019-2024 pixiv Inc.
52
957
  * @pixiv/three-vrm-springbone is distributed under MIT License
53
958
  * https://github.com/pixiv/three-vrm/blob/release/LICENSE
54
959
  */
55
- class Mt{}const xt=new e.Vector3,yt=new e.Vector3;class Tt extends Mt{get type(){return"capsule"}constructor(t){var i,n,r;super(),this.offset=null!==(i=null==t?void 0:t.offset)&&void 0!==i?i:new e.Vector3(0,0,0),this.tail=null!==(n=null==t?void 0:t.tail)&&void 0!==n?n:new e.Vector3(0,0,0),this.radius=null!==(r=null==t?void 0:t.radius)&&void 0!==r?r:0}calculateCollision(e,t,i,n){xt.copy(this.offset).applyMatrix4(e),yt.copy(this.tail).applyMatrix4(e),yt.sub(xt);const r=yt.lengthSq();n.copy(t).sub(xt);const o=yt.dot(n);o<=0||(r<=o||yt.multiplyScalar(o/r),n.sub(yt));const s=i+this.radius,a=n.length()-s;return n.normalize(),a}}class Rt extends Mt{get type(){return"sphere"}constructor(t){var i,n;super(),this.offset=null!==(i=null==t?void 0:t.offset)&&void 0!==i?i:new e.Vector3(0,0,0),this.radius=null!==(n=null==t?void 0:t.radius)&&void 0!==n?n:0}calculateCollision(e,t,i,n){n.copy(this.offset).applyMatrix4(e),n.negate().add(t);const r=i+this.radius,o=n.length()-r;return n.normalize(),o}}const Et=new e.Vector3;class wt extends e.BufferGeometry{constructor(t){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new e.Vector3,this._currentTail=new e.Vector3,this._shape=t,this._attrPos=new e.BufferAttribute(new Float32Array(396),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;const t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0);const i=Et.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(i)>1e-10&&(this._currentTail.copy(i),e=!0),e&&this._buildPosition()}_buildPosition(){Et.copy(this._currentTail).sub(this._currentOffset);const e=Et.length()/this._currentRadius;for(let t=0;t<=16;t++){const i=t/16*Math.PI;this._attrPos.setXYZ(t,-Math.sin(i),-Math.cos(i),0),this._attrPos.setXYZ(17+t,e+Math.sin(i),Math.cos(i),0),this._attrPos.setXYZ(34+t,-Math.sin(i),0,-Math.cos(i)),this._attrPos.setXYZ(51+t,e+Math.sin(i),0,Math.cos(i))}for(let t=0;t<32;t++){const i=t/16*Math.PI;this._attrPos.setXYZ(68+t,0,Math.sin(i),Math.cos(i)),this._attrPos.setXYZ(100+t,e,Math.sin(i),Math.cos(i))}const t=Math.atan2(Et.y,Math.sqrt(Et.x*Et.x+Et.z*Et.z)),i=-Math.atan2(Et.z,Et.x);this.rotateZ(t),this.rotateY(i),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<34;e++){const t=(e+1)%34;this._attrIndex.setXY(2*e,e,t),this._attrIndex.setXY(68+2*e,34+e,34+t)}for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(136+2*e,68+e,68+t),this._attrIndex.setXY(200+2*e,100+e,100+t)}this._attrIndex.needsUpdate=!0}}class Pt extends e.BufferGeometry{constructor(t){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new e.Vector3,this._shape=t,this._attrPos=new e.BufferAttribute(new Float32Array(288),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(192),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;const t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){const t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(2*e,e,t),this._attrIndex.setXY(64+2*e,32+e,32+t),this._attrIndex.setXY(128+2*e,64+e,64+t)}this._attrIndex.needsUpdate=!0}}const St=new e.Vector3;class At extends e.Group{constructor(t){if(super(),this.matrixAutoUpdate=!1,this.collider=t,this.collider.shape instanceof Rt)this._geometry=new Pt(this.collider.shape);else{if(!(this.collider.shape instanceof Tt))throw new Error("VRMSpringBoneColliderHelper: Unknown collider shape type detected");this._geometry=new wt(this.collider.shape)}const i=new e.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new e.LineSegments(this._geometry,i),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);const t=this.matrix.elements;this._geometry.worldScale=St.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}}class Lt extends e.BufferGeometry{constructor(t){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new e.Vector3,this._springBone=t,this._attrPos=new e.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new e.BufferAttribute(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;const t=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){const t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(2*e,e,t),this._attrIndex.setXY(64+2*e,32+e,32+t),this._attrIndex.setXY(128+2*e,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}}const It=new e.Vector3;class bt extends e.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.springBone=t,this._geometry=new Lt(this.springBone);const i=new e.LineBasicMaterial({color:16776960,depthTest:!1,depthWrite:!1});this._line=new e.LineSegments(this._geometry,i),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);const t=this.matrix.elements;this._geometry.worldScale=It.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}}class Ut extends e.Object3D{constructor(e){super(),this.shape=e}}const Ot=new e.Matrix4;function Nt(e){return e.invert?e.invert():e.getInverse(Ot.copy(e)),e}class Vt{get inverse(){return this._shouldUpdateInverse&&(this._inverseCache.copy(this.matrix),Nt(this._inverseCache),this._shouldUpdateInverse=!1),this._inverseCache}constructor(t){this._inverseCache=new e.Matrix4,this._shouldUpdateInverse=!0,this.matrix=t;const i={set:(e,t,i)=>(this._shouldUpdateInverse=!0,e[t]=i,!0)};this._originalElements=t.elements,t.elements=new Proxy(t.elements,i)}revert(){this.matrix.elements=this._originalElements}}const Ct=new e.Matrix4,Dt=new e.Vector3,Ft=new e.Vector3,Ht=new e.Vector3,Bt=new e.Vector3,kt=new e.Vector3,Wt=new e.Vector3,zt=new e.Quaternion,Gt=new e.Matrix4,Qt=new e.Matrix4;class jt{get center(){return this._center}set center(e){var t;(null===(t=this._center)||void 0===t?void 0:t.userData.inverseCacheProxy)&&(this._center.userData.inverseCacheProxy.revert(),delete this._center.userData.inverseCacheProxy),this._center=e,this._center&&(this._center.userData.inverseCacheProxy||(this._center.userData.inverseCacheProxy=new Vt(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:Ct}constructor(t,i,n={},r=[]){var o,s,a,l,u,d;this._currentTail=new e.Vector3,this._prevTail=new e.Vector3,this._boneAxis=new e.Vector3,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new e.Matrix4,this._initialLocalRotation=new e.Quaternion,this._initialLocalChildPosition=new e.Vector3,this.bone=t,this.bone.matrixAutoUpdate=!1,this.child=i,this.settings={hitRadius:null!==(o=n.hitRadius)&&void 0!==o?o:0,stiffness:null!==(s=n.stiffness)&&void 0!==s?s:1,gravityPower:null!==(a=n.gravityPower)&&void 0!==a?a:0,gravityDir:null!==(u=null===(l=n.gravityDir)||void 0===l?void 0:l.clone())&&void 0!==u?u:new e.Vector3(0,-1,0),dragForce:null!==(d=n.dragForce)&&void 0!==d?d:.4},this.colliderGroups=r}setInitState(){this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),this.child?this._initialLocalChildPosition.copy(this.child.position):this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);const e=this._getMatrixWorldToCenter(Gt);this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix);const e=this._getMatrixWorldToCenter(Gt);this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail)}update(e){if(e<=0)return;this._calcWorldSpaceBoneLength(),Bt.setFromMatrixPosition(this.bone.matrixWorld);let t=this._getMatrixWorldToCenter(Gt);kt.copy(Bt).applyMatrix4(t);const i=zt.setFromRotationMatrix(t),n=Qt.copy(t).multiply(this._parentMatrixWorld),r=Ft.copy(this._boneAxis).applyMatrix4(this._initialLocalMatrix).applyMatrix4(n).sub(kt).normalize(),o=Ht.copy(this.settings.gravityDir).applyQuaternion(i).normalize(),s=this._getMatrixCenterToWorld(Gt);Wt.copy(this._currentTail).add(Dt.copy(this._currentTail).sub(this._prevTail).multiplyScalar(1-this.settings.dragForce)).add(Dt.copy(r).multiplyScalar(this.settings.stiffness*e)).add(Dt.copy(o).multiplyScalar(this.settings.gravityPower*e)).applyMatrix4(s),Wt.sub(Bt).normalize().multiplyScalar(this._worldSpaceBoneLength).add(Bt),this._collision(Wt),t=this._getMatrixWorldToCenter(Gt),this._prevTail.copy(this._currentTail),this._currentTail.copy(Dt.copy(Wt).applyMatrix4(t));const a=Nt(Gt.copy(this._parentMatrixWorld).multiply(this._initialLocalMatrix)),l=zt.setFromUnitVectors(this._boneAxis,Dt.copy(Wt).applyMatrix4(a).normalize());this.bone.quaternion.copy(this._initialLocalRotation).multiply(l),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(e){this.colliderGroups.forEach((t=>{t.colliders.forEach((t=>{const i=t.shape.calculateCollision(t.matrixWorld,e,this.settings.hitRadius,Dt);i<0&&(e.add(Dt.multiplyScalar(-i)),e.sub(Bt).normalize().multiplyScalar(this._worldSpaceBoneLength).add(Bt))}))}))}_calcWorldSpaceBoneLength(){Dt.setFromMatrixPosition(this.bone.matrixWorld),this.child?Ft.setFromMatrixPosition(this.child.matrixWorld):(Ft.copy(this._initialLocalChildPosition),Ft.applyMatrix4(this.bone.matrixWorld)),this._worldSpaceBoneLength=Dt.sub(Ft).length()}_getMatrixCenterToWorld(e){return this._center?e.copy(this._center.matrixWorld):e.identity(),e}_getMatrixWorldToCenter(e){return this._center?e.copy(this._center.userData.inverseCacheProxy.inverse):e.identity(),e}}function Xt(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((n=n.apply(e,t||[])).next())}))}function Yt(e,t){const i=[];let n=e;for(;null!==n;)i.unshift(n),n=n.parent;i.forEach((e=>{t(e)}))}function qt(e,t){e.children.forEach((e=>{t(e)||qt(e,t)}))}"function"==typeof SuppressedError&&SuppressedError;class $t{constructor(){this._joints=new Set,this._objectSpringBonesMap=new Map}get joints(){return this._joints}get springBones(){return console.warn("VRMSpringBoneManager: springBones is deprecated. use joints instead."),this._joints}get colliderGroups(){const e=new Set;return this._joints.forEach((t=>{t.colliderGroups.forEach((t=>{e.add(t)}))})),Array.from(e)}get colliders(){const e=new Set;return this.colliderGroups.forEach((t=>{t.colliders.forEach((t=>{e.add(t)}))})),Array.from(e)}addJoint(e){this._joints.add(e);let t=this._objectSpringBonesMap.get(e.bone);null==t&&(t=new Set,this._objectSpringBonesMap.set(e.bone,t)),t.add(e)}addSpringBone(e){console.warn("VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead."),this.addJoint(e)}deleteJoint(e){this._joints.delete(e);this._objectSpringBonesMap.get(e.bone).delete(e)}deleteSpringBone(e){console.warn("VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead."),this.deleteJoint(e)}setInitState(){const e=new Set,t=new Set,i=new Set;for(const n of this._joints)this._processSpringBone(n,e,t,i,(e=>e.setInitState()))}reset(){const e=new Set,t=new Set,i=new Set;for(const n of this._joints)this._processSpringBone(n,e,t,i,(e=>e.reset()))}update(e){const t=new Set,i=new Set,n=new Set;for(const r of this._joints)this._processSpringBone(r,t,i,n,(t=>t.update(e))),qt(r.bone,(e=>{var t,i;return(null!==(i=null===(t=this._objectSpringBonesMap.get(e))||void 0===t?void 0:t.size)&&void 0!==i?i:0)>0||(e.updateWorldMatrix(!1,!1),!1)}))}_processSpringBone(e,t,i,n,r){if(i.has(e))return;if(t.has(e))throw new Error("VRMSpringBoneManager: Circular dependency detected while updating springbones");t.add(e);const o=this._getDependencies(e);for(const e of o)Yt(e,(e=>{const o=this._objectSpringBonesMap.get(e);if(o)for(const e of o)this._processSpringBone(e,t,i,n,r);else n.has(e)||(e.updateWorldMatrix(!1,!1),n.add(e))}));e.bone.updateMatrix(),e.bone.updateWorldMatrix(!1,!1),r(e),n.add(e.bone),i.add(e)}_getDependencies(e){const t=new Set,i=e.bone.parent;return i&&t.add(i),e.colliderGroups.forEach((e=>{e.colliders.forEach((e=>{t.add(e)}))})),t}}const Zt=new Set(["1.0","1.0-beta"]);class Jt{get name(){return Jt.EXTENSION_NAME}constructor(e,t){this.parser=e,this.jointHelperRoot=null==t?void 0:t.jointHelperRoot,this.colliderHelperRoot=null==t?void 0:t.colliderHelperRoot}afterRoot(e){return Xt(this,void 0,void 0,(function*(){e.userData.vrmSpringBoneManager=yield this._import(e)}))}_import(e){return Xt(this,void 0,void 0,(function*(){const t=yield this._v1Import(e);if(null!=t)return t;const i=yield this._v0Import(e);return null!=i?i:null}))}_v1Import(t){var i,n,r,o,s;return Xt(this,void 0,void 0,(function*(){const a=t.parser.json;if(!(-1!==(null===(i=a.extensionsUsed)||void 0===i?void 0:i.indexOf(Jt.EXTENSION_NAME))))return null;const l=new $t,u=yield t.parser.getDependencies("node"),d=null===(n=a.extensions)||void 0===n?void 0:n[Jt.EXTENSION_NAME];if(!d)return null;const h=d.specVersion;if(!Zt.has(h))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${Jt.EXTENSION_NAME} specVersion "${h}"`),null;const c=null===(r=d.colliders)||void 0===r?void 0:r.map(((t,i)=>{var n,r,o,s,a;const l=u[t.node],d=t.shape;if(d.sphere)return this._importSphereCollider(l,{offset:(new e.Vector3).fromArray(null!==(n=d.sphere.offset)&&void 0!==n?n:[0,0,0]),radius:null!==(r=d.sphere.radius)&&void 0!==r?r:0});if(d.capsule)return this._importCapsuleCollider(l,{offset:(new e.Vector3).fromArray(null!==(o=d.capsule.offset)&&void 0!==o?o:[0,0,0]),radius:null!==(s=d.capsule.radius)&&void 0!==s?s:0,tail:(new e.Vector3).fromArray(null!==(a=d.capsule.tail)&&void 0!==a?a:[0,0,0])});throw new Error(`VRMSpringBoneLoaderPlugin: The collider #${i} has no valid shape`)})),p=null===(o=d.colliderGroups)||void 0===o?void 0:o.map(((e,t)=>{var i;return{colliders:(null!==(i=e.colliders)&&void 0!==i?i:[]).map((e=>{const i=null==c?void 0:c[e];if(null==i)throw new Error(`VRMSpringBoneLoaderPlugin: The colliderGroup #${t} attempted to use a collider #${e} but not found`);return i})),name:e.name}}));return null===(s=d.springs)||void 0===s||s.forEach(((t,i)=>{var n;const r=t.joints,o=null===(n=t.colliderGroups)||void 0===n?void 0:n.map((e=>{const t=null==p?void 0:p[e];if(null==t)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${i} attempted to use a colliderGroup ${e} but not found`);return t})),s=null!=t.center?u[t.center]:void 0;let a;r.forEach((t=>{if(a){const i=a.node,n=u[i],r=t.node,d=u[r],h={hitRadius:a.hitRadius,dragForce:a.dragForce,gravityPower:a.gravityPower,stiffness:a.stiffness,gravityDir:null!=a.gravityDir?(new e.Vector3).fromArray(a.gravityDir):void 0},c=this._importJoint(n,d,h,o);s&&(c.center=s),l.addJoint(c)}a=t}))})),l.setInitState(),l}))}_v0Import(t){var i,n,r;return Xt(this,void 0,void 0,(function*(){const o=t.parser.json;if(!(-1!==(null===(i=o.extensionsUsed)||void 0===i?void 0:i.indexOf("VRM"))))return null;const s=null===(n=o.extensions)||void 0===n?void 0:n.VRM,a=null==s?void 0:s.secondaryAnimation;if(!a)return null;const l=null==a?void 0:a.boneGroups;if(!l)return null;const u=new $t,d=yield t.parser.getDependencies("node"),h=null===(r=a.colliderGroups)||void 0===r?void 0:r.map((t=>{var i;const n=d[t.node],r=(null!==(i=t.colliders)&&void 0!==i?i:[]).map(((t,i)=>{var r,o,s;const a=new e.Vector3(0,0,0);return t.offset&&a.set(null!==(r=t.offset.x)&&void 0!==r?r:0,null!==(o=t.offset.y)&&void 0!==o?o:0,t.offset.z?-t.offset.z:0),this._importSphereCollider(n,{offset:a,radius:null!==(s=t.radius)&&void 0!==s?s:0})}));return{colliders:r}}));return null==l||l.forEach(((t,i)=>{const n=t.bones;n&&n.forEach((n=>{var r,o,s,a;const l=d[n],c=new e.Vector3;t.gravityDir?c.set(null!==(r=t.gravityDir.x)&&void 0!==r?r:0,null!==(o=t.gravityDir.y)&&void 0!==o?o:0,null!==(s=t.gravityDir.z)&&void 0!==s?s:0):c.set(0,-1,0);const p=null!=t.center?d[t.center]:void 0,m={hitRadius:t.hitRadius,dragForce:t.dragForce,gravityPower:t.gravityPower,stiffness:t.stiffiness,gravityDir:c},f=null===(a=t.colliderGroups)||void 0===a?void 0:a.map((e=>{const t=null==h?void 0:h[e];if(null==t)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${i} attempted to use a colliderGroup ${e} but not found`);return t}));l.traverse((e=>{var t;const i=null!==(t=e.children[0])&&void 0!==t?t:null,n=this._importJoint(e,i,m,f);p&&(n.center=p),u.addJoint(n)}))}))})),t.scene.updateMatrixWorld(),u.setInitState(),u}))}_importJoint(e,t,i,n){const r=new jt(e,t,i,n);if(this.jointHelperRoot){const e=new bt(r);this.jointHelperRoot.add(e),e.renderOrder=this.jointHelperRoot.renderOrder}return r}_importSphereCollider(e,t){const{offset:i,radius:n}=t,r=new Rt({offset:i,radius:n}),o=new Ut(r);if(e.add(o),this.colliderHelperRoot){const e=new At(o);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return o}_importCapsuleCollider(e,t){const{offset:i,radius:n,tail:r}=t,o=new Tt({offset:i,radius:n,tail:r}),s=new Ut(o);if(e.add(s),this.colliderHelperRoot){const e=new At(s);this.colliderHelperRoot.add(e),e.renderOrder=this.colliderHelperRoot.renderOrder}return s}}Jt.EXTENSION_NAME="VRMC_springBone";class Kt{get name(){return"VRMLoaderPlugin"}constructor(e,t){var i,n,r,o,s,a,l,u,d,h;this.parser=e;const c=null==t?void 0:t.helperRoot,p=null==t?void 0:t.autoUpdateHumanBones;this.expressionPlugin=null!==(i=null==t?void 0:t.expressionPlugin)&&void 0!==i?i:new M(e),this.firstPersonPlugin=null!==(n=null==t?void 0:t.firstPersonPlugin)&&void 0!==n?n:new R(e),this.humanoidPlugin=null!==(r=null==t?void 0:t.humanoidPlugin)&&void 0!==r?r:new G(e,{helperRoot:c,autoUpdateHumanBones:p}),this.lookAtPlugin=null!==(o=null==t?void 0:t.lookAtPlugin)&&void 0!==o?o:new Ee(e,{helperRoot:c}),this.metaPlugin=null!==(s=null==t?void 0:t.metaPlugin)&&void 0!==s?s:new Se(e),this.mtoonMaterialPlugin=null!==(a=null==t?void 0:t.mtoonMaterialPlugin)&&void 0!==a?a:new ke(e),this.materialsHDREmissiveMultiplierPlugin=null!==(l=null==t?void 0:t.materialsHDREmissiveMultiplierPlugin)&&void 0!==l?l:new ze(e),this.materialsV0CompatPlugin=null!==(u=null==t?void 0:t.materialsV0CompatPlugin)&&void 0!==u?u:new je(e),this.springBonePlugin=null!==(d=null==t?void 0:t.springBonePlugin)&&void 0!==d?d:new Jt(e,{colliderHelperRoot:c,jointHelperRoot:c}),this.nodeConstraintPlugin=null!==(h=null==t?void 0:t.nodeConstraintPlugin)&&void 0!==h?h:new _t(e,{helperRoot:c})}beforeRoot(){return be(this,void 0,void 0,(function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()}))}loadMesh(e){return be(this,void 0,void 0,(function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)}))}getMaterialType(e){const t=this.mtoonMaterialPlugin.getMaterialType(e);return null!=t?t:null}extendMaterialParams(e,t){return be(this,void 0,void 0,(function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,t),yield this.mtoonMaterialPlugin.extendMaterialParams(e,t)}))}afterRoot(e){return be(this,void 0,void 0,(function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);const t=e.userData.vrmMeta,i=e.userData.vrmHumanoid;if(t&&i){const n=new Ie({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:i,lookAt:e.userData.vrmLookAt,meta:t,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=n}}))}}function ei(e){if(Object.values(e).forEach((e=>{if(null==e?void 0:e.isTexture){e.dispose()}})),e.isShaderMaterial){const t=e.uniforms;t&&Object.values(t).forEach((e=>{const t=e.value;if(null==t?void 0:t.isTexture){t.dispose()}}))}e.dispose()}function ti(e){const t=e.geometry;t&&t.dispose();const i=e.skeleton;i&&i.dispose();const n=e.material;n&&(Array.isArray(n)?n.forEach((e=>ei(e))):n&&ei(n))}class ii{constructor(){}}ii.deepDispose=function(e){e.traverse(ti)},ii.removeUnnecessaryJoints=function(t){const i=new Map;t.traverse((t=>{if("SkinnedMesh"!==t.type)return;const n=t,r=n.geometry.getAttribute("skinIndex");let o=i.get(r);if(!o){const t=[],s=[],a={},l=r.array;for(let e=0;e<l.length;e++){const i=l[e];void 0===a[i]&&(a[i]=t.length,t.push(n.skeleton.bones[i]),s.push(n.skeleton.boneInverses[i])),l[e]=a[i]}r.copyArray(l),r.needsUpdate=!0,o=new e.Skeleton(t,s),i.set(r,o)}n.bind(o,new e.Matrix4)}))},ii.removeUnnecessaryVertices=function(i){const n=new Map;i.traverse((i=>{var r,o,s,a;if(!i.isMesh)return;const l=i,u=l.geometry,d=u.index;if(null==d)return;const h=n.get(u);if(null!=h)return void(l.geometry=h);const c=new e.BufferGeometry;c.name=u.name,c.morphTargetsRelative=u.morphTargetsRelative,u.groups.forEach((e=>{c.addGroup(e.start,e.count,e.materialIndex)})),c.boundingBox=null!==(o=null===(r=u.boundingBox)||void 0===r?void 0:r.clone())&&void 0!==o?o:null,c.boundingSphere=null!==(a=null===(s=u.boundingSphere)||void 0===s?void 0:s.clone())&&void 0!==a?a:null,c.setDrawRange(u.drawRange.start,u.drawRange.count),c.userData=u.userData,n.set(u,c);const p=[],m=[];{const e=d.array,i=new e.constructor(e.length);let n=0;for(let t=0;t<e.length;t++){const r=e[t];let o=p[r];null==o&&(p[r]=n,m[n]=r,o=n,n++),i[t]=o}c.setIndex(new t(i,1,!1))}Object.keys(u.attributes).forEach((e=>{const i=u.attributes[e];if(i.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const n=i.array,{itemSize:r,normalized:o}=i,s=new n.constructor(m.length*r);m.forEach(((e,t)=>{for(let i=0;i<r;i++)s[t*r+i]=n[e*r+i]})),c.setAttribute(e,new t(s,r,o))}));let f=!0;Object.keys(u.morphAttributes).forEach((e=>{c.morphAttributes[e]=[];const i=u.morphAttributes[e];for(let n=0;n<i.length;n++){const r=i[n];if(r.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const o=r.array,{itemSize:s,normalized:a}=r,l=new o.constructor(m.length*s);m.forEach(((e,t)=>{for(let i=0;i<s;i++)l[t*s+i]=o[e*s+i]})),f=f&&l.every((e=>0===e)),c.morphAttributes[e][n]=new t(l,s,a)}})),f&&(c.morphAttributes={}),l.geometry=c})),Array.from(n.keys()).forEach((e=>{e.dispose()}))},ii.rotateVRM0=function(e){var t;"0"===(null===(t=e.meta)||void 0===t?void 0:t.metaVersion)&&(e.scene.rotation.y=Math.PI)};export{De as MToonMaterial,Oe as MToonMaterialDebugMode,ke as MToonMaterialLoaderPlugin,Ne as MToonMaterialOutlineWidthMode,Ie as VRM,st as VRMAimConstraint,Ae as VRMCore,Le as VRMCoreLoaderPlugin,i as VRMExpression,M as VRMExpressionLoaderPlugin,d as VRMExpressionManager,m as VRMExpressionMaterialColorBind,h as VRMExpressionMaterialColorType,f as VRMExpressionMorphTargetBind,x as VRMExpressionOverrideType,l as VRMExpressionPresetName,v as VRMExpressionTextureTransformBind,y as VRMFirstPerson,R as VRMFirstPersonLoaderPlugin,E as VRMFirstPersonMeshAnnotationType,L as VRMHumanBoneList,I as VRMHumanBoneName,b as VRMHumanBoneParentMap,B as VRMHumanoid,A as VRMHumanoidHelper,G as VRMHumanoidLoaderPlugin,Kt as VRMLoaderPlugin,fe as VRMLookAt,xe as VRMLookAtBoneApplier,ye as VRMLookAtExpressionApplier,ee as VRMLookAtHelper,Ee as VRMLookAtLoaderPlugin,Te as VRMLookAtRangeMap,we as VRMLookAtTypeName,Se as VRMMetaLoaderPlugin,Ke as VRMNodeConstraint,Ye as VRMNodeConstraintHelper,_t as VRMNodeConstraintLoaderPlugin,ut as VRMNodeConstraintManager,k as VRMRequiredHumanBoneName,gt as VRMRollConstraint,ct as VRMRotationConstraint,Ut as VRMSpringBoneCollider,At as VRMSpringBoneColliderHelper,Mt as VRMSpringBoneColliderShape,Tt as VRMSpringBoneColliderShapeCapsule,Rt as VRMSpringBoneColliderShapeSphere,jt as VRMSpringBoneJoint,bt as VRMSpringBoneJointHelper,Jt as VRMSpringBoneLoaderPlugin,$t as VRMSpringBoneManager,ii as VRMUtils};