@mymosdk/avatar 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Avatar-DEkBZdcp.js +2583 -0
- package/dist/Avatar-DEkBZdcp.js.map +1 -0
- package/dist/Avatar-Ok6vAXs6.cjs +10 -0
- package/dist/Avatar-Ok6vAXs6.cjs.map +1 -0
- package/dist/Avatar.d.ts +77 -0
- package/dist/Avatar.d.ts.map +1 -0
- package/dist/animation/AnimationEngine.d.ts +58 -0
- package/dist/animation/AnimationEngine.d.ts.map +1 -0
- package/dist/audio/AudioEngine.d.ts +19 -0
- package/dist/audio/AudioEngine.d.ts.map +1 -0
- package/dist/audio/LipSync.d.ts +14 -0
- package/dist/audio/LipSync.d.ts.map +1 -0
- package/dist/events/EventEmitter.d.ts +9 -0
- package/dist/events/EventEmitter.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/loader/AssetLoader.d.ts +18 -0
- package/dist/loader/AssetLoader.d.ts.map +1 -0
- package/dist/mymo-avatar.cjs +2 -0
- package/dist/mymo-avatar.cjs.map +1 -0
- package/dist/mymo-avatar.js +5 -0
- package/dist/mymo-avatar.js.map +1 -0
- package/dist/mymo-avatar.umd.js +992 -0
- package/dist/mymo-avatar.umd.js.map +1 -0
- package/dist/plugins/PluginSystem.d.ts +7 -0
- package/dist/plugins/PluginSystem.d.ts.map +1 -0
- package/dist/react/AvatarWidget.d.ts +4 -0
- package/dist/react/AvatarWidget.d.ts.map +1 -0
- package/dist/react/index.d.ts +4 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/useAvatar.d.ts +3 -0
- package/dist/react/useAvatar.d.ts.map +1 -0
- package/dist/react.cjs +2 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.js +19 -0
- package/dist/react.js.map +1 -0
- package/dist/renderer/Renderer.d.ts +46 -0
- package/dist/renderer/Renderer.d.ts.map +1 -0
- package/dist/types/index.d.ts +69 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/vue/AvatarWidget.d.ts +4 -0
- package/dist/vue/AvatarWidget.d.ts.map +1 -0
- package/dist/vue/index.d.ts +3 -0
- package/dist/vue/index.d.ts.map +1 -0
- package/dist/vue/useAvatar.d.ts +4 -0
- package/dist/vue/useAvatar.d.ts.map +1 -0
- package/dist/vue.cjs +2 -0
- package/dist/vue.cjs.map +1 -0
- package/dist/vue.js +41 -0
- package/dist/vue.js.map +1 -0
- package/package.json +71 -0
|
@@ -0,0 +1,992 @@
|
|
|
1
|
+
(function(q,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],m):(q=typeof globalThis<"u"?globalThis:q||self,m(q.MymoAvatar={},q.THREE))})(this,function(q,m){"use strict";function Jn(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const c=Jn(m);class ei{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){return this.listeners.get(e)?.delete(t),this}emit(e,t){this.listeners.get(e)?.forEach(i=>i(e,t))}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}}const ti={full:[0,1,.5],half:[.48,1,.5],bust:[.68,1,.46],face:[.8,1,.36]},ni={full:{camY:0,camZ:2.8,lookY:0},half:{camY:.5,camZ:2,lookY:.4},bust:{camY:.8,camZ:1,lookY:.55},face:{camY:.8,camZ:.7,lookY:.7}},ii={"bottom-right":{bottom:"20px",right:"20px"},"bottom-left":{bottom:"20px",left:"20px"},"top-right":{top:"20px",right:"20px"},"top-left":{top:"20px",left:"20px"}};class ri{constructor(){this.clock=new c.Clock,this.rafId=0,this.tickCallbacks=[],this.currentModel=null,this.currentFraming="full",this.currentTheme="light",this.modelFraming=null,this.userSliceConfig={},this.userThemeConfig={},this._skeletonHelper=null,this.scene=new c.Scene,this.camera=new c.PerspectiveCamera(45,1,.1,100)}setup(e){this.webgl=new c.WebGLRenderer({antialias:!0,alpha:!0}),this.webgl.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.webgl.setSize(e.size,e.size),this.webgl.shadowMap.enabled=e.shadows,this.webgl.shadowMap.type=c.PCFSoftShadowMap,this.webgl.outputColorSpace=c.SRGBColorSpace,this.webgl.toneMapping=c.ACESFilmicToneMapping,this._setupLights(),e.themeConfig&&(this.userThemeConfig=e.themeConfig),this._createContainer(e),this.currentFraming=e.framing,e.framingConfig&&(this.userSliceConfig=e.framingConfig),this._applyFraming(e.framing),this._startLoop()}_setupLights(){const e=new c.AmbientLight(16777215,.8),t=new c.DirectionalLight(16777215,1.5);t.position.set(1.5,3,2.5);const i=new c.DirectionalLight(8947967,.5);i.position.set(-2,0,1),this.scene.add(e,t,i)}_createContainer(e){this.container=document.createElement("div");const t=this.container.style;t.position="fixed",t.width=`${e.size}px`,t.height=`${e.size}px`,t.zIndex=String(e.zIndex),t.overflow="hidden",t.borderRadius="50%",t.cursor="pointer",t.userSelect="none",t.boxSizing="border-box",this.currentTheme=e.theme,this._applyTheme(e.theme,e.size),this._applyPosition(e.position),this.container.appendChild(this.webgl.domElement),document.body.appendChild(this.container),e.draggable&&this._makeDraggable()}setTheme(e){this.currentTheme=e,this._applyTheme(e,0)}setThemeConfig(e){this.userThemeConfig={...this.userThemeConfig,...e},this._applyTheme(this.currentTheme,0)}_applyTheme(e,t){const i=this.container.style;if(e==="dark"?(i.background=this.userThemeConfig.dark?.background??"radial-gradient(circle at 40% 35%, #2a2a4a 0%, #0d0d1a 100%)",i.boxShadow=this.userThemeConfig.dark?.boxShadow??"0 8px 32px rgba(0,0,0,0.5), 0 0 0 2px rgba(255,255,255,0.08)"):e==="light"?(i.background=this.userThemeConfig.light?.background??"radial-gradient(circle at 40% 35%, #f8f8ff 0%, #e0e0f0 100%)",i.boxShadow=this.userThemeConfig.light?.boxShadow??"0 8px 32px rgba(0,0,0,0.15), 0 0 0 2px rgba(0,0,0,0.06)"):(i.background="transparent",i.boxShadow="none"),i.transition="box-shadow 0.3s ease",i.setProperty("--ring-color","transparent"),!document.getElementById("__mymo_styles__")){const r=document.createElement("style");r.id="__mymo_styles__",r.textContent=`
|
|
2
|
+
@keyframes mymo-ring {
|
|
3
|
+
0% { box-shadow: 0 0 0 0px var(--ring-color); }
|
|
4
|
+
70% { box-shadow: 0 0 0 10px transparent; }
|
|
5
|
+
100% { box-shadow: 0 0 0 0px transparent; }
|
|
6
|
+
}
|
|
7
|
+
[data-state] { animation: mymo-ring 1.2s ease-out infinite; }
|
|
8
|
+
[data-state=""] { animation: none; }
|
|
9
|
+
`,document.head.appendChild(r)}}_applyPosition(e){const t=this.container.style;t.top=t.bottom=t.left=t.right="";const i=ii[e];for(const[r,s]of Object.entries(i))s!==void 0&&(t[r]=s)}_startLoop(){const e=()=>{this.rafId=requestAnimationFrame(e);const t=this.clock.getDelta();for(const i of this.tickCallbacks)i(t);this.webgl.render(this.scene,this.camera)};e()}_makeDraggable(){let e=!1,t=0,i=0;this.container.addEventListener("pointerdown",r=>{e=!0;const s=this.container.getBoundingClientRect();t=r.clientX-s.left,i=r.clientY-s.top,this.container.style.transition="none",r.preventDefault()}),window.addEventListener("pointermove",r=>{if(!e)return;const s=this.container.style;s.top=s.bottom=s.left=s.right="",s.left=`${r.clientX-t}px`,s.top=`${r.clientY-i}px`}),window.addEventListener("pointerup",()=>{e=!1})}addTickCallback(e){this.tickCallbacks.push(e)}setModel(e){this.currentModel&&this.scene.remove(this.currentModel),this._skeletonHelper&&(this.scene.remove(this._skeletonHelper),this._skeletonHelper=null),this.currentModel=e,this._autoFit(e),this.scene.add(e),this.modelFraming=this._computeFraming(e),this._applyFraming(this.currentFraming)}debugBones(e){if(this.currentModel){if(e===!1){this._skeletonHelper&&(this.scene.remove(this._skeletonHelper),this._skeletonHelper=null);return}this._skeletonHelper?(this.scene.remove(this._skeletonHelper),this._skeletonHelper=null):(this._skeletonHelper=new c.SkeletonHelper(this.currentModel),this.scene.add(this._skeletonHelper))}}_computeFraming(e){const t=new c.Box3().setFromObject(e),i=t.max.y-t.min.y,r=Math.tan(this.camera.fov*Math.PI/180/2),s={};for(const[o,l]of Object.entries(ti)){const a=this.userSliceConfig[o]??{},u=a.from??l[0],h=a.to??l[1],d=a.lookBias??l[2],p=t.min.y+i*u,g=t.min.y+i*h-p,_=p+g*d,v=g/2/r*1.15;s[o]={camY:_,camZ:v,lookY:_}}return s}_autoFit(e){const t=new c.Box3().setFromObject(e),i=t.getCenter(new c.Vector3),r=t.getSize(new c.Vector3),o=1.8/Math.max(r.x,r.y,r.z);e.scale.setScalar(o),e.position.set(-i.x*o,-i.y*o,-i.z*o)}_applyFraming(e){const{camY:t,camZ:i,lookY:r}=(this.modelFraming??ni)[e];this.camera.position.set(0,t,i),this.camera.lookAt(0,r,0)}show(){this.container.style.display=""}hide(){this.container.style.display="none"}setFraming(e){this.currentFraming=e,this._applyFraming(e)}setFramingConfig(e){this.userSliceConfig={...this.userSliceConfig,...e},this.currentModel&&(this.modelFraming=this._computeFraming(this.currentModel),this._applyFraming(this.currentFraming))}setPosition(e){this._applyPosition(e)}setSize(e){this.container.style.width=`${e}px`,this.container.style.height=`${e}px`,this.webgl.setSize(e,e)}moveTo(e,t){const i=this.container.style;i.top=i.bottom=i.left=i.right="",i.left=`${e}px`,i.top=`${t}px`}getContainer(){return this.container}dispose(){cancelAnimationFrame(this.rafId),this.tickCallbacks=[],this.webgl.dispose(),this.container.remove()}}/*!
|
|
10
|
+
* @pixiv/three-vrm v3.5.4
|
|
11
|
+
* VRM file loader for three.js.
|
|
12
|
+
*
|
|
13
|
+
* Copyright (c) 2019-2026 pixiv Inc.
|
|
14
|
+
* @pixiv/three-vrm is distributed under MIT License
|
|
15
|
+
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
16
|
+
*/var xe=(n,e,t)=>new Promise((i,r)=>{var s=a=>{try{l(t.next(a))}catch(u){r(u)}},o=a=>{try{l(t.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,o);l((t=t.apply(n,e)).next())}),N=(n,e,t)=>new Promise((i,r)=>{var s=a=>{try{l(t.next(a))}catch(u){r(u)}},o=a=>{try{l(t.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,o);l((t=t.apply(n,e)).next())}),lt=class extends c.Object3D{constructor(n){super(),this.weight=0,this.isBinary=!1,this.overrideBlink="none",this.overrideLookAt="none",this.overrideMouth="none",this._binds=[],this.name=`VRMExpression_${n}`,this.expressionName=n,this.type="VRMExpression",this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink==="block"?0<this.outputWeight?1:0:this.overrideBlink==="blend"?this.outputWeight:0}get overrideLookAtAmount(){return this.overrideLookAt==="block"?0<this.outputWeight?1:0:this.overrideLookAt==="blend"?this.outputWeight:0}get overrideMouthAmount(){return this.overrideMouth==="block"?0<this.outputWeight?1:0:this.overrideMouth==="blend"?this.outputWeight:0}get outputWeight(){return this.isBinary?this.weight>.5?1:0:this.weight}addBind(n){this._binds.push(n)}deleteBind(n){const e=this._binds.indexOf(n);e>=0&&this._binds.splice(e,1)}applyWeight(n){var e;let t=this.outputWeight;t*=(e=n?.multiplier)!=null?e:1,this.isBinary&&t<1&&(t=0),this._binds.forEach(i=>i.applyWeight(t))}clearAppliedWeight(){this._binds.forEach(n=>n.clearAppliedWeight())}};function ut(n,e,t){var i,r;const s=n.parser.json,o=(i=s.nodes)==null?void 0:i[e];if(o==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${e}] of glTF but the node doesn't exist`),null;const l=o.mesh;if(l==null)return null;const a=(r=s.meshes)==null?void 0:r[l];if(a==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${l}] of glTF but the mesh doesn't exist`),null;const u=a.primitives.length,h=[];return t.traverse(d=>{h.length<u&&d.isMesh&&h.push(d)}),h}function ct(n,e){return N(this,null,function*(){const t=yield n.parser.getDependency("node",e);return ut(n,e,t)})}function ht(n){return N(this,null,function*(){const e=yield n.parser.getDependencies("node"),t=new Map;return e.forEach((i,r)=>{const s=ut(n,r,i);s!=null&&t.set(r,s)}),t})}var Ie={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 dt(n){return Math.max(Math.min(n,1),0)}var pt=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(){const e={},t=new Set(Object.values(Ie));return Object.entries(this._expressionMap).forEach(([i,r])=>{t.has(i)&&(e[i]=r)}),e}get customExpressionMap(){const e={},t=new Set(Object.values(Ie));return Object.entries(this._expressionMap).forEach(([i,r])=>{t.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 t;return(t=this._expressionMap[e])!=null?t:null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){const t=this._expressions.indexOf(e);t===-1&&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(t=i?.weight)!=null?t:null}setValue(e,t){const i=this.getExpression(e);i&&(i.weight=dt(t))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){const t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){const e=this._calculateWeightMultipliers();this._expressions.forEach(t=>{t.clearAppliedWeight()}),this._expressions.forEach(t=>{let i=1;const r=t.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),t.applyWeight({multiplier:i})})}_calculateWeightMultipliers(){let e=1,t=1,i=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,t-=r.overrideLookAtAmount,i-=r.overrideMouthAmount}),e=Math.max(0,e),t=Math.max(0,t),i=Math.max(0,i),{blink:e,lookAt:t,mouth:i}}},ce={Color:"color",EmissionColor:"emissionColor",ShadeColor:"shadeColor",RimColor:"rimColor",OutlineColor:"outlineColor"},si={_Color:ce.Color,_EmissionColor:ce.EmissionColor,_ShadeColor:ce.ShadeColor,_RimColor:ce.RimColor,_OutlineColor:ce.OutlineColor},oi=new c.Color,ft=class Qn{constructor({material:e,type:t,targetValue:i,targetAlpha:r}){this.material=e,this.type=t,this.targetValue=i,this.targetAlpha=r??1;const s=this._initColorBindState(),o=this._initAlphaBindState();this._state={color:s,alpha:o}}applyWeight(e){const{color:t,alpha:i}=this._state;if(t!=null){const{propertyName:r,deltaValue:s}=t,o=this.material[r];o?.add(oi.copy(s).multiplyScalar(e))}if(i!=null){const{propertyName:r,deltaValue:s}=i;this.material[r]!=null&&(this.material[r]+=s*e)}}clearAppliedWeight(){const{color:e,alpha:t}=this._state;if(e!=null){const{propertyName:i,initialValue:r}=e,s=this.material[i];s?.copy(r)}if(t!=null){const{propertyName:i,initialValue:r}=t;this.material[i]!=null&&(this.material[i]=r)}}_initColorBindState(){var e,t,i;const{material:r,type:s,targetValue:o}=this,l=this._getPropertyNameMap(),a=(t=(e=l?.[s])==null?void 0:e[0])!=null?t:null;if(a==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;const h=r[a].clone(),d=new c.Color(o.r-h.r,o.g-h.g,o.b-h.b);return{propertyName:a,initialValue:h,deltaValue:d}}_initAlphaBindState(){var e,t,i;const{material:r,type:s,targetAlpha:o}=this,l=this._getPropertyNameMap(),a=(t=(e=l?.[s])==null?void 0:e[1])!=null?t:null;if(a==null&&o!==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(a==null)return null;const u=r[a],h=o-u;return{propertyName:a,initialValue:u,deltaValue:h}}_getPropertyNameMap(){var e,t;return(t=(e=Object.entries(Qn._propertyNameMapMap).find(([i])=>this.material[i]===!0))==null?void 0:e[1])!=null?t:null}};ft._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 mt=ft,gt=class{constructor({primitives:n,index:e,weight:t}){this.primitives=n,this.index=e,this.weight=t}applyWeight(n){this.primitives.forEach(e=>{var t;((t=e.morphTargetInfluences)==null?void 0:t[this.index])!=null&&(e.morphTargetInfluences[this.index]+=this.weight*n)})}clearAppliedWeight(){this.primitives.forEach(n=>{var e;((e=n.morphTargetInfluences)==null?void 0:e[this.index])!=null&&(n.morphTargetInfluences[this.index]=0)})}},_t=new c.Vector2,vt=class Yn{constructor({material:e,scale:t,offset:i}){var r,s;this.material=e,this.scale=t,this.offset=i;const o=(r=Object.entries(Yn._propertyNamesMap).find(([l])=>e[l]===!0))==null?void 0:r[1];o==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=[],o.forEach(l=>{var a;const u=(a=e[l])==null?void 0:a.clone();if(!u)return null;e[l]=u;const h=u.offset.clone(),d=u.repeat.clone(),p=i.clone().sub(h),f=t.clone().sub(d);this._properties.push({name:l,initialOffset:h,deltaOffset:p,initialScale:d,deltaScale:f})}))}applyWeight(e){this._properties.forEach(t=>{const i=this.material[t.name];i!==void 0&&(i.offset.add(_t.copy(t.deltaOffset).multiplyScalar(e)),i.repeat.add(_t.copy(t.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{const t=this.material[e.name];t!==void 0&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))})}};vt._propertyNamesMap={isMeshStandardMaterial:["map","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap"],isMeshBasicMaterial:["map","specularMap","alphaMap"],isMToonMaterial:["map","normalMap","emissiveMap","shadeMultiplyTexture","rimMultiplyTexture","outlineWidthMultiplyTexture","uvAnimationMaskTexture"]};var Mt=vt,ai=new Set(["1.0","1.0-beta"]),xt=class qn{get name(){return"VRMExpressionLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return N(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return N(this,null,function*(){const t=yield this._v1Import(e);if(t)return t;const i=yield this._v0Import(e);return i||null})}_v1Import(e){return N(this,null,function*(){var t,i;const r=this.parser.json;if(!(((t=r.extensionsUsed)==null?void 0:t.indexOf("VRMC_vrm"))!==-1))return null;const o=(i=r.extensions)==null?void 0:i.VRMC_vrm;if(!o)return null;const l=o.specVersion;if(!ai.has(l))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${l}"`),null;const a=o.expressions;if(!a)return null;const u=new Set(Object.values(Ie)),h=new Map;a.preset!=null&&Object.entries(a.preset).forEach(([p,f])=>{if(f!=null){if(!u.has(p)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${p}" detected. Ignoring the expression`);return}h.set(p,f)}}),a.custom!=null&&Object.entries(a.custom).forEach(([p,f])=>{if(u.has(p)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${p}". Ignoring the expression`);return}h.set(p,f)});const d=new pt;return yield Promise.all(Array.from(h.entries()).map(p=>N(this,[p],function*([f,g]){var _,v,y,A,R,x,S;const T=new lt(f);if(e.scene.add(T),T.isBinary=(_=g.isBinary)!=null?_:!1,T.overrideBlink=(v=g.overrideBlink)!=null?v:"none",T.overrideLookAt=(y=g.overrideLookAt)!=null?y:"none",T.overrideMouth=(A=g.overrideMouth)!=null?A:"none",(R=g.morphTargetBinds)==null||R.forEach(w=>N(this,null,function*(){var E;if(w.node===void 0||w.index===void 0)return;const I=yield ct(e,w.node),b=w.index;if(!I.every(C=>Array.isArray(C.morphTargetInfluences)&&b<C.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${g.name} attempts to index morph #${b} but not found.`);return}T.addBind(new gt({primitives:I,index:b,weight:(E=w.weight)!=null?E:1}))})),g.materialColorBinds||g.textureTransformBinds){const w=[];e.scene.traverse(E=>{const I=E.material;I&&(Array.isArray(I)?w.push(...I):w.push(I))}),(x=g.materialColorBinds)==null||x.forEach(E=>N(this,null,function*(){w.filter(b=>{var C;const U=(C=this.parser.associations.get(b))==null?void 0:C.materials;return E.material===U}).forEach(b=>{T.addBind(new mt({material:b,type:E.type,targetValue:new c.Color().fromArray(E.targetValue),targetAlpha:E.targetValue[3]}))})})),(S=g.textureTransformBinds)==null||S.forEach(E=>N(this,null,function*(){w.filter(b=>{var C;const U=(C=this.parser.associations.get(b))==null?void 0:C.materials;return E.material===U}).forEach(b=>{var C,U;T.addBind(new Mt({material:b,offset:new c.Vector2().fromArray((C=E.offset)!=null?C:[0,0]),scale:new c.Vector2().fromArray((U=E.scale)!=null?U:[1,1])}))})}))}d.registerExpression(T)}))),d})}_v0Import(e){return N(this,null,function*(){var t;const i=this.parser.json,r=(t=i.extensions)==null?void 0:t.VRM;if(!r)return null;const s=r.blendShapeMaster;if(!s)return null;const o=new pt,l=s.blendShapeGroups;if(!l)return o;const a=new Set;return yield Promise.all(l.map(u=>N(this,null,function*(){var h;const d=u.presetName,p=d!=null&&qn.v0v1PresetNameMap[d]||null,f=p??u.name;if(f==null){console.warn("VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression");return}if(a.has(f)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${d} has duplicated entries. Ignoring the expression`);return}a.add(f);const g=new lt(f);e.scene.add(g),g.isBinary=(h=u.isBinary)!=null?h:!1,u.binds&&u.binds.forEach(v=>N(this,null,function*(){var y;if(v.mesh===void 0||v.index===void 0)return;const A=[];if((y=i.nodes)==null||y.forEach((x,S)=>{x.mesh===v.mesh&&A.push(S)}),A.length===0){console.warn(`VRMExpressionLoaderPlugin: ${u.name} attempts to bind a morph target to the mesh #${v.mesh} but the mesh is not found or not used in the scene. Ignoring the bind.`);return}const R=v.index;yield Promise.all(A.map(x=>N(this,null,function*(){var S;const T=yield ct(e,x);if(!T.every(w=>Array.isArray(w.morphTargetInfluences)&&R<w.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${u.name} attempts to index ${R}th morph but not found.`);return}g.addBind(new gt({primitives:T,index:R,weight:.01*((S=v.weight)!=null?S:100)}))})))}));const _=u.materialValues;_&&_.length!==0&&_.forEach(v=>{if(v.materialName===void 0||v.propertyName===void 0||v.targetValue===void 0)return;const y=[];e.scene.traverse(R=>{if(R.material){const x=R.material;Array.isArray(x)?y.push(...x.filter(S=>(S.name===v.materialName||S.name===v.materialName+" (Outline)")&&y.indexOf(S)===-1)):x.name===v.materialName&&y.indexOf(x)===-1&&y.push(x)}});const A=v.propertyName;y.forEach(R=>{if(A==="_MainTex_ST"){const S=new c.Vector2(v.targetValue[0],v.targetValue[1]),T=new c.Vector2(v.targetValue[2],v.targetValue[3]);T.y=1-T.y-S.y,g.addBind(new Mt({material:R,scale:S,offset:T}));return}const x=si[A];if(x){g.addBind(new mt({material:R,type:x,targetValue:new c.Color().fromArray(v.targetValue),targetAlpha:v.targetValue[3]}));return}console.warn(A+" is not supported")})}),o.registerExpression(g)}))),o})}};xt.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 li=xt,Ce=class le{constructor(e,t){this._firstPersonOnlyLayer=le.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=le.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(t=>({meshes:t.meshes.concat(),type:t.type})),this}clone(){return new le(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:e=le.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=le.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||(this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=t,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,t,i,r){let s=0;if(t!=null&&t.length>0)for(let o=0;o<e.length;o+=3){const l=e[o],a=e[o+1],u=e[o+2],h=t[l],d=i[l];if(h[0]>0&&r.includes(d[0])||h[1]>0&&r.includes(d[1])||h[2]>0&&r.includes(d[2])||h[3]>0&&r.includes(d[3]))continue;const p=t[a],f=i[a];if(p[0]>0&&r.includes(f[0])||p[1]>0&&r.includes(f[1])||p[2]>0&&r.includes(f[2])||p[3]>0&&r.includes(f[3]))continue;const g=t[u],_=i[u];g[0]>0&&r.includes(_[0])||g[1]>0&&r.includes(_[1])||g[2]>0&&r.includes(_[2])||g[3]>0&&r.includes(_[3])||(e[s++]=l,e[s++]=a,e[s++]=u)}return s}_createErasedMesh(e,t){const i=new c.SkinnedMesh(e.geometry.clone(),e.material);i.name=`${e.name}(erase)`,i.frustumCulled=e.frustumCulled,i.layers.set(this._firstPersonOnlyLayer);const r=i.geometry,s=r.getAttribute("skinIndex"),o=s instanceof c.GLBufferAttribute?[]:s.array,l=[];for(let _=0;_<o.length;_+=4)l.push([o[_],o[_+1],o[_+2],o[_+3]]);const a=r.getAttribute("skinWeight"),u=a instanceof c.GLBufferAttribute?[]:a.array,h=[];for(let _=0;_<u.length;_+=4)h.push([u[_],u[_+1],u[_+2],u[_+3]]);const d=r.getIndex();if(!d)throw new Error("The geometry doesn't have an index buffer");const p=Array.from(d.array),f=this._excludeTriangles(p,h,l,t),g=[];for(let _=0;_<f;_++)g[_]=p[_];return r.setIndex(g),e.onBeforeRender&&(i.onBeforeRender=e.onBeforeRender),i.bind(new c.Skeleton(e.skeleton.bones,e.skeleton.boneInverses),new c.Matrix4),i}_createHeadlessModelForSkinnedMesh(e,t){const i=[];if(t.skeleton.bones.forEach((s,o)=>{this._isEraseTarget(s)&&i.push(o)}),!i.length){t.layers.enable(this._thirdPersonOnlyLayer),t.layers.enable(this._firstPersonOnlyLayer);return}t.layers.set(this._thirdPersonOnlyLayer);const r=this._createErasedMesh(t,i);e.add(r)}_createHeadlessModel(e){if(e.type==="Group")if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(t=>t.layers.set(this._thirdPersonOnlyLayer));else{const t=new c.Group;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter(i=>i.type==="SkinnedMesh").forEach(i=>{const r=i;this._createHeadlessModelForSkinnedMesh(t,r)})}else if(e.type==="SkinnedMesh"){const t=e;this._createHeadlessModelForSkinnedMesh(e.parent,t)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(t=>t.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode("head")?!0:e.parent?this._isEraseTarget(e.parent):!1}};Ce.DEFAULT_FIRSTPERSON_ONLY_LAYER=9,Ce.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var yt=Ce,ui=new Set(["1.0","1.0-beta"]),ci=class{get name(){return"VRMFirstPersonLoaderPlugin"}constructor(n){this.parser=n}afterRoot(n){return N(this,null,function*(){const e=n.userData.vrmHumanoid;if(e!==null){if(e===void 0)throw new Error("VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");n.userData.vrmFirstPerson=yield this._import(n,e)}})}_import(n,e){return N(this,null,function*(){if(e==null)return null;const t=yield this._v1Import(n,e);if(t)return t;const i=yield this._v0Import(n,e);return i||null})}_v1Import(n,e){return N(this,null,function*(){var t,i;const r=this.parser.json;if(!(((t=r.extensionsUsed)==null?void 0:t.indexOf("VRMC_vrm"))!==-1))return null;const o=(i=r.extensions)==null?void 0:i.VRMC_vrm;if(!o)return null;const l=o.specVersion;if(!ui.has(l))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${l}"`),null;const a=o.firstPerson,u=[],h=yield ht(n);return Array.from(h.entries()).forEach(([d,p])=>{var f,g;const _=(f=a?.meshAnnotations)==null?void 0:f.find(v=>v.node===d);u.push({meshes:p,type:(g=_?.type)!=null?g:"auto"})}),new yt(e,u)})}_v0Import(n,e){return N(this,null,function*(){var t;const i=this.parser.json,r=(t=i.extensions)==null?void 0:t.VRM;if(!r)return null;const s=r.firstPerson;if(!s)return null;const o=[],l=yield ht(n);return Array.from(l.entries()).forEach(([a,u])=>{const h=i.nodes[a],d=s.meshAnnotations?s.meshAnnotations.find(p=>p.mesh===h.mesh):void 0;o.push({meshes:u,type:this._convertV0FlagToV1Type(d?.firstPersonFlag)})}),new yt(e,o)})}_convertV0FlagToV1Type(n){return n==="FirstPersonOnly"?"firstPersonOnly":n==="ThirdPersonOnly"?"thirdPersonOnly":n==="Both"?"both":"auto"}},At=new c.Vector3,Tt=new c.Vector3,hi=new c.Quaternion,Rt=class extends c.Group{constructor(n){super(),this.vrmHumanoid=n,this._boneAxesMap=new Map,Object.values(n.humanBones).forEach(e=>{const t=new c.AxesHelper(1);t.matrixAutoUpdate=!1,t.material.depthTest=!1,t.material.depthWrite=!1,this.add(t),this._boneAxesMap.set(e,t)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(n=>{n.geometry.dispose(),n.material.dispose()})}updateMatrixWorld(n){Array.from(this._boneAxesMap.entries()).forEach(([e,t])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(At,hi,Tt);const i=At.set(.1,.1,.1).divide(Tt);t.matrix.copy(e.node.matrixWorld).scale(i)}),super.updateMatrixWorld(n)}},Oe=["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"],M={Hips:"hips",Spine:"spine",Chest:"chest",Neck:"neck",Head:"head",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightShoulder:"rightShoulder",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand",LeftThumbProximal:"leftThumbProximal",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"},di={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 St(n){return n.invert?n.invert():n.inverse(),n}var K=new c.Vector3,$=new c.Quaternion,Ue=class{constructor(n){this.humanBones=n,this.restPose=this.getAbsolutePose()}getAbsolutePose(){const n={};return Object.keys(this.humanBones).forEach(e=>{const t=e,i=this.getBoneNode(t);i&&(K.copy(i.position),$.copy(i.quaternion),n[t]={position:K.toArray(),rotation:$.toArray()})}),n}getPose(){const n={};return Object.keys(this.humanBones).forEach(e=>{const t=e,i=this.getBoneNode(t);if(!i)return;K.set(0,0,0),$.identity();const r=this.restPose[t];r?.position&&K.fromArray(r.position).negate(),r?.rotation&&St($.fromArray(r.rotation)),K.add(i.position),$.premultiply(i.quaternion),n[t]={position:K.toArray(),rotation:$.toArray()}}),n}setPose(n){Object.entries(n).forEach(([e,t])=>{const i=e,r=this.getBoneNode(i);if(!r)return;const s=this.restPose[i];s&&(t?.position&&(r.position.fromArray(t.position),s.position&&r.position.add(K.fromArray(s.position))),t?.rotation&&(r.quaternion.fromArray(t.rotation),s.rotation&&r.quaternion.multiply($.fromArray(s.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([n,e])=>{const t=this.getBoneNode(n);t&&(e?.position&&t.position.fromArray(e.position),e?.rotation&&t.quaternion.fromArray(e.rotation))})}getBone(n){var e;return(e=this.humanBones[n])!=null?e:void 0}getBoneNode(n){var e,t;return(t=(e=this.humanBones[n])==null?void 0:e.node)!=null?t:null}},Be=new c.Vector3,pi=new c.Quaternion,fi=new c.Vector3,wt=class Kn extends Ue{static _setupTransforms(e){const t=new c.Object3D;t.name="VRMHumanoidRig";const i={},r={},s={};Oe.forEach(l=>{var a;const u=e.getBoneNode(l);if(u){const h=new c.Vector3,d=new c.Quaternion;u.updateWorldMatrix(!0,!1),u.matrixWorld.decompose(h,d,Be),i[l]=h,r[l]=u.quaternion.clone();const p=new c.Quaternion;(a=u.parent)==null||a.matrixWorld.decompose(Be,p,Be),s[l]=p}});const o={};return Oe.forEach(l=>{var a;const u=e.getBoneNode(l);if(u){const h=i[l];let d=l,p;for(;p==null&&(d=di[d],d!=null);)p=i[d];const f=new c.Object3D;f.name="Normalized_"+u.name,(d?(a=o[d])==null?void 0:a.node:t).add(f),f.position.copy(h),p&&f.position.sub(p),o[l]={node:f}}}),{rigBones:o,root:t,parentWorldRotations:s,boneRotations:r}}constructor(e){const{rigBones:t,root:i,parentWorldRotations:r,boneRotations:s}=Kn._setupTransforms(e);super(t),this.original=e,this.root=i,this._parentWorldRotations=r,this._boneRotations=s}update(){Oe.forEach(e=>{const t=this.original.getBoneNode(e);if(t!=null){const i=this.getBoneNode(e),r=this._parentWorldRotations[e],s=pi.copy(r).invert(),o=this._boneRotations[e];if(t.quaternion.copy(i.quaternion).multiply(r).premultiply(s).multiply(o),e==="hips"){const l=i.getWorldPosition(fi);t.parent.updateWorldMatrix(!0,!1);const a=t.parent.matrixWorld,u=l.applyMatrix4(a.invert());t.position.copy(u)}}})}},Lt=class $n{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=(i=t?.autoUpdateHumanBones)!=null?i:!0,this._rawHumanBones=new Ue(e),this._normalizedHumanBones=new wt(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new Ue(e.humanBones),this._normalizedHumanBones=new wt(this._rawHumanBones),this}clone(){return new $n(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()}},mi={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"},gi=new Set(["1.0","1.0-beta"]),Pt={leftThumbProximal:"leftThumbMetacarpal",leftThumbIntermediate:"leftThumbProximal",rightThumbProximal:"rightThumbMetacarpal",rightThumbIntermediate:"rightThumbProximal"},_i=class{get name(){return"VRMHumanoidLoaderPlugin"}constructor(n,e){this.parser=n,this.helperRoot=e?.helperRoot,this.autoUpdateHumanBones=e?.autoUpdateHumanBones}afterRoot(n){return N(this,null,function*(){n.userData.vrmHumanoid=yield this._import(n)})}_import(n){return N(this,null,function*(){const e=yield this._v1Import(n);if(e)return e;const t=yield this._v0Import(n);return t||null})}_v1Import(n){return N(this,null,function*(){var e,t;const i=this.parser.json;if(!(((e=i.extensionsUsed)==null?void 0:e.indexOf("VRMC_vrm"))!==-1))return null;const s=(t=i.extensions)==null?void 0:t.VRMC_vrm;if(!s)return null;const o=s.specVersion;if(!gi.has(o))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${o}"`),null;const l=s.humanoid;if(!l)return null;const a=l.humanBones.leftThumbIntermediate!=null||l.humanBones.rightThumbIntermediate!=null,u={};l.humanBones!=null&&(yield Promise.all(Object.entries(l.humanBones).map(d=>N(this,[d],function*([p,f]){let g=p;const _=f.node;if(a){const y=Pt[g];y!=null&&(g=y)}const v=yield this.parser.getDependency("node",_);if(v==null){console.warn(`A glTF node bound to the humanoid bone ${g} (index = ${_}) does not exist`);return}u[g]={node:v}}))));const h=new Lt(this._ensureRequiredBonesExist(u),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(n.scene.add(h.normalizedHumanBonesRoot),this.helperRoot){const d=new Rt(h);this.helperRoot.add(d),d.renderOrder=this.helperRoot.renderOrder}return h})}_v0Import(n){return N(this,null,function*(){var e;const i=(e=this.parser.json.extensions)==null?void 0:e.VRM;if(!i)return null;const r=i.humanoid;if(!r)return null;const s={};r.humanBones!=null&&(yield Promise.all(r.humanBones.map(l=>N(this,null,function*(){const a=l.bone,u=l.node;if(a==null||u==null)return;if(u<0){console.warn(`A glTF node index for the humanoid bone ${a} is negative (${u}), ignoring this bone.`);return}const h=yield this.parser.getDependency("node",u);if(h==null){console.warn(`A glTF node bound to the humanoid bone ${a} (index = ${u}) does not exist`);return}const d=Pt[a],p=d??a;if(s[p]!=null){console.warn(`Multiple bone entries for ${p} detected (index = ${u}), ignoring duplicated entries.`);return}s[p]={node:h}}))));const o=new Lt(this._ensureRequiredBonesExist(s),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(n.scene.add(o.normalizedHumanBonesRoot),this.helperRoot){const l=new Rt(o);this.helperRoot.add(l),l.renderOrder=this.helperRoot.renderOrder}return o})}_ensureRequiredBonesExist(n){const e=Object.values(mi).filter(t=>n[t]==null);if(e.length>0)throw new Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${e.join(", ")}`);return n}},Et=class extends c.BufferGeometry{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new c.BufferAttribute(new Float32Array(65*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new c.BufferAttribute(new Uint16Array(3*63),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,n=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,n=!0),n&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let n=0;n<64;n++){const e=n/63*this._currentTheta;this._attrPos.setXYZ(n+1,this._currentRadius*Math.sin(e),0,this._currentRadius*Math.cos(e))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let n=0;n<63;n++)this._attrIndex.setXYZ(n*3,0,n+1,n+2);this._attrIndex.needsUpdate=!0}},vi=class extends c.BufferGeometry{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new c.Vector3,this._currentTail=new c.Vector3,this._attrPos=new c.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new c.BufferAttribute(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,n=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),n=!0),n&&this._buildPosition()}_buildPosition(){for(let n=0;n<32;n++){const e=n/16*Math.PI;this._attrPos.setXYZ(n,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+n,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+n,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 n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(64+n*2,32+n,32+e),this._attrIndex.setXY(128+n*2,64+n,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},ye=new c.Quaternion,Nt=new c.Quaternion,he=new c.Vector3,bt=new c.Vector3,It=Math.sqrt(2)/2,Mi=new c.Quaternion(0,0,-It,It),xi=new c.Vector3(0,1,0),yi=class extends c.Group{constructor(n){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=n;{const e=new Et;e.radius=.5;const t=new c.MeshBasicMaterial({color:65280,transparent:!0,opacity:.5,side:c.DoubleSide,depthTest:!1,depthWrite:!1});this._meshPitch=new c.Mesh(e,t),this.add(this._meshPitch)}{const e=new Et;e.radius=.5;const t=new c.MeshBasicMaterial({color:16711680,transparent:!0,opacity:.5,side:c.DoubleSide,depthTest:!1,depthWrite:!1});this._meshYaw=new c.Mesh(e,t),this.add(this._meshYaw)}{const e=new vi;e.radius=.1;const t=new c.LineBasicMaterial({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new c.LineSegments(e,t),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(n){const e=c.MathUtils.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=e,this._meshYaw.geometry.update();const t=c.MathUtils.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=t,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(he),this.vrmLookAt.getLookAtWorldQuaternion(ye),ye.multiply(this.vrmLookAt.getFaceFrontQuaternion(Nt)),this._meshYaw.position.copy(he),this._meshYaw.quaternion.copy(ye),this._meshPitch.position.copy(he),this._meshPitch.quaternion.copy(ye),this._meshPitch.quaternion.multiply(Nt.setFromAxisAngle(xi,e)),this._meshPitch.quaternion.multiply(Mi);const{target:i,autoUpdate:r}=this.vrmLookAt;i!=null&&r&&(i.getWorldPosition(bt).sub(he),this._lineTarget.geometry.tail.copy(bt),this._lineTarget.geometry.update(),this._lineTarget.position.copy(he)),super.updateMatrixWorld(n)}},Ai=new c.Vector3,Ti=new c.Vector3;function Ve(n,e){return n.matrixWorld.decompose(Ai,e,Ti),e}function Ae(n){return[Math.atan2(-n.z,n.x),Math.atan2(n.y,Math.sqrt(n.x*n.x+n.z*n.z))]}function Ct(n){const e=Math.round(n/2/Math.PI);return n-2*Math.PI*e}var Ot=new c.Vector3(0,0,1),Ri=new c.Vector3,Si=new c.Vector3,wi=new c.Vector3,Li=new c.Quaternion,De=new c.Quaternion,Ut=new c.Quaternion,Pi=new c.Quaternion,Fe=new c.Euler,Bt=class Zn{constructor(e,t){this.offsetFromHeadBone=new c.Vector3,this.autoUpdate=!0,this.faceFront=new c.Vector3(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new c.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 c.Euler)}getEuler(e){return e.set(c.MathUtils.DEG2RAD*this._pitch,c.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 Zn(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){const t=this.humanoid.getRawBoneNode("head");return Ve(t,e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(Ot)<.01)return e.copy(this._restHeadWorldQuaternion).invert();const[t,i]=Ae(this.faceFront);return Fe.set(0,.5*Math.PI+t,i,"YZX"),e.setFromEuler(Fe).premultiply(Pi.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(De),this.getFaceFrontQuaternion(Ut),e.copy(Ot).applyQuaternion(De).applyQuaternion(Ut).applyEuler(this.getEuler(Fe))}lookAt(e){const t=Li.copy(this._restHeadWorldQuaternion).multiply(St(this.getLookAtWorldQuaternion(De))),i=this.getLookAtWorldPosition(Si),r=wi.copy(e).sub(i).applyQuaternion(t).normalize(),[s,o]=Ae(this.faceFront),[l,a]=Ae(r),u=Ct(l-s),h=Ct(o-a);this._yaw=c.MathUtils.RAD2DEG*u,this._pitch=c.MathUtils.RAD2DEG*h,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(Ri)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};Bt.EULER_ORDER="YXZ";var Ei=Bt,Ni=new c.Vector3(0,0,1),k=new c.Quaternion,ie=new c.Quaternion,D=new c.Euler(0,0,0,"YXZ"),Te=class{constructor(n,e,t,i,r){this.humanoid=n,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=t,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=r,this.faceFront=new c.Vector3(0,0,1),this._restQuatLeftEye=new c.Quaternion,this._restQuatRightEye=new c.Quaternion,this._restLeftEyeParentWorldQuat=new c.Quaternion,this._restRightEyeParentWorldQuat=new c.Quaternion;const s=this.humanoid.getRawBoneNode("leftEye"),o=this.humanoid.getRawBoneNode("rightEye");s&&(this._restQuatLeftEye.copy(s.quaternion),Ve(s.parent,this._restLeftEyeParentWorldQuat)),o&&(this._restQuatRightEye.copy(o.quaternion),Ve(o.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(n,e){const t=this.humanoid.getRawBoneNode("leftEye"),i=this.humanoid.getRawBoneNode("rightEye"),r=this.humanoid.getNormalizedBoneNode("leftEye"),s=this.humanoid.getNormalizedBoneNode("rightEye");t&&(e<0?D.x=-c.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-e):D.x=c.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(e),n<0?D.y=-c.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(-n):D.y=c.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(n),k.setFromEuler(D),this._getWorldFaceFrontQuat(ie),r.quaternion.copy(ie).multiply(k).multiply(ie.invert()),k.copy(this._restLeftEyeParentWorldQuat),t.quaternion.copy(r.quaternion).multiply(k).premultiply(k.invert()).multiply(this._restQuatLeftEye)),i&&(e<0?D.x=-c.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-e):D.x=c.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(e),n<0?D.y=-c.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(-n):D.y=c.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(n),k.setFromEuler(D),this._getWorldFaceFrontQuat(ie),s.quaternion.copy(ie).multiply(k).multiply(ie.invert()),k.copy(this._restRightEyeParentWorldQuat),i.quaternion.copy(s.quaternion).multiply(k).premultiply(k.invert()).multiply(this._restQuatRightEye))}lookAt(n){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const e=c.MathUtils.RAD2DEG*n.y,t=c.MathUtils.RAD2DEG*n.x;this.applyYawPitch(e,t)}_getWorldFaceFrontQuat(n){if(this.faceFront.distanceToSquared(Ni)<.01)return n.identity();const[e,t]=Ae(this.faceFront);return D.set(0,.5*Math.PI+e,t,"YZX"),n.setFromEuler(D)}};Te.type="bone";var ke=class{constructor(n,e,t,i,r){this.expressions=n,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=t,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=r}applyYawPitch(n,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))),n<0?(this.expressions.setValue("lookLeft",0),this.expressions.setValue("lookRight",this.rangeMapHorizontalOuter.map(-n))):(this.expressions.setValue("lookRight",0),this.expressions.setValue("lookLeft",this.rangeMapHorizontalOuter.map(n)))}lookAt(n){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");const e=c.MathUtils.RAD2DEG*n.y,t=c.MathUtils.RAD2DEG*n.x;this.applyYawPitch(e,t)}};ke.type="expression";var Vt=class{constructor(n,e){this.inputMaxValue=n,this.outputScale=e}map(n){return this.outputScale*dt(n/this.inputMaxValue)}},bi=new Set(["1.0","1.0-beta"]),Re=.01,Ii=class{get name(){return"VRMLookAtLoaderPlugin"}constructor(n,e){this.parser=n,this.helperRoot=e?.helperRoot}afterRoot(n){return N(this,null,function*(){const e=n.userData.vrmHumanoid;if(e===null)return;if(e===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");const t=n.userData.vrmExpressionManager;if(t!==null){if(t===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first");n.userData.vrmLookAt=yield this._import(n,e,t)}})}_import(n,e,t){return N(this,null,function*(){if(e==null||t==null)return null;const i=yield this._v1Import(n,e,t);if(i)return i;const r=yield this._v0Import(n,e,t);return r||null})}_v1Import(n,e,t){return N(this,null,function*(){var i,r,s;const o=this.parser.json;if(!(((i=o.extensionsUsed)==null?void 0:i.indexOf("VRMC_vrm"))!==-1))return null;const a=(r=o.extensions)==null?void 0:r.VRMC_vrm;if(!a)return null;const u=a.specVersion;if(!bi.has(u))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${u}"`),null;const h=a.lookAt;if(!h)return null;const d=h.type==="expression"?1:10,p=this._v1ImportRangeMap(h.rangeMapHorizontalInner,d),f=this._v1ImportRangeMap(h.rangeMapHorizontalOuter,d),g=this._v1ImportRangeMap(h.rangeMapVerticalDown,d),_=this._v1ImportRangeMap(h.rangeMapVerticalUp,d);let v;h.type==="expression"?v=new ke(t,p,f,g,_):v=new Te(e,p,f,g,_);const y=this._importLookAt(e,v);return y.offsetFromHeadBone.fromArray((s=h.offsetFromHeadBone)!=null?s:[0,.06,0]),y})}_v1ImportRangeMap(n,e){var t,i;let r=(t=n?.inputMaxValue)!=null?t:90;const s=(i=n?.outputScale)!=null?i:e;return r<Re&&(console.warn("VRMLookAtLoaderPlugin: inputMaxValue of a range map is too small. Consider reviewing the range map!"),r=Re),new Vt(r,s)}_v0Import(n,e,t){return N(this,null,function*(){var i,r,s,o;const a=(i=this.parser.json.extensions)==null?void 0:i.VRM;if(!a)return null;const u=a.firstPerson;if(!u)return null;const h=u.lookAtTypeName==="BlendShape"?1:10,d=this._v0ImportDegreeMap(u.lookAtHorizontalInner,h),p=this._v0ImportDegreeMap(u.lookAtHorizontalOuter,h),f=this._v0ImportDegreeMap(u.lookAtVerticalDown,h),g=this._v0ImportDegreeMap(u.lookAtVerticalUp,h);let _;u.lookAtTypeName==="BlendShape"?_=new ke(t,d,p,f,g):_=new Te(e,d,p,f,g);const v=this._importLookAt(e,_);return u.firstPersonBoneOffset?v.offsetFromHeadBone.set((r=u.firstPersonBoneOffset.x)!=null?r:0,(s=u.firstPersonBoneOffset.y)!=null?s:.06,-((o=u.firstPersonBoneOffset.z)!=null?o:0)):v.offsetFromHeadBone.set(0,.06,0),v.faceFront.set(0,0,-1),_ instanceof Te&&_.faceFront.set(0,0,-1),v})}_v0ImportDegreeMap(n,e){var t,i;const r=n?.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=(t=n?.xRange)!=null?t:90;const o=(i=n?.yRange)!=null?i:e;return s<Re&&(console.warn("VRMLookAtLoaderPlugin: xRange of a degree map is too small. Consider reviewing the degree map!"),s=Re),new Vt(s,o)}_importLookAt(n,e){const t=new Ei(n,e);if(this.helperRoot){const i=new yi(t);this.helperRoot.add(i),i.renderOrder=this.helperRoot.renderOrder}return t}};function Ci(n,e){return typeof n!="string"||n===""?"":(/^https?:\/\//i.test(e)&&/^\//.test(n)&&(e=e.replace(/(^https?:\/\/[^/]+).*/i,"$1")),/^(https?:)?\/\//i.test(n)||/^data:.*,.*$/i.test(n)||/^blob:.*$/i.test(n)?n:e+n)}var Oi=new Set(["1.0","1.0-beta"]),Ui=class{get name(){return"VRMMetaLoaderPlugin"}constructor(n,e){var t,i,r;this.parser=n,this.needThumbnailImage=(t=e?.needThumbnailImage)!=null?t:!1,this.acceptLicenseUrls=(i=e?.acceptLicenseUrls)!=null?i:["https://vrm.dev/licenses/1.0/"],this.acceptV0Meta=(r=e?.acceptV0Meta)!=null?r:!0}afterRoot(n){return N(this,null,function*(){n.userData.vrmMeta=yield this._import(n)})}_import(n){return N(this,null,function*(){const e=yield this._v1Import(n);if(e!=null)return e;const t=yield this._v0Import(n);return t??null})}_v1Import(n){return N(this,null,function*(){var e,t,i;const r=this.parser.json;if(!(((e=r.extensionsUsed)==null?void 0:e.indexOf("VRMC_vrm"))!==-1))return null;const o=(t=r.extensions)==null?void 0:t.VRMC_vrm;if(o==null)return null;const l=o.specVersion;if(!Oi.has(l))return console.warn(`VRMMetaLoaderPlugin: Unknown VRMC_vrm specVersion "${l}"`),null;const a=o.meta;if(!a)return null;const u=a.licenseUrl;if(!new Set(this.acceptLicenseUrls).has(u))throw new Error(`VRMMetaLoaderPlugin: The license url "${u}" is not accepted`);let d;return this.needThumbnailImage&&a.thumbnailImage!=null&&(d=(i=yield this._extractGLTFImage(a.thumbnailImage))!=null?i:void 0),{metaVersion:"1",name:a.name,version:a.version,authors:a.authors,copyrightInformation:a.copyrightInformation,contactInformation:a.contactInformation,references:a.references,thirdPartyLicenses:a.thirdPartyLicenses,thumbnailImage:d,licenseUrl:a.licenseUrl,avatarPermission:a.avatarPermission,allowExcessivelyViolentUsage:a.allowExcessivelyViolentUsage,allowExcessivelySexualUsage:a.allowExcessivelySexualUsage,commercialUsage:a.commercialUsage,allowPoliticalOrReligiousUsage:a.allowPoliticalOrReligiousUsage,allowAntisocialOrHateUsage:a.allowAntisocialOrHateUsage,creditNotation:a.creditNotation,allowRedistribution:a.allowRedistribution,modification:a.modification,otherLicenseUrl:a.otherLicenseUrl}})}_v0Import(n){return N(this,null,function*(){var e;const i=(e=this.parser.json.extensions)==null?void 0:e.VRM;if(!i)return null;const 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??void 0,title:r.title,version:r.version,violentUssageName:r.violentUssageName}})}_extractGLTFImage(n){return N(this,null,function*(){var e;const i=(e=this.parser.json.images)==null?void 0:e[n];if(i==null)return console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${n}] of glTF as a thumbnail but the image doesn't exist`),null;let r=i.uri;if(i.bufferView!=null){const o=yield this.parser.getDependency("bufferView",i.bufferView),l=new Blob([o],{type:i.mimeType});r=URL.createObjectURL(l)}return r==null?(console.warn(`VRMMetaLoaderPlugin: Attempt to use images[${n}] of glTF as a thumbnail but the image couldn't load properly`),null):yield new c.ImageLoader().loadAsync(Ci(r,this.parser.options.path)).catch(o=>(console.error(o),console.warn("VRMMetaLoaderPlugin: Failed to load a thumbnail image"),null))})}},Bi=class{constructor(n){this.scene=n.scene,this.meta=n.meta,this.humanoid=n.humanoid,this.expressionManager=n.expressionManager,this.firstPerson=n.firstPerson,this.lookAt=n.lookAt}update(n){this.humanoid.update(),this.lookAt&&this.lookAt.update(n),this.expressionManager&&this.expressionManager.update()}},Vi=class extends Bi{constructor(n){super(n),this.materials=n.materials,this.springBoneManager=n.springBoneManager,this.nodeConstraintManager=n.nodeConstraintManager}update(n){super.update(n),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(n),this.materials&&this.materials.forEach(e=>{e.update&&e.update(n)})}},Di=Object.defineProperty,Dt=Object.getOwnPropertySymbols,Fi=Object.prototype.hasOwnProperty,ki=Object.prototype.propertyIsEnumerable,Ft=(n,e,t)=>e in n?Di(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,kt=(n,e)=>{for(var t in e||(e={}))Fi.call(e,t)&&Ft(n,t,e[t]);if(Dt)for(var t of Dt(e))ki.call(e,t)&&Ft(n,t,e[t]);return n},Z=(n,e,t)=>new Promise((i,r)=>{var s=a=>{try{l(t.next(a))}catch(u){r(u)}},o=a=>{try{l(t.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,o);l((t=t.apply(n,e)).next())}),Hi={"":3e3,srgb:3001};function zi(n,e){parseInt(c.REVISION,10)>=152?n.colorSpace=e:n.encoding=Hi[e]}var Wi=class{get pending(){return Promise.all(this._pendings)}constructor(n,e){this._parser=n,this._materialParams=e,this._pendings=[]}assignPrimitive(n,e){e!=null&&(this._materialParams[n]=e)}assignColor(n,e,t){if(e!=null){const i=new c.Color().fromArray(e);t&&i.convertSRGBToLinear(),this._materialParams[n]=i}}assignTexture(n,e,t){return Z(this,null,function*(){const i=Z(this,null,function*(){if(e!=null){const r=yield this._parser.assignTexture(this._materialParams,n,e);if(r==null){console.warn("GLTFMToonMaterialParamsAssignHelper: Failed to load texture. The rendering result may be wrong");return}t&&zi(r,"srgb")}});return this._pendings.push(i),i})}assignTextureByIndex(n,e,t){return Z(this,null,function*(){return this.assignTexture(n,e!=null?{index:e}:void 0,t)})}},Gi=`// #define PHONG
|
|
17
|
+
|
|
18
|
+
varying vec3 vViewPosition;
|
|
19
|
+
|
|
20
|
+
#ifndef FLAT_SHADED
|
|
21
|
+
varying vec3 vNormal;
|
|
22
|
+
#endif
|
|
23
|
+
|
|
24
|
+
#include <common>
|
|
25
|
+
|
|
26
|
+
// #include <uv_pars_vertex>
|
|
27
|
+
#ifdef MTOON_USE_UV
|
|
28
|
+
varying vec2 vUv;
|
|
29
|
+
|
|
30
|
+
// COMPAT: pre-r151 uses a common uvTransform
|
|
31
|
+
#if THREE_VRM_THREE_REVISION < 151
|
|
32
|
+
uniform mat3 uvTransform;
|
|
33
|
+
#endif
|
|
34
|
+
#endif
|
|
35
|
+
|
|
36
|
+
// #include <uv2_pars_vertex>
|
|
37
|
+
// COMAPT: pre-r151 uses uv2 for lightMap and aoMap
|
|
38
|
+
#if THREE_VRM_THREE_REVISION < 151
|
|
39
|
+
#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )
|
|
40
|
+
attribute vec2 uv2;
|
|
41
|
+
varying vec2 vUv2;
|
|
42
|
+
uniform mat3 uv2Transform;
|
|
43
|
+
#endif
|
|
44
|
+
#endif
|
|
45
|
+
|
|
46
|
+
// #include <displacementmap_pars_vertex>
|
|
47
|
+
// #include <envmap_pars_vertex>
|
|
48
|
+
#include <color_pars_vertex>
|
|
49
|
+
#include <fog_pars_vertex>
|
|
50
|
+
#include <morphtarget_pars_vertex>
|
|
51
|
+
#include <skinning_pars_vertex>
|
|
52
|
+
#include <shadowmap_pars_vertex>
|
|
53
|
+
#include <logdepthbuf_pars_vertex>
|
|
54
|
+
#include <clipping_planes_pars_vertex>
|
|
55
|
+
|
|
56
|
+
#ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE
|
|
57
|
+
uniform sampler2D outlineWidthMultiplyTexture;
|
|
58
|
+
uniform mat3 outlineWidthMultiplyTextureUvTransform;
|
|
59
|
+
#endif
|
|
60
|
+
|
|
61
|
+
uniform float outlineWidthFactor;
|
|
62
|
+
|
|
63
|
+
void main() {
|
|
64
|
+
|
|
65
|
+
// #include <uv_vertex>
|
|
66
|
+
#ifdef MTOON_USE_UV
|
|
67
|
+
// COMPAT: pre-r151 uses a common uvTransform
|
|
68
|
+
#if THREE_VRM_THREE_REVISION >= 151
|
|
69
|
+
vUv = uv;
|
|
70
|
+
#else
|
|
71
|
+
vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
|
|
72
|
+
#endif
|
|
73
|
+
#endif
|
|
74
|
+
|
|
75
|
+
// #include <uv2_vertex>
|
|
76
|
+
// COMAPT: pre-r151 uses uv2 for lightMap and aoMap
|
|
77
|
+
#if THREE_VRM_THREE_REVISION < 151
|
|
78
|
+
#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )
|
|
79
|
+
vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;
|
|
80
|
+
#endif
|
|
81
|
+
#endif
|
|
82
|
+
|
|
83
|
+
#include <color_vertex>
|
|
84
|
+
|
|
85
|
+
#include <beginnormal_vertex>
|
|
86
|
+
#include <morphnormal_vertex>
|
|
87
|
+
#include <skinbase_vertex>
|
|
88
|
+
#include <skinnormal_vertex>
|
|
89
|
+
|
|
90
|
+
// we need this to compute the outline properly
|
|
91
|
+
objectNormal = normalize( objectNormal );
|
|
92
|
+
|
|
93
|
+
#include <defaultnormal_vertex>
|
|
94
|
+
|
|
95
|
+
#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED
|
|
96
|
+
vNormal = normalize( transformedNormal );
|
|
97
|
+
#endif
|
|
98
|
+
|
|
99
|
+
#include <begin_vertex>
|
|
100
|
+
|
|
101
|
+
#include <morphtarget_vertex>
|
|
102
|
+
#include <skinning_vertex>
|
|
103
|
+
// #include <displacementmap_vertex>
|
|
104
|
+
#include <project_vertex>
|
|
105
|
+
#include <logdepthbuf_vertex>
|
|
106
|
+
#include <clipping_planes_vertex>
|
|
107
|
+
|
|
108
|
+
vViewPosition = - mvPosition.xyz;
|
|
109
|
+
|
|
110
|
+
#ifdef OUTLINE
|
|
111
|
+
float worldNormalLength = length( transformedNormal );
|
|
112
|
+
vec3 outlineOffset = outlineWidthFactor * worldNormalLength * objectNormal;
|
|
113
|
+
|
|
114
|
+
#ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE
|
|
115
|
+
vec2 outlineWidthMultiplyTextureUv = ( outlineWidthMultiplyTextureUvTransform * vec3( vUv, 1 ) ).xy;
|
|
116
|
+
float outlineTex = texture2D( outlineWidthMultiplyTexture, outlineWidthMultiplyTextureUv ).g;
|
|
117
|
+
outlineOffset *= outlineTex;
|
|
118
|
+
#endif
|
|
119
|
+
|
|
120
|
+
#ifdef OUTLINE_WIDTH_SCREEN
|
|
121
|
+
outlineOffset *= vViewPosition.z / projectionMatrix[ 1 ].y;
|
|
122
|
+
#endif
|
|
123
|
+
|
|
124
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 );
|
|
125
|
+
|
|
126
|
+
gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic
|
|
127
|
+
#endif
|
|
128
|
+
|
|
129
|
+
#include <worldpos_vertex>
|
|
130
|
+
// #include <envmap_vertex>
|
|
131
|
+
#include <shadowmap_vertex>
|
|
132
|
+
#include <fog_vertex>
|
|
133
|
+
|
|
134
|
+
}`,ji=`// #define PHONG
|
|
135
|
+
|
|
136
|
+
uniform vec3 litFactor;
|
|
137
|
+
|
|
138
|
+
uniform float opacity;
|
|
139
|
+
|
|
140
|
+
uniform vec3 shadeColorFactor;
|
|
141
|
+
#ifdef USE_SHADEMULTIPLYTEXTURE
|
|
142
|
+
uniform sampler2D shadeMultiplyTexture;
|
|
143
|
+
uniform mat3 shadeMultiplyTextureUvTransform;
|
|
144
|
+
#endif
|
|
145
|
+
|
|
146
|
+
uniform float shadingShiftFactor;
|
|
147
|
+
uniform float shadingToonyFactor;
|
|
148
|
+
|
|
149
|
+
#ifdef USE_SHADINGSHIFTTEXTURE
|
|
150
|
+
uniform sampler2D shadingShiftTexture;
|
|
151
|
+
uniform mat3 shadingShiftTextureUvTransform;
|
|
152
|
+
uniform float shadingShiftTextureScale;
|
|
153
|
+
#endif
|
|
154
|
+
|
|
155
|
+
uniform float giEqualizationFactor;
|
|
156
|
+
|
|
157
|
+
uniform vec3 parametricRimColorFactor;
|
|
158
|
+
#ifdef USE_RIMMULTIPLYTEXTURE
|
|
159
|
+
uniform sampler2D rimMultiplyTexture;
|
|
160
|
+
uniform mat3 rimMultiplyTextureUvTransform;
|
|
161
|
+
#endif
|
|
162
|
+
uniform float rimLightingMixFactor;
|
|
163
|
+
uniform float parametricRimFresnelPowerFactor;
|
|
164
|
+
uniform float parametricRimLiftFactor;
|
|
165
|
+
|
|
166
|
+
#ifdef USE_MATCAPTEXTURE
|
|
167
|
+
uniform vec3 matcapFactor;
|
|
168
|
+
uniform sampler2D matcapTexture;
|
|
169
|
+
uniform mat3 matcapTextureUvTransform;
|
|
170
|
+
#endif
|
|
171
|
+
|
|
172
|
+
uniform vec3 emissive;
|
|
173
|
+
uniform float emissiveIntensity;
|
|
174
|
+
|
|
175
|
+
uniform vec3 outlineColorFactor;
|
|
176
|
+
uniform float outlineLightingMixFactor;
|
|
177
|
+
|
|
178
|
+
#ifdef USE_UVANIMATIONMASKTEXTURE
|
|
179
|
+
uniform sampler2D uvAnimationMaskTexture;
|
|
180
|
+
uniform mat3 uvAnimationMaskTextureUvTransform;
|
|
181
|
+
#endif
|
|
182
|
+
|
|
183
|
+
uniform float uvAnimationScrollXOffset;
|
|
184
|
+
uniform float uvAnimationScrollYOffset;
|
|
185
|
+
uniform float uvAnimationRotationPhase;
|
|
186
|
+
|
|
187
|
+
#include <common>
|
|
188
|
+
#include <packing>
|
|
189
|
+
#include <dithering_pars_fragment>
|
|
190
|
+
#include <color_pars_fragment>
|
|
191
|
+
|
|
192
|
+
// #include <uv_pars_fragment>
|
|
193
|
+
#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )
|
|
194
|
+
varying vec2 vUv;
|
|
195
|
+
#endif
|
|
196
|
+
|
|
197
|
+
// #include <uv2_pars_fragment>
|
|
198
|
+
// COMAPT: pre-r151 uses uv2 for lightMap and aoMap
|
|
199
|
+
#if THREE_VRM_THREE_REVISION < 151
|
|
200
|
+
#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )
|
|
201
|
+
varying vec2 vUv2;
|
|
202
|
+
#endif
|
|
203
|
+
#endif
|
|
204
|
+
|
|
205
|
+
#include <map_pars_fragment>
|
|
206
|
+
|
|
207
|
+
#ifdef USE_MAP
|
|
208
|
+
uniform mat3 mapUvTransform;
|
|
209
|
+
#endif
|
|
210
|
+
|
|
211
|
+
// #include <alphamap_pars_fragment>
|
|
212
|
+
|
|
213
|
+
#include <alphatest_pars_fragment>
|
|
214
|
+
|
|
215
|
+
#include <aomap_pars_fragment>
|
|
216
|
+
// #include <lightmap_pars_fragment>
|
|
217
|
+
#include <emissivemap_pars_fragment>
|
|
218
|
+
|
|
219
|
+
#ifdef USE_EMISSIVEMAP
|
|
220
|
+
uniform mat3 emissiveMapUvTransform;
|
|
221
|
+
#endif
|
|
222
|
+
|
|
223
|
+
// #include <envmap_common_pars_fragment>
|
|
224
|
+
// #include <envmap_pars_fragment>
|
|
225
|
+
// #include <cube_uv_reflection_fragment>
|
|
226
|
+
#include <fog_pars_fragment>
|
|
227
|
+
|
|
228
|
+
// #include <bsdfs>
|
|
229
|
+
// COMPAT: pre-r151 doesn't have BRDF_Lambert in <common>
|
|
230
|
+
#if THREE_VRM_THREE_REVISION < 151
|
|
231
|
+
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
|
|
232
|
+
return RECIPROCAL_PI * diffuseColor;
|
|
233
|
+
}
|
|
234
|
+
#endif
|
|
235
|
+
|
|
236
|
+
#include <lights_pars_begin>
|
|
237
|
+
|
|
238
|
+
#include <normal_pars_fragment>
|
|
239
|
+
|
|
240
|
+
// #include <lights_phong_pars_fragment>
|
|
241
|
+
varying vec3 vViewPosition;
|
|
242
|
+
|
|
243
|
+
struct MToonMaterial {
|
|
244
|
+
vec3 diffuseColor;
|
|
245
|
+
vec3 shadeColor;
|
|
246
|
+
float shadingShift;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
float linearstep( float a, float b, float t ) {
|
|
250
|
+
return clamp( ( t - a ) / ( b - a ), 0.0, 1.0 );
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Convert NdotL into toon shading factor using shadingShift and shadingToony
|
|
255
|
+
*/
|
|
256
|
+
float getShading(
|
|
257
|
+
const in float dotNL,
|
|
258
|
+
const in float shadow,
|
|
259
|
+
const in float shadingShift
|
|
260
|
+
) {
|
|
261
|
+
float shading = dotNL;
|
|
262
|
+
shading = shading + shadingShift;
|
|
263
|
+
shading = linearstep( -1.0 + shadingToonyFactor, 1.0 - shadingToonyFactor, shading );
|
|
264
|
+
shading *= shadow;
|
|
265
|
+
return shading;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Mix diffuseColor and shadeColor using shading factor and light color
|
|
270
|
+
*/
|
|
271
|
+
vec3 getDiffuse(
|
|
272
|
+
const in MToonMaterial material,
|
|
273
|
+
const in float shading,
|
|
274
|
+
in vec3 lightColor
|
|
275
|
+
) {
|
|
276
|
+
#ifdef DEBUG_LITSHADERATE
|
|
277
|
+
return vec3( BRDF_Lambert( shading * lightColor ) );
|
|
278
|
+
#endif
|
|
279
|
+
|
|
280
|
+
vec3 col = lightColor * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, shading ) );
|
|
281
|
+
|
|
282
|
+
// The "comment out if you want to PBR absolutely" line
|
|
283
|
+
#ifdef V0_COMPAT_SHADE
|
|
284
|
+
col = min( col, material.diffuseColor );
|
|
285
|
+
#endif
|
|
286
|
+
|
|
287
|
+
return col;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// COMPAT: pre-r156 uses a struct GeometricContext
|
|
291
|
+
#if THREE_VRM_THREE_REVISION >= 157
|
|
292
|
+
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 ) {
|
|
293
|
+
float dotNL = clamp( dot( geometryNormal, directLight.direction ), -1.0, 1.0 );
|
|
294
|
+
vec3 irradiance = directLight.color;
|
|
295
|
+
|
|
296
|
+
// directSpecular will be used for rim lighting, not an actual specular
|
|
297
|
+
reflectedLight.directSpecular += irradiance;
|
|
298
|
+
|
|
299
|
+
irradiance *= dotNL;
|
|
300
|
+
|
|
301
|
+
float shading = getShading( dotNL, shadow, material.shadingShift );
|
|
302
|
+
|
|
303
|
+
// toon shaded diffuse
|
|
304
|
+
reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color );
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
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 ) {
|
|
308
|
+
// indirect diffuse will use diffuseColor, no shadeColor involved
|
|
309
|
+
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
|
|
310
|
+
|
|
311
|
+
// directSpecular will be used for rim lighting, not an actual specular
|
|
312
|
+
reflectedLight.directSpecular += irradiance;
|
|
313
|
+
}
|
|
314
|
+
#else
|
|
315
|
+
void RE_Direct_MToon( const in IncidentLight directLight, const in GeometricContext geometry, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) {
|
|
316
|
+
float dotNL = clamp( dot( geometry.normal, directLight.direction ), -1.0, 1.0 );
|
|
317
|
+
vec3 irradiance = directLight.color;
|
|
318
|
+
|
|
319
|
+
// directSpecular will be used for rim lighting, not an actual specular
|
|
320
|
+
reflectedLight.directSpecular += irradiance;
|
|
321
|
+
|
|
322
|
+
irradiance *= dotNL;
|
|
323
|
+
|
|
324
|
+
float shading = getShading( dotNL, shadow, material.shadingShift );
|
|
325
|
+
|
|
326
|
+
// toon shaded diffuse
|
|
327
|
+
reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color );
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in GeometricContext geometry, const in MToonMaterial material, inout ReflectedLight reflectedLight ) {
|
|
331
|
+
// indirect diffuse will use diffuseColor, no shadeColor involved
|
|
332
|
+
reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
|
|
333
|
+
|
|
334
|
+
// directSpecular will be used for rim lighting, not an actual specular
|
|
335
|
+
reflectedLight.directSpecular += irradiance;
|
|
336
|
+
}
|
|
337
|
+
#endif
|
|
338
|
+
|
|
339
|
+
#define RE_Direct RE_Direct_MToon
|
|
340
|
+
#define RE_IndirectDiffuse RE_IndirectDiffuse_MToon
|
|
341
|
+
#define Material_LightProbeLOD( material ) (0)
|
|
342
|
+
|
|
343
|
+
#include <shadowmap_pars_fragment>
|
|
344
|
+
// #include <bumpmap_pars_fragment>
|
|
345
|
+
|
|
346
|
+
// #include <normalmap_pars_fragment>
|
|
347
|
+
#ifdef USE_NORMALMAP
|
|
348
|
+
|
|
349
|
+
uniform sampler2D normalMap;
|
|
350
|
+
uniform mat3 normalMapUvTransform;
|
|
351
|
+
uniform vec2 normalScale;
|
|
352
|
+
|
|
353
|
+
#endif
|
|
354
|
+
|
|
355
|
+
// COMPAT: pre-r151
|
|
356
|
+
// USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151
|
|
357
|
+
#if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP )
|
|
358
|
+
|
|
359
|
+
uniform mat3 normalMatrix;
|
|
360
|
+
|
|
361
|
+
#endif
|
|
362
|
+
|
|
363
|
+
// COMPAT: pre-r151
|
|
364
|
+
// USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151
|
|
365
|
+
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( TANGENTSPACE_NORMALMAP ) )
|
|
366
|
+
|
|
367
|
+
// Per-Pixel Tangent Space Normal Mapping
|
|
368
|
+
// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
|
|
369
|
+
|
|
370
|
+
// three-vrm specific change: it requires \`uv\` as an input in order to support uv scrolls
|
|
371
|
+
|
|
372
|
+
// Temporary compat against shader change @ Three.js r126, r151
|
|
373
|
+
#if THREE_VRM_THREE_REVISION >= 151
|
|
374
|
+
|
|
375
|
+
mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
|
|
376
|
+
|
|
377
|
+
vec3 q0 = dFdx( eye_pos.xyz );
|
|
378
|
+
vec3 q1 = dFdy( eye_pos.xyz );
|
|
379
|
+
vec2 st0 = dFdx( uv.st );
|
|
380
|
+
vec2 st1 = dFdy( uv.st );
|
|
381
|
+
|
|
382
|
+
vec3 N = surf_norm;
|
|
383
|
+
|
|
384
|
+
vec3 q1perp = cross( q1, N );
|
|
385
|
+
vec3 q0perp = cross( N, q0 );
|
|
386
|
+
|
|
387
|
+
vec3 T = q1perp * st0.x + q0perp * st1.x;
|
|
388
|
+
vec3 B = q1perp * st0.y + q0perp * st1.y;
|
|
389
|
+
|
|
390
|
+
float det = max( dot( T, T ), dot( B, B ) );
|
|
391
|
+
float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
|
|
392
|
+
|
|
393
|
+
return mat3( T * scale, B * scale, N );
|
|
394
|
+
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
#else
|
|
398
|
+
|
|
399
|
+
vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {
|
|
400
|
+
|
|
401
|
+
vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );
|
|
402
|
+
vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );
|
|
403
|
+
vec2 st0 = dFdx( uv.st );
|
|
404
|
+
vec2 st1 = dFdy( uv.st );
|
|
405
|
+
|
|
406
|
+
vec3 N = normalize( surf_norm );
|
|
407
|
+
|
|
408
|
+
vec3 q1perp = cross( q1, N );
|
|
409
|
+
vec3 q0perp = cross( N, q0 );
|
|
410
|
+
|
|
411
|
+
vec3 T = q1perp * st0.x + q0perp * st1.x;
|
|
412
|
+
vec3 B = q1perp * st0.y + q0perp * st1.y;
|
|
413
|
+
|
|
414
|
+
// three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0
|
|
415
|
+
// TODO: Is this still required? Or shall I make a PR about it?
|
|
416
|
+
if ( length( T ) == 0.0 || length( B ) == 0.0 ) {
|
|
417
|
+
return surf_norm;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
float det = max( dot( T, T ), dot( B, B ) );
|
|
421
|
+
float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );
|
|
422
|
+
|
|
423
|
+
return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );
|
|
424
|
+
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
#endif
|
|
428
|
+
|
|
429
|
+
#endif
|
|
430
|
+
|
|
431
|
+
// #include <specularmap_pars_fragment>
|
|
432
|
+
#include <logdepthbuf_pars_fragment>
|
|
433
|
+
#include <clipping_planes_pars_fragment>
|
|
434
|
+
|
|
435
|
+
// == post correction ==========================================================
|
|
436
|
+
void postCorrection() {
|
|
437
|
+
#include <tonemapping_fragment>
|
|
438
|
+
#include <colorspace_fragment>
|
|
439
|
+
#include <fog_fragment>
|
|
440
|
+
#include <premultiplied_alpha_fragment>
|
|
441
|
+
#include <dithering_fragment>
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// == main procedure ===========================================================
|
|
445
|
+
void main() {
|
|
446
|
+
#include <clipping_planes_fragment>
|
|
447
|
+
|
|
448
|
+
vec2 uv = vec2(0.5, 0.5);
|
|
449
|
+
|
|
450
|
+
#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )
|
|
451
|
+
uv = vUv;
|
|
452
|
+
|
|
453
|
+
float uvAnimMask = 1.0;
|
|
454
|
+
#ifdef USE_UVANIMATIONMASKTEXTURE
|
|
455
|
+
vec2 uvAnimationMaskTextureUv = ( uvAnimationMaskTextureUvTransform * vec3( uv, 1 ) ).xy;
|
|
456
|
+
uvAnimMask = texture2D( uvAnimationMaskTexture, uvAnimationMaskTextureUv ).b;
|
|
457
|
+
#endif
|
|
458
|
+
|
|
459
|
+
float uvRotCos = cos( uvAnimationRotationPhase * uvAnimMask );
|
|
460
|
+
float uvRotSin = sin( uvAnimationRotationPhase * uvAnimMask );
|
|
461
|
+
uv = mat2( uvRotCos, -uvRotSin, uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5;
|
|
462
|
+
uv = uv + vec2( uvAnimationScrollXOffset, uvAnimationScrollYOffset ) * uvAnimMask;
|
|
463
|
+
#endif
|
|
464
|
+
|
|
465
|
+
#ifdef DEBUG_UV
|
|
466
|
+
gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
|
|
467
|
+
#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )
|
|
468
|
+
gl_FragColor = vec4( uv, 0.0, 1.0 );
|
|
469
|
+
#endif
|
|
470
|
+
return;
|
|
471
|
+
#endif
|
|
472
|
+
|
|
473
|
+
vec4 diffuseColor = vec4( litFactor, opacity );
|
|
474
|
+
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
|
|
475
|
+
vec3 totalEmissiveRadiance = emissive * emissiveIntensity;
|
|
476
|
+
|
|
477
|
+
#include <logdepthbuf_fragment>
|
|
478
|
+
|
|
479
|
+
// #include <map_fragment>
|
|
480
|
+
#ifdef USE_MAP
|
|
481
|
+
vec2 mapUv = ( mapUvTransform * vec3( uv, 1 ) ).xy;
|
|
482
|
+
vec4 sampledDiffuseColor = texture2D( map, mapUv );
|
|
483
|
+
#ifdef DECODE_VIDEO_TEXTURE
|
|
484
|
+
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 );
|
|
485
|
+
#endif
|
|
486
|
+
diffuseColor *= sampledDiffuseColor;
|
|
487
|
+
#endif
|
|
488
|
+
|
|
489
|
+
// #include <color_fragment>
|
|
490
|
+
#if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )
|
|
491
|
+
diffuseColor.rgb *= vColor;
|
|
492
|
+
#endif
|
|
493
|
+
|
|
494
|
+
// #include <alphamap_fragment>
|
|
495
|
+
|
|
496
|
+
#include <alphatest_fragment>
|
|
497
|
+
|
|
498
|
+
// #include <specularmap_fragment>
|
|
499
|
+
|
|
500
|
+
// #include <normal_fragment_begin>
|
|
501
|
+
float faceDirection = gl_FrontFacing ? 1.0 : -1.0;
|
|
502
|
+
|
|
503
|
+
#ifdef FLAT_SHADED
|
|
504
|
+
|
|
505
|
+
vec3 fdx = dFdx( vViewPosition );
|
|
506
|
+
vec3 fdy = dFdy( vViewPosition );
|
|
507
|
+
vec3 normal = normalize( cross( fdx, fdy ) );
|
|
508
|
+
|
|
509
|
+
#else
|
|
510
|
+
|
|
511
|
+
vec3 normal = normalize( vNormal );
|
|
512
|
+
|
|
513
|
+
#ifdef DOUBLE_SIDED
|
|
514
|
+
|
|
515
|
+
normal *= faceDirection;
|
|
516
|
+
|
|
517
|
+
#endif
|
|
518
|
+
|
|
519
|
+
#endif
|
|
520
|
+
|
|
521
|
+
#ifdef USE_NORMALMAP
|
|
522
|
+
|
|
523
|
+
vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy;
|
|
524
|
+
|
|
525
|
+
#endif
|
|
526
|
+
|
|
527
|
+
#ifdef USE_NORMALMAP_TANGENTSPACE
|
|
528
|
+
|
|
529
|
+
#ifdef USE_TANGENT
|
|
530
|
+
|
|
531
|
+
mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
|
|
532
|
+
|
|
533
|
+
#else
|
|
534
|
+
|
|
535
|
+
mat3 tbn = getTangentFrame( - vViewPosition, normal, normalMapUv );
|
|
536
|
+
|
|
537
|
+
#endif
|
|
538
|
+
|
|
539
|
+
#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
|
|
540
|
+
|
|
541
|
+
tbn[0] *= faceDirection;
|
|
542
|
+
tbn[1] *= faceDirection;
|
|
543
|
+
|
|
544
|
+
#endif
|
|
545
|
+
|
|
546
|
+
#endif
|
|
547
|
+
|
|
548
|
+
#ifdef USE_CLEARCOAT_NORMALMAP
|
|
549
|
+
|
|
550
|
+
#ifdef USE_TANGENT
|
|
551
|
+
|
|
552
|
+
mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
|
|
553
|
+
|
|
554
|
+
#else
|
|
555
|
+
|
|
556
|
+
mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
|
|
557
|
+
|
|
558
|
+
#endif
|
|
559
|
+
|
|
560
|
+
#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
|
|
561
|
+
|
|
562
|
+
tbn2[0] *= faceDirection;
|
|
563
|
+
tbn2[1] *= faceDirection;
|
|
564
|
+
|
|
565
|
+
#endif
|
|
566
|
+
|
|
567
|
+
#endif
|
|
568
|
+
|
|
569
|
+
// non perturbed normal for clearcoat among others
|
|
570
|
+
|
|
571
|
+
vec3 nonPerturbedNormal = normal;
|
|
572
|
+
|
|
573
|
+
#ifdef OUTLINE
|
|
574
|
+
normal *= -1.0;
|
|
575
|
+
#endif
|
|
576
|
+
|
|
577
|
+
// #include <normal_fragment_maps>
|
|
578
|
+
|
|
579
|
+
// COMPAT: pre-r151
|
|
580
|
+
// USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151
|
|
581
|
+
#if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP )
|
|
582
|
+
|
|
583
|
+
normal = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals
|
|
584
|
+
|
|
585
|
+
#ifdef FLIP_SIDED
|
|
586
|
+
|
|
587
|
+
normal = - normal;
|
|
588
|
+
|
|
589
|
+
#endif
|
|
590
|
+
|
|
591
|
+
#ifdef DOUBLE_SIDED
|
|
592
|
+
|
|
593
|
+
normal = normal * faceDirection;
|
|
594
|
+
|
|
595
|
+
#endif
|
|
596
|
+
|
|
597
|
+
normal = normalize( normalMatrix * normal );
|
|
598
|
+
|
|
599
|
+
// COMPAT: pre-r151
|
|
600
|
+
// USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151
|
|
601
|
+
#elif defined( USE_NORMALMAP_TANGENTSPACE ) || defined( TANGENTSPACE_NORMALMAP )
|
|
602
|
+
|
|
603
|
+
vec3 mapN = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0;
|
|
604
|
+
mapN.xy *= normalScale;
|
|
605
|
+
|
|
606
|
+
// COMPAT: pre-r151
|
|
607
|
+
#if THREE_VRM_THREE_REVISION >= 151 || defined( USE_TANGENT )
|
|
608
|
+
|
|
609
|
+
normal = normalize( tbn * mapN );
|
|
610
|
+
|
|
611
|
+
#else
|
|
612
|
+
|
|
613
|
+
normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection );
|
|
614
|
+
|
|
615
|
+
#endif
|
|
616
|
+
|
|
617
|
+
#endif
|
|
618
|
+
|
|
619
|
+
// #include <emissivemap_fragment>
|
|
620
|
+
#ifdef USE_EMISSIVEMAP
|
|
621
|
+
vec2 emissiveMapUv = ( emissiveMapUvTransform * vec3( uv, 1 ) ).xy;
|
|
622
|
+
totalEmissiveRadiance *= texture2D( emissiveMap, emissiveMapUv ).rgb;
|
|
623
|
+
#endif
|
|
624
|
+
|
|
625
|
+
#ifdef DEBUG_NORMAL
|
|
626
|
+
gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 );
|
|
627
|
+
return;
|
|
628
|
+
#endif
|
|
629
|
+
|
|
630
|
+
// -- MToon: lighting --------------------------------------------------------
|
|
631
|
+
// accumulation
|
|
632
|
+
// #include <lights_phong_fragment>
|
|
633
|
+
MToonMaterial material;
|
|
634
|
+
|
|
635
|
+
material.diffuseColor = diffuseColor.rgb;
|
|
636
|
+
|
|
637
|
+
material.shadeColor = shadeColorFactor;
|
|
638
|
+
#ifdef USE_SHADEMULTIPLYTEXTURE
|
|
639
|
+
vec2 shadeMultiplyTextureUv = ( shadeMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;
|
|
640
|
+
material.shadeColor *= texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv ).rgb;
|
|
641
|
+
#endif
|
|
642
|
+
|
|
643
|
+
#if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) )
|
|
644
|
+
material.shadeColor.rgb *= vColor;
|
|
645
|
+
#endif
|
|
646
|
+
|
|
647
|
+
material.shadingShift = shadingShiftFactor;
|
|
648
|
+
#ifdef USE_SHADINGSHIFTTEXTURE
|
|
649
|
+
vec2 shadingShiftTextureUv = ( shadingShiftTextureUvTransform * vec3( uv, 1 ) ).xy;
|
|
650
|
+
material.shadingShift += texture2D( shadingShiftTexture, shadingShiftTextureUv ).r * shadingShiftTextureScale;
|
|
651
|
+
#endif
|
|
652
|
+
|
|
653
|
+
// #include <lights_fragment_begin>
|
|
654
|
+
|
|
655
|
+
// MToon Specific changes:
|
|
656
|
+
// Since we want to take shadows into account of shading instead of irradiance,
|
|
657
|
+
// we had to modify the codes that multiplies the results of shadowmap into color of direct lights.
|
|
658
|
+
|
|
659
|
+
// COMPAT: pre-r156 uses a struct GeometricContext
|
|
660
|
+
#if THREE_VRM_THREE_REVISION >= 157
|
|
661
|
+
vec3 geometryPosition = - vViewPosition;
|
|
662
|
+
vec3 geometryNormal = normal;
|
|
663
|
+
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
|
|
664
|
+
|
|
665
|
+
vec3 geometryClearcoatNormal;
|
|
666
|
+
|
|
667
|
+
#ifdef USE_CLEARCOAT
|
|
668
|
+
|
|
669
|
+
geometryClearcoatNormal = clearcoatNormal;
|
|
670
|
+
|
|
671
|
+
#endif
|
|
672
|
+
#else
|
|
673
|
+
GeometricContext geometry;
|
|
674
|
+
|
|
675
|
+
geometry.position = - vViewPosition;
|
|
676
|
+
geometry.normal = normal;
|
|
677
|
+
geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
|
|
678
|
+
|
|
679
|
+
#ifdef USE_CLEARCOAT
|
|
680
|
+
|
|
681
|
+
geometry.clearcoatNormal = clearcoatNormal;
|
|
682
|
+
|
|
683
|
+
#endif
|
|
684
|
+
#endif
|
|
685
|
+
|
|
686
|
+
IncidentLight directLight;
|
|
687
|
+
|
|
688
|
+
// since these variables will be used in unrolled loop, we have to define in prior
|
|
689
|
+
float shadow;
|
|
690
|
+
|
|
691
|
+
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
|
|
692
|
+
|
|
693
|
+
PointLight pointLight;
|
|
694
|
+
#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
|
|
695
|
+
PointLightShadow pointLightShadow;
|
|
696
|
+
#endif
|
|
697
|
+
|
|
698
|
+
#pragma unroll_loop_start
|
|
699
|
+
for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
|
|
700
|
+
|
|
701
|
+
pointLight = pointLights[ i ];
|
|
702
|
+
|
|
703
|
+
// COMPAT: pre-r156 uses a struct GeometricContext
|
|
704
|
+
#if THREE_VRM_THREE_REVISION >= 157
|
|
705
|
+
getPointLightInfo( pointLight, geometryPosition, directLight );
|
|
706
|
+
#else
|
|
707
|
+
getPointLightInfo( pointLight, geometry, directLight );
|
|
708
|
+
#endif
|
|
709
|
+
|
|
710
|
+
shadow = 1.0;
|
|
711
|
+
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
|
|
712
|
+
pointLightShadow = pointLightShadows[ i ];
|
|
713
|
+
// COMPAT: pre-r166
|
|
714
|
+
// r166 introduced shadowIntensity
|
|
715
|
+
#if THREE_VRM_THREE_REVISION >= 166
|
|
716
|
+
shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
|
|
717
|
+
#else
|
|
718
|
+
shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
|
|
719
|
+
#endif
|
|
720
|
+
#endif
|
|
721
|
+
|
|
722
|
+
// COMPAT: pre-r156 uses a struct GeometricContext
|
|
723
|
+
#if THREE_VRM_THREE_REVISION >= 157
|
|
724
|
+
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );
|
|
725
|
+
#else
|
|
726
|
+
RE_Direct( directLight, geometry, material, shadow, reflectedLight );
|
|
727
|
+
#endif
|
|
728
|
+
|
|
729
|
+
}
|
|
730
|
+
#pragma unroll_loop_end
|
|
731
|
+
|
|
732
|
+
#endif
|
|
733
|
+
|
|
734
|
+
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
|
|
735
|
+
|
|
736
|
+
SpotLight spotLight;
|
|
737
|
+
// COMPAT: pre-r144 uses NUM_SPOT_LIGHT_SHADOWS, r144+ uses NUM_SPOT_LIGHT_COORDS
|
|
738
|
+
#if THREE_VRM_THREE_REVISION >= 144
|
|
739
|
+
#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_COORDS > 0
|
|
740
|
+
SpotLightShadow spotLightShadow;
|
|
741
|
+
#endif
|
|
742
|
+
#elif defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
|
|
743
|
+
SpotLightShadow spotLightShadow;
|
|
744
|
+
#endif
|
|
745
|
+
|
|
746
|
+
#pragma unroll_loop_start
|
|
747
|
+
for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
|
|
748
|
+
|
|
749
|
+
spotLight = spotLights[ i ];
|
|
750
|
+
|
|
751
|
+
// COMPAT: pre-r156 uses a struct GeometricContext
|
|
752
|
+
#if THREE_VRM_THREE_REVISION >= 157
|
|
753
|
+
getSpotLightInfo( spotLight, geometryPosition, directLight );
|
|
754
|
+
#else
|
|
755
|
+
getSpotLightInfo( spotLight, geometry, directLight );
|
|
756
|
+
#endif
|
|
757
|
+
|
|
758
|
+
shadow = 1.0;
|
|
759
|
+
// COMPAT: pre-r144 uses NUM_SPOT_LIGHT_SHADOWS and vSpotShadowCoord, r144+ uses NUM_SPOT_LIGHT_COORDS and vSpotLightCoord
|
|
760
|
+
// COMPAT: pre-r166 does not have shadowIntensity, r166+ has shadowIntensity
|
|
761
|
+
#if THREE_VRM_THREE_REVISION >= 166
|
|
762
|
+
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_COORDS )
|
|
763
|
+
spotLightShadow = spotLightShadows[ i ];
|
|
764
|
+
shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
|
|
765
|
+
#endif
|
|
766
|
+
#elif THREE_VRM_THREE_REVISION >= 144
|
|
767
|
+
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_COORDS )
|
|
768
|
+
spotLightShadow = spotLightShadows[ i ];
|
|
769
|
+
shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
|
|
770
|
+
#endif
|
|
771
|
+
#elif defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
|
|
772
|
+
spotLightShadow = spotLightShadows[ i ];
|
|
773
|
+
shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;
|
|
774
|
+
#endif
|
|
775
|
+
|
|
776
|
+
// COMPAT: pre-r156 uses a struct GeometricContext
|
|
777
|
+
#if THREE_VRM_THREE_REVISION >= 157
|
|
778
|
+
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );
|
|
779
|
+
#else
|
|
780
|
+
RE_Direct( directLight, geometry, material, shadow, reflectedLight );
|
|
781
|
+
#endif
|
|
782
|
+
|
|
783
|
+
}
|
|
784
|
+
#pragma unroll_loop_end
|
|
785
|
+
|
|
786
|
+
#endif
|
|
787
|
+
|
|
788
|
+
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
|
|
789
|
+
|
|
790
|
+
DirectionalLight directionalLight;
|
|
791
|
+
#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
|
|
792
|
+
DirectionalLightShadow directionalLightShadow;
|
|
793
|
+
#endif
|
|
794
|
+
|
|
795
|
+
#pragma unroll_loop_start
|
|
796
|
+
for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
|
|
797
|
+
|
|
798
|
+
directionalLight = directionalLights[ i ];
|
|
799
|
+
|
|
800
|
+
// COMPAT: pre-r156 uses a struct GeometricContext
|
|
801
|
+
#if THREE_VRM_THREE_REVISION >= 157
|
|
802
|
+
getDirectionalLightInfo( directionalLight, directLight );
|
|
803
|
+
#else
|
|
804
|
+
getDirectionalLightInfo( directionalLight, geometry, directLight );
|
|
805
|
+
#endif
|
|
806
|
+
|
|
807
|
+
shadow = 1.0;
|
|
808
|
+
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
|
|
809
|
+
directionalLightShadow = directionalLightShadows[ i ];
|
|
810
|
+
// COMPAT: pre-r166
|
|
811
|
+
// r166 introduced shadowIntensity
|
|
812
|
+
#if THREE_VRM_THREE_REVISION >= 166
|
|
813
|
+
shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
|
|
814
|
+
#else
|
|
815
|
+
shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
|
|
816
|
+
#endif
|
|
817
|
+
#endif
|
|
818
|
+
|
|
819
|
+
// COMPAT: pre-r156 uses a struct GeometricContext
|
|
820
|
+
#if THREE_VRM_THREE_REVISION >= 157
|
|
821
|
+
RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight );
|
|
822
|
+
#else
|
|
823
|
+
RE_Direct( directLight, geometry, material, shadow, reflectedLight );
|
|
824
|
+
#endif
|
|
825
|
+
|
|
826
|
+
}
|
|
827
|
+
#pragma unroll_loop_end
|
|
828
|
+
|
|
829
|
+
#endif
|
|
830
|
+
|
|
831
|
+
// #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
|
|
832
|
+
|
|
833
|
+
// RectAreaLight rectAreaLight;
|
|
834
|
+
|
|
835
|
+
// #pragma unroll_loop_start
|
|
836
|
+
// for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
|
|
837
|
+
|
|
838
|
+
// rectAreaLight = rectAreaLights[ i ];
|
|
839
|
+
// RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );
|
|
840
|
+
|
|
841
|
+
// }
|
|
842
|
+
// #pragma unroll_loop_end
|
|
843
|
+
|
|
844
|
+
// #endif
|
|
845
|
+
|
|
846
|
+
#if defined( RE_IndirectDiffuse )
|
|
847
|
+
|
|
848
|
+
vec3 iblIrradiance = vec3( 0.0 );
|
|
849
|
+
|
|
850
|
+
vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
|
|
851
|
+
|
|
852
|
+
// COMPAT: pre-r156 uses a struct GeometricContext
|
|
853
|
+
// COMPAT: pre-r156 doesn't have a define USE_LIGHT_PROBES
|
|
854
|
+
#if THREE_VRM_THREE_REVISION >= 157
|
|
855
|
+
#if defined( USE_LIGHT_PROBES )
|
|
856
|
+
irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
|
|
857
|
+
#endif
|
|
858
|
+
#else
|
|
859
|
+
irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
|
|
860
|
+
#endif
|
|
861
|
+
|
|
862
|
+
#if ( NUM_HEMI_LIGHTS > 0 )
|
|
863
|
+
|
|
864
|
+
#pragma unroll_loop_start
|
|
865
|
+
for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
|
|
866
|
+
|
|
867
|
+
// COMPAT: pre-r156 uses a struct GeometricContext
|
|
868
|
+
#if THREE_VRM_THREE_REVISION >= 157
|
|
869
|
+
irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
|
|
870
|
+
#else
|
|
871
|
+
irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );
|
|
872
|
+
#endif
|
|
873
|
+
|
|
874
|
+
}
|
|
875
|
+
#pragma unroll_loop_end
|
|
876
|
+
|
|
877
|
+
#endif
|
|
878
|
+
|
|
879
|
+
#endif
|
|
880
|
+
|
|
881
|
+
// #if defined( RE_IndirectSpecular )
|
|
882
|
+
|
|
883
|
+
// vec3 radiance = vec3( 0.0 );
|
|
884
|
+
// vec3 clearcoatRadiance = vec3( 0.0 );
|
|
885
|
+
|
|
886
|
+
// #endif
|
|
887
|
+
|
|
888
|
+
#include <lights_fragment_maps>
|
|
889
|
+
#include <lights_fragment_end>
|
|
890
|
+
|
|
891
|
+
// modulation
|
|
892
|
+
#include <aomap_fragment>
|
|
893
|
+
|
|
894
|
+
vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
|
|
895
|
+
|
|
896
|
+
#ifdef DEBUG_LITSHADERATE
|
|
897
|
+
gl_FragColor = vec4( col, diffuseColor.a );
|
|
898
|
+
postCorrection();
|
|
899
|
+
return;
|
|
900
|
+
#endif
|
|
901
|
+
|
|
902
|
+
// -- MToon: rim lighting -----------------------------------------
|
|
903
|
+
vec3 viewDir = normalize( vViewPosition );
|
|
904
|
+
|
|
905
|
+
#ifndef PHYSICALLY_CORRECT_LIGHTS
|
|
906
|
+
reflectedLight.directSpecular /= PI;
|
|
907
|
+
#endif
|
|
908
|
+
vec3 rimMix = mix( vec3( 1.0 ), reflectedLight.directSpecular, rimLightingMixFactor );
|
|
909
|
+
|
|
910
|
+
vec3 rim = parametricRimColorFactor * pow( saturate( 1.0 - dot( viewDir, normal ) + parametricRimLiftFactor ), parametricRimFresnelPowerFactor );
|
|
911
|
+
|
|
912
|
+
#ifdef USE_MATCAPTEXTURE
|
|
913
|
+
{
|
|
914
|
+
vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) );
|
|
915
|
+
vec3 y = cross( viewDir, x ); // guaranteed to be normalized
|
|
916
|
+
vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) );
|
|
917
|
+
sphereUv = ( matcapTextureUvTransform * vec3( sphereUv, 1 ) ).xy;
|
|
918
|
+
vec3 matcap = texture2D( matcapTexture, sphereUv ).rgb;
|
|
919
|
+
rim += matcapFactor * matcap;
|
|
920
|
+
}
|
|
921
|
+
#endif
|
|
922
|
+
|
|
923
|
+
#ifdef USE_RIMMULTIPLYTEXTURE
|
|
924
|
+
vec2 rimMultiplyTextureUv = ( rimMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy;
|
|
925
|
+
rim *= texture2D( rimMultiplyTexture, rimMultiplyTextureUv ).rgb;
|
|
926
|
+
#endif
|
|
927
|
+
|
|
928
|
+
col += rimMix * rim;
|
|
929
|
+
|
|
930
|
+
// -- MToon: Emission --------------------------------------------------------
|
|
931
|
+
col += totalEmissiveRadiance;
|
|
932
|
+
|
|
933
|
+
// #include <envmap_fragment>
|
|
934
|
+
|
|
935
|
+
// -- Almost done! -----------------------------------------------------------
|
|
936
|
+
#if defined( OUTLINE )
|
|
937
|
+
col = outlineColorFactor.rgb * mix( vec3( 1.0 ), col, outlineLightingMixFactor );
|
|
938
|
+
#endif
|
|
939
|
+
|
|
940
|
+
#ifdef OPAQUE
|
|
941
|
+
diffuseColor.a = 1.0;
|
|
942
|
+
#endif
|
|
943
|
+
|
|
944
|
+
gl_FragColor = vec4( col, diffuseColor.a );
|
|
945
|
+
postCorrection();
|
|
946
|
+
}
|
|
947
|
+
`,Xi={None:"none"},Ht={None:"none",ScreenCoordinates:"screenCoordinates"},Qi={3e3:"",3001:"srgb"};function He(n){return parseInt(c.REVISION,10)>=152?n.colorSpace:Qi[n.encoding]}var Yi=class extends c.ShaderMaterial{constructor(n={}){var e;super({vertexShader:Gi,fragmentShader:ji}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=c.TangentSpaceNormalMap,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=Xi.None,this._outlineWidthMode=Ht.None,this._isOutline=!1,n.transparentWithZWrite&&(n.depthWrite=!0),delete n.transparentWithZWrite,n.fog=!0,n.lights=!0,n.clipping=!0,this.uniforms=c.UniformsUtils.merge([c.UniformsLib.common,c.UniformsLib.normalmap,c.UniformsLib.emissivemap,c.UniformsLib.fog,c.UniformsLib.lights,{litFactor:{value:new c.Color(1,1,1)},mapUvTransform:{value:new c.Matrix3},colorAlpha:{value:1},normalMapUvTransform:{value:new c.Matrix3},shadeColorFactor:{value:new c.Color(0,0,0)},shadeMultiplyTexture:{value:null},shadeMultiplyTextureUvTransform:{value:new c.Matrix3},shadingShiftFactor:{value:0},shadingShiftTexture:{value:null},shadingShiftTextureUvTransform:{value:new c.Matrix3},shadingShiftTextureScale:{value:1},shadingToonyFactor:{value:.9},giEqualizationFactor:{value:.9},matcapFactor:{value:new c.Color(1,1,1)},matcapTexture:{value:null},matcapTextureUvTransform:{value:new c.Matrix3},parametricRimColorFactor:{value:new c.Color(0,0,0)},rimMultiplyTexture:{value:null},rimMultiplyTextureUvTransform:{value:new c.Matrix3},rimLightingMixFactor:{value:1},parametricRimFresnelPowerFactor:{value:5},parametricRimLiftFactor:{value:0},emissive:{value:new c.Color(0,0,0)},emissiveIntensity:{value:1},emissiveMapUvTransform:{value:new c.Matrix3},outlineWidthMultiplyTexture:{value:null},outlineWidthMultiplyTextureUvTransform:{value:new c.Matrix3},outlineWidthFactor:{value:0},outlineColorFactor:{value:new c.Color(0,0,0)},outlineLightingMixFactor:{value:1},uvAnimationMaskTexture:{value:null},uvAnimationMaskTextureUvTransform:{value:new c.Matrix3},uvAnimationScrollXOffset:{value:0},uvAnimationScrollYOffset:{value:0},uvAnimationRotationPhase:{value:0}},(e=n.uniforms)!=null?e:{}]),this.setValues(n),this._uploadUniformsWorkaround(),this.customProgramCacheKey=()=>[...Object.entries(this._generateDefines()).map(([t,i])=>`${t}:${i}`),this.matcapTexture?`matcapTextureColorSpace:${He(this.matcapTexture)}`:"",this.shadeMultiplyTexture?`shadeMultiplyTextureColorSpace:${He(this.shadeMultiplyTexture)}`:"",this.rimMultiplyTexture?`rimMultiplyTextureColorSpace:${He(this.rimMultiplyTexture)}`:""].join(","),this.onBeforeCompile=t=>{const i=parseInt(c.REVISION,10),r=Object.entries(kt(kt({},this._generateDefines()),this.defines)).filter(([s,o])=>!!o).map(([s,o])=>`#define ${s} ${o}`).join(`
|
|
948
|
+
`)+`
|
|
949
|
+
`;t.vertexShader=r+t.vertexShader,t.fragmentShader=r+t.fragmentShader,i<154&&(t.fragmentShader=t.fragmentShader.replace("#include <colorspace_fragment>","#include <encodings_fragment>"))}}get color(){return this.uniforms.litFactor.value}set color(n){this.uniforms.litFactor.value=n}get map(){return this.uniforms.map.value}set map(n){this.uniforms.map.value=n}get normalMap(){return this.uniforms.normalMap.value}set normalMap(n){this.uniforms.normalMap.value=n}get normalScale(){return this.uniforms.normalScale.value}set normalScale(n){this.uniforms.normalScale.value=n}get emissive(){return this.uniforms.emissive.value}set emissive(n){this.uniforms.emissive.value=n}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(n){this.uniforms.emissiveIntensity.value=n}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(n){this.uniforms.emissiveMap.value=n}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(n){this.uniforms.shadeColorFactor.value=n}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(n){this.uniforms.shadeMultiplyTexture.value=n}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(n){this.uniforms.shadingShiftFactor.value=n}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(n){this.uniforms.shadingShiftTexture.value=n}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(n){this.uniforms.shadingShiftTextureScale.value=n}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(n){this.uniforms.shadingToonyFactor.value=n}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(n){this.uniforms.giEqualizationFactor.value=n}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(n){this.uniforms.matcapFactor.value=n}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(n){this.uniforms.matcapTexture.value=n}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(n){this.uniforms.parametricRimColorFactor.value=n}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(n){this.uniforms.rimMultiplyTexture.value=n}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(n){this.uniforms.rimLightingMixFactor.value=n}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(n){this.uniforms.parametricRimFresnelPowerFactor.value=n}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(n){this.uniforms.parametricRimLiftFactor.value=n}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(n){this.uniforms.outlineWidthMultiplyTexture.value=n}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(n){this.uniforms.outlineWidthFactor.value=n}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(n){this.uniforms.outlineColorFactor.value=n}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(n){this.uniforms.outlineLightingMixFactor.value=n}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(n){this.uniforms.uvAnimationMaskTexture.value=n}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(n){this.uniforms.uvAnimationScrollXOffset.value=n}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(n){this.uniforms.uvAnimationScrollYOffset.value=n}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(n){this.uniforms.uvAnimationRotationPhase.value=n}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(n){this._ignoreVertexColor=n,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(n){this._v0CompatShade=n,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(n){this._debugMode=n,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(n){this._outlineWidthMode=n,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(n){this._isOutline=n,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(n){this._uploadUniformsWorkaround(),this._updateUVAnimation(n)}copy(n){return super.copy(n),this.map=n.map,this.normalMap=n.normalMap,this.emissiveMap=n.emissiveMap,this.shadeMultiplyTexture=n.shadeMultiplyTexture,this.shadingShiftTexture=n.shadingShiftTexture,this.matcapTexture=n.matcapTexture,this.rimMultiplyTexture=n.rimMultiplyTexture,this.outlineWidthMultiplyTexture=n.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=n.uvAnimationMaskTexture,this.normalMapType=n.normalMapType,this.uvAnimationScrollXSpeedFactor=n.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=n.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=n.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=n.ignoreVertexColor,this.v0CompatShade=n.v0CompatShade,this.debugMode=n.debugMode,this.outlineWidthMode=n.outlineWidthMode,this.isOutline=n.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(n){this.uniforms.uvAnimationScrollXOffset.value+=n*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=n*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=n*this.uvAnimationRotationSpeedFactor,this.uniforms.alphaTest.value=this.alphaTest,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(){const n=parseInt(c.REVISION,10),e=this.outlineWidthMultiplyTexture!==null,t=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:n,OUTLINE:this._isOutline,MTOON_USE_UV:e||t,MTOON_UVS_VERTEX_ONLY:e&&!t,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_SCREEN:this._isOutline&&this._outlineWidthMode===Ht.ScreenCoordinates}}_updateTextureMatrix(n,e){n.value&&(n.value.matrixAutoUpdate&&n.value.updateMatrix(),e.value.copy(n.value.matrix))}},qi=new Set(["1.0","1.0-beta"]),zt=class be{get name(){return be.EXTENSION_NAME}constructor(e,t={}){var i,r,s,o;this.parser=e,this.materialType=(i=t.materialType)!=null?i:Yi,this.renderOrderOffset=(r=t.renderOrderOffset)!=null?r:0,this.v0CompatShade=(s=t.v0CompatShade)!=null?s:!1,this.debugMode=(o=t.debugMode)!=null?o:"none",this._mToonMaterialSet=new Set}beforeRoot(){return Z(this,null,function*(){this._removeUnlitExtensionIfMToonExists()})}afterRoot(e){return Z(this,null,function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)})}getMaterialType(e){return this._getMToonExtension(e)?this.materialType:null}extendMaterialParams(e,t){const i=this._getMToonExtension(e);return i?this._extendMaterialParams(i,t):null}loadMesh(e){return Z(this,null,function*(){var t;const i=this.parser,s=(t=i.json.meshes)==null?void 0:t[e];if(s==null)throw new Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);const o=s.primitives,l=yield i.loadMesh(e);if(o.length===1){const a=l,u=o[0].material;u!=null&&this._setupPrimitive(a,u)}else{const a=l;for(let u=0;u<o.length;u++){const h=a.children[u],d=o[u].material;d!=null&&this._setupPrimitive(h,d)}}return l})}_removeUnlitExtensionIfMToonExists(){const i=this.parser.json.materials;i?.map((r,s)=>{var o;this._getMToonExtension(s)&&((o=r.extensions)!=null&&o.KHR_materials_unlit)&&delete r.extensions.KHR_materials_unlit})}_getMToonExtension(e){var t,i;const o=(t=this.parser.json.materials)==null?void 0:t[e];if(o==null){console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);return}const l=(i=o.extensions)==null?void 0:i[be.EXTENSION_NAME];if(l==null)return;const a=l.specVersion;if(!qi.has(a)){console.warn(`MToonMaterialLoaderPlugin: Unknown ${be.EXTENSION_NAME} specVersion "${a}"`);return}return l}_extendMaterialParams(e,t){return Z(this,null,function*(){var i;delete t.metalness,delete t.roughness;const r=new Wi(this.parser,t);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,t){const i=this._getMToonExtension(t);if(i){const 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){const t=e.material;if(!(t instanceof c.Material)||!this._shouldGenerateOutline(t))return;e.material=[t];const i=t.clone();i.name+=" (Outline)",i.isOutline=!0,i.side=c.BackSide,e.material.push(i);const 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){const t=e.material,i=new Set;Array.isArray(t)?t.forEach(r=>i.add(r)):i.add(t);for(const r of i)this._mToonMaterialSet.add(r)}_parseRenderOrder(e){var t;return(e.transparentWithZWrite?0:19)+((t=e.renderQueueOffsetNumber)!=null?t:0)}};zt.EXTENSION_NAME="VRMC_materials_mtoon";var Ki=zt,$i=(n,e,t)=>new Promise((i,r)=>{var s=a=>{try{l(t.next(a))}catch(u){r(u)}},o=a=>{try{l(t.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,o);l((t=t.apply(n,e)).next())}),Wt=class at{get name(){return at.EXTENSION_NAME}constructor(e){this.parser=e}extendMaterialParams(e,t){return $i(this,null,function*(){const i=this._getHDREmissiveMultiplierExtension(e);if(i==null)return;console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead.");const r=i.emissiveMultiplier;t.emissiveIntensity=r})}_getHDREmissiveMultiplierExtension(e){var t,i;const o=(t=this.parser.json.materials)==null?void 0:t[e];if(o==null){console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);return}const l=(i=o.extensions)==null?void 0:i[at.EXTENSION_NAME];if(l!=null)return l}};Wt.EXTENSION_NAME="VRMC_materials_hdr_emissiveMultiplier";var Zi=Wt,Ji=Object.defineProperty,er=Object.defineProperties,tr=Object.getOwnPropertyDescriptors,Gt=Object.getOwnPropertySymbols,nr=Object.prototype.hasOwnProperty,ir=Object.prototype.propertyIsEnumerable,jt=(n,e,t)=>e in n?Ji(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,H=(n,e)=>{for(var t in e||(e={}))nr.call(e,t)&&jt(n,t,e[t]);if(Gt)for(var t of Gt(e))ir.call(e,t)&&jt(n,t,e[t]);return n},Xt=(n,e)=>er(n,tr(e)),rr=(n,e,t)=>new Promise((i,r)=>{var s=a=>{try{l(t.next(a))}catch(u){r(u)}},o=a=>{try{l(t.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,o);l((t=t.apply(n,e)).next())});function re(n){return Math.pow(n,2.2)}var sr=class{get name(){return"VRMMaterialsV0CompatPlugin"}constructor(n){var e;this.parser=n,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;const t=this.parser.json;t.extensionsUsed=(e=t.extensionsUsed)!=null?e:[],t.extensionsUsed.indexOf("KHR_texture_transform")===-1&&t.extensionsUsed.push("KHR_texture_transform")}beforeRoot(){return rr(this,null,function*(){var n;const e=this.parser.json,t=(n=e.extensions)==null?void 0:n.VRM,i=t?.materialProperties;i&&(this._populateRenderQueueMap(i),i.forEach((r,s)=>{var o,l;const a=(o=e.materials)==null?void 0:o[s];if(a==null){console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${s}] of glTF but the material doesn't exist`);return}if(r.shader==="VRM/MToon"){const u=this._parseV0MToonProperties(r,a);e.materials[s]=u}else if((l=r.shader)!=null&&l.startsWith("VRM/Unlit")){const u=this._parseV0UnlitProperties(r,a);e.materials[s]=u}else r.shader==="VRM_USE_GLTFSHADER"||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${r.shader}`)}))})}_parseV0MToonProperties(n,e){var t,i,r,s,o,l,a,u,h,d,p,f,g,_,v,y,A,R,x,S,T,w,E,I,b,C,U,Y,ge,_e,j,W,ae,ve,B,mn,gn,_n,vn,Mn,xn,yn,An,Tn,Rn,Sn,wn,Ln,Pn,En,Nn,bn,In,Cn,On;const Un=(i=(t=n.keywordMap)==null?void 0:t._ALPHABLEND_ON)!=null?i:!1,Hs=((r=n.floatProperties)==null?void 0:r._ZWrite)===1&&Un,zs=this._v0ParseRenderQueue(n),Bn=(o=(s=n.keywordMap)==null?void 0:s._ALPHATEST_ON)!=null?o:!1,Ws=Un?"BLEND":Bn?"MASK":"OPAQUE",Gs=Bn?(a=(l=n.floatProperties)==null?void 0:l._Cutoff)!=null?a:.5:void 0,js=((h=(u=n.floatProperties)==null?void 0:u._CullMode)!=null?h:2)===0,ne=this._portTextureTransform(n),Xs=((p=(d=n.vectorProperties)==null?void 0:d._Color)!=null?p:[1,1,1,1]).map((jn,_o)=>_o===3?jn:re(jn)),Vn=(f=n.textureProperties)==null?void 0:f._MainTex,Qs=Vn!=null?{index:Vn,extensions:H({},ne)}:void 0,Ys=(_=(g=n.floatProperties)==null?void 0:g._BumpScale)!=null?_:1,Dn=(v=n.textureProperties)==null?void 0:v._BumpMap,qs=Dn!=null?{index:Dn,scale:Ys,extensions:H({},ne)}:void 0,Ks=((A=(y=n.vectorProperties)==null?void 0:y._EmissionColor)!=null?A:[0,0,0,1]).map(re),Fn=(R=n.textureProperties)==null?void 0:R._EmissionMap,$s=Fn!=null?{index:Fn,extensions:H({},ne)}:void 0,Zs=((S=(x=n.vectorProperties)==null?void 0:x._ShadeColor)!=null?S:[.97,.81,.86,1]).map(re),kn=(T=n.textureProperties)==null?void 0:T._ShadeTexture,Js=kn!=null?{index:kn,extensions:H({},ne)}:void 0;let Pe=(E=(w=n.floatProperties)==null?void 0:w._ShadeShift)!=null?E:0,Ee=(b=(I=n.floatProperties)==null?void 0:I._ShadeToony)!=null?b:.9;Ee=c.MathUtils.lerp(Ee,1,.5+.5*Pe),Pe=-Pe-(1-Ee);const Hn=(U=(C=n.floatProperties)==null?void 0:C._IndirectLightIntensity)!=null?U:.1,eo=Hn?1-Hn:void 0,st=(Y=n.textureProperties)==null?void 0:Y._SphereAdd,to=st!=null?[1,1,1]:void 0,no=st!=null?{index:st}:void 0,io=(_e=(ge=n.floatProperties)==null?void 0:ge._RimLightingMix)!=null?_e:0,zn=(j=n.textureProperties)==null?void 0:j._RimTexture,ro=zn!=null?{index:zn,extensions:H({},ne)}:void 0,so=((ae=(W=n.vectorProperties)==null?void 0:W._RimColor)!=null?ae:[0,0,0,1]).map(re),oo=(B=(ve=n.floatProperties)==null?void 0:ve._RimFresnelPower)!=null?B:1,ao=(gn=(mn=n.floatProperties)==null?void 0:mn._RimLift)!=null?gn:0,lo=["none","worldCoordinates","screenCoordinates"][(vn=(_n=n.floatProperties)==null?void 0:_n._OutlineWidthMode)!=null?vn:0];let ot=(xn=(Mn=n.floatProperties)==null?void 0:Mn._OutlineWidth)!=null?xn:0;ot=.01*ot;const Wn=(yn=n.textureProperties)==null?void 0:yn._OutlineWidthTexture,uo=Wn!=null?{index:Wn,extensions:H({},ne)}:void 0,co=((Tn=(An=n.vectorProperties)==null?void 0:An._OutlineColor)!=null?Tn:[0,0,0]).map(re),ho=((Sn=(Rn=n.floatProperties)==null?void 0:Rn._OutlineColorMode)!=null?Sn:0)===1?(Ln=(wn=n.floatProperties)==null?void 0:wn._OutlineLightingMix)!=null?Ln:1:0,Gn=(Pn=n.textureProperties)==null?void 0:Pn._UvAnimMaskTexture,po=Gn!=null?{index:Gn,extensions:H({},ne)}:void 0,fo=(Nn=(En=n.floatProperties)==null?void 0:En._UvAnimScrollX)!=null?Nn:0;let Ne=(In=(bn=n.floatProperties)==null?void 0:bn._UvAnimScrollY)!=null?In:0;Ne!=null&&(Ne=-Ne);const mo=(On=(Cn=n.floatProperties)==null?void 0:Cn._UvAnimRotation)!=null?On:0,go={specVersion:"1.0",transparentWithZWrite:Hs,renderQueueOffsetNumber:zs,shadeColorFactor:Zs,shadeMultiplyTexture:Js,shadingShiftFactor:Pe,shadingToonyFactor:Ee,giEqualizationFactor:eo,matcapFactor:to,matcapTexture:no,rimLightingMixFactor:io,rimMultiplyTexture:ro,parametricRimColorFactor:so,parametricRimFresnelPowerFactor:oo,parametricRimLiftFactor:ao,outlineWidthMode:lo,outlineWidthFactor:ot,outlineWidthMultiplyTexture:uo,outlineColorFactor:co,outlineLightingMixFactor:ho,uvAnimationMaskTexture:po,uvAnimationScrollXSpeedFactor:fo,uvAnimationScrollYSpeedFactor:Ne,uvAnimationRotationSpeedFactor:mo};return Xt(H({},e),{pbrMetallicRoughness:{baseColorFactor:Xs,baseColorTexture:Qs},normalTexture:qs,emissiveTexture:$s,emissiveFactor:Ks,alphaMode:Ws,alphaCutoff:Gs,doubleSided:js,extensions:{VRMC_materials_mtoon:go}})}_parseV0UnlitProperties(n,e){var t,i,r,s,o;const l=n.shader==="VRM/UnlitTransparentZWrite",a=n.shader==="VRM/UnlitTransparent"||l,u=this._v0ParseRenderQueue(n),h=n.shader==="VRM/UnlitCutout",d=a?"BLEND":h?"MASK":"OPAQUE",p=h?(i=(t=n.floatProperties)==null?void 0:t._Cutoff)!=null?i:.5:void 0,f=this._portTextureTransform(n),g=((s=(r=n.vectorProperties)==null?void 0:r._Color)!=null?s:[1,1,1,1]).map(re),_=(o=n.textureProperties)==null?void 0:o._MainTex,v=_!=null?{index:_,extensions:H({},f)}:void 0,y={specVersion:"1.0",transparentWithZWrite:l,renderQueueOffsetNumber:u,shadeColorFactor:g,shadeMultiplyTexture:v};return Xt(H({},e),{pbrMetallicRoughness:{baseColorFactor:g,baseColorTexture:v},alphaMode:d,alphaCutoff:p,extensions:{VRMC_materials_mtoon:y}})}_portTextureTransform(n){var e,t,i,r,s;const o=(e=n.vectorProperties)==null?void 0:e._MainTex;if(o==null)return{};const l=[(t=o?.[0])!=null?t:0,(i=o?.[1])!=null?i:0],a=[(r=o?.[2])!=null?r:1,(s=o?.[3])!=null?s:1];return l[1]=1-a[1]-l[1],{KHR_texture_transform:{offset:l,scale:a}}}_v0ParseRenderQueue(n){var e,t;const i=n.shader==="VRM/UnlitTransparentZWrite",r=((e=n.keywordMap)==null?void 0:e._ALPHABLEND_ON)!=null||n.shader==="VRM/UnlitTransparent"||i,s=((t=n.floatProperties)==null?void 0:t._ZWrite)===1||i;let o=0;if(r){const l=n.renderQueue;l!=null&&(s?o=this._renderQueueMapTransparentZWrite.get(l):o=this._renderQueueMapTransparent.get(l))}return o}_populateRenderQueueMap(n){const e=new Set,t=new Set;n.forEach(i=>{var r,s;const o=i.shader==="VRM/UnlitTransparentZWrite",l=((r=i.keywordMap)==null?void 0:r._ALPHABLEND_ON)!=null||i.shader==="VRM/UnlitTransparent"||o,a=((s=i.floatProperties)==null?void 0:s._ZWrite)===1||o;if(l){const u=i.renderQueue;u!=null&&(a?t.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.`),t.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${t.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)=>{const s=Math.min(Math.max(r-e.size+1,-9),0);this._renderQueueMapTransparent.set(i,s)}),Array.from(t).sort().forEach((i,r)=>{const s=Math.min(Math.max(r,0),9);this._renderQueueMapTransparentZWrite.set(i,s)})}},Qt=(n,e,t)=>new Promise((i,r)=>{var s=a=>{try{l(t.next(a))}catch(u){r(u)}},o=a=>{try{l(t.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,o);l((t=t.apply(n,e)).next())}),X=new c.Vector3,ze=class extends c.Group{constructor(n){super(),this._attrPosition=new c.BufferAttribute(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(c.DynamicDrawUsage);const e=new c.BufferGeometry;e.setAttribute("position",this._attrPosition);const t=new c.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new c.Line(e,t),this.add(this._line),this.constraint=n}updateMatrixWorld(n){X.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,X.x,X.y,X.z),this.constraint.source&&X.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,X.x,X.y,X.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(n)}};function Yt(n,e){return e.set(n.elements[12],n.elements[13],n.elements[14])}var or=new c.Vector3,ar=new c.Vector3;function lr(n,e){return n.decompose(or,e,ar),e}function Se(n){return n.invert?n.invert():n.inverse(),n}var We=class{constructor(n,e){this.destination=n,this.source=e,this.weight=1}},ur=new c.Vector3,cr=new c.Vector3,hr=new c.Vector3,dr=new c.Quaternion,pr=new c.Quaternion,fr=new c.Quaternion,mr=class extends We{get aimAxis(){return this._aimAxis}set aimAxis(n){this._aimAxis=n,this._v3AimAxis.set(n==="PositiveX"?1:n==="NegativeX"?-1:0,n==="PositiveY"?1:n==="NegativeY"?-1:0,n==="PositiveZ"?1:n==="NegativeZ"?-1:0)}get dependencies(){const n=new Set([this.source]);return this.destination.parent&&n.add(this.destination.parent),n}constructor(n,e){super(n,e),this._aimAxis="PositiveX",this._v3AimAxis=new c.Vector3(1,0,0),this._dstRestQuat=new c.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);const n=dr.identity(),e=pr.identity();this.destination.parent&&(lr(this.destination.parent.matrixWorld,n),Se(e.copy(n)));const t=ur.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(n),i=Yt(this.source.matrixWorld,cr).sub(Yt(this.destination.matrixWorld,hr)).normalize(),r=fr.setFromUnitVectors(t,i).premultiply(e).multiply(n).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(r,this.weight)}};function gr(n,e){const t=[n];let i=n.parent;for(;i!==null;)t.unshift(i),i=i.parent;t.forEach(r=>{e(r)})}var _r=class{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(n){this._constraints.add(n);let e=this._objectConstraintsMap.get(n.destination);e==null&&(e=new Set,this._objectConstraintsMap.set(n.destination,e)),e.add(n)}deleteConstraint(n){this._constraints.delete(n),this._objectConstraintsMap.get(n.destination).delete(n)}setInitState(){const n=new Set,e=new Set;for(const t of this._constraints)this._processConstraint(t,n,e,i=>i.setInitState())}update(){const n=new Set,e=new Set;for(const t of this._constraints)this._processConstraint(t,n,e,i=>i.update())}_processConstraint(n,e,t,i){if(t.has(n))return;if(e.has(n))throw new Error("VRMNodeConstraintManager: Circular dependency detected while updating constraints");e.add(n);const r=n.dependencies;for(const s of r)gr(s,o=>{const l=this._objectConstraintsMap.get(o);if(l)for(const a of l)this._processConstraint(a,e,t,i)});i(n),t.add(n)}},vr=new c.Quaternion,Mr=new c.Quaternion,xr=class extends We{get dependencies(){return new Set([this.source])}constructor(n,e){super(n,e),this._dstRestQuat=new c.Quaternion,this._invSrcRestQuat=new c.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Se(this._invSrcRestQuat.copy(this.source.quaternion))}update(){const n=vr.copy(this._invSrcRestQuat).multiply(this.source.quaternion),e=Mr.copy(this._dstRestQuat).multiply(n);this.destination.quaternion.copy(this._dstRestQuat).slerp(e,this.weight)}},yr=new c.Vector3,Ar=new c.Quaternion,Tr=new c.Quaternion,Rr=class extends We{get rollAxis(){return this._rollAxis}set rollAxis(n){this._rollAxis=n,this._v3RollAxis.set(n==="X"?1:0,n==="Y"?1:0,n==="Z"?1:0)}get dependencies(){return new Set([this.source])}constructor(n,e){super(n,e),this._rollAxis="X",this._v3RollAxis=new c.Vector3(1,0,0),this._dstRestQuat=new c.Quaternion,this._invDstRestQuat=new c.Quaternion,this._invSrcRestQuatMulDstRestQuat=new c.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Se(this._invDstRestQuat.copy(this._dstRestQuat)),Se(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){const n=Ar.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),e=yr.copy(this._v3RollAxis).applyQuaternion(n),i=Tr.setFromUnitVectors(e,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(n);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}},Sr=new Set(["1.0","1.0-beta"]),qt=class Me{get name(){return Me.EXTENSION_NAME}constructor(e,t){this.parser=e,this.helperRoot=t?.helperRoot}afterRoot(e){return Qt(this,null,function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)})}_import(e){return Qt(this,null,function*(){var t;const i=this.parser.json;if(!(((t=i.extensionsUsed)==null?void 0:t.indexOf(Me.EXTENSION_NAME))!==-1))return null;const s=new _r,o=yield this.parser.getDependencies("node");return o.forEach((l,a)=>{var u;const h=i.nodes[a],d=(u=h?.extensions)==null?void 0:u[Me.EXTENSION_NAME];if(d==null)return;const p=d.specVersion;if(!Sr.has(p)){console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${Me.EXTENSION_NAME} specVersion "${p}"`);return}const f=d.constraint;if(f.roll!=null){const g=this._importRollConstraint(l,o,f.roll);s.addConstraint(g)}else if(f.aim!=null){const g=this._importAimConstraint(l,o,f.aim);s.addConstraint(g)}else if(f.rotation!=null){const g=this._importRotationConstraint(l,o,f.rotation);s.addConstraint(g)}}),e.scene.updateMatrixWorld(),s.setInitState(),s})}_importRollConstraint(e,t,i){const{source:r,rollAxis:s,weight:o}=i,l=t[r],a=new Rr(e,l);if(s!=null&&(a.rollAxis=s),o!=null&&(a.weight=o),this.helperRoot){const u=new ze(a);this.helperRoot.add(u)}return a}_importAimConstraint(e,t,i){const{source:r,aimAxis:s,weight:o}=i,l=t[r],a=new mr(e,l);if(s!=null&&(a.aimAxis=s),o!=null&&(a.weight=o),this.helperRoot){const u=new ze(a);this.helperRoot.add(u)}return a}_importRotationConstraint(e,t,i){const{source:r,weight:s}=i,o=t[r],l=new xr(e,o);if(s!=null&&(l.weight=s),this.helperRoot){const a=new ze(l);this.helperRoot.add(a)}return l}};qt.EXTENSION_NAME="VRMC_node_constraint";var wr=qt,we=(n,e,t)=>new Promise((i,r)=>{var s=a=>{try{l(t.next(a))}catch(u){r(u)}},o=a=>{try{l(t.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(s,o);l((t=t.apply(n,e)).next())}),Ge=class{},je=new c.Vector3,J=new c.Vector3,Kt=class extends Ge{get type(){return"capsule"}constructor(n){var e,t,i,r;super(),this.offset=(e=n?.offset)!=null?e:new c.Vector3(0,0,0),this.tail=(t=n?.tail)!=null?t:new c.Vector3(0,0,0),this.radius=(i=n?.radius)!=null?i:0,this.inside=(r=n?.inside)!=null?r:!1}calculateCollision(n,e,t,i){je.setFromMatrixPosition(n),J.subVectors(this.tail,this.offset).applyMatrix4(n),J.sub(je);const r=J.lengthSq();i.copy(e).sub(je);const s=J.dot(i);s<=0||(r<=s||J.multiplyScalar(s/r),i.sub(J));const o=i.length(),l=this.inside?this.radius-t-o:o-t-this.radius;return l<0&&(i.multiplyScalar(1/o),this.inside&&i.negate()),l}},Xe=new c.Vector3,$t=new c.Matrix3,Zt=class extends Ge{get type(){return"plane"}constructor(n){var e,t;super(),this.offset=(e=n?.offset)!=null?e:new c.Vector3(0,0,0),this.normal=(t=n?.normal)!=null?t:new c.Vector3(0,0,1)}calculateCollision(n,e,t,i){i.setFromMatrixPosition(n),i.negate().add(e),$t.getNormalMatrix(n),Xe.copy(this.normal).applyNormalMatrix($t).normalize();const r=i.dot(Xe)-t;return i.copy(Xe),r}},Lr=new c.Vector3,Jt=class extends Ge{get type(){return"sphere"}constructor(n){var e,t,i;super(),this.offset=(e=n?.offset)!=null?e:new c.Vector3(0,0,0),this.radius=(t=n?.radius)!=null?t:0,this.inside=(i=n?.inside)!=null?i:!1}calculateCollision(n,e,t,i){i.subVectors(e,Lr.setFromMatrixPosition(n));const r=i.length(),s=this.inside?this.radius-t-r:r-t-this.radius;return s<0&&(i.multiplyScalar(1/r),this.inside&&i.negate()),s}},z=new c.Vector3,Pr=class extends c.BufferGeometry{constructor(n){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new c.Vector3,this._currentTail=new c.Vector3,this._shape=n,this._attrPos=new c.BufferAttribute(new Float32Array(396),3),this.setAttribute("position",this._attrPos),this._attrIndex=new c.BufferAttribute(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;const e=this._shape.radius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,n=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),n=!0);const t=z.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(t)>1e-10&&(this._currentTail.copy(t),n=!0),n&&this._buildPosition()}_buildPosition(){z.copy(this._currentTail).sub(this._currentOffset);const n=z.length()/this._currentRadius;for(let i=0;i<=16;i++){const r=i/16*Math.PI;this._attrPos.setXYZ(i,-Math.sin(r),-Math.cos(r),0),this._attrPos.setXYZ(17+i,n+Math.sin(r),Math.cos(r),0),this._attrPos.setXYZ(34+i,-Math.sin(r),0,-Math.cos(r)),this._attrPos.setXYZ(51+i,n+Math.sin(r),0,Math.cos(r))}for(let i=0;i<32;i++){const r=i/16*Math.PI;this._attrPos.setXYZ(68+i,0,Math.sin(r),Math.cos(r)),this._attrPos.setXYZ(100+i,n,Math.sin(r),Math.cos(r))}const e=Math.atan2(z.y,Math.sqrt(z.x*z.x+z.z*z.z)),t=-Math.atan2(z.z,z.x);this.rotateZ(e),this.rotateY(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 n=0;n<34;n++){const e=(n+1)%34;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(68+n*2,34+n,34+e)}for(let n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(136+n*2,68+n,68+e),this._attrIndex.setXY(200+n*2,100+n,100+e)}this._attrIndex.needsUpdate=!0}},Er=class extends c.BufferGeometry{constructor(n){super(),this.worldScale=1,this._currentOffset=new c.Vector3,this._currentNormal=new c.Vector3,this._shape=n,this._attrPos=new c.BufferAttribute(new Float32Array(6*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new c.BufferAttribute(new Uint16Array(10),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),n=!0),this._currentNormal.equals(this._shape.normal)||(this._currentNormal.copy(this._shape.normal),n=!0),n&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,-.5,-.5,0),this._attrPos.setXYZ(1,.5,-.5,0),this._attrPos.setXYZ(2,.5,.5,0),this._attrPos.setXYZ(3,-.5,.5,0),this._attrPos.setXYZ(4,0,0,0),this._attrPos.setXYZ(5,0,0,.25),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this.lookAt(this._currentNormal),this._attrPos.needsUpdate=!0}_buildIndex(){this._attrIndex.setXY(0,0,1),this._attrIndex.setXY(2,1,2),this._attrIndex.setXY(4,2,3),this._attrIndex.setXY(6,3,0),this._attrIndex.setXY(8,4,5),this._attrIndex.needsUpdate=!0}},Nr=class extends c.BufferGeometry{constructor(n){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new c.Vector3,this._shape=n,this._attrPos=new c.BufferAttribute(new Float32Array(32*3*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new c.BufferAttribute(new Uint16Array(64*3),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;const e=this._shape.radius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,n=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),n=!0),n&&this._buildPosition()}_buildPosition(){for(let n=0;n<32;n++){const e=n/16*Math.PI;this._attrPos.setXYZ(n,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+n,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+n,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 n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(64+n*2,32+n,32+e),this._attrIndex.setXY(128+n*2,64+n,64+e)}this._attrIndex.needsUpdate=!0}},br=new c.Vector3,Qe=class extends c.Group{constructor(n){if(super(),this.matrixAutoUpdate=!1,this.collider=n,this.collider.shape instanceof Jt)this._geometry=new Nr(this.collider.shape);else if(this.collider.shape instanceof Kt)this._geometry=new Pr(this.collider.shape);else if(this.collider.shape instanceof Zt)this._geometry=new Er(this.collider.shape);else throw new Error("VRMSpringBoneColliderHelper: Unknown collider shape type detected");const e=new c.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new c.LineSegments(this._geometry,e),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(n){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);const e=this.matrix.elements;this._geometry.worldScale=br.set(e[0],e[1],e[2]).length(),this._geometry.update(),super.updateMatrixWorld(n)}},Ir=class extends c.BufferGeometry{constructor(n){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new c.Vector3,this._springBone=n,this._attrPos=new c.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new c.BufferAttribute(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let n=!1;const e=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,n=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),n=!0),n&&this._buildPosition()}_buildPosition(){for(let n=0;n<32;n++){const e=n/16*Math.PI;this._attrPos.setXYZ(n,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+n,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+n,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 n=0;n<32;n++){const e=(n+1)%32;this._attrIndex.setXY(n*2,n,e),this._attrIndex.setXY(64+n*2,32+n,32+e),this._attrIndex.setXY(128+n*2,64+n,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},Cr=new c.Vector3,Or=class extends c.Group{constructor(n){super(),this.matrixAutoUpdate=!1,this.springBone=n,this._geometry=new Ir(this.springBone);const e=new c.LineBasicMaterial({color:16776960,depthTest:!1,depthWrite:!1});this._line=new c.LineSegments(this._geometry,e),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(n){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);const e=this.matrix.elements;this._geometry.worldScale=Cr.set(e[0],e[1],e[2]).length(),this._geometry.update(),super.updateMatrixWorld(n)}},Ye=class extends c.Object3D{constructor(n){super(),this.colliderMatrix=new c.Matrix4,this.shape=n}updateWorldMatrix(n,e){super.updateWorldMatrix(n,e),Ur(this.colliderMatrix,this.matrixWorld,this.shape.offset)}};function Ur(n,e,t){const i=e.elements;n.copy(e),t&&(n.elements[12]=i[0]*t.x+i[4]*t.y+i[8]*t.z+i[12],n.elements[13]=i[1]*t.x+i[5]*t.y+i[9]*t.z+i[13],n.elements[14]=i[2]*t.x+i[6]*t.y+i[10]*t.z+i[14])}var Br=new c.Matrix4;function Vr(n){return n.invert?n.invert():n.getInverse(Br.copy(n)),n}var Dr=class{constructor(n){this._inverseCache=new c.Matrix4,this._shouldUpdateInverse=!0,this.matrix=n;const e={set:(t,i,r)=>(this._shouldUpdateInverse=!0,t[i]=r,!0)};this._originalElements=n.elements,n.elements=new Proxy(n.elements,e)}get inverse(){return this._shouldUpdateInverse&&(Vr(this._inverseCache.copy(this.matrix)),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}},qe=new c.Matrix4,se=new c.Vector3,de=new c.Vector3,pe=new c.Vector3,fe=new c.Vector3,Fr=new c.Matrix4,kr=class{constructor(n,e,t={},i=[]){this._currentTail=new c.Vector3,this._prevTail=new c.Vector3,this._boneAxis=new c.Vector3,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new c.Matrix4,this._initialLocalRotation=new c.Quaternion,this._initialLocalChildPosition=new c.Vector3;var r,s,o,l,a,u;this.bone=n,this.bone.matrixAutoUpdate=!1,this.child=e,this.settings={hitRadius:(r=t.hitRadius)!=null?r:0,stiffness:(s=t.stiffness)!=null?s:1,gravityPower:(o=t.gravityPower)!=null?o:0,gravityDir:(a=(l=t.gravityDir)==null?void 0:l.clone())!=null?a:new c.Vector3(0,-1,0),dragForce:(u=t.dragForce)!=null?u:.4},this.colliderGroups=i}get dependencies(){const n=new Set,e=this.bone.parent;e&&n.add(e);for(let t=0;t<this.colliderGroups.length;t++)for(let i=0;i<this.colliderGroups[t].colliders.length;i++)n.add(this.colliderGroups[t].colliders[i]);return n}get center(){return this._center}set center(n){var e;(e=this._center)!=null&&e.userData.inverseCacheProxy&&(this._center.userData.inverseCacheProxy.revert(),delete this._center.userData.inverseCacheProxy),this._center=n,this._center&&(this._center.userData.inverseCacheProxy||(this._center.userData.inverseCacheProxy=new Dr(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:qe}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 n=this._getMatrixWorldToCenter();this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(n),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 n=this._getMatrixWorldToCenter();this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(n),this._prevTail.copy(this._currentTail)}update(n){if(n<=0)return;this._calcWorldSpaceBoneLength();const e=de.copy(this._boneAxis).transformDirection(this._initialLocalMatrix).transformDirection(this._parentMatrixWorld);fe.copy(this._currentTail).add(se.subVectors(this._currentTail,this._prevTail).multiplyScalar(1-this.settings.dragForce)).applyMatrix4(this._getMatrixCenterToWorld()).addScaledVector(e,this.settings.stiffness*n).addScaledVector(this.settings.gravityDir,this.settings.gravityPower*n),pe.setFromMatrixPosition(this.bone.matrixWorld),fe.sub(pe).normalize().multiplyScalar(this._worldSpaceBoneLength).add(pe),this._collision(fe),this._prevTail.copy(this._currentTail),this._currentTail.copy(fe).applyMatrix4(this._getMatrixWorldToCenter());const t=Fr.multiplyMatrices(this._parentMatrixWorld,this._initialLocalMatrix).invert();this.bone.quaternion.setFromUnitVectors(this._boneAxis,se.copy(fe).applyMatrix4(t).normalize()).premultiply(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(n){for(let e=0;e<this.colliderGroups.length;e++)for(let t=0;t<this.colliderGroups[e].colliders.length;t++){const i=this.colliderGroups[e].colliders[t],r=i.shape.calculateCollision(i.colliderMatrix,n,this.settings.hitRadius,se);if(r<0){n.addScaledVector(se,-r),n.sub(pe);const s=n.length();n.multiplyScalar(this._worldSpaceBoneLength/s).add(pe)}}}_calcWorldSpaceBoneLength(){se.setFromMatrixPosition(this.bone.matrixWorld),this.child?de.setFromMatrixPosition(this.child.matrixWorld):(de.copy(this._initialLocalChildPosition),de.applyMatrix4(this.bone.matrixWorld)),this._worldSpaceBoneLength=se.sub(de).length()}_getMatrixCenterToWorld(){return this._center?this._center.matrixWorld:qe}_getMatrixWorldToCenter(){return this._center?this._center.userData.inverseCacheProxy.inverse:qe}};function Hr(n,e){const t=[];let i=n;for(;i!==null;)t.unshift(i),i=i.parent;t.forEach(r=>{e(r)})}function Ke(n,e){n.children.forEach(t=>{e(t)||Ke(t,e)})}function zr(n){var e;const t=new Map;for(const i of n){let r=i;do{const s=((e=t.get(r))!=null?e:0)+1;if(s===n.size)return r;t.set(r,s),r=r.parent}while(r!==null)}return null}var en=class{constructor(){this._joints=new Set,this._sortedJoints=[],this._hasWarnedCircularDependency=!1,this._ancestors=[],this._objectSpringBonesMap=new Map,this._isSortedJointsDirty=!1,this._relevantChildrenUpdated=this._relevantChildrenUpdated.bind(this)}get joints(){return this._joints}get springBones(){return console.warn("VRMSpringBoneManager: springBones is deprecated. use joints instead."),this._joints}get colliderGroups(){const n=new Set;return this._joints.forEach(e=>{e.colliderGroups.forEach(t=>{n.add(t)})}),Array.from(n)}get colliders(){const n=new Set;return this.colliderGroups.forEach(e=>{e.colliders.forEach(t=>{n.add(t)})}),Array.from(n)}addJoint(n){this._joints.add(n);let e=this._objectSpringBonesMap.get(n.bone);e==null&&(e=new Set,this._objectSpringBonesMap.set(n.bone,e)),e.add(n),this._isSortedJointsDirty=!0}addSpringBone(n){console.warn("VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead."),this.addJoint(n)}deleteJoint(n){this._joints.delete(n),this._objectSpringBonesMap.get(n.bone).delete(n),this._isSortedJointsDirty=!0}deleteSpringBone(n){console.warn("VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead."),this.deleteJoint(n)}setInitState(){this._sortJoints();for(let n=0;n<this._sortedJoints.length;n++){const e=this._sortedJoints[n];e.bone.updateMatrix(),e.bone.updateWorldMatrix(!1,!1),e.setInitState()}}reset(){this._sortJoints();for(let n=0;n<this._sortedJoints.length;n++){const e=this._sortedJoints[n];e.bone.updateMatrix(),e.bone.updateWorldMatrix(!1,!1),e.reset()}}update(n){this._sortJoints();for(let e=0;e<this._ancestors.length;e++)this._ancestors[e].updateWorldMatrix(e===0,!1);for(let e=0;e<this._sortedJoints.length;e++){const t=this._sortedJoints[e];t.bone.updateMatrix(),t.bone.updateWorldMatrix(!1,!1),t.update(n),Ke(t.bone,this._relevantChildrenUpdated)}}_sortJoints(){if(!this._isSortedJointsDirty)return;const n=[],e=new Set,t=new Set,i=new Set;for(const s of this._joints)this._insertJointSort(s,e,t,n,i);this._sortedJoints=n;const r=zr(i);this._ancestors=[],r&&(this._ancestors.push(r),Ke(r,s=>{var o,l;return((l=(o=this._objectSpringBonesMap.get(s))==null?void 0:o.size)!=null?l:0)>0?!0:(this._ancestors.push(s),!1)})),this._isSortedJointsDirty=!1}_insertJointSort(n,e,t,i,r){if(t.has(n))return;if(e.has(n)){this._hasWarnedCircularDependency||(console.warn("VRMSpringBoneManager: Circular dependency detected"),this._hasWarnedCircularDependency=!0);return}e.add(n);const s=n.dependencies;for(const o of s){let l=!1,a=null;Hr(o,u=>{const h=this._objectSpringBonesMap.get(u);if(h)for(const d of h)l=!0,this._insertJointSort(d,e,t,i,r);else l||(a=u)}),a&&r.add(a)}i.push(n),t.add(n)}_relevantChildrenUpdated(n){var e,t;return((t=(e=this._objectSpringBonesMap.get(n))==null?void 0:e.size)!=null?t:0)>0?!0:(n.updateWorldMatrix(!1,!1),!1)}},tn="VRMC_springBone_extended_collider",Wr=new Set(["1.0","1.0-beta"]),Gr=new Set(["1.0"]),nn=class ue{get name(){return ue.EXTENSION_NAME}constructor(e,t){var i;this.parser=e,this.jointHelperRoot=t?.jointHelperRoot,this.colliderHelperRoot=t?.colliderHelperRoot,this.useExtendedColliders=(i=t?.useExtendedColliders)!=null?i:!0}afterRoot(e){return we(this,null,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return we(this,null,function*(){const t=yield this._v1Import(e);if(t!=null)return t;const i=yield this._v0Import(e);return i??null})}_v1Import(e){return we(this,null,function*(){var t,i,r,s,o;const l=e.parser.json;if(!(((t=l.extensionsUsed)==null?void 0:t.indexOf(ue.EXTENSION_NAME))!==-1))return null;const u=new en,h=yield e.parser.getDependencies("node"),d=(i=l.extensions)==null?void 0:i[ue.EXTENSION_NAME];if(!d)return null;const p=d.specVersion;if(!Wr.has(p))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${ue.EXTENSION_NAME} specVersion "${p}"`),null;const f=(r=d.colliders)==null?void 0:r.map((_,v)=>{var y,A,R,x,S,T,w,E,I,b,C,U,Y,ge,_e;const j=h[_.node];if(j==null)return console.warn(`VRMSpringBoneLoaderPlugin: The collider #${v} attempted to reference a node #${_.node} but not found. Skipping the collider`),null;const W=_.shape,ae=(y=_.extensions)==null?void 0:y[tn];if(this.useExtendedColliders&&ae!=null){const ve=ae.specVersion;if(!Gr.has(ve))console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${tn} specVersion "${ve}". Fallbacking to the ${ue.EXTENSION_NAME} definition`);else{const B=ae.shape;if(B.sphere)return this._importSphereCollider(j,{offset:new c.Vector3().fromArray((A=B.sphere.offset)!=null?A:[0,0,0]),radius:(R=B.sphere.radius)!=null?R:0,inside:(x=B.sphere.inside)!=null?x:!1});if(B.capsule)return this._importCapsuleCollider(j,{offset:new c.Vector3().fromArray((S=B.capsule.offset)!=null?S:[0,0,0]),radius:(T=B.capsule.radius)!=null?T:0,tail:new c.Vector3().fromArray((w=B.capsule.tail)!=null?w:[0,0,0]),inside:(E=B.capsule.inside)!=null?E:!1});if(B.plane)return this._importPlaneCollider(j,{offset:new c.Vector3().fromArray((I=B.plane.offset)!=null?I:[0,0,0]),normal:new c.Vector3().fromArray((b=B.plane.normal)!=null?b:[0,0,1])})}}if(W.sphere)return this._importSphereCollider(j,{offset:new c.Vector3().fromArray((C=W.sphere.offset)!=null?C:[0,0,0]),radius:(U=W.sphere.radius)!=null?U:0,inside:!1});if(W.capsule)return this._importCapsuleCollider(j,{offset:new c.Vector3().fromArray((Y=W.capsule.offset)!=null?Y:[0,0,0]),radius:(ge=W.capsule.radius)!=null?ge:0,tail:new c.Vector3().fromArray((_e=W.capsule.tail)!=null?_e:[0,0,0]),inside:!1});console.warn(`VRMSpringBoneLoaderPlugin: The collider #${v} has no valid shape. Skipping the collider`)}),g=(s=d.colliderGroups)==null?void 0:s.map((_,v)=>{var y;return{colliders:((y=_.colliders)!=null?y:[]).map(R=>{const x=f?.[R];return x??(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${v} attempted to reference a collider #${R} but not found. Skipping the collider`),null)}).filter(R=>R!=null),name:_.name}});return(o=d.springs)==null||o.forEach((_,v)=>{var y;const A=_.joints,R=(y=_.colliderGroups)==null?void 0:y.map(T=>{const w=g?.[T];return w??(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${v} attempted to reference a collider group #${T} but not found. Skipping the collider group`),null)}).filter(T=>T!=null),x=_.center!=null?h[_.center]:void 0;let S;A.forEach(T=>{if(S){const w=S.node,E=h[w],I=T.node,b=h[I],C={hitRadius:S.hitRadius,dragForce:S.dragForce,gravityPower:S.gravityPower,stiffness:S.stiffness,gravityDir:S.gravityDir!=null?new c.Vector3().fromArray(S.gravityDir):void 0},U=this._importJoint(E,b,C,R);x&&(U.center=x),u.addJoint(U)}S=T})}),u.setInitState(),u})}_v0Import(e){return we(this,null,function*(){var t,i,r;const s=e.parser.json;if(!(((t=s.extensionsUsed)==null?void 0:t.indexOf("VRM"))!==-1))return null;const l=(i=s.extensions)==null?void 0:i.VRM,a=l?.secondaryAnimation;if(!a)return null;const u=a?.boneGroups;if(!u)return null;const h=new en,d=yield e.parser.getDependencies("node"),p=(r=a.colliderGroups)==null?void 0:r.map((f,g)=>{var _;const v=d[f.node];return v==null?(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${g} attempted to reference a node #${f.node} but not found. Skipping the collider group`),null):{colliders:((_=f.colliders)!=null?_:[]).map((A,R)=>{var x,S,T;const w=new c.Vector3(0,0,0);return A.offset&&w.set((x=A.offset.x)!=null?x:0,(S=A.offset.y)!=null?S:0,A.offset.z?-A.offset.z:0),this._importSphereCollider(v,{offset:w,radius:(T=A.radius)!=null?T:0,inside:!1})})}});return u?.forEach((f,g)=>{const _=f.bones;_&&_.forEach(v=>{var y,A,R,x;const S=d[v];if(S==null){console.warn(`VRMSpringBoneLoaderPlugin: The spring bone group #${g} attempted to reference a node #${v} but not found. Skipping the node`);return}const T=new c.Vector3;f.gravityDir?T.set((y=f.gravityDir.x)!=null?y:0,(A=f.gravityDir.y)!=null?A:0,(R=f.gravityDir.z)!=null?R:0):T.set(0,-1,0);const w=f.center!=null?d[f.center]:void 0,E={hitRadius:f.hitRadius,dragForce:f.dragForce,gravityPower:f.gravityPower,stiffness:f.stiffiness,gravityDir:T},I=(x=f.colliderGroups)==null?void 0:x.map(b=>{const C=p?.[b];return C??(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${g} attempted to reference a collider group #${b} but not found. Skipping the collider group`),null)}).filter(b=>b!=null);S.traverse(b=>{var C;const U=(C=b.children[0])!=null?C:null,Y=this._importJoint(b,U,E,I);w&&(Y.center=w),h.addJoint(Y)})})}),e.scene.updateMatrixWorld(),h.setInitState(),h})}_importJoint(e,t,i,r){const s=new kr(e,t,i,r);if(this.jointHelperRoot){const o=new Or(s);this.jointHelperRoot.add(o),o.renderOrder=this.jointHelperRoot.renderOrder}return s}_importSphereCollider(e,t){const i=new Jt(t),r=new Ye(i);if(e.add(r),this.colliderHelperRoot){const s=new Qe(r);this.colliderHelperRoot.add(s),s.renderOrder=this.colliderHelperRoot.renderOrder}return r}_importCapsuleCollider(e,t){const i=new Kt(t),r=new Ye(i);if(e.add(r),this.colliderHelperRoot){const s=new Qe(r);this.colliderHelperRoot.add(s),s.renderOrder=this.colliderHelperRoot.renderOrder}return r}_importPlaneCollider(e,t){const i=new Zt(t),r=new Ye(i);if(e.add(r),this.colliderHelperRoot){const s=new Qe(r);this.colliderHelperRoot.add(s),s.renderOrder=this.colliderHelperRoot.renderOrder}return r}};nn.EXTENSION_NAME="VRMC_springBone";var jr=nn,Xr=class{get name(){return"VRMLoaderPlugin"}constructor(n,e){var t,i,r,s,o,l,a,u,h,d;this.parser=n;const p=e?.helperRoot,f=e?.autoUpdateHumanBones;this.expressionPlugin=(t=e?.expressionPlugin)!=null?t:new li(n),this.firstPersonPlugin=(i=e?.firstPersonPlugin)!=null?i:new ci(n),this.humanoidPlugin=(r=e?.humanoidPlugin)!=null?r:new _i(n,{helperRoot:p,autoUpdateHumanBones:f}),this.lookAtPlugin=(s=e?.lookAtPlugin)!=null?s:new Ii(n,{helperRoot:p}),this.metaPlugin=(o=e?.metaPlugin)!=null?o:new Ui(n),this.mtoonMaterialPlugin=(l=e?.mtoonMaterialPlugin)!=null?l:new Ki(n),this.materialsHDREmissiveMultiplierPlugin=(a=e?.materialsHDREmissiveMultiplierPlugin)!=null?a:new Zi(n),this.materialsV0CompatPlugin=(u=e?.materialsV0CompatPlugin)!=null?u:new sr(n),this.springBonePlugin=(h=e?.springBonePlugin)!=null?h:new jr(n,{colliderHelperRoot:p,jointHelperRoot:p}),this.nodeConstraintPlugin=(d=e?.nodeConstraintPlugin)!=null?d:new wr(n,{helperRoot:p})}beforeRoot(){return xe(this,null,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(n){return xe(this,null,function*(){return yield this.mtoonMaterialPlugin.loadMesh(n)})}getMaterialType(n){const e=this.mtoonMaterialPlugin.getMaterialType(n);return e??null}extendMaterialParams(n,e){return xe(this,null,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(n,e),yield this.mtoonMaterialPlugin.extendMaterialParams(n,e)})}afterRoot(n){return xe(this,null,function*(){yield this.metaPlugin.afterRoot(n),yield this.humanoidPlugin.afterRoot(n),yield this.expressionPlugin.afterRoot(n),yield this.lookAtPlugin.afterRoot(n),yield this.firstPersonPlugin.afterRoot(n),yield this.springBonePlugin.afterRoot(n),yield this.nodeConstraintPlugin.afterRoot(n),yield this.mtoonMaterialPlugin.afterRoot(n);const e=n.userData.vrmMeta,t=n.userData.vrmHumanoid;if(e&&t){const i=new Vi({scene:n.scene,expressionManager:n.userData.vrmExpressionManager,firstPerson:n.userData.vrmFirstPerson,humanoid:t,lookAt:n.userData.vrmLookAt,meta:e,materials:n.userData.vrmMToonMaterials,springBoneManager:n.userData.vrmSpringBoneManager,nodeConstraintManager:n.userData.vrmNodeConstraintManager});n.userData.vrm=i}})}};/*!
|
|
950
|
+
* @pixiv/three-vrm-core v3.5.4
|
|
951
|
+
* The implementation of core features of VRM, for @pixiv/three-vrm
|
|
952
|
+
*
|
|
953
|
+
* Copyright (c) 2019-2026 pixiv Inc.
|
|
954
|
+
* @pixiv/three-vrm-core is distributed under MIT License
|
|
955
|
+
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
956
|
+
*//*!
|
|
957
|
+
* @pixiv/three-vrm-materials-mtoon v3.5.4
|
|
958
|
+
* MToon (toon material) module for @pixiv/three-vrm
|
|
959
|
+
*
|
|
960
|
+
* Copyright (c) 2019-2026 pixiv Inc.
|
|
961
|
+
* @pixiv/three-vrm-materials-mtoon is distributed under MIT License
|
|
962
|
+
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
963
|
+
*//*!
|
|
964
|
+
* @pixiv/three-vrm-materials-hdr-emissive-multiplier v3.5.4
|
|
965
|
+
* Support VRMC_hdr_emissiveMultiplier for @pixiv/three-vrm
|
|
966
|
+
*
|
|
967
|
+
* Copyright (c) 2019-2026 pixiv Inc.
|
|
968
|
+
* @pixiv/three-vrm-materials-hdr-emissive-multiplier is distributed under MIT License
|
|
969
|
+
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
970
|
+
*//*!
|
|
971
|
+
* @pixiv/three-vrm-materials-v0compat v3.5.4
|
|
972
|
+
* VRM0.0 materials compatibility layer plugin for @pixiv/three-vrm
|
|
973
|
+
*
|
|
974
|
+
* Copyright (c) 2019-2026 pixiv Inc.
|
|
975
|
+
* @pixiv/three-vrm-materials-v0compat is distributed under MIT License
|
|
976
|
+
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
977
|
+
*//*!
|
|
978
|
+
* @pixiv/three-vrm-node-constraint v3.5.4
|
|
979
|
+
* Node constraint module for @pixiv/three-vrm
|
|
980
|
+
*
|
|
981
|
+
* Copyright (c) 2019-2026 pixiv Inc.
|
|
982
|
+
* @pixiv/three-vrm-node-constraint is distributed under MIT License
|
|
983
|
+
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
984
|
+
*//*!
|
|
985
|
+
* @pixiv/three-vrm-springbone v3.5.4
|
|
986
|
+
* Spring bone module for @pixiv/three-vrm
|
|
987
|
+
*
|
|
988
|
+
* Copyright (c) 2019-2026 pixiv Inc.
|
|
989
|
+
* @pixiv/three-vrm-springbone is distributed under MIT License
|
|
990
|
+
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
991
|
+
*/function L(n,e,t){return n+(e-n)*t}function V(n){return n*n*(3-2*n)}function rn(n){return Math.max(0,Math.min(1,n))}const O=Math.PI/3.2,$e=-.1,Qr=.1,Le=-.15,Yr={wave:{duration:3,fn(n,e){const t=e.humanoid,i=t.getNormalizedBoneNode(M.RightShoulder),r=t.getNormalizedBoneNode(M.RightUpperArm),s=t.getNormalizedBoneNode(M.RightLowerArm),o=t.getNormalizedBoneNode(M.RightHand),l=t.getNormalizedBoneNode(M.LeftUpperArm),a=V(rn(n/.25)),u=n>.8?V((n-.8)/.2):0,h=a*(1-u);i&&(i.rotation.z=L(0,-.2,h),i.rotation.x=0,i.rotation.y=0),r&&(r.rotation.z=L(O,0,h),r.rotation.x=0,r.rotation.y=0),s&&(s.rotation.order="XYZ",s.rotation.z=L($e,-Math.PI/2,h),s.rotation.x=0,s.rotation.y=0);const d=n>=.25&&n<=.8?Math.sin((n-.25)/.55*Math.PI*4):0;o&&(o.rotation.x=L(Le,-Math.PI/2,h),o.rotation.y=d*.4*h,o.rotation.z=0),l&&(l.rotation.z=-O)}},nod:{duration:1.8,fn(n,e){const t=e.humanoid,i=t.getNormalizedBoneNode(M.Neck),r=t.getNormalizedBoneNode(M.RightUpperArm),s=t.getNormalizedBoneNode(M.LeftUpperArm),o=n>.85?(1-n)/.15:1;i&&(i.rotation.x=.32*Math.max(0,Math.sin(n*Math.PI*2))*o),r&&(r.rotation.z=O),s&&(s.rotation.z=-O)}},shakeHead:{duration:1.8,fn(n,e){const t=e.humanoid,i=t.getNormalizedBoneNode(M.Neck),r=t.getNormalizedBoneNode(M.RightUpperArm),s=t.getNormalizedBoneNode(M.LeftUpperArm),o=n>.85?(1-n)/.15:1;i&&(i.rotation.y=.35*Math.sin(n*Math.PI*2.5)*o),r&&(r.rotation.z=O),s&&(s.rotation.z=-O)}},clap:{duration:2.2,fn(n,e){const t=e.humanoid,i=t.getNormalizedBoneNode(M.RightUpperArm),r=t.getNormalizedBoneNode(M.LeftUpperArm),s=t.getNormalizedBoneNode(M.RightLowerArm),o=t.getNormalizedBoneNode(M.LeftLowerArm),l=V(rn(n/.2)),a=n>.8?V((n-.8)/.2):0,u=l*(1-a),h=n>=.2&&n<=.8?Math.max(0,Math.sin((n-.2)/.6*Math.PI*10)):0,d=Math.PI/2-.08,p=Math.PI/2+.05,f=L(d,p,h);i&&(i.rotation.z=L(O,Math.PI/3,u),i.rotation.y=L(0,f,u),i.rotation.x=0),r&&(r.rotation.z=L(-O,-Math.PI/3,u),r.rotation.y=L(0,-f,u),r.rotation.x=0);const g=t.getNormalizedBoneNode(M.RightHand),_=t.getNormalizedBoneNode(M.LeftHand);s&&(s.rotation.z=L($e,-Math.PI/2.5,u),s.rotation.y=L(0,Math.PI/2,u),s.rotation.x=0),o&&(o.rotation.z=L(Qr,Math.PI/2.5,u),o.rotation.y=L(0,-Math.PI/2,u),o.rotation.x=0),g&&(g.rotation.z=L(0,-Math.PI/11.25,u),g.rotation.y=0,g.rotation.x=L(Le,0,u)),_&&(_.rotation.z=L(0,Math.PI/11.25,u),_.rotation.y=0,_.rotation.x=L(Le,0,u))}},jump:{duration:1.5,fn(n,e){const t=e.humanoid,i=t.getNormalizedBoneNode(M.Hips),r=t.getNormalizedBoneNode(M.Spine),s=t.getNormalizedBoneNode(M.Chest),o=t.getNormalizedBoneNode(M.RightUpperArm),l=t.getNormalizedBoneNode(M.LeftUpperArm),a=t.getNormalizedBoneNode(M.RightUpperLeg),u=t.getNormalizedBoneNode(M.LeftUpperLeg),h=t.getNormalizedBoneNode(M.RightLowerLeg),d=t.getNormalizedBoneNode(M.LeftLowerLeg),p=t.getNormalizedBoneNode(M.RightFoot),f=t.getNormalizedBoneNode(M.LeftFoot);let g=0,_=0,v=0,y=0,A=0;if(n<.22){const x=V(n/.22);g=-.12*x,_=x,v=-x*.85,A=x*.06}else if(n<.55){const x=V((n-.22)/.33);g=L(-.12,.22,x),_=L(1,0,x),v=L(-.85,.6,x),y=x*.5,A=L(.06,-.05,x)}else if(n<.72){const x=V((n-.55)/.17);g=L(.22,-.07,x),_=x*.75,v=L(.6,-.6,x),y=L(.5,0,x),A=L(-.05,.07,x)}else{const x=V((n-.72)/.28);g=L(-.07,0,x),_=L(.75,0,x),v=L(-.6,0,x),A=L(.07,0,x)}const R=e.scene.userData.hipsRestY??0;i&&(i.position.y=R+g),a&&(a.rotation.x=-_*.35,a.rotation.z=0,a.rotation.y=0),u&&(u.rotation.x=-_*.35,u.rotation.z=0,u.rotation.y=0),h&&(h.rotation.x=_*1.2,h.rotation.z=0,h.rotation.y=0),d&&(d.rotation.x=_*1.2,d.rotation.z=0,d.rotation.y=0),p&&(p.rotation.x=v,p.rotation.z=0,p.rotation.y=0),f&&(f.rotation.x=v,f.rotation.z=0,f.rotation.y=0),r&&(r.rotation.x=A),s&&(s.rotation.x=A*.4),o&&(o.rotation.z=O-y),l&&(l.rotation.z=-O+y)}},no:{duration:1.8,fn(n,e){const t=e.humanoid,i=t.getNormalizedBoneNode(M.Neck),r=t.getNormalizedBoneNode(M.Head),s=t.getNormalizedBoneNode(M.RightUpperArm),o=t.getNormalizedBoneNode(M.LeftUpperArm),l=n<.12?V(n/.12):n>.85?V((1-n)/.15):1,a=Math.sin(n*Math.PI*6)*l;i&&(i.rotation.y=a*.38),r&&(r.rotation.y=a*.12),s&&(s.rotation.z=O),o&&(o.rotation.z=-O)}},yes:{duration:2,fn(n,e){const t=e.humanoid,i=t.getNormalizedBoneNode(M.Neck),r=t.getNormalizedBoneNode(M.Head),s=t.getNormalizedBoneNode(M.RightUpperArm),o=t.getNormalizedBoneNode(M.LeftUpperArm),l=n<.12?V(n/.12):n>.85?V((1-n)/.15):1,a=Math.max(0,Math.sin(n*Math.PI*6))*l;i&&(i.rotation.x=a*.3),r&&(r.rotation.x=a*.12),s&&(s.rotation.z=O),o&&(o.rotation.z=-O)}},thumbsUp:{duration:2.5,fn(n,e){const t=e.humanoid,i=t.getNormalizedBoneNode(M.RightUpperArm),r=t.getNormalizedBoneNode(M.RightLowerArm),s=t.getNormalizedBoneNode(M.RightHand),o=t.getNormalizedBoneNode(M.LeftUpperArm),l=n<.2?V(n/.2):n>.8?V(1-(n-.8)/.2):1;i&&(i.rotation.y=L(0,.9,l),i.rotation.z=O,i.rotation.x=0),r&&(r.rotation.order="XYZ",r.rotation.y=L(0,1.8,l),r.rotation.z=L($e,0,l),r.rotation.x=0),s&&(s.rotation.x=L(Le,-.9,l),s.rotation.y=L(0,.05,l),s.rotation.z=L(0,.6,l));const a=[[M.RightIndexProximal,M.RightIndexIntermediate,M.RightIndexDistal],[M.RightMiddleProximal,M.RightMiddleIntermediate,M.RightMiddleDistal],[M.RightRingProximal,M.RightRingIntermediate,M.RightRingDistal],[M.RightLittleProximal,M.RightLittleIntermediate,M.RightLittleDistal]];for(const[p,f,g]of a){const _=L(.28,1.45,l),v=t.getNormalizedBoneNode(p),y=t.getNormalizedBoneNode(f),A=t.getNormalizedBoneNode(g);v&&(v.rotation.z=_,v.rotation.x=0),y&&(y.rotation.z=_*.9,y.rotation.x=0),A&&(A.rotation.z=_*.7,A.rotation.x=0)}const u=t.getNormalizedBoneNode(M.RightThumbMetacarpal),h=t.getNormalizedBoneNode(M.RightThumbProximal),d=t.getNormalizedBoneNode(M.RightThumbDistal);u&&(u.rotation.x=L(.2,.2,l),u.rotation.z=L(-.3,-.3,l),u.rotation.y=0),h&&(h.rotation.x=0,h.rotation.z=0,h.rotation.y=0),d&&(d.rotation.x=0,d.rotation.z=0,d.rotation.y=0),o&&(o.rotation.z=-O)}},dance:{duration:3,fn(n,e){const t=e.humanoid,i=t.getNormalizedBoneNode(M.Hips),r=t.getNormalizedBoneNode(M.Spine),s=t.getNormalizedBoneNode(M.Chest),o=t.getNormalizedBoneNode(M.Neck),l=t.getNormalizedBoneNode(M.RightUpperArm),a=t.getNormalizedBoneNode(M.LeftUpperArm),u=n<.1?n/.1:n>.9?(1-n)/.1:1,h=Math.sin(n*Math.PI*4)*u,d=Math.sin(n*Math.PI*4+Math.PI)*u,p=e.scene.userData.hipsRestY??0,f=t.getNormalizedBoneNode(M.RightUpperLeg),g=t.getNormalizedBoneNode(M.LeftUpperLeg),_=t.getNormalizedBoneNode(M.RightFoot),v=t.getNormalizedBoneNode(M.LeftFoot);i&&(i.position.y=p,i.rotation.z=d*.18,i.rotation.y=d*.06),f&&(f.rotation.z=-d*.18,f.rotation.x=0,f.rotation.y=0),g&&(g.rotation.z=-d*.18,g.rotation.x=0,g.rotation.y=0),_&&(_.rotation.x=0,_.rotation.z=0,_.rotation.y=0),v&&(v.rotation.x=0,v.rotation.z=0,v.rotation.y=0),r&&(r.rotation.z=h*.1),s&&(s.rotation.z=-h*.07),o&&(o.rotation.z=Math.sin(n*Math.PI*4+Math.PI/4)*.07*u),l&&(l.rotation.z=O-h*.5,l.rotation.x=Math.abs(h)*.1),a&&(a.rotation.z=-O+h*.5,a.rotation.x=Math.abs(h)*.1)}}},Ze={idle:[],smile:["Smile","smile","Happy","happy","mouthSmile","Joy"],sad:["Sad","sad","Frown","frown","mouthFrown"],happy:["Smile","smile","Happy","happy","Joy","joy"],angry:["Angry","angry","Frown","frown","Mad"],surprised:["Surprised","surprised","Awe","awe","Oh","Shock"],thinking:["Thinking","thinking","Sad","Awe"],confused:["Confused","confused","Awe","Surprised"],sleep:["Sleep","sleep","Blink","eyesClosed"]},sn={idle:null,smile:"happy",happy:"happy",sad:"sad",angry:"angry",surprised:"surprised",thinking:"relaxed",confused:"surprised",sleep:"blink"},on=["Blink","blink","EyesClosed","eyesClosed","eyeBlink_L","eyeBlink"],qr=["mouthOpen","MouthOpen","jawOpen","JawOpen","jaw_open","mouth_open","viseme_O","viseme_aa","A","open"],Kr=["Head","head","mixamorigHead","Bip01_Head","Bip001 Head","head_joint","HeadBone"],$r=[/^bip_head/i,/^head$/i,/head_0/i],te=class te{constructor(){this.mixer=null,this.clips=[],this.currentAction=null,this.idleAction=null,this.vrm=null,this.morphMeshes=[],this.headBone=null,this.headBoneRestWorldQ=new c.Quaternion,this.lookCurrentDelta=new c.Quaternion,this.lookTargetDelta=new c.Quaternion,this.lookSettled=!0,this._tmpParentWorldQInv=new c.Quaternion,this._tmpDesiredWorldQ=new c.Quaternion,this.blinkTimer=null,this.idleTimer=null,this.randomLookTimeout=null,this._vrmIdleTime=0,this._gestureActive=!1,this._gestureElapsed=0,this._gestureDuration=0,this._gestureUpdateFn=null,this._pendingGesture=null}init(e){if(this.dispose(),this.vrm=e.vrm??null,this.mixer=new c.AnimationMixer(e.scene),this.clips=e.animations,this.morphMeshes=[],this.headBone=null,this.vrm){const t=this.vrm.humanoid.getNormalizedBoneNode(M.Head);t&&(this.headBone=t,e.scene.updateWorldMatrix(!0,!0),this.headBone.getWorldQuaternion(this.headBoneRestWorldQ)),this._initVRMRestPose()}else e.scene.traverse(t=>{if(t instanceof c.Bone&&!this.headBone){const i=Kr.includes(t.name),r=!i&&$r.some(s=>s.test(t.name));(i||r)&&(this.headBone=t,e.scene.updateWorldMatrix(!0,!0),t.getWorldQuaternion(this.headBoneRestWorldQ))}(t instanceof c.Mesh||t instanceof c.SkinnedMesh)&&t.morphTargetDictionary&&Object.keys(t.morphTargetDictionary).length>0&&this.morphMeshes.push(t)})}update(e){if(this.mixer?.update(e),this._vrmIdleTime+=e,this._gestureActive?this._tickProceduralGesture(e):this._updateVRMProceduralIdle(this._vrmIdleTime),this.vrm?.update(e),this.headBone){if(!this.lookSettled){const i=1-Math.pow(1e-4,e);this.lookCurrentDelta.slerp(this.lookTargetDelta,i),this.lookCurrentDelta.angleTo(this.lookTargetDelta)<.01&&(this.lookCurrentDelta.copy(this.lookTargetDelta),this.lookSettled=!0)}this._tmpDesiredWorldQ.multiplyQuaternions(this.headBoneRestWorldQ,this.lookCurrentDelta);const t=this.headBone.parent;t?(t.getWorldQuaternion(this._tmpParentWorldQInv),this._tmpParentWorldQInv.invert(),this.headBone.quaternion.multiplyQuaternions(this._tmpParentWorldQInv,this._tmpDesiredWorldQ)):this.headBone.quaternion.copy(this._tmpDesiredWorldQ)}}play(e){const t=c.AnimationClip.findByName(this.clips,e);!t||!this.mixer||this._transitionTo(this.mixer.clipAction(t))}stop(){this.currentAction&&(this.currentAction.fadeOut(.3),this.currentAction=null,this.idleAction&&this.idleAction.fadeIn(.3).play())}_transitionTo(e,t=.3){this.currentAction!==e&&(this.currentAction?.fadeOut(t),e.reset().fadeIn(t).play(),this.currentAction=e)}startIdle(e=8e3){const t=this._findClip(/idle|breathing|float/i)??this.clips[0];t&&this.mixer&&(this.idleAction=this.mixer.clipAction(t),this.idleAction.setLoop(c.LoopRepeat,1/0),this.idleAction.play()),this.idleTimer=setInterval(()=>{this._randomIdleExpression()},e)}stopIdle(){this.idleAction?.stop(),this.idleAction=null,this.idleTimer&&(clearInterval(this.idleTimer),this.idleTimer=null)}_randomIdleExpression(){const e=["idle","smile","thinking"],t=e[Math.floor(Math.random()*e.length)];t!=="idle"&&(this.setExpression(t,.3),setTimeout(()=>this.setExpression("idle",0),1200))}startBlink(e=3500){this.blinkTimer=setInterval(()=>{this._doBlink()},e+Math.random()*1e3-500)}stopBlink(){this.blinkTimer&&(clearInterval(this.blinkTimer),this.blinkTimer=null)}async _doBlink(){this.vrm?.expressionManager?(this.vrm.expressionManager.setValue("blink",1),await this._delay(120),this.vrm.expressionManager.setValue("blink",0)):(this._setMorphTarget(on,1),await this._delay(120),this._setMorphTarget(on,0))}setExpression(e,t=1){if(this.vrm?.expressionManager){const r=this.vrm.expressionManager;for(const o of Object.values(sn))o&&r.setValue(o,0);const s=sn[e];s&&r.setValue(s,t);return}if(e==="idle"){for(const r of Object.values(Ze))this._setMorphTarget(r,0);return}const i=Ze[e];if(i.length){for(const[r,s]of Object.entries(Ze))r!==e&&r!=="idle"&&this._setMorphTarget(s,0);this._setMorphTarget(i,t)}}setMouthMorph(e){const t=Math.max(0,Math.min(1,e));if(this.vrm?.expressionManager){const i=this.vrm.expressionManager;for(const r of te._VRM_VISEMES)i.setValue(r,0);if(t>.01){const r=Math.floor(performance.now()/250)%te._VRM_VISEME_CYCLE.length,s=te._VRM_VISEME_CYCLE[r]??"aa";i.setValue(s,t)}return}this._setMorphTarget(qr,t)}playGesture(e){if(this.vrm){this._playVRMProceduralGesture(e);return}const t=this._findClip(new RegExp(e,"i"));if(t&&this.mixer){const i=this.mixer.clipAction(t);i.setLoop(c.LoopOnce,1),i.clampWhenFinished=!0,this._transitionTo(i),this.mixer.addEventListener("finished",r=>{r.action===i&&(this.stop(),this.mixer?.removeEventListener("finished",()=>{}))})}}_playVRMProceduralGesture(e){if(this.vrm){if(this._gestureActive){const t=this._gestureDuration*.82;this._gestureElapsed<t&&(this._gestureElapsed=t),this._pendingGesture=e;return}this._startGesture(e)}}_startGesture(e){const t=Yr[e];if(!t||!this.vrm)return;const i=this.vrm;this._gestureActive=!0,this._gestureElapsed=0,this._gestureDuration=t.duration,this._gestureUpdateFn=r=>t.fn(r,i),this._pendingGesture=null}_tickProceduralGesture(e){if(!this._gestureUpdateFn)return;this._gestureElapsed+=e;const t=Math.min(this._gestureElapsed/this._gestureDuration,1);this._gestureUpdateFn(t),t>=1&&(this._gestureActive=!1,this._gestureUpdateFn=null,this._gestureElapsed=0,this._pendingGesture&&this._startGesture(this._pendingGesture))}lookAt(e,t){const i=new c.Euler(t*.6,e*.75,0,"YXZ");this.lookTargetDelta.setFromEuler(i),this.lookSettled=!1}lookForward(){this.stopRandomLook(),this.lookTargetDelta.identity(),this.lookSettled=!1}startRandomLook(){this.stopRandomLook();const e=()=>{const t=(Math.random()-.5)*1.4,i=(Math.random()-.5)*.8;this.lookAt(t,i),this.randomLookTimeout=setTimeout(e,1500+Math.random()*2e3)};e()}stopRandomLook(){this.randomLookTimeout&&(clearTimeout(this.randomLookTimeout),this.randomLookTimeout=null)}stopLook(){this.stopRandomLook(),this.lookTargetDelta.identity(),this.lookCurrentDelta.identity()}hasHeadBone(){return this.headBone!==null}_setMorphTarget(e,t){for(const i of this.morphMeshes){const r=i.morphTargetDictionary;if(!(!r||!i.morphTargetInfluences))for(const s of e){const o=r[s];if(o!==void 0){i.morphTargetInfluences[o]=t;break}}}}_initVRMRestPose(){if(!this.vrm)return;const e=this.vrm.humanoid,t=e.getNormalizedBoneNode(M.RightUpperArm),i=e.getNormalizedBoneNode(M.LeftUpperArm);t&&(t.rotation.z=Math.PI/6),i&&(i.rotation.z=-Math.PI/6);const r=e.getNormalizedBoneNode(M.Hips);r&&(this.vrm.scene.userData.hipsRestY=r.position.y)}_updateVRMProceduralIdle(e){if(!this.vrm)return;const t=this.vrm.humanoid,i=t.getNormalizedBoneNode(M.Hips);i&&(i.position.y=this.vrm.scene.userData.hipsRestY??0);const r=Math.sin(e*1.8),s=Math.sin(e*.7),o=t.getNormalizedBoneNode(M.Spine),l=t.getNormalizedBoneNode(M.Chest);o&&(o.rotation.z=s*.008),l&&(l.rotation.x=r*.015);const a=t.getNormalizedBoneNode(M.RightUpperArm),u=t.getNormalizedBoneNode(M.LeftUpperArm);a&&(a.rotation.z=Math.PI/3.2+r*.018,a.rotation.y=0,a.rotation.x=0),u&&(u.rotation.z=-(Math.PI/3.2+r*.018),u.rotation.y=0,u.rotation.x=0);const h=t.getNormalizedBoneNode(M.RightLowerArm),d=t.getNormalizedBoneNode(M.LeftLowerArm);h&&(h.rotation.order="XYZ",h.rotation.z=-.1,h.rotation.y=0,h.rotation.x=0),d&&(d.rotation.z=.1,d.rotation.y=0,d.rotation.x=0);const p=t.getNormalizedBoneNode(M.RightHand),f=t.getNormalizedBoneNode(M.LeftHand);p&&(p.rotation.x=-.15,p.rotation.y=0,p.rotation.z=0),f&&(f.rotation.x=-.15,f.rotation.y=0,f.rotation.z=0);const g=.28+r*.06,_=[[M.RightIndexProximal,M.RightIndexIntermediate,M.RightIndexDistal],[M.RightMiddleProximal,M.RightMiddleIntermediate,M.RightMiddleDistal],[M.RightRingProximal,M.RightRingIntermediate,M.RightRingDistal],[M.RightLittleProximal,M.RightLittleIntermediate,M.RightLittleDistal]];for(const[R,x,S]of _){const T=t.getNormalizedBoneNode(R),w=t.getNormalizedBoneNode(x),E=t.getNormalizedBoneNode(S);T&&(T.rotation.z=g,T.rotation.x=0),w&&(w.rotation.z=g*.8,w.rotation.x=0),E&&(E.rotation.z=g*.5,E.rotation.x=0)}const v=[[M.LeftIndexProximal,M.LeftIndexIntermediate,M.LeftIndexDistal],[M.LeftMiddleProximal,M.LeftMiddleIntermediate,M.LeftMiddleDistal],[M.LeftRingProximal,M.LeftRingIntermediate,M.LeftRingDistal],[M.LeftLittleProximal,M.LeftLittleIntermediate,M.LeftLittleDistal]];for(const[R,x,S]of v){const T=t.getNormalizedBoneNode(R),w=t.getNormalizedBoneNode(x),E=t.getNormalizedBoneNode(S);T&&(T.rotation.z=-g,T.rotation.x=0),w&&(w.rotation.z=-g*.8,w.rotation.x=0),E&&(E.rotation.z=-g*.5,E.rotation.x=0)}const y=t.getNormalizedBoneNode(M.RightThumbProximal),A=t.getNormalizedBoneNode(M.LeftThumbProximal);y&&(y.rotation.z=-.3,y.rotation.x=.2),A&&(A.rotation.z=.3,A.rotation.x=.2)}_findClip(e){return this.clips.find(t=>e.test(t.name))}_delay(e){return new Promise(t=>setTimeout(t,e))}dispose(){this.stopBlink(),this.stopIdle(),this.stopRandomLook(),this.stopLook(),this.mixer?.stopAllAction(),this.mixer=null,this.vrm=null,this.clips=[],this.morphMeshes=[],this.headBone=null,this.lookCurrentDelta.identity(),this.lookTargetDelta.identity(),this.lookSettled=!0,this.currentAction=null,this.idleAction=null,this._gestureActive=!1,this._gestureUpdateFn=null,this._gestureElapsed=0,this._pendingGesture=null}};te._VRM_VISEME_CYCLE=["aa","aa","oh","aa","ih","aa","ee","ou"],te._VRM_VISEMES=["aa","ih","ou","ee","oh"];let Je=te;class Zr{constructor(){this.context=null,this.source=null,this.analyser=null,this.gainNode=null,this.dataArray=new Float32Array(0),this._endedCallback=null}_ctx(){return(!this.context||this.context.state==="closed")&&(this.context=new AudioContext),this.context}async play(e){const t=this._ctx();t.state==="suspended"&&await t.resume(),this._stopSource();const i=await this._toBuffer(t,e);return this.analyser=t.createAnalyser(),this.analyser.fftSize=512,this.analyser.smoothingTimeConstant=.6,this.dataArray=new Float32Array(this.analyser.frequencyBinCount),this.gainNode=t.createGain(),this.source=t.createBufferSource(),this.source.buffer=i,this.source.connect(this.analyser),this.analyser.connect(this.gainNode),this.gainNode.connect(t.destination),new Promise(r=>{this.source.onended=()=>{this._endedCallback?.(),r()},this.source.start(0)})}pause(){this.context?.suspend()}async resume(){await this.context?.resume()}stop(){this._stopSource()}getAmplitude(){if(!this.analyser||this.dataArray.length===0)return 0;this.analyser.getFloatTimeDomainData(this.dataArray);let e=0;for(const t of this.dataArray)e+=t*t;return Math.sqrt(e/this.dataArray.length)}set onEnded(e){this._endedCallback=e}async _toBuffer(e,t){if(t instanceof AudioBuffer)return t;if(typeof t=="string"){const r=await(await fetch(t)).arrayBuffer();return e.decodeAudioData(r)}return e.decodeAudioData(t.slice(0))}_stopSource(){try{this.source?.stop()}catch{}this.source?.disconnect(),this.source=null}dispose(){this._stopSource(),this.context?.close(),this.context=null,this.analyser=null,this.gainNode=null}}const Jr={sil:0,PP:.05,FF:.2,TH:.25,DD:.3,kk:.35,CH:.5,SS:.2,nn:.15,RR:.4,aa:1,E:.7,ih:.5,oh:.85,ou:.6};class es{constructor(e,t){this.audioEngine=e,this.onMouth=t,this.rafId=0}setViseme(e){this.onMouth(Jr[e]??0)}setMouth(e){this.onMouth(Math.max(0,Math.min(1,e)))}setVolume(e){this.onMouth(Math.max(0,Math.min(1,e)))}startAutoSync(){this.stopAutoSync();const e=()=>{const t=this.audioEngine.getAmplitude();this.onMouth(Math.min(1,t*10)),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}stopAutoSync(){cancelAnimationFrame(this.rafId),this.rafId=0,this.onMouth(0)}}function an(n,e){if(e===m.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===m.TriangleFanDrawMode||e===m.TriangleStripDrawMode){let t=n.getIndex();if(t===null){const o=[],l=n.getAttribute("position");if(l!==void 0){for(let a=0;a<l.count;a++)o.push(a);n.setIndex(o),t=n.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),n}const i=t.count-2,r=[];if(e===m.TriangleFanDrawMode)for(let o=1;o<=i;o++)r.push(t.getX(0)),r.push(t.getX(o)),r.push(t.getX(o+1));else for(let o=0;o<i;o++)o%2===0?(r.push(t.getX(o)),r.push(t.getX(o+1)),r.push(t.getX(o+2))):(r.push(t.getX(o+2)),r.push(t.getX(o+1)),r.push(t.getX(o)));r.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const s=n.clone();return s.setIndex(r),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),n}class ln extends m.Loader{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new ss(t)}),this.register(function(t){return new os(t)}),this.register(function(t){return new ms(t)}),this.register(function(t){return new gs(t)}),this.register(function(t){return new _s(t)}),this.register(function(t){return new ls(t)}),this.register(function(t){return new us(t)}),this.register(function(t){return new cs(t)}),this.register(function(t){return new hs(t)}),this.register(function(t){return new rs(t)}),this.register(function(t){return new ds(t)}),this.register(function(t){return new as(t)}),this.register(function(t){return new fs(t)}),this.register(function(t){return new ps(t)}),this.register(function(t){return new ns(t)}),this.register(function(t){return new vs(t)}),this.register(function(t){return new Ms(t)})}load(e,t,i,r){const s=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const u=m.LoaderUtils.extractUrlBase(e);o=m.LoaderUtils.resolveURL(u,this.path)}else o=m.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const l=function(u){r?r(u):console.error(u),s.manager.itemError(e),s.manager.itemEnd(e)},a=new m.FileLoader(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(u){try{s.parse(u,o,function(h){t(h),s.manager.itemEnd(e)},l)}catch(h){l(h)}},i,l)}setDRACOLoader(e){return this.dracoLoader=e,this}setDDSLoader(){throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,r){let s;const o={},l={},a=new TextDecoder;if(typeof e=="string")s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(a.decode(new Uint8Array(e,0,4))===un){try{o[P.KHR_BINARY_GLTF]=new xs(e)}catch(d){r&&r(d);return}s=JSON.parse(o[P.KHR_BINARY_GLTF].content)}else s=JSON.parse(a.decode(e));else s=e;if(s.asset===void 0||s.asset.version[0]<2){r&&r(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const u=new Cs(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});u.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h<this.pluginCallbacks.length;h++){const d=this.pluginCallbacks[h](u);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),l[d.name]=d,o[d.name]=!0}if(s.extensionsUsed)for(let h=0;h<s.extensionsUsed.length;++h){const d=s.extensionsUsed[h],p=s.extensionsRequired||[];switch(d){case P.KHR_MATERIALS_UNLIT:o[d]=new is;break;case P.KHR_DRACO_MESH_COMPRESSION:o[d]=new ys(s,this.dracoLoader);break;case P.KHR_TEXTURE_TRANSFORM:o[d]=new As;break;case P.KHR_MESH_QUANTIZATION:o[d]=new Ts;break;default:p.indexOf(d)>=0&&l[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}u.setExtensions(o),u.setPlugins(l),u.parse(i,r)}parseAsync(e,t){const i=this;return new Promise(function(r,s){i.parse(e,t,r,s)})}}function ts(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const P={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class ns{constructor(e){this.parser=e,this.name=P.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,r=t.length;i<r;i++){const s=t[i];s.extensions&&s.extensions[this.name]&&s.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,s.extensions[this.name].light)}}_loadLight(e){const t=this.parser,i="light:"+e;let r=t.cache.get(i);if(r)return r;const s=t.json,a=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e];let u;const h=new m.Color(16777215);a.color!==void 0&&h.setRGB(a.color[0],a.color[1],a.color[2],m.LinearSRGBColorSpace);const d=a.range!==void 0?a.range:0;switch(a.type){case"directional":u=new m.DirectionalLight(h),u.target.position.set(0,0,-1),u.add(u.target);break;case"point":u=new m.PointLight(h),u.distance=d;break;case"spot":u=new m.SpotLight(h),u.distance=d,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,u.angle=a.spot.outerConeAngle,u.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,u.target.position.set(0,0,-1),u.add(u.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return u.position.set(0,0,0),u.decay=2,G(u,a),a.intensity!==void 0&&(u.intensity=a.intensity),u.name=t.createUniqueName(a.name||"light_"+e),r=Promise.resolve(u),t.cache.add(i,r),r}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,i=this.parser,s=i.json.nodes[e],l=(s.extensions&&s.extensions[this.name]||{}).light;return l===void 0?null:this._loadLight(l).then(function(a){return i._getNodeRef(t.cache,l,a)})}}class is{constructor(){this.name=P.KHR_MATERIALS_UNLIT}getMaterialType(){return m.MeshBasicMaterial}extendParams(e,t,i){const r=[];e.color=new m.Color(1,1,1),e.opacity=1;const s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){const o=s.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],m.LinearSRGBColorSpace),e.opacity=o[3]}s.baseColorTexture!==void 0&&r.push(i.assignTexture(e,"map",s.baseColorTexture,m.SRGBColorSpace))}return Promise.all(r)}}class rs{constructor(e){this.parser=e,this.name=P.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const r=this.parser.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=r.extensions[this.name].emissiveStrength;return s!==void 0&&(t.emissiveIntensity=s),Promise.resolve()}}class ss{constructor(e){this.parser=e,this.name=P.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:m.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,r=i.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=[],o=r.extensions[this.name];if(o.clearcoatFactor!==void 0&&(t.clearcoat=o.clearcoatFactor),o.clearcoatTexture!==void 0&&s.push(i.assignTexture(t,"clearcoatMap",o.clearcoatTexture)),o.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=o.clearcoatRoughnessFactor),o.clearcoatRoughnessTexture!==void 0&&s.push(i.assignTexture(t,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),o.clearcoatNormalTexture!==void 0&&(s.push(i.assignTexture(t,"clearcoatNormalMap",o.clearcoatNormalTexture)),o.clearcoatNormalTexture.scale!==void 0)){const l=o.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new m.Vector2(l,l)}return Promise.all(s)}}class os{constructor(e){this.parser=e,this.name=P.KHR_MATERIALS_DISPERSION}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:m.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=r.extensions[this.name];return t.dispersion=s.dispersion!==void 0?s.dispersion:0,Promise.resolve()}}class as{constructor(e){this.parser=e,this.name=P.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:m.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,r=i.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=[],o=r.extensions[this.name];return o.iridescenceFactor!==void 0&&(t.iridescence=o.iridescenceFactor),o.iridescenceTexture!==void 0&&s.push(i.assignTexture(t,"iridescenceMap",o.iridescenceTexture)),o.iridescenceIor!==void 0&&(t.iridescenceIOR=o.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),o.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=o.iridescenceThicknessMinimum),o.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=o.iridescenceThicknessMaximum),o.iridescenceThicknessTexture!==void 0&&s.push(i.assignTexture(t,"iridescenceThicknessMap",o.iridescenceThicknessTexture)),Promise.all(s)}}class ls{constructor(e){this.parser=e,this.name=P.KHR_MATERIALS_SHEEN}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:m.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,r=i.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=[];t.sheenColor=new m.Color(0,0,0),t.sheenRoughness=0,t.sheen=1;const o=r.extensions[this.name];if(o.sheenColorFactor!==void 0){const l=o.sheenColorFactor;t.sheenColor.setRGB(l[0],l[1],l[2],m.LinearSRGBColorSpace)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&s.push(i.assignTexture(t,"sheenColorMap",o.sheenColorTexture,m.SRGBColorSpace)),o.sheenRoughnessTexture!==void 0&&s.push(i.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(s)}}class us{constructor(e){this.parser=e,this.name=P.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:m.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,r=i.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=[],o=r.extensions[this.name];return o.transmissionFactor!==void 0&&(t.transmission=o.transmissionFactor),o.transmissionTexture!==void 0&&s.push(i.assignTexture(t,"transmissionMap",o.transmissionTexture)),Promise.all(s)}}class cs{constructor(e){this.parser=e,this.name=P.KHR_MATERIALS_VOLUME}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:m.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,r=i.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=[],o=r.extensions[this.name];t.thickness=o.thicknessFactor!==void 0?o.thicknessFactor:0,o.thicknessTexture!==void 0&&s.push(i.assignTexture(t,"thicknessMap",o.thicknessTexture)),t.attenuationDistance=o.attenuationDistance||1/0;const l=o.attenuationColor||[1,1,1];return t.attenuationColor=new m.Color().setRGB(l[0],l[1],l[2],m.LinearSRGBColorSpace),Promise.all(s)}}class hs{constructor(e){this.parser=e,this.name=P.KHR_MATERIALS_IOR}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:m.MeshPhysicalMaterial}extendMaterialParams(e,t){const r=this.parser.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=r.extensions[this.name];return t.ior=s.ior!==void 0?s.ior:1.5,Promise.resolve()}}class ds{constructor(e){this.parser=e,this.name=P.KHR_MATERIALS_SPECULAR}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:m.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,r=i.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=[],o=r.extensions[this.name];t.specularIntensity=o.specularFactor!==void 0?o.specularFactor:1,o.specularTexture!==void 0&&s.push(i.assignTexture(t,"specularIntensityMap",o.specularTexture));const l=o.specularColorFactor||[1,1,1];return t.specularColor=new m.Color().setRGB(l[0],l[1],l[2],m.LinearSRGBColorSpace),o.specularColorTexture!==void 0&&s.push(i.assignTexture(t,"specularColorMap",o.specularColorTexture,m.SRGBColorSpace)),Promise.all(s)}}class ps{constructor(e){this.parser=e,this.name=P.EXT_MATERIALS_BUMP}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:m.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,r=i.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=[],o=r.extensions[this.name];return t.bumpScale=o.bumpFactor!==void 0?o.bumpFactor:1,o.bumpTexture!==void 0&&s.push(i.assignTexture(t,"bumpMap",o.bumpTexture)),Promise.all(s)}}class fs{constructor(e){this.parser=e,this.name=P.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:m.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,r=i.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();const s=[],o=r.extensions[this.name];return o.anisotropyStrength!==void 0&&(t.anisotropy=o.anisotropyStrength),o.anisotropyRotation!==void 0&&(t.anisotropyRotation=o.anisotropyRotation),o.anisotropyTexture!==void 0&&s.push(i.assignTexture(t,"anisotropyMap",o.anisotropyTexture)),Promise.all(s)}}class ms{constructor(e){this.parser=e,this.name=P.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,i=t.json,r=i.textures[e];if(!r.extensions||!r.extensions[this.name])return null;const s=r.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(i.extensionsRequired&&i.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,o)}}class gs{constructor(e){this.parser=e,this.name=P.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,i=this.parser,r=i.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;const o=s.extensions[t],l=r.images[o.source];let a=i.textureLoader;if(l.uri){const u=i.options.manager.getHandler(l.uri);u!==null&&(a=u)}return this.detectSupport().then(function(u){if(u)return i.loadTextureImage(e,o.source,a);if(r.extensionsRequired&&r.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return i.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class _s{constructor(e){this.parser=e,this.name=P.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,i=this.parser,r=i.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;const o=s.extensions[t],l=r.images[o.source];let a=i.textureLoader;if(l.uri){const u=i.options.manager.getHandler(l.uri);u!==null&&(a=u)}return this.detectSupport().then(function(u){if(u)return i.loadTextureImage(e,o.source,a);if(r.extensionsRequired&&r.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return i.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class vs{constructor(e){this.name=P.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const r=i.extensions[this.name],s=this.parser.getDependency("buffer",r.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(l){const a=r.byteOffset||0,u=r.byteLength||0,h=r.count,d=r.byteStride,p=new Uint8Array(l,a,u);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(h,d,p,r.mode,r.filter).then(function(f){return f.buffer}):o.ready.then(function(){const f=new ArrayBuffer(h*d);return o.decodeGltfBuffer(new Uint8Array(f),h,d,p,r.mode,r.filter),f})})}else return null}}class Ms{constructor(e){this.name=P.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const r=t.meshes[i.mesh];for(const u of r.primitives)if(u.mode!==F.TRIANGLES&&u.mode!==F.TRIANGLE_STRIP&&u.mode!==F.TRIANGLE_FAN&&u.mode!==void 0)return null;const o=i.extensions[this.name].attributes,l=[],a={};for(const u in o)l.push(this.parser.getDependency("accessor",o[u]).then(h=>(a[u]=h,a[u])));return l.length<1?null:(l.push(this.parser.createNodeMesh(e)),Promise.all(l).then(u=>{const h=u.pop(),d=h.isGroup?h.children:[h],p=u[0].count,f=[];for(const g of d){const _=new m.Matrix4,v=new m.Vector3,y=new m.Quaternion,A=new m.Vector3(1,1,1),R=new m.InstancedMesh(g.geometry,g.material,p);for(let x=0;x<p;x++)a.TRANSLATION&&v.fromBufferAttribute(a.TRANSLATION,x),a.ROTATION&&y.fromBufferAttribute(a.ROTATION,x),a.SCALE&&A.fromBufferAttribute(a.SCALE,x),R.setMatrixAt(x,_.compose(v,y,A));for(const x in a)if(x==="_COLOR_0"){const S=a[x];R.instanceColor=new m.InstancedBufferAttribute(S.array,S.itemSize,S.normalized)}else x!=="TRANSLATION"&&x!=="ROTATION"&&x!=="SCALE"&&g.geometry.setAttribute(x,a[x]);m.Object3D.prototype.copy.call(R,g),this.parser.assignFinalMaterial(R),f.push(R)}return h.isGroup?(h.clear(),h.add(...f),h):f[0]}))}}const un="glTF",me=12,cn={JSON:1313821514,BIN:5130562};class xs{constructor(e){this.name=P.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,me),i=new TextDecoder;if(this.header={magic:i.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==un)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const r=this.header.length-me,s=new DataView(e,me);let o=0;for(;o<r;){const l=s.getUint32(o,!0);o+=4;const a=s.getUint32(o,!0);if(o+=4,a===cn.JSON){const u=new Uint8Array(e,me+o,l);this.content=i.decode(u)}else if(a===cn.BIN){const u=me+o;this.body=e.slice(u,u+l)}o+=l}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class ys{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=P.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const i=this.json,r=this.dracoLoader,s=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,l={},a={},u={};for(const h in o){const d=tt[h]||h.toLowerCase();l[d]=o[h]}for(const h in e.attributes){const d=tt[h]||h.toLowerCase();if(o[h]!==void 0){const p=i.accessors[e.attributes[h]],f=oe[p.componentType];u[d]=f.name,a[d]=p.normalized===!0}}return t.getDependency("bufferView",s).then(function(h){return new Promise(function(d,p){r.decodeDracoFile(h,function(f){for(const g in f.attributes){const _=f.attributes[g],v=a[g];v!==void 0&&(_.normalized=v)}d(f)},l,u,m.LinearSRGBColorSpace,p)})})}}class As{constructor(){this.name=P.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class Ts{constructor(){this.name=P.KHR_MESH_QUANTIZATION}}class hn extends m.Interpolant{constructor(e,t,i,r){super(e,t,i,r)}copySampleValue_(e){const t=this.resultBuffer,i=this.sampleValues,r=this.valueSize,s=e*r*3+r;for(let o=0;o!==r;o++)t[o]=i[s+o];return t}interpolate_(e,t,i,r){const s=this.resultBuffer,o=this.sampleValues,l=this.valueSize,a=l*2,u=l*3,h=r-t,d=(i-t)/h,p=d*d,f=p*d,g=e*u,_=g-u,v=-2*f+3*p,y=f-p,A=1-v,R=y-p+d;for(let x=0;x!==l;x++){const S=o[_+x+l],T=o[_+x+a]*h,w=o[g+x+l],E=o[g+x]*h;s[x]=A*S+R*T+v*w+y*E}return s}}const Rs=new m.Quaternion;class Ss extends hn{interpolate_(e,t,i,r){const s=super.interpolate_(e,t,i,r);return Rs.fromArray(s).normalize().toArray(s),s}}const F={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},oe={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},dn={9728:m.NearestFilter,9729:m.LinearFilter,9984:m.NearestMipmapNearestFilter,9985:m.LinearMipmapNearestFilter,9986:m.NearestMipmapLinearFilter,9987:m.LinearMipmapLinearFilter},pn={33071:m.ClampToEdgeWrapping,33648:m.MirroredRepeatWrapping,10497:m.RepeatWrapping},et={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},tt={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Q={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},ws={CUBICSPLINE:void 0,LINEAR:m.InterpolateLinear,STEP:m.InterpolateDiscrete},nt={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function Ls(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new m.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:m.FrontSide})),n.DefaultMaterial}function ee(n,e,t){for(const i in t.extensions)n[i]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[i]=t.extensions[i])}function G(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function Ps(n,e,t){let i=!1,r=!1,s=!1;for(let u=0,h=e.length;u<h;u++){const d=e[u];if(d.POSITION!==void 0&&(i=!0),d.NORMAL!==void 0&&(r=!0),d.COLOR_0!==void 0&&(s=!0),i&&r&&s)break}if(!i&&!r&&!s)return Promise.resolve(n);const o=[],l=[],a=[];for(let u=0,h=e.length;u<h;u++){const d=e[u];if(i){const p=d.POSITION!==void 0?t.getDependency("accessor",d.POSITION):n.attributes.position;o.push(p)}if(r){const p=d.NORMAL!==void 0?t.getDependency("accessor",d.NORMAL):n.attributes.normal;l.push(p)}if(s){const p=d.COLOR_0!==void 0?t.getDependency("accessor",d.COLOR_0):n.attributes.color;a.push(p)}}return Promise.all([Promise.all(o),Promise.all(l),Promise.all(a)]).then(function(u){const h=u[0],d=u[1],p=u[2];return i&&(n.morphAttributes.position=h),r&&(n.morphAttributes.normal=d),s&&(n.morphAttributes.color=p),n.morphTargetsRelative=!0,n})}function Es(n,e){if(n.updateMorphTargets(),e.weights!==void 0)for(let t=0,i=e.weights.length;t<i;t++)n.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(n.morphTargetInfluences.length===t.length){n.morphTargetDictionary={};for(let i=0,r=t.length;i<r;i++)n.morphTargetDictionary[t[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Ns(n){let e;const t=n.extensions&&n.extensions[P.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+it(t.attributes):e=n.indices+":"+it(n.attributes)+":"+n.mode,n.targets!==void 0)for(let i=0,r=n.targets.length;i<r;i++)e+=":"+it(n.targets[i]);return e}function it(n){let e="";const t=Object.keys(n).sort();for(let i=0,r=t.length;i<r;i++)e+=t[i]+":"+n[t[i]]+";";return e}function rt(n){switch(n){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function bs(n){return n.search(/\.jpe?g($|\?)/i)>0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":"image/png"}const Is=new m.Matrix4;class Cs{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new ts,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,r=!1,s=-1;typeof navigator<"u"&&(i=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)===!0,r=navigator.userAgent.indexOf("Firefox")>-1,s=r?navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]:-1),typeof createImageBitmap>"u"||i||r&&s<98?this.textureLoader=new m.TextureLoader(this.options.manager):this.textureLoader=new m.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new m.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,r=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(o){const l={scene:o[0][r.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:r.asset,parser:i,userData:{}};return ee(s,l,r),G(l,r),Promise.all(i._invokeAll(function(a){return a.afterRoot&&a.afterRoot(l)})).then(function(){for(const a of l.scenes)a.updateMatrixWorld();e(l)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let r=0,s=t.length;r<s;r++){const o=t[r].joints;for(let l=0,a=o.length;l<a;l++)e[o[l]].isBone=!0}for(let r=0,s=e.length;r<s;r++){const o=e[r];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(i[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,i){if(e.refs[t]<=1)return i;const r=i.clone(),s=(o,l)=>{const a=this.associations.get(o);a!=null&&this.associations.set(l,a);for(const[u,h]of o.children.entries())s(h,l.children[u])};return s(i,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i<t.length;i++){const r=e(t[i]);if(r)return r}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const i=[];for(let r=0;r<t.length;r++){const s=e(t[r]);s&&i.push(s)}return i}getDependency(e,t){const i=e+":"+t;let r=this.cache.get(i);if(!r){switch(e){case"scene":r=this.loadScene(t);break;case"node":r=this._invokeOne(function(s){return s.loadNode&&s.loadNode(t)});break;case"mesh":r=this._invokeOne(function(s){return s.loadMesh&&s.loadMesh(t)});break;case"accessor":r=this.loadAccessor(t);break;case"bufferView":r=this._invokeOne(function(s){return s.loadBufferView&&s.loadBufferView(t)});break;case"buffer":r=this.loadBuffer(t);break;case"material":r=this._invokeOne(function(s){return s.loadMaterial&&s.loadMaterial(t)});break;case"texture":r=this._invokeOne(function(s){return s.loadTexture&&s.loadTexture(t)});break;case"skin":r=this.loadSkin(t);break;case"animation":r=this._invokeOne(function(s){return s.loadAnimation&&s.loadAnimation(t)});break;case"camera":r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(s){return s!=this&&s.getDependency&&s.getDependency(e,t)}),!r)throw new Error("Unknown type: "+e);break}this.cache.add(i,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){const i=this,r=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(r.map(function(s,o){return i.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],i=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[P.KHR_BINARY_GLTF].body);const r=this.options;return new Promise(function(s,o){i.load(m.LoaderUtils.resolveURL(t.uri,r.path),s,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(i){const r=t.byteLength||0,s=t.byteOffset||0;return i.slice(s,s+r)})}loadAccessor(e){const t=this,i=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){const o=et[r.type],l=oe[r.componentType],a=r.normalized===!0,u=new l(r.count*o);return Promise.resolve(new m.BufferAttribute(u,o,a))}const s=[];return r.bufferView!==void 0?s.push(this.getDependency("bufferView",r.bufferView)):s.push(null),r.sparse!==void 0&&(s.push(this.getDependency("bufferView",r.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",r.sparse.values.bufferView))),Promise.all(s).then(function(o){const l=o[0],a=et[r.type],u=oe[r.componentType],h=u.BYTES_PER_ELEMENT,d=h*a,p=r.byteOffset||0,f=r.bufferView!==void 0?i.bufferViews[r.bufferView].byteStride:void 0,g=r.normalized===!0;let _,v;if(f&&f!==d){const y=Math.floor(p/f),A="InterleavedBuffer:"+r.bufferView+":"+r.componentType+":"+y+":"+r.count;let R=t.cache.get(A);R||(_=new u(l,y*f,r.count*f/h),R=new m.InterleavedBuffer(_,f/h),t.cache.add(A,R)),v=new m.InterleavedBufferAttribute(R,a,p%f/h,g)}else l===null?_=new u(r.count*a):_=new u(l,p,r.count*a),v=new m.BufferAttribute(_,a,g);if(r.sparse!==void 0){const y=et.SCALAR,A=oe[r.sparse.indices.componentType],R=r.sparse.indices.byteOffset||0,x=r.sparse.values.byteOffset||0,S=new A(o[1],R,r.sparse.count*y),T=new u(o[2],x,r.sparse.count*a);l!==null&&(v=new m.BufferAttribute(v.array.slice(),v.itemSize,v.normalized));for(let w=0,E=S.length;w<E;w++){const I=S[w];if(v.setX(I,T[w*a]),a>=2&&v.setY(I,T[w*a+1]),a>=3&&v.setZ(I,T[w*a+2]),a>=4&&v.setW(I,T[w*a+3]),a>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return v})}loadTexture(e){const t=this.json,i=this.options,s=t.textures[e].source,o=t.images[s];let l=this.textureLoader;if(o.uri){const a=i.manager.getHandler(o.uri);a!==null&&(l=a)}return this.loadTextureImage(e,s,l)}loadTextureImage(e,t,i){const r=this,s=this.json,o=s.textures[e],l=s.images[t],a=(l.uri||l.bufferView)+":"+o.sampler;if(this.textureCache[a])return this.textureCache[a];const u=this.loadImageSource(t,i).then(function(h){h.flipY=!1,h.name=o.name||l.name||"",h.name===""&&typeof l.uri=="string"&&l.uri.startsWith("data:image/")===!1&&(h.name=l.uri);const p=(s.samplers||{})[o.sampler]||{};return h.magFilter=dn[p.magFilter]||m.LinearFilter,h.minFilter=dn[p.minFilter]||m.LinearMipmapLinearFilter,h.wrapS=pn[p.wrapS]||m.RepeatWrapping,h.wrapT=pn[p.wrapT]||m.RepeatWrapping,r.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[a]=u,u}loadImageSource(e,t){const i=this,r=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());const o=r.images[e],l=self.URL||self.webkitURL;let a=o.uri||"",u=!1;if(o.bufferView!==void 0)a=i.getDependency("bufferView",o.bufferView).then(function(d){u=!0;const p=new Blob([d],{type:o.mimeType});return a=l.createObjectURL(p),a});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const h=Promise.resolve(a).then(function(d){return new Promise(function(p,f){let g=p;t.isImageBitmapLoader===!0&&(g=function(_){const v=new m.Texture(_);v.needsUpdate=!0,p(v)}),t.load(m.LoaderUtils.resolveURL(d,s.path),g,void 0,f)})}).then(function(d){return u===!0&&l.revokeObjectURL(a),G(d,o),d.userData.mimeType=o.mimeType||bs(o.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",a),d});return this.sourceCache[e]=h,h}assignTexture(e,t,i,r){const s=this;return this.getDependency("texture",i.index).then(function(o){if(!o)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(o=o.clone(),o.channel=i.texCoord),s.extensions[P.KHR_TEXTURE_TRANSFORM]){const l=i.extensions!==void 0?i.extensions[P.KHR_TEXTURE_TRANSFORM]:void 0;if(l){const a=s.associations.get(o);o=s.extensions[P.KHR_TEXTURE_TRANSFORM].extendTexture(o,l),s.associations.set(o,a)}}return r!==void 0&&(o.colorSpace=r),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const r=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const l="PointsMaterial:"+i.uuid;let a=this.cache.get(l);a||(a=new m.PointsMaterial,m.Material.prototype.copy.call(a,i),a.color.copy(i.color),a.map=i.map,a.sizeAttenuation=!1,this.cache.add(l,a)),i=a}else if(e.isLine){const l="LineBasicMaterial:"+i.uuid;let a=this.cache.get(l);a||(a=new m.LineBasicMaterial,m.Material.prototype.copy.call(a,i),a.color.copy(i.color),a.map=i.map,this.cache.add(l,a)),i=a}if(r||s||o){let l="ClonedMaterial:"+i.uuid+":";r&&(l+="derivative-tangents:"),s&&(l+="vertex-colors:"),o&&(l+="flat-shading:");let a=this.cache.get(l);a||(a=i.clone(),s&&(a.vertexColors=!0),o&&(a.flatShading=!0),r&&(a.normalScale&&(a.normalScale.y*=-1),a.clearcoatNormalScale&&(a.clearcoatNormalScale.y*=-1)),this.cache.add(l,a),this.associations.set(a,this.associations.get(i))),i=a}e.material=i}getMaterialType(){return m.MeshStandardMaterial}loadMaterial(e){const t=this,i=this.json,r=this.extensions,s=i.materials[e];let o;const l={},a=s.extensions||{},u=[];if(a[P.KHR_MATERIALS_UNLIT]){const d=r[P.KHR_MATERIALS_UNLIT];o=d.getMaterialType(),u.push(d.extendParams(l,s,t))}else{const d=s.pbrMetallicRoughness||{};if(l.color=new m.Color(1,1,1),l.opacity=1,Array.isArray(d.baseColorFactor)){const p=d.baseColorFactor;l.color.setRGB(p[0],p[1],p[2],m.LinearSRGBColorSpace),l.opacity=p[3]}d.baseColorTexture!==void 0&&u.push(t.assignTexture(l,"map",d.baseColorTexture,m.SRGBColorSpace)),l.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,l.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(u.push(t.assignTexture(l,"metalnessMap",d.metallicRoughnessTexture)),u.push(t.assignTexture(l,"roughnessMap",d.metallicRoughnessTexture))),o=this._invokeOne(function(p){return p.getMaterialType&&p.getMaterialType(e)}),u.push(Promise.all(this._invokeAll(function(p){return p.extendMaterialParams&&p.extendMaterialParams(e,l)})))}s.doubleSided===!0&&(l.side=m.DoubleSide);const h=s.alphaMode||nt.OPAQUE;if(h===nt.BLEND?(l.transparent=!0,l.depthWrite=!1):(l.transparent=!1,h===nt.MASK&&(l.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&o!==m.MeshBasicMaterial&&(u.push(t.assignTexture(l,"normalMap",s.normalTexture)),l.normalScale=new m.Vector2(1,1),s.normalTexture.scale!==void 0)){const d=s.normalTexture.scale;l.normalScale.set(d,d)}if(s.occlusionTexture!==void 0&&o!==m.MeshBasicMaterial&&(u.push(t.assignTexture(l,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(l.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&o!==m.MeshBasicMaterial){const d=s.emissiveFactor;l.emissive=new m.Color().setRGB(d[0],d[1],d[2],m.LinearSRGBColorSpace)}return s.emissiveTexture!==void 0&&o!==m.MeshBasicMaterial&&u.push(t.assignTexture(l,"emissiveMap",s.emissiveTexture,m.SRGBColorSpace)),Promise.all(u).then(function(){const d=new o(l);return s.name&&(d.name=s.name),G(d,s),t.associations.set(d,{materials:e}),s.extensions&&ee(r,d,s),d})}createUniqueName(e){const t=m.PropertyBinding.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,r=this.primitiveCache;function s(l){return i[P.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(l,t).then(function(a){return fn(a,l,t)})}const o=[];for(let l=0,a=e.length;l<a;l++){const u=e[l],h=Ns(u),d=r[h];if(d)o.push(d.promise);else{let p;u.extensions&&u.extensions[P.KHR_DRACO_MESH_COMPRESSION]?p=s(u):p=fn(new m.BufferGeometry,u,t),r[h]={primitive:u,promise:p},o.push(p)}}return Promise.all(o)}loadMesh(e){const t=this,i=this.json,r=this.extensions,s=i.meshes[e],o=s.primitives,l=[];for(let a=0,u=o.length;a<u;a++){const h=o[a].material===void 0?Ls(this.cache):this.getDependency("material",o[a].material);l.push(h)}return l.push(t.loadGeometries(o)),Promise.all(l).then(function(a){const u=a.slice(0,a.length-1),h=a[a.length-1],d=[];for(let f=0,g=h.length;f<g;f++){const _=h[f],v=o[f];let y;const A=u[f];if(v.mode===F.TRIANGLES||v.mode===F.TRIANGLE_STRIP||v.mode===F.TRIANGLE_FAN||v.mode===void 0)y=s.isSkinnedMesh===!0?new m.SkinnedMesh(_,A):new m.Mesh(_,A),y.isSkinnedMesh===!0&&y.normalizeSkinWeights(),v.mode===F.TRIANGLE_STRIP?y.geometry=an(y.geometry,m.TriangleStripDrawMode):v.mode===F.TRIANGLE_FAN&&(y.geometry=an(y.geometry,m.TriangleFanDrawMode));else if(v.mode===F.LINES)y=new m.LineSegments(_,A);else if(v.mode===F.LINE_STRIP)y=new m.Line(_,A);else if(v.mode===F.LINE_LOOP)y=new m.LineLoop(_,A);else if(v.mode===F.POINTS)y=new m.Points(_,A);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+v.mode);Object.keys(y.geometry.morphAttributes).length>0&&Es(y,s),y.name=t.createUniqueName(s.name||"mesh_"+e),G(y,s),v.extensions&&ee(r,y,v),t.assignFinalMaterial(y),d.push(y)}for(let f=0,g=d.length;f<g;f++)t.associations.set(d[f],{meshes:e,primitives:f});if(d.length===1)return s.extensions&&ee(r,d[0],s),d[0];const p=new m.Group;s.extensions&&ee(r,p,s),t.associations.set(p,{meshes:e});for(let f=0,g=d.length;f<g;f++)p.add(d[f]);return p})}loadCamera(e){let t;const i=this.json.cameras[e],r=i[i.type];if(!r){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return i.type==="perspective"?t=new m.PerspectiveCamera(m.MathUtils.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):i.type==="orthographic"&&(t=new m.OrthographicCamera(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),G(t,i),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],i=[];for(let r=0,s=t.joints.length;r<s;r++)i.push(this._loadNodeShallow(t.joints[r]));return t.inverseBindMatrices!==void 0?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(r){const s=r.pop(),o=r,l=[],a=[];for(let u=0,h=o.length;u<h;u++){const d=o[u];if(d){l.push(d);const p=new m.Matrix4;s!==null&&p.fromArray(s.array,u*16),a.push(p)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[u])}return new m.Skeleton(l,a)})}loadAnimation(e){const t=this.json,i=this,r=t.animations[e],s=r.name?r.name:"animation_"+e,o=[],l=[],a=[],u=[],h=[];for(let d=0,p=r.channels.length;d<p;d++){const f=r.channels[d],g=r.samplers[f.sampler],_=f.target,v=_.node,y=r.parameters!==void 0?r.parameters[g.input]:g.input,A=r.parameters!==void 0?r.parameters[g.output]:g.output;_.node!==void 0&&(o.push(this.getDependency("node",v)),l.push(this.getDependency("accessor",y)),a.push(this.getDependency("accessor",A)),u.push(g),h.push(_))}return Promise.all([Promise.all(o),Promise.all(l),Promise.all(a),Promise.all(u),Promise.all(h)]).then(function(d){const p=d[0],f=d[1],g=d[2],_=d[3],v=d[4],y=[];for(let A=0,R=p.length;A<R;A++){const x=p[A],S=f[A],T=g[A],w=_[A],E=v[A];if(x===void 0)continue;x.updateMatrix&&x.updateMatrix();const I=i._createAnimationTracks(x,S,T,w,E);if(I)for(let b=0;b<I.length;b++)y.push(I[b])}return new m.AnimationClip(s,void 0,y)})}createNodeMesh(e){const t=this.json,i=this,r=t.nodes[e];return r.mesh===void 0?null:i.getDependency("mesh",r.mesh).then(function(s){const o=i._getNodeRef(i.meshCache,r.mesh,s);return r.weights!==void 0&&o.traverse(function(l){if(l.isMesh)for(let a=0,u=r.weights.length;a<u;a++)l.morphTargetInfluences[a]=r.weights[a]}),o})}loadNode(e){const t=this.json,i=this,r=t.nodes[e],s=i._loadNodeShallow(e),o=[],l=r.children||[];for(let u=0,h=l.length;u<h;u++)o.push(i.getDependency("node",l[u]));const a=r.skin===void 0?Promise.resolve(null):i.getDependency("skin",r.skin);return Promise.all([s,Promise.all(o),a]).then(function(u){const h=u[0],d=u[1],p=u[2];p!==null&&h.traverse(function(f){f.isSkinnedMesh&&f.bind(p,Is)});for(let f=0,g=d.length;f<g;f++)h.add(d[f]);return h})}_loadNodeShallow(e){const t=this.json,i=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const s=t.nodes[e],o=s.name?r.createUniqueName(s.name):"",l=[],a=r._invokeOne(function(u){return u.createNodeMesh&&u.createNodeMesh(e)});return a&&l.push(a),s.camera!==void 0&&l.push(r.getDependency("camera",s.camera).then(function(u){return r._getNodeRef(r.cameraCache,s.camera,u)})),r._invokeAll(function(u){return u.createNodeAttachment&&u.createNodeAttachment(e)}).forEach(function(u){l.push(u)}),this.nodeCache[e]=Promise.all(l).then(function(u){let h;if(s.isBone===!0?h=new m.Bone:u.length>1?h=new m.Group:u.length===1?h=u[0]:h=new m.Object3D,h!==u[0])for(let d=0,p=u.length;d<p;d++)h.add(u[d]);if(s.name&&(h.userData.name=s.name,h.name=o),G(h,s),s.extensions&&ee(i,h,s),s.matrix!==void 0){const d=new m.Matrix4;d.fromArray(s.matrix),h.applyMatrix4(d)}else s.translation!==void 0&&h.position.fromArray(s.translation),s.rotation!==void 0&&h.quaternion.fromArray(s.rotation),s.scale!==void 0&&h.scale.fromArray(s.scale);return r.associations.has(h)||r.associations.set(h,{}),r.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],r=this,s=new m.Group;i.name&&(s.name=r.createUniqueName(i.name)),G(s,i),i.extensions&&ee(t,s,i);const o=i.nodes||[],l=[];for(let a=0,u=o.length;a<u;a++)l.push(r.getDependency("node",o[a]));return Promise.all(l).then(function(a){for(let h=0,d=a.length;h<d;h++)s.add(a[h]);const u=h=>{const d=new Map;for(const[p,f]of r.associations)(p instanceof m.Material||p instanceof m.Texture)&&d.set(p,f);return h.traverse(p=>{const f=r.associations.get(p);f!=null&&d.set(p,f)}),d};return r.associations=u(s),s})}_createAnimationTracks(e,t,i,r,s){const o=[],l=e.name?e.name:e.uuid,a=[];Q[s.path]===Q.weights?e.traverse(function(p){p.morphTargetInfluences&&a.push(p.name?p.name:p.uuid)}):a.push(l);let u;switch(Q[s.path]){case Q.weights:u=m.NumberKeyframeTrack;break;case Q.rotation:u=m.QuaternionKeyframeTrack;break;case Q.position:case Q.scale:u=m.VectorKeyframeTrack;break;default:switch(i.itemSize){case 1:u=m.NumberKeyframeTrack;break;case 2:case 3:default:u=m.VectorKeyframeTrack;break}break}const h=r.interpolation!==void 0?ws[r.interpolation]:m.InterpolateLinear,d=this._getArrayFromAccessor(i);for(let p=0,f=a.length;p<f;p++){const g=new u(a[p]+"."+Q[s.path],t.array,d,h);r.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(g),o.push(g)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const i=rt(t.constructor),r=new Float32Array(t.length);for(let s=0,o=t.length;s<o;s++)r[s]=t[s]*i;t=r}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(i){const r=this instanceof m.QuaternionKeyframeTrack?Ss:hn;return new r(this.times,this.values,this.getValueSize()/3,i)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Os(n,e,t){const i=e.attributes,r=new m.Box3;if(i.POSITION!==void 0){const l=t.json.accessors[i.POSITION],a=l.min,u=l.max;if(a!==void 0&&u!==void 0){if(r.set(new m.Vector3(a[0],a[1],a[2]),new m.Vector3(u[0],u[1],u[2])),l.normalized){const h=rt(oe[l.componentType]);r.min.multiplyScalar(h),r.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const s=e.targets;if(s!==void 0){const l=new m.Vector3,a=new m.Vector3;for(let u=0,h=s.length;u<h;u++){const d=s[u];if(d.POSITION!==void 0){const p=t.json.accessors[d.POSITION],f=p.min,g=p.max;if(f!==void 0&&g!==void 0){if(a.setX(Math.max(Math.abs(f[0]),Math.abs(g[0]))),a.setY(Math.max(Math.abs(f[1]),Math.abs(g[1]))),a.setZ(Math.max(Math.abs(f[2]),Math.abs(g[2]))),p.normalized){const _=rt(oe[p.componentType]);a.multiplyScalar(_)}l.max(a)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(l)}n.boundingBox=r;const o=new m.Sphere;r.getCenter(o.center),o.radius=r.min.distanceTo(r.max)/2,n.boundingSphere=o}function fn(n,e,t){const i=e.attributes,r=[];function s(o,l){return t.getDependency("accessor",o).then(function(a){n.setAttribute(l,a)})}for(const o in i){const l=tt[o]||o.toLowerCase();l in n.attributes||r.push(s(i[o],l))}if(e.indices!==void 0&&!n.index){const o=t.getDependency("accessor",e.indices).then(function(l){n.setIndex(l)});r.push(o)}return m.ColorManagement.workingColorSpace!==m.LinearSRGBColorSpace&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${m.ColorManagement.workingColorSpace}" not supported.`),G(n,e),Os(n,e,t),Promise.all(r).then(function(){return e.targets!==void 0?Ps(n,e.targets,t):n})}const Us="https://cdn.jsdelivr.net/npm/@mymo";class Bs{constructor(){this.cache=new Map}async load(e){const t=this._resolve(e),i=this.cache.get(t);if(i)return i;const s=t.endsWith(".vrm")?await this._loadVRM(t):await this._loadGLB(t);return this.cache.set(t,s),s}_resolve(e){return e.startsWith("http")||e.startsWith("/")||e.endsWith(".glb")||e.endsWith(".vrm")?e:`${Us}/model-${e}/latest/${e}.glb`}async _loadGLB(e){console.warn("[mymo-avatar] GLB support is best-effort. For guaranteed expressions, gestures, lip sync, and blink, use a VRM model.");const t=new ln,i=await this._load(t,e);return this._prepareMeshes(i.scene),{scene:i.scene,animations:i.animations}}async _loadVRM(e){const t=new ln;t.register(s=>new Xr(s));const i=await this._load(t,e),r=i.userData.vrm;return this._prepareMeshes(r.scene),{scene:r.scene,animations:i.animations,vrm:r}}_prepareMeshes(e){e.traverse(t=>{(t instanceof c.Mesh||t instanceof c.SkinnedMesh)&&(t.castShadow=!0,t.receiveShadow=!0,t.morphTargetInfluences&&t.morphTargetInfluences.fill(0))})}_load(e,t){return new Promise((i,r)=>{e.load(t,i,void 0,s=>r(new Error(`Failed to load model: ${t} — ${String(s)}`)))})}clearCache(){this.cache.clear()}}class Vs{constructor(){this.installed=new Map}use(e,t,i){this.installed.has(e.name)||(e.install(t,i),this.installed.set(e.name,e))}has(e){return this.installed.has(e)}}const Ds={"pulse-blue":"rgba(96,165,250,0.7)","pulse-green":"rgba(74,222,128,0.7)","pulse-red":"rgba(248,113,113,0.7)","pulse-orange":"rgba(251,146,60,0.7)"},Fs={model:"maya",position:"bottom-right",size:180,theme:"light",framing:"full",draggable:!1,shadows:!1,idle:!0,idleInterval:8e3,blink:!0,blinkInterval:3500,lipSync:!0,followMouse:!1,autoHide:!1,zIndex:99999,framingConfig:{},themeConfig:{}};class ks{constructor(e={}){this._boundMouseLook=t=>{const i=t.clientX/window.innerWidth*2-1,r=t.clientY/window.innerHeight*2-1;this.animation.lookAt(i,r)},this.options={...Fs,...e},this.events=new ei,this.renderer=new ri,this.animation=new Je,this.audio=new Zr,this.lipSync=new es(this.audio,t=>this.animation.setMouthMorph(t)),this.loader=new Bs,this.plugins=new Vs,this.renderer.setup(this.options),this.renderer.addTickCallback(t=>this.animation.update(t)),this._bindContainerEvents(),this._initialize().catch(t=>console.error("[mymo-avatar]",t))}async _initialize(){try{const e=await this.loader.load(this.options.model);this.renderer.setModel(e.scene),this.animation.init(e),this.options.idle&&this.animation.startIdle(this.options.idleInterval),this.options.blink&&this.animation.startBlink(this.options.blinkInterval),this.options.followMouse&&this._bindMouseLook(),this.events.emit("loaded"),this.events.emit("modelLoaded",{model:this.options.model})}catch(e){console.error("[mymo-avatar] Failed to load model:",e)}}_bindContainerEvents(){this.renderer.getContainer().addEventListener("click",()=>{this.events.emit("click")})}_bindMouseLook(){window.addEventListener("mousemove",this._boundMouseLook)}debugBones(e){return this.renderer.debugBones(e),this}show(){return this.renderer.show(),this}hide(){return this.renderer.hide(),this}destroy(){window.removeEventListener("mousemove",this._boundMouseLook),this.animation.stopLook(),this.animation.dispose(),this.audio.dispose(),this.renderer.dispose(),this.events.removeAllListeners()}move(e,t){return this.renderer.moveTo(e,t),this}position(e){return this.renderer.setPosition(e),this}scale(e){const t=parseInt(this.renderer.getContainer().style.width,10)||this.options.size;return this.renderer.setSize(t*e),this}size(e){return this.renderer.setSize(e),this}frame(e){return this.renderer.setFraming(e),this}setFramingConfig(e){return this.renderer.setFramingConfig(e),this}setTheme(e){return this.renderer.setTheme(e),this}setThemeConfig(e){return this.renderer.setThemeConfig(e),this}expression(e,t=1){return this.animation.setExpression(e,t),this}smile(){return this.expression("smile")}sad(){return this.expression("sad")}happy(){return this.expression("happy")}angry(){return this.expression("angry")}surprised(){return this.expression("surprised")}thinking(){return this.expression("thinking")}confused(){return this.expression("confused")}sleep(){return this.expression("sleep")}idle(){return this.expression("idle")}wave(){return this._gesture("wave")}nod(){return this._gesture("nod")}shakeHead(){return this._gesture("shakeHead")}clap(){return this._gesture("clap")}jump(){return this._gesture("jump")}dance(){return this._gesture("dance")}yes(){return this._gesture("yes")}no(){return this._gesture("no")}thumbsUp(){return this._gesture("thumbsUp")}_gesture(e){return this.events.emit("animationStart",{gesture:e}),this.animation.playGesture(e),this}lookAtMouse(){return this._bindMouseLook(),this}lookAt(e,t){const i=e/window.innerWidth*2-1,r=t/window.innerHeight*2-1;return this.animation.lookAt(i,r),this}lookForward(){return window.removeEventListener("mousemove",this._boundMouseLook),this.animation.lookForward(),this}randomLook(){return this.animation.startRandomLook(),this}async talk(e){return this.events.emit("speechStart"),this.options.lipSync&&this.lipSync.startAutoSync(),await this.audio.play(e),this.options.lipSync&&this.lipSync.stopAutoSync(),this.events.emit("speechEnd"),this}startTalking(){return this.events.emit("speechStart"),this.options.lipSync&&this.lipSync.startAutoSync(),this}stopTalking(){return this.audio.stop(),this.lipSync.stopAutoSync(),this.events.emit("speechEnd"),this}pauseTalking(){return this.audio.pause(),this}setViseme(e){return this.lipSync.setViseme(e),this}setMouth(e){return this.lipSync.setMouth(e),this}setVolume(e){return this.lipSync.setVolume(e),this}setState(e){const t={loading:{expression:"thinking",animation:"Idle",ring:"pulse-blue"},success:{expression:"happy",animation:"Yes",ring:"pulse-green"},error:{expression:"sad",animation:"No",ring:"pulse-red"},warning:{expression:"surprised",animation:"Idle",ring:"pulse-orange"},typing:{expression:"thinking",animation:"Idle",ring:""},listening:{expression:"smile",animation:"Idle",ring:"pulse-blue"},processing:{expression:"thinking",animation:"Idle",ring:"pulse-blue"},complete:{expression:"happy",animation:"ThumbsUp",ring:"pulse-green"}},{expression:i,animation:r,ring:s}=t[e];this.animation.setExpression(i),this.animation.play(r);const o=this.renderer.getContainer();return o.dataset.state=e,o.style.setProperty("--ring-color",s?Ds[s]??"transparent":"transparent"),this.events.emit("animationStart",{state:e}),this}loading(){return this.setState("loading")}success(){return this.setState("success")}error(){return this.setState("error")}warning(){return this.setState("warning")}typing(){return this.setState("typing")}listening(){return this.setState("listening")}processing(){return this.setState("processing")}complete(){return this.setState("complete")}clearState(){this.animation.setExpression("idle"),this.animation.stop();const e=this.renderer.getContainer();return e.dataset.state="",e.style.setProperty("--ring-color","transparent"),this.events.emit("animationEnd"),this}play(e){return this.events.emit("animationStart",{name:e}),this.animation.play(e),this}stop(){return this.animation.stop(),this.events.emit("animationEnd"),this}async load(e){const t=await this.loader.load(e);return this.animation.dispose(),this.renderer.setModel(t.scene),this.animation.init(t),this.options.idle&&this.animation.startIdle(this.options.idleInterval),this.options.blink&&this.animation.startBlink(this.options.blinkInterval),this.events.emit("modelLoaded",{model:e}),this}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}use(e,t){return this.plugins.use(e,this,t),this}}q.Avatar=ks,Object.defineProperty(q,Symbol.toStringTag,{value:"Module"})});
|
|
992
|
+
//# sourceMappingURL=mymo-avatar.umd.js.map
|