@pixiv/three-vrm 0.6.8 → 0.6.11
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/lib/three-vrm.js +58 -26
- package/lib/three-vrm.min.js +1 -1
- package/lib/three-vrm.module.js +58 -26
- package/lib/three-vrm.module.min.js +1 -1
- package/package.json +6 -6
- package/ts3.4/types/VRM.d.ts +1 -1
- package/ts3.4/types/VRMImporter.d.ts +1 -1
- package/ts3.4/types/blendshape/VRMBlendShapeImporter.d.ts +1 -1
- package/ts3.4/types/debug/VRMDebug.d.ts +1 -1
- package/ts3.4/types/debug/VRMImporterDebug.d.ts +1 -1
- package/ts3.4/types/debug/VRMLookAtImporterDebug.d.ts +1 -1
- package/ts3.4/types/debug/VRMSpringBoneImporterDebug.d.ts +1 -1
- package/ts3.4/types/firstperson/VRMFirstPersonImporter.d.ts +1 -1
- package/ts3.4/types/humanoid/VRMHumanoidImporter.d.ts +1 -1
- package/ts3.4/types/lookat/VRMLookAtImporter.d.ts +1 -1
- package/ts3.4/types/material/VRMMaterialImporter.d.ts +1 -1
- package/ts3.4/types/material/getTexelDecodingFunction.d.ts +4 -0
- package/ts3.4/types/meta/VRMMetaImporter.d.ts +1 -1
- package/ts3.4/types/springbone/VRMSpringBoneImporter.d.ts +1 -1
- package/ts3.4/types/springbone/VRMSpringBoneManager.d.ts +7 -0
- package/ts3.4/types/utils/gltfExtractPrimitivesFromNode.d.ts +1 -1
- package/types/VRM.d.ts +1 -1
- package/types/VRMImporter.d.ts +1 -1
- package/types/blendshape/VRMBlendShapeImporter.d.ts +1 -1
- package/types/debug/VRMDebug.d.ts +1 -1
- package/types/debug/VRMImporterDebug.d.ts +1 -1
- package/types/debug/VRMLookAtImporterDebug.d.ts +1 -1
- package/types/debug/VRMSpringBoneImporterDebug.d.ts +1 -1
- package/types/firstperson/VRMFirstPersonImporter.d.ts +1 -1
- package/types/humanoid/VRMHumanoidImporter.d.ts +1 -1
- package/types/lookat/VRMLookAtImporter.d.ts +1 -1
- package/types/material/VRMMaterialImporter.d.ts +1 -1
- package/types/material/getTexelDecodingFunction.d.ts +4 -0
- package/types/meta/VRMMetaImporter.d.ts +1 -1
- package/types/springbone/VRMSpringBoneImporter.d.ts +1 -1
- package/types/springbone/VRMSpringBoneManager.d.ts +7 -0
- package/types/utils/gltfExtractPrimitivesFromNode.d.ts +1 -1
package/lib/three-vrm.min.js
CHANGED
|
@@ -13,4 +13,4 @@
|
|
|
13
13
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
14
14
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
15
15
|
PERFORMANCE OF THIS SOFTWARE.
|
|
16
|
-
***************************************************************************** */function o(e,t,n,i){return new(n||(n=Promise))((function(r,o){function a(e){try{l(i.next(e))}catch(e){o(e)}}function s(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}l((i=i.apply(e,t||[])).next())}))}function a(e){Object.keys(e).forEach((t=>{const n=e[t];if(null==n?void 0:n.isTexture){n.dispose()}})),e.dispose()}function s(e){const t=e.geometry;t&&t.dispose();const n=e.material;n&&(Array.isArray(n)?n.forEach((e=>a(e))):n&&a(n))}!function(e){e[e.NUMBER=0]="NUMBER",e[e.VECTOR2=1]="VECTOR2",e[e.VECTOR3=2]="VECTOR3",e[e.VECTOR4=3]="VECTOR4",e[e.COLOR=4]="COLOR"}(i||(i={}));const l=new r.Vector2,d=new r.Vector3,h=new r.Vector4,u=new r.Color;class c extends r.Object3D{constructor(e){super(),this.weight=0,this.isBinary=!1,this._binds=[],this._materialValues=[],this.name=`BlendShapeController_${e}`,this.type="BlendShapeController",this.visible=!1}addBind(e){const t=e.weight/100;this._binds.push({meshes:e.meshes,morphTargetIndex:e.morphTargetIndex,weight:t})}addMaterialValue(e){const t=e.material,n=e.propertyName;let o,a,s,l,d=t[n];d&&(d=e.defaultValue||d,d.isVector2?(o=i.VECTOR2,a=d.clone(),s=(new r.Vector2).fromArray(e.targetValue),l=s.clone().sub(a)):d.isVector3?(o=i.VECTOR3,a=d.clone(),s=(new r.Vector3).fromArray(e.targetValue),l=s.clone().sub(a)):d.isVector4?(o=i.VECTOR4,a=d.clone(),s=(new r.Vector4).fromArray([e.targetValue[2],e.targetValue[3],e.targetValue[0],e.targetValue[1]]),l=s.clone().sub(a)):d.isColor?(o=i.COLOR,a=d.clone(),s=(new r.Color).fromArray(e.targetValue),l=s.clone().sub(a)):(o=i.NUMBER,a=d,s=e.targetValue[0],l=s-a),this._materialValues.push({material:t,propertyName:n,defaultValue:a,targetValue:s,deltaValue:l,type:o}))}applyWeight(){const e=this.isBinary?this.weight<.5?0:1:this.weight;this._binds.forEach((t=>{t.meshes.forEach((n=>{n.morphTargetInfluences&&(n.morphTargetInfluences[t.morphTargetIndex]+=e*t.weight)}))})),this._materialValues.forEach((t=>{if(void 0!==t.material[t.propertyName]){if(t.type===i.NUMBER){const n=t.deltaValue;t.material[t.propertyName]+=n*e}else if(t.type===i.VECTOR2){const n=t.deltaValue;t.material[t.propertyName].add(l.copy(n).multiplyScalar(e))}else if(t.type===i.VECTOR3){const n=t.deltaValue;t.material[t.propertyName].add(d.copy(n).multiplyScalar(e))}else if(t.type===i.VECTOR4){const n=t.deltaValue;t.material[t.propertyName].add(h.copy(n).multiplyScalar(e))}else if(t.type===i.COLOR){const n=t.deltaValue;t.material[t.propertyName].add(u.copy(n).multiplyScalar(e))}"boolean"==typeof t.material.shouldApplyUniforms&&(t.material.shouldApplyUniforms=!0)}}))}clearAppliedWeight(){this._binds.forEach((e=>{e.meshes.forEach((t=>{t.morphTargetInfluences&&(t.morphTargetInfluences[e.morphTargetIndex]=0)}))})),this._materialValues.forEach((e=>{if(void 0!==e.material[e.propertyName]){if(e.type===i.NUMBER){const t=e.defaultValue;e.material[e.propertyName]=t}else if(e.type===i.VECTOR2){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===i.VECTOR3){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===i.VECTOR4){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===i.COLOR){const t=e.defaultValue;e.material[e.propertyName].copy(t)}"boolean"==typeof e.material.shouldApplyUniforms&&(e.material.shouldApplyUniforms=!0)}}))}}var p,m,f,g,_,v,M;function T(e,t,n){const i=e.parser.json.nodes[t].mesh;if(null==i)return null;const r=e.parser.json.meshes[i].primitives.length,o=[];return n.traverse((e=>{o.length<r&&e.isMesh&&o.push(e)})),o}function y(e){return o(this,void 0,void 0,(function*(){const t=yield e.parser.getDependencies("node"),n=new Map;return t.forEach(((t,i)=>{const r=T(e,i,t);null!=r&&n.set(i,r)})),n}))}function x(e){return"_"!==e[0]?(console.warn(`renameMaterialProperty: Given property name "${e}" might be invalid`),e):(e=e.substring(1),/[A-Z]/.test(e[0])?e[0].toLowerCase()+e.substring(1):(console.warn(`renameMaterialProperty: Given property name "${e}" might be invalid`),e))}e.VRMSchema=void 0,p=e.VRMSchema||(e.VRMSchema={}),(m=p.BlendShapePresetName||(p.BlendShapePresetName={})).A="a",m.Angry="angry",m.Blink="blink",m.BlinkL="blink_l",m.BlinkR="blink_r",m.E="e",m.Fun="fun",m.I="i",m.Joy="joy",m.Lookdown="lookdown",m.Lookleft="lookleft",m.Lookright="lookright",m.Lookup="lookup",m.Neutral="neutral",m.O="o",m.Sorrow="sorrow",m.U="u",m.Unknown="unknown",(f=p.FirstPersonLookAtTypeName||(p.FirstPersonLookAtTypeName={})).BlendShape="BlendShape",f.Bone="Bone",(g=p.HumanoidBoneName||(p.HumanoidBoneName={})).Chest="chest",g.Head="head",g.Hips="hips",g.Jaw="jaw",g.LeftEye="leftEye",g.LeftFoot="leftFoot",g.LeftHand="leftHand",g.LeftIndexDistal="leftIndexDistal",g.LeftIndexIntermediate="leftIndexIntermediate",g.LeftIndexProximal="leftIndexProximal",g.LeftLittleDistal="leftLittleDistal",g.LeftLittleIntermediate="leftLittleIntermediate",g.LeftLittleProximal="leftLittleProximal",g.LeftLowerArm="leftLowerArm",g.LeftLowerLeg="leftLowerLeg",g.LeftMiddleDistal="leftMiddleDistal",g.LeftMiddleIntermediate="leftMiddleIntermediate",g.LeftMiddleProximal="leftMiddleProximal",g.LeftRingDistal="leftRingDistal",g.LeftRingIntermediate="leftRingIntermediate",g.LeftRingProximal="leftRingProximal",g.LeftShoulder="leftShoulder",g.LeftThumbDistal="leftThumbDistal",g.LeftThumbIntermediate="leftThumbIntermediate",g.LeftThumbProximal="leftThumbProximal",g.LeftToes="leftToes",g.LeftUpperArm="leftUpperArm",g.LeftUpperLeg="leftUpperLeg",g.Neck="neck",g.RightEye="rightEye",g.RightFoot="rightFoot",g.RightHand="rightHand",g.RightIndexDistal="rightIndexDistal",g.RightIndexIntermediate="rightIndexIntermediate",g.RightIndexProximal="rightIndexProximal",g.RightLittleDistal="rightLittleDistal",g.RightLittleIntermediate="rightLittleIntermediate",g.RightLittleProximal="rightLittleProximal",g.RightLowerArm="rightLowerArm",g.RightLowerLeg="rightLowerLeg",g.RightMiddleDistal="rightMiddleDistal",g.RightMiddleIntermediate="rightMiddleIntermediate",g.RightMiddleProximal="rightMiddleProximal",g.RightRingDistal="rightRingDistal",g.RightRingIntermediate="rightRingIntermediate",g.RightRingProximal="rightRingProximal",g.RightShoulder="rightShoulder",g.RightThumbDistal="rightThumbDistal",g.RightThumbIntermediate="rightThumbIntermediate",g.RightThumbProximal="rightThumbProximal",g.RightToes="rightToes",g.RightUpperArm="rightUpperArm",g.RightUpperLeg="rightUpperLeg",g.Spine="spine",g.UpperChest="upperChest",(_=p.MetaAllowedUserName||(p.MetaAllowedUserName={})).Everyone="Everyone",_.ExplicitlyLicensedPerson="ExplicitlyLicensedPerson",_.OnlyAuthor="OnlyAuthor",(v=p.MetaUssageName||(p.MetaUssageName={})).Allow="Allow",v.Disallow="Disallow",(M=p.MetaLicenseName||(p.MetaLicenseName={})).Cc0="CC0",M.CcBy="CC_BY",M.CcByNc="CC_BY_NC",M.CcByNcNd="CC_BY_NC_ND",M.CcByNcSa="CC_BY_NC_SA",M.CcByNd="CC_BY_ND",M.CcBySa="CC_BY_SA",M.Other="Other",M.RedistributionProhibited="Redistribution_Prohibited";const S=new r.Vector3,R=new r.Vector3;function E(e,t){return e.matrixWorld.decompose(S,t,R),t}new r.Quaternion;class L{constructor(){this._blendShapeGroups={},this._blendShapePresetMap={},this._unknownGroupNames=[]}get expressions(){return Object.keys(this._blendShapeGroups)}get blendShapePresetMap(){return this._blendShapePresetMap}get unknownGroupNames(){return this._unknownGroupNames}getBlendShapeGroup(e){const t=this._blendShapePresetMap[e],n=t?this._blendShapeGroups[t]:this._blendShapeGroups[e];if(n)return n;console.warn(`no blend shape found by ${e}`)}registerBlendShapeGroup(e,t,n){this._blendShapeGroups[e]=n,t?this._blendShapePresetMap[t]=e:this._unknownGroupNames.push(e)}getValue(e){var t;const n=this.getBlendShapeGroup(e);return null!==(t=null==n?void 0:n.weight)&&void 0!==t?t:null}setValue(e,t){const n=this.getBlendShapeGroup(e);var i;n&&(n.weight=(i=t,Math.max(Math.min(i,1),0)))}getBlendShapeTrackName(e){const t=this.getBlendShapeGroup(e);return t?`${t.name}.weight`:null}update(){Object.keys(this._blendShapeGroups).forEach((e=>{this._blendShapeGroups[e].clearAppliedWeight()})),Object.keys(this._blendShapeGroups).forEach((e=>{this._blendShapeGroups[e].applyWeight()}))}}class w{import(t){var n;return o(this,void 0,void 0,(function*(){const i=null===(n=t.parser.json.extensions)||void 0===n?void 0:n.VRM;if(!i)return null;const r=i.blendShapeMaster;if(!r)return null;const a=new L,s=r.blendShapeGroups;if(!s)return a;const l={};return yield Promise.all(s.map((n=>o(this,void 0,void 0,(function*(){const i=n.name;if(void 0===i)return void console.warn("VRMBlendShapeImporter: One of blendShapeGroups has no name");let r;n.presetName&&n.presetName!==e.VRMSchema.BlendShapePresetName.Unknown&&!l[n.presetName]&&(r=n.presetName,l[n.presetName]=i);const s=new c(i);t.scene.add(s),s.isBinary=n.isBinary||!1,n.binds&&n.binds.forEach((e=>o(this,void 0,void 0,(function*(){if(void 0===e.mesh||void 0===e.index)return;const i=[];t.parser.json.nodes.forEach(((t,n)=>{t.mesh===e.mesh&&i.push(n)}));const r=e.index;yield Promise.all(i.map((i=>o(this,void 0,void 0,(function*(){var a;const l=yield function(e,t){return o(this,void 0,void 0,(function*(){const n=yield e.parser.getDependency("node",t);return T(e,t,n)}))}(t,i);l.every((e=>Array.isArray(e.morphTargetInfluences)&&r<e.morphTargetInfluences.length))?s.addBind({meshes:l,morphTargetIndex:r,weight:null!==(a=e.weight)&&void 0!==a?a:100}):console.warn(`VRMBlendShapeImporter: ${n.name} attempts to index ${r}th morph but not found.`)})))))}))));const d=n.materialValues;d&&d.forEach((e=>{if(void 0===e.materialName||void 0===e.propertyName||void 0===e.targetValue)return;const n=[];t.scene.traverse((t=>{if(t.material){const i=t.material;Array.isArray(i)?n.push(...i.filter((t=>t.name===e.materialName&&-1===n.indexOf(t)))):i.name===e.materialName&&-1===n.indexOf(i)&&n.push(i)}})),n.forEach((t=>{s.addMaterialValue({material:t,propertyName:x(e.propertyName),targetValue:e.targetValue})}))})),a.registerBlendShapeGroup(i,r,s)}))))),a}))}}const P=Object.freeze(new r.Vector3(0,0,-1)),A=new r.Quaternion;var b;!function(e){e[e.Auto=0]="Auto",e[e.Both=1]="Both",e[e.ThirdPersonOnly=2]="ThirdPersonOnly",e[e.FirstPersonOnly=3]="FirstPersonOnly"}(b||(b={}));class O{constructor(e,t){this.firstPersonFlag=O._parseFirstPersonFlag(e),this.primitives=t}static _parseFirstPersonFlag(e){switch(e){case"Both":return b.Both;case"ThirdPersonOnly":return b.ThirdPersonOnly;case"FirstPersonOnly":return b.FirstPersonOnly;default:return b.Auto}}}class C{constructor(e,t,n){this._meshAnnotations=[],this._firstPersonOnlyLayer=C._DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=C._DEFAULT_THIRDPERSON_ONLY_LAYER,this._initialized=!1,this._firstPersonBone=e,this._firstPersonBoneOffset=t,this._meshAnnotations=n}get firstPersonBone(){return this._firstPersonBone}get meshAnnotations(){return this._meshAnnotations}getFirstPersonWorldDirection(e){return e.copy(P).applyQuaternion(E(this._firstPersonBone,A))}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}getFirstPersonBoneOffset(e){return e.copy(this._firstPersonBoneOffset)}getFirstPersonWorldPosition(e){const t=this._firstPersonBoneOffset,n=new r.Vector4(t.x,t.y,t.z,1);return n.applyMatrix4(this._firstPersonBone.matrixWorld),e.set(n.x,n.y,n.z)}setup({firstPersonOnlyLayer:e=C._DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=C._DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initialized||(this._initialized=!0,this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=t,this._meshAnnotations.forEach((e=>{e.firstPersonFlag===b.FirstPersonOnly?e.primitives.forEach((e=>{e.layers.set(this._firstPersonOnlyLayer)})):e.firstPersonFlag===b.ThirdPersonOnly?e.primitives.forEach((e=>{e.layers.set(this._thirdPersonOnlyLayer)})):e.firstPersonFlag===b.Auto&&this._createHeadlessModel(e.primitives)})))}_excludeTriangles(e,t,n,i){let r=0;if(null!=t&&t.length>0)for(let o=0;o<e.length;o+=3){const a=e[o],s=e[o+1],l=e[o+2],d=t[a],h=n[a];if(d[0]>0&&i.includes(h[0]))continue;if(d[1]>0&&i.includes(h[1]))continue;if(d[2]>0&&i.includes(h[2]))continue;if(d[3]>0&&i.includes(h[3]))continue;const u=t[s],c=n[s];if(u[0]>0&&i.includes(c[0]))continue;if(u[1]>0&&i.includes(c[1]))continue;if(u[2]>0&&i.includes(c[2]))continue;if(u[3]>0&&i.includes(c[3]))continue;const p=t[l],m=n[l];p[0]>0&&i.includes(m[0])||(p[1]>0&&i.includes(m[1])||p[2]>0&&i.includes(m[2])||p[3]>0&&i.includes(m[3])||(e[r++]=a,e[r++]=s,e[r++]=l))}return r}_createErasedMesh(e,t){const n=new r.SkinnedMesh(e.geometry.clone(),e.material);n.name=`${e.name}(erase)`,n.frustumCulled=e.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);const i=n.geometry,o=i.getAttribute("skinIndex").array,a=[];for(let e=0;e<o.length;e+=4)a.push([o[e],o[e+1],o[e+2],o[e+3]]);const s=i.getAttribute("skinWeight").array,l=[];for(let e=0;e<s.length;e+=4)l.push([s[e],s[e+1],s[e+2],s[e+3]]);const d=i.getIndex();if(!d)throw new Error("The geometry doesn't have an index buffer");const h=Array.from(d.array),u=this._excludeTriangles(h,l,a,t),c=[];for(let e=0;e<u;e++)c[e]=h[e];return i.setIndex(c),e.onBeforeRender&&(n.onBeforeRender=e.onBeforeRender),n.bind(new r.Skeleton(e.skeleton.bones,e.skeleton.boneInverses),new r.Matrix4),n}_createHeadlessModelForSkinnedMesh(e,t){const n=[];if(t.skeleton.bones.forEach(((e,t)=>{this._isEraseTarget(e)&&n.push(t)})),!n.length)return t.layers.enable(this._thirdPersonOnlyLayer),void t.layers.enable(this._firstPersonOnlyLayer);t.layers.set(this._thirdPersonOnlyLayer);const i=this._createErasedMesh(t,n);e.add(i)}_createHeadlessModel(e){e.forEach((e=>{if("SkinnedMesh"===e.type){const t=e;this._createHeadlessModelForSkinnedMesh(t.parent,t)}else this._isEraseTarget(e)&&e.layers.set(this._thirdPersonOnlyLayer)}))}_isEraseTarget(e){return e===this._firstPersonBone||!!e.parent&&this._isEraseTarget(e.parent)}}C._DEFAULT_FIRSTPERSON_ONLY_LAYER=9,C._DEFAULT_THIRDPERSON_ONLY_LAYER=10;class I{import(t,n){var i;return o(this,void 0,void 0,(function*(){const o=null===(i=t.parser.json.extensions)||void 0===i?void 0:i.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=a.firstPersonBone;let l;if(l=void 0===s||-1===s?n.getBoneNode(e.VRMSchema.HumanoidBoneName.Head):yield t.parser.getDependency("node",s),!l)return console.warn("VRMFirstPersonImporter: Could not find firstPersonBone of the VRM"),null;const d=a.firstPersonBoneOffset?new r.Vector3(a.firstPersonBoneOffset.x,a.firstPersonBoneOffset.y,-a.firstPersonBoneOffset.z):new r.Vector3(0,.06,0),h=[],u=yield y(t);return Array.from(u.entries()).forEach((([e,n])=>{const i=t.parser.json.nodes[e],r=a.meshAnnotations?a.meshAnnotations.find((e=>e.mesh===i.mesh)):void 0;h.push(new O(null==r?void 0:r.firstPersonFlag,n))})),new C(l,d,h)}))}}class V{constructor(e,t){this.node=e,this.humanLimit=t}}function D(e){return e.invert?e.invert():e.inverse(),e}const N=new r.Vector3,U=new r.Quaternion;class B{constructor(e,t){this.restPose={},this.humanBones=this._createHumanBones(e),this.humanDescription=t,this.restPose=this.getPose()}getPose(){const e={};return Object.keys(this.humanBones).forEach((t=>{const n=this.getBoneNode(t);if(!n)return;if(e[t])return;N.set(0,0,0),U.identity();const i=this.restPose[t];(null==i?void 0:i.position)&&N.fromArray(i.position).negate(),(null==i?void 0:i.rotation)&&D(U.fromArray(i.rotation)),N.add(n.position),U.premultiply(n.quaternion),e[t]={position:N.toArray(),rotation:U.toArray()}}),{}),e}setPose(e){Object.keys(e).forEach((t=>{const n=e[t],i=this.getBoneNode(t);if(!i)return;const r=this.restPose[t];r&&(n.position&&(i.position.fromArray(n.position),r.position&&i.position.add(N.fromArray(r.position))),n.rotation&&(i.quaternion.fromArray(n.rotation),r.rotation&&i.quaternion.multiply(U.fromArray(r.rotation))))}))}resetPose(){Object.entries(this.restPose).forEach((([e,t])=>{const n=this.getBoneNode(e);n&&((null==t?void 0:t.position)&&n.position.fromArray(t.position),(null==t?void 0:t.rotation)&&n.quaternion.fromArray(t.rotation))}))}getBone(e){var t;return null!==(t=this.humanBones[e][0])&&void 0!==t?t:void 0}getBones(e){var t;return null!==(t=this.humanBones[e])&&void 0!==t?t:[]}getBoneNode(e){var t,n;return null!==(n=null===(t=this.humanBones[e][0])||void 0===t?void 0:t.node)&&void 0!==n?n:null}getBoneNodes(e){var t,n;return null!==(n=null===(t=this.humanBones[e])||void 0===t?void 0:t.map((e=>e.node)))&&void 0!==n?n:[]}_createHumanBones(t){const n=Object.values(e.VRMSchema.HumanoidBoneName).reduce(((e,t)=>(e[t]=[],e)),{});return t.forEach((e=>{n[e.name].push(e.bone)})),n}}class G{import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.humanoid;if(!i)return null;const a=[];i.humanBones&&(yield Promise.all(i.humanBones.map((t=>o(this,void 0,void 0,(function*(){if(!t.bone||null==t.node)return;const n=yield e.parser.getDependency("node",t.node);a.push({name:t.bone,bone:new V(n,{axisLength:t.axisLength,center:t.center&&new r.Vector3(t.center.x,t.center.y,t.center.z),max:t.max&&new r.Vector3(t.max.x,t.max.y,t.max.z),min:t.min&&new r.Vector3(t.min.x,t.min.y,t.min.z),useDefaultValues:t.useDefaultValues})})}))))));const s={armStretch:i.armStretch,legStretch:i.legStretch,upperArmTwist:i.upperArmTwist,lowerArmTwist:i.lowerArmTwist,upperLegTwist:i.upperLegTwist,lowerLegTwist:i.lowerLegTwist,feetSpacing:i.feetSpacing,hasTranslationDoF:i.hasTranslationDoF};return new B(a,s)}))}}class k{constructor(e,t,n){this.curve=[0,0,0,1,1,1,1,0],this.curveXRangeDegree=90,this.curveYRangeDegree=10,void 0!==e&&(this.curveXRangeDegree=e),void 0!==t&&(this.curveYRangeDegree=t),void 0!==n&&(this.curve=n)}map(e){const t=Math.min(Math.max(e,0),this.curveXRangeDegree)/this.curveXRangeDegree;return this.curveYRangeDegree*((e,t)=>{if(e.length<8)throw new Error("evaluateCurve: Invalid curve detected! (Array length must be 8 at least)");if(e.length%4!=0)throw new Error("evaluateCurve: Invalid curve detected! (Array length must be multiples of 4");let n;for(n=0;;n++){if(e.length<=4*n)return e[4*n-3];if(t<=e[4*n])break}const i=n-1;if(i<0)return e[4*i+5];const r=e[4*i],o=(t-r)/(e[4*n]-r);return((e,t,n,i,r)=>{const o=r*r*r,a=r*r;return e+(t-e)*(-2*o+3*a)+n*(o-2*a+r)+i*(o-a)})(e[4*i+1],e[4*n+1],e[4*i+3],e[4*n+2],o)})(this.curve,t)}}class F{}class H extends F{constructor(t,n,i,r){super(),this.type=e.VRMSchema.FirstPersonLookAtTypeName.BlendShape,this._curveHorizontal=n,this._curveVerticalDown=i,this._curveVerticalUp=r,this._blendShapeProxy=t}name(){return e.VRMSchema.FirstPersonLookAtTypeName.BlendShape}lookAt(t){const n=t.x,i=t.y;n<0?(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookup,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookdown,this._curveVerticalDown.map(-n))):(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookdown,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookup,this._curveVerticalUp.map(n))),i<0?(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookleft,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookright,this._curveHorizontal.map(-i))):(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookright,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookleft,this._curveHorizontal.map(i)))}}const W=Object.freeze(new r.Vector3(0,0,-1)),z=new r.Vector3,j=new r.Vector3,Y=new r.Vector3,X=new r.Quaternion;class q{constructor(e,t){this.autoUpdate=!0,this._euler=new r.Euler(0,0,0,q.EULER_ORDER),this.firstPerson=e,this.applyer=t}getLookAtWorldDirection(e){const t=E(this.firstPerson.firstPersonBone,X);return e.copy(W).applyEuler(this._euler).applyQuaternion(t)}lookAt(e){this._calcEuler(this._euler,e),this.applyer&&this.applyer.lookAt(this._euler)}update(e){this.target&&this.autoUpdate&&(this.lookAt(this.target.getWorldPosition(z)),this.applyer&&this.applyer.lookAt(this._euler))}_calcEuler(e,t){const n=this.firstPerson.getFirstPersonWorldPosition(j),i=Y.copy(t).sub(n).normalize();return i.applyQuaternion(D(E(this.firstPerson.firstPersonBone,X))),e.x=Math.atan2(i.y,Math.sqrt(i.x*i.x+i.z*i.z)),e.y=Math.atan2(-i.x,-i.z),e}}q.EULER_ORDER="YXZ";const Q=new r.Euler(0,0,0,q.EULER_ORDER);class Z extends F{constructor(t,n,i,r,o){super(),this.type=e.VRMSchema.FirstPersonLookAtTypeName.Bone,this._curveHorizontalInner=n,this._curveHorizontalOuter=i,this._curveVerticalDown=r,this._curveVerticalUp=o,this._leftEye=t.getBoneNode(e.VRMSchema.HumanoidBoneName.LeftEye),this._rightEye=t.getBoneNode(e.VRMSchema.HumanoidBoneName.RightEye)}lookAt(e){const t=e.x,n=e.y;this._leftEye&&(Q.x=t<0?-this._curveVerticalDown.map(-t):this._curveVerticalUp.map(t),Q.y=n<0?-this._curveHorizontalInner.map(-n):this._curveHorizontalOuter.map(n),this._leftEye.quaternion.setFromEuler(Q)),this._rightEye&&(Q.x=t<0?-this._curveVerticalDown.map(-t):this._curveVerticalUp.map(t),Q.y=n<0?-this._curveHorizontalOuter.map(-n):this._curveHorizontalInner.map(n),this._rightEye.quaternion.setFromEuler(Q))}}const $=Math.PI/180;class J{import(e,t,n,i){var r;const o=null===(r=e.parser.json.extensions)||void 0===r?void 0:r.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=this._importApplyer(a,n,i);return new q(t,s||void 0)}_importApplyer(t,n,i){const r=t.lookAtHorizontalInner,o=t.lookAtHorizontalOuter,a=t.lookAtVerticalDown,s=t.lookAtVerticalUp;switch(t.lookAtTypeName){case e.VRMSchema.FirstPersonLookAtTypeName.Bone:return void 0===r||void 0===o||void 0===a||void 0===s?null:new Z(i,this._importCurveMapperBone(r),this._importCurveMapperBone(o),this._importCurveMapperBone(a),this._importCurveMapperBone(s));case e.VRMSchema.FirstPersonLookAtTypeName.BlendShape:return void 0===o||void 0===a||void 0===s?null:new H(n,this._importCurveMapperBlendShape(o),this._importCurveMapperBlendShape(a),this._importCurveMapperBlendShape(s));default:return null}}_importCurveMapperBone(e){return new k("number"==typeof e.xRange?$*e.xRange:void 0,"number"==typeof e.yRange?$*e.yRange:void 0,e.curve)}_importCurveMapperBlendShape(e){return new k("number"==typeof e.xRange?$*e.xRange:void 0,e.yRange,e.curve)}}const K=(e,t)=>{const n=(e=>{if(parseInt(r.REVISION,10)>=136)switch(e){case r.LinearEncoding:return["Linear","( value )"];case r.sRGBEncoding:return["sRGB","( value )"];default:return console.warn("THREE.WebGLProgram: Unsupported encoding:",e),["Linear","( value )"]}else switch(e){case r.LinearEncoding:return["Linear","( value )"];case r.sRGBEncoding:return["sRGB","( value )"];case r.RGBEEncoding:return["RGBE","( value )"];case r.RGBM7Encoding:return["RGBM","( value, 7.0 )"];case r.RGBM16Encoding:return["RGBM","( value, 16.0 )"];case r.RGBDEncoding:return["RGBD","( value, 256.0 )"];case r.GammaEncoding:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw new Error("unsupported encoding: "+e)}})(t);return"vec4 "+e+"( vec4 value ) { return "+n[0]+"ToLinear"+n[1]+"; }"};const ee=2*Math.PI;var te,ne,ie,re,oe;e.MToonMaterialCullMode=void 0,(te=e.MToonMaterialCullMode||(e.MToonMaterialCullMode={}))[te.Off=0]="Off",te[te.Front=1]="Front",te[te.Back=2]="Back",e.MToonMaterialDebugMode=void 0,(ne=e.MToonMaterialDebugMode||(e.MToonMaterialDebugMode={}))[ne.None=0]="None",ne[ne.Normal=1]="Normal",ne[ne.LitShadeRate=2]="LitShadeRate",ne[ne.UV=3]="UV",e.MToonMaterialOutlineColorMode=void 0,(ie=e.MToonMaterialOutlineColorMode||(e.MToonMaterialOutlineColorMode={}))[ie.FixedColor=0]="FixedColor",ie[ie.MixedLighting=1]="MixedLighting",e.MToonMaterialOutlineWidthMode=void 0,(re=e.MToonMaterialOutlineWidthMode||(e.MToonMaterialOutlineWidthMode={}))[re.None=0]="None",re[re.WorldCoordinates=1]="WorldCoordinates",re[re.ScreenCoordinates=2]="ScreenCoordinates",e.MToonMaterialRenderMode=void 0,(oe=e.MToonMaterialRenderMode||(e.MToonMaterialRenderMode={}))[oe.Opaque=0]="Opaque",oe[oe.Cutout=1]="Cutout",oe[oe.Transparent=2]="Transparent",oe[oe.TransparentWithZWrite=3]="TransparentWithZWrite";class ae extends r.ShaderMaterial{constructor(t={}){super(),this.isMToonMaterial=!0,this.cutoff=.5,this.color=new r.Vector4(1,1,1,1),this.shadeColor=new r.Vector4(.97,.81,.86,1),this.map=null,this.mainTex_ST=new r.Vector4(0,0,1,1),this.shadeTexture=null,this.normalMap=null,this.normalMapType=r.TangentSpaceNormalMap,this.normalScale=new r.Vector2(1,1),this.receiveShadowRate=1,this.receiveShadowTexture=null,this.shadingGradeRate=1,this.shadingGradeTexture=null,this.shadeShift=0,this.shadeToony=.9,this.lightColorAttenuation=0,this.indirectLightIntensity=.1,this.rimTexture=null,this.rimColor=new r.Vector4(0,0,0,1),this.rimLightingMix=0,this.rimFresnelPower=1,this.rimLift=0,this.sphereAdd=null,this.emissionColor=new r.Vector4(0,0,0,1),this.emissiveMap=null,this.outlineWidthTexture=null,this.outlineWidth=.5,this.outlineScaledMaxDistance=1,this.outlineColor=new r.Vector4(0,0,0,1),this.outlineLightingMix=1,this.uvAnimMaskTexture=null,this.uvAnimScrollX=0,this.uvAnimScrollY=0,this.uvAnimRotation=0,this.shouldApplyUniforms=!0,this._debugMode=e.MToonMaterialDebugMode.None,this._blendMode=e.MToonMaterialRenderMode.Opaque,this._outlineWidthMode=e.MToonMaterialOutlineWidthMode.None,this._outlineColorMode=e.MToonMaterialOutlineColorMode.FixedColor,this._cullMode=e.MToonMaterialCullMode.Back,this._outlineCullMode=e.MToonMaterialCullMode.Front,this._isOutline=!1,this._uvAnimOffsetX=0,this._uvAnimOffsetY=0,this._uvAnimPhase=0,this.encoding=t.encoding||r.LinearEncoding,this.encoding!==r.LinearEncoding&&this.encoding!==r.sRGBEncoding&&console.warn("The specified color encoding does not work properly with MToonMaterial. You might want to use THREE.sRGBEncoding instead."),["mToonVersion","shadeTexture_ST","bumpMap_ST","receiveShadowTexture_ST","shadingGradeTexture_ST","rimTexture_ST","sphereAdd_ST","emissionMap_ST","outlineWidthTexture_ST","uvAnimMaskTexture_ST","srcBlend","dstBlend"].forEach((e=>{void 0!==t[e]&&delete t[e]})),t.fog=!0,t.lights=!0,t.clipping=!0,parseInt(r.REVISION,10)<129&&(t.skinning=t.skinning||!1),parseInt(r.REVISION,10)<131&&(t.morphTargets=t.morphTargets||!1,t.morphNormals=t.morphNormals||!1),t.uniforms=r.UniformsUtils.merge([r.UniformsLib.common,r.UniformsLib.normalmap,r.UniformsLib.emissivemap,r.UniformsLib.fog,r.UniformsLib.lights,{cutoff:{value:.5},color:{value:new r.Color(1,1,1)},colorAlpha:{value:1},shadeColor:{value:new r.Color(.97,.81,.86)},mainTex_ST:{value:new r.Vector4(0,0,1,1)},shadeTexture:{value:null},receiveShadowRate:{value:1},receiveShadowTexture:{value:null},shadingGradeRate:{value:1},shadingGradeTexture:{value:null},shadeShift:{value:0},shadeToony:{value:.9},lightColorAttenuation:{value:0},indirectLightIntensity:{value:.1},rimTexture:{value:null},rimColor:{value:new r.Color(0,0,0)},rimLightingMix:{value:0},rimFresnelPower:{value:1},rimLift:{value:0},sphereAdd:{value:null},emissionColor:{value:new r.Color(0,0,0)},outlineWidthTexture:{value:null},outlineWidth:{value:.5},outlineScaledMaxDistance:{value:1},outlineColor:{value:new r.Color(0,0,0)},outlineLightingMix:{value:1},uvAnimMaskTexture:{value:null},uvAnimOffsetX:{value:0},uvAnimOffsetY:{value:0},uvAnimTheta:{value:0}}]),this.setValues(t),this._updateShaderCode(),this._applyUniforms()}get mainTex(){return this.map}set mainTex(e){this.map=e}get bumpMap(){return this.normalMap}set bumpMap(e){this.normalMap=e}get bumpScale(){return this.normalScale.x}set bumpScale(e){this.normalScale.set(e,e)}get emissionMap(){return this.emissiveMap}set emissionMap(e){this.emissiveMap=e}get blendMode(){return this._blendMode}set blendMode(t){this._blendMode=t,this.depthWrite=this._blendMode!==e.MToonMaterialRenderMode.Transparent,this.transparent=this._blendMode===e.MToonMaterialRenderMode.Transparent||this._blendMode===e.MToonMaterialRenderMode.TransparentWithZWrite,this._updateShaderCode()}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this._updateShaderCode()}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this._updateShaderCode()}get outlineColorMode(){return this._outlineColorMode}set outlineColorMode(e){this._outlineColorMode=e,this._updateShaderCode()}get cullMode(){return this._cullMode}set cullMode(e){this._cullMode=e,this._updateCullFace()}get outlineCullMode(){return this._outlineCullMode}set outlineCullMode(e){this._outlineCullMode=e,this._updateCullFace()}get zWrite(){return this.depthWrite?1:0}set zWrite(e){this.depthWrite=.5<=e}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this._updateShaderCode(),this._updateCullFace()}updateVRMMaterials(e){this._uvAnimOffsetX=this._uvAnimOffsetX+e*this.uvAnimScrollX,this._uvAnimOffsetY=this._uvAnimOffsetY-e*this.uvAnimScrollY,this._uvAnimPhase=this._uvAnimPhase+e*this.uvAnimRotation,this._applyUniforms()}copy(e){return super.copy(e),this.cutoff=e.cutoff,this.color.copy(e.color),this.shadeColor.copy(e.shadeColor),this.map=e.map,this.mainTex_ST.copy(e.mainTex_ST),this.shadeTexture=e.shadeTexture,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(this.normalScale),this.receiveShadowRate=e.receiveShadowRate,this.receiveShadowTexture=e.receiveShadowTexture,this.shadingGradeRate=e.shadingGradeRate,this.shadingGradeTexture=e.shadingGradeTexture,this.shadeShift=e.shadeShift,this.shadeToony=e.shadeToony,this.lightColorAttenuation=e.lightColorAttenuation,this.indirectLightIntensity=e.indirectLightIntensity,this.rimTexture=e.rimTexture,this.rimColor.copy(e.rimColor),this.rimLightingMix=e.rimLightingMix,this.rimFresnelPower=e.rimFresnelPower,this.rimLift=e.rimLift,this.sphereAdd=e.sphereAdd,this.emissionColor.copy(e.emissionColor),this.emissiveMap=e.emissiveMap,this.outlineWidthTexture=e.outlineWidthTexture,this.outlineWidth=e.outlineWidth,this.outlineScaledMaxDistance=e.outlineScaledMaxDistance,this.outlineColor.copy(e.outlineColor),this.outlineLightingMix=e.outlineLightingMix,this.uvAnimMaskTexture=e.uvAnimMaskTexture,this.uvAnimScrollX=e.uvAnimScrollX,this.uvAnimScrollY=e.uvAnimScrollY,this.uvAnimRotation=e.uvAnimRotation,this.debugMode=e.debugMode,this.blendMode=e.blendMode,this.outlineWidthMode=e.outlineWidthMode,this.outlineColorMode=e.outlineColorMode,this.cullMode=e.cullMode,this.outlineCullMode=e.outlineCullMode,this.isOutline=e.isOutline,this}_applyUniforms(){this.uniforms.uvAnimOffsetX.value=this._uvAnimOffsetX,this.uniforms.uvAnimOffsetY.value=this._uvAnimOffsetY,this.uniforms.uvAnimTheta.value=ee*this._uvAnimPhase,this.shouldApplyUniforms&&(this.shouldApplyUniforms=!1,this.uniforms.cutoff.value=this.cutoff,this.uniforms.color.value.setRGB(this.color.x,this.color.y,this.color.z),this.uniforms.colorAlpha.value=this.color.w,this.uniforms.shadeColor.value.setRGB(this.shadeColor.x,this.shadeColor.y,this.shadeColor.z),this.uniforms.map.value=this.map,this.uniforms.mainTex_ST.value.copy(this.mainTex_ST),this.uniforms.shadeTexture.value=this.shadeTexture,this.uniforms.normalMap.value=this.normalMap,this.uniforms.normalScale.value.copy(this.normalScale),this.uniforms.receiveShadowRate.value=this.receiveShadowRate,this.uniforms.receiveShadowTexture.value=this.receiveShadowTexture,this.uniforms.shadingGradeRate.value=this.shadingGradeRate,this.uniforms.shadingGradeTexture.value=this.shadingGradeTexture,this.uniforms.shadeShift.value=this.shadeShift,this.uniforms.shadeToony.value=this.shadeToony,this.uniforms.lightColorAttenuation.value=this.lightColorAttenuation,this.uniforms.indirectLightIntensity.value=this.indirectLightIntensity,this.uniforms.rimTexture.value=this.rimTexture,this.uniforms.rimColor.value.setRGB(this.rimColor.x,this.rimColor.y,this.rimColor.z),this.uniforms.rimLightingMix.value=this.rimLightingMix,this.uniforms.rimFresnelPower.value=this.rimFresnelPower,this.uniforms.rimLift.value=this.rimLift,this.uniforms.sphereAdd.value=this.sphereAdd,this.uniforms.emissionColor.value.setRGB(this.emissionColor.x,this.emissionColor.y,this.emissionColor.z),this.uniforms.emissiveMap.value=this.emissiveMap,this.uniforms.outlineWidthTexture.value=this.outlineWidthTexture,this.uniforms.outlineWidth.value=this.outlineWidth,this.uniforms.outlineScaledMaxDistance.value=this.outlineScaledMaxDistance,this.uniforms.outlineColor.value.setRGB(this.outlineColor.x,this.outlineColor.y,this.outlineColor.z),this.uniforms.outlineLightingMix.value=this.outlineLightingMix,this.uniforms.uvAnimMaskTexture.value=this.uvAnimMaskTexture,this.encoding===r.sRGBEncoding&&(this.uniforms.color.value.convertSRGBToLinear(),this.uniforms.shadeColor.value.convertSRGBToLinear(),this.uniforms.rimColor.value.convertSRGBToLinear(),this.uniforms.emissionColor.value.convertSRGBToLinear(),this.uniforms.outlineColor.value.convertSRGBToLinear()),this._updateCullFace())}_updateShaderCode(){const t=null!==this.outlineWidthTexture,n=null!==this.map||null!==this.shadeTexture||null!==this.receiveShadowTexture||null!==this.shadingGradeTexture||null!==this.rimTexture||null!==this.uvAnimMaskTexture;this.defines={THREE_VRM_THREE_REVISION:parseInt(r.REVISION,10),OUTLINE:this._isOutline,BLENDMODE_OPAQUE:this._blendMode===e.MToonMaterialRenderMode.Opaque,BLENDMODE_CUTOUT:this._blendMode===e.MToonMaterialRenderMode.Cutout,BLENDMODE_TRANSPARENT:this._blendMode===e.MToonMaterialRenderMode.Transparent||this._blendMode===e.MToonMaterialRenderMode.TransparentWithZWrite,MTOON_USE_UV:t||n,MTOON_UVS_VERTEX_ONLY:t&&!n,USE_SHADETEXTURE:null!==this.shadeTexture,USE_RECEIVESHADOWTEXTURE:null!==this.receiveShadowTexture,USE_SHADINGGRADETEXTURE:null!==this.shadingGradeTexture,USE_RIMTEXTURE:null!==this.rimTexture,USE_SPHEREADD:null!==this.sphereAdd,USE_OUTLINEWIDTHTEXTURE:null!==this.outlineWidthTexture,USE_UVANIMMASKTEXTURE:null!==this.uvAnimMaskTexture,DEBUG_NORMAL:this._debugMode===e.MToonMaterialDebugMode.Normal,DEBUG_LITSHADERATE:this._debugMode===e.MToonMaterialDebugMode.LitShadeRate,DEBUG_UV:this._debugMode===e.MToonMaterialDebugMode.UV,OUTLINE_WIDTH_WORLD:this._outlineWidthMode===e.MToonMaterialOutlineWidthMode.WorldCoordinates,OUTLINE_WIDTH_SCREEN:this._outlineWidthMode===e.MToonMaterialOutlineWidthMode.ScreenCoordinates,OUTLINE_COLOR_FIXED:this._outlineColorMode===e.MToonMaterialOutlineColorMode.FixedColor,OUTLINE_COLOR_MIXED:this._outlineColorMode===e.MToonMaterialOutlineColorMode.MixedLighting};const i=(null!==this.shadeTexture?K("shadeTextureTexelToLinear",this.shadeTexture.encoding)+"\n":"")+(null!==this.sphereAdd?K("sphereAddTexelToLinear",this.sphereAdd.encoding)+"\n":"")+(null!==this.rimTexture?K("rimTextureTexelToLinear",this.rimTexture.encoding)+"\n":"");this.vertexShader="// #define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n\n#include <common>\n\n// #include <uv_pars_vertex>\n#ifdef MTOON_USE_UV\n #ifdef MTOON_UVS_VERTEX_ONLY\n vec2 vUv;\n #else\n varying vec2 vUv;\n #endif\n\n uniform vec4 mainTex_ST;\n#endif\n\n#include <uv2_pars_vertex>\n// #include <displacementmap_pars_vertex>\n// #include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\n#ifdef USE_OUTLINEWIDTHTEXTURE\n uniform sampler2D outlineWidthTexture;\n#endif\n\nuniform float outlineWidth;\nuniform float outlineScaledMaxDistance;\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef MTOON_USE_UV\n vUv = uv;\n vUv.y = 1.0 - vUv.y; // uv.y is opposite from UniVRM's\n vUv = mainTex_ST.st + mainTex_ST.pq * vUv;\n vUv.y = 1.0 - vUv.y; // reverting the previous flip\n #endif\n\n #include <uv2_vertex>\n #include <color_vertex>\n\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n\n // we need this to compute the outline properly\n objectNormal = normalize( objectNormal );\n\n #include <defaultnormal_vertex>\n\n #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #endif\n\n #include <begin_vertex>\n\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n // #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n\n vViewPosition = - mvPosition.xyz;\n\n float outlineTex = 1.0;\n\n #ifdef OUTLINE\n #ifdef USE_OUTLINEWIDTHTEXTURE\n outlineTex = texture2D( outlineWidthTexture, vUv ).r;\n #endif\n\n #ifdef OUTLINE_WIDTH_WORLD\n float worldNormalLength = length( transformedNormal );\n vec3 outlineOffset = 0.01 * outlineWidth * outlineTex * worldNormalLength * objectNormal;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 );\n #endif\n\n #ifdef OUTLINE_WIDTH_SCREEN\n vec3 clipNormal = ( projectionMatrix * modelViewMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n vec2 projectedNormal = normalize( clipNormal.xy );\n projectedNormal *= min( gl_Position.w, outlineScaledMaxDistance );\n projectedNormal.x *= projectionMatrix[ 0 ].x / projectionMatrix[ 1 ].y;\n gl_Position.xy += 0.01 * outlineWidth * outlineTex * projectedNormal.xy;\n #endif\n\n gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic\n #endif\n\n #include <worldpos_vertex>\n // #include <envmap_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n\n}",this.fragmentShader=i+'// #define PHONG\n\n#ifdef BLENDMODE_CUTOUT\n uniform float cutoff;\n#endif\n\nuniform vec3 color;\nuniform float colorAlpha;\nuniform vec3 shadeColor;\n#ifdef USE_SHADETEXTURE\n uniform sampler2D shadeTexture;\n#endif\n\nuniform float receiveShadowRate;\n#ifdef USE_RECEIVESHADOWTEXTURE\n uniform sampler2D receiveShadowTexture;\n#endif\n\nuniform float shadingGradeRate;\n#ifdef USE_SHADINGGRADETEXTURE\n uniform sampler2D shadingGradeTexture;\n#endif\n\nuniform float shadeShift;\nuniform float shadeToony;\nuniform float lightColorAttenuation;\nuniform float indirectLightIntensity;\n\n#ifdef USE_RIMTEXTURE\n uniform sampler2D rimTexture;\n#endif\nuniform vec3 rimColor;\nuniform float rimLightingMix;\nuniform float rimFresnelPower;\nuniform float rimLift;\n\n#ifdef USE_SPHEREADD\n uniform sampler2D sphereAdd;\n#endif\n\nuniform vec3 emissionColor;\n\nuniform vec3 outlineColor;\nuniform float outlineLightingMix;\n\n#ifdef USE_UVANIMMASKTEXTURE\n uniform sampler2D uvAnimMaskTexture;\n#endif\n\nuniform float uvAnimOffsetX;\nuniform float uvAnimOffsetY;\nuniform float uvAnimTheta;\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n\n// #include <uv_pars_fragment>\n#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n varying vec2 vUv;\n#endif\n\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n// #include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n// #include <envmap_common_pars_fragment>\n// #include <envmap_pars_fragment>\n// #include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n\n// #include <bsdfs>\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\n\n#include <lights_pars_begin>\n\n// #include <lights_phong_pars_fragment>\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n\nstruct MToonMaterial {\n vec3 diffuseColor;\n vec3 shadeColor;\n float shadingGrade;\n float receiveShadow;\n};\n\n#define Material_LightProbeLOD( material ) (0)\n\n#include <shadowmap_pars_fragment>\n// #include <bumpmap_pars_fragment>\n\n// #include <normalmap_pars_fragment>\n#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n\n#endif\n\n#ifdef OBJECTSPACE_NORMALMAP\n\n uniform mat3 normalMatrix;\n\n#endif\n\n#if ! defined ( USE_TANGENT ) && defined ( TANGENTSPACE_NORMALMAP )\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n // three-vrm specific change: it requires `uv` as an input in order to support uv scrolls\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n vec3 N = normalize( surf_norm );\n\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n if ( length( T ) == 0.0 || length( B ) == 0.0 ) {\n return surf_norm;\n }\n\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\n return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\n }\n\n #else\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\n // Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n float scale = sign( st1.t * st0.s - st0.t * st1.s ); // we do not care about the magnitude\n\n vec3 S = ( q0 * st1.t - q1 * st0.t ) * scale;\n vec3 T = ( - q0 * st1.s + q1 * st0.s ) * scale;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n\n if ( length( S ) == 0.0 || length( T ) == 0.0 ) {\n return surf_norm;\n }\n\n S = normalize( S );\n T = normalize( T );\n vec3 N = normalize( surf_norm );\n\n #ifdef DOUBLE_SIDED\n\n // Workaround for Adreno GPUs gl_FrontFacing bug. See #15850 and #10331\n\n bool frontFacing = dot( cross( S, T ), N ) > 0.0;\n\n mapN.xy *= ( float( frontFacing ) * 2.0 - 1.0 );\n\n #else\n\n mapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n #endif\n\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n #endif\n\n#endif\n\n// #include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\n// == lighting stuff ===========================================================\nfloat getLightIntensity(\n const in IncidentLight directLight,\n const in GeometricContext geometry,\n const in float shadow,\n const in float shadingGrade\n) {\n float lightIntensity = dot( geometry.normal, directLight.direction );\n lightIntensity = 0.5 + 0.5 * lightIntensity;\n lightIntensity = lightIntensity * shadow;\n lightIntensity = lightIntensity * shadingGrade;\n lightIntensity = lightIntensity * 2.0 - 1.0;\n return shadeToony == 1.0\n ? step( shadeShift, lightIntensity )\n : smoothstep( shadeShift, shadeShift + ( 1.0 - shadeToony ), lightIntensity );\n}\n\nvec3 getLighting( const in vec3 lightColor ) {\n vec3 lighting = lightColor;\n lighting = mix(\n lighting,\n vec3( max( 0.001, max( lighting.x, max( lighting.y, lighting.z ) ) ) ),\n lightColorAttenuation\n );\n\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lighting *= PI;\n #endif\n\n return lighting;\n}\n\nvec3 getDiffuse(\n const in MToonMaterial material,\n const in float lightIntensity,\n const in vec3 lighting\n) {\n #ifdef DEBUG_LITSHADERATE\n return vec3( BRDF_Lambert( lightIntensity * lighting ) );\n #endif\n\n return lighting * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, lightIntensity ) );\n}\n\n// == post correction ==========================================================\nvoid postCorrection() {\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}\n\n// == main procedure ===========================================================\nvoid main() {\n #include <clipping_planes_fragment>\n\n vec2 uv = vec2(0.5, 0.5);\n\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n uv = vUv;\n\n float uvAnimMask = 1.0;\n #ifdef USE_UVANIMMASKTEXTURE\n uvAnimMask = texture2D( uvAnimMaskTexture, uv ).x;\n #endif\n\n uv = uv + vec2( uvAnimOffsetX, uvAnimOffsetY ) * uvAnimMask;\n float uvRotCos = cos( uvAnimTheta * uvAnimMask );\n float uvRotSin = sin( uvAnimTheta * uvAnimMask );\n uv = mat2( uvRotCos, uvRotSin, -uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5;\n #endif\n\n #ifdef DEBUG_UV\n gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n gl_FragColor = vec4( uv, 0.0, 1.0 );\n #endif\n return;\n #endif\n\n vec4 diffuseColor = vec4( color, colorAlpha );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissionColor;\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n diffuseColor *= mapTexelToLinear( texture2D( map, uv ) );\n #endif\n\n #include <color_fragment>\n // #include <alphamap_fragment>\n\n // -- MToon: alpha -----------------------------------------------------------\n // #include <alphatest_fragment>\n #ifdef BLENDMODE_CUTOUT\n if ( diffuseColor.a <= cutoff ) { discard; }\n diffuseColor.a = 1.0;\n #endif\n\n #ifdef BLENDMODE_OPAQUE\n diffuseColor.a = 1.0;\n #endif\n\n #if defined( OUTLINE ) && defined( OUTLINE_COLOR_FIXED ) // omitting DebugMode\n gl_FragColor = vec4( outlineColor, diffuseColor.a );\n postCorrection();\n return;\n #endif\n\n // #include <specularmap_fragment>\n #include <normal_fragment_begin>\n\n #ifdef OUTLINE\n normal *= -1.0;\n #endif\n\n // #include <normal_fragment_maps>\n\n #ifdef OBJECTSPACE_NORMALMAP\n\n normal = texture2D( normalMap, uv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals\n\n #ifdef FLIP_SIDED\n\n normal = - normal;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n normal = normal * faceDirection;\n\n #else\n\n normal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n #endif\n\n #endif\n\n normal = normalize( normalMatrix * normal );\n\n #elif defined( TANGENTSPACE_NORMALMAP )\n\n vec3 mapN = texture2D( normalMap, uv ).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n\n #ifdef USE_TANGENT\n\n normal = normalize( vTBN * mapN );\n\n #else\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection );\n\n #else\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN );\n\n #endif\n\n #endif\n\n #endif\n\n // #include <emissivemap_fragment>\n #ifdef USE_EMISSIVEMAP\n totalEmissiveRadiance *= emissiveMapTexelToLinear( texture2D( emissiveMap, uv ) ).rgb;\n #endif\n\n #ifdef DEBUG_NORMAL\n gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 );\n return;\n #endif\n\n // -- MToon: lighting --------------------------------------------------------\n // accumulation\n // #include <lights_phong_fragment>\n MToonMaterial material;\n\n material.diffuseColor = diffuseColor.rgb;\n\n material.shadeColor = shadeColor;\n #ifdef USE_SHADETEXTURE\n material.shadeColor *= shadeTextureTexelToLinear( texture2D( shadeTexture, uv ) ).rgb;\n #endif\n\n material.shadingGrade = 1.0;\n #ifdef USE_SHADINGGRADETEXTURE\n material.shadingGrade = 1.0 - shadingGradeRate * ( 1.0 - texture2D( shadingGradeTexture, uv ).r );\n #endif\n\n material.receiveShadow = receiveShadowRate;\n #ifdef USE_RECEIVESHADOWTEXTURE\n material.receiveShadow *= texture2D( receiveShadowTexture, uv ).a;\n #endif\n\n // #include <lights_fragment_begin>\n GeometricContext geometry;\n\n geometry.position = - vViewPosition;\n geometry.normal = normal;\n geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n IncidentLight directLight;\n vec3 lightingSum = vec3( 0.0 );\n\n // since these variables will be used in unrolled loop, we have to define in prior\n float atten, shadow, lightIntensity;\n vec3 lighting;\n\n #if ( NUM_POINT_LIGHTS > 0 )\n PointLight pointLight;\n\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getPointLightInfo( pointLight, geometry, directLight );\n #else\n getPointDirectLightIrradiance( pointLight, geometry, directLight );\n #endif\n\n atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n atten = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n\n shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n #if ( NUM_SPOT_LIGHTS > 0 )\n SpotLight spotLight;\n\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getSpotLightInfo( spotLight, geometry, directLight );\n #else\n getSpotDirectLightIrradiance( spotLight, geometry, directLight );\n #endif\n\n atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n atten = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n\n shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n #if ( NUM_DIR_LIGHTS > 0 )\n DirectionalLight directionalLight;\n\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getDirectionalLightInfo( directionalLight, geometry, directLight );\n #else\n getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n #endif\n\n atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n atten = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n\n shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n // #if defined( RE_IndirectDiffuse )\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #if THREE_VRM_THREE_REVISION >= 133\n irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n #else\n irradiance += getLightProbeIrradiance( lightProbe, geometry );\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n }\n #pragma unroll_loop_end\n #endif\n // #endif\n\n // #include <lights_fragment_maps>\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vUv2 );\n vec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lightMapIrradiance *= PI;\n #endif\n irradiance += lightMapIrradiance;\n #endif\n\n // #include <lights_fragment_end>\n // RE_IndirectDiffuse here\n reflectedLight.indirectDiffuse += indirectLightIntensity * irradiance * BRDF_Lambert( material.diffuseColor );\n\n // modulation\n #include <aomap_fragment>\n\n vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\n // The "comment out if you want to PBR absolutely" line\n #ifndef DEBUG_LITSHADERATE\n col = min(col, material.diffuseColor);\n #endif\n\n #if defined( OUTLINE ) && defined( OUTLINE_COLOR_MIXED )\n gl_FragColor = vec4(\n outlineColor.rgb * mix( vec3( 1.0 ), col, outlineLightingMix ),\n diffuseColor.a\n );\n postCorrection();\n return;\n #endif\n\n #ifdef DEBUG_LITSHADERATE\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n return;\n #endif\n\n // -- MToon: parametric rim lighting -----------------------------------------\n vec3 viewDir = normalize( vViewPosition );\n vec3 rimMix = mix( vec3( 1.0 ), lightingSum + indirectLightIntensity * irradiance, rimLightingMix );\n vec3 rim = rimColor * pow( saturate( 1.0 - dot( viewDir, normal ) + rimLift ), rimFresnelPower );\n #ifdef USE_RIMTEXTURE\n rim *= rimTextureTexelToLinear( texture2D( rimTexture, uv ) ).rgb;\n #endif\n col += rim;\n\n // -- MToon: additive matcap -------------------------------------------------\n #ifdef USE_SPHEREADD\n {\n vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) );\n vec3 y = cross( viewDir, x ); // guaranteed to be normalized\n vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) );\n vec3 matcap = sphereAddTexelToLinear( texture2D( sphereAdd, sphereUv ) ).xyz;\n col += matcap;\n }\n #endif\n\n // -- MToon: Emission --------------------------------------------------------\n col += totalEmissiveRadiance;\n\n // #include <envmap_fragment>\n\n // -- Almost done! -----------------------------------------------------------\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n}',this.needsUpdate=!0}_updateCullFace(){this.isOutline?this.outlineCullMode===e.MToonMaterialCullMode.Off?this.side=r.DoubleSide:this.outlineCullMode===e.MToonMaterialCullMode.Front?this.side=r.BackSide:this.outlineCullMode===e.MToonMaterialCullMode.Back&&(this.side=r.FrontSide):this.cullMode===e.MToonMaterialCullMode.Off?this.side=r.DoubleSide:this.cullMode===e.MToonMaterialCullMode.Front?this.side=r.BackSide:this.cullMode===e.MToonMaterialCullMode.Back&&(this.side=r.FrontSide)}}var se;e.VRMUnlitMaterialRenderType=void 0,(se=e.VRMUnlitMaterialRenderType||(e.VRMUnlitMaterialRenderType={}))[se.Opaque=0]="Opaque",se[se.Cutout=1]="Cutout",se[se.Transparent=2]="Transparent",se[se.TransparentWithZWrite=3]="TransparentWithZWrite";class le extends r.ShaderMaterial{constructor(t){super(),this.isVRMUnlitMaterial=!0,this.cutoff=.5,this.map=null,this.mainTex_ST=new r.Vector4(0,0,1,1),this._renderType=e.VRMUnlitMaterialRenderType.Opaque,this.shouldApplyUniforms=!0,void 0===t&&(t={}),t.fog=!0,t.clipping=!0,parseInt(r.REVISION,10)<129&&(t.skinning=t.skinning||!1),parseInt(r.REVISION,10)<131&&(t.morphTargets=t.morphTargets||!1,t.morphNormals=t.morphNormals||!1),t.uniforms=r.UniformsUtils.merge([r.UniformsLib.common,r.UniformsLib.fog,{cutoff:{value:.5},mainTex_ST:{value:new r.Vector4(0,0,1,1)}}]),this.setValues(t),this._updateShaderCode(),this._applyUniforms()}get mainTex(){return this.map}set mainTex(e){this.map=e}get renderType(){return this._renderType}set renderType(t){this._renderType=t,this.depthWrite=this._renderType!==e.VRMUnlitMaterialRenderType.Transparent,this.transparent=this._renderType===e.VRMUnlitMaterialRenderType.Transparent||this._renderType===e.VRMUnlitMaterialRenderType.TransparentWithZWrite,this._updateShaderCode()}updateVRMMaterials(e){this._applyUniforms()}copy(e){return super.copy(e),this.cutoff=e.cutoff,this.map=e.map,this.mainTex_ST.copy(e.mainTex_ST),this.renderType=e.renderType,this}_applyUniforms(){this.shouldApplyUniforms&&(this.shouldApplyUniforms=!1,this.uniforms.cutoff.value=this.cutoff,this.uniforms.map.value=this.map,this.uniforms.mainTex_ST.value.copy(this.mainTex_ST))}_updateShaderCode(){this.defines={RENDERTYPE_OPAQUE:this._renderType===e.VRMUnlitMaterialRenderType.Opaque,RENDERTYPE_CUTOUT:this._renderType===e.VRMUnlitMaterialRenderType.Cutout,RENDERTYPE_TRANSPARENT:this._renderType===e.VRMUnlitMaterialRenderType.Transparent||this._renderType===e.VRMUnlitMaterialRenderType.TransparentWithZWrite},this.vertexShader="#include <common>\n\n// #include <uv_pars_vertex>\n#ifdef USE_MAP\n varying vec2 vUv;\n uniform vec4 mainTex_ST;\n#endif\n\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef USE_MAP\n vUv = vec2( mainTex_ST.p * uv.x + mainTex_ST.s, mainTex_ST.q * uv.y + mainTex_ST.t );\n #endif\n\n #include <uv2_vertex>\n #include <color_vertex>\n #include <skinbase_vertex>\n\n #ifdef USE_ENVMAP\n\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n\n #endif\n\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n\n #include <worldpos_vertex>\n #include <clipping_planes_vertex>\n #include <envmap_vertex>\n #include <fog_vertex>\n\n}",this.fragmentShader="#ifdef RENDERTYPE_CUTOUT\n uniform float cutoff;\n#endif\n\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n// #include <alphamap_pars_fragment>\n// #include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n// #include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n// #include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\n// == main procedure ===========================================================\nvoid main() {\n #include <clipping_planes_fragment>\n\n vec4 diffuseColor = vec4( 1.0 );\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n diffuseColor *= mapTexelToLinear( texture2D( map, vUv ) );\n #endif\n\n #include <color_fragment>\n // #include <alphamap_fragment>\n\n // MToon: alpha\n // #include <alphatest_fragment>\n #ifdef RENDERTYPE_CUTOUT\n if ( diffuseColor.a <= cutoff ) { discard; }\n diffuseColor.a = 1.0;\n #endif\n\n #ifdef RENDERTYPE_OPAQUE\n diffuseColor.a = 1.0;\n #endif\n\n // #include <specularmap_fragment>\n\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\n // accumulation (baked indirect lighting only)\n #ifdef USE_LIGHTMAP\n reflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n #else\n reflectedLight.indirectDiffuse += vec3( 1.0 );\n #endif\n\n // modulation\n // #include <aomap_fragment>\n\n reflectedLight.indirectDiffuse *= diffuseColor.rgb;\n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n // #include <envmap_fragment>\n\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n #include <premultiplied_alpha_fragment>\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n}",this.needsUpdate=!0}}class de{constructor(e={}){this._encoding=e.encoding||r.LinearEncoding,this._encoding!==r.LinearEncoding&&this._encoding!==r.sRGBEncoding&&console.warn("The specified color encoding might not work properly with VRMMaterialImporter. You might want to use THREE.sRGBEncoding instead."),this._requestEnvMap=e.requestEnvMap}convertGLTFMaterials(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.materialProperties;if(!i)return null;const r=yield y(e),a={},s=[];return yield Promise.all(Array.from(r.entries()).map((([t,n])=>o(this,void 0,void 0,(function*(){const r=e.parser.json.nodes[t],l=e.parser.json.meshes[r.mesh];yield Promise.all(n.map(((t,n)=>o(this,void 0,void 0,(function*(){const r=l.primitives[n];if(!r)return;const o=t.geometry,d=o.index?o.index.count:o.attributes.position.count/3;Array.isArray(t.material)||(t.material=[t.material],o.addGroup(0,d,0));const h=r.material;let u,c=i[h];c||(console.warn(`VRMMaterialImporter: There are no material definition for material #${h} on VRM extension.`),c={shader:"VRM_USE_GLTFSHADER"}),a[h]?u=a[h]:(u=yield this.createVRMMaterials(t.material[0],c,e),a[h]=u,s.push(u.surface),u.outline&&s.push(u.outline)),t.material[0]=u.surface,this._requestEnvMap&&u.surface.isMeshStandardMaterial&&this._requestEnvMap().then((e=>{u.surface.envMap=e,u.surface.needsUpdate=!0})),t.renderOrder=c.renderQueue||2e3,u.outline&&(t.material[1]=u.outline,o.addGroup(0,d,1))})))))}))))),s}))}createVRMMaterials(t,n,i){return o(this,void 0,void 0,(function*(){let r,o;if("VRM/MToon"===n.shader){const a=yield this._extractMaterialProperties(t,n,i);["srcBlend","dstBlend","isFirstSetup"].forEach((e=>{void 0!==a[e]&&delete a[e]})),["mainTex","shadeTexture","emissionMap","sphereAdd","rimTexture"].forEach((e=>{void 0!==a[e]&&(a[e].encoding=this._encoding)})),a.encoding=this._encoding,r=new ae(a),a.outlineWidthMode!==e.MToonMaterialOutlineWidthMode.None&&(a.isOutline=!0,o=new ae(a))}else if("VRM/UnlitTexture"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.Opaque,r=new le(o)}else if("VRM/UnlitCutout"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.Cutout,r=new le(o)}else if("VRM/UnlitTransparent"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.Transparent,r=new le(o)}else if("VRM/UnlitTransparentZWrite"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.TransparentWithZWrite,r=new le(o)}else"VRM_USE_GLTFSHADER"!==n.shader&&console.warn(`Unknown shader detected: "${n.shader}"`),r=this._convertGLTFMaterial(t.clone());return r.name=t.name,r.userData=JSON.parse(JSON.stringify(t.userData)),r.userData.vrmMaterialProperties=n,o&&(o.name=t.name+" (Outline)",o.userData=JSON.parse(JSON.stringify(t.userData)),o.userData.vrmMaterialProperties=n),{surface:r,outline:o}}))}_renameMaterialProperty(e){return"_"!==e[0]?(console.warn(`VRMMaterials: Given property name "${e}" might be invalid`),e):(e=e.substring(1),/[A-Z]/.test(e[0])?e[0].toLowerCase()+e.substring(1):(console.warn(`VRMMaterials: Given property name "${e}" might be invalid`),e))}_convertGLTFMaterial(e){if(e.isMeshStandardMaterial){const t=e;t.map&&(t.map.encoding=this._encoding),t.emissiveMap&&(t.emissiveMap.encoding=this._encoding),this._encoding===r.LinearEncoding&&(t.color.convertLinearToSRGB(),t.emissive.convertLinearToSRGB())}if(e.isMeshBasicMaterial){const t=e;t.map&&(t.map.encoding=this._encoding),this._encoding===r.LinearEncoding&&t.color.convertLinearToSRGB()}return e}_extractMaterialProperties(e,t,n){const i=[],o={};if(t.textureProperties)for(const e of Object.keys(t.textureProperties)){const r=this._renameMaterialProperty(e),a=t.textureProperties[e];i.push(n.parser.getDependency("texture",a).then((e=>{o[r]=e})))}if(t.floatProperties)for(const e of Object.keys(t.floatProperties)){const n=this._renameMaterialProperty(e);o[n]=t.floatProperties[e]}if(t.vectorProperties)for(const e of Object.keys(t.vectorProperties)){let n=this._renameMaterialProperty(e);["_MainTex","_ShadeTexture","_BumpMap","_ReceiveShadowTexture","_ShadingGradeTexture","_RimTexture","_SphereAdd","_EmissionMap","_OutlineWidthTexture","_UvAnimMaskTexture"].some((t=>e===t))&&(n+="_ST"),o[n]=new r.Vector4(...t.vectorProperties[e])}return parseInt(r.REVISION,10)<129&&(o.skinning=e.skinning||!1),parseInt(r.REVISION,10)<131&&(o.morphTargets=e.morphTargets||!1,o.morphNormals=e.morphNormals||!1),Promise.all(i).then((()=>o))}}class he{constructor(e){var t;this.ignoreTexture=null!==(t=null==e?void 0:e.ignoreTexture)&&void 0!==t&&t}import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.meta;if(!i)return null;let r;return this.ignoreTexture||null==i.texture||-1===i.texture||(r=yield e.parser.getDependency("texture",i.texture)),{allowedUserName:i.allowedUserName,author:i.author,commercialUssageName:i.commercialUssageName,contactInformation:i.contactInformation,licenseName:i.licenseName,otherLicenseUrl:i.otherLicenseUrl,otherPermissionUrl:i.otherPermissionUrl,reference:i.reference,sexualUssageName:i.sexualUssageName,texture:null!=r?r:void 0,title:i.title,version:i.version,violentUssageName:i.violentUssageName}}))}}const ue=new r.Matrix4;function ce(e){return e.invert?e.invert():e.getInverse(ue.copy(e)),e}class pe{constructor(e){this._inverseCache=new r.Matrix4,this._shouldUpdateInverse=!0,this.matrix=e;const t={set:(e,t,n)=>(this._shouldUpdateInverse=!0,e[t]=n,!0)};this._originalElements=e.elements,e.elements=new Proxy(e.elements,t)}get inverse(){return this._shouldUpdateInverse&&(ce(this._inverseCache.copy(this.matrix)),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}}const me=Object.freeze(new r.Matrix4),fe=Object.freeze(new r.Quaternion),ge=new r.Vector3,_e=new r.Vector3,ve=new r.Vector3,Me=new r.Quaternion,Te=new r.Matrix4,ye=new r.Matrix4;class xe{constructor(e,t={}){var n,i,o,a,s,l;if(this._currentTail=new r.Vector3,this._prevTail=new r.Vector3,this._nextTail=new r.Vector3,this._boneAxis=new r.Vector3,this._centerSpacePosition=new r.Vector3,this._center=null,this._parentWorldRotation=new r.Quaternion,this._initialLocalMatrix=new r.Matrix4,this._initialLocalRotation=new r.Quaternion,this._initialLocalChildPosition=new r.Vector3,this.bone=e,this.bone.matrixAutoUpdate=!1,this.radius=null!==(n=t.radius)&&void 0!==n?n:.02,this.stiffnessForce=null!==(i=t.stiffnessForce)&&void 0!==i?i:1,this.gravityDir=t.gravityDir?(new r.Vector3).copy(t.gravityDir):(new r.Vector3).set(0,-1,0),this.gravityPower=null!==(o=t.gravityPower)&&void 0!==o?o:0,this.dragForce=null!==(a=t.dragForce)&&void 0!==a?a:.4,this.colliders=null!==(s=t.colliders)&&void 0!==s?s:[],this._centerSpacePosition.setFromMatrixPosition(this.bone.matrixWorld),this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),0===this.bone.children.length)this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);else{const e=this.bone.children[0];this._initialLocalChildPosition.copy(e.position)}this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)),this._prevTail.copy(this._currentTail),this._nextTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize(),this._centerSpaceBoneLength=ge.copy(this._initialLocalChildPosition).applyMatrix4(this.bone.matrixWorld).sub(this._centerSpacePosition).length(),this.center=null!==(l=t.center)&&void 0!==l?l:null}get center(){return this._center}set center(e){var t;this._getMatrixCenterToWorld(Te),this._currentTail.applyMatrix4(Te),this._prevTail.applyMatrix4(Te),this._nextTail.applyMatrix4(Te),(null===(t=this._center)||void 0===t?void 0:t.userData.inverseCacheProxy)&&(this._center.userData.inverseCacheProxy.revert(),delete this._center.userData.inverseCacheProxy),this._center=e,this._center&&(this._center.userData.inverseCacheProxy||(this._center.userData.inverseCacheProxy=new pe(this._center.matrixWorld))),this._getMatrixWorldToCenter(Te),this._currentTail.applyMatrix4(Te),this._prevTail.applyMatrix4(Te),this._nextTail.applyMatrix4(Te),Te.multiply(this.bone.matrixWorld),this._centerSpacePosition.setFromMatrixPosition(Te),this._centerSpaceBoneLength=ge.copy(this._initialLocalChildPosition).applyMatrix4(Te).sub(this._centerSpacePosition).length()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix),this._centerSpacePosition.setFromMatrixPosition(this.bone.matrixWorld),this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)),this._prevTail.copy(this._currentTail),this._nextTail.copy(this._currentTail)}update(e){if(e<=0)return;this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix),this.bone.parent?E(this.bone.parent,this._parentWorldRotation):this._parentWorldRotation.copy(fe),this._getMatrixWorldToCenter(Te),Te.multiply(this.bone.matrixWorld),this._centerSpacePosition.setFromMatrixPosition(Te),this._getMatrixWorldToCenter(ye),ye.multiply(this._getParentMatrixWorld());const t=this.stiffnessForce*e,n=_e.copy(this.gravityDir).multiplyScalar(this.gravityPower*e);this._nextTail.copy(this._currentTail).add(ge.copy(this._currentTail).sub(this._prevTail).multiplyScalar(1-this.dragForce)).add(ge.copy(this._boneAxis).applyMatrix4(this._initialLocalMatrix).applyMatrix4(ye).sub(this._centerSpacePosition).normalize().multiplyScalar(t)).add(n),this._nextTail.sub(this._centerSpacePosition).normalize().multiplyScalar(this._centerSpaceBoneLength).add(this._centerSpacePosition),this._collision(this._nextTail),this._prevTail.copy(this._currentTail),this._currentTail.copy(this._nextTail);const i=ce(Te.copy(ye.multiply(this._initialLocalMatrix))),r=Me.setFromUnitVectors(this._boneAxis,ge.copy(this._nextTail).applyMatrix4(i).normalize());this.bone.quaternion.copy(this._initialLocalRotation).multiply(r),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix)}_collision(e){this.colliders.forEach((t=>{this._getMatrixWorldToCenter(Te),Te.multiply(t.matrixWorld);const n=ge.setFromMatrixPosition(Te),i=t.geometry.boundingSphere.radius,r=this.radius+i;if(e.distanceToSquared(n)<=r*r){const t=_e.subVectors(e,n).normalize(),i=ve.addVectors(n,t.multiplyScalar(r));e.copy(i.sub(this._centerSpacePosition).normalize().multiplyScalar(this._centerSpaceBoneLength).add(this._centerSpacePosition))}}))}_getMatrixCenterToWorld(e){return this._center?e.copy(this._center.matrixWorld):e.identity(),e}_getMatrixWorldToCenter(e){return this._center?e.copy(this._center.userData.inverseCacheProxy.inverse):e.identity(),e}_getParentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:me}}class Se{constructor(e,t){this.colliderGroups=[],this.springBoneGroupList=[],this.colliderGroups=e,this.springBoneGroupList=t}setCenter(e){this.springBoneGroupList.forEach((t=>{t.forEach((t=>{t.center=e}))}))}lateUpdate(e){this.springBoneGroupList.forEach((t=>{t.forEach((t=>{t.update(e)}))}))}reset(){this.springBoneGroupList.forEach((e=>{e.forEach((e=>{e.reset()}))}))}}const Re=new r.Vector3,Ee=new r.MeshBasicMaterial({visible:!1});class Le{import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.secondaryAnimation;if(!i)return null;const r=yield this._importColliderMeshGroups(e,i),o=yield this._importSpringBoneGroupList(e,i,r);return new Se(r,o)}))}_createSpringBone(e,t={}){return new xe(e,t)}_importSpringBoneGroupList(e,t,n){return o(this,void 0,void 0,(function*(){const i=t.boneGroups||[],a=[];return yield Promise.all(i.map((t=>o(this,void 0,void 0,(function*(){if(void 0===t.stiffiness||void 0===t.gravityDir||void 0===t.gravityDir.x||void 0===t.gravityDir.y||void 0===t.gravityDir.z||void 0===t.gravityPower||void 0===t.dragForce||void 0===t.hitRadius||void 0===t.colliderGroups||void 0===t.bones||void 0===t.center)return;const i=t.stiffiness,s=new r.Vector3(t.gravityDir.x,t.gravityDir.y,-t.gravityDir.z),l=t.gravityPower,d=t.dragForce,h=t.hitRadius,u=[];t.colliderGroups.forEach((e=>{u.push(...n[e].colliders)}));const c=[];yield Promise.all(t.bones.map((n=>o(this,void 0,void 0,(function*(){const r=yield e.parser.getDependency("node",n),o=-1!==t.center?yield e.parser.getDependency("node",t.center):null;r&&r.traverse((e=>{const t=this._createSpringBone(e,{radius:h,stiffnessForce:i,gravityDir:s,gravityPower:l,dragForce:d,colliders:u,center:o});c.push(t)}))}))))),a.push(c)}))))),a}))}_importColliderMeshGroups(e,t){return o(this,void 0,void 0,(function*(){const n=t.colliderGroups;if(void 0===n)return[];const i=[];return n.forEach((t=>o(this,void 0,void 0,(function*(){if(void 0===t.node||void 0===t.colliders)return;const n=yield e.parser.getDependency("node",t.node),r=[];t.colliders.forEach((e=>{if(void 0===e.offset||void 0===e.offset.x||void 0===e.offset.y||void 0===e.offset.z||void 0===e.radius)return;const t=Re.set(e.offset.x,e.offset.y,-e.offset.z),i=this._createColliderMesh(e.radius,t);n.add(i),r.push(i)}));const o={node:t.node,colliders:r};i.push(o)})))),i}))}_createColliderMesh(e,t){const n=new r.Mesh(new r.SphereBufferGeometry(e,8,4),Ee);return n.position.copy(t),n.name="vrmColliderSphere",n.geometry.computeBoundingSphere(),n}}class we{constructor(e={}){this._metaImporter=e.metaImporter||new he,this._blendShapeImporter=e.blendShapeImporter||new w,this._lookAtImporter=e.lookAtImporter||new J,this._humanoidImporter=e.humanoidImporter||new G,this._firstPersonImporter=e.firstPersonImporter||new I,this._materialImporter=e.materialImporter||new de,this._springBoneImporter=e.springBoneImporter||new Le}import(e){return o(this,void 0,void 0,(function*(){if(void 0===e.parser.json.extensions||void 0===e.parser.json.extensions.VRM)throw new Error("Could not find VRM extension on the GLTF");const t=e.scene;t.updateMatrixWorld(!1),t.traverse((e=>{e.isMesh&&(e.frustumCulled=!1)}));const n=(yield this._metaImporter.import(e))||void 0,i=(yield this._materialImporter.convertGLTFMaterials(e))||void 0,r=(yield this._humanoidImporter.import(e))||void 0,o=r&&(yield this._firstPersonImporter.import(e,r))||void 0,a=(yield this._blendShapeImporter.import(e))||void 0,s=o&&a&&r&&(yield this._lookAtImporter.import(e,o,a,r))||void 0,l=(yield this._springBoneImporter.import(e))||void 0;return new Pe({scene:e.scene,meta:n,materials:i,humanoid:r,firstPerson:o,blendShapeProxy:a,lookAt:s,springBoneManager:l})}))}}class Pe{constructor(e){this.scene=e.scene,this.humanoid=e.humanoid,this.blendShapeProxy=e.blendShapeProxy,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt,this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.meta=e.meta}static from(e,t={}){return o(this,void 0,void 0,(function*(){const n=new we(t);return yield n.import(e)}))}update(e){this.lookAt&&this.lookAt.update(e),this.blendShapeProxy&&this.blendShapeProxy.update(),this.springBoneManager&&this.springBoneManager.lateUpdate(e),this.materials&&this.materials.forEach((t=>{t.updateVRMMaterials&&t.updateVRMMaterials(e)}))}dispose(){var e,t;const n=this.scene;n&&n.traverse(s),null===(t=null===(e=this.meta)||void 0===e?void 0:e.texture)||void 0===t||t.dispose()}}const Ae=new r.Vector2,be=new r.OrthographicCamera(-1,1,-1,1,-1,1),Oe=new r.MeshBasicMaterial({color:16777215,side:r.DoubleSide}),Ce=new r.Mesh(new r.PlaneBufferGeometry(2,2),Oe),Ie=new r.Scene;Ie.add(Ce);class Ve{constructor(){}}Ve.extractThumbnailBlob=function(e,t,n=512){var i;const r=null===(i=t.meta)||void 0===i?void 0:i.texture;if(!r)throw new Error("extractThumbnailBlob: This VRM does not have a thumbnail");const o=e.getContext().canvas;e.getSize(Ae);const a=Ae.x,s=Ae.y;return e.setSize(n,n,!1),Oe.map=r,e.render(Ie,be),Oe.map=null,o instanceof OffscreenCanvas?o.convertToBlob().finally((()=>{e.setSize(a,s,!1)})):new Promise(((t,n)=>{o.toBlob((i=>{e.setSize(a,s,!1),null==i?n("extractThumbnailBlob: Failed to create a blob"):t(i)}))}))},Ve.removeUnnecessaryJoints=function(e){const t=new Map;e.traverse((e=>{if("SkinnedMesh"!==e.type)return;const n=e,i=n.geometry.getAttribute("skinIndex");let o=t.get(i);if(!o){const e=[],a=[],s={},l=i.array;for(let t=0;t<l.length;t++){const i=l[t];void 0===s[i]&&(s[i]=e.length,e.push(n.skeleton.bones[i]),a.push(n.skeleton.boneInverses[i])),l[t]=s[i]}i.copyArray(l),i.needsUpdate=!0,o=new r.Skeleton(e,a),t.set(i,o)}n.bind(o,new r.Matrix4)}))},Ve.removeUnnecessaryVertices=function(e){const n=new Map;e.traverse((e=>{var i,o,a,s;if(!e.isMesh)return;const l=e,d=l.geometry,h=d.index;if(null==h)return;const u=n.get(d);if(null!=u)return void(l.geometry=u);const c=new r.BufferGeometry;c.name=d.name,c.morphTargetsRelative=d.morphTargetsRelative,d.groups.forEach((e=>{c.addGroup(e.start,e.count,e.materialIndex)})),c.boundingBox=null!==(o=null===(i=d.boundingBox)||void 0===i?void 0:i.clone())&&void 0!==o?o:null,c.boundingSphere=null!==(s=null===(a=d.boundingSphere)||void 0===a?void 0:a.clone())&&void 0!==s?s:null,c.setDrawRange(d.drawRange.start,d.drawRange.count),c.userData=d.userData,n.set(d,c);const p=[],m=[];{const e=h.array,n=new e.constructor(e.length);let i=0;for(let t=0;t<e.length;t++){const r=e[t];let o=p[r];null==o&&(p[r]=i,m[i]=r,o=i,i++),n[t]=o}c.setIndex(new t.BufferAttribute(n,1,!1))}Object.keys(d.attributes).forEach((e=>{const n=d.attributes[e];if(n.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const i=n.array,{itemSize:r,normalized:o}=n,a=new i.constructor(m.length*r);m.forEach(((e,t)=>{for(let n=0;n<r;n++)a[t*r+n]=i[e*r+n]})),c.setAttribute(e,new t.BufferAttribute(a,r,o))}));let f=!0;Object.keys(d.morphAttributes).forEach((e=>{c.morphAttributes[e]=[];const n=d.morphAttributes[e];for(let i=0;i<n.length;i++){const r=n[i];if(r.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const o=r.array,{itemSize:a,normalized:s}=r,l=new o.constructor(m.length*a);m.forEach(((e,t)=>{for(let n=0;n<a;n++)l[t*a+n]=o[e*a+n]})),f=f&&l.every((e=>0===e)),c.morphAttributes[e][i]=new t.BufferAttribute(l,a,s)}})),f&&(c.morphAttributes={}),l.geometry=c})),Array.from(n.keys()).forEach((e=>{e.dispose()}))};const De=new r.Vector3;class Ne extends q{setupHelper(e,t){t.disableFaceDirectionHelper||(this._faceDirectionHelper=new r.ArrowHelper(new r.Vector3(0,0,-1),new r.Vector3(0,0,0),.5,16711935),e.add(this._faceDirectionHelper))}update(e){super.update(e),this._faceDirectionHelper&&(this.firstPerson.getFirstPersonWorldPosition(this._faceDirectionHelper.position),this._faceDirectionHelper.setDirection(this.getLookAtWorldDirection(De)))}}class Ue extends J{import(e,t,n,i){var r;const o=null===(r=e.parser.json.extensions)||void 0===r?void 0:r.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=this._importApplyer(a,n,i);return new Ne(t,s||void 0)}}const Be=new r.MeshBasicMaterial({color:16711935,wireframe:!0,transparent:!0,depthTest:!1});class Ge extends Se{setupHelper(e,t){t.disableSpringBoneHelper||(this.springBoneGroupList.forEach((t=>{t.forEach((t=>{if(t.getGizmo){const n=t.getGizmo();e.add(n)}}))})),this.colliderGroups.forEach((e=>{e.colliders.forEach((e=>{e.material=Be,e.renderOrder=ze}))})))}}const ke=new r.Vector3;class Fe extends xe{constructor(e,t){super(e,t)}getGizmo(){if(this._gizmo)return this._gizmo;const e=ke.copy(this._nextTail).sub(this._centerSpacePosition),t=e.length();return this._gizmo=new r.ArrowHelper(e.normalize(),this._centerSpacePosition,t,16776960,this.radius,this.radius),this._gizmo.line.renderOrder=ze,this._gizmo.cone.renderOrder=ze,this._gizmo.line.material.depthTest=!1,this._gizmo.line.material.transparent=!0,this._gizmo.cone.material.depthTest=!1,this._gizmo.cone.material.transparent=!0,this._gizmo}update(e){super.update(e),this._updateGizmo()}_updateGizmo(){if(!this._gizmo)return;const e=ke.copy(this._currentTail).sub(this._centerSpacePosition),t=e.length();this._gizmo.setDirection(e.normalize()),this._gizmo.setLength(t,this.radius,this.radius),this._gizmo.position.copy(this._centerSpacePosition)}}class He extends Le{import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.secondaryAnimation;if(!i)return null;const r=yield this._importColliderMeshGroups(e,i),o=yield this._importSpringBoneGroupList(e,i,r);return new Ge(r,o)}))}_createSpringBone(e,t){return new Fe(e,t)}}class We extends we{constructor(e={}){e.lookAtImporter=e.lookAtImporter||new Ue,e.springBoneImporter=e.springBoneImporter||new He,super(e)}import(e,t={}){return o(this,void 0,void 0,(function*(){if(void 0===e.parser.json.extensions||void 0===e.parser.json.extensions.VRM)throw new Error("Could not find VRM extension on the GLTF");const n=e.scene;n.updateMatrixWorld(!1),n.traverse((e=>{e.isMesh&&(e.frustumCulled=!1)}));const i=(yield this._metaImporter.import(e))||void 0,r=(yield this._materialImporter.convertGLTFMaterials(e))||void 0,o=(yield this._humanoidImporter.import(e))||void 0,a=o&&(yield this._firstPersonImporter.import(e,o))||void 0,s=(yield this._blendShapeImporter.import(e))||void 0,l=a&&s&&o&&(yield this._lookAtImporter.import(e,a,s,o))||void 0;l.setupHelper&&l.setupHelper(n,t);const d=(yield this._springBoneImporter.import(e))||void 0;return d.setupHelper&&d.setupHelper(n,t),new je({scene:e.scene,meta:i,materials:r,humanoid:o,firstPerson:a,blendShapeProxy:s,lookAt:l,springBoneManager:d},t)}))}}const ze=1e4;class je extends Pe{static from(e,t={},n={}){return o(this,void 0,void 0,(function*(){const i=new We(t);return yield i.import(e,n)}))}constructor(e,t={}){super(e),t.disableBoxHelper||this.scene.add(new r.BoxHelper(this.scene)),t.disableSkeletonHelper||this.scene.add(new r.SkeletonHelper(this.scene))}update(e){super.update(e)}}e.MToonMaterial=ae,e.VRM=Pe,e.VRMBlendShapeGroup=c,e.VRMBlendShapeImporter=w,e.VRMBlendShapeProxy=L,e.VRMCurveMapper=k,e.VRMDebug=je,e.VRMFirstPerson=C,e.VRMFirstPersonImporter=I,e.VRMHumanBone=V,e.VRMHumanoid=B,e.VRMHumanoidImporter=G,e.VRMImporter=we,e.VRMLookAtApplyer=F,e.VRMLookAtBlendShapeApplyer=H,e.VRMLookAtBoneApplyer=Z,e.VRMLookAtHead=q,e.VRMLookAtImporter=J,e.VRMMaterialImporter=de,e.VRMMetaImporter=he,e.VRMRendererFirstPersonFlags=O,e.VRMSpringBone=xe,e.VRMSpringBoneDebug=Fe,e.VRMSpringBoneImporter=Le,e.VRMSpringBoneImporterDebug=He,e.VRMSpringBoneManager=Se,e.VRMUnlitMaterial=le,e.VRMUtils=Ve,e.VRM_GIZMO_RENDER_ORDER=ze,Object.defineProperty(e,"__esModule",{value:!0}),Object.assign(t,e)}));
|
|
16
|
+
***************************************************************************** */function o(e,t,n,i){return new(n||(n=Promise))((function(r,o){function a(e){try{l(i.next(e))}catch(e){o(e)}}function s(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}l((i=i.apply(e,t||[])).next())}))}function a(e){Object.keys(e).forEach((t=>{const n=e[t];if(null==n?void 0:n.isTexture){n.dispose()}})),e.dispose()}function s(e){const t=e.geometry;t&&t.dispose();const n=e.material;n&&(Array.isArray(n)?n.forEach((e=>a(e))):n&&a(n))}!function(e){e[e.NUMBER=0]="NUMBER",e[e.VECTOR2=1]="VECTOR2",e[e.VECTOR3=2]="VECTOR3",e[e.VECTOR4=3]="VECTOR4",e[e.COLOR=4]="COLOR"}(i||(i={}));const l=new r.Vector2,d=new r.Vector3,h=new r.Vector4,u=new r.Color;class c extends r.Object3D{constructor(e){super(),this.weight=0,this.isBinary=!1,this._binds=[],this._materialValues=[],this.name=`BlendShapeController_${e}`,this.type="BlendShapeController",this.visible=!1}addBind(e){const t=e.weight/100;this._binds.push({meshes:e.meshes,morphTargetIndex:e.morphTargetIndex,weight:t})}addMaterialValue(e){const t=e.material,n=e.propertyName;let o,a,s,l,d=t[n];d&&(d=e.defaultValue||d,d.isVector2?(o=i.VECTOR2,a=d.clone(),s=(new r.Vector2).fromArray(e.targetValue),l=s.clone().sub(a)):d.isVector3?(o=i.VECTOR3,a=d.clone(),s=(new r.Vector3).fromArray(e.targetValue),l=s.clone().sub(a)):d.isVector4?(o=i.VECTOR4,a=d.clone(),s=(new r.Vector4).fromArray([e.targetValue[2],e.targetValue[3],e.targetValue[0],e.targetValue[1]]),l=s.clone().sub(a)):d.isColor?(o=i.COLOR,a=d.clone(),s=(new r.Color).fromArray(e.targetValue),l=s.clone().sub(a)):(o=i.NUMBER,a=d,s=e.targetValue[0],l=s-a),this._materialValues.push({material:t,propertyName:n,defaultValue:a,targetValue:s,deltaValue:l,type:o}))}applyWeight(){const e=this.isBinary?this.weight<.5?0:1:this.weight;this._binds.forEach((t=>{t.meshes.forEach((n=>{n.morphTargetInfluences&&(n.morphTargetInfluences[t.morphTargetIndex]+=e*t.weight)}))})),this._materialValues.forEach((t=>{if(void 0!==t.material[t.propertyName]){if(t.type===i.NUMBER){const n=t.deltaValue;t.material[t.propertyName]+=n*e}else if(t.type===i.VECTOR2){const n=t.deltaValue;t.material[t.propertyName].add(l.copy(n).multiplyScalar(e))}else if(t.type===i.VECTOR3){const n=t.deltaValue;t.material[t.propertyName].add(d.copy(n).multiplyScalar(e))}else if(t.type===i.VECTOR4){const n=t.deltaValue;t.material[t.propertyName].add(h.copy(n).multiplyScalar(e))}else if(t.type===i.COLOR){const n=t.deltaValue;t.material[t.propertyName].add(u.copy(n).multiplyScalar(e))}"boolean"==typeof t.material.shouldApplyUniforms&&(t.material.shouldApplyUniforms=!0)}}))}clearAppliedWeight(){this._binds.forEach((e=>{e.meshes.forEach((t=>{t.morphTargetInfluences&&(t.morphTargetInfluences[e.morphTargetIndex]=0)}))})),this._materialValues.forEach((e=>{if(void 0!==e.material[e.propertyName]){if(e.type===i.NUMBER){const t=e.defaultValue;e.material[e.propertyName]=t}else if(e.type===i.VECTOR2){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===i.VECTOR3){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===i.VECTOR4){const t=e.defaultValue;e.material[e.propertyName].copy(t)}else if(e.type===i.COLOR){const t=e.defaultValue;e.material[e.propertyName].copy(t)}"boolean"==typeof e.material.shouldApplyUniforms&&(e.material.shouldApplyUniforms=!0)}}))}}var p,m,f,g,_,v,M;function T(e,t,n){const i=e.parser.json.nodes[t].mesh;if(null==i)return null;const r=e.parser.json.meshes[i].primitives.length,o=[];return n.traverse((e=>{o.length<r&&e.isMesh&&o.push(e)})),o}function y(e){return o(this,void 0,void 0,(function*(){const t=yield e.parser.getDependencies("node"),n=new Map;return t.forEach(((t,i)=>{const r=T(e,i,t);null!=r&&n.set(i,r)})),n}))}function x(e){return"_"!==e[0]?(console.warn(`renameMaterialProperty: Given property name "${e}" might be invalid`),e):(e=e.substring(1),/[A-Z]/.test(e[0])?e[0].toLowerCase()+e.substring(1):(console.warn(`renameMaterialProperty: Given property name "${e}" might be invalid`),e))}e.VRMSchema=void 0,p=e.VRMSchema||(e.VRMSchema={}),(m=p.BlendShapePresetName||(p.BlendShapePresetName={})).A="a",m.Angry="angry",m.Blink="blink",m.BlinkL="blink_l",m.BlinkR="blink_r",m.E="e",m.Fun="fun",m.I="i",m.Joy="joy",m.Lookdown="lookdown",m.Lookleft="lookleft",m.Lookright="lookright",m.Lookup="lookup",m.Neutral="neutral",m.O="o",m.Sorrow="sorrow",m.U="u",m.Unknown="unknown",(f=p.FirstPersonLookAtTypeName||(p.FirstPersonLookAtTypeName={})).BlendShape="BlendShape",f.Bone="Bone",(g=p.HumanoidBoneName||(p.HumanoidBoneName={})).Chest="chest",g.Head="head",g.Hips="hips",g.Jaw="jaw",g.LeftEye="leftEye",g.LeftFoot="leftFoot",g.LeftHand="leftHand",g.LeftIndexDistal="leftIndexDistal",g.LeftIndexIntermediate="leftIndexIntermediate",g.LeftIndexProximal="leftIndexProximal",g.LeftLittleDistal="leftLittleDistal",g.LeftLittleIntermediate="leftLittleIntermediate",g.LeftLittleProximal="leftLittleProximal",g.LeftLowerArm="leftLowerArm",g.LeftLowerLeg="leftLowerLeg",g.LeftMiddleDistal="leftMiddleDistal",g.LeftMiddleIntermediate="leftMiddleIntermediate",g.LeftMiddleProximal="leftMiddleProximal",g.LeftRingDistal="leftRingDistal",g.LeftRingIntermediate="leftRingIntermediate",g.LeftRingProximal="leftRingProximal",g.LeftShoulder="leftShoulder",g.LeftThumbDistal="leftThumbDistal",g.LeftThumbIntermediate="leftThumbIntermediate",g.LeftThumbProximal="leftThumbProximal",g.LeftToes="leftToes",g.LeftUpperArm="leftUpperArm",g.LeftUpperLeg="leftUpperLeg",g.Neck="neck",g.RightEye="rightEye",g.RightFoot="rightFoot",g.RightHand="rightHand",g.RightIndexDistal="rightIndexDistal",g.RightIndexIntermediate="rightIndexIntermediate",g.RightIndexProximal="rightIndexProximal",g.RightLittleDistal="rightLittleDistal",g.RightLittleIntermediate="rightLittleIntermediate",g.RightLittleProximal="rightLittleProximal",g.RightLowerArm="rightLowerArm",g.RightLowerLeg="rightLowerLeg",g.RightMiddleDistal="rightMiddleDistal",g.RightMiddleIntermediate="rightMiddleIntermediate",g.RightMiddleProximal="rightMiddleProximal",g.RightRingDistal="rightRingDistal",g.RightRingIntermediate="rightRingIntermediate",g.RightRingProximal="rightRingProximal",g.RightShoulder="rightShoulder",g.RightThumbDistal="rightThumbDistal",g.RightThumbIntermediate="rightThumbIntermediate",g.RightThumbProximal="rightThumbProximal",g.RightToes="rightToes",g.RightUpperArm="rightUpperArm",g.RightUpperLeg="rightUpperLeg",g.Spine="spine",g.UpperChest="upperChest",(_=p.MetaAllowedUserName||(p.MetaAllowedUserName={})).Everyone="Everyone",_.ExplicitlyLicensedPerson="ExplicitlyLicensedPerson",_.OnlyAuthor="OnlyAuthor",(v=p.MetaUssageName||(p.MetaUssageName={})).Allow="Allow",v.Disallow="Disallow",(M=p.MetaLicenseName||(p.MetaLicenseName={})).Cc0="CC0",M.CcBy="CC_BY",M.CcByNc="CC_BY_NC",M.CcByNcNd="CC_BY_NC_ND",M.CcByNcSa="CC_BY_NC_SA",M.CcByNd="CC_BY_ND",M.CcBySa="CC_BY_SA",M.Other="Other",M.RedistributionProhibited="Redistribution_Prohibited";const S=new r.Vector3,R=new r.Vector3;function E(e,t){return e.matrixWorld.decompose(S,t,R),t}new r.Quaternion;class L{constructor(){this._blendShapeGroups={},this._blendShapePresetMap={},this._unknownGroupNames=[]}get expressions(){return Object.keys(this._blendShapeGroups)}get blendShapePresetMap(){return this._blendShapePresetMap}get unknownGroupNames(){return this._unknownGroupNames}getBlendShapeGroup(e){const t=this._blendShapePresetMap[e],n=t?this._blendShapeGroups[t]:this._blendShapeGroups[e];if(n)return n;console.warn(`no blend shape found by ${e}`)}registerBlendShapeGroup(e,t,n){this._blendShapeGroups[e]=n,t?this._blendShapePresetMap[t]=e:this._unknownGroupNames.push(e)}getValue(e){var t;const n=this.getBlendShapeGroup(e);return null!==(t=null==n?void 0:n.weight)&&void 0!==t?t:null}setValue(e,t){const n=this.getBlendShapeGroup(e);var i;n&&(n.weight=(i=t,Math.max(Math.min(i,1),0)))}getBlendShapeTrackName(e){const t=this.getBlendShapeGroup(e);return t?`${t.name}.weight`:null}update(){Object.keys(this._blendShapeGroups).forEach((e=>{this._blendShapeGroups[e].clearAppliedWeight()})),Object.keys(this._blendShapeGroups).forEach((e=>{this._blendShapeGroups[e].applyWeight()}))}}class w{import(t){var n;return o(this,void 0,void 0,(function*(){const i=null===(n=t.parser.json.extensions)||void 0===n?void 0:n.VRM;if(!i)return null;const r=i.blendShapeMaster;if(!r)return null;const a=new L,s=r.blendShapeGroups;if(!s)return a;const l={};return yield Promise.all(s.map((n=>o(this,void 0,void 0,(function*(){const i=n.name;if(void 0===i)return void console.warn("VRMBlendShapeImporter: One of blendShapeGroups has no name");let r;n.presetName&&n.presetName!==e.VRMSchema.BlendShapePresetName.Unknown&&!l[n.presetName]&&(r=n.presetName,l[n.presetName]=i);const s=new c(i);t.scene.add(s),s.isBinary=n.isBinary||!1,n.binds&&n.binds.forEach((e=>o(this,void 0,void 0,(function*(){if(void 0===e.mesh||void 0===e.index)return;const i=[];t.parser.json.nodes.forEach(((t,n)=>{t.mesh===e.mesh&&i.push(n)}));const r=e.index;yield Promise.all(i.map((i=>o(this,void 0,void 0,(function*(){var a;const l=yield function(e,t){return o(this,void 0,void 0,(function*(){const n=yield e.parser.getDependency("node",t);return T(e,t,n)}))}(t,i);l.every((e=>Array.isArray(e.morphTargetInfluences)&&r<e.morphTargetInfluences.length))?s.addBind({meshes:l,morphTargetIndex:r,weight:null!==(a=e.weight)&&void 0!==a?a:100}):console.warn(`VRMBlendShapeImporter: ${n.name} attempts to index ${r}th morph but not found.`)})))))}))));const d=n.materialValues;d&&d.forEach((e=>{if(void 0===e.materialName||void 0===e.propertyName||void 0===e.targetValue)return;const n=[];t.scene.traverse((t=>{if(t.material){const i=t.material;Array.isArray(i)?n.push(...i.filter((t=>t.name===e.materialName&&-1===n.indexOf(t)))):i.name===e.materialName&&-1===n.indexOf(i)&&n.push(i)}})),n.forEach((t=>{s.addMaterialValue({material:t,propertyName:x(e.propertyName),targetValue:e.targetValue})}))})),a.registerBlendShapeGroup(i,r,s)}))))),a}))}}const P=Object.freeze(new r.Vector3(0,0,-1)),A=new r.Quaternion;var b;!function(e){e[e.Auto=0]="Auto",e[e.Both=1]="Both",e[e.ThirdPersonOnly=2]="ThirdPersonOnly",e[e.FirstPersonOnly=3]="FirstPersonOnly"}(b||(b={}));class O{constructor(e,t){this.firstPersonFlag=O._parseFirstPersonFlag(e),this.primitives=t}static _parseFirstPersonFlag(e){switch(e){case"Both":return b.Both;case"ThirdPersonOnly":return b.ThirdPersonOnly;case"FirstPersonOnly":return b.FirstPersonOnly;default:return b.Auto}}}class C{constructor(e,t,n){this._meshAnnotations=[],this._firstPersonOnlyLayer=C._DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=C._DEFAULT_THIRDPERSON_ONLY_LAYER,this._initialized=!1,this._firstPersonBone=e,this._firstPersonBoneOffset=t,this._meshAnnotations=n}get firstPersonBone(){return this._firstPersonBone}get meshAnnotations(){return this._meshAnnotations}getFirstPersonWorldDirection(e){return e.copy(P).applyQuaternion(E(this._firstPersonBone,A))}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}getFirstPersonBoneOffset(e){return e.copy(this._firstPersonBoneOffset)}getFirstPersonWorldPosition(e){const t=this._firstPersonBoneOffset,n=new r.Vector4(t.x,t.y,t.z,1);return n.applyMatrix4(this._firstPersonBone.matrixWorld),e.set(n.x,n.y,n.z)}setup({firstPersonOnlyLayer:e=C._DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:t=C._DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initialized||(this._initialized=!0,this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=t,this._meshAnnotations.forEach((e=>{e.firstPersonFlag===b.FirstPersonOnly?e.primitives.forEach((e=>{e.layers.set(this._firstPersonOnlyLayer)})):e.firstPersonFlag===b.ThirdPersonOnly?e.primitives.forEach((e=>{e.layers.set(this._thirdPersonOnlyLayer)})):e.firstPersonFlag===b.Auto&&this._createHeadlessModel(e.primitives)})))}_excludeTriangles(e,t,n,i){let r=0;if(null!=t&&t.length>0)for(let o=0;o<e.length;o+=3){const a=e[o],s=e[o+1],l=e[o+2],d=t[a],h=n[a];if(d[0]>0&&i.includes(h[0]))continue;if(d[1]>0&&i.includes(h[1]))continue;if(d[2]>0&&i.includes(h[2]))continue;if(d[3]>0&&i.includes(h[3]))continue;const u=t[s],c=n[s];if(u[0]>0&&i.includes(c[0]))continue;if(u[1]>0&&i.includes(c[1]))continue;if(u[2]>0&&i.includes(c[2]))continue;if(u[3]>0&&i.includes(c[3]))continue;const p=t[l],m=n[l];p[0]>0&&i.includes(m[0])||(p[1]>0&&i.includes(m[1])||p[2]>0&&i.includes(m[2])||p[3]>0&&i.includes(m[3])||(e[r++]=a,e[r++]=s,e[r++]=l))}return r}_createErasedMesh(e,t){const n=new r.SkinnedMesh(e.geometry.clone(),e.material);n.name=`${e.name}(erase)`,n.frustumCulled=e.frustumCulled,n.layers.set(this._firstPersonOnlyLayer);const i=n.geometry,o=i.getAttribute("skinIndex").array,a=[];for(let e=0;e<o.length;e+=4)a.push([o[e],o[e+1],o[e+2],o[e+3]]);const s=i.getAttribute("skinWeight").array,l=[];for(let e=0;e<s.length;e+=4)l.push([s[e],s[e+1],s[e+2],s[e+3]]);const d=i.getIndex();if(!d)throw new Error("The geometry doesn't have an index buffer");const h=Array.from(d.array),u=this._excludeTriangles(h,l,a,t),c=[];for(let e=0;e<u;e++)c[e]=h[e];return i.setIndex(c),e.onBeforeRender&&(n.onBeforeRender=e.onBeforeRender),n.bind(new r.Skeleton(e.skeleton.bones,e.skeleton.boneInverses),new r.Matrix4),n}_createHeadlessModelForSkinnedMesh(e,t){const n=[];if(t.skeleton.bones.forEach(((e,t)=>{this._isEraseTarget(e)&&n.push(t)})),!n.length)return t.layers.enable(this._thirdPersonOnlyLayer),void t.layers.enable(this._firstPersonOnlyLayer);t.layers.set(this._thirdPersonOnlyLayer);const i=this._createErasedMesh(t,n);e.add(i)}_createHeadlessModel(e){e.forEach((e=>{if("SkinnedMesh"===e.type){const t=e;this._createHeadlessModelForSkinnedMesh(t.parent,t)}else this._isEraseTarget(e)&&e.layers.set(this._thirdPersonOnlyLayer)}))}_isEraseTarget(e){return e===this._firstPersonBone||!!e.parent&&this._isEraseTarget(e.parent)}}C._DEFAULT_FIRSTPERSON_ONLY_LAYER=9,C._DEFAULT_THIRDPERSON_ONLY_LAYER=10;class I{import(t,n){var i;return o(this,void 0,void 0,(function*(){const o=null===(i=t.parser.json.extensions)||void 0===i?void 0:i.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=a.firstPersonBone;let l;if(l=void 0===s||-1===s?n.getBoneNode(e.VRMSchema.HumanoidBoneName.Head):yield t.parser.getDependency("node",s),!l)return console.warn("VRMFirstPersonImporter: Could not find firstPersonBone of the VRM"),null;const d=a.firstPersonBoneOffset?new r.Vector3(a.firstPersonBoneOffset.x,a.firstPersonBoneOffset.y,-a.firstPersonBoneOffset.z):new r.Vector3(0,.06,0),h=[],u=yield y(t);return Array.from(u.entries()).forEach((([e,n])=>{const i=t.parser.json.nodes[e],r=a.meshAnnotations?a.meshAnnotations.find((e=>e.mesh===i.mesh)):void 0;h.push(new O(null==r?void 0:r.firstPersonFlag,n))})),new C(l,d,h)}))}}class V{constructor(e,t){this.node=e,this.humanLimit=t}}function D(e){return e.invert?e.invert():e.inverse(),e}const N=new r.Vector3,U=new r.Quaternion;class B{constructor(e,t){this.restPose={},this.humanBones=this._createHumanBones(e),this.humanDescription=t,this.restPose=this.getPose()}getPose(){const e={};return Object.keys(this.humanBones).forEach((t=>{const n=this.getBoneNode(t);if(!n)return;if(e[t])return;N.set(0,0,0),U.identity();const i=this.restPose[t];(null==i?void 0:i.position)&&N.fromArray(i.position).negate(),(null==i?void 0:i.rotation)&&D(U.fromArray(i.rotation)),N.add(n.position),U.premultiply(n.quaternion),e[t]={position:N.toArray(),rotation:U.toArray()}}),{}),e}setPose(e){Object.keys(e).forEach((t=>{const n=e[t],i=this.getBoneNode(t);if(!i)return;const r=this.restPose[t];r&&(n.position&&(i.position.fromArray(n.position),r.position&&i.position.add(N.fromArray(r.position))),n.rotation&&(i.quaternion.fromArray(n.rotation),r.rotation&&i.quaternion.multiply(U.fromArray(r.rotation))))}))}resetPose(){Object.entries(this.restPose).forEach((([e,t])=>{const n=this.getBoneNode(e);n&&((null==t?void 0:t.position)&&n.position.fromArray(t.position),(null==t?void 0:t.rotation)&&n.quaternion.fromArray(t.rotation))}))}getBone(e){var t;return null!==(t=this.humanBones[e][0])&&void 0!==t?t:void 0}getBones(e){var t;return null!==(t=this.humanBones[e])&&void 0!==t?t:[]}getBoneNode(e){var t,n;return null!==(n=null===(t=this.humanBones[e][0])||void 0===t?void 0:t.node)&&void 0!==n?n:null}getBoneNodes(e){var t,n;return null!==(n=null===(t=this.humanBones[e])||void 0===t?void 0:t.map((e=>e.node)))&&void 0!==n?n:[]}_createHumanBones(t){const n=Object.values(e.VRMSchema.HumanoidBoneName).reduce(((e,t)=>(e[t]=[],e)),{});return t.forEach((e=>{n[e.name].push(e.bone)})),n}}class G{import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.humanoid;if(!i)return null;const a=[];i.humanBones&&(yield Promise.all(i.humanBones.map((t=>o(this,void 0,void 0,(function*(){if(!t.bone||null==t.node)return;const n=yield e.parser.getDependency("node",t.node);a.push({name:t.bone,bone:new V(n,{axisLength:t.axisLength,center:t.center&&new r.Vector3(t.center.x,t.center.y,t.center.z),max:t.max&&new r.Vector3(t.max.x,t.max.y,t.max.z),min:t.min&&new r.Vector3(t.min.x,t.min.y,t.min.z),useDefaultValues:t.useDefaultValues})})}))))));const s={armStretch:i.armStretch,legStretch:i.legStretch,upperArmTwist:i.upperArmTwist,lowerArmTwist:i.lowerArmTwist,upperLegTwist:i.upperLegTwist,lowerLegTwist:i.lowerLegTwist,feetSpacing:i.feetSpacing,hasTranslationDoF:i.hasTranslationDoF};return new B(a,s)}))}}class H{constructor(e,t,n){this.curve=[0,0,0,1,1,1,1,0],this.curveXRangeDegree=90,this.curveYRangeDegree=10,void 0!==e&&(this.curveXRangeDegree=e),void 0!==t&&(this.curveYRangeDegree=t),void 0!==n&&(this.curve=n)}map(e){const t=Math.min(Math.max(e,0),this.curveXRangeDegree)/this.curveXRangeDegree;return this.curveYRangeDegree*((e,t)=>{if(e.length<8)throw new Error("evaluateCurve: Invalid curve detected! (Array length must be 8 at least)");if(e.length%4!=0)throw new Error("evaluateCurve: Invalid curve detected! (Array length must be multiples of 4");let n;for(n=0;;n++){if(e.length<=4*n)return e[4*n-3];if(t<=e[4*n])break}const i=n-1;if(i<0)return e[4*i+5];const r=e[4*i],o=(t-r)/(e[4*n]-r);return((e,t,n,i,r)=>{const o=r*r*r,a=r*r;return e+(t-e)*(-2*o+3*a)+n*(o-2*a+r)+i*(o-a)})(e[4*i+1],e[4*n+1],e[4*i+3],e[4*n+2],o)})(this.curve,t)}}class k{}class F extends k{constructor(t,n,i,r){super(),this.type=e.VRMSchema.FirstPersonLookAtTypeName.BlendShape,this._curveHorizontal=n,this._curveVerticalDown=i,this._curveVerticalUp=r,this._blendShapeProxy=t}name(){return e.VRMSchema.FirstPersonLookAtTypeName.BlendShape}lookAt(t){const n=t.x,i=t.y;n<0?(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookup,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookdown,this._curveVerticalDown.map(-n))):(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookdown,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookup,this._curveVerticalUp.map(n))),i<0?(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookleft,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookright,this._curveHorizontal.map(-i))):(this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookright,0),this._blendShapeProxy.setValue(e.VRMSchema.BlendShapePresetName.Lookleft,this._curveHorizontal.map(i)))}}const W=Object.freeze(new r.Vector3(0,0,-1)),z=new r.Vector3,j=new r.Vector3,Y=new r.Vector3,X=new r.Quaternion;class q{constructor(e,t){this.autoUpdate=!0,this._euler=new r.Euler(0,0,0,q.EULER_ORDER),this.firstPerson=e,this.applyer=t}getLookAtWorldDirection(e){const t=E(this.firstPerson.firstPersonBone,X);return e.copy(W).applyEuler(this._euler).applyQuaternion(t)}lookAt(e){this._calcEuler(this._euler,e),this.applyer&&this.applyer.lookAt(this._euler)}update(e){this.target&&this.autoUpdate&&(this.lookAt(this.target.getWorldPosition(z)),this.applyer&&this.applyer.lookAt(this._euler))}_calcEuler(e,t){const n=this.firstPerson.getFirstPersonWorldPosition(j),i=Y.copy(t).sub(n).normalize();return i.applyQuaternion(D(E(this.firstPerson.firstPersonBone,X))),e.x=Math.atan2(i.y,Math.sqrt(i.x*i.x+i.z*i.z)),e.y=Math.atan2(-i.x,-i.z),e}}q.EULER_ORDER="YXZ";const Q=new r.Euler(0,0,0,q.EULER_ORDER);class Z extends k{constructor(t,n,i,r,o){super(),this.type=e.VRMSchema.FirstPersonLookAtTypeName.Bone,this._curveHorizontalInner=n,this._curveHorizontalOuter=i,this._curveVerticalDown=r,this._curveVerticalUp=o,this._leftEye=t.getBoneNode(e.VRMSchema.HumanoidBoneName.LeftEye),this._rightEye=t.getBoneNode(e.VRMSchema.HumanoidBoneName.RightEye)}lookAt(e){const t=e.x,n=e.y;this._leftEye&&(Q.x=t<0?-this._curveVerticalDown.map(-t):this._curveVerticalUp.map(t),Q.y=n<0?-this._curveHorizontalInner.map(-n):this._curveHorizontalOuter.map(n),this._leftEye.quaternion.setFromEuler(Q)),this._rightEye&&(Q.x=t<0?-this._curveVerticalDown.map(-t):this._curveVerticalUp.map(t),Q.y=n<0?-this._curveHorizontalOuter.map(-n):this._curveHorizontalInner.map(n),this._rightEye.quaternion.setFromEuler(Q))}}const $=Math.PI/180;class J{import(e,t,n,i){var r;const o=null===(r=e.parser.json.extensions)||void 0===r?void 0:r.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=this._importApplyer(a,n,i);return new q(t,s||void 0)}_importApplyer(t,n,i){const r=t.lookAtHorizontalInner,o=t.lookAtHorizontalOuter,a=t.lookAtVerticalDown,s=t.lookAtVerticalUp;switch(t.lookAtTypeName){case e.VRMSchema.FirstPersonLookAtTypeName.Bone:return void 0===r||void 0===o||void 0===a||void 0===s?null:new Z(i,this._importCurveMapperBone(r),this._importCurveMapperBone(o),this._importCurveMapperBone(a),this._importCurveMapperBone(s));case e.VRMSchema.FirstPersonLookAtTypeName.BlendShape:return void 0===o||void 0===a||void 0===s?null:new F(n,this._importCurveMapperBlendShape(o),this._importCurveMapperBlendShape(a),this._importCurveMapperBlendShape(s));default:return null}}_importCurveMapperBone(e){return new H("number"==typeof e.xRange?$*e.xRange:void 0,"number"==typeof e.yRange?$*e.yRange:void 0,e.curve)}_importCurveMapperBlendShape(e){return new H("number"==typeof e.xRange?$*e.xRange:void 0,e.yRange,e.curve)}}var K='// #define PHONG\n\n#ifdef BLENDMODE_CUTOUT\n uniform float cutoff;\n#endif\n\nuniform vec3 color;\nuniform float colorAlpha;\nuniform vec3 shadeColor;\n#ifdef USE_SHADETEXTURE\n uniform sampler2D shadeTexture;\n#endif\n\nuniform float receiveShadowRate;\n#ifdef USE_RECEIVESHADOWTEXTURE\n uniform sampler2D receiveShadowTexture;\n#endif\n\nuniform float shadingGradeRate;\n#ifdef USE_SHADINGGRADETEXTURE\n uniform sampler2D shadingGradeTexture;\n#endif\n\nuniform float shadeShift;\nuniform float shadeToony;\nuniform float lightColorAttenuation;\nuniform float indirectLightIntensity;\n\n#ifdef USE_RIMTEXTURE\n uniform sampler2D rimTexture;\n#endif\nuniform vec3 rimColor;\nuniform float rimLightingMix;\nuniform float rimFresnelPower;\nuniform float rimLift;\n\n#ifdef USE_SPHEREADD\n uniform sampler2D sphereAdd;\n#endif\n\nuniform vec3 emissionColor;\n\nuniform vec3 outlineColor;\nuniform float outlineLightingMix;\n\n#ifdef USE_UVANIMMASKTEXTURE\n uniform sampler2D uvAnimMaskTexture;\n#endif\n\nuniform float uvAnimOffsetX;\nuniform float uvAnimOffsetY;\nuniform float uvAnimTheta;\n\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n\n// #include <uv_pars_fragment>\n#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n varying vec2 vUv;\n#endif\n\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n// #include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n// #include <envmap_common_pars_fragment>\n// #include <envmap_pars_fragment>\n// #include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n\n// #include <bsdfs>\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\n\n#include <lights_pars_begin>\n\n// #include <lights_phong_pars_fragment>\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n\nstruct MToonMaterial {\n vec3 diffuseColor;\n vec3 shadeColor;\n float shadingGrade;\n float receiveShadow;\n};\n\n#define Material_LightProbeLOD( material ) (0)\n\n#include <shadowmap_pars_fragment>\n// #include <bumpmap_pars_fragment>\n\n// #include <normalmap_pars_fragment>\n#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n\n#endif\n\n#ifdef OBJECTSPACE_NORMALMAP\n\n uniform mat3 normalMatrix;\n\n#endif\n\n#if ! defined ( USE_TANGENT ) && defined ( TANGENTSPACE_NORMALMAP )\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n // three-vrm specific change: it requires `uv` as an input in order to support uv scrolls\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n vec3 N = normalize( surf_norm );\n\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n if ( length( T ) == 0.0 || length( B ) == 0.0 ) {\n return surf_norm;\n }\n\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\n return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\n }\n\n #else\n\n vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\n // Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\n\n vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n\n float scale = sign( st1.t * st0.s - st0.t * st1.s ); // we do not care about the magnitude\n\n vec3 S = ( q0 * st1.t - q1 * st0.t ) * scale;\n vec3 T = ( - q0 * st1.s + q1 * st0.s ) * scale;\n\n // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0\n // TODO: Is this still required? Or shall I make a PR about it?\n\n if ( length( S ) == 0.0 || length( T ) == 0.0 ) {\n return surf_norm;\n }\n\n S = normalize( S );\n T = normalize( T );\n vec3 N = normalize( surf_norm );\n\n #ifdef DOUBLE_SIDED\n\n // Workaround for Adreno GPUs gl_FrontFacing bug. See #15850 and #10331\n\n bool frontFacing = dot( cross( S, T ), N ) > 0.0;\n\n mapN.xy *= ( float( frontFacing ) * 2.0 - 1.0 );\n\n #else\n\n mapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n #endif\n\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n #endif\n\n#endif\n\n// #include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\n// == lighting stuff ===========================================================\nfloat getLightIntensity(\n const in IncidentLight directLight,\n const in GeometricContext geometry,\n const in float shadow,\n const in float shadingGrade\n) {\n float lightIntensity = dot( geometry.normal, directLight.direction );\n lightIntensity = 0.5 + 0.5 * lightIntensity;\n lightIntensity = lightIntensity * shadow;\n lightIntensity = lightIntensity * shadingGrade;\n lightIntensity = lightIntensity * 2.0 - 1.0;\n return shadeToony == 1.0\n ? step( shadeShift, lightIntensity )\n : smoothstep( shadeShift, shadeShift + ( 1.0 - shadeToony ), lightIntensity );\n}\n\nvec3 getLighting( const in vec3 lightColor ) {\n vec3 lighting = lightColor;\n lighting = mix(\n lighting,\n vec3( max( 0.001, max( lighting.x, max( lighting.y, lighting.z ) ) ) ),\n lightColorAttenuation\n );\n\n #if THREE_VRM_THREE_REVISION < 132\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lighting *= PI;\n #endif\n #endif\n\n return lighting;\n}\n\nvec3 getDiffuse(\n const in MToonMaterial material,\n const in float lightIntensity,\n const in vec3 lighting\n) {\n #ifdef DEBUG_LITSHADERATE\n return vec3( BRDF_Lambert( lightIntensity * lighting ) );\n #endif\n\n return lighting * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, lightIntensity ) );\n}\n\n// == post correction ==========================================================\nvoid postCorrection() {\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}\n\n// == main procedure ===========================================================\nvoid main() {\n #include <clipping_planes_fragment>\n\n vec2 uv = vec2(0.5, 0.5);\n\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n uv = vUv;\n\n float uvAnimMask = 1.0;\n #ifdef USE_UVANIMMASKTEXTURE\n uvAnimMask = texture2D( uvAnimMaskTexture, uv ).x;\n #endif\n\n uv = uv + vec2( uvAnimOffsetX, uvAnimOffsetY ) * uvAnimMask;\n float uvRotCos = cos( uvAnimTheta * uvAnimMask );\n float uvRotSin = sin( uvAnimTheta * uvAnimMask );\n uv = mat2( uvRotCos, uvRotSin, -uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5;\n #endif\n\n #ifdef DEBUG_UV\n gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) )\n gl_FragColor = vec4( uv, 0.0, 1.0 );\n #endif\n return;\n #endif\n\n vec4 diffuseColor = vec4( color, colorAlpha );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissionColor;\n\n #include <logdepthbuf_fragment>\n\n // #include <map_fragment>\n #ifdef USE_MAP\n #if THREE_VRM_THREE_REVISION >= 137\n vec4 sampledDiffuseColor = texture2D( map, uv );\n #ifdef DECODE_VIDEO_TEXTURE\n sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n #endif\n diffuseColor *= sampledDiffuseColor;\n #else\n // COMPAT: pre-r137\n diffuseColor *= mapTexelToLinear( texture2D( map, uv ) );\n #endif\n #endif\n\n #include <color_fragment>\n // #include <alphamap_fragment>\n\n // -- MToon: alpha -----------------------------------------------------------\n // #include <alphatest_fragment>\n #ifdef BLENDMODE_CUTOUT\n if ( diffuseColor.a <= cutoff ) { discard; }\n diffuseColor.a = 1.0;\n #endif\n\n #ifdef BLENDMODE_OPAQUE\n diffuseColor.a = 1.0;\n #endif\n\n #if defined( OUTLINE ) && defined( OUTLINE_COLOR_FIXED ) // omitting DebugMode\n gl_FragColor = vec4( outlineColor, diffuseColor.a );\n postCorrection();\n return;\n #endif\n\n // #include <specularmap_fragment>\n #include <normal_fragment_begin>\n\n #ifdef OUTLINE\n normal *= -1.0;\n #endif\n\n // #include <normal_fragment_maps>\n\n #ifdef OBJECTSPACE_NORMALMAP\n\n normal = texture2D( normalMap, uv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals\n\n #ifdef FLIP_SIDED\n\n normal = - normal;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n normal = normal * faceDirection;\n\n #else\n\n normal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\n #endif\n\n #endif\n\n normal = normalize( normalMatrix * normal );\n\n #elif defined( TANGENTSPACE_NORMALMAP )\n\n vec3 mapN = texture2D( normalMap, uv ).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n\n #ifdef USE_TANGENT\n\n normal = normalize( vTBN * mapN );\n\n #else\n\n // Temporary compat against shader change @ Three.js r126\n // See: #21205, #21307, #21299\n #if THREE_VRM_THREE_REVISION >= 126\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection );\n\n #else\n\n normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN );\n\n #endif\n\n #endif\n\n #endif\n\n // #include <emissivemap_fragment>\n #ifdef USE_EMISSIVEMAP\n #if THREE_VRM_THREE_REVISION >= 137\n totalEmissiveRadiance *= texture2D( emissiveMap, uv ).rgb;\n #else\n // COMPAT: pre-r137\n totalEmissiveRadiance *= emissiveMapTexelToLinear( texture2D( emissiveMap, uv ) ).rgb;\n #endif\n #endif\n\n #ifdef DEBUG_NORMAL\n gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 );\n return;\n #endif\n\n // -- MToon: lighting --------------------------------------------------------\n // accumulation\n // #include <lights_phong_fragment>\n MToonMaterial material;\n\n material.diffuseColor = diffuseColor.rgb;\n\n material.shadeColor = shadeColor;\n #ifdef USE_SHADETEXTURE\n #if THREE_VRM_THREE_REVISION >= 137\n material.shadeColor *= texture2D( shadeTexture, uv ).rgb;\n #else\n // COMPAT: pre-r137\n material.shadeColor *= shadeTextureTexelToLinear( texture2D( shadeTexture, uv ) ).rgb;\n #endif\n #endif\n\n material.shadingGrade = 1.0;\n #ifdef USE_SHADINGGRADETEXTURE\n material.shadingGrade = 1.0 - shadingGradeRate * ( 1.0 - texture2D( shadingGradeTexture, uv ).r );\n #endif\n\n material.receiveShadow = receiveShadowRate;\n #ifdef USE_RECEIVESHADOWTEXTURE\n material.receiveShadow *= texture2D( receiveShadowTexture, uv ).a;\n #endif\n\n // #include <lights_fragment_begin>\n GeometricContext geometry;\n\n geometry.position = - vViewPosition;\n geometry.normal = normal;\n geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\n IncidentLight directLight;\n vec3 lightingSum = vec3( 0.0 );\n\n // since these variables will be used in unrolled loop, we have to define in prior\n float atten, shadow, lightIntensity;\n vec3 lighting;\n\n #if ( NUM_POINT_LIGHTS > 0 )\n PointLight pointLight;\n\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getPointLightInfo( pointLight, geometry, directLight );\n #else\n getPointDirectLightIrradiance( pointLight, geometry, directLight );\n #endif\n\n atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n atten = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n\n shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n #if ( NUM_SPOT_LIGHTS > 0 )\n SpotLight spotLight;\n\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getSpotLightInfo( spotLight, geometry, directLight );\n #else\n getSpotDirectLightIrradiance( spotLight, geometry, directLight );\n #endif\n\n atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n atten = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n\n shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n #if ( NUM_DIR_LIGHTS > 0 )\n DirectionalLight directionalLight;\n\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n\n #if THREE_VRM_THREE_REVISION >= 132\n getDirectionalLightInfo( directionalLight, geometry, directLight );\n #else\n getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n #endif\n\n atten = 1.0;\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n atten = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n\n shadow = 1.0 - material.receiveShadow * ( 1.0 - ( 0.5 + 0.5 * atten ) );\n lightIntensity = getLightIntensity( directLight, geometry, shadow, material.shadingGrade );\n lighting = getLighting( directLight.color );\n reflectedLight.directDiffuse += getDiffuse( material, lightIntensity, lighting );\n lightingSum += lighting;\n }\n #pragma unroll_loop_end\n #endif\n\n // #if defined( RE_IndirectDiffuse )\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #if THREE_VRM_THREE_REVISION >= 133\n irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n #else\n irradiance += getLightProbeIrradiance( lightProbe, geometry );\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n #if THREE_VRM_THREE_REVISION >= 133\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n #else\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n #endif\n }\n #pragma unroll_loop_end\n #endif\n // #endif\n\n // #include <lights_fragment_maps>\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vUv2 );\n #if THREE_VRM_THREE_REVISION >= 137\n vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n #else\n // COMPAT: pre-r137\n vec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n #endif\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lightMapIrradiance *= PI;\n #endif\n irradiance += lightMapIrradiance;\n #endif\n\n // #include <lights_fragment_end>\n // RE_IndirectDiffuse here\n reflectedLight.indirectDiffuse += indirectLightIntensity * irradiance * BRDF_Lambert( material.diffuseColor );\n\n // modulation\n #include <aomap_fragment>\n\n vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\n // The "comment out if you want to PBR absolutely" line\n #ifndef DEBUG_LITSHADERATE\n col = min(col, material.diffuseColor);\n #endif\n\n #if defined( OUTLINE ) && defined( OUTLINE_COLOR_MIXED )\n gl_FragColor = vec4(\n outlineColor.rgb * mix( vec3( 1.0 ), col, outlineLightingMix ),\n diffuseColor.a\n );\n postCorrection();\n return;\n #endif\n\n #ifdef DEBUG_LITSHADERATE\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n return;\n #endif\n\n // -- MToon: parametric rim lighting -----------------------------------------\n vec3 viewDir = normalize( vViewPosition );\n vec3 rimMix = mix( vec3( 1.0 ), lightingSum + indirectLightIntensity * irradiance, rimLightingMix );\n vec3 rim = rimColor * pow( saturate( 1.0 - dot( viewDir, normal ) + rimLift ), rimFresnelPower );\n #ifdef USE_RIMTEXTURE\n #if THREE_VRM_THREE_REVISION >= 137\n rim *= texture2D( rimTexture, uv ).rgb;\n #else\n // COMPAT: pre-r137\n rim *= rimTextureTexelToLinear( texture2D( rimTexture, uv ) ).rgb;\n #endif\n #endif\n col += rim;\n\n // -- MToon: additive matcap -------------------------------------------------\n #ifdef USE_SPHEREADD\n {\n vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) );\n vec3 y = cross( viewDir, x ); // guaranteed to be normalized\n vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) );\n #if THREE_VRM_THREE_REVISION >= 137\n vec3 matcap = texture2D( sphereAdd, sphereUv ).xyz;\n #else\n // COMPAT: pre-r137\n vec3 matcap = sphereAddTexelToLinear( texture2D( sphereAdd, sphereUv ) ).xyz;\n #endif\n col += matcap;\n }\n #endif\n\n // -- MToon: Emission --------------------------------------------------------\n col += totalEmissiveRadiance;\n\n // #include <envmap_fragment>\n\n // -- Almost done! -----------------------------------------------------------\n gl_FragColor = vec4( col, diffuseColor.a );\n postCorrection();\n}';const ee=(e,t)=>{const n=(e=>{if(parseInt(r.REVISION,10)>=136)switch(e){case r.LinearEncoding:return["Linear","( value )"];case r.sRGBEncoding:return["sRGB","( value )"];default:return console.warn("THREE.WebGLProgram: Unsupported encoding:",e),["Linear","( value )"]}else switch(e){case r.LinearEncoding:return["Linear","( value )"];case r.sRGBEncoding:return["sRGB","( value )"];case 3002:return["RGBE","( value )"];case 3004:return["RGBM","( value, 7.0 )"];case 3005:return["RGBM","( value, 16.0 )"];case 3006:return["RGBD","( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw new Error("unsupported encoding: "+e)}})(t);return"vec4 "+e+"( vec4 value ) { return "+n[0]+"ToLinear"+n[1]+"; }"},te=2*Math.PI;var ne,ie,re,oe,ae;e.MToonMaterialCullMode=void 0,(ne=e.MToonMaterialCullMode||(e.MToonMaterialCullMode={}))[ne.Off=0]="Off",ne[ne.Front=1]="Front",ne[ne.Back=2]="Back",e.MToonMaterialDebugMode=void 0,(ie=e.MToonMaterialDebugMode||(e.MToonMaterialDebugMode={}))[ie.None=0]="None",ie[ie.Normal=1]="Normal",ie[ie.LitShadeRate=2]="LitShadeRate",ie[ie.UV=3]="UV",e.MToonMaterialOutlineColorMode=void 0,(re=e.MToonMaterialOutlineColorMode||(e.MToonMaterialOutlineColorMode={}))[re.FixedColor=0]="FixedColor",re[re.MixedLighting=1]="MixedLighting",e.MToonMaterialOutlineWidthMode=void 0,(oe=e.MToonMaterialOutlineWidthMode||(e.MToonMaterialOutlineWidthMode={}))[oe.None=0]="None",oe[oe.WorldCoordinates=1]="WorldCoordinates",oe[oe.ScreenCoordinates=2]="ScreenCoordinates",e.MToonMaterialRenderMode=void 0,(ae=e.MToonMaterialRenderMode||(e.MToonMaterialRenderMode={}))[ae.Opaque=0]="Opaque",ae[ae.Cutout=1]="Cutout",ae[ae.Transparent=2]="Transparent",ae[ae.TransparentWithZWrite=3]="TransparentWithZWrite";class se extends r.ShaderMaterial{constructor(t={}){super(),this.isMToonMaterial=!0,this.cutoff=.5,this.color=new r.Vector4(1,1,1,1),this.shadeColor=new r.Vector4(.97,.81,.86,1),this.map=null,this.mainTex_ST=new r.Vector4(0,0,1,1),this.shadeTexture=null,this.normalMap=null,this.normalMapType=r.TangentSpaceNormalMap,this.normalScale=new r.Vector2(1,1),this.receiveShadowRate=1,this.receiveShadowTexture=null,this.shadingGradeRate=1,this.shadingGradeTexture=null,this.shadeShift=0,this.shadeToony=.9,this.lightColorAttenuation=0,this.indirectLightIntensity=.1,this.rimTexture=null,this.rimColor=new r.Vector4(0,0,0,1),this.rimLightingMix=0,this.rimFresnelPower=1,this.rimLift=0,this.sphereAdd=null,this.emissionColor=new r.Vector4(0,0,0,1),this.emissiveMap=null,this.outlineWidthTexture=null,this.outlineWidth=.5,this.outlineScaledMaxDistance=1,this.outlineColor=new r.Vector4(0,0,0,1),this.outlineLightingMix=1,this.uvAnimMaskTexture=null,this.uvAnimScrollX=0,this.uvAnimScrollY=0,this.uvAnimRotation=0,this.shouldApplyUniforms=!0,this._debugMode=e.MToonMaterialDebugMode.None,this._blendMode=e.MToonMaterialRenderMode.Opaque,this._outlineWidthMode=e.MToonMaterialOutlineWidthMode.None,this._outlineColorMode=e.MToonMaterialOutlineColorMode.FixedColor,this._cullMode=e.MToonMaterialCullMode.Back,this._outlineCullMode=e.MToonMaterialCullMode.Front,this._isOutline=!1,this._uvAnimOffsetX=0,this._uvAnimOffsetY=0,this._uvAnimPhase=0,this.encoding=t.encoding||r.LinearEncoding,this.encoding!==r.LinearEncoding&&this.encoding!==r.sRGBEncoding&&console.warn("The specified color encoding does not work properly with MToonMaterial. You might want to use THREE.sRGBEncoding instead."),["mToonVersion","shadeTexture_ST","bumpMap_ST","receiveShadowTexture_ST","shadingGradeTexture_ST","rimTexture_ST","sphereAdd_ST","emissionMap_ST","outlineWidthTexture_ST","uvAnimMaskTexture_ST","srcBlend","dstBlend"].forEach((e=>{void 0!==t[e]&&delete t[e]})),t.fog=!0,t.lights=!0,t.clipping=!0,parseInt(r.REVISION,10)<129&&(t.skinning=t.skinning||!1),parseInt(r.REVISION,10)<131&&(t.morphTargets=t.morphTargets||!1,t.morphNormals=t.morphNormals||!1),t.uniforms=r.UniformsUtils.merge([r.UniformsLib.common,r.UniformsLib.normalmap,r.UniformsLib.emissivemap,r.UniformsLib.fog,r.UniformsLib.lights,{cutoff:{value:.5},color:{value:new r.Color(1,1,1)},colorAlpha:{value:1},shadeColor:{value:new r.Color(.97,.81,.86)},mainTex_ST:{value:new r.Vector4(0,0,1,1)},shadeTexture:{value:null},receiveShadowRate:{value:1},receiveShadowTexture:{value:null},shadingGradeRate:{value:1},shadingGradeTexture:{value:null},shadeShift:{value:0},shadeToony:{value:.9},lightColorAttenuation:{value:0},indirectLightIntensity:{value:.1},rimTexture:{value:null},rimColor:{value:new r.Color(0,0,0)},rimLightingMix:{value:0},rimFresnelPower:{value:1},rimLift:{value:0},sphereAdd:{value:null},emissionColor:{value:new r.Color(0,0,0)},outlineWidthTexture:{value:null},outlineWidth:{value:.5},outlineScaledMaxDistance:{value:1},outlineColor:{value:new r.Color(0,0,0)},outlineLightingMix:{value:1},uvAnimMaskTexture:{value:null},uvAnimOffsetX:{value:0},uvAnimOffsetY:{value:0},uvAnimTheta:{value:0}}]),this.setValues(t),this._updateShaderCode(),this._applyUniforms()}get mainTex(){return this.map}set mainTex(e){this.map=e}get bumpMap(){return this.normalMap}set bumpMap(e){this.normalMap=e}get bumpScale(){return this.normalScale.x}set bumpScale(e){this.normalScale.set(e,e)}get emissionMap(){return this.emissiveMap}set emissionMap(e){this.emissiveMap=e}get blendMode(){return this._blendMode}set blendMode(t){this._blendMode=t,this.depthWrite=this._blendMode!==e.MToonMaterialRenderMode.Transparent,this.transparent=this._blendMode===e.MToonMaterialRenderMode.Transparent||this._blendMode===e.MToonMaterialRenderMode.TransparentWithZWrite,this._updateShaderCode()}get debugMode(){return this._debugMode}set debugMode(e){this._debugMode=e,this._updateShaderCode()}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(e){this._outlineWidthMode=e,this._updateShaderCode()}get outlineColorMode(){return this._outlineColorMode}set outlineColorMode(e){this._outlineColorMode=e,this._updateShaderCode()}get cullMode(){return this._cullMode}set cullMode(e){this._cullMode=e,this._updateCullFace()}get outlineCullMode(){return this._outlineCullMode}set outlineCullMode(e){this._outlineCullMode=e,this._updateCullFace()}get zWrite(){return this.depthWrite?1:0}set zWrite(e){this.depthWrite=.5<=e}get isOutline(){return this._isOutline}set isOutline(e){this._isOutline=e,this._updateShaderCode(),this._updateCullFace()}updateVRMMaterials(e){this._uvAnimOffsetX=this._uvAnimOffsetX+e*this.uvAnimScrollX,this._uvAnimOffsetY=this._uvAnimOffsetY-e*this.uvAnimScrollY,this._uvAnimPhase=this._uvAnimPhase+e*this.uvAnimRotation,this._applyUniforms()}copy(e){return super.copy(e),this.cutoff=e.cutoff,this.color.copy(e.color),this.shadeColor.copy(e.shadeColor),this.map=e.map,this.mainTex_ST.copy(e.mainTex_ST),this.shadeTexture=e.shadeTexture,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(this.normalScale),this.receiveShadowRate=e.receiveShadowRate,this.receiveShadowTexture=e.receiveShadowTexture,this.shadingGradeRate=e.shadingGradeRate,this.shadingGradeTexture=e.shadingGradeTexture,this.shadeShift=e.shadeShift,this.shadeToony=e.shadeToony,this.lightColorAttenuation=e.lightColorAttenuation,this.indirectLightIntensity=e.indirectLightIntensity,this.rimTexture=e.rimTexture,this.rimColor.copy(e.rimColor),this.rimLightingMix=e.rimLightingMix,this.rimFresnelPower=e.rimFresnelPower,this.rimLift=e.rimLift,this.sphereAdd=e.sphereAdd,this.emissionColor.copy(e.emissionColor),this.emissiveMap=e.emissiveMap,this.outlineWidthTexture=e.outlineWidthTexture,this.outlineWidth=e.outlineWidth,this.outlineScaledMaxDistance=e.outlineScaledMaxDistance,this.outlineColor.copy(e.outlineColor),this.outlineLightingMix=e.outlineLightingMix,this.uvAnimMaskTexture=e.uvAnimMaskTexture,this.uvAnimScrollX=e.uvAnimScrollX,this.uvAnimScrollY=e.uvAnimScrollY,this.uvAnimRotation=e.uvAnimRotation,this.debugMode=e.debugMode,this.blendMode=e.blendMode,this.outlineWidthMode=e.outlineWidthMode,this.outlineColorMode=e.outlineColorMode,this.cullMode=e.cullMode,this.outlineCullMode=e.outlineCullMode,this.isOutline=e.isOutline,this}_applyUniforms(){this.uniforms.uvAnimOffsetX.value=this._uvAnimOffsetX,this.uniforms.uvAnimOffsetY.value=this._uvAnimOffsetY,this.uniforms.uvAnimTheta.value=te*this._uvAnimPhase,this.shouldApplyUniforms&&(this.shouldApplyUniforms=!1,this.uniforms.cutoff.value=this.cutoff,this.uniforms.color.value.setRGB(this.color.x,this.color.y,this.color.z),this.uniforms.colorAlpha.value=this.color.w,this.uniforms.shadeColor.value.setRGB(this.shadeColor.x,this.shadeColor.y,this.shadeColor.z),this.uniforms.map.value=this.map,this.uniforms.mainTex_ST.value.copy(this.mainTex_ST),this.uniforms.shadeTexture.value=this.shadeTexture,this.uniforms.normalMap.value=this.normalMap,this.uniforms.normalScale.value.copy(this.normalScale),this.uniforms.receiveShadowRate.value=this.receiveShadowRate,this.uniforms.receiveShadowTexture.value=this.receiveShadowTexture,this.uniforms.shadingGradeRate.value=this.shadingGradeRate,this.uniforms.shadingGradeTexture.value=this.shadingGradeTexture,this.uniforms.shadeShift.value=this.shadeShift,this.uniforms.shadeToony.value=this.shadeToony,this.uniforms.lightColorAttenuation.value=this.lightColorAttenuation,this.uniforms.indirectLightIntensity.value=this.indirectLightIntensity,this.uniforms.rimTexture.value=this.rimTexture,this.uniforms.rimColor.value.setRGB(this.rimColor.x,this.rimColor.y,this.rimColor.z),this.uniforms.rimLightingMix.value=this.rimLightingMix,this.uniforms.rimFresnelPower.value=this.rimFresnelPower,this.uniforms.rimLift.value=this.rimLift,this.uniforms.sphereAdd.value=this.sphereAdd,this.uniforms.emissionColor.value.setRGB(this.emissionColor.x,this.emissionColor.y,this.emissionColor.z),this.uniforms.emissiveMap.value=this.emissiveMap,this.uniforms.outlineWidthTexture.value=this.outlineWidthTexture,this.uniforms.outlineWidth.value=this.outlineWidth,this.uniforms.outlineScaledMaxDistance.value=this.outlineScaledMaxDistance,this.uniforms.outlineColor.value.setRGB(this.outlineColor.x,this.outlineColor.y,this.outlineColor.z),this.uniforms.outlineLightingMix.value=this.outlineLightingMix,this.uniforms.uvAnimMaskTexture.value=this.uvAnimMaskTexture,this.encoding===r.sRGBEncoding&&(this.uniforms.color.value.convertSRGBToLinear(),this.uniforms.shadeColor.value.convertSRGBToLinear(),this.uniforms.rimColor.value.convertSRGBToLinear(),this.uniforms.emissionColor.value.convertSRGBToLinear(),this.uniforms.outlineColor.value.convertSRGBToLinear()),this._updateCullFace())}_updateShaderCode(){const t=null!==this.outlineWidthTexture,n=null!==this.map||null!==this.shadeTexture||null!==this.receiveShadowTexture||null!==this.shadingGradeTexture||null!==this.rimTexture||null!==this.uvAnimMaskTexture;if(this.defines={THREE_VRM_THREE_REVISION:parseInt(r.REVISION,10),OUTLINE:this._isOutline,BLENDMODE_OPAQUE:this._blendMode===e.MToonMaterialRenderMode.Opaque,BLENDMODE_CUTOUT:this._blendMode===e.MToonMaterialRenderMode.Cutout,BLENDMODE_TRANSPARENT:this._blendMode===e.MToonMaterialRenderMode.Transparent||this._blendMode===e.MToonMaterialRenderMode.TransparentWithZWrite,MTOON_USE_UV:t||n,MTOON_UVS_VERTEX_ONLY:t&&!n,USE_SHADETEXTURE:null!==this.shadeTexture,USE_RECEIVESHADOWTEXTURE:null!==this.receiveShadowTexture,USE_SHADINGGRADETEXTURE:null!==this.shadingGradeTexture,USE_RIMTEXTURE:null!==this.rimTexture,USE_SPHEREADD:null!==this.sphereAdd,USE_OUTLINEWIDTHTEXTURE:null!==this.outlineWidthTexture,USE_UVANIMMASKTEXTURE:null!==this.uvAnimMaskTexture,DEBUG_NORMAL:this._debugMode===e.MToonMaterialDebugMode.Normal,DEBUG_LITSHADERATE:this._debugMode===e.MToonMaterialDebugMode.LitShadeRate,DEBUG_UV:this._debugMode===e.MToonMaterialDebugMode.UV,OUTLINE_WIDTH_WORLD:this._outlineWidthMode===e.MToonMaterialOutlineWidthMode.WorldCoordinates,OUTLINE_WIDTH_SCREEN:this._outlineWidthMode===e.MToonMaterialOutlineWidthMode.ScreenCoordinates,OUTLINE_COLOR_FIXED:this._outlineColorMode===e.MToonMaterialOutlineColorMode.FixedColor,OUTLINE_COLOR_MIXED:this._outlineColorMode===e.MToonMaterialOutlineColorMode.MixedLighting},this.vertexShader="// #define PHONG\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n\n#include <common>\n\n// #include <uv_pars_vertex>\n#ifdef MTOON_USE_UV\n #ifdef MTOON_UVS_VERTEX_ONLY\n vec2 vUv;\n #else\n varying vec2 vUv;\n #endif\n\n uniform vec4 mainTex_ST;\n#endif\n\n#include <uv2_pars_vertex>\n// #include <displacementmap_pars_vertex>\n// #include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\n#ifdef USE_OUTLINEWIDTHTEXTURE\n uniform sampler2D outlineWidthTexture;\n#endif\n\nuniform float outlineWidth;\nuniform float outlineScaledMaxDistance;\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef MTOON_USE_UV\n vUv = uv;\n vUv.y = 1.0 - vUv.y; // uv.y is opposite from UniVRM's\n vUv = mainTex_ST.st + mainTex_ST.pq * vUv;\n vUv.y = 1.0 - vUv.y; // reverting the previous flip\n #endif\n\n #include <uv2_vertex>\n #include <color_vertex>\n\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n\n // we need this to compute the outline properly\n objectNormal = normalize( objectNormal );\n\n #include <defaultnormal_vertex>\n\n #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #endif\n\n #include <begin_vertex>\n\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n // #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n\n vViewPosition = - mvPosition.xyz;\n\n float outlineTex = 1.0;\n\n #ifdef OUTLINE\n #ifdef USE_OUTLINEWIDTHTEXTURE\n outlineTex = texture2D( outlineWidthTexture, vUv ).r;\n #endif\n\n #ifdef OUTLINE_WIDTH_WORLD\n float worldNormalLength = length( transformedNormal );\n vec3 outlineOffset = 0.01 * outlineWidth * outlineTex * worldNormalLength * objectNormal;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 );\n #endif\n\n #ifdef OUTLINE_WIDTH_SCREEN\n vec3 clipNormal = ( projectionMatrix * modelViewMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n vec2 projectedNormal = normalize( clipNormal.xy );\n projectedNormal *= min( gl_Position.w, outlineScaledMaxDistance );\n projectedNormal.x *= projectionMatrix[ 0 ].x / projectionMatrix[ 1 ].y;\n gl_Position.xy += 0.01 * outlineWidth * outlineTex * projectedNormal.xy;\n #endif\n\n gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic\n #endif\n\n #include <worldpos_vertex>\n // #include <envmap_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n\n}",this.fragmentShader=K,parseInt(r.REVISION,10)<137){const e=(null!==this.shadeTexture?ee("shadeTextureTexelToLinear",this.shadeTexture.encoding)+"\n":"")+(null!==this.sphereAdd?ee("sphereAddTexelToLinear",this.sphereAdd.encoding)+"\n":"")+(null!==this.rimTexture?ee("rimTextureTexelToLinear",this.rimTexture.encoding)+"\n":"");this.fragmentShader=e+K}this.needsUpdate=!0}_updateCullFace(){this.isOutline?this.outlineCullMode===e.MToonMaterialCullMode.Off?this.side=r.DoubleSide:this.outlineCullMode===e.MToonMaterialCullMode.Front?this.side=r.BackSide:this.outlineCullMode===e.MToonMaterialCullMode.Back&&(this.side=r.FrontSide):this.cullMode===e.MToonMaterialCullMode.Off?this.side=r.DoubleSide:this.cullMode===e.MToonMaterialCullMode.Front?this.side=r.BackSide:this.cullMode===e.MToonMaterialCullMode.Back&&(this.side=r.FrontSide)}}var le;e.VRMUnlitMaterialRenderType=void 0,(le=e.VRMUnlitMaterialRenderType||(e.VRMUnlitMaterialRenderType={}))[le.Opaque=0]="Opaque",le[le.Cutout=1]="Cutout",le[le.Transparent=2]="Transparent",le[le.TransparentWithZWrite=3]="TransparentWithZWrite";class de extends r.ShaderMaterial{constructor(t){super(),this.isVRMUnlitMaterial=!0,this.cutoff=.5,this.map=null,this.mainTex_ST=new r.Vector4(0,0,1,1),this._renderType=e.VRMUnlitMaterialRenderType.Opaque,this.shouldApplyUniforms=!0,void 0===t&&(t={}),t.fog=!0,t.clipping=!0,parseInt(r.REVISION,10)<129&&(t.skinning=t.skinning||!1),parseInt(r.REVISION,10)<131&&(t.morphTargets=t.morphTargets||!1,t.morphNormals=t.morphNormals||!1),t.uniforms=r.UniformsUtils.merge([r.UniformsLib.common,r.UniformsLib.fog,{cutoff:{value:.5},mainTex_ST:{value:new r.Vector4(0,0,1,1)}}]),this.setValues(t),this._updateShaderCode(),this._applyUniforms()}get mainTex(){return this.map}set mainTex(e){this.map=e}get renderType(){return this._renderType}set renderType(t){this._renderType=t,this.depthWrite=this._renderType!==e.VRMUnlitMaterialRenderType.Transparent,this.transparent=this._renderType===e.VRMUnlitMaterialRenderType.Transparent||this._renderType===e.VRMUnlitMaterialRenderType.TransparentWithZWrite,this._updateShaderCode()}updateVRMMaterials(e){this._applyUniforms()}copy(e){return super.copy(e),this.cutoff=e.cutoff,this.map=e.map,this.mainTex_ST.copy(e.mainTex_ST),this.renderType=e.renderType,this}_applyUniforms(){this.shouldApplyUniforms&&(this.shouldApplyUniforms=!1,this.uniforms.cutoff.value=this.cutoff,this.uniforms.map.value=this.map,this.uniforms.mainTex_ST.value.copy(this.mainTex_ST))}_updateShaderCode(){this.defines={RENDERTYPE_OPAQUE:this._renderType===e.VRMUnlitMaterialRenderType.Opaque,RENDERTYPE_CUTOUT:this._renderType===e.VRMUnlitMaterialRenderType.Cutout,RENDERTYPE_TRANSPARENT:this._renderType===e.VRMUnlitMaterialRenderType.Transparent||this._renderType===e.VRMUnlitMaterialRenderType.TransparentWithZWrite},this.vertexShader="#include <common>\n\n// #include <uv_pars_vertex>\n#ifdef USE_MAP\n varying vec2 vUv;\n uniform vec4 mainTex_ST;\n#endif\n\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n\nvoid main() {\n\n // #include <uv_vertex>\n #ifdef USE_MAP\n vUv = vec2( mainTex_ST.p * uv.x + mainTex_ST.s, mainTex_ST.q * uv.y + mainTex_ST.t );\n #endif\n\n #include <uv2_vertex>\n #include <color_vertex>\n #include <skinbase_vertex>\n\n #ifdef USE_ENVMAP\n\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n\n #endif\n\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n\n #include <worldpos_vertex>\n #include <clipping_planes_vertex>\n #include <envmap_vertex>\n #include <fog_vertex>\n\n}",this.fragmentShader="#ifdef RENDERTYPE_CUTOUT\n uniform float cutoff;\n#endif\n\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n// #include <alphamap_pars_fragment>\n// #include <aomap_pars_fragment>\n// #include <lightmap_pars_fragment>\n// #include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n// #include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n\n// == main procedure ===========================================================\nvoid main() {\n #include <clipping_planes_fragment>\n\n vec4 diffuseColor = vec4( 1.0 );\n\n #include <logdepthbuf_fragment>\n\n #include <map_fragment>\n #include <color_fragment>\n // #include <alphamap_fragment>\n\n // MToon: alpha\n // #include <alphatest_fragment>\n #ifdef RENDERTYPE_CUTOUT\n if ( diffuseColor.a <= cutoff ) { discard; }\n diffuseColor.a = 1.0;\n #endif\n\n #ifdef RENDERTYPE_OPAQUE\n diffuseColor.a = 1.0;\n #endif\n\n // #include <specularmap_fragment>\n\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\n // accumulation (baked indirect lighting only)\n #ifdef USE_LIGHTMAP\n reflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n #else\n reflectedLight.indirectDiffuse += vec3( 1.0 );\n #endif\n\n // modulation\n // #include <aomap_fragment>\n\n reflectedLight.indirectDiffuse *= diffuseColor.rgb;\n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n\n // #include <envmap_fragment>\n\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\n #include <premultiplied_alpha_fragment>\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n}",this.needsUpdate=!0}}class he{constructor(e={}){this._encoding=e.encoding||r.LinearEncoding,this._encoding!==r.LinearEncoding&&this._encoding!==r.sRGBEncoding&&console.warn("The specified color encoding might not work properly with VRMMaterialImporter. You might want to use THREE.sRGBEncoding instead."),this._requestEnvMap=e.requestEnvMap}convertGLTFMaterials(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.materialProperties;if(!i)return null;const r=yield y(e),a={},s=[];return yield Promise.all(Array.from(r.entries()).map((([t,n])=>o(this,void 0,void 0,(function*(){const r=e.parser.json.nodes[t],l=e.parser.json.meshes[r.mesh];yield Promise.all(n.map(((t,n)=>o(this,void 0,void 0,(function*(){const r=l.primitives[n];if(!r)return;const o=t.geometry,d=o.index?o.index.count:o.attributes.position.count/3;Array.isArray(t.material)||(t.material=[t.material],o.addGroup(0,d,0));const h=r.material;let u,c=i[h];c||(console.warn(`VRMMaterialImporter: There are no material definition for material #${h} on VRM extension.`),c={shader:"VRM_USE_GLTFSHADER"}),a[h]?u=a[h]:(u=yield this.createVRMMaterials(t.material[0],c,e),a[h]=u,s.push(u.surface),u.outline&&s.push(u.outline)),t.material[0]=u.surface,this._requestEnvMap&&u.surface.isMeshStandardMaterial&&this._requestEnvMap().then((e=>{u.surface.envMap=e,u.surface.needsUpdate=!0})),t.renderOrder=c.renderQueue||2e3,u.outline&&(t.material[1]=u.outline,o.addGroup(0,d,1))})))))}))))),s}))}createVRMMaterials(t,n,i){return o(this,void 0,void 0,(function*(){let r,o;if("VRM/MToon"===n.shader){const a=yield this._extractMaterialProperties(t,n,i);["srcBlend","dstBlend","isFirstSetup"].forEach((e=>{void 0!==a[e]&&delete a[e]})),["mainTex","shadeTexture","emissionMap","sphereAdd","rimTexture"].forEach((e=>{void 0!==a[e]&&(a[e].encoding=this._encoding)})),a.encoding=this._encoding,r=new se(a),a.outlineWidthMode!==e.MToonMaterialOutlineWidthMode.None&&(a.isOutline=!0,o=new se(a))}else if("VRM/UnlitTexture"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.Opaque,r=new de(o)}else if("VRM/UnlitCutout"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.Cutout,r=new de(o)}else if("VRM/UnlitTransparent"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.Transparent,r=new de(o)}else if("VRM/UnlitTransparentZWrite"===n.shader){const o=yield this._extractMaterialProperties(t,n,i);o.renderType=e.VRMUnlitMaterialRenderType.TransparentWithZWrite,r=new de(o)}else"VRM_USE_GLTFSHADER"!==n.shader&&console.warn(`Unknown shader detected: "${n.shader}"`),r=this._convertGLTFMaterial(t.clone());return r.name=t.name,r.userData=JSON.parse(JSON.stringify(t.userData)),r.userData.vrmMaterialProperties=n,o&&(o.name=t.name+" (Outline)",o.userData=JSON.parse(JSON.stringify(t.userData)),o.userData.vrmMaterialProperties=n),{surface:r,outline:o}}))}_renameMaterialProperty(e){return"_"!==e[0]?(console.warn(`VRMMaterials: Given property name "${e}" might be invalid`),e):(e=e.substring(1),/[A-Z]/.test(e[0])?e[0].toLowerCase()+e.substring(1):(console.warn(`VRMMaterials: Given property name "${e}" might be invalid`),e))}_convertGLTFMaterial(e){if(e.isMeshStandardMaterial){const t=e;t.map&&(t.map.encoding=this._encoding),t.emissiveMap&&(t.emissiveMap.encoding=this._encoding),this._encoding===r.LinearEncoding&&(t.color.convertLinearToSRGB(),t.emissive.convertLinearToSRGB())}if(e.isMeshBasicMaterial){const t=e;t.map&&(t.map.encoding=this._encoding),this._encoding===r.LinearEncoding&&t.color.convertLinearToSRGB()}return e}_extractMaterialProperties(e,t,n){const i=[],o={};if(t.textureProperties)for(const e of Object.keys(t.textureProperties)){const r=this._renameMaterialProperty(e),a=t.textureProperties[e];i.push(n.parser.getDependency("texture",a).then((e=>{o[r]=e})))}if(t.floatProperties)for(const e of Object.keys(t.floatProperties)){const n=this._renameMaterialProperty(e);o[n]=t.floatProperties[e]}if(t.vectorProperties)for(const e of Object.keys(t.vectorProperties)){let n=this._renameMaterialProperty(e);["_MainTex","_ShadeTexture","_BumpMap","_ReceiveShadowTexture","_ShadingGradeTexture","_RimTexture","_SphereAdd","_EmissionMap","_OutlineWidthTexture","_UvAnimMaskTexture"].some((t=>e===t))&&(n+="_ST"),o[n]=new r.Vector4(...t.vectorProperties[e])}return parseInt(r.REVISION,10)<129&&(o.skinning=e.skinning||!1),parseInt(r.REVISION,10)<131&&(o.morphTargets=e.morphTargets||!1,o.morphNormals=e.morphNormals||!1),Promise.all(i).then((()=>o))}}class ue{constructor(e){var t;this.ignoreTexture=null!==(t=null==e?void 0:e.ignoreTexture)&&void 0!==t&&t}import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.meta;if(!i)return null;let r;return this.ignoreTexture||null==i.texture||-1===i.texture||(r=yield e.parser.getDependency("texture",i.texture)),{allowedUserName:i.allowedUserName,author:i.author,commercialUssageName:i.commercialUssageName,contactInformation:i.contactInformation,licenseName:i.licenseName,otherLicenseUrl:i.otherLicenseUrl,otherPermissionUrl:i.otherPermissionUrl,reference:i.reference,sexualUssageName:i.sexualUssageName,texture:null!=r?r:void 0,title:i.title,version:i.version,violentUssageName:i.violentUssageName}}))}}const ce=new r.Matrix4;function pe(e){return e.invert?e.invert():e.getInverse(ce.copy(e)),e}class me{constructor(e){this._inverseCache=new r.Matrix4,this._shouldUpdateInverse=!0,this.matrix=e;const t={set:(e,t,n)=>(this._shouldUpdateInverse=!0,e[t]=n,!0)};this._originalElements=e.elements,e.elements=new Proxy(e.elements,t)}get inverse(){return this._shouldUpdateInverse&&(pe(this._inverseCache.copy(this.matrix)),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}}const fe=Object.freeze(new r.Matrix4),ge=Object.freeze(new r.Quaternion),_e=new r.Vector3,ve=new r.Vector3,Me=new r.Vector3,Te=new r.Quaternion,ye=new r.Matrix4,xe=new r.Matrix4;class Se{constructor(e,t={}){var n,i,o,a,s,l;if(this._currentTail=new r.Vector3,this._prevTail=new r.Vector3,this._nextTail=new r.Vector3,this._boneAxis=new r.Vector3,this._centerSpacePosition=new r.Vector3,this._center=null,this._parentWorldRotation=new r.Quaternion,this._initialLocalMatrix=new r.Matrix4,this._initialLocalRotation=new r.Quaternion,this._initialLocalChildPosition=new r.Vector3,this.bone=e,this.bone.matrixAutoUpdate=!1,this.radius=null!==(n=t.radius)&&void 0!==n?n:.02,this.stiffnessForce=null!==(i=t.stiffnessForce)&&void 0!==i?i:1,this.gravityDir=t.gravityDir?(new r.Vector3).copy(t.gravityDir):(new r.Vector3).set(0,-1,0),this.gravityPower=null!==(o=t.gravityPower)&&void 0!==o?o:0,this.dragForce=null!==(a=t.dragForce)&&void 0!==a?a:.4,this.colliders=null!==(s=t.colliders)&&void 0!==s?s:[],this._centerSpacePosition.setFromMatrixPosition(this.bone.matrixWorld),this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),0===this.bone.children.length)this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);else{const e=this.bone.children[0];this._initialLocalChildPosition.copy(e.position)}this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)),this._prevTail.copy(this._currentTail),this._nextTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize(),this._centerSpaceBoneLength=_e.copy(this._initialLocalChildPosition).applyMatrix4(this.bone.matrixWorld).sub(this._centerSpacePosition).length(),this.center=null!==(l=t.center)&&void 0!==l?l:null}get center(){return this._center}set center(e){var t;this._getMatrixCenterToWorld(ye),this._currentTail.applyMatrix4(ye),this._prevTail.applyMatrix4(ye),this._nextTail.applyMatrix4(ye),(null===(t=this._center)||void 0===t?void 0:t.userData.inverseCacheProxy)&&(this._center.userData.inverseCacheProxy.revert(),delete this._center.userData.inverseCacheProxy),this._center=e,this._center&&(this._center.userData.inverseCacheProxy||(this._center.userData.inverseCacheProxy=new me(this._center.matrixWorld))),this._getMatrixWorldToCenter(ye),this._currentTail.applyMatrix4(ye),this._prevTail.applyMatrix4(ye),this._nextTail.applyMatrix4(ye),ye.multiply(this.bone.matrixWorld),this._centerSpacePosition.setFromMatrixPosition(ye),this._centerSpaceBoneLength=_e.copy(this._initialLocalChildPosition).applyMatrix4(ye).sub(this._centerSpacePosition).length()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix),this._centerSpacePosition.setFromMatrixPosition(this.bone.matrixWorld),this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)),this._prevTail.copy(this._currentTail),this._nextTail.copy(this._currentTail)}update(e){if(e<=0)return;this.bone.parent?E(this.bone.parent,this._parentWorldRotation):this._parentWorldRotation.copy(ge),this._getMatrixWorldToCenter(ye),ye.multiply(this.bone.matrixWorld),this._centerSpacePosition.setFromMatrixPosition(ye),this._getMatrixWorldToCenter(xe),xe.multiply(this._getParentMatrixWorld());const t=this.stiffnessForce*e,n=ve.copy(this.gravityDir).multiplyScalar(this.gravityPower*e);this._nextTail.copy(this._currentTail).add(_e.copy(this._currentTail).sub(this._prevTail).multiplyScalar(1-this.dragForce)).add(_e.copy(this._boneAxis).applyMatrix4(this._initialLocalMatrix).applyMatrix4(xe).sub(this._centerSpacePosition).normalize().multiplyScalar(t)).add(n),this._nextTail.sub(this._centerSpacePosition).normalize().multiplyScalar(this._centerSpaceBoneLength).add(this._centerSpacePosition),this._collision(this._nextTail),this._prevTail.copy(this._currentTail),this._currentTail.copy(this._nextTail);const i=pe(ye.copy(xe.multiply(this._initialLocalMatrix))),r=Te.setFromUnitVectors(this._boneAxis,_e.copy(this._nextTail).applyMatrix4(i).normalize());this.bone.quaternion.copy(this._initialLocalRotation).multiply(r),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(),this.bone.matrix)}_collision(e){this.colliders.forEach((t=>{this._getMatrixWorldToCenter(ye),ye.multiply(t.matrixWorld);const n=_e.setFromMatrixPosition(ye),i=t.geometry.boundingSphere.radius,r=this.radius+i;if(e.distanceToSquared(n)<=r*r){const t=ve.subVectors(e,n).normalize(),i=Me.addVectors(n,t.multiplyScalar(r));e.copy(i.sub(this._centerSpacePosition).normalize().multiplyScalar(this._centerSpaceBoneLength).add(this._centerSpacePosition))}}))}_getMatrixCenterToWorld(e){return this._center?e.copy(this._center.matrixWorld):e.identity(),e}_getMatrixWorldToCenter(e){return this._center?e.copy(this._center.userData.inverseCacheProxy.inverse):e.identity(),e}_getParentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:fe}}class Re{constructor(e,t){this.colliderGroups=[],this.springBoneGroupList=[],this.colliderGroups=e,this.springBoneGroupList=t}setCenter(e){this.springBoneGroupList.forEach((t=>{t.forEach((t=>{t.center=e}))}))}lateUpdate(e){const t=new Set;this.springBoneGroupList.forEach((n=>{n.forEach((n=>{this._updateWorldMatrix(t,n.bone),n.update(e)}))}))}reset(){const e=new Set;this.springBoneGroupList.forEach((t=>{t.forEach((t=>{this._updateWorldMatrix(e,t.bone),t.reset()}))}))}_updateWorldMatrix(e,t){e.has(t)||(t.parent&&this._updateWorldMatrix(e,t.parent),t.updateWorldMatrix(!1,!1),e.add(t))}}const Ee=new r.Vector3,Le=new r.MeshBasicMaterial({visible:!1});class we{import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.secondaryAnimation;if(!i)return null;const r=yield this._importColliderMeshGroups(e,i),o=yield this._importSpringBoneGroupList(e,i,r);return new Re(r,o)}))}_createSpringBone(e,t={}){return new Se(e,t)}_importSpringBoneGroupList(e,t,n){return o(this,void 0,void 0,(function*(){const i=t.boneGroups||[],a=[];return yield Promise.all(i.map((t=>o(this,void 0,void 0,(function*(){if(void 0===t.stiffiness||void 0===t.gravityDir||void 0===t.gravityDir.x||void 0===t.gravityDir.y||void 0===t.gravityDir.z||void 0===t.gravityPower||void 0===t.dragForce||void 0===t.hitRadius||void 0===t.colliderGroups||void 0===t.bones||void 0===t.center)return;const i=t.stiffiness,s=new r.Vector3(t.gravityDir.x,t.gravityDir.y,-t.gravityDir.z),l=t.gravityPower,d=t.dragForce,h=t.hitRadius,u=[];t.colliderGroups.forEach((e=>{u.push(...n[e].colliders)}));const c=[];yield Promise.all(t.bones.map((n=>o(this,void 0,void 0,(function*(){const r=yield e.parser.getDependency("node",n),o=-1!==t.center?yield e.parser.getDependency("node",t.center):null;r&&r.traverse((e=>{const t=this._createSpringBone(e,{radius:h,stiffnessForce:i,gravityDir:s,gravityPower:l,dragForce:d,colliders:u,center:o});c.push(t)}))}))))),a.push(c)}))))),a}))}_importColliderMeshGroups(e,t){return o(this,void 0,void 0,(function*(){const n=t.colliderGroups;if(void 0===n)return[];const i=[];return n.forEach((t=>o(this,void 0,void 0,(function*(){if(void 0===t.node||void 0===t.colliders)return;const n=yield e.parser.getDependency("node",t.node),r=[];t.colliders.forEach((e=>{if(void 0===e.offset||void 0===e.offset.x||void 0===e.offset.y||void 0===e.offset.z||void 0===e.radius)return;const t=Ee.set(e.offset.x,e.offset.y,-e.offset.z),i=this._createColliderMesh(e.radius,t);n.add(i),r.push(i)}));const o={node:t.node,colliders:r};i.push(o)})))),i}))}_createColliderMesh(e,t){const n=new r.Mesh(new r.SphereBufferGeometry(e,8,4),Le);return n.position.copy(t),n.name="vrmColliderSphere",n.geometry.computeBoundingSphere(),n}}class Pe{constructor(e={}){this._metaImporter=e.metaImporter||new ue,this._blendShapeImporter=e.blendShapeImporter||new w,this._lookAtImporter=e.lookAtImporter||new J,this._humanoidImporter=e.humanoidImporter||new G,this._firstPersonImporter=e.firstPersonImporter||new I,this._materialImporter=e.materialImporter||new he,this._springBoneImporter=e.springBoneImporter||new we}import(e){return o(this,void 0,void 0,(function*(){if(void 0===e.parser.json.extensions||void 0===e.parser.json.extensions.VRM)throw new Error("Could not find VRM extension on the GLTF");const t=e.scene;t.updateMatrixWorld(!1),t.traverse((e=>{e.isMesh&&(e.frustumCulled=!1)}));const n=(yield this._metaImporter.import(e))||void 0,i=(yield this._materialImporter.convertGLTFMaterials(e))||void 0,r=(yield this._humanoidImporter.import(e))||void 0,o=r&&(yield this._firstPersonImporter.import(e,r))||void 0,a=(yield this._blendShapeImporter.import(e))||void 0,s=o&&a&&r&&(yield this._lookAtImporter.import(e,o,a,r))||void 0,l=(yield this._springBoneImporter.import(e))||void 0;return new Ae({scene:e.scene,meta:n,materials:i,humanoid:r,firstPerson:o,blendShapeProxy:a,lookAt:s,springBoneManager:l})}))}}class Ae{constructor(e){this.scene=e.scene,this.humanoid=e.humanoid,this.blendShapeProxy=e.blendShapeProxy,this.firstPerson=e.firstPerson,this.lookAt=e.lookAt,this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.meta=e.meta}static from(e,t={}){return o(this,void 0,void 0,(function*(){const n=new Pe(t);return yield n.import(e)}))}update(e){this.lookAt&&this.lookAt.update(e),this.blendShapeProxy&&this.blendShapeProxy.update(),this.springBoneManager&&this.springBoneManager.lateUpdate(e),this.materials&&this.materials.forEach((t=>{t.updateVRMMaterials&&t.updateVRMMaterials(e)}))}dispose(){var e,t;const n=this.scene;n&&n.traverse(s),null===(t=null===(e=this.meta)||void 0===e?void 0:e.texture)||void 0===t||t.dispose()}}const be=new r.Vector2,Oe=new r.OrthographicCamera(-1,1,-1,1,-1,1),Ce=new r.MeshBasicMaterial({color:16777215,side:r.DoubleSide}),Ie=new r.Mesh(new r.PlaneBufferGeometry(2,2),Ce),Ve=new r.Scene;Ve.add(Ie);class De{constructor(){}}De.extractThumbnailBlob=function(e,t,n=512){var i;const r=null===(i=t.meta)||void 0===i?void 0:i.texture;if(!r)throw new Error("extractThumbnailBlob: This VRM does not have a thumbnail");const o=e.getContext().canvas;e.getSize(be);const a=be.x,s=be.y;return e.setSize(n,n,!1),Ce.map=r,e.render(Ve,Oe),Ce.map=null,o instanceof OffscreenCanvas?o.convertToBlob().finally((()=>{e.setSize(a,s,!1)})):new Promise(((t,n)=>{o.toBlob((i=>{e.setSize(a,s,!1),null==i?n("extractThumbnailBlob: Failed to create a blob"):t(i)}))}))},De.removeUnnecessaryJoints=function(e){const t=new Map;e.traverse((e=>{if("SkinnedMesh"!==e.type)return;const n=e,i=n.geometry.getAttribute("skinIndex");let o=t.get(i);if(!o){const e=[],a=[],s={},l=i.array;for(let t=0;t<l.length;t++){const i=l[t];void 0===s[i]&&(s[i]=e.length,e.push(n.skeleton.bones[i]),a.push(n.skeleton.boneInverses[i])),l[t]=s[i]}i.copyArray(l),i.needsUpdate=!0,o=new r.Skeleton(e,a),t.set(i,o)}n.bind(o,new r.Matrix4)}))},De.removeUnnecessaryVertices=function(e){const n=new Map;e.traverse((e=>{var i,o,a,s;if(!e.isMesh)return;const l=e,d=l.geometry,h=d.index;if(null==h)return;const u=n.get(d);if(null!=u)return void(l.geometry=u);const c=new r.BufferGeometry;c.name=d.name,c.morphTargetsRelative=d.morphTargetsRelative,d.groups.forEach((e=>{c.addGroup(e.start,e.count,e.materialIndex)})),c.boundingBox=null!==(o=null===(i=d.boundingBox)||void 0===i?void 0:i.clone())&&void 0!==o?o:null,c.boundingSphere=null!==(s=null===(a=d.boundingSphere)||void 0===a?void 0:a.clone())&&void 0!==s?s:null,c.setDrawRange(d.drawRange.start,d.drawRange.count),c.userData=d.userData,n.set(d,c);const p=[],m=[];{const e=h.array,n=new e.constructor(e.length);let i=0;for(let t=0;t<e.length;t++){const r=e[t];let o=p[r];null==o&&(p[r]=i,m[i]=r,o=i,i++),n[t]=o}c.setIndex(new t.BufferAttribute(n,1,!1))}Object.keys(d.attributes).forEach((e=>{const n=d.attributes[e];if(n.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const i=n.array,{itemSize:r,normalized:o}=n,a=new i.constructor(m.length*r);m.forEach(((e,t)=>{for(let n=0;n<r;n++)a[t*r+n]=i[e*r+n]})),c.setAttribute(e,new t.BufferAttribute(a,r,o))}));let f=!0;Object.keys(d.morphAttributes).forEach((e=>{c.morphAttributes[e]=[];const n=d.morphAttributes[e];for(let i=0;i<n.length;i++){const r=n[i];if(r.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const o=r.array,{itemSize:a,normalized:s}=r,l=new o.constructor(m.length*a);m.forEach(((e,t)=>{for(let n=0;n<a;n++)l[t*a+n]=o[e*a+n]})),f=f&&l.every((e=>0===e)),c.morphAttributes[e][i]=new t.BufferAttribute(l,a,s)}})),f&&(c.morphAttributes={}),l.geometry=c})),Array.from(n.keys()).forEach((e=>{e.dispose()}))};const Ne=new r.Vector3;class Ue extends q{setupHelper(e,t){t.disableFaceDirectionHelper||(this._faceDirectionHelper=new r.ArrowHelper(new r.Vector3(0,0,-1),new r.Vector3(0,0,0),.5,16711935),e.add(this._faceDirectionHelper))}update(e){super.update(e),this._faceDirectionHelper&&(this.firstPerson.getFirstPersonWorldPosition(this._faceDirectionHelper.position),this._faceDirectionHelper.setDirection(this.getLookAtWorldDirection(Ne)))}}class Be extends J{import(e,t,n,i){var r;const o=null===(r=e.parser.json.extensions)||void 0===r?void 0:r.VRM;if(!o)return null;const a=o.firstPerson;if(!a)return null;const s=this._importApplyer(a,n,i);return new Ue(t,s||void 0)}}const Ge=new r.MeshBasicMaterial({color:16711935,wireframe:!0,transparent:!0,depthTest:!1});class He extends Re{setupHelper(e,t){t.disableSpringBoneHelper||(this.springBoneGroupList.forEach((t=>{t.forEach((t=>{if(t.getGizmo){const n=t.getGizmo();e.add(n)}}))})),this.colliderGroups.forEach((e=>{e.colliders.forEach((e=>{e.material=Ge,e.renderOrder=je}))})))}}const ke=new r.Vector3;class Fe extends Se{constructor(e,t){super(e,t)}getGizmo(){if(this._gizmo)return this._gizmo;const e=ke.copy(this._nextTail).sub(this._centerSpacePosition),t=e.length();return this._gizmo=new r.ArrowHelper(e.normalize(),this._centerSpacePosition,t,16776960,this.radius,this.radius),this._gizmo.line.renderOrder=je,this._gizmo.cone.renderOrder=je,this._gizmo.line.material.depthTest=!1,this._gizmo.line.material.transparent=!0,this._gizmo.cone.material.depthTest=!1,this._gizmo.cone.material.transparent=!0,this._gizmo}update(e){super.update(e),this._updateGizmo()}_updateGizmo(){if(!this._gizmo)return;const e=ke.copy(this._currentTail).sub(this._centerSpacePosition),t=e.length();this._gizmo.setDirection(e.normalize()),this._gizmo.setLength(t,this.radius,this.radius),this._gizmo.position.copy(this._centerSpacePosition)}}class We extends we{import(e){var t;return o(this,void 0,void 0,(function*(){const n=null===(t=e.parser.json.extensions)||void 0===t?void 0:t.VRM;if(!n)return null;const i=n.secondaryAnimation;if(!i)return null;const r=yield this._importColliderMeshGroups(e,i),o=yield this._importSpringBoneGroupList(e,i,r);return new He(r,o)}))}_createSpringBone(e,t){return new Fe(e,t)}}class ze extends Pe{constructor(e={}){e.lookAtImporter=e.lookAtImporter||new Be,e.springBoneImporter=e.springBoneImporter||new We,super(e)}import(e,t={}){return o(this,void 0,void 0,(function*(){if(void 0===e.parser.json.extensions||void 0===e.parser.json.extensions.VRM)throw new Error("Could not find VRM extension on the GLTF");const n=e.scene;n.updateMatrixWorld(!1),n.traverse((e=>{e.isMesh&&(e.frustumCulled=!1)}));const i=(yield this._metaImporter.import(e))||void 0,r=(yield this._materialImporter.convertGLTFMaterials(e))||void 0,o=(yield this._humanoidImporter.import(e))||void 0,a=o&&(yield this._firstPersonImporter.import(e,o))||void 0,s=(yield this._blendShapeImporter.import(e))||void 0,l=a&&s&&o&&(yield this._lookAtImporter.import(e,a,s,o))||void 0;l.setupHelper&&l.setupHelper(n,t);const d=(yield this._springBoneImporter.import(e))||void 0;return d.setupHelper&&d.setupHelper(n,t),new Ye({scene:e.scene,meta:i,materials:r,humanoid:o,firstPerson:a,blendShapeProxy:s,lookAt:l,springBoneManager:d},t)}))}}const je=1e4;class Ye extends Ae{static from(e,t={},n={}){return o(this,void 0,void 0,(function*(){const i=new ze(t);return yield i.import(e,n)}))}constructor(e,t={}){super(e),t.disableBoxHelper||this.scene.add(new r.BoxHelper(this.scene)),t.disableSkeletonHelper||this.scene.add(new r.SkeletonHelper(this.scene))}update(e){super.update(e)}}e.MToonMaterial=se,e.VRM=Ae,e.VRMBlendShapeGroup=c,e.VRMBlendShapeImporter=w,e.VRMBlendShapeProxy=L,e.VRMCurveMapper=H,e.VRMDebug=Ye,e.VRMFirstPerson=C,e.VRMFirstPersonImporter=I,e.VRMHumanBone=V,e.VRMHumanoid=B,e.VRMHumanoidImporter=G,e.VRMImporter=Pe,e.VRMLookAtApplyer=k,e.VRMLookAtBlendShapeApplyer=F,e.VRMLookAtBoneApplyer=Z,e.VRMLookAtHead=q,e.VRMLookAtImporter=J,e.VRMMaterialImporter=he,e.VRMMetaImporter=ue,e.VRMRendererFirstPersonFlags=O,e.VRMSpringBone=Se,e.VRMSpringBoneDebug=Fe,e.VRMSpringBoneImporter=we,e.VRMSpringBoneImporterDebug=We,e.VRMSpringBoneManager=Re,e.VRMUnlitMaterial=de,e.VRMUtils=De,e.VRM_GIZMO_RENDER_ORDER=je,Object.defineProperty(e,"__esModule",{value:!0}),Object.assign(t,e)}));
|