11 lines
33 KiB
JavaScript
11 lines
33 KiB
JavaScript
/*! (c) 2019-2025 pixiv Inc. - https://github.com/pixiv/three-vrm/blob/release/LICENSE */
|
|
"use strict";var ze=Object.create;var $=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Ge=(o,e)=>{for(var t in e)$(o,t,{get:e[t],enumerable:!0})},fe=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qe(e))!$e.call(o,r)&&r!==t&&$(o,r,{get:()=>e[r],enumerable:!(n=je(e,r))||n.enumerable});return o};var v=(o,e,t)=>(t=o!=null?ze(Ye(o)):{},fe(e||!o||!o.__esModule?$(t,"default",{value:o,enumerable:!0}):t,o)),Xe=o=>fe($({},"__esModule",{value:!0}),o);var ee=(o,e,t)=>new Promise((n,r)=>{var i=l=>{try{a(t.next(l))}catch(u){r(u)}},s=l=>{try{a(t.throw(l))}catch(u){r(u)}},a=l=>l.done?n(l.value):Promise.resolve(l.value).then(i,s);a((t=t.apply(o,e)).next())});var Mt={};Ge(Mt,{VRMAnimation:()=>z,VRMAnimationLoaderPlugin:()=>J,VRMLookAtQuaternionProxy:()=>S,createVRMAnimationClip:()=>Fe,createVRMAnimationExpressionTracks:()=>de,createVRMAnimationHumanoidTracks:()=>he,createVRMAnimationLookAtTrack:()=>ce});module.exports=Xe(Mt);var Z=v(require("three"),1);var Ae=v(require("three"),1),O=v(require("three"),1),ie=v(require("three"),1),ke=v(require("three"),1),B=v(require("three"),1),D=v(require("three"),1),X=v(require("three"),1),Q=v(require("three"),1),w=v(require("three"),1),Ue=v(require("three"),1),ae=v(require("three"),1),M=v(require("three"),1),le=v(require("three"),1),R=v(require("three"),1),oe=v(require("three"),1),mt=v(require("three"),1);var H=(o,e,t)=>new Promise((n,r)=>{var i=l=>{try{a(t.next(l))}catch(u){r(u)}},s=l=>{try{a(t.throw(l))}catch(u){r(u)}},a=l=>l.done?n(l.value):Promise.resolve(l.value).then(i,s);a((t=t.apply(o,e)).next())}),ge=class extends Ae.Object3D{constructor(o){super(),this.weight=0,this.isBinary=!1,this.overrideBlink="none",this.overrideLookAt="none",this.overrideMouth="none",this._binds=[],this.name=`VRMExpression_${o}`,this.expressionName=o,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(o){this._binds.push(o)}deleteBind(o){let e=this._binds.indexOf(o);e>=0&&this._binds.splice(e,1)}applyWeight(o){var e;let t=this.outputWeight;t*=(e=o==null?void 0:o.multiplier)!=null?e:1,this.isBinary&&t<1&&(t=0),this._binds.forEach(n=>n.applyWeight(t))}clearAppliedWeight(){this._binds.forEach(o=>o.clearAppliedWeight())}};function Ke(o,e,t){var n,r;let i=o.parser.json,s=(n=i.nodes)==null?void 0:n[e];if(s==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${e}] of glTF but the node doesn't exist`),null;let a=s.mesh;if(a==null)return null;let l=(r=i.meshes)==null?void 0:r[a];if(l==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${a}] of glTF but the mesh doesn't exist`),null;let u=l.primitives.length,d=[];return t.traverse(f=>{d.length<u&&f.isMesh&&d.push(f)}),d}function Re(o,e){return H(this,null,function*(){let t=yield o.parser.getDependency("node",e);return Ke(o,e,t)})}var q={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 Ze(o){return Math.max(Math.min(o,1),0)}var Ee=class Le{constructor(){this.blinkExpressionNames=["blink","blinkLeft","blinkRight"],this.lookAtExpressionNames=["lookLeft","lookRight","lookUp","lookDown"],this.mouthExpressionNames=["aa","ee","ih","oh","ou"],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){let e={},t=new Set(Object.values(q));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)&&(e[n]=r)}),e}get customExpressionMap(){let e={},t=new Set(Object.values(q));return Object.entries(this._expressionMap).forEach(([n,r])=>{t.has(n)||(e[n]=r)}),e}copy(e){return this._expressions.concat().forEach(n=>{this.unregisterExpression(n)}),e._expressions.forEach(n=>{this.registerExpression(n)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new Le().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){let 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;let n=this.getExpression(e);return(t=n==null?void 0:n.weight)!=null?t:null}setValue(e,t){let n=this.getExpression(e);n&&(n.weight=Ze(t))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){let t=this.getExpression(e);return t?`${t.name}.weight`:null}update(){let e=this._calculateWeightMultipliers();this._expressions.forEach(t=>{t.clearAppliedWeight()}),this._expressions.forEach(t=>{let n=1,r=t.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(n*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(n*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(n*=e.mouth),t.applyWeight({multiplier:n})})}_calculateWeightMultipliers(){let e=1,t=1,n=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,t-=r.overrideLookAtAmount,n-=r.overrideMouthAmount}),e=Math.max(0,e),t=Math.max(0,t),n=Math.max(0,n),{blink:e,lookAt:t,mouth:n}}},j={Color:"color",EmissionColor:"emissionColor",ShadeColor:"shadeColor",MatcapColor:"matcapColor",RimColor:"rimColor",OutlineColor:"outlineColor"},Je={_Color:j.Color,_EmissionColor:j.EmissionColor,_ShadeColor:j.ShadeColor,_RimColor:j.RimColor,_OutlineColor:j.OutlineColor},et=new ie.Color,Ve=class He{constructor({material:e,type:t,targetValue:n,targetAlpha:r}){this.material=e,this.type=t,this.targetValue=n,this.targetAlpha=r!=null?r:1;let i=this._initColorBindState(),s=this._initAlphaBindState();this._state={color:i,alpha:s}}applyWeight(e){let{color:t,alpha:n}=this._state;if(t!=null){let{propertyName:r,deltaValue:i}=t,s=this.material[r];s!=null&&s.add(et.copy(i).multiplyScalar(e))}if(n!=null){let{propertyName:r,deltaValue:i}=n;this.material[r]!=null&&(this.material[r]+=i*e)}}clearAppliedWeight(){let{color:e,alpha:t}=this._state;if(e!=null){let{propertyName:n,initialValue:r}=e,i=this.material[n];i!=null&&i.copy(r)}if(t!=null){let{propertyName:n,initialValue:r}=t;this.material[n]!=null&&(this.material[n]=r)}}_initColorBindState(){var e,t,n;let{material:r,type:i,targetValue:s}=this,a=this._getPropertyNameMap(),l=(t=(e=a==null?void 0:a[i])==null?void 0:e[0])!=null?t:null;if(l==null)return console.warn(`Tried to add a material color bind to the material ${(n=r.name)!=null?n:"(no name)"}, the type ${i} but the material or the type is not supported.`),null;let d=r[l].clone(),f=new ie.Color(s.r-d.r,s.g-d.g,s.b-d.b);return{propertyName:l,initialValue:d,deltaValue:f}}_initAlphaBindState(){var e,t,n;let{material:r,type:i,targetAlpha:s}=this,a=this._getPropertyNameMap(),l=(t=(e=a==null?void 0:a[i])==null?void 0:e[1])!=null?t:null;if(l==null&&s!==1)return console.warn(`Tried to add a material alpha bind to the material ${(n=r.name)!=null?n:"(no name)"}, the type ${i} but the material or the type does not support alpha.`),null;if(l==null)return null;let u=r[l],d=s-u;return{propertyName:l,initialValue:u,deltaValue:d}}_getPropertyNameMap(){var e,t;return(t=(e=Object.entries(He._propertyNameMapMap).find(([n])=>this.material[n]===!0))==null?void 0:e[1])!=null?t:null}};Ve._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 Me=Ve,_e=class{constructor({primitives:o,index:e,weight:t}){this.primitives=o,this.index=e,this.weight=t}applyWeight(o){this.primitives.forEach(e=>{var t;((t=e.morphTargetInfluences)==null?void 0:t[this.index])!=null&&(e.morphTargetInfluences[this.index]+=this.weight*o)})}clearAppliedWeight(){this.primitives.forEach(o=>{var e;((e=o.morphTargetInfluences)==null?void 0:e[this.index])!=null&&(o.morphTargetInfluences[this.index]=0)})}},ye=new ke.Vector2,be=class Be{constructor({material:e,scale:t,offset:n}){var r,i;this.material=e,this.scale=t,this.offset=n;let s=(r=Object.entries(Be._propertyNamesMap).find(([a])=>e[a]===!0))==null?void 0:r[1];s==null?(console.warn(`Tried to add a texture transform bind to the material ${(i=e.name)!=null?i:"(no name)"} but the material is not supported.`),this._properties=[]):(this._properties=[],s.forEach(a=>{var l;let u=(l=e[a])==null?void 0:l.clone();if(!u)return null;e[a]=u;let d=u.offset.clone(),f=u.repeat.clone(),m=n.clone().sub(d),p=t.clone().sub(f);this._properties.push({name:a,initialOffset:d,deltaOffset:m,initialScale:f,deltaScale:p})}))}applyWeight(e){this._properties.forEach(t=>{let n=this.material[t.name];n!==void 0&&(n.offset.add(ye.copy(t.deltaOffset).multiplyScalar(e)),n.repeat.add(ye.copy(t.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{let t=this.material[e.name];t!==void 0&&(t.offset.copy(e.initialOffset),t.repeat.copy(e.initialScale))})}};be._propertyNamesMap={isMeshStandardMaterial:["map","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap"],isMeshBasicMaterial:["map","specularMap","alphaMap"],isMToonMaterial:["map","normalMap","emissiveMap","shadeMultiplyTexture","rimMultiplyTexture","outlineWidthMultiplyTexture","uvAnimationMaskTexture"]};var ve=be,tt=new Set(["1.0","1.0-beta"]),nt=class Ie{get name(){return"VRMExpressionLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return H(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return H(this,null,function*(){let t=yield this._v1Import(e);if(t)return t;let n=yield this._v0Import(e);return n||null})}_v1Import(e){return H(this,null,function*(){var t,n;let r=this.parser.json;if(!(((t=r.extensionsUsed)==null?void 0:t.indexOf("VRMC_vrm"))!==-1))return null;let s=(n=r.extensions)==null?void 0:n.VRMC_vrm;if(!s)return null;let a=s.specVersion;if(!tt.has(a))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${a}"`),null;let l=s.expressions;if(!l)return null;let u=new Set(Object.values(q)),d=new Map;l.preset!=null&&Object.entries(l.preset).forEach(([m,p])=>{if(p!=null){if(!u.has(m)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${m}" detected. Ignoring the expression`);return}d.set(m,p)}}),l.custom!=null&&Object.entries(l.custom).forEach(([m,p])=>{if(u.has(m)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${m}". Ignoring the expression`);return}d.set(m,p)});let f=new Ee;return yield Promise.all(Array.from(d.entries()).map(m=>H(this,[m],function*([p,c]){var h,g,_,E,y,x,P;let T=new ge(p);if(e.scene.add(T),T.isBinary=(h=c.isBinary)!=null?h:!1,T.overrideBlink=(g=c.overrideBlink)!=null?g:"none",T.overrideLookAt=(_=c.overrideLookAt)!=null?_:"none",T.overrideMouth=(E=c.overrideMouth)!=null?E:"none",(y=c.morphTargetBinds)==null||y.forEach(A=>H(this,null,function*(){var L;if(A.node===void 0||A.index===void 0)return;let U=yield Re(e,A.node),k=A.index;if(!U.every(b=>Array.isArray(b.morphTargetInfluences)&&k<b.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${c.name} attempts to index morph #${k} but not found.`);return}T.addBind(new _e({primitives:U,index:k,weight:(L=A.weight)!=null?L:1}))})),c.materialColorBinds||c.textureTransformBinds){let A=[];e.scene.traverse(L=>{let U=L.material;U&&(Array.isArray(U)?A.push(...U):A.push(U))}),(x=c.materialColorBinds)==null||x.forEach(L=>H(this,null,function*(){A.filter(k=>{var b;let C=(b=this.parser.associations.get(k))==null?void 0:b.materials;return L.material===C}).forEach(k=>{T.addBind(new Me({material:k,type:L.type,targetValue:new O.Color().fromArray(L.targetValue),targetAlpha:L.targetValue[3]}))})})),(P=c.textureTransformBinds)==null||P.forEach(L=>H(this,null,function*(){A.filter(k=>{var b;let C=(b=this.parser.associations.get(k))==null?void 0:b.materials;return L.material===C}).forEach(k=>{var b,C;T.addBind(new ve({material:k,offset:new O.Vector2().fromArray((b=L.offset)!=null?b:[0,0]),scale:new O.Vector2().fromArray((C=L.scale)!=null?C:[1,1])}))})}))}f.registerExpression(T)}))),f})}_v0Import(e){return H(this,null,function*(){var t;let n=this.parser.json,r=(t=n.extensions)==null?void 0:t.VRM;if(!r)return null;let i=r.blendShapeMaster;if(!i)return null;let s=new Ee,a=i.blendShapeGroups;if(!a)return s;let l=new Set;return yield Promise.all(a.map(u=>H(this,null,function*(){var d;let f=u.presetName,m=f!=null&&Ie.v0v1PresetNameMap[f]||null,p=m!=null?m:u.name;if(p==null){console.warn("VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression");return}if(l.has(p)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${f} has duplicated entries. Ignoring the expression`);return}l.add(p);let c=new ge(p);e.scene.add(c),c.isBinary=(d=u.isBinary)!=null?d:!1,u.binds&&u.binds.forEach(g=>H(this,null,function*(){var _;if(g.mesh===void 0||g.index===void 0)return;let E=[];(_=n.nodes)==null||_.forEach((x,P)=>{x.mesh===g.mesh&&E.push(P)});let y=g.index;yield Promise.all(E.map(x=>H(this,null,function*(){var P;let T=yield Re(e,x);if(!T.every(A=>Array.isArray(A.morphTargetInfluences)&&y<A.morphTargetInfluences.length)){console.warn(`VRMExpressionLoaderPlugin: ${u.name} attempts to index ${y}th morph but not found.`);return}c.addBind(new _e({primitives:T,index:y,weight:.01*((P=g.weight)!=null?P:100)}))})))}));let h=u.materialValues;h&&h.length!==0&&h.forEach(g=>{if(g.materialName===void 0||g.propertyName===void 0||g.targetValue===void 0)return;let _=[];e.scene.traverse(y=>{if(y.material){let x=y.material;Array.isArray(x)?_.push(...x.filter(P=>(P.name===g.materialName||P.name===g.materialName+" (Outline)")&&_.indexOf(P)===-1)):x.name===g.materialName&&_.indexOf(x)===-1&&_.push(x)}});let E=g.propertyName;_.forEach(y=>{if(E==="_MainTex_ST"){let P=new O.Vector2(g.targetValue[0],g.targetValue[1]),T=new O.Vector2(g.targetValue[2],g.targetValue[3]);T.y=1-T.y-P.y,c.addBind(new ve({material:y,scale:P,offset:T}));return}let x=Je[E];if(x){c.addBind(new Me({material:y,type:x,targetValue:new O.Color().fromArray(g.targetValue),targetAlpha:g.targetValue[3]}));return}console.warn(E+" is not supported")})}),s.registerExpression(c)}))),s})}};nt.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 Ne=class W{constructor(e,t){this._firstPersonOnlyLayer=W.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=W.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 W(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:e=W.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=W.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||(this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=t,this.meshAnnotations.forEach(n=>{n.meshes.forEach(r=>{n.type==="firstPersonOnly"?(r.layers.set(this._firstPersonOnlyLayer),r.traverse(i=>i.layers.set(this._firstPersonOnlyLayer))):n.type==="thirdPersonOnly"?(r.layers.set(this._thirdPersonOnlyLayer),r.traverse(i=>i.layers.set(this._thirdPersonOnlyLayer))):n.type==="auto"&&this._createHeadlessModel(r)})}),this._initializedLayers=!0)}_excludeTriangles(e,t,n,r){let i=0;if(t!=null&&t.length>0)for(let s=0;s<e.length;s+=3){let a=e[s],l=e[s+1],u=e[s+2],d=t[a],f=n[a];if(d[0]>0&&r.includes(f[0])||d[1]>0&&r.includes(f[1])||d[2]>0&&r.includes(f[2])||d[3]>0&&r.includes(f[3]))continue;let m=t[l],p=n[l];if(m[0]>0&&r.includes(p[0])||m[1]>0&&r.includes(p[1])||m[2]>0&&r.includes(p[2])||m[3]>0&&r.includes(p[3]))continue;let c=t[u],h=n[u];c[0]>0&&r.includes(h[0])||c[1]>0&&r.includes(h[1])||c[2]>0&&r.includes(h[2])||c[3]>0&&r.includes(h[3])||(e[i++]=a,e[i++]=l,e[i++]=u)}return i}_createErasedMesh(e,t){let n=new B.SkinnedMesh(e.geometry.clone(),e.material);n.name=`${e.name}(erase)`,n.frustumCulled=e.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);let r=n.geometry,i=r.getAttribute("skinIndex"),s=i instanceof B.GLBufferAttribute?[]:i.array,a=[];for(let h=0;h<s.length;h+=4)a.push([s[h],s[h+1],s[h+2],s[h+3]]);let l=r.getAttribute("skinWeight"),u=l instanceof B.GLBufferAttribute?[]:l.array,d=[];for(let h=0;h<u.length;h+=4)d.push([u[h],u[h+1],u[h+2],u[h+3]]);let f=r.getIndex();if(!f)throw new Error("The geometry doesn't have an index buffer");let m=Array.from(f.array),p=this._excludeTriangles(m,d,a,t),c=[];for(let h=0;h<p;h++)c[h]=m[h];return r.setIndex(c),e.onBeforeRender&&(n.onBeforeRender=e.onBeforeRender),n.bind(new B.Skeleton(e.skeleton.bones,e.skeleton.boneInverses),new B.Matrix4),n}_createHeadlessModelForSkinnedMesh(e,t){let n=[];if(t.skeleton.bones.forEach((i,s)=>{this._isEraseTarget(i)&&n.push(s)}),!n.length){t.layers.enable(this._thirdPersonOnlyLayer),t.layers.enable(this._firstPersonOnlyLayer);return}t.layers.set(this._thirdPersonOnlyLayer);let r=this._createErasedMesh(t,n);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{let t=new B.Group;t.name=`_headless_${e.name}`,t.layers.set(this._firstPersonOnlyLayer),e.parent.add(t),e.children.filter(n=>n.type==="SkinnedMesh").forEach(n=>{let r=n;this._createHeadlessModelForSkinnedMesh(t,r)})}else if(e.type==="SkinnedMesh"){let 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}};Ne.DEFAULT_FIRSTPERSON_ONLY_LAYER=9;Ne.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var yt=new D.Vector3,vt=new D.Vector3,xt=new D.Quaternion;var se={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 rt(o){return o.invert?o.invert():o.inverse(),o}var Tt=new X.Vector3,wt=new X.Quaternion;var Pt=new Q.Vector3,At=new Q.Quaternion,Lt=new Q.Vector3;var Vt=new w.Quaternion,Ht=new w.Quaternion,kt=new w.Vector3,bt=new w.Vector3,xe=Math.sqrt(2)/2,Bt=new w.Quaternion(0,0,-xe,xe),It=new w.Vector3(0,1,0);var ot=new le.Vector3,it=new le.Vector3;function re(o,e){return o.matrixWorld.decompose(ot,e,it),e}function G(o){return[Math.atan2(-o.z,o.x),Math.atan2(o.y,Math.sqrt(o.x*o.x+o.z*o.z))]}function Te(o){let e=Math.round(o/2/Math.PI);return o-2*Math.PI*e}var we=new M.Vector3(0,0,1),st=new M.Vector3,at=new M.Vector3,lt=new M.Vector3,ut=new M.Quaternion,te=new M.Quaternion,Pe=new M.Quaternion,ht=new M.Quaternion,ne=new M.Euler,Oe=class De{constructor(e,t){this.offsetFromHeadBone=new M.Vector3,this.autoUpdate=!0,this.faceFront=new M.Vector3(0,0,1),this.humanoid=e,this.applier=t,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new M.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 M.Euler)}getEuler(e){return e.set(M.MathUtils.DEG2RAD*this._pitch,M.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 De(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){let t=this.humanoid.getRawBoneNode("head");return e.copy(this.offsetFromHeadBone).applyMatrix4(t.matrixWorld)}getLookAtWorldQuaternion(e){let t=this.humanoid.getRawBoneNode("head");return re(t,e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(we)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[t,n]=G(this.faceFront);return ne.set(0,.5*Math.PI+t,n,"YZX"),e.setFromEuler(ne).premultiply(ht.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(te),this.getFaceFrontQuaternion(Pe),e.copy(we).applyQuaternion(te).applyQuaternion(Pe).applyEuler(this.getEuler(ne))}lookAt(e){let t=ut.copy(this._restHeadWorldQuaternion).multiply(rt(this.getLookAtWorldQuaternion(te))),n=this.getLookAtWorldPosition(at),r=lt.copy(e).sub(n).applyQuaternion(t).normalize(),[i,s]=G(this.faceFront),[a,l]=G(r),u=Te(a-i),d=Te(s-l);this._yaw=M.MathUtils.RAD2DEG*u,this._pitch=M.MathUtils.RAD2DEG*d,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(st)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};Oe.EULER_ORDER="YXZ";var Se=Oe,dt=new R.Vector3(0,0,1),N=new R.Quaternion,F=new R.Quaternion,V=new R.Euler(0,0,0,"YXZ"),ct=class{constructor(o,e,t,n,r){this.humanoid=o,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=t,this.rangeMapVerticalDown=n,this.rangeMapVerticalUp=r,this.faceFront=new R.Vector3(0,0,1),this._restQuatLeftEye=new R.Quaternion,this._restQuatRightEye=new R.Quaternion,this._restLeftEyeParentWorldQuat=new R.Quaternion,this._restRightEyeParentWorldQuat=new R.Quaternion;let i=this.humanoid.getRawBoneNode("leftEye"),s=this.humanoid.getRawBoneNode("rightEye");i&&(this._restQuatLeftEye.copy(i.quaternion),re(i.parent,this._restLeftEyeParentWorldQuat)),s&&(this._restQuatRightEye.copy(s.quaternion),re(s.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(o,e){let t=this.humanoid.getRawBoneNode("leftEye"),n=this.humanoid.getRawBoneNode("rightEye"),r=this.humanoid.getNormalizedBoneNode("leftEye"),i=this.humanoid.getNormalizedBoneNode("rightEye");t&&(e<0?V.x=-R.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-e):V.x=R.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(e),o<0?V.y=-R.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(-o):V.y=R.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(o),N.setFromEuler(V),this._getWorldFaceFrontQuat(F),r.quaternion.copy(F).multiply(N).multiply(F.invert()),N.copy(this._restLeftEyeParentWorldQuat),t.quaternion.copy(r.quaternion).multiply(N).premultiply(N.invert()).multiply(this._restQuatLeftEye)),n&&(e<0?V.x=-R.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-e):V.x=R.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(e),o<0?V.y=-R.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(-o):V.y=R.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(o),N.setFromEuler(V),this._getWorldFaceFrontQuat(F),i.quaternion.copy(F).multiply(N).multiply(F.invert()),N.copy(this._restRightEyeParentWorldQuat),n.quaternion.copy(i.quaternion).multiply(N).premultiply(N.invert()).multiply(this._restQuatRightEye))}lookAt(o){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");let e=R.MathUtils.RAD2DEG*o.y,t=R.MathUtils.RAD2DEG*o.x;this.applyYawPitch(e,t)}_getWorldFaceFrontQuat(o){if(this.faceFront.distanceToSquared(dt)<.01)return o.identity();let[e,t]=G(this.faceFront);return V.set(0,.5*Math.PI+e,t,"YZX"),o.setFromEuler(V)}};ct.type="bone";var pt=class{constructor(o,e,t,n,r){this.expressions=o,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=t,this.rangeMapVerticalDown=n,this.rangeMapVerticalUp=r}applyYawPitch(o,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))),o<0?(this.expressions.setValue("lookLeft",0),this.expressions.setValue("lookRight",this.rangeMapHorizontalOuter.map(-o))):(this.expressions.setValue("lookRight",0),this.expressions.setValue("lookLeft",this.rangeMapHorizontalOuter.map(o)))}lookAt(o){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");let e=oe.MathUtils.RAD2DEG*o.y,t=oe.MathUtils.RAD2DEG*o.x;this.applyYawPitch(e,t)}};pt.type="expression";var K=v(require("three"),1),Ce=180/Math.PI,ue=new K.Euler,S=class extends K.Object3D{constructor(e){super(),this.vrmLookAt=e,this.type="VRMLookAtQuaternionProxy";let t=this.rotation._onChangeCallback;this.rotation._onChange(()=>{t(),this._applyToLookAt()});let n=this.quaternion._onChangeCallback;this.quaternion._onChange(()=>{n(),this._applyToLookAt()})}_applyToLookAt(){ue.setFromQuaternion(this.quaternion,Se.EULER_ORDER),this.vrmLookAt.yaw=Ce*ue.y,this.vrmLookAt.pitch=Ce*ue.x}};function he(o,e,t){var i,s;let n=new Map,r=new Map;for(let[a,l]of o.humanoidTracks.rotation.entries()){let u=(i=e.getNormalizedBoneNode(a))==null?void 0:i.name;if(u!=null){let d=new Z.QuaternionKeyframeTrack(`${u}.quaternion`,l.times,l.values.map((f,m)=>t==="0"&&m%2===0?-f:f));r.set(a,d)}}for(let[a,l]of o.humanoidTracks.translation.entries()){let u=(s=e.getNormalizedBoneNode(a))==null?void 0:s.name;if(u!=null){let d=o.restHipsPosition.y,m=e.normalizedRestPose.hips.position[1]/d,p=l.clone();p.values=p.values.map((c,h)=>(t==="0"&&h%3!==1?-c:c)*m),p.name=`${u}.position`,n.set(a,p)}}return{translation:n,rotation:r}}function de(o,e){let t=new Map,n=new Map;for(let[r,i]of o.expressionTracks.preset.entries()){let s=e.getExpressionTrackName(r);if(s!=null){let a=i.clone();a.name=s,t.set(r,a)}}for(let[r,i]of o.expressionTracks.custom.entries()){let s=e.getExpressionTrackName(r);if(s!=null){let a=i.clone();a.name=s,n.set(r,a)}}return{preset:t,custom:n}}function ce(o,e){if(o.lookAtTrack==null)return null;let t=o.lookAtTrack.clone();return t.name=e,t}function Fe(o,e){let t=[],n=he(o,e.humanoid,e.meta.metaVersion);if(t.push(...n.translation.values()),t.push(...n.rotation.values()),e.expressionManager!=null){let r=de(o,e.expressionManager);t.push(...r.preset.values()),t.push(...r.custom.values())}if(e.lookAt!=null){let r=e.scene.children.find(s=>s instanceof S);r==null?(console.warn("createVRMAnimationClip: VRMLookAtQuaternionProxy is not found. Creating a new one automatically. To suppress this warning, create a VRMLookAtQuaternionProxy manually"),r=new S(e.lookAt),r.name="VRMLookAtQuaternionProxy",e.scene.add(r)):r.name===""&&(console.warn("createVRMAnimationClip: VRMLookAtQuaternionProxy is found but its name is not set. Setting the name automatically. To suppress this warning, set the name manually"),r.name="VRMLookAtQuaternionProxy");let i=ce(o,`${r.name}.quaternion`);i!=null&&t.push(i)}return new Z.AnimationClip("Clip",o.duration,t)}var We=v(require("three"),1),z=class{constructor(){this.duration=0,this.restHipsPosition=new We.Vector3,this.humanoidTracks={translation:new Map,rotation:new Map},this.expressionTracks={preset:new Map,custom:new Map},this.lookAtTrack=null}};var I=v(require("three"),1);function pe(o,e){let t=o.length,n=[],r=[],i=0;for(let s=0;s<t;s++){let a=o[s];i<=0&&(i=e,r=[],n.push(r)),r.push(a),i--}return n}var ft=new I.Matrix4,Y=new I.Vector3,me=new I.Quaternion,Qe=new I.Quaternion,gt=new I.Quaternion,Rt=new Set(["1.0","1.0-draft"]),Et=new Set(Object.values(q)),J=class{constructor(e){this.parser=e}get name(){return"VRMC_vrm_animation"}afterRoot(e){return ee(this,null,function*(){var p,c,h;let t=e.parser.json,n=t.extensionsUsed;if(n==null||n.indexOf(this.name)==-1)return;let r=(p=t.extensions)==null?void 0:p[this.name];if(r==null)return;let i=r.specVersion;if(i==null)console.warn("VRMAnimationLoaderPlugin: specVersion of the VRMA is not defined. Consider updating the animation file. Assuming the spec version is 1.0.");else{if(!Rt.has(i)){console.warn(`VRMAnimationLoaderPlugin: Unknown VRMC_vrm_animation spec version: ${i}`);return}i==="1.0-draft"&&console.warn("VRMAnimationLoaderPlugin: Using a draft spec version: 1.0-draft. Some behaviors may be different. Consider updating the animation file.")}let s=this._createNodeMap(r),a=yield this._createBoneWorldMatrixMap(e,r),l=(h=(c=r.humanoid)==null?void 0:c.humanBones.hips)==null?void 0:h.node,u=l!=null?yield e.parser.getDependency("node",l):null,d=new I.Vector3;u==null||u.getWorldPosition(d),d.y<.001&&console.warn("VRMAnimationLoaderPlugin: The loaded VRM Animation might violate the VRM T-pose (The y component of the rest hips position is approximately zero or below.)");let m=e.animations.map((g,_)=>{let E=t.animations[_],y=this._parseAnimation(g,E,s,a);return y.restHipsPosition=d,y});e.userData.vrmAnimations=m})}_createNodeMap(e){var l,u,d,f,m;let t=new Map,n=new Map,r=(l=e.humanoid)==null?void 0:l.humanBones;r&&Object.entries(r).forEach(([p,c])=>{let h=c==null?void 0:c.node;h!=null&&t.set(h,p)});let i=(u=e.expressions)==null?void 0:u.preset;i&&Object.entries(i).forEach(([p,c])=>{let h=c==null?void 0:c.node;h!=null&&n.set(h,p)});let s=(d=e.expressions)==null?void 0:d.custom;s&&Object.entries(s).forEach(([p,c])=>{let{node:h}=c;n.set(h,p)});let a=(m=(f=e.lookAt)==null?void 0:f.node)!=null?m:null;return{humanoidIndexToName:t,expressionsIndexToName:n,lookAtIndex:a}}_createBoneWorldMatrixMap(e,t){return ee(this,null,function*(){var i,s;e.scene.updateWorldMatrix(!1,!0);let n=yield e.parser.getDependencies("node"),r=new Map;if(t.humanoid==null)return r;for(let[a,l]of Object.entries(t.humanoid.humanBones)){let u=l==null?void 0:l.node;if(u!=null){let d=n[u];r.set(a,d.matrixWorld),a==="hips"&&r.set("hipsParent",(s=(i=d.parent)==null?void 0:i.matrixWorld)!=null?s:ft)}}return r})}_parseAnimation(e,t,n,r){let i=e.tracks,s=t.channels,a=new z;return a.duration=e.duration,s.forEach((l,u)=>{let{node:d,path:f}=l.target,m=i[u];if(d==null)return;let p=n.humanoidIndexToName.get(d);if(p!=null){let h=se[p];for(;h!=null&&r.get(h)==null;)h=se[h];if(h==null&&(h="hipsParent"),f==="translation")if(p!=="hips")console.warn(`The loading animation contains a translation track for ${p}, which is not permitted in the VRMC_vrm_animation spec. ignoring the track`);else{let g=r.get("hipsParent"),_=pe(m.values,3).flatMap(y=>Y.fromArray(y).applyMatrix4(g).toArray()),E=m.clone();E.values=new Float32Array(_),a.humanoidTracks.translation.set(p,E)}else if(f==="rotation"){let g=r.get(p),_=r.get(h);g.decompose(Y,me,Y),me.invert(),_.decompose(Y,Qe,Y);let E=pe(m.values,4).flatMap(x=>gt.fromArray(x).premultiply(Qe).multiply(me).toArray()),y=m.clone();y.values=new Float32Array(E),a.humanoidTracks.rotation.set(p,y)}else throw new Error(`Invalid path "${f}"`);return}let c=n.expressionsIndexToName.get(d);if(c!=null){if(f==="translation"){let h=m.times,g=new Float32Array(m.values.length/3);for(let E=0;E<g.length;E++)g[E]=m.values[3*E];let _=new I.NumberKeyframeTrack(`${c}.weight`,h,g);Et.has(c)?a.expressionTracks.preset.set(c,_):a.expressionTracks.custom.set(c,_)}else throw new Error(`Invalid path "${f}"`);return}if(d===n.lookAtIndex)if(f==="rotation")a.lookAtTrack=m;else throw new Error(`Invalid path "${f}"`)}),a}};
|
|
/*!
|
|
* @pixiv/three-vrm-core v3.4.1
|
|
* The implementation of core features of VRM, for @pixiv/three-vrm
|
|
*
|
|
* Copyright (c) 2019-2025 pixiv Inc.
|
|
* @pixiv/three-vrm-core is distributed under MIT License
|
|
* https://github.com/pixiv/three-vrm/blob/release/LICENSE
|
|
*/
|