diff --git a/assets/howler-ccbf4ffc.js b/assets/howler-a528f2ae.js similarity index 99% rename from assets/howler-ccbf4ffc.js rename to assets/howler-a528f2ae.js index d2a46ada..56c0741c 100644 --- a/assets/howler-ccbf4ffc.js +++ b/assets/howler-a528f2ae.js @@ -1,4 +1,4 @@ -import{g as L,c as S}from"./index-28b71aae.js";function D(b,g){for(var r=0;ru[i]})}}}return Object.freeze(Object.defineProperty(b,Symbol.toStringTag,{value:"Module"}))}var O={};/*! +import{g as L,c as S}from"./index-1f82b44b.js";function D(b,g){for(var r=0;ru[i]})}}}return Object.freeze(Object.defineProperty(b,Symbol.toStringTag,{value:"Module"}))}var O={};/*! * howler.js v2.2.3 * howlerjs.com * diff --git a/assets/index-28b71aae.js b/assets/index-1f82b44b.js similarity index 98% rename from assets/index-28b71aae.js rename to assets/index-1f82b44b.js index 8ede7832..964d9238 100644 --- a/assets/index-28b71aae.js +++ b/assets/index-1f82b44b.js @@ -4104,7 +4104,7 @@ void main() { * Copyright (c) 2020-2023 pixiv Inc. * @pixiv/three-vrm-springbone is distributed under MIT License * https://github.com/pixiv/three-vrm/blob/release/LICENSE - */class mH{}const i1=new z,Ec=new z;class vH extends mH{constructor(e){var t,r,i;super(),this.offset=(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:new z(0,0,0),this.tail=(r=e==null?void 0:e.tail)!==null&&r!==void 0?r:new z(0,0,0),this.radius=(i=e==null?void 0:e.radius)!==null&&i!==void 0?i:0}get type(){return"capsule"}calculateCollision(e,t,r,i){i1.copy(this.offset).applyMatrix4(e),Ec.copy(this.tail).applyMatrix4(e),Ec.sub(i1);const s=Ec.lengthSq();i.copy(t).sub(i1);const o=Ec.dot(i);o<=0||(s<=o||Ec.multiplyScalar(o/s),i.sub(Ec));const a=r+this.radius,l=i.length()-a;return i.normalize(),l}}class yH extends mH{constructor(e){var t,r;super(),this.offset=(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:new z(0,0,0),this.radius=(r=e==null?void 0:e.radius)!==null&&r!==void 0?r:0}get type(){return"sphere"}calculateCollision(e,t,r,i){i.copy(this.offset).applyMatrix4(e),i.negate().add(t);const s=r+this.radius,o=i.length()-s;return i.normalize(),o}}const Yo=new z;class Bfe extends Ht{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new z,this._currentTail=new z,this._shape=e,this._attrPos=new At(new Float32Array(396),3),this.setAttribute("position",this._attrPos),this._attrIndex=new At(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;const t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0);const r=Yo.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(r)>1e-10&&(this._currentTail.copy(r),e=!0),e&&this._buildPosition()}_buildPosition(){Yo.copy(this._currentTail).sub(this._currentOffset);const e=Yo.length()/this._currentRadius;for(let i=0;i<=16;i++){const s=i/16*Math.PI;this._attrPos.setXYZ(i,-Math.sin(s),-Math.cos(s),0),this._attrPos.setXYZ(17+i,e+Math.sin(s),Math.cos(s),0),this._attrPos.setXYZ(34+i,-Math.sin(s),0,-Math.cos(s)),this._attrPos.setXYZ(51+i,e+Math.sin(s),0,Math.cos(s))}for(let i=0;i<32;i++){const s=i/16*Math.PI;this._attrPos.setXYZ(68+i,0,Math.sin(s),Math.cos(s)),this._attrPos.setXYZ(100+i,e,Math.sin(s),Math.cos(s))}const t=Math.atan2(Yo.y,Math.sqrt(Yo.x*Yo.x+Yo.z*Yo.z)),r=-Math.atan2(Yo.z,Yo.x);this.rotateZ(t),this.rotateY(r),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<34;e++){const t=(e+1)%34;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(68+e*2,34+e,34+t)}for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(136+e*2,68+e,68+t),this._attrIndex.setXY(200+e*2,100+e,100+t)}this._attrIndex.needsUpdate=!0}}class wfe extends Ht{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new z,this._shape=e,this._attrPos=new At(new Float32Array(32*3*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new At(new Uint16Array(64*3),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;const t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){const t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.needsUpdate=!0}}const Cfe=new z;class $D extends Tr{constructor(e){if(super(),this.matrixAutoUpdate=!1,this.collider=e,this.collider.shape instanceof yH)this._geometry=new wfe(this.collider.shape);else if(this.collider.shape instanceof vH)this._geometry=new Bfe(this.collider.shape);else throw new Error("VRMSpringBoneColliderHelper: Unknown collider shape type detected");const t=new Wl({color:16711935,depthTest:!1,depthWrite:!1});this._line=new u0(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);const t=this.matrix.elements;this._geometry.worldScale=Cfe.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}}class bfe extends Ht{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new z,this._springBone=e,this._attrPos=new At(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new At(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;const t=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){const t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}}const xfe=new z;class Ife extends Tr{constructor(e){super(),this.matrixAutoUpdate=!1,this.springBone=e,this._geometry=new bfe(this.springBone);const t=new Wl({color:16776960,depthTest:!1,depthWrite:!1});this._line=new u0(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);const t=this.matrix.elements;this._geometry.worldScale=xfe.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}}class qD extends kt{constructor(e){super(),this.shape=e}}const Ffe=new Le;function BH(n){return n.invert?n.invert():n.getInverse(Ffe.copy(n)),n}class Efe{constructor(e){this._inverseCache=new Le,this._shouldUpdateInverse=!0,this.matrix=e;const t={set:(r,i,s)=>(this._shouldUpdateInverse=!0,r[i]=s,!0)};this._originalElements=e.elements,e.elements=new Proxy(e.elements,t)}get inverse(){return this._shouldUpdateInverse&&(this._inverseCache.copy(this.matrix),BH(this._inverseCache),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}}const Ufe=new Le,ja=new z,Vp=new z,Sfe=new z,wf=new z,ek=new z,Lp=new z,tk=new tt,Cf=new Le,_fe=new Le;class Qfe{constructor(e,t,r={},i=[]){var s,o,a,l,A,c;this._currentTail=new z,this._prevTail=new z,this._boneAxis=new z,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new Le,this._initialLocalRotation=new tt,this._initialLocalChildPosition=new z,this.bone=e,this.bone.matrixAutoUpdate=!1,this.child=t,this.settings={hitRadius:(s=r.hitRadius)!==null&&s!==void 0?s:0,stiffness:(o=r.stiffness)!==null&&o!==void 0?o:1,gravityPower:(a=r.gravityPower)!==null&&a!==void 0?a:0,gravityDir:(A=(l=r.gravityDir)===null||l===void 0?void 0:l.clone())!==null&&A!==void 0?A:new z(0,-1,0),dragForce:(c=r.dragForce)!==null&&c!==void 0?c:.4},this.colliderGroups=i}get center(){return this._center}set center(e){var t;!((t=this._center)===null||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 Efe(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:Ufe}setInitState(){this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),this.child?this._initialLocalChildPosition.copy(this.child.position):this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);const e=this._getMatrixWorldToCenter(Cf);this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix);const e=this._getMatrixWorldToCenter(Cf);this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail)}update(e){if(e<=0)return;this._calcWorldSpaceBoneLength(),wf.setFromMatrixPosition(this.bone.matrixWorld);let t=this._getMatrixWorldToCenter(Cf);ek.copy(wf).applyMatrix4(t);const r=tk.setFromRotationMatrix(t),i=_fe.copy(t).multiply(this._parentMatrixWorld),s=Vp.copy(this._boneAxis).applyMatrix4(this._initialLocalMatrix).applyMatrix4(i).sub(ek).normalize(),o=Sfe.copy(this.settings.gravityDir).applyQuaternion(r).normalize(),a=this._getMatrixCenterToWorld(Cf);Lp.copy(this._currentTail).add(ja.copy(this._currentTail).sub(this._prevTail).multiplyScalar(1-this.settings.dragForce)).add(ja.copy(s).multiplyScalar(this.settings.stiffness*e)).add(ja.copy(o).multiplyScalar(this.settings.gravityPower*e)).applyMatrix4(a),Lp.sub(wf).normalize().multiplyScalar(this._worldSpaceBoneLength).add(wf),this._collision(Lp),t=this._getMatrixWorldToCenter(Cf),this._prevTail.copy(this._currentTail),this._currentTail.copy(ja.copy(Lp).applyMatrix4(t));const l=BH(Cf.copy(this._parentMatrixWorld).multiply(this._initialLocalMatrix)),A=tk.setFromUnitVectors(this._boneAxis,ja.copy(Lp).applyMatrix4(l).normalize());this.bone.quaternion.copy(this._initialLocalRotation).multiply(A),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(e){this.colliderGroups.forEach(t=>{t.colliders.forEach(r=>{const i=r.shape.calculateCollision(r.matrixWorld,e,this.settings.hitRadius,ja);i<0&&(e.add(ja.multiplyScalar(-i)),e.sub(wf).normalize().multiplyScalar(this._worldSpaceBoneLength).add(wf))})})}_calcWorldSpaceBoneLength(){ja.setFromMatrixPosition(this.bone.matrixWorld),this.child?Vp.setFromMatrixPosition(this.child.matrixWorld):(Vp.copy(this._initialLocalChildPosition),Vp.applyMatrix4(this.bone.matrixWorld)),this._worldSpaceBoneLength=ja.sub(Vp).length()}_getMatrixCenterToWorld(e){return this._center?e.copy(this._center.matrixWorld):e.identity(),e}_getMatrixWorldToCenter(e){return this._center?e.copy(this._center.userData.inverseCacheProxy.inverse):e.identity(),e}}function ry(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{A(r.next(c))}catch(u){o(u)}}function l(c){try{A(r.throw(c))}catch(u){o(u)}}function A(c){c.done?s(c.value):i(c.value).then(a,l)}A((r=r.apply(n,e||[])).next())})}function Rfe(n,e){const t=[];let r=n;for(;r!==null;)t.unshift(r),r=r.parent;t.forEach(i=>{e(i)})}function wH(n,e){n.children.forEach(t=>{e(t)||wH(t,e)})}class nk{constructor(){this._joints=new Set,this._objectSpringBonesMap=new Map}get joints(){return this._joints}get springBones(){return console.warn("VRMSpringBoneManager: springBones is deprecated. use joints instead."),this._joints}get colliderGroups(){const e=new Set;return this._joints.forEach(t=>{t.colliderGroups.forEach(r=>{e.add(r)})}),Array.from(e)}get colliders(){const e=new Set;return this.colliderGroups.forEach(t=>{t.colliders.forEach(r=>{e.add(r)})}),Array.from(e)}addJoint(e){this._joints.add(e);let t=this._objectSpringBonesMap.get(e.bone);t==null&&(t=new Set,this._objectSpringBonesMap.set(e.bone,t)),t.add(e)}addSpringBone(e){console.warn("VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead."),this.addJoint(e)}deleteJoint(e){this._joints.delete(e),this._objectSpringBonesMap.get(e.bone).delete(e)}deleteSpringBone(e){console.warn("VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead."),this.deleteJoint(e)}setInitState(){const e=new Set,t=new Set,r=new Set;for(const i of this._joints)this._processSpringBone(i,e,t,r,s=>s.setInitState())}reset(){const e=new Set,t=new Set,r=new Set;for(const i of this._joints)this._processSpringBone(i,e,t,r,s=>s.reset())}update(e){const t=new Set,r=new Set,i=new Set;for(const s of this._joints)this._processSpringBone(s,t,r,i,o=>o.update(e)),wH(s.bone,o=>{var a,l;return((l=(a=this._objectSpringBonesMap.get(o))===null||a===void 0?void 0:a.size)!==null&&l!==void 0?l:0)>0?!0:(o.updateWorldMatrix(!1,!1),!1)})}_processSpringBone(e,t,r,i,s){if(r.has(e))return;if(t.has(e))throw new Error("VRMSpringBoneManager: Circular dependency detected while updating springbones");t.add(e);const o=this._getDependencies(e);for(const a of o)Rfe(a,l=>{const A=this._objectSpringBonesMap.get(l);if(A)for(const c of A)this._processSpringBone(c,t,r,i,s);else i.has(l)||(l.updateWorldMatrix(!1,!1),i.add(l))});e.bone.updateMatrix(),e.bone.updateWorldMatrix(!1,!1),s(e),i.add(e.bone),r.add(e)}_getDependencies(e){const t=new Set,r=e.bone.parent;return r&&t.add(r),e.colliderGroups.forEach(i=>{i.colliders.forEach(s=>{t.add(s)})}),t}}const Mfe=new Set(["1.0","1.0-beta"]);class Kc{constructor(e,t){this.parser=e,this.jointHelperRoot=t==null?void 0:t.jointHelperRoot,this.colliderHelperRoot=t==null?void 0:t.colliderHelperRoot}get name(){return Kc.EXTENSION_NAME}afterRoot(e){return ry(this,void 0,void 0,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return ry(this,void 0,void 0,function*(){const t=yield this._v1Import(e);if(t!=null)return t;const r=yield this._v0Import(e);return r??null})}_v1Import(e){var t,r,i,s,o;return ry(this,void 0,void 0,function*(){const a=e.parser.json;if(!(((t=a.extensionsUsed)===null||t===void 0?void 0:t.indexOf(Kc.EXTENSION_NAME))!==-1))return null;const A=new nk,c=yield e.parser.getDependencies("node"),u=(r=a.extensions)===null||r===void 0?void 0:r[Kc.EXTENSION_NAME];if(!u)return null;const f=u.specVersion;if(!Mfe.has(f))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${Kc.EXTENSION_NAME} specVersion "${f}"`),null;const d=(i=u.colliders)===null||i===void 0?void 0:i.map((p,m)=>{var g,v,y,w,C;const b=c[p.node],E=p.shape;if(E.sphere)return this._importSphereCollider(b,{offset:new z().fromArray((g=E.sphere.offset)!==null&&g!==void 0?g:[0,0,0]),radius:(v=E.sphere.radius)!==null&&v!==void 0?v:0});if(E.capsule)return this._importCapsuleCollider(b,{offset:new z().fromArray((y=E.capsule.offset)!==null&&y!==void 0?y:[0,0,0]),radius:(w=E.capsule.radius)!==null&&w!==void 0?w:0,tail:new z().fromArray((C=E.capsule.tail)!==null&&C!==void 0?C:[0,0,0])});throw new Error(`VRMSpringBoneLoaderPlugin: The collider #${m} has no valid shape`)}),h=(s=u.colliderGroups)===null||s===void 0?void 0:s.map((p,m)=>{var g;return{colliders:((g=p.colliders)!==null&&g!==void 0?g:[]).map(y=>{const w=d==null?void 0:d[y];if(w==null)throw new Error(`VRMSpringBoneLoaderPlugin: The colliderGroup #${m} attempted to use a collider #${y} but not found`);return w}),name:p.name}});return(o=u.springs)===null||o===void 0||o.forEach((p,m)=>{var g;const v=p.joints,y=(g=p.colliderGroups)===null||g===void 0?void 0:g.map(b=>{const E=h==null?void 0:h[b];if(E==null)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${m} attempted to use a colliderGroup ${b} but not found`);return E}),w=p.center!=null?c[p.center]:void 0;let C;v.forEach(b=>{if(C){const E=C.node,x=c[E],S=b.node,M=c[S],Z={hitRadius:C.hitRadius,dragForce:C.dragForce,gravityPower:C.gravityPower,stiffness:C.stiffness,gravityDir:C.gravityDir!=null?new z().fromArray(C.gravityDir):void 0},K=this._importJoint(x,M,Z,y);w&&(K.center=w),A.addJoint(K)}C=b})}),A.setInitState(),A})}_v0Import(e){var t,r,i;return ry(this,void 0,void 0,function*(){const s=e.parser.json;if(!(((t=s.extensionsUsed)===null||t===void 0?void 0:t.indexOf("VRM"))!==-1))return null;const a=(r=s.extensions)===null||r===void 0?void 0:r.VRM,l=a==null?void 0:a.secondaryAnimation;if(!l)return null;const A=l==null?void 0:l.boneGroups;if(!A)return null;const c=new nk,u=yield e.parser.getDependencies("node"),f=(i=l.colliderGroups)===null||i===void 0?void 0:i.map(d=>{var h;const p=u[d.node];return{colliders:((h=d.colliders)!==null&&h!==void 0?h:[]).map((g,v)=>{var y,w,C;const b=new z(0,0,0);return g.offset&&b.set((y=g.offset.x)!==null&&y!==void 0?y:0,(w=g.offset.y)!==null&&w!==void 0?w:0,g.offset.z?-g.offset.z:0),this._importSphereCollider(p,{offset:b,radius:(C=g.radius)!==null&&C!==void 0?C:0})})}});return A==null||A.forEach((d,h)=>{const p=d.bones;p&&p.forEach(m=>{var g,v,y,w;const C=u[m],b=new z;d.gravityDir?b.set((g=d.gravityDir.x)!==null&&g!==void 0?g:0,(v=d.gravityDir.y)!==null&&v!==void 0?v:0,(y=d.gravityDir.z)!==null&&y!==void 0?y:0):b.set(0,-1,0);const E=d.center!=null?u[d.center]:void 0,x={hitRadius:d.hitRadius,dragForce:d.dragForce,gravityPower:d.gravityPower,stiffness:d.stiffiness,gravityDir:b},S=(w=d.colliderGroups)===null||w===void 0?void 0:w.map(M=>{const Z=f==null?void 0:f[M];if(Z==null)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${h} attempted to use a colliderGroup ${M} but not found`);return Z});C.traverse(M=>{var Z;const K=(Z=M.children[0])!==null&&Z!==void 0?Z:null,_=this._importJoint(M,K,x,S);E&&(_.center=E),c.addJoint(_)})})}),e.scene.updateMatrixWorld(),c.setInitState(),c})}_importJoint(e,t,r,i){const s=new Qfe(e,t,r,i);if(this.jointHelperRoot){const o=new Ife(s);this.jointHelperRoot.add(o),o.renderOrder=this.jointHelperRoot.renderOrder}return s}_importSphereCollider(e,t){const{offset:r,radius:i}=t,s=new yH({offset:r,radius:i}),o=new qD(s);if(e.add(o),this.colliderHelperRoot){const a=new $D(o);this.colliderHelperRoot.add(a),a.renderOrder=this.colliderHelperRoot.renderOrder}return o}_importCapsuleCollider(e,t){const{offset:r,radius:i,tail:s}=t,o=new vH({offset:r,radius:i,tail:s}),a=new qD(o);if(e.add(a),this.colliderHelperRoot){const l=new $D(a);this.colliderHelperRoot.add(l),l.renderOrder=this.colliderHelperRoot.renderOrder}return a}}Kc.EXTENSION_NAME="VRMC_springBone";class Tfe{constructor(e,t){var r,i,s,o,a,l,A,c,u,f;this.parser=e;const d=t==null?void 0:t.helperRoot,h=t==null?void 0:t.autoUpdateHumanBones;this.expressionPlugin=(r=t==null?void 0:t.expressionPlugin)!==null&&r!==void 0?r:new fb(e),this.firstPersonPlugin=(i=t==null?void 0:t.firstPersonPlugin)!==null&&i!==void 0?i:new fue(e),this.humanoidPlugin=(s=t==null?void 0:t.humanoidPlugin)!==null&&s!==void 0?s:new Bue(e,{helperRoot:d,autoUpdateHumanBones:h}),this.lookAtPlugin=(o=t==null?void 0:t.lookAtPlugin)!==null&&o!==void 0?o:new Tue(e,{helperRoot:d}),this.metaPlugin=(a=t==null?void 0:t.metaPlugin)!==null&&a!==void 0?a:new kue(e),this.mtoonMaterialPlugin=(l=t==null?void 0:t.mtoonMaterialPlugin)!==null&&l!==void 0?l:new Jd(e),this.materialsHDREmissiveMultiplierPlugin=(A=t==null?void 0:t.materialsHDREmissiveMultiplierPlugin)!==null&&A!==void 0?A:new Pm(e),this.materialsV0CompatPlugin=(c=t==null?void 0:t.materialsV0CompatPlugin)!==null&&c!==void 0?c:new que(e),this.springBonePlugin=(u=t==null?void 0:t.springBonePlugin)!==null&&u!==void 0?u:new Kc(e,{colliderHelperRoot:d,jointHelperRoot:d}),this.nodeConstraintPlugin=(f=t==null?void 0:t.nodeConstraintPlugin)!==null&&f!==void 0?f:new Xc(e,{helperRoot:d})}get name(){return"VRMLoaderPlugin"}beforeRoot(){return ny(this,void 0,void 0,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(e){return ny(this,void 0,void 0,function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)})}getMaterialType(e){const t=this.mtoonMaterialPlugin.getMaterialType(e);return t??null}extendMaterialParams(e,t){return ny(this,void 0,void 0,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,t),yield this.mtoonMaterialPlugin.extendMaterialParams(e,t)})}afterRoot(e){return ny(this,void 0,void 0,function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);const t=e.userData.vrmMeta,r=e.userData.vrmHumanoid;if(t&&r){const i=new Lue({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:r,lookAt:e.userData.vrmLookAt,meta:t,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=i}})}}function rk(n){if(Object.values(n).forEach(e=>{e!=null&&e.isTexture&&e.dispose()}),n.isShaderMaterial){const e=n.uniforms;e&&Object.values(e).forEach(t=>{const r=t.value;r!=null&&r.isTexture&&r.dispose()})}n.dispose()}function Nfe(n){const e=n.geometry;e&&e.dispose();const t=n.skeleton;t&&t.dispose();const r=n.material;r&&(Array.isArray(r)?r.forEach(i=>rk(i)):r&&rk(r))}function Dfe(n){n.traverse(Nfe)}function kfe(n){const e=new Map;n.traverse(t=>{if(t.type!=="SkinnedMesh")return;const r=t,s=r.geometry.getAttribute("skinIndex");let o=e.get(s);if(!o){const a=[],l=[],A={},c=s.array;for(let u=0;u{var r,i,s,o;if(!t.isMesh)return;const a=t,l=a.geometry,A=l.index;if(A==null)return;const c=e.get(l);if(c!=null){a.geometry=c;return}const u=new Ht;u.name=l.name,u.morphTargetsRelative=l.morphTargetsRelative,l.groups.forEach(p=>{u.addGroup(p.start,p.count,p.materialIndex)}),u.boundingBox=(i=(r=l.boundingBox)===null||r===void 0?void 0:r.clone())!==null&&i!==void 0?i:null,u.boundingSphere=(o=(s=l.boundingSphere)===null||s===void 0?void 0:s.clone())!==null&&o!==void 0?o:null,u.setDrawRange(l.drawRange.start,l.drawRange.count),u.userData=l.userData,e.set(l,u);const f=[],d=[];{const p=A.array,m=new p.constructor(p.length);let g=0;for(let v=0;v{const m=l.attributes[p];if(m.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const g=m.array,{itemSize:v,normalized:y}=m,w=new g.constructor(d.length*v);d.forEach((C,b)=>{for(let E=0;E{u.morphAttributes[p]=[];const m=l.morphAttributes[p];for(let g=0;g{for(let S=0;SE===0),u.morphAttributes[p][g]=new At(b,w,C)}}),h&&(u.morphAttributes={}),a.geometry=u}),Array.from(e.keys()).forEach(t=>{t.dispose()})}function Lfe(n){var e;((e=n.meta)===null||e===void 0?void 0:e.metaVersion)==="0"&&(n.scene.rotation.y=Math.PI)}class Xh{constructor(){}}Xh.deepDispose=Dfe;Xh.removeUnnecessaryJoints=kfe;Xh.removeUnnecessaryVertices=Vfe;Xh.rotateVRM0=Lfe;var Kn;(function(n){n[n.ARRAY_BUFFER=34962]="ARRAY_BUFFER",n[n.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",n[n.BYTE=5120]="BYTE",n[n.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",n[n.SHORT=5122]="SHORT",n[n.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",n[n.UNSIGNED_INT=5125]="UNSIGNED_INT",n[n.FLOAT=5126]="FLOAT",n[n.LINEAR=9729]="LINEAR",n[n.REPEAT=10497]="REPEAT"})(Kn||(Kn={}));const Ww="blend_",ik="vrmColliderSphere";class Pfe{parse(e,t,r,i){const s=e.humanoid,o=e.meta,a=e.materials,l={},A={},c={},u=e.lookAt,f={generator:"UniGLTF-2.0.0",version:"2.0"};if(t)if(s)if(o)if(a){if(!u)throw new Error("lookAt is undefined or null")}else throw new Error("materials is undefined or null");else throw new Error("meta is undefined or null");else throw new Error("humanoid is undefined or null");else throw new Error("avatar is undefined or null");const d=a.filter((X,ne,ae)=>ae.findIndex(Be=>Be.name===X.name.replace(" (Outline)",""))===ne).map(X=>X),h=d.map(X=>X.name),p=r?{name:"icon",imageBitmap:r.image}:null,m=d.filter(X=>X.map).map(X=>{if(!X.map)throw new Error(X.name+" map is null");return{name:X.name,imageBitmap:X.map.image}}),g=d.filter(X=>X.userData.shadeTexture).map(X=>{if(!X.userData.shadeTexture)throw new Error(X.userData.shadeTexture+" map is null");return{name:X.name+"_shade",imageBitmap:X.userData.shadeTexture.image}}),v=m.concat(g),y=Jfe(v,p),w=Hfe(y),C=zfe(y),b=Zfe(d,v),E=t.children.filter(X=>X.children.length>0&&X.children[0].type===ui.Bone)[0],x=CH(E).filter(X=>X.name!==ik),S=x.map(X=>X.name),M=x.map(X=>({children:X.children.filter(ne=>ne.name!==ik).map(ne=>S.indexOf(ne.name)),name:X.name,rotation:[X.quaternion.x,X.quaternion.y,X.quaternion.z,X.quaternion.w],scale:[X.scale.x,X.scale.y,X.scale.z],translation:[X.position.x,X.position.y,X.position.z]})),Z=[],K=t.children.filter(X=>X.type===ui.Group||X.type===ui.SkinnedMesh),_=[];K.forEach(X=>{const ne=X.type===ui.Group?X.children[0]:X,ae=ne.geometry.attributes;_.push(new $a(ae.position,Kn.FLOAT,jt.POSITION,xo.VEC3,ne.name,void 0)),_.push(new $a(ae.normal,Kn.FLOAT,jt.NORMAL,xo.VEC3,ne.name,void 0)),_.push(new $a(ae.uv,Kn.FLOAT,jt.UV,xo.VEC2,ne.name,void 0)),_.push(new $a(ae.skinWeight,Kn.FLOAT,jt.SKIN_WEIGHT,xo.VEC4,ne.name,void 0)),_.push(new $a(ae.skinIndex,Kn.UNSIGNED_SHORT,jt.SKIN_INDEX,xo.VEC4,ne.name,void 0)),(X.type===ui.Group?X.children.map(pe=>pe):[X]).forEach(pe=>{if(!pe.geometry.index)throw new Error(pe.name+" geometry.index is null");_.push(new $a(pe.geometry.index,Kn.UNSIGNED_INT,jt.INDEX,xo.SCALAR,ne.name,pe.name))}),ne.morphTargetDictionary||(ne.morphTargetDictionary={},ne.morphTargetInfluences=[],ne.geometry.morphAttributes={},ne.updateMorphTargets()),ne.geometry.userData.targetNames=[];for(const pe in e.expressionManager.expressionMap){const Fe=e.expressionManager.expressionMap[pe],rt=Fe._binds.map(ke=>({node:x.length,index:ke.index,weight:ke.weight}));let Oe=!1;for(const ke in ci)if(pe.toLowerCase()===ci[ke].toLowerCase()){l[ci[ke]]={morphTargetBinds:rt,isBinary:Fe.isBinary,overrideBlink:Fe.overrideBlink,overrideLookAt:Fe.overrideLookAt,overrideMouth:Fe.overrideMouth},Oe=!0;break}!Oe&&pe.toLowerCase()==="surprise"&&(l.surprised={morphTargetBinds:rt,isBinary:Fe.isBinary,overrideBlink:Fe.overrideBlink,overrideLookAt:Fe.overrideLookAt,overrideMouth:Fe.overrideMouth},Oe=!0),Oe===!1&&(A[pe]={morphTargetBinds:rt,isBinary:Fe.isBinary,overrideBlink:Fe.overrideBlink,overrideLookAt:Fe.overrideLookAt,overrideMouth:Fe.overrideMouth})}for(const pe in ne.morphTargetDictionary){ne.geometry.userData.targetNames.push(pe);const Fe=ne.morphTargetDictionary[pe],rt=ne.geometry.morphAttributes;_.push(new $a(rt.position[Fe],Kn.FLOAT,jt.BLEND_POSITION,xo.VEC3,ne.name,Ww+pe)),_.push(new $a(rt.normal[Fe],Kn.FLOAT,jt.BLEND_NORMAL,xo.VEC3,ne.name,Ww+pe))}}),Object.keys(l).length>0&&(c.preset=l),Object.keys(A).length>0&&(c.custom=A),K.forEach(X=>{const ne=X.type===ui.Group?X.children[0]:X,ae=new Float32Array(ne.skeleton.boneInverses.map(Be=>Be.elements).flat());_.push(new $a(new At(ae,16),Kn.FLOAT,jt.BIND_MATRIX,xo.MAT4,ne.name,ne.name))}),Z.push(..._.map(X=>({bufferView:-1,byteOffset:0,componentType:X.valueType,count:X.attribute.count,max:X.max,min:X.min,normalized:!1,type:X.accessorsType})));const B=Ofe(K,_,h);K.forEach((X,ne)=>{M.push({mesh:ne,name:X.name,rotation:[X.quaternion.x,X.quaternion.y,X.quaternion.z,X.quaternion.w],scale:[X.scale.x,X.scale.y,X.scale.z],skin:ne,translation:[X.position.x,X.position.y,X.position.z]})});const F=Gfe(K,_,S),R={offsetFromHeadBone:[0,0,0],rangeMapHorizontalInner:{inputMaxValue:u.applier.rangeMapHorizontalInner.inputMaxValue,outputScale:u.applier.rangeMapHorizontalInner.outputScale},rangeMapHorizontalOuter:{inputMaxValue:u.applier.rangeMapHorizontalOuter.inputMaxValue,outputScale:u.applier.rangeMapHorizontalOuter.outputScale},rangeMapVerticalDown:{inputMaxValue:u.applier.rangeMapVerticalDown.inputMaxValue,outputScale:u.applier.rangeMapVerticalDown.outputScale},rangeMapVerticalUp:{inputMaxValue:u.applier.rangeMapVerticalUp.inputMaxValue,outputScale:u.applier.rangeMapVerticalUp.outputScale},type:"bone"},k={humanBones:{}};for(const X in s.humanBones)k.humanBones[X]={node:S.indexOf(s.humanBones[X].node.name)};const T=o,V=[];V.push(...v.map(X=>({buffer:sk(X.imageBitmap),type:jt.IMAGE}))),V.push(..._.map(X=>({buffer:X.buffer,type:X.type}))),p&&V.push({buffer:sk(p.imageBitmap),type:jt.IMAGE});let O=0,L=0,U=0;const H=V.map((X,ne)=>{const ae={buffer:0,byteLength:X.buffer.byteLength,byteOffset:O,target:X.type===jt.IMAGE||X.type===jt.BIND_MATRIX?void 0:X.type===jt.INDEX?Kn.ELEMENT_ARRAY_BUFFER:Kn.ARRAY_BUFFER};return O+=X.buffer.byteLength,X.type===jt.IMAGE?y[L++].bufferView=ne:Z[U++].bufferView=ne,ae}),le=Yfe(t,M),N={accessors:Z,asset:f,buffers:[{byteLength:O}],bufferViews:H,extensions:{VRMC_vrm:{expressions:c,humanoid:k,lookAt:R,meta:T,specVersion:"1.0"}},extensionsUsed:["KHR_materials_unlit","KHR_texture_transform","VRMC_materials_mtoon","VRMC_vrm"],images:y,materials:b,meshes:B,nodes:M,samplers:w,avatar:0,scenes:le,skins:F,textures:C},j=new ok($E(JSON.stringify(N,void 0,2)),"JSON"),oe=new ok(wg(V.map(X=>X.buffer)),"BIN\0"),ie=wg([j.buffer,oe.buffer]),de=wg([$E("glTF"),jE(2,4),jE(ie.byteLength+12,4)]);i(wg([de,ie]))}}function CH(n){return n.children.length<=0?[n]:[n].concat(n.children.map(e=>CH(e)).flat())}function sk(n){const e=document.createElement("canvas");e.width=n.width,e.height=n.height,e.getContext("2d").drawImage(n,0,0);const t=e.toDataURL("image/png"),r=atob(t.split(",")[1]),i=new ArrayBuffer(r.length),s=new DataView(i);for(let o=0;o4?A=r[a*n.itemSize+l]:l===0?A=n.getX(a):l===1?A=n.getY(a):l===2?A=n.getZ(a):A=n.getW(a),e===Kn.UNSIGNED_SHORT?o.setUint16(i,A,!0):e===Kn.UNSIGNED_INT?o.setUint32(i,A,!0):o.setFloat32(i,A,!0),i+=t}return s}let ok=class{constructor(e,t){this.data=e,this.type=t;const r=this.data;this.buffer=wg([jE(r.byteLength,4),$E(this.type),r])}paddingBinary(e,t){const r=Math.ceil(e.byteLength/4)*4;if(e.byteLength===r)return e;const i=new Uint8Array(r);i.set(new Uint8Array(e),0);for(let s=e.byteLength;sl%3===0)),Math.max.apply(null,Array.from(this.attribute.array).filter((a,l)=>l%3===1)),Math.max.apply(null,Array.from(this.attribute.array).filter((a,l)=>l%3===2))]:void 0,this.min=r===jt.POSITION||r===jt.BLEND_POSITION?[Math.min.apply(null,Array.from(this.attribute.array).filter((a,l)=>l%3===0)),Math.min.apply(null,Array.from(this.attribute.array).filter((a,l)=>l%3===1)),Math.min.apply(null,Array.from(this.attribute.array).filter((a,l)=>l%3===2))]:void 0}};var xd;(function(n){n.MeshBasicMaterial="MeshBasicMaterial",n.MeshStandardMaterial="MeshStandardMaterial",n.MToonMaterial="MToonMaterial"})(xd||(xd={}));var xo;(function(n){n.SCALAR="SCALAR",n.VEC2="VEC2",n.VEC3="VEC3",n.VEC4="VEC4",n.MAT4="MAT4"})(xo||(xo={}));var jt;(function(n){n.POSITION="POSITION",n.NORMAL="NORMAL",n.UV="UV",n.INDEX="INDEX",n.SKIN_WEIGHT="SKIN_WEIGHT",n.SKIN_INDEX="SKIN_INDEX",n.BLEND_POSITION="BLEND_POSITION",n.BLEND_NORMAL="BLEND_NORMAL",n.BIND_MATRIX="BIND_MATRIX",n.IMAGE="IMAGE"})(jt||(jt={}));var ui;(function(n){n.Group="Group",n.SkinnedMesh="SkinnedMesh",n.Object3D="Object3D",n.Bone="Bone"})(ui||(ui={}));const Ofe=(n,e,t)=>n.map(r=>{const i=r.type===ui.Group?r.children[0]:r,s=r.type===ui.Group?r.children.map(o=>o):[r];return{name:r.name,primitives:s.map(o=>{const a=e.map(A=>A.meshName===i.name?A.type:null),l=Array.isArray(o.material)?o.material[0].name:o.material.name;return{attributes:{JOINTS_0:a.indexOf(jt.SKIN_INDEX),NORMAL:a.indexOf(jt.NORMAL),POSITION:a.indexOf(jt.POSITION),TEXCOORD_0:a.indexOf(jt.UV),WEIGHTS_0:a.indexOf(jt.SKIN_WEIGHT)},extras:{targetNames:o.geometry.userData.targetNames},indices:e.map(A=>A.type===jt.INDEX&&A.meshName===i.name?A.name:null).indexOf(o.name),material:t.indexOf(l),mode:4,targets:i.geometry.userData.targetNames?i.geometry.userData.targetNames.map(A=>({NORMAL:e.map(c=>c.type===jt.BLEND_NORMAL&&c.meshName===i.name?c.name:null).indexOf(Ww+A),POSITION:e.map(c=>c.type===jt.BLEND_POSITION&&c.meshName===i.name?c.name:null).indexOf(Ww+A)})):void 0}})}}),Gfe=(n,e,t)=>n.map(r=>{const i=r.type===ui.Group?r.children[0]:r;return{inverseBindMatrices:e.map(s=>s.type===jt.BIND_MATRIX?s.meshName:null).indexOf(i.name),joints:i.skeleton.bones.map(s=>t.indexOf(s.name)),skeleton:t.indexOf(i.skeleton.bones[0].name)}}),Zfe=(n,e)=>n.map(t=>{let r,i=null;if(t=t.userData.vrmMaterial?t.userData.vrmMaterial:t,t.type==="ShaderMaterial")i=t.userData.gltfExtensions.VRMC_materials_mtoon,i.shadeMultiplyTexture={index:e.map(c=>c.name).indexOf(t.uniforms.shadeMultiplyTexture.name)},r=t.color?[1,1,1,1]:void 0;else{const A=t;r=A.color?[A.color.r,A.color.g,A.color.b,1]:void 0}let s=-1;t.map?s=e.map(A=>A.name).indexOf(t.name):t.uniforms&&t.uniforms.map&&(s=e.map(A=>A.name).indexOf(t.uniforms.map.name));const o=s>=0?{extensions:{KHR_texture_transform:{offset:[0,0],scale:[1,1]}},index:s,texCoord:0}:void 0,a=(()=>{switch(t.type){case xd.MeshStandardMaterial:return t.metalness;case xd.MeshBasicMaterial:return 0;default:return 0}})(),l=(()=>{switch(t.type){case xd.MeshStandardMaterial:return t.roughness;case xd.MeshBasicMaterial:return .9;default:return .9}})();return{alphaCutoff:t.alphaTest>0?t.alphaTest:void 0,alphaMode:t.transparent?"BLEND":t.alphaTest>0?"MASK":"OPAQUE",doubleSided:t.side===2,extensions:t.type==="ShaderMaterial"?{KHR_materials_unlit:{},VRMC_materials_mtoon:i}:void 0,name:t.name,pbrMetallicRoughness:{baseColorFactor:r,baseColorTexture:o,metallicFactor:a,roughnessFactor:l}}}),Jfe=(n,e)=>(e?n.concat(e):n).filter(t=>t&&t.imageBitmap).map(t=>({bufferView:-1,mimeType:"image/png",name:t.name})),Hfe=n=>n.map(()=>({magFilter:Kn.LINEAR,minFilter:Kn.LINEAR,wrapS:Kn.REPEAT,wrapT:Kn.REPEAT})),zfe=n=>n.map((e,t)=>({sampler:0,source:t})),Yfe=(n,e)=>{const t=e.map(r=>r.name);return[{nodes:n.children.filter(r=>r.type===ui.Object3D||r.type===ui.SkinnedMesh||r.type===ui.Group||r.type===ui.Bone).map(r=>t.indexOf(r.name))}]},bH=0,Xfe=1,xH=2,ak=2,s1=1.25,lk=1,hB=6*4+4+4,qE=65535,Kfe=Math.pow(2,-24);class iy{constructor(){}}function fa(n,e,t){return t.min.x=e[n],t.min.y=e[n+1],t.min.z=e[n+2],t.max.x=e[n+3],t.max.y=e[n+4],t.max.z=e[n+5],t}function Ak(n){let e=-1,t=-1/0;for(let r=0;r<3;r++){const i=n[r+3]-n[r];i>t&&(t=i,e=r)}return e}function ck(n,e){e.set(n)}function uk(n,e,t){let r,i;for(let s=0;s<3;s++){const o=s+3;r=n[s],i=e[s],t[s]=ri?r:i}}function sy(n,e,t){for(let r=0;r<3;r++){const i=e[n+2*r],s=e[n+2*r+1],o=i-s,a=i+s;ot[r+3]&&(t[r+3]=a)}}function Pp(n){const e=n[3]-n[0],t=n[4]-n[1],r=n[5]-n[2];return 2*(e*t+t*r+r*e)}function jfe(n,e){if(!n.index){const t=n.attributes.position.count,r=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer;let i;t>65535?i=new Uint32Array(new r(4*t)):i=new Uint16Array(new r(2*t)),n.setIndex(new At(i,1));for(let s=0;si-s);for(let i=0;il&&(l=E),g&&wh&&(h=w);const x=n[v+2],S=n[v+3],M=x-S,Z=x+S;MA&&(A=Z),g&&xp&&(p=x);const K=n[v+4],_=n[v+5],B=K-_,F=K+_;Bc&&(c=F),g&&Km&&(m=K)}r[0]=s,r[1]=o,r[2]=a,r[3]=l,r[4]=A,r[5]=c,g&&(i[0]=u,i[1]=f,i[2]=d,i[3]=h,i[4]=p,i[5]=m)}function qfe(n,e,t,r){let i=1/0,s=1/0,o=1/0,a=-1/0,l=-1/0,A=-1/0;for(let c=e*6,u=(e+t)*6;ca&&(a=f);const d=n[c+2];dl&&(l=d);const h=n[c+4];hA&&(A=h)}r[0]=i,r[1]=s,r[2]=o,r[3]=a,r[4]=l,r[5]=A}function ede(n,e,t,r,i){let s=t,o=t+r-1;const a=i.pos,l=i.axis*2;for(;;){for(;s<=o&&e[s*6+l]=a;)o--;if(sn.candidate-e.candidate,oA=new Array(rl).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),oy=new Float32Array(6);function nde(n,e,t,r,i,s){let o=-1,a=0;if(s===bH)o=Ak(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(s===Xfe)o=Ak(n),o!==-1&&(a=rde(t,r,i,o));else if(s===xH){const l=Pp(n);let A=s1*i;const c=r*6,u=(r+i)*6;for(let f=0;f<3;f++){const d=e[f],m=(e[f+3]-d)/rl;if(i=E.candidate?sy(w,t,E.rightCacheBounds):(sy(w,t,E.leftCacheBounds),E.count++)}}for(let w=0;w=rl&&(b=rl-1);const E=oA[b];E.count++,sy(y,t,E.bounds)}const g=oA[rl-1];ck(g.bounds,g.rightCacheBounds);for(let y=rl-2;y>=0;y--){const w=oA[y],C=oA[y+1];uk(w.bounds,C.rightCacheBounds,w.rightCacheBounds)}let v=0;for(let y=0;yb&&(b=y),w>b&&(b=w);const E=(b-C)/2,x=g*2;s[d+x+0]=C+E,s[d+x+1]=E+(Math.abs(C)+E)*Kfe,Ce[g+3]&&(e[g+3]=b)}}return s}function sde(n,e){function t(g){f&&f(g/d)}function r(g,v,y,w=null,C=0){if(!h&&C>=l&&(h=!0,A&&(console.warn(`MeshBVH: Max depth of ${l} reached when generating BVH. Consider increasing maxDepth.`),console.warn(n))),y<=c||C>=l)return t(v+y),g.offset=v,g.count=y,g;const b=nde(g.boundingData,w,o,v,y,u);if(b.axis===-1)return t(v+y),g.offset=v,g.count=y,g;const E=ede(a,o,v,y,b);if(E===v||E===v+y)t(v+y),g.offset=v,g.count=y;else{g.splitAxis=b.axis;const x=new iy,S=v,M=E-v;g.left=x,x.boundingData=new Float32Array(6),o1(o,S,M,x.boundingData,s),r(x,S,M,s,C+1);const Z=new iy,K=E,_=y-M;g.right=Z,Z.boundingData=new Float32Array(6),o1(o,K,_,Z.boundingData,s),r(Z,K,_,s,C+1)}return g}jfe(n,e);const i=new Float32Array(6),s=new Float32Array(6),o=ide(n,i),a=n.index.array,l=e.maxDepth,A=e.verbose,c=e.maxLeafTris,u=e.strategy,f=e.onProgress,d=n.index.count/3;let h=!1;const p=[],m=$fe(n);if(m.length===1){const g=m[0],v=new iy;v.boundingData=i,qfe(o,g.offset,g.count,s),r(v,g.offset,g.count,s),p.push(v)}else for(let g of m){const v=new iy;v.boundingData=new Float32Array(6),o1(o,g.offset,g.count,v.boundingData,s),r(v,g.offset,g.count,s),p.push(v)}return p}function ode(n,e){const t=sde(n,e);let r,i,s;const o=[],a=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer;for(let c=0;cMath.pow(2,32))throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits.");return i[f+6]=y/4,y=A(y,g),i[f+7]=v,y}}}class kl{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let r=1/0,i=-1/0;for(let s=0,o=e.length;si?l:i}this.min=r,this.max=i}setFromPoints(e,t){let r=1/0,i=-1/0;for(let s=0,o=t.length;si?l:i}this.min=r,this.max=i}isSeparated(e){return this.min>e.max||e.min>this.max}}kl.prototype.setFromBox=function(){const n=new z;return function(t,r){const i=r.min,s=r.max;let o=1/0,a=-1/0;for(let l=0;l<=1;l++)for(let A=0;A<=1;A++)for(let c=0;c<=1;c++){n.x=i.x*l+s.x*(1-l),n.y=i.y*A+s.y*(1-A),n.z=i.z*c+s.z*(1-c);const u=t.dot(n);o=Math.min(u,o),a=Math.max(u,a)}this.min=o,this.max=a}}();const ade=function(){const n=new z,e=new z,t=new z;return function(i,s,o){const a=i.start,l=n,A=s.start,c=e;t.subVectors(a,A),n.subVectors(i.end,i.start),e.subVectors(s.end,s.start);const u=t.dot(c),f=c.dot(l),d=c.dot(c),h=t.dot(l),m=l.dot(l)*d-f*f;let g,v;m!==0?g=(u*f-h*d)/m:g=0,v=(u+g*f)/d,o.x=g,o.y=v}}(),X_=function(){const n=new We,e=new z,t=new z;return function(i,s,o,a){ade(i,s,n);let l=n.x,A=n.y;if(l>=0&&l<=1&&A>=0&&A<=1){i.at(l,o),s.at(A,a);return}else if(l>=0&&l<=1){A<0?s.at(0,a):s.at(1,a),i.closestPointToPoint(a,!0,o);return}else if(A>=0&&A<=1){l<0?i.at(0,o):i.at(1,o),s.closestPointToPoint(o,!0,a);return}else{let c;l<0?c=i.start:c=i.end;let u;A<0?u=s.start:u=s.end;const f=e,d=t;if(i.closestPointToPoint(u,!0,e),s.closestPointToPoint(c,!0,t),f.distanceToSquared(u)<=d.distanceToSquared(c)){o.copy(f),a.copy(u);return}else{o.copy(c),a.copy(d);return}}}}(),lde=function(){const n=new z,e=new z,t=new hl,r=new Il;return function(s,o){const{radius:a,center:l}=s,{a:A,b:c,c:u}=o;if(r.start=A,r.end=c,r.closestPointToPoint(l,!0,n).distanceTo(l)<=a||(r.start=A,r.end=u,r.closestPointToPoint(l,!0,n).distanceTo(l)<=a)||(r.start=c,r.end=u,r.closestPointToPoint(l,!0,n).distanceTo(l)<=a))return!0;const p=o.getPlane(t);if(Math.abs(p.distanceToPoint(l))<=a){const g=p.projectPoint(l,e);if(o.containsPoint(g))return!0}return!1}}(),Ade=1e-15;function bf(n){return Math.abs(n)new z),this.satBounds=new Array(4).fill().map(()=>new kl),this.points=[this.a,this.b,this.c],this.sphere=new Qu,this.plane=new hl,this.needsUpdate=!0}intersectsSphere(e){return lde(e,this)}update(){const e=this.a,t=this.b,r=this.c,i=this.points,s=this.satAxes,o=this.satBounds,a=s[0],l=o[0];this.getNormal(a),l.setFromPoints(a,i);const A=s[1],c=o[1];A.subVectors(e,t),c.setFromPoints(A,i);const u=s[2],f=o[2];u.subVectors(t,r),f.setFromPoints(u,i);const d=s[3],h=o[3];d.subVectors(r,e),h.setFromPoints(d,i),this.sphere.setFromPoints(this.points),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Vl.prototype.closestPointToSegment=function(){const n=new z,e=new z,t=new Il;return function(i,s=null,o=null){const{start:a,end:l}=i,A=this.points;let c,u=1/0;for(let f=0;f<3;f++){const d=(f+1)%3;t.start.copy(A[f]),t.end.copy(A[d]),X_(t,i,n,e),c=n.distanceToSquared(e),c1-1e-10){const v=this.satBounds,y=this.satAxes;t[0]=d.a,t[1]=d.b,t[2]=d.c;for(let b=0;b<4;b++){const E=v[b],x=y[b];if(r.setFromPoints(x,t),E.isSeparated(r))return!1}const w=d.satBounds,C=d.satAxes;e[0]=this.a,e[1]=this.b,e[2]=this.c;for(let b=0;b<4;b++){const E=w[b],x=C[b];if(r.setFromPoints(x,e),E.isSeparated(r))return!1}for(let b=0;b<4;b++){const E=y[b];for(let x=0;x<4;x++){const S=C[x];if(s.crossVectors(E,S),r.setFromPoints(s,e),i.setFromPoints(s,t),r.isSeparated(i))return!1}}return h&&(p||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),h.start.set(0,0,0),h.end.set(0,0,0)),!0}else{const v=this.points;let y=!1,w=0;for(let B=0;B<3;B++){const F=v[B],R=v[(B+1)%3];A.start.copy(F),A.end.copy(R),A.delta(o);const k=y?c.start:c.end,T=bf(g.distanceToPoint(F));if(bf(g.normal.dot(o))&&T){c.copy(A),w=2;break}if((g.intersectLine(A,k)||T)&&!bf(k.distanceTo(R))){if(w++,y)break;y=!0}}if(w===1&&d.containsPoint(c.end))return h&&(h.start.copy(c.end),h.end.copy(c.end)),!0;if(w!==2)return!1;const C=d.points;let b=!1,E=0;for(let B=0;B<3;B++){const F=C[B],R=C[(B+1)%3];A.start.copy(F),A.end.copy(R),A.delta(a);const k=b?u.start:u.end,T=bf(m.distanceToPoint(F));if(bf(m.normal.dot(a))&&T){u.copy(A),E=2;break}if((m.intersectLine(A,k)||T)&&!bf(k.distanceTo(R))){if(E++,b)break;b=!0}}if(E===1&&this.containsPoint(u.end))return h&&(h.start.copy(u.end),h.end.copy(u.end)),!0;if(E!==2)return!1;if(c.delta(o),u.delta(a),o.dot(a)<0){let B=u.start;u.start=u.end,u.end=B}const x=c.start.dot(o),S=c.end.dot(o),M=u.start.dot(o),Z=u.end.dot(o),K=S0?h.start.copy(c.start):h.start.copy(u.start),l.subVectors(c.end,u.end),l.dot(o)<0?h.end.copy(c.end):h.end.copy(u.end)),!0)}}}();Vl.prototype.distanceToPoint=function(){const n=new z;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}}();Vl.prototype.distanceToTriangle=function(){const n=new z,e=new z,t=["a","b","c"],r=new Il,i=new Il;return function(o,a=null,l=null){const A=a||l?r:null;if(this.intersectsTriangle(o,A))return(a||l)&&(a&&A.getCenter(a),l&&A.getCenter(l)),0;let c=1/0;for(let u=0;u<3;u++){let f;const d=t[u],h=o[d];this.closestPointToPoint(h,n),f=h.distanceToSquared(n),fnew z),this.satAxes=new Array(3).fill().map(()=>new z),this.satBounds=new Array(3).fill().map(()=>new kl),this.alignedSatBounds=new Array(3).fill().map(()=>new kl),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),r&&this.matrix.copy(r)}set(e,t,r){this.min.copy(e),this.max.copy(t),this.matrix.copy(r),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Ma.prototype.update=function(){return function(){const e=this.matrix,t=this.min,r=this.max,i=this.points;for(let A=0;A<=1;A++)for(let c=0;c<=1;c++)for(let u=0;u<=1;u++){const f=1*A|2*c|4*u,d=i[f];d.x=A?r.x:t.x,d.y=c?r.y:t.y,d.z=u?r.z:t.z,d.applyMatrix4(e)}const s=this.satBounds,o=this.satAxes,a=i[0];for(let A=0;A<3;A++){const c=o[A],u=s[A],f=1<new Il),t=new Array(12).fill().map(()=>new Il),r=new z,i=new z;return function(o,a=0,l=null,A=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(l||A)&&(o.getCenter(i),this.closestPointToPoint(i,r),o.closestPointToPoint(r,i),l&&l.copy(r),A&&A.copy(i)),0;const c=a*a,u=o.min,f=o.max,d=this.points;let h=1/0;for(let m=0;m<8;m++){const g=d[m];i.copy(g).clamp(u,f);const v=g.distanceToSquared(i);if(vt.far)?null:n}function aa(n,e,t,r){const i=n.a,s=n.b,o=n.c;let a=e,l=e+1,A=e+2;t&&(a=t.getX(e),l=t.getX(e+1),A=t.getX(e+2)),i.x=r.getX(a),i.y=r.getY(a),i.z=r.getZ(a),s.x=r.getX(l),s.y=r.getY(l),s.z=r.getZ(l),o.x=r.getX(A),o.y=r.getY(A),o.z=r.getZ(A)}function mk(n,e,t,r,i,s,o){const a=t.index,l=t.attributes.position;for(let A=n,c=e+n;A=0;let d,h;f?(d=Om(n),h=Gm(n,a)):(d=Gm(n,a),h=Om(n));const m=Gw(d,s,r,Ow)?tU(d,e,t,r):null;if(m){const y=m.point[c];if(f?y<=s[h+A]:y>=s[h+A+3])return m}const v=Gw(h,s,r,Ow)?tU(h,e,t,r):null;return m&&v?m.distance<=v.distance?m:v:m||v||null}}const gde=function(){let n,e;const t=[],r=new FH(()=>new ws);return function(...o){n=r.getPrimitive(),e=r.getPrimitive(),t.push(n,e);const a=i(...o);r.releasePrimitive(n),r.releasePrimitive(e),t.pop(),t.pop();const l=t.length;return l>0&&(e=t[l-1],n=t[l-2]),a};function i(s,o,a,l,A=null,c=0,u=0){function f(y){let w=y*2,C=ZA,b=JA;for(;!yA(w,C);)y=Om(y),w=y*2;return Hd(y,b)}function d(y){let w=y*2,C=ZA,b=JA;for(;!yA(w,C);)y=Gm(y,b),w=y*2;return Hd(y,b)+Wm(w,C)}let h=s*2,p=Kh,m=ZA,g=JA;if(yA(h,m)){const y=Hd(s,g),w=Wm(h,m);return fa(s,p,n),l(y,w,!1,u,c+s,n)}else{const y=Om(s),w=Gm(s,g);let C=y,b=w,E,x,S,M;if(A&&(S=n,M=e,fa(C,p,S),fa(b,p,M),E=A(S),x=A(M),xi.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(A),x.b.applyMatrix4(A),x.c.applyMatrix4(A),x.needsUpdate=!0;for(let S=C*3,M=(b+C)*3;Snew Vl);class Yg{static serialize(e,t={}){if(t.isBufferGeometry)return console.warn("MeshBVH.serialize: The arguments for the function have changed. See documentation for new signature."),Yg.serialize(arguments[0],{cloneBuffers:arguments[2]===void 0?!0:arguments[2]});t={cloneBuffers:!0,...t};const r=e.geometry,i=e._roots,s=r.getIndex();let o;return t.cloneBuffers?o={roots:i.map(a=>a.slice()),index:s.array.slice()}:o={roots:i,index:s.array},o}static deserialize(e,t,r={}){if(typeof r=="boolean")return console.warn("MeshBVH.deserialize: The arguments for the function have changed. See documentation for new signature."),Yg.deserialize(arguments[0],arguments[1],{setIndex:arguments[2]===void 0?!0:arguments[2]});r={setIndex:!0,...r};const{index:i,roots:s}=e,o=new Yg(t,{...r,[a1]:!0});if(o._roots=s,r.setIndex){const a=t.getIndex();if(a===null){const l=new At(e.index,1,!1);t.setIndex(l)}else a.array!==i&&(a.array.set(i),a.needsUpdate=!0)}return o}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({strategy:bH,maxDepth:40,maxLeafTris:10,verbose:!0,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,[a1]:!1},t),t.useSharedArrayBuffer&&typeof SharedArrayBuffer>"u")throw new Error("MeshBVH: SharedArrayBuffer is not available.");this._roots=null,t[a1]||(this._roots=ode(e,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new ws))),this.geometry=e}refit(e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=this.geometry,r=t.index.array,i=t.attributes.position;let s,o,a,l,A=0;const c=this._roots;for(let f=0,d=c.length;fb&&(b=K),_E&&(E=_),Bx&&(x=B)}return l[f+0]!==y||l[f+1]!==w||l[f+2]!==C||l[f+3]!==b||l[f+4]!==E||l[f+5]!==x?(l[f+0]=y,l[f+1]=w,l[f+2]=C,l[f+3]=b,l[f+4]=E,l[f+5]=x,!0):!1}else{const g=f+8,v=o[f+6],y=g+d,w=v+d;let C=h,b=!1,E=!1;e?C||(b=e.has(y),E=e.has(w),C=!b&&!E):(b=!0,E=!0);const x=C||b,S=C||E;let M=!1;x&&(M=u(g,d,C));let Z=!1;S&&(Z=u(v,d,C));const K=M||Z;if(K)for(let _=0;_<3;_++){const B=g+_,F=v+_,R=l[B],k=l[B+3],T=l[F],V=l[F+3];l[f+_]=RV?k:V}return K}}}traverse(e,t=0){const r=this._roots[t],i=new Uint32Array(r),s=new Uint16Array(r);o(0);function o(a,l=0){const A=a*2,c=s[A+15]===qE;if(c){const u=i[a+6],f=s[A+14];e(l,c,new Float32Array(r,a*4,6),u,f)}else{const u=a+hB/4,f=i[a+6],d=i[a+7];e(l,c,new Float32Array(r,a*4,6),d)||(o(u,l+1),o(f,l+1))}}}raycast(e,t=Vo){const r=this._roots,i=this.geometry,s=[],o=t.isMaterial,a=Array.isArray(t),l=i.groups,A=o?t.side:t;for(let c=0,u=r.length;c{const g=h*3;return f(d,g,g+1,g+2,p,m)}}e={boundsTraverseOrder:r,intersectsBounds:e,intersectsTriangle:t,intersectsRange:null},console.warn("MeshBVH: Shapecast function signature has changed and now takes an object of callbacks as a second argument. See docs for new signature.")}const s=Xo.getPrimitive();let{boundsTraverseOrder:o,intersectsBounds:a,intersectsRange:l,intersectsTriangle:A}=e;if(l&&A){const f=l;l=(d,h,p,m,g)=>f(d,h,p,m,g)?!0:mk(d,h,i,A,p,m,s)}else l||(A?l=(f,d,h,p)=>mk(f,d,i,A,h,p,s):l=(f,d,h)=>h);let c=!1,u=0;for(const f of this._roots){if(Cg(f),c=gde(0,i,a,l,o,u),cy(),c)break;u+=f.byteLength}return Xo.releasePrimitive(s),c}bvhcast(e,t,r){let{intersectsRanges:i,intersectsTriangles:s}=r;const o=this.geometry.index,a=this.geometry.attributes.position,l=e.geometry.index,A=e.geometry.attributes.position;xf.copy(t).invert();const c=Xo.getPrimitive(),u=Xo.getPrimitive();if(s){let d=function(h,p,m,g,v,y,w,C){for(let b=m,E=m+g;bA1.intersectsBox(d),intersectsRange:(d,h,p,m,g,v)=>(l1.copy(v),l1.applyMatrix4(xf),e.shapecast({intersectsBounds:y=>l1.intersectsBox(y),intersectsRange:(y,w,C,b,E)=>i(d,h,y,w,m,g,b,E)}))});return Xo.releasePrimitive(c),Xo.releasePrimitive(u),f}intersectsBox(e,t){return Uc.set(e.min,e.max,t),Uc.needsUpdate=!0,this.shapecast({intersectsBounds:r=>Uc.intersectsBox(r),intersectsTriangle:r=>Uc.intersectsTriangle(r)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,r={},i={},s=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Uc.set(e.boundingBox.min,e.boundingBox.max,t),Uc.needsUpdate=!0;const a=this.geometry,l=a.attributes.position,A=a.index,c=e.attributes.position,u=e.index,f=Xo.getPrimitive(),d=Xo.getPrimitive();let h=uy,p=vde,m=null,g=null;i&&(m=yde,g=Bde);let v=1/0,y=null,w=null;return xf.copy(t).invert(),Wp.matrix.copy(xf),this.shapecast({boundsTraverseOrder:C=>Uc.distanceToBox(C),intersectsBounds:(C,b,E)=>E{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:E=>Wp.distanceToBox(E),intersectsBounds:(E,x,S)=>S{for(let S=E*3,M=(E+x)*3;S(Op.copy(e).clamp(c.min,c.max),Op.distanceToSquared(e)),intersectsBounds:(c,u,f)=>f{c.closestPointToPoint(e,Op);const f=e.distanceToSquared(Op);return f{fa(0,new Float32Array(r),vk),e.union(vk)}),e}}const c1=new l0,yk=new Le,wde=In.prototype.raycast;function Cde(n,e){if(this.geometry.boundsTree){if(this.material===void 0)return;yk.copy(this.matrixWorld).invert(),c1.copy(n.ray).applyMatrix4(yk);const t=this.geometry.boundsTree;if(n.firstHitOnly===!0){const r=gk(t.raycastFirst(c1,this.material),this,n);r&&e.push(r)}else{const r=t.raycast(c1,this.material);for(let i=0,s=r.length;i{const e=n.attributes.position,t=n.index,r=new ns,i=new z,s=new z,o=new z,a=[];for(let l=0;l{const e=n.geometry.clone();let t=[];if(Array.isArray(n.material))for(let i=0;i{n.isMesh&&(n.geometry.userData.faceNormals=null,n.geometry.dispose(),n.geometry.disposeBoundsTree(),n.parent&&n.parent.remove(n),n.userData.cancelMesh&&gB(n.userData.cancelMesh))},EH=n=>{var e,t;n.userData.cullingClone&&(gB(n.userData.cullingClone),n.userData.cullingClone=null,gB(n.userData.cullingCloneP),n.userData.cullingCloneP=null,gB(n.userData.cullingCloneN),n.userData.cullingCloneN=null,((e=n.userData)==null?void 0:e.clippedIndexGeometry)!=null&&(n.userData.clippedIndexGeometry=null),((t=n.userData)==null?void 0:t.origIndexBuffer)!=null&&(n.userData.origIndexBuffer=null))},Qde=async n=>{if(n==null){console.warn("Null parameter for meshes was provided. Skipping mesh culling.");return}if(!Array.isArray(n)){console.warn("No valid mesh array was provided. Skipping mesh culling.");return}if(n.length==0){console.warn("No mesh array with elements was provided. Skipping mesh culling.");return}const e=[];bg=n[0].parent,bg.lines!=null&&(bg.lines.forEach(i=>{i.visible=!1}),bg.lines.length=0),n.forEach(i=>{if(i.userData.cullLayer!=null){i.userData.origIndexBuffer==null&&(i.userData.origIndexBuffer=i.geometry.index.clone()),e[i.userData.cullLayer]==null&&(e[i.userData.cullLayer]={origMeshes:[],cloneMeshes:[],posMeshes:[],negMeshes:[],scaleMeshes:[],positionMeshes:[]}),i.userData.cullingClone==null&&(i.userData.cullingClone=_de(i),i.userData.cullingCloneP=i.userData.cullingClone.clone(),i.userData.cullingCloneN=i.userData.cullingClone.clone());const s=i.userData.cullingClone,o=i.userData.cullingCloneP,a=i.userData.cullingCloneN;o.material=Ede,a.userData.cancelMesh=o,a.material=Ude,o.userData.maxCullDistance=a.userData.maxCullDistance=i.userData.maxCullDistance,e[i.userData.cullLayer].origMeshes.push(i),e[i.userData.cullLayer].cloneMeshes.push(s),e[i.userData.cullLayer].posMeshes.push(o),e[i.userData.cullLayer].negMeshes.push(a),i.geometry.setIndex(i.userData.origIndexBuffer)}});for(let i=e.length-1;i>=0;i--)e[i]==null&&e.splice(i,1);let t=[];const r=[];for(let i=e.length-1;i>=0;i--){if(t.length!=0||e.length>=1)for(let s=0;s{i.geom.setIndex(i.index)})},Rde=n=>{let e=Ide,t=Fde;return n&&(isNaN(n)?Array.isArray(n)&&(isNaN(n[0])||(e=n[0]),isNaN(n[1])||(t=n[1])):e=n),[e,t]},Mde=(n,e,t,r,i,s,o=!1)=>{const a=[],l=Rde(s);let A=l[0],c=l[1];fy.far=A+c;for(let f=0;f=0;v--)A-g[v].distance>=g[v].object.userData.maxCullDistance&&g.splice(v,1);if(g.length===0){for(let v=0;v<3;v++)a.push(n[d+v]);break}else{const v=g.map(y=>y.object);for(let y=0;yy).length===0){for(let y=0;y<3;y++)a.push(n[d+y]);break}if(p===0)h=g.map(y=>y.object);else if(h=g.map(y=>{if(h.indexOf(y.object)!==-1)return y.object}),h=h.filter(y=>y),p===2&&h.filter(y=>y).length===0)for(let y=0;y<3;y++)a.push(n[d+y]);o&&Tde(u1,Gp.clone().multiplyScalar(-1),fy.far,16711680,bg)}}}const u=new Uint32Array(a);return new At(u,1,!1)};function Tde(n,e,t,r,i){i.lines==null&&(i.lines=[]);let s=new z;s.addVectors(n,e.clone().multiplyScalar(t));const o=[];o.push(n),o.push(s);const a=new Ht().setFromPoints(o),l=[];l.push(new Re(0)),l.push(new Re(16777215));let A=new Wl({color:r});var c=new kh(a,A);c.renderOrder=100,i.add(c),i.lines.push(c)}function UH(n){let e,t,r,i=0;for(let a=0;atypeof window>"u"?await Lde({meshes:e,atlasSize:t,mtoon:r,transparentMaterial:i,transparentTexture:s}):await Pde({backColor:n,meshes:e,atlasSize:t,mtoon:r,transparentMaterial:i,transparentTexture:s,twoSidedMaterial:o}),Lde=async({meshes:n,atlasSize:e,mtoon:t,transparentMaterial:r,transparentTexture:i})=>{const s=e,o=["diffuse"],a=[];n.forEach(E=>{const x=E.material;let S=a.find(M=>M.material===x);if(!S)a.push({material:x,mesh:E});else{const{dest:M}=K_({meshes:[S.mesh,E]});S.mesh.geometry=M}});const l=Object.fromEntries(o.map(E=>[E,SH({width:s,height:s,transparent:i})])),A=Math.floor(Math.sqrt(n.length)+1),c=s/A,u=new Map(a.map((E,x)=>{const S=new We(x%A,Math.floor(x/A)).multiplyScalar(1/A),M=new We(S.x+1/A,S.y+1/A);return[E.mesh,{min:S,max:M}]})),f={diffuse:["map"],normal:["normalMap"],orm:["ormMap","aoMap","roughnessMap","metalnessMap"]},d=[],h=[];a.forEach(E=>{const{min:x,max:S}=u.get(E.mesh);h.push(S),d.push(x)});const p=new We(Math.max(...h.map(E=>E.x)),Math.max(...h.map(E=>E.y))),m=new We(Math.min(...d.map(E=>E.x)),Math.min(...d.map(E=>E.y))),g=1/(p.x-m.x),v=1/(p.y-m.y),y=c*g,w=c*v,C=new Map(a.map(E=>{let{min:x,max:S}=u.get(E.mesh);return x.x=x.x*g,x.y=x.y*v,S.x=S.x*g,S.y=S.y*v,[E.mesh,{min:x,max:S}]}));a.forEach(E=>{const{material:x,mesh:S}=E,{min:M,max:Z}=C.get(S);o.forEach(F=>{const R=l[F];R.globalCompositeOperation="source-over";let k=rU(x,f[F].find(T=>rU(x,T)));if(k!==""&&k!==void 0)try{const T=new Uint8ClampedArray(k.data),V=new ImageData(T,y,w),O=document.createElement("canvas");O.width=y,O.height=w;const L=O.getContext("2d");L.putImageData(V,0,0),L.save(),R.drawImage(O,M.x*s,M.y*s,y,w)}catch(T){console.error("error",T)}else R.fillStyle=F==="diffuse"?`#${x.color.clone().getHexString()}`:F==="normal"?"#8080ff":F==="orm"?`#${new Re(x.aoMapIntensity,x.roughness,x.metalness).getHexString()}`:"#7F7F7F",R.fillRect(M.x*s,M.y*s,y,w)});const K=S.geometry,_=K.attributes.uv;if(_)for(let F=0;F<_.array.length;F+=2)_.array[F]=_A(_.array[F],0,1,M.x,Z.x),_.array[F+1]=_A(_.array[F+1],0,1,M.y,Z.y);const B=K.attributes.uv2;if(B)for(let F=0;F{const x=new ir(l[E].canvas);return x.flipY=!1,[E,x]})));return{bakeObjects:a,textures:b,uvs:C}},Pde=async({backColor:n,meshes:e,atlasSize:t,mtoon:r,transparentMaterial:i,transparentTexture:s,twoSidedMaterial:o})=>{Nde();const a=t,l=r?["diffuse"]:["diffuse","orm"],A=[];let c=null;e.forEach(_=>{_=_.clone();const B=_.material.length==null?_.material:_.material[0];r&&c==null&&B.type=="ShaderMaterial"&&(c=B.clone());let F=A.find(R=>{R.material});if(!F)A.push({material:B,mesh:_});else{const{dest:R}=K_({meshes:[F.mesh,_]});F.mesh.geometry=R}});const u=Object.fromEntries(l.map(_=>[_,SH({width:a,height:a,transparent:s})])),f=Math.floor(Math.sqrt(e.length)+1),d=a/f,h=new Map(A.map((_,B)=>{const F=new We(B%f,Math.floor(B/f)).multiplyScalar(1/f),R=new We(F.x+1/f,F.y+1/f);return[_.mesh,{min:F,max:R}]})),p={diffuse:["map"],normal:["normalMap"],orm:["ormMap","aoMap","roughnessMap","metalnessMap"]},m=[],g=[];A.forEach(_=>{const{min:B,max:F}=h.get(_.mesh);g.push(F),m.push(B)});const v=new We(Math.max(...g.map(_=>_.x)),Math.max(...g.map(_=>_.y))),y=new We(Math.min(...m.map(_=>_.x)),Math.min(...m.map(_=>_.y))),w=1/(v.x-y.x),C=1/(v.y-y.y),b=d*w,E=d*C,x=new Map(A.map(_=>{let{min:B,max:F}=h.get(_.mesh);return B.x=B.x*w,B.y=B.y*C,F.x=F.x*w,F.y=F.y*C,[_.mesh,{min:B,max:F}]}));A.forEach(_=>{const{material:B,mesh:F}=_,{min:R,max:k}=x.get(F);l.forEach(L=>{var oe;const U=u[L];U.globalCompositeOperation="source-over";let H,le=new Re(1,1,1);switch(L){case"diffuse":H=B.color||n,(oe=B.uniforms)!=null&&oe.litFactor?le=B.uniforms.litFactor.value:le=B.color;break;case"normal":H=new Re(8421631);break;case"orm":H=new Re(B.aoMapIntensity,B.roughness,B.metalness);break;default:H=new Re(1,1,1);break}let N=kde(B,p[L].find(ie=>rU(B,ie)));const j=Dde(N,le,H,a,a,s);createImageBitmap(j).then(ie=>U.drawImage(ie,R.x*a,R.y*a,b,E))});const T=F.geometry.clone();F.geometry=T;const V=T.attributes.uv.clone();if(T.attributes.uv=V,V)for(let L=0;L{const B=new ir(u[_].canvas);return B.flipY=!1,[_,B]}))),M=o?pi:Vo;let Z;const K=i?"transparent":"opaque";return r?(Z=new mu({map:S.diffuse,transparent:i,side:M}),c==null&&(c=new dB),c.side=M,c.uniforms.map=S.diffuse,c.uniforms.shadeMultiplyTexture=S.diffuse,c.transparent=i,s&&!i&&(Z.alphaTest=.5,c.alphaTest=.5),Z.userData.vrmMaterial=c,Z.userData.shadeTexture=S.uniformColor,Z.name="mToon_"+K,Z.map.name=Z.name):(Z=new mu({map:S.diffuse,roughnessMap:S.orm,metalnessMap:S.orm,normalMap:S.normal,transparent:i,side:M}),s&&!i&&(Z.alphaTest=.5),Z.name="standard_"+K,Z.roughnessMap!=null&&(Z.roughnessMap.name=Z.name+"_orm"),Z.normalMap!=null&&(Z.normalMap.name=Z.name+"_normal")),{bakeObjects:A,material:Z}};function _H(n){const e=new Map;for(const r of n.skeleton.bones){const i=r.clone(!1);e.set(r,i)}n.skeleton.bones[0].traverse(r=>{if(r.type!=="Bone")return;const i=e.get(r);for(const s of r.children){const o=e.get(s);o&&i.add(o)}});const t=new hc(n.skeleton.bones.map(r=>e.get(r)));return t.boneInverses=n.skeleton.boneInverses,t.pose(),t}function QH(n,e){const t=new Map;new z(-1,1,-1),new Le,new z;let r=0;n.forEach(l=>{if(l.skeleton){var A=_H(l);const c=A.bones;A.bones.forEach((u,f)=>{var d;if(c.indexOf(u)!==-1){const h=t.get(u.name);if(h==null){const p={index:r,boneInverses:A.boneInverses[f],bone:u.clone(!1),parentName:((d=u.parent)==null?void 0:d.type)=="Bone"?u.parent.name:null};r++,t.set(u.name,p)}else u.userData.VRMcolliders!=null&&(h.bone.userData.VRMcolliders==null?h.bone.userData.VRMcolliders=u.userData.VRMcolliders:h.bone.userData.VRMcolliders=[...h.bone.userData.VRMcolliders,...u.userData.VRMcolliders])}})}});const i=[],s=[];[...t.values()].forEach(l=>{var A;if(i.push(l.bone),s.push(l.boneInverses),l.parentName!=null){const c=(A=t.get(l.parentName))==null?void 0:A.bone;c&&c.add(l.bone)}});const a=new hc(i,s);return a.bones.forEach(l=>{var c;const A=(c=l.userData)==null?void 0:c.vrm0RestPosition;A&&l.position.set(-A.x,A.y,-A.z),l.position.set(l.position.x*e,l.position.y*e,l.position.z*e)}),a}function Wde(n,e){if(!e.skeleton)return;const t=new Map;if(e.skeleton){e.skeleton.bones.forEach((o,a)=>{const l=n.bones.filter(c=>c.name===o.name),A=l.length>0?n.bones.indexOf(l[0]):-1;t.set(a,A)});const r=[],i=e.geometry.attributes.skinIndex.array;for(let o=0;oe.indexOf(t)===r)}function Ode(n){const t=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array].filter(r=>n.constructor===r);return t.length&&t[0]||null}function Zw(n,e){const t=[];for(let s=0;ss.name===r.name);return i?t.bones.indexOf(i):-1}async function Jde(n,e){const{scale:t,isVrm0:r}=e,i=[],s=[];Ih(n,"SkinnedMesh").forEach(A=>{const c=A.clone();i.push(c),Array.isArray(A.material)?s.push(...A.material):s.push(A.material)});const a=QH(i,t),l=new kt;return l.name="AvatarRoot",i.forEach(A=>{var b;const c=new Ht,u={};for(const E in A.geometry.attributes){const x=A.geometry.attributes[E];u[E]=x.clone()}if((b=A.userData)!=null&&b.isVRM0)for(let E=0;E[E,E.geometry.morphAttributes])),h=new Map([A].map(E=>[E,E.morphTargetDictionary||{}]));if(f.morphAttributes=MH({meshes:[A],sourceMorphAttributes:d,sourceMorphTargetDictionaries:h,destMorphTargetDictionary:f.morphTargetDictionary,scale:t},r),r)for(let E=0;Ed.name===e.userData.boneName),s=e.userData.globalPosition,o=e.userData.globalScale||new z(1,1,1),a=e.userData.globalRotationMatrix;t.add(r.bones[0]);const l=[],A=[],c=t.geometry.attributes.position.array,u=new z,f=e.userData.isVRM0?-1:1;for(let d=0;d0){const{bakeObjects:M,material:Z}=await Vde({transparentColor:t,atlasSize:x.size,meshes:S,mtoon:x.isMtoon,transparentMaterial:x.transparentMaterial,transparentTexture:y,twoSidedMaterial:u}),K=M.map(T=>T.mesh),_=[];K.forEach(T=>{T.type=="Mesh"&&(T=zde(C,T)),_.push(T);const V=T.geometry,O=V.index.array,L=RH(T.geometry.index.array),U=[];for(let N=0;N{const o=n.find(l=>e.get(l).hasOwnProperty(i)),a=o.morphTargetDictionary[i];r[s]=o.morphTargetInfluences[a]}),r}function Kde({sourceAttributes:n}){const e=new Set,t=Array.from(n.values());t.forEach(i=>{Object.keys(i).forEach(s=>e.add(s))});const r={};return Array.from(e.keys()).map(i=>{r[i]=UH(t.map(s=>s[i]).flat().filter(s=>s!==void 0))}),r}function jde({sourceMorphTargetDictionaries:n}){const e=new Set;Array.from(n.values()).forEach(i=>{Object.keys(i).forEach(s=>e.add(s))});const r={};return Array.from(e.keys()).map((i,s)=>{r[i]=s}),r}function MH({meshes:n,sourceMorphTargetDictionaries:e,sourceMorphAttributes:t,destMorphTargetDictionary:r,scale:i},s=!1){const o=new Set;Array.from(t.values()).forEach(u=>{Object.keys(u).forEach(f=>o.add(f))});const l=Array.from(o),A={};l.forEach(u=>{A[u]=[],Object.entries(r).forEach(([f,d])=>{A[u][d]=[],n.forEach(h=>{let p;const m=e.get(h);if(m.hasOwnProperty(f)&&h.geometry.morphAttributes[u]){const g=m[f];p=h.geometry.morphAttributes[u][g]}else{const g=h.geometry.attributes[u],v=new g.array.constructor(new Array(g.array.length).fill(0));p=new At(v,g.itemSize,g.normalized)}A[u][d].push(p)})})});const c={};return l.forEach(u=>{c[u]=[];for(let f=0;f{const i=r.geometry.index;for(var s=0;s{var l;if(r+=a.geometry.attributes.uv.count,(l=a.userData)!=null&&l.isVRM0)for(let A=0;A[a,a.geometry.attributes])),morphAttributes:new Map(n.map(a=>[a,a.geometry.morphAttributes])),morphTargetDictionaries:new Map(n.map(a=>[a,a.morphTargetDictionary||{}])),morphTargetInfluences:new Map(n.map(a=>[a,a.morphTargetInfluences||[]]))},s={attributes:null,morphTargetDictionary:null,morphAttributes:null,morphTargetInfluences:null,index:null,animations:{}};s.attributes=Kde({sourceAttributes:i.attributes});const o=jde({sourceMorphTargetDictionaries:i.morphTargetDictionaries});return s.morphTargetDictionary=o,s.morphAttributes=MH({meshes:n,sourceMorphAttributes:i.morphAttributes,sourceMorphTargetDictionaries:i.morphTargetDictionaries,destMorphTargetDictionary:o,scale:e},t),s.morphTargetInfluences=Xde({meshes:n,sourceMorphTargetDictionaries:i.morphTargetDictionaries,destMorphTargetDictionary:o}),s.index=$de({meshes:n}),s.animations={},{source:i,dest:s}}function Yt(n){return n==null?[]:Array.isArray(n)?n:[n]}async function qde(n,e){const r=await new Nu().load(e);r.encoding=ht,r.flipY=!1,n.traverse(i=>{if(i instanceof In){const s=Array.isArray(i.material)?i.material:[i.material];for(let o=0;o{const e=[];for(const t in n){const r=n[t].vrm;if(r){const i=r.data.cullingLayer;i>=0&&r.data.cullingMeshes.map(s=>{s.userData.cullLayer=i,s.userData.cullDistance=r.data.cullingDistance,s.userData.maxCullDistance=r.data.maxCullingDistance,e.push(s)})}}Qde(e)};function nhe(n){const e=[],t=[],r=[],i=[];let s=!1;return n.forEach(o=>{var A;const l=Yt(o.material)[0];l.type=="ShaderMaterial"?l.transparent==!0?(i.push(o),s=!0):(r.push(o),((A=l.uniforms.alphaTest)==null?void 0:A.value)!=0&&(s=!0)):l.transparent==!0?(t.push(o),s=!0):(e.push(o),l.alphaTest!=0&&(s=!0))}),{stdMesh:e,stdTranspMesh:t,mToonMesh:r,mToonTranspMesh:i,requiresTransparency:s}}function rhe(n){const e=[],t=[],r=[],i=[],s=[],o=[];return n.forEach(a=>{Yt(a.material).forEach(A=>{A.type=="ShaderMaterial"?A.transparent==!0?o.push(A):A.uniforms.alphaTest.value!=0?s.push(A):i.push(A):A.transparent==!0?r.push(A):A.alphaTest!=0?t.push(A):e.push(A)})}),{stdMats:e,stdCutoutpMats:t,stdTranspMats:r,mToonMats:i,mToonCutoutMats:s,mToonTranspMats:o}}function wk(n,e){n.data==null?n.data=e:n.data={...n.data,...e}}function ihe(n,e){if(n.data!=null)return n.data[e]}function she(n){const e=ihe(n,"cullingMeshes");e&&(e.forEach(t=>{EH(t)}),n.data.cullingMeshes=null)}function Cn(n){switch(n){case 1:return 128;case 2:return 256;case 3:return 512;case 4:return 1024;case 5:return 2048;case 6:return 4096;case 7:return 8192;case 8:return 16384;default:return 4096}}function ohe(n){const e=n.scene;she(n),e.traverse(t=>{t.material&&iU(t.material),t.geometry&&(EH(t),t.geometry.dispose(),t.geometry.disposeBoundsTree())}),e.parent&&e.parent.remove(e),Xh.deepDispose(e),n.expressionManager&&n.expressionManager.expressions.forEach(t=>{t._binds&&t._binds.forEach(r=>{r.primitives&&r.primitives.forEach(i=>{i.geometry.dispose(),i.material&&iU(i.material)})})});for(const t in n)n[t]=null}const iU=n=>{var e,t,r,i,s,o;if(n.length)for(let a=0;a{const t=new Blob([n],{type:"text/plain"}),r=document.createElement("a");r.href=window.URL.createObjectURL(t),r.download=e+".txt",document.body.appendChild(r),r.click(),document.body.removeChild(r)},TH=n=>{let e,t,r=0;return Array.isArray(n)?(e=n[0]||0,t=n[1]||0,r=n[2]||0):(typeof n=="string"||n instanceof String)&&n.split("-").forEach(s=>{switch(s=s.toLowerCase(),s){case"left":e=-1;break;case"right":e=1;break;case"bottom":case"down":t=-1;break;case"top":case"up":t=1;break;case"back":case"backward":r=-1;break;case"front":case"forward":r=1;break;default:console.warn("unkown cameraPosition name: "+s+" in: "+n+". Please use left, right, bottom, top, back or front");break}}),new z(e,t,r)},lhe=n=>{var t,r,i,s,o,a,l,A,c,u,f;const e=n.humanoid.humanBones;e.upperChest==null&&e.neck.node.parent!=e.chest&&(e.neck.node.parent!=e.chest.node?e.upperChest={node:e.neck.node.parent}:e.upperChest!=null&&(e.upperChest={node:e.neck.node.parent},e.chest={node:e.neck.node.parent.parent})),e.leftShoulder==null&&(e.leftUpperArm.node.parent!=((t=e.chest)==null?void 0:t.node)&&e.leftUpperArm.node.parent!=((r=e.upperChest)==null?void 0:r.node)&&e.leftUpperArm.node.parent!=((i=e.spine)==null?void 0:i.node)&&e.leftUpperArm.node.parent!=((s=e.neck)==null?void 0:s.node)&&e.leftUpperArm.node.parent!=((o=e.head)==null?void 0:o.node),e.leftShoulder={node:e.leftUpperArm.node.parent}),e.rightShoulder==null&&(e.rightUpperArm.node.parent!=((a=e.chest)==null?void 0:a.node)&&e.rightUpperArm.node.parent!=((l=e.upperChest)==null?void 0:l.node)&&e.rightUpperArm.node.parent!=((A=e.spine)==null?void 0:A.node)&&e.rightUpperArm.node.parent!=((c=e.neck)==null?void 0:c.node)&&e.rightUpperArm.node.parent!=((u=e.head)==null?void 0:u.node),e.rightShoulder={node:e.rightUpperArm.node.parent});for(let d in Lm)d=d.charAt(0).toLowerCase()+d.slice(1),(f=e[d])!=null&&f.node&&(e[d].node.name=d)};function NH({candidates:n,predicate:e}){if(!n.length)return null;const t=n.shift();return e(t)?t:(n=n.concat(t.children),NH({candidates:n,predicate:e}))}function DH(n,e){return NH({candidates:[n],predicate:t=>t.name===e})}function kH({candidates:n,predicate:e,results:t=[]}){if(!n.length)return t;const r=n.shift();return e(r)&&t.push(r),n=n.concat(r.children),kH({candidates:n,predicate:e,results:t})}function Ih(n,e){return kH({candidates:[n],predicate:t=>Yt(e).includes(t.type)})}function Ahe(n,e,t){const r=Ih(n,"SkinnedMesh");return{humanBones:uhe(r[0]),materials:n.userData.atlasMaterial,meta:che(e,t)}}function che(n,e){return e=e||{},{...{authors:["CharacterStudio"],metaVersion:"1",version:"v1",name:n,licenseUrl:"https://vrm.dev/licenses/1.0/",commercialUssageName:"personalNonProfit",contactInformation:"https://m3org.com/",allowExcessivelyViolentUsage:!1,allowExcessivelySexualUsage:!1,allowPoliticalOrReligiousUsage:!1,allowAntisocialOrHateUsage:!1,creditNotation:"required",allowRedistribution:!1,modification:"prohibited"},...e}}function uhe(n){const e={};return n.skeleton.bones.map(t=>{for(const r in Lm)if(Lm[r]===t.name){e[t.name]={node:t};break}}),e}const fhe={mixamorigHips:"hips",mixamorigSpine:"spine",mixamorigSpine1:"chest",mixamorigSpine2:"upperChest",mixamorigNeck:"neck",mixamorigHead:"head",mixamorigLeftShoulder:"leftShoulder",mixamorigLeftArm:"leftUpperArm",mixamorigLeftForeArm:"leftLowerArm",mixamorigLeftHand:"leftHand",mixamorigLeftHandThumb1:"leftThumbMetacarpal",mixamorigLeftHandThumb2:"leftThumbProximal",mixamorigLeftHandThumb3:"leftThumbDistal",mixamorigLeftHandIndex1:"leftIndexProximal",mixamorigLeftHandIndex2:"leftIndexIntermediate",mixamorigLeftHandIndex3:"leftIndexDistal",mixamorigLeftHandMiddle1:"leftMiddleProximal",mixamorigLeftHandMiddle2:"leftMiddleIntermediate",mixamorigLeftHandMiddle3:"leftMiddleDistal",mixamorigLeftHandRing1:"leftRingProximal",mixamorigLeftHandRing2:"leftRingIntermediate",mixamorigLeftHandRing3:"leftRingDistal",mixamorigLeftHandPinky1:"leftLittleProximal",mixamorigLeftHandPinky2:"leftLittleIntermediate",mixamorigLeftHandPinky3:"leftLittleDistal",mixamorigRightShoulder:"rightShoulder",mixamorigRightArm:"rightUpperArm",mixamorigRightForeArm:"rightLowerArm",mixamorigRightHand:"rightHand",mixamorigRightHandPinky1:"rightLittleProximal",mixamorigRightHandPinky2:"rightLittleIntermediate",mixamorigRightHandPinky3:"rightLittleDistal",mixamorigRightHandRing1:"rightRingProximal",mixamorigRightHandRing2:"rightRingIntermediate",mixamorigRightHandRing3:"rightRingDistal",mixamorigRightHandMiddle1:"rightMiddleProximal",mixamorigRightHandMiddle2:"rightMiddleIntermediate",mixamorigRightHandMiddle3:"rightMiddleDistal",mixamorigRightHandIndex1:"rightIndexProximal",mixamorigRightHandIndex2:"rightIndexIntermediate",mixamorigRightHandIndex3:"rightIndexDistal",mixamorigRightHandThumb1:"rightThumbMetacarpal",mixamorigRightHandThumb2:"rightThumbProximal",mixamorigRightHandThumb3:"rightThumbDistal",mixamorigLeftUpLeg:"leftUpperLeg",mixamorigLeftLeg:"leftLowerLeg",mixamorigLeftFoot:"leftFoot",mixamorigLeftToeBase:"leftToes",mixamorigRightUpLeg:"rightUpperLeg",mixamorigRightLeg:"rightLowerLeg",mixamorigRightFoot:"rightFoot",mixamorigRightToeBase:"rightToes"};function VH(n,e,t){var p;const r=vu.findByName(n,"mixamo.com");if(r==null)return null;const i=[],s=new tt,o=new tt,a=new tt,l=new z,A=e.getObjectByName("mixamorigHips").position.y,c=(p=t.humanoid)==null?void 0:p.getNormalizedBoneNode("hips").getWorldPosition(l).y,u=t.scene.getWorldPosition(l).y,d=Math.abs(c-u)/A;return r.tracks.forEach(m=>{const g=m.clone(),v=g.name.split("."),y=v[0],C=fhe[y],b=e.getObjectByName(y);if(C!=null){const E=v[1];if(b.getWorldQuaternion(s).invert(),b.parent.getWorldQuaternion(o),g instanceof Qa){for(let x=0;x{g.values[Z+x]=M})}i.push(new Qa(`${C}.${E}`,g.times,g.values.map((x,S)=>{var M;return((M=t.meta)==null?void 0:M.metaVersion)==="0"&&S%2===0?-x:x})))}else if(g instanceof ec){const x=g.values.map((S,M)=>{var Z;return(((Z=t.meta)==null?void 0:Z.metaVersion)==="0"&&M%3!==1?-S:S)*d});i.push(new ec(`${C}.${E}`,g.times,x))}}}),new vu("vrmAnimation",r.duration,i)}const dhe=new Ese,hhe=new x_,h1=.2,phe=n=>Math.floor(Math.random()*n);class Ck{constructor(e,t,r,i,s,o,a){var l,A,c,u;this.mixer=new wie(t),this.actions=[],this.to=null,this.from=null,this.vrm=r,this.animationManager=e,this.mixamoModel=null,this.fadeOutActions=null,this.newAnimationWeight=1,this.neckBone=(A=(l=r==null?void 0:r.humanoid)==null?void 0:l.humanBones)==null?void 0:A.neck,this.spineBone=(u=(c=r==null?void 0:r.humanoid)==null?void 0:c.humanBones)==null?void 0:u.spine,this.timeScale=1,i&&(this.setAnimations(i,null,null,a),this.to=this.actions[s],o!=-1&&(this.from=this.actions[o],this.from.reset(),this.from.time=e.getFromActionTime(),this.from.play(),this.to.weight=e.getWeightIn(),this.from.weight=e.getWeightOut()),this.actions[s].reset(),this.actions[s].time=e.getToActionTime(),this.actions[s].play())}setTimeScale(e){this.timeScale=e,this.actions.forEach(t=>{t.timeScale=e})}setMouseLookEnabled(e){this.setAnimations(this.animations,this.mixamoModel,e)}setAnimations(e,t=null,r=null,i=!1){if(r=r??this.animationManager.mouseLookEnabled,this.animations=e,t!=null){if(this.vrm!=null){const s=VH(e,t,this.vrm);s&&(e=[s],this.mixamoModel=t)}}else{const s=[];e.forEach(o=>{s.push(o.clone())}),e=s}if(r&&e[0].tracks.map((s,o)=>{(s.name==="neck.quaternion"||s.name==="spine.quaternion")&&e[0].tracks.splice(o,1)}),i){this.actions.forEach(s=>{s.weight=0,s.stop()}),this.actions=[],this.newAnimationWeight=1;for(let s=0;s{r.weight=1-this.newAnimationWeight}),this.newAnimationWeight>=1&&(this.newAnimationWeight=1,this.fadeOutActions.forEach(r=>{r.weight=0,r.stop()}),this.fadeOutActions=null),this.actions.forEach(r=>{r.weight=this.newAnimationWeight})),this.from!=null&&(this.from.weight=t),this.to!=null&&(this.to.weight=e),this.mixer.update(1/30)}reset(){this.mixer.setTime(0),this.to.paused=!0}resume(){this.to.paused=!1}setTime(e){this.mixer.setTime(e)}dispose(){this.animationManager.disposeAnimation(this)}}class ghe{constructor(){this.animationPaths=null,this.lastAnimID=null,this.mainControl=null,this.animationControl=null,this.animations=null,this.paused=!1,this.scale=1,this.curLoadAnim=0,this.currentAnimationName="",this.weightIn=NaN,this.weightOut=NaN,this.lastAnimID=-1,this.curAnimID=0,this.animationControls=[],this.started=!1,this.mouseLookEnabled=!1,this.mixamoModel=null,this.mixamoAnimations=null,this.currentClip=null,setInterval(()=>{this.update()},1e3/30)}enableMouseLook(e){this.mouseLookEnabled=e,this.animationControls.forEach(t=>{t.setMouseLookEnabled(e)})}setScale(e){this.scale=e}async loadAnimation(e,t,r=0,i=!0,s="",o=""){const a=s+(s!=""?"/":"")+Yt(e)[0];o=o==""?rc(a):o,this.currentAnimationName=o;const A=await(i?dhe:hhe).loadAsync(a);A.scale.set(this.scale,this.scale,this.scale),this._scaleOffsetHips(A.animations);const c=vu.findByName(A.animations,"mixamo.com");c!=null?(this.mixamoModel=A.clone(),this.mixamoAnimations=A.animations,this.currentClip=c):(this.mixamoModel=null,this.animations=A.animations,this.currentClip=A.animations[0]),this.mainControl==null&&(this.curAnimID=0,this.lastAnimID=-1,this.mainControl=new Ck(this,A,null,A.animations,this.curAnimID,this.lastAnimID,t),this.animationControls.push(this.mainControl)),this.animationControls.forEach(u=>{u.setAnimations(A.animations,this.mixamoModel,this.mouseLookEnabled,t)}),this.setTime(r),t?this.pause():this.play()}getCurrentClip(){return this.currentClip}getCurrentAnimationName(){return this.currentAnimationName}clearCurrentAnimations(){this.animationPaths=null,this.animationControls=[],this.mainControl=null}storeAnimationPaths(e,t){const r=Yt(e);this.animationPaths=r.map(i=>`${t}/${i}`)}loadNextAnimation(){this.curLoadAnim==this.animationPaths.length-1?this.curLoadAnim=0:this.curLoadAnim++,this.loadAnimation(this.animationPaths[this.curLoadAnim])}loadPreviousAnimation(){this.curLoadAnim==0?this.curLoadAnim=this.animationPaths.length-1:this.curLoadAnim--,this.loadAnimation(this.animationPaths[this.curLoadAnim])}enableScreenshot(){this.animationControls.forEach(e=>{e.reset()})}disableScreenshot(){this.animationControls.forEach(e=>{e.resume()})}_scaleOffsetHips(e){e.forEach(t=>{for(let r=0;rr.vrm===e);t!==-1&&this.animationControls.splice(t,1)[0].dispose()}getFromActionTime(){return this.mainControl.actions[this.lastAnimID].time}getToActionTime(){return this.mainControl?this.mainControl.actions[this.curAnimID].time:.1}getWeightIn(){return this.weightIn}getWeightOut(){return this.weightOut}disposeAnimation(e){if(e!=null){const t=this.animationControls.indexOf(e);t!=-1&&this.animationControls.splice(t,1)}}dispose(){this.animationControls.forEach(e=>{e.dispose()})}animRandomizer(e){setTimeout(()=>{this.lastAnimID=this.curAnimID,this.curAnimID=phe(this.animations.length),this.curAnimID!=this.lastAnimID&&this.animationControls.forEach(t=>{t.from=t.actions[this.lastAnimID],t.to=t.actions[this.curAnimID],this.weightIn=0,this.weightOut=1,t.to.play(),t.to.reset()}),this.animRandomizer(this.animations[this.curAnimID].duration-h1)},e*1e3)}pause(){this.paused=!0}play(){this.paused=!1}isPaused(){return this.paused}setTime(e){this.mainControl&&this.animationControls.forEach(t=>{t.setTime(e)})}setSpeed(e){this.mainControl&&this.animationControls.forEach(t=>{t.setTimeScale(e)})}update(){this.mainControl&&!this.paused&&(this.animationControls.forEach(e=>{e.update(this.weightIn,this.weightOut)}),this.weightIn<1?this.weightIn+=1/(30*h1):this.weightIn=1,this.weightOut>0?this.weightOut-=1/(30*h1):this.weightOut=0)}}const bk={uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:` + */class mH{}const i1=new z,Ec=new z;class vH extends mH{constructor(e){var t,r,i;super(),this.offset=(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:new z(0,0,0),this.tail=(r=e==null?void 0:e.tail)!==null&&r!==void 0?r:new z(0,0,0),this.radius=(i=e==null?void 0:e.radius)!==null&&i!==void 0?i:0}get type(){return"capsule"}calculateCollision(e,t,r,i){i1.copy(this.offset).applyMatrix4(e),Ec.copy(this.tail).applyMatrix4(e),Ec.sub(i1);const s=Ec.lengthSq();i.copy(t).sub(i1);const o=Ec.dot(i);o<=0||(s<=o||Ec.multiplyScalar(o/s),i.sub(Ec));const a=r+this.radius,l=i.length()-a;return i.normalize(),l}}class yH extends mH{constructor(e){var t,r;super(),this.offset=(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:new z(0,0,0),this.radius=(r=e==null?void 0:e.radius)!==null&&r!==void 0?r:0}get type(){return"sphere"}calculateCollision(e,t,r,i){i.copy(this.offset).applyMatrix4(e),i.negate().add(t);const s=r+this.radius,o=i.length()-s;return i.normalize(),o}}const Yo=new z;class Bfe extends Ht{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new z,this._currentTail=new z,this._shape=e,this._attrPos=new At(new Float32Array(396),3),this.setAttribute("position",this._attrPos),this._attrIndex=new At(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;const t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0);const r=Yo.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(r)>1e-10&&(this._currentTail.copy(r),e=!0),e&&this._buildPosition()}_buildPosition(){Yo.copy(this._currentTail).sub(this._currentOffset);const e=Yo.length()/this._currentRadius;for(let i=0;i<=16;i++){const s=i/16*Math.PI;this._attrPos.setXYZ(i,-Math.sin(s),-Math.cos(s),0),this._attrPos.setXYZ(17+i,e+Math.sin(s),Math.cos(s),0),this._attrPos.setXYZ(34+i,-Math.sin(s),0,-Math.cos(s)),this._attrPos.setXYZ(51+i,e+Math.sin(s),0,Math.cos(s))}for(let i=0;i<32;i++){const s=i/16*Math.PI;this._attrPos.setXYZ(68+i,0,Math.sin(s),Math.cos(s)),this._attrPos.setXYZ(100+i,e,Math.sin(s),Math.cos(s))}const t=Math.atan2(Yo.y,Math.sqrt(Yo.x*Yo.x+Yo.z*Yo.z)),r=-Math.atan2(Yo.z,Yo.x);this.rotateZ(t),this.rotateY(r),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<34;e++){const t=(e+1)%34;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(68+e*2,34+e,34+t)}for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(136+e*2,68+e,68+t),this._attrIndex.setXY(200+e*2,100+e,100+t)}this._attrIndex.needsUpdate=!0}}class wfe extends Ht{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new z,this._shape=e,this._attrPos=new At(new Float32Array(32*3*3),3),this.setAttribute("position",this._attrPos),this._attrIndex=new At(new Uint16Array(64*3),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;const t=this._shape.radius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){const t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.needsUpdate=!0}}const Cfe=new z;class $D extends Tr{constructor(e){if(super(),this.matrixAutoUpdate=!1,this.collider=e,this.collider.shape instanceof yH)this._geometry=new wfe(this.collider.shape);else if(this.collider.shape instanceof vH)this._geometry=new Bfe(this.collider.shape);else throw new Error("VRMSpringBoneColliderHelper: Unknown collider shape type detected");const t=new Wl({color:16711935,depthTest:!1,depthWrite:!1});this._line=new u0(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);const t=this.matrix.elements;this._geometry.worldScale=Cfe.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}}class bfe extends Ht{constructor(e){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new z,this._springBone=e,this._attrPos=new At(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new At(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let e=!1;const t=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==t&&(this._currentRadius=t,e=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),e=!0),e&&this._buildPosition()}_buildPosition(){for(let e=0;e<32;e++){const t=e/16*Math.PI;this._attrPos.setXYZ(e,Math.cos(t),Math.sin(t),0),this._attrPos.setXYZ(32+e,0,Math.cos(t),Math.sin(t)),this._attrPos.setXYZ(64+e,Math.sin(t),0,Math.cos(t))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let e=0;e<32;e++){const t=(e+1)%32;this._attrIndex.setXY(e*2,e,t),this._attrIndex.setXY(64+e*2,32+e,32+t),this._attrIndex.setXY(128+e*2,64+e,64+t)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}}const xfe=new z;class Ife extends Tr{constructor(e){super(),this.matrixAutoUpdate=!1,this.springBone=e,this._geometry=new bfe(this.springBone);const t=new Wl({color:16776960,depthTest:!1,depthWrite:!1});this._line=new u0(this._geometry,t),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(e){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);const t=this.matrix.elements;this._geometry.worldScale=xfe.set(t[0],t[1],t[2]).length(),this._geometry.update(),super.updateMatrixWorld(e)}}class qD extends kt{constructor(e){super(),this.shape=e}}const Ffe=new Le;function BH(n){return n.invert?n.invert():n.getInverse(Ffe.copy(n)),n}class Efe{constructor(e){this._inverseCache=new Le,this._shouldUpdateInverse=!0,this.matrix=e;const t={set:(r,i,s)=>(this._shouldUpdateInverse=!0,r[i]=s,!0)};this._originalElements=e.elements,e.elements=new Proxy(e.elements,t)}get inverse(){return this._shouldUpdateInverse&&(this._inverseCache.copy(this.matrix),BH(this._inverseCache),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}}const Ufe=new Le,ja=new z,Vp=new z,Sfe=new z,wf=new z,ek=new z,Lp=new z,tk=new tt,Cf=new Le,_fe=new Le;class Qfe{constructor(e,t,r={},i=[]){var s,o,a,l,A,c;this._currentTail=new z,this._prevTail=new z,this._boneAxis=new z,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new Le,this._initialLocalRotation=new tt,this._initialLocalChildPosition=new z,this.bone=e,this.bone.matrixAutoUpdate=!1,this.child=t,this.settings={hitRadius:(s=r.hitRadius)!==null&&s!==void 0?s:0,stiffness:(o=r.stiffness)!==null&&o!==void 0?o:1,gravityPower:(a=r.gravityPower)!==null&&a!==void 0?a:0,gravityDir:(A=(l=r.gravityDir)===null||l===void 0?void 0:l.clone())!==null&&A!==void 0?A:new z(0,-1,0),dragForce:(c=r.dragForce)!==null&&c!==void 0?c:.4},this.colliderGroups=i}get center(){return this._center}set center(e){var t;!((t=this._center)===null||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 Efe(this._center.matrixWorld)))}get initialLocalChildPosition(){return this._initialLocalChildPosition}get _parentMatrixWorld(){return this.bone.parent?this.bone.parent.matrixWorld:Ufe}setInitState(){this._initialLocalMatrix.copy(this.bone.matrix),this._initialLocalRotation.copy(this.bone.quaternion),this.child?this._initialLocalChildPosition.copy(this.child.position):this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(.07);const e=this._getMatrixWorldToCenter(Cf);this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail),this._boneAxis.copy(this._initialLocalChildPosition).normalize()}reset(){this.bone.quaternion.copy(this._initialLocalRotation),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix);const e=this._getMatrixWorldToCenter(Cf);this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)).applyMatrix4(e),this._prevTail.copy(this._currentTail)}update(e){if(e<=0)return;this._calcWorldSpaceBoneLength(),wf.setFromMatrixPosition(this.bone.matrixWorld);let t=this._getMatrixWorldToCenter(Cf);ek.copy(wf).applyMatrix4(t);const r=tk.setFromRotationMatrix(t),i=_fe.copy(t).multiply(this._parentMatrixWorld),s=Vp.copy(this._boneAxis).applyMatrix4(this._initialLocalMatrix).applyMatrix4(i).sub(ek).normalize(),o=Sfe.copy(this.settings.gravityDir).applyQuaternion(r).normalize(),a=this._getMatrixCenterToWorld(Cf);Lp.copy(this._currentTail).add(ja.copy(this._currentTail).sub(this._prevTail).multiplyScalar(1-this.settings.dragForce)).add(ja.copy(s).multiplyScalar(this.settings.stiffness*e)).add(ja.copy(o).multiplyScalar(this.settings.gravityPower*e)).applyMatrix4(a),Lp.sub(wf).normalize().multiplyScalar(this._worldSpaceBoneLength).add(wf),this._collision(Lp),t=this._getMatrixWorldToCenter(Cf),this._prevTail.copy(this._currentTail),this._currentTail.copy(ja.copy(Lp).applyMatrix4(t));const l=BH(Cf.copy(this._parentMatrixWorld).multiply(this._initialLocalMatrix)),A=tk.setFromUnitVectors(this._boneAxis,ja.copy(Lp).applyMatrix4(l).normalize());this.bone.quaternion.copy(this._initialLocalRotation).multiply(A),this.bone.updateMatrix(),this.bone.matrixWorld.multiplyMatrices(this._parentMatrixWorld,this.bone.matrix)}_collision(e){this.colliderGroups.forEach(t=>{t.colliders.forEach(r=>{const i=r.shape.calculateCollision(r.matrixWorld,e,this.settings.hitRadius,ja);i<0&&(e.add(ja.multiplyScalar(-i)),e.sub(wf).normalize().multiplyScalar(this._worldSpaceBoneLength).add(wf))})})}_calcWorldSpaceBoneLength(){ja.setFromMatrixPosition(this.bone.matrixWorld),this.child?Vp.setFromMatrixPosition(this.child.matrixWorld):(Vp.copy(this._initialLocalChildPosition),Vp.applyMatrix4(this.bone.matrixWorld)),this._worldSpaceBoneLength=ja.sub(Vp).length()}_getMatrixCenterToWorld(e){return this._center?e.copy(this._center.matrixWorld):e.identity(),e}_getMatrixWorldToCenter(e){return this._center?e.copy(this._center.userData.inverseCacheProxy.inverse):e.identity(),e}}function ry(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(c){try{A(r.next(c))}catch(u){o(u)}}function l(c){try{A(r.throw(c))}catch(u){o(u)}}function A(c){c.done?s(c.value):i(c.value).then(a,l)}A((r=r.apply(n,e||[])).next())})}function Rfe(n,e){const t=[];let r=n;for(;r!==null;)t.unshift(r),r=r.parent;t.forEach(i=>{e(i)})}function wH(n,e){n.children.forEach(t=>{e(t)||wH(t,e)})}class nk{constructor(){this._joints=new Set,this._objectSpringBonesMap=new Map}get joints(){return this._joints}get springBones(){return console.warn("VRMSpringBoneManager: springBones is deprecated. use joints instead."),this._joints}get colliderGroups(){const e=new Set;return this._joints.forEach(t=>{t.colliderGroups.forEach(r=>{e.add(r)})}),Array.from(e)}get colliders(){const e=new Set;return this.colliderGroups.forEach(t=>{t.colliders.forEach(r=>{e.add(r)})}),Array.from(e)}addJoint(e){this._joints.add(e);let t=this._objectSpringBonesMap.get(e.bone);t==null&&(t=new Set,this._objectSpringBonesMap.set(e.bone,t)),t.add(e)}addSpringBone(e){console.warn("VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead."),this.addJoint(e)}deleteJoint(e){this._joints.delete(e),this._objectSpringBonesMap.get(e.bone).delete(e)}deleteSpringBone(e){console.warn("VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead."),this.deleteJoint(e)}setInitState(){const e=new Set,t=new Set,r=new Set;for(const i of this._joints)this._processSpringBone(i,e,t,r,s=>s.setInitState())}reset(){const e=new Set,t=new Set,r=new Set;for(const i of this._joints)this._processSpringBone(i,e,t,r,s=>s.reset())}update(e){const t=new Set,r=new Set,i=new Set;for(const s of this._joints)this._processSpringBone(s,t,r,i,o=>o.update(e)),wH(s.bone,o=>{var a,l;return((l=(a=this._objectSpringBonesMap.get(o))===null||a===void 0?void 0:a.size)!==null&&l!==void 0?l:0)>0?!0:(o.updateWorldMatrix(!1,!1),!1)})}_processSpringBone(e,t,r,i,s){if(r.has(e))return;if(t.has(e))throw new Error("VRMSpringBoneManager: Circular dependency detected while updating springbones");t.add(e);const o=this._getDependencies(e);for(const a of o)Rfe(a,l=>{const A=this._objectSpringBonesMap.get(l);if(A)for(const c of A)this._processSpringBone(c,t,r,i,s);else i.has(l)||(l.updateWorldMatrix(!1,!1),i.add(l))});e.bone.updateMatrix(),e.bone.updateWorldMatrix(!1,!1),s(e),i.add(e.bone),r.add(e)}_getDependencies(e){const t=new Set,r=e.bone.parent;return r&&t.add(r),e.colliderGroups.forEach(i=>{i.colliders.forEach(s=>{t.add(s)})}),t}}const Mfe=new Set(["1.0","1.0-beta"]);class Kc{constructor(e,t){this.parser=e,this.jointHelperRoot=t==null?void 0:t.jointHelperRoot,this.colliderHelperRoot=t==null?void 0:t.colliderHelperRoot}get name(){return Kc.EXTENSION_NAME}afterRoot(e){return ry(this,void 0,void 0,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return ry(this,void 0,void 0,function*(){const t=yield this._v1Import(e);if(t!=null)return t;const r=yield this._v0Import(e);return r??null})}_v1Import(e){var t,r,i,s,o;return ry(this,void 0,void 0,function*(){const a=e.parser.json;if(!(((t=a.extensionsUsed)===null||t===void 0?void 0:t.indexOf(Kc.EXTENSION_NAME))!==-1))return null;const A=new nk,c=yield e.parser.getDependencies("node"),u=(r=a.extensions)===null||r===void 0?void 0:r[Kc.EXTENSION_NAME];if(!u)return null;const f=u.specVersion;if(!Mfe.has(f))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${Kc.EXTENSION_NAME} specVersion "${f}"`),null;const d=(i=u.colliders)===null||i===void 0?void 0:i.map((p,m)=>{var g,v,y,w,C;const b=c[p.node],E=p.shape;if(E.sphere)return this._importSphereCollider(b,{offset:new z().fromArray((g=E.sphere.offset)!==null&&g!==void 0?g:[0,0,0]),radius:(v=E.sphere.radius)!==null&&v!==void 0?v:0});if(E.capsule)return this._importCapsuleCollider(b,{offset:new z().fromArray((y=E.capsule.offset)!==null&&y!==void 0?y:[0,0,0]),radius:(w=E.capsule.radius)!==null&&w!==void 0?w:0,tail:new z().fromArray((C=E.capsule.tail)!==null&&C!==void 0?C:[0,0,0])});throw new Error(`VRMSpringBoneLoaderPlugin: The collider #${m} has no valid shape`)}),h=(s=u.colliderGroups)===null||s===void 0?void 0:s.map((p,m)=>{var g;return{colliders:((g=p.colliders)!==null&&g!==void 0?g:[]).map(y=>{const w=d==null?void 0:d[y];if(w==null)throw new Error(`VRMSpringBoneLoaderPlugin: The colliderGroup #${m} attempted to use a collider #${y} but not found`);return w}),name:p.name}});return(o=u.springs)===null||o===void 0||o.forEach((p,m)=>{var g;const v=p.joints,y=(g=p.colliderGroups)===null||g===void 0?void 0:g.map(b=>{const E=h==null?void 0:h[b];if(E==null)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${m} attempted to use a colliderGroup ${b} but not found`);return E}),w=p.center!=null?c[p.center]:void 0;let C;v.forEach(b=>{if(C){const E=C.node,x=c[E],S=b.node,M=c[S],Z={hitRadius:C.hitRadius,dragForce:C.dragForce,gravityPower:C.gravityPower,stiffness:C.stiffness,gravityDir:C.gravityDir!=null?new z().fromArray(C.gravityDir):void 0},K=this._importJoint(x,M,Z,y);w&&(K.center=w),A.addJoint(K)}C=b})}),A.setInitState(),A})}_v0Import(e){var t,r,i;return ry(this,void 0,void 0,function*(){const s=e.parser.json;if(!(((t=s.extensionsUsed)===null||t===void 0?void 0:t.indexOf("VRM"))!==-1))return null;const a=(r=s.extensions)===null||r===void 0?void 0:r.VRM,l=a==null?void 0:a.secondaryAnimation;if(!l)return null;const A=l==null?void 0:l.boneGroups;if(!A)return null;const c=new nk,u=yield e.parser.getDependencies("node"),f=(i=l.colliderGroups)===null||i===void 0?void 0:i.map(d=>{var h;const p=u[d.node];return{colliders:((h=d.colliders)!==null&&h!==void 0?h:[]).map((g,v)=>{var y,w,C;const b=new z(0,0,0);return g.offset&&b.set((y=g.offset.x)!==null&&y!==void 0?y:0,(w=g.offset.y)!==null&&w!==void 0?w:0,g.offset.z?-g.offset.z:0),this._importSphereCollider(p,{offset:b,radius:(C=g.radius)!==null&&C!==void 0?C:0})})}});return A==null||A.forEach((d,h)=>{const p=d.bones;p&&p.forEach(m=>{var g,v,y,w;const C=u[m],b=new z;d.gravityDir?b.set((g=d.gravityDir.x)!==null&&g!==void 0?g:0,(v=d.gravityDir.y)!==null&&v!==void 0?v:0,(y=d.gravityDir.z)!==null&&y!==void 0?y:0):b.set(0,-1,0);const E=d.center!=null?u[d.center]:void 0,x={hitRadius:d.hitRadius,dragForce:d.dragForce,gravityPower:d.gravityPower,stiffness:d.stiffiness,gravityDir:b},S=(w=d.colliderGroups)===null||w===void 0?void 0:w.map(M=>{const Z=f==null?void 0:f[M];if(Z==null)throw new Error(`VRMSpringBoneLoaderPlugin: The spring #${h} attempted to use a colliderGroup ${M} but not found`);return Z});C.traverse(M=>{var Z;const K=(Z=M.children[0])!==null&&Z!==void 0?Z:null,_=this._importJoint(M,K,x,S);E&&(_.center=E),c.addJoint(_)})})}),e.scene.updateMatrixWorld(),c.setInitState(),c})}_importJoint(e,t,r,i){const s=new Qfe(e,t,r,i);if(this.jointHelperRoot){const o=new Ife(s);this.jointHelperRoot.add(o),o.renderOrder=this.jointHelperRoot.renderOrder}return s}_importSphereCollider(e,t){const{offset:r,radius:i}=t,s=new yH({offset:r,radius:i}),o=new qD(s);if(e.add(o),this.colliderHelperRoot){const a=new $D(o);this.colliderHelperRoot.add(a),a.renderOrder=this.colliderHelperRoot.renderOrder}return o}_importCapsuleCollider(e,t){const{offset:r,radius:i,tail:s}=t,o=new vH({offset:r,radius:i,tail:s}),a=new qD(o);if(e.add(a),this.colliderHelperRoot){const l=new $D(a);this.colliderHelperRoot.add(l),l.renderOrder=this.colliderHelperRoot.renderOrder}return a}}Kc.EXTENSION_NAME="VRMC_springBone";class Tfe{constructor(e,t){var r,i,s,o,a,l,A,c,u,f;this.parser=e;const d=t==null?void 0:t.helperRoot,h=t==null?void 0:t.autoUpdateHumanBones;this.expressionPlugin=(r=t==null?void 0:t.expressionPlugin)!==null&&r!==void 0?r:new fb(e),this.firstPersonPlugin=(i=t==null?void 0:t.firstPersonPlugin)!==null&&i!==void 0?i:new fue(e),this.humanoidPlugin=(s=t==null?void 0:t.humanoidPlugin)!==null&&s!==void 0?s:new Bue(e,{helperRoot:d,autoUpdateHumanBones:h}),this.lookAtPlugin=(o=t==null?void 0:t.lookAtPlugin)!==null&&o!==void 0?o:new Tue(e,{helperRoot:d}),this.metaPlugin=(a=t==null?void 0:t.metaPlugin)!==null&&a!==void 0?a:new kue(e),this.mtoonMaterialPlugin=(l=t==null?void 0:t.mtoonMaterialPlugin)!==null&&l!==void 0?l:new Jd(e),this.materialsHDREmissiveMultiplierPlugin=(A=t==null?void 0:t.materialsHDREmissiveMultiplierPlugin)!==null&&A!==void 0?A:new Pm(e),this.materialsV0CompatPlugin=(c=t==null?void 0:t.materialsV0CompatPlugin)!==null&&c!==void 0?c:new que(e),this.springBonePlugin=(u=t==null?void 0:t.springBonePlugin)!==null&&u!==void 0?u:new Kc(e,{colliderHelperRoot:d,jointHelperRoot:d}),this.nodeConstraintPlugin=(f=t==null?void 0:t.nodeConstraintPlugin)!==null&&f!==void 0?f:new Xc(e,{helperRoot:d})}get name(){return"VRMLoaderPlugin"}beforeRoot(){return ny(this,void 0,void 0,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(e){return ny(this,void 0,void 0,function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)})}getMaterialType(e){const t=this.mtoonMaterialPlugin.getMaterialType(e);return t??null}extendMaterialParams(e,t){return ny(this,void 0,void 0,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,t),yield this.mtoonMaterialPlugin.extendMaterialParams(e,t)})}afterRoot(e){return ny(this,void 0,void 0,function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);const t=e.userData.vrmMeta,r=e.userData.vrmHumanoid;if(t&&r){const i=new Lue({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:r,lookAt:e.userData.vrmLookAt,meta:t,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=i}})}}function rk(n){if(Object.values(n).forEach(e=>{e!=null&&e.isTexture&&e.dispose()}),n.isShaderMaterial){const e=n.uniforms;e&&Object.values(e).forEach(t=>{const r=t.value;r!=null&&r.isTexture&&r.dispose()})}n.dispose()}function Nfe(n){const e=n.geometry;e&&e.dispose();const t=n.skeleton;t&&t.dispose();const r=n.material;r&&(Array.isArray(r)?r.forEach(i=>rk(i)):r&&rk(r))}function Dfe(n){n.traverse(Nfe)}function kfe(n){const e=new Map;n.traverse(t=>{if(t.type!=="SkinnedMesh")return;const r=t,s=r.geometry.getAttribute("skinIndex");let o=e.get(s);if(!o){const a=[],l=[],A={},c=s.array;for(let u=0;u{var r,i,s,o;if(!t.isMesh)return;const a=t,l=a.geometry,A=l.index;if(A==null)return;const c=e.get(l);if(c!=null){a.geometry=c;return}const u=new Ht;u.name=l.name,u.morphTargetsRelative=l.morphTargetsRelative,l.groups.forEach(p=>{u.addGroup(p.start,p.count,p.materialIndex)}),u.boundingBox=(i=(r=l.boundingBox)===null||r===void 0?void 0:r.clone())!==null&&i!==void 0?i:null,u.boundingSphere=(o=(s=l.boundingSphere)===null||s===void 0?void 0:s.clone())!==null&&o!==void 0?o:null,u.setDrawRange(l.drawRange.start,l.drawRange.count),u.userData=l.userData,e.set(l,u);const f=[],d=[];{const p=A.array,m=new p.constructor(p.length);let g=0;for(let v=0;v{const m=l.attributes[p];if(m.isInterleavedBufferAttribute)throw new Error("removeUnnecessaryVertices: InterleavedBufferAttribute is not supported");const g=m.array,{itemSize:v,normalized:y}=m,w=new g.constructor(d.length*v);d.forEach((C,b)=>{for(let E=0;E{u.morphAttributes[p]=[];const m=l.morphAttributes[p];for(let g=0;g{for(let S=0;SE===0),u.morphAttributes[p][g]=new At(b,w,C)}}),h&&(u.morphAttributes={}),a.geometry=u}),Array.from(e.keys()).forEach(t=>{t.dispose()})}function Lfe(n){var e;((e=n.meta)===null||e===void 0?void 0:e.metaVersion)==="0"&&(n.scene.rotation.y=Math.PI)}class Xh{constructor(){}}Xh.deepDispose=Dfe;Xh.removeUnnecessaryJoints=kfe;Xh.removeUnnecessaryVertices=Vfe;Xh.rotateVRM0=Lfe;var Kn;(function(n){n[n.ARRAY_BUFFER=34962]="ARRAY_BUFFER",n[n.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",n[n.BYTE=5120]="BYTE",n[n.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",n[n.SHORT=5122]="SHORT",n[n.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",n[n.UNSIGNED_INT=5125]="UNSIGNED_INT",n[n.FLOAT=5126]="FLOAT",n[n.LINEAR=9729]="LINEAR",n[n.REPEAT=10497]="REPEAT"})(Kn||(Kn={}));const Ww="blend_",ik="vrmColliderSphere";class Pfe{parse(e,t,r,i){const s=e.humanoid,o=e.meta,a=e.materials,l={},A={},c={},u=e.lookAt,f={generator:"UniGLTF-2.0.0",version:"2.0"};if(t)if(s)if(o)if(a){if(!u)throw new Error("lookAt is undefined or null")}else throw new Error("materials is undefined or null");else throw new Error("meta is undefined or null");else throw new Error("humanoid is undefined or null");else throw new Error("avatar is undefined or null");const d=a.filter((X,ne,ae)=>ae.findIndex(Be=>Be.name===X.name.replace(" (Outline)",""))===ne).map(X=>X),h=d.map(X=>X.name),p=r?{name:"icon",imageBitmap:r.image}:null,m=d.filter(X=>X.map).map(X=>{if(!X.map)throw new Error(X.name+" map is null");return{name:X.name,imageBitmap:X.map.image}}),g=d.filter(X=>X.userData.shadeTexture).map(X=>{if(!X.userData.shadeTexture)throw new Error(X.userData.shadeTexture+" map is null");return{name:X.name+"_shade",imageBitmap:X.userData.shadeTexture.image}}),v=m.concat(g),y=Jfe(v,p),w=Hfe(y),C=zfe(y),b=Zfe(d,v),E=t.children.filter(X=>X.children.length>0&&X.children[0].type===ui.Bone)[0],x=CH(E).filter(X=>X.name!==ik),S=x.map(X=>X.name),M=x.map(X=>({children:X.children.filter(ne=>ne.name!==ik).map(ne=>S.indexOf(ne.name)),name:X.name,rotation:[X.quaternion.x,X.quaternion.y,X.quaternion.z,X.quaternion.w],scale:[X.scale.x,X.scale.y,X.scale.z],translation:[X.position.x,X.position.y,X.position.z]})),Z=[],K=t.children.filter(X=>X.type===ui.Group||X.type===ui.SkinnedMesh),_=[];K.forEach(X=>{const ne=X.type===ui.Group?X.children[0]:X,ae=ne.geometry.attributes;_.push(new $a(ae.position,Kn.FLOAT,jt.POSITION,xo.VEC3,ne.name,void 0)),_.push(new $a(ae.normal,Kn.FLOAT,jt.NORMAL,xo.VEC3,ne.name,void 0)),_.push(new $a(ae.uv,Kn.FLOAT,jt.UV,xo.VEC2,ne.name,void 0)),_.push(new $a(ae.skinWeight,Kn.FLOAT,jt.SKIN_WEIGHT,xo.VEC4,ne.name,void 0)),_.push(new $a(ae.skinIndex,Kn.UNSIGNED_SHORT,jt.SKIN_INDEX,xo.VEC4,ne.name,void 0)),(X.type===ui.Group?X.children.map(pe=>pe):[X]).forEach(pe=>{if(!pe.geometry.index)throw new Error(pe.name+" geometry.index is null");_.push(new $a(pe.geometry.index,Kn.UNSIGNED_INT,jt.INDEX,xo.SCALAR,ne.name,pe.name))}),ne.morphTargetDictionary||(ne.morphTargetDictionary={},ne.morphTargetInfluences=[],ne.geometry.morphAttributes={},ne.updateMorphTargets()),ne.geometry.userData.targetNames=[];for(const pe in e.expressionManager.expressionMap){const Fe=e.expressionManager.expressionMap[pe],rt=Fe._binds.map(ke=>({node:x.length,index:ke.index,weight:ke.weight}));let Oe=!1;for(const ke in ci)if(pe.toLowerCase()===ci[ke].toLowerCase()){l[ci[ke]]={morphTargetBinds:rt,isBinary:Fe.isBinary,overrideBlink:Fe.overrideBlink,overrideLookAt:Fe.overrideLookAt,overrideMouth:Fe.overrideMouth},Oe=!0;break}!Oe&&pe.toLowerCase()==="surprise"&&(l.surprised={morphTargetBinds:rt,isBinary:Fe.isBinary,overrideBlink:Fe.overrideBlink,overrideLookAt:Fe.overrideLookAt,overrideMouth:Fe.overrideMouth},Oe=!0),Oe===!1&&(A[pe]={morphTargetBinds:rt,isBinary:Fe.isBinary,overrideBlink:Fe.overrideBlink,overrideLookAt:Fe.overrideLookAt,overrideMouth:Fe.overrideMouth})}for(const pe in ne.morphTargetDictionary){ne.geometry.userData.targetNames.push(pe);const Fe=ne.morphTargetDictionary[pe],rt=ne.geometry.morphAttributes;_.push(new $a(rt.position[Fe],Kn.FLOAT,jt.BLEND_POSITION,xo.VEC3,ne.name,Ww+pe)),_.push(new $a(rt.normal[Fe],Kn.FLOAT,jt.BLEND_NORMAL,xo.VEC3,ne.name,Ww+pe))}}),Object.keys(l).length>0&&(c.preset=l),Object.keys(A).length>0&&(c.custom=A),K.forEach(X=>{const ne=X.type===ui.Group?X.children[0]:X,ae=new Float32Array(ne.skeleton.boneInverses.map(Be=>Be.elements).flat());_.push(new $a(new At(ae,16),Kn.FLOAT,jt.BIND_MATRIX,xo.MAT4,ne.name,ne.name))}),Z.push(..._.map(X=>({bufferView:-1,byteOffset:0,componentType:X.valueType,count:X.attribute.count,max:X.max,min:X.min,normalized:!1,type:X.accessorsType})));const B=Ofe(K,_,h);K.forEach((X,ne)=>{M.push({mesh:ne,name:X.name,rotation:[X.quaternion.x,X.quaternion.y,X.quaternion.z,X.quaternion.w],scale:[X.scale.x,X.scale.y,X.scale.z],skin:ne,translation:[X.position.x,X.position.y,X.position.z]})});const F=Gfe(K,_,S),R={offsetFromHeadBone:[0,0,0],rangeMapHorizontalInner:{inputMaxValue:u.applier.rangeMapHorizontalInner.inputMaxValue,outputScale:u.applier.rangeMapHorizontalInner.outputScale},rangeMapHorizontalOuter:{inputMaxValue:u.applier.rangeMapHorizontalOuter.inputMaxValue,outputScale:u.applier.rangeMapHorizontalOuter.outputScale},rangeMapVerticalDown:{inputMaxValue:u.applier.rangeMapVerticalDown.inputMaxValue,outputScale:u.applier.rangeMapVerticalDown.outputScale},rangeMapVerticalUp:{inputMaxValue:u.applier.rangeMapVerticalUp.inputMaxValue,outputScale:u.applier.rangeMapVerticalUp.outputScale},type:"bone"},k={humanBones:{}};for(const X in s.humanBones)k.humanBones[X]={node:S.indexOf(s.humanBones[X].node.name)};const T=o,V=[];V.push(...v.map(X=>({buffer:sk(X.imageBitmap),type:jt.IMAGE}))),V.push(..._.map(X=>({buffer:X.buffer,type:X.type}))),p&&V.push({buffer:sk(p.imageBitmap),type:jt.IMAGE});let O=0,L=0,U=0;const H=V.map((X,ne)=>{const ae={buffer:0,byteLength:X.buffer.byteLength,byteOffset:O,target:X.type===jt.IMAGE||X.type===jt.BIND_MATRIX?void 0:X.type===jt.INDEX?Kn.ELEMENT_ARRAY_BUFFER:Kn.ARRAY_BUFFER};return O+=X.buffer.byteLength,X.type===jt.IMAGE?y[L++].bufferView=ne:Z[U++].bufferView=ne,ae}),le=Yfe(t,M),N={accessors:Z,asset:f,buffers:[{byteLength:O}],bufferViews:H,extensions:{VRMC_vrm:{expressions:c,humanoid:k,lookAt:R,meta:T,specVersion:"1.0"}},extensionsUsed:["KHR_materials_unlit","KHR_texture_transform","VRMC_materials_mtoon","VRMC_vrm"],images:y,materials:b,meshes:B,nodes:M,samplers:w,avatar:0,scenes:le,skins:F,textures:C},j=new ok($E(JSON.stringify(N,void 0,2)),"JSON"),oe=new ok(wg(V.map(X=>X.buffer)),"BIN\0"),ie=wg([j.buffer,oe.buffer]),de=wg([$E("glTF"),jE(2,4),jE(ie.byteLength+12,4)]);i(wg([de,ie]))}}function CH(n){return n.children.length<=0?[n]:[n].concat(n.children.map(e=>CH(e)).flat())}function sk(n){const e=document.createElement("canvas");e.width=n.width,e.height=n.height,e.getContext("2d").drawImage(n,0,0);const t=e.toDataURL("image/png"),r=atob(t.split(",")[1]),i=new ArrayBuffer(r.length),s=new DataView(i);for(let o=0;o4?A=r[a*n.itemSize+l]:l===0?A=n.getX(a):l===1?A=n.getY(a):l===2?A=n.getZ(a):A=n.getW(a),e===Kn.UNSIGNED_SHORT?o.setUint16(i,A,!0):e===Kn.UNSIGNED_INT?o.setUint32(i,A,!0):o.setFloat32(i,A,!0),i+=t}return s}let ok=class{constructor(e,t){this.data=e,this.type=t;const r=this.data;this.buffer=wg([jE(r.byteLength,4),$E(this.type),r])}paddingBinary(e,t){const r=Math.ceil(e.byteLength/4)*4;if(e.byteLength===r)return e;const i=new Uint8Array(r);i.set(new Uint8Array(e),0);for(let s=e.byteLength;sl%3===0)),Math.max.apply(null,Array.from(this.attribute.array).filter((a,l)=>l%3===1)),Math.max.apply(null,Array.from(this.attribute.array).filter((a,l)=>l%3===2))]:void 0,this.min=r===jt.POSITION||r===jt.BLEND_POSITION?[Math.min.apply(null,Array.from(this.attribute.array).filter((a,l)=>l%3===0)),Math.min.apply(null,Array.from(this.attribute.array).filter((a,l)=>l%3===1)),Math.min.apply(null,Array.from(this.attribute.array).filter((a,l)=>l%3===2))]:void 0}};var xd;(function(n){n.MeshBasicMaterial="MeshBasicMaterial",n.MeshStandardMaterial="MeshStandardMaterial",n.MToonMaterial="MToonMaterial"})(xd||(xd={}));var xo;(function(n){n.SCALAR="SCALAR",n.VEC2="VEC2",n.VEC3="VEC3",n.VEC4="VEC4",n.MAT4="MAT4"})(xo||(xo={}));var jt;(function(n){n.POSITION="POSITION",n.NORMAL="NORMAL",n.UV="UV",n.INDEX="INDEX",n.SKIN_WEIGHT="SKIN_WEIGHT",n.SKIN_INDEX="SKIN_INDEX",n.BLEND_POSITION="BLEND_POSITION",n.BLEND_NORMAL="BLEND_NORMAL",n.BIND_MATRIX="BIND_MATRIX",n.IMAGE="IMAGE"})(jt||(jt={}));var ui;(function(n){n.Group="Group",n.SkinnedMesh="SkinnedMesh",n.Object3D="Object3D",n.Bone="Bone"})(ui||(ui={}));const Ofe=(n,e,t)=>n.map(r=>{const i=r.type===ui.Group?r.children[0]:r,s=r.type===ui.Group?r.children.map(o=>o):[r];return{name:r.name,primitives:s.map(o=>{const a=e.map(A=>A.meshName===i.name?A.type:null),l=Array.isArray(o.material)?o.material[0].name:o.material.name;return{attributes:{JOINTS_0:a.indexOf(jt.SKIN_INDEX),NORMAL:a.indexOf(jt.NORMAL),POSITION:a.indexOf(jt.POSITION),TEXCOORD_0:a.indexOf(jt.UV),WEIGHTS_0:a.indexOf(jt.SKIN_WEIGHT)},extras:{targetNames:o.geometry.userData.targetNames},indices:e.map(A=>A.type===jt.INDEX&&A.meshName===i.name?A.name:null).indexOf(o.name),material:t.indexOf(l),mode:4,targets:i.geometry.userData.targetNames?i.geometry.userData.targetNames.map(A=>({NORMAL:e.map(c=>c.type===jt.BLEND_NORMAL&&c.meshName===i.name?c.name:null).indexOf(Ww+A),POSITION:e.map(c=>c.type===jt.BLEND_POSITION&&c.meshName===i.name?c.name:null).indexOf(Ww+A)})):void 0}})}}),Gfe=(n,e,t)=>n.map(r=>{const i=r.type===ui.Group?r.children[0]:r;return{inverseBindMatrices:e.map(s=>s.type===jt.BIND_MATRIX?s.meshName:null).indexOf(i.name),joints:i.skeleton.bones.map(s=>t.indexOf(s.name)),skeleton:t.indexOf(i.skeleton.bones[0].name)}}),Zfe=(n,e)=>n.map(t=>{let r,i=null;if(t=t.userData.vrmMaterial?t.userData.vrmMaterial:t,t.type==="ShaderMaterial")i=t.userData.gltfExtensions.VRMC_materials_mtoon,i.shadeMultiplyTexture={index:e.map(c=>c.name).indexOf(t.uniforms.shadeMultiplyTexture.name)},r=t.color?[1,1,1,1]:void 0;else{const A=t;r=A.color?[A.color.r,A.color.g,A.color.b,1]:void 0}let s=-1;t.map?s=e.map(A=>A.name).indexOf(t.name):t.uniforms&&t.uniforms.map&&(s=e.map(A=>A.name).indexOf(t.uniforms.map.name));const o=s>=0?{extensions:{KHR_texture_transform:{offset:[0,0],scale:[1,1]}},index:s,texCoord:0}:void 0,a=(()=>{switch(t.type){case xd.MeshStandardMaterial:return t.metalness;case xd.MeshBasicMaterial:return 0;default:return 0}})(),l=(()=>{switch(t.type){case xd.MeshStandardMaterial:return t.roughness;case xd.MeshBasicMaterial:return .9;default:return .9}})();return{alphaCutoff:t.alphaTest>0?t.alphaTest:void 0,alphaMode:t.transparent?"BLEND":t.alphaTest>0?"MASK":"OPAQUE",doubleSided:t.side===2,extensions:t.type==="ShaderMaterial"?{KHR_materials_unlit:{},VRMC_materials_mtoon:i}:void 0,name:t.name,pbrMetallicRoughness:{baseColorFactor:r,baseColorTexture:o,metallicFactor:a,roughnessFactor:l}}}),Jfe=(n,e)=>(e?n.concat(e):n).filter(t=>t&&t.imageBitmap).map(t=>({bufferView:-1,mimeType:"image/png",name:t.name})),Hfe=n=>n.map(()=>({magFilter:Kn.LINEAR,minFilter:Kn.LINEAR,wrapS:Kn.REPEAT,wrapT:Kn.REPEAT})),zfe=n=>n.map((e,t)=>({sampler:0,source:t})),Yfe=(n,e)=>{const t=e.map(r=>r.name);return[{nodes:n.children.filter(r=>r.type===ui.Object3D||r.type===ui.SkinnedMesh||r.type===ui.Group||r.type===ui.Bone).map(r=>t.indexOf(r.name))}]},bH=0,Xfe=1,xH=2,ak=2,s1=1.25,lk=1,hB=6*4+4+4,qE=65535,Kfe=Math.pow(2,-24);class iy{constructor(){}}function fa(n,e,t){return t.min.x=e[n],t.min.y=e[n+1],t.min.z=e[n+2],t.max.x=e[n+3],t.max.y=e[n+4],t.max.z=e[n+5],t}function Ak(n){let e=-1,t=-1/0;for(let r=0;r<3;r++){const i=n[r+3]-n[r];i>t&&(t=i,e=r)}return e}function ck(n,e){e.set(n)}function uk(n,e,t){let r,i;for(let s=0;s<3;s++){const o=s+3;r=n[s],i=e[s],t[s]=ri?r:i}}function sy(n,e,t){for(let r=0;r<3;r++){const i=e[n+2*r],s=e[n+2*r+1],o=i-s,a=i+s;ot[r+3]&&(t[r+3]=a)}}function Pp(n){const e=n[3]-n[0],t=n[4]-n[1],r=n[5]-n[2];return 2*(e*t+t*r+r*e)}function jfe(n,e){if(!n.index){const t=n.attributes.position.count,r=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer;let i;t>65535?i=new Uint32Array(new r(4*t)):i=new Uint16Array(new r(2*t)),n.setIndex(new At(i,1));for(let s=0;si-s);for(let i=0;il&&(l=E),g&&wh&&(h=w);const x=n[v+2],S=n[v+3],M=x-S,Z=x+S;MA&&(A=Z),g&&xp&&(p=x);const K=n[v+4],_=n[v+5],B=K-_,F=K+_;Bc&&(c=F),g&&Km&&(m=K)}r[0]=s,r[1]=o,r[2]=a,r[3]=l,r[4]=A,r[5]=c,g&&(i[0]=u,i[1]=f,i[2]=d,i[3]=h,i[4]=p,i[5]=m)}function qfe(n,e,t,r){let i=1/0,s=1/0,o=1/0,a=-1/0,l=-1/0,A=-1/0;for(let c=e*6,u=(e+t)*6;ca&&(a=f);const d=n[c+2];dl&&(l=d);const h=n[c+4];hA&&(A=h)}r[0]=i,r[1]=s,r[2]=o,r[3]=a,r[4]=l,r[5]=A}function ede(n,e,t,r,i){let s=t,o=t+r-1;const a=i.pos,l=i.axis*2;for(;;){for(;s<=o&&e[s*6+l]=a;)o--;if(sn.candidate-e.candidate,oA=new Array(rl).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),oy=new Float32Array(6);function nde(n,e,t,r,i,s){let o=-1,a=0;if(s===bH)o=Ak(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(s===Xfe)o=Ak(n),o!==-1&&(a=rde(t,r,i,o));else if(s===xH){const l=Pp(n);let A=s1*i;const c=r*6,u=(r+i)*6;for(let f=0;f<3;f++){const d=e[f],m=(e[f+3]-d)/rl;if(i=E.candidate?sy(w,t,E.rightCacheBounds):(sy(w,t,E.leftCacheBounds),E.count++)}}for(let w=0;w=rl&&(b=rl-1);const E=oA[b];E.count++,sy(y,t,E.bounds)}const g=oA[rl-1];ck(g.bounds,g.rightCacheBounds);for(let y=rl-2;y>=0;y--){const w=oA[y],C=oA[y+1];uk(w.bounds,C.rightCacheBounds,w.rightCacheBounds)}let v=0;for(let y=0;yb&&(b=y),w>b&&(b=w);const E=(b-C)/2,x=g*2;s[d+x+0]=C+E,s[d+x+1]=E+(Math.abs(C)+E)*Kfe,Ce[g+3]&&(e[g+3]=b)}}return s}function sde(n,e){function t(g){f&&f(g/d)}function r(g,v,y,w=null,C=0){if(!h&&C>=l&&(h=!0,A&&(console.warn(`MeshBVH: Max depth of ${l} reached when generating BVH. Consider increasing maxDepth.`),console.warn(n))),y<=c||C>=l)return t(v+y),g.offset=v,g.count=y,g;const b=nde(g.boundingData,w,o,v,y,u);if(b.axis===-1)return t(v+y),g.offset=v,g.count=y,g;const E=ede(a,o,v,y,b);if(E===v||E===v+y)t(v+y),g.offset=v,g.count=y;else{g.splitAxis=b.axis;const x=new iy,S=v,M=E-v;g.left=x,x.boundingData=new Float32Array(6),o1(o,S,M,x.boundingData,s),r(x,S,M,s,C+1);const Z=new iy,K=E,_=y-M;g.right=Z,Z.boundingData=new Float32Array(6),o1(o,K,_,Z.boundingData,s),r(Z,K,_,s,C+1)}return g}jfe(n,e);const i=new Float32Array(6),s=new Float32Array(6),o=ide(n,i),a=n.index.array,l=e.maxDepth,A=e.verbose,c=e.maxLeafTris,u=e.strategy,f=e.onProgress,d=n.index.count/3;let h=!1;const p=[],m=$fe(n);if(m.length===1){const g=m[0],v=new iy;v.boundingData=i,qfe(o,g.offset,g.count,s),r(v,g.offset,g.count,s),p.push(v)}else for(let g of m){const v=new iy;v.boundingData=new Float32Array(6),o1(o,g.offset,g.count,v.boundingData,s),r(v,g.offset,g.count,s),p.push(v)}return p}function ode(n,e){const t=sde(n,e);let r,i,s;const o=[],a=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer;for(let c=0;cMath.pow(2,32))throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits.");return i[f+6]=y/4,y=A(y,g),i[f+7]=v,y}}}class kl{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let r=1/0,i=-1/0;for(let s=0,o=e.length;si?l:i}this.min=r,this.max=i}setFromPoints(e,t){let r=1/0,i=-1/0;for(let s=0,o=t.length;si?l:i}this.min=r,this.max=i}isSeparated(e){return this.min>e.max||e.min>this.max}}kl.prototype.setFromBox=function(){const n=new z;return function(t,r){const i=r.min,s=r.max;let o=1/0,a=-1/0;for(let l=0;l<=1;l++)for(let A=0;A<=1;A++)for(let c=0;c<=1;c++){n.x=i.x*l+s.x*(1-l),n.y=i.y*A+s.y*(1-A),n.z=i.z*c+s.z*(1-c);const u=t.dot(n);o=Math.min(u,o),a=Math.max(u,a)}this.min=o,this.max=a}}();const ade=function(){const n=new z,e=new z,t=new z;return function(i,s,o){const a=i.start,l=n,A=s.start,c=e;t.subVectors(a,A),n.subVectors(i.end,i.start),e.subVectors(s.end,s.start);const u=t.dot(c),f=c.dot(l),d=c.dot(c),h=t.dot(l),m=l.dot(l)*d-f*f;let g,v;m!==0?g=(u*f-h*d)/m:g=0,v=(u+g*f)/d,o.x=g,o.y=v}}(),X_=function(){const n=new We,e=new z,t=new z;return function(i,s,o,a){ade(i,s,n);let l=n.x,A=n.y;if(l>=0&&l<=1&&A>=0&&A<=1){i.at(l,o),s.at(A,a);return}else if(l>=0&&l<=1){A<0?s.at(0,a):s.at(1,a),i.closestPointToPoint(a,!0,o);return}else if(A>=0&&A<=1){l<0?i.at(0,o):i.at(1,o),s.closestPointToPoint(o,!0,a);return}else{let c;l<0?c=i.start:c=i.end;let u;A<0?u=s.start:u=s.end;const f=e,d=t;if(i.closestPointToPoint(u,!0,e),s.closestPointToPoint(c,!0,t),f.distanceToSquared(u)<=d.distanceToSquared(c)){o.copy(f),a.copy(u);return}else{o.copy(c),a.copy(d);return}}}}(),lde=function(){const n=new z,e=new z,t=new hl,r=new Il;return function(s,o){const{radius:a,center:l}=s,{a:A,b:c,c:u}=o;if(r.start=A,r.end=c,r.closestPointToPoint(l,!0,n).distanceTo(l)<=a||(r.start=A,r.end=u,r.closestPointToPoint(l,!0,n).distanceTo(l)<=a)||(r.start=c,r.end=u,r.closestPointToPoint(l,!0,n).distanceTo(l)<=a))return!0;const p=o.getPlane(t);if(Math.abs(p.distanceToPoint(l))<=a){const g=p.projectPoint(l,e);if(o.containsPoint(g))return!0}return!1}}(),Ade=1e-15;function bf(n){return Math.abs(n)new z),this.satBounds=new Array(4).fill().map(()=>new kl),this.points=[this.a,this.b,this.c],this.sphere=new Qu,this.plane=new hl,this.needsUpdate=!0}intersectsSphere(e){return lde(e,this)}update(){const e=this.a,t=this.b,r=this.c,i=this.points,s=this.satAxes,o=this.satBounds,a=s[0],l=o[0];this.getNormal(a),l.setFromPoints(a,i);const A=s[1],c=o[1];A.subVectors(e,t),c.setFromPoints(A,i);const u=s[2],f=o[2];u.subVectors(t,r),f.setFromPoints(u,i);const d=s[3],h=o[3];d.subVectors(r,e),h.setFromPoints(d,i),this.sphere.setFromPoints(this.points),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Vl.prototype.closestPointToSegment=function(){const n=new z,e=new z,t=new Il;return function(i,s=null,o=null){const{start:a,end:l}=i,A=this.points;let c,u=1/0;for(let f=0;f<3;f++){const d=(f+1)%3;t.start.copy(A[f]),t.end.copy(A[d]),X_(t,i,n,e),c=n.distanceToSquared(e),c1-1e-10){const v=this.satBounds,y=this.satAxes;t[0]=d.a,t[1]=d.b,t[2]=d.c;for(let b=0;b<4;b++){const E=v[b],x=y[b];if(r.setFromPoints(x,t),E.isSeparated(r))return!1}const w=d.satBounds,C=d.satAxes;e[0]=this.a,e[1]=this.b,e[2]=this.c;for(let b=0;b<4;b++){const E=w[b],x=C[b];if(r.setFromPoints(x,e),E.isSeparated(r))return!1}for(let b=0;b<4;b++){const E=y[b];for(let x=0;x<4;x++){const S=C[x];if(s.crossVectors(E,S),r.setFromPoints(s,e),i.setFromPoints(s,t),r.isSeparated(i))return!1}}return h&&(p||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),h.start.set(0,0,0),h.end.set(0,0,0)),!0}else{const v=this.points;let y=!1,w=0;for(let B=0;B<3;B++){const F=v[B],R=v[(B+1)%3];A.start.copy(F),A.end.copy(R),A.delta(o);const k=y?c.start:c.end,T=bf(g.distanceToPoint(F));if(bf(g.normal.dot(o))&&T){c.copy(A),w=2;break}if((g.intersectLine(A,k)||T)&&!bf(k.distanceTo(R))){if(w++,y)break;y=!0}}if(w===1&&d.containsPoint(c.end))return h&&(h.start.copy(c.end),h.end.copy(c.end)),!0;if(w!==2)return!1;const C=d.points;let b=!1,E=0;for(let B=0;B<3;B++){const F=C[B],R=C[(B+1)%3];A.start.copy(F),A.end.copy(R),A.delta(a);const k=b?u.start:u.end,T=bf(m.distanceToPoint(F));if(bf(m.normal.dot(a))&&T){u.copy(A),E=2;break}if((m.intersectLine(A,k)||T)&&!bf(k.distanceTo(R))){if(E++,b)break;b=!0}}if(E===1&&this.containsPoint(u.end))return h&&(h.start.copy(u.end),h.end.copy(u.end)),!0;if(E!==2)return!1;if(c.delta(o),u.delta(a),o.dot(a)<0){let B=u.start;u.start=u.end,u.end=B}const x=c.start.dot(o),S=c.end.dot(o),M=u.start.dot(o),Z=u.end.dot(o),K=S0?h.start.copy(c.start):h.start.copy(u.start),l.subVectors(c.end,u.end),l.dot(o)<0?h.end.copy(c.end):h.end.copy(u.end)),!0)}}}();Vl.prototype.distanceToPoint=function(){const n=new z;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}}();Vl.prototype.distanceToTriangle=function(){const n=new z,e=new z,t=["a","b","c"],r=new Il,i=new Il;return function(o,a=null,l=null){const A=a||l?r:null;if(this.intersectsTriangle(o,A))return(a||l)&&(a&&A.getCenter(a),l&&A.getCenter(l)),0;let c=1/0;for(let u=0;u<3;u++){let f;const d=t[u],h=o[d];this.closestPointToPoint(h,n),f=h.distanceToSquared(n),fnew z),this.satAxes=new Array(3).fill().map(()=>new z),this.satBounds=new Array(3).fill().map(()=>new kl),this.alignedSatBounds=new Array(3).fill().map(()=>new kl),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),r&&this.matrix.copy(r)}set(e,t,r){this.min.copy(e),this.max.copy(t),this.matrix.copy(r),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Ma.prototype.update=function(){return function(){const e=this.matrix,t=this.min,r=this.max,i=this.points;for(let A=0;A<=1;A++)for(let c=0;c<=1;c++)for(let u=0;u<=1;u++){const f=1*A|2*c|4*u,d=i[f];d.x=A?r.x:t.x,d.y=c?r.y:t.y,d.z=u?r.z:t.z,d.applyMatrix4(e)}const s=this.satBounds,o=this.satAxes,a=i[0];for(let A=0;A<3;A++){const c=o[A],u=s[A],f=1<new Il),t=new Array(12).fill().map(()=>new Il),r=new z,i=new z;return function(o,a=0,l=null,A=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(l||A)&&(o.getCenter(i),this.closestPointToPoint(i,r),o.closestPointToPoint(r,i),l&&l.copy(r),A&&A.copy(i)),0;const c=a*a,u=o.min,f=o.max,d=this.points;let h=1/0;for(let m=0;m<8;m++){const g=d[m];i.copy(g).clamp(u,f);const v=g.distanceToSquared(i);if(vt.far)?null:n}function aa(n,e,t,r){const i=n.a,s=n.b,o=n.c;let a=e,l=e+1,A=e+2;t&&(a=t.getX(e),l=t.getX(e+1),A=t.getX(e+2)),i.x=r.getX(a),i.y=r.getY(a),i.z=r.getZ(a),s.x=r.getX(l),s.y=r.getY(l),s.z=r.getZ(l),o.x=r.getX(A),o.y=r.getY(A),o.z=r.getZ(A)}function mk(n,e,t,r,i,s,o){const a=t.index,l=t.attributes.position;for(let A=n,c=e+n;A=0;let d,h;f?(d=Om(n),h=Gm(n,a)):(d=Gm(n,a),h=Om(n));const m=Gw(d,s,r,Ow)?tU(d,e,t,r):null;if(m){const y=m.point[c];if(f?y<=s[h+A]:y>=s[h+A+3])return m}const v=Gw(h,s,r,Ow)?tU(h,e,t,r):null;return m&&v?m.distance<=v.distance?m:v:m||v||null}}const gde=function(){let n,e;const t=[],r=new FH(()=>new ws);return function(...o){n=r.getPrimitive(),e=r.getPrimitive(),t.push(n,e);const a=i(...o);r.releasePrimitive(n),r.releasePrimitive(e),t.pop(),t.pop();const l=t.length;return l>0&&(e=t[l-1],n=t[l-2]),a};function i(s,o,a,l,A=null,c=0,u=0){function f(y){let w=y*2,C=ZA,b=JA;for(;!yA(w,C);)y=Om(y),w=y*2;return Hd(y,b)}function d(y){let w=y*2,C=ZA,b=JA;for(;!yA(w,C);)y=Gm(y,b),w=y*2;return Hd(y,b)+Wm(w,C)}let h=s*2,p=Kh,m=ZA,g=JA;if(yA(h,m)){const y=Hd(s,g),w=Wm(h,m);return fa(s,p,n),l(y,w,!1,u,c+s,n)}else{const y=Om(s),w=Gm(s,g);let C=y,b=w,E,x,S,M;if(A&&(S=n,M=e,fa(C,p,S),fa(b,p,M),E=A(S),x=A(M),xi.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(A),x.b.applyMatrix4(A),x.c.applyMatrix4(A),x.needsUpdate=!0;for(let S=C*3,M=(b+C)*3;Snew Vl);class Yg{static serialize(e,t={}){if(t.isBufferGeometry)return console.warn("MeshBVH.serialize: The arguments for the function have changed. See documentation for new signature."),Yg.serialize(arguments[0],{cloneBuffers:arguments[2]===void 0?!0:arguments[2]});t={cloneBuffers:!0,...t};const r=e.geometry,i=e._roots,s=r.getIndex();let o;return t.cloneBuffers?o={roots:i.map(a=>a.slice()),index:s.array.slice()}:o={roots:i,index:s.array},o}static deserialize(e,t,r={}){if(typeof r=="boolean")return console.warn("MeshBVH.deserialize: The arguments for the function have changed. See documentation for new signature."),Yg.deserialize(arguments[0],arguments[1],{setIndex:arguments[2]===void 0?!0:arguments[2]});r={setIndex:!0,...r};const{index:i,roots:s}=e,o=new Yg(t,{...r,[a1]:!0});if(o._roots=s,r.setIndex){const a=t.getIndex();if(a===null){const l=new At(e.index,1,!1);t.setIndex(l)}else a.array!==i&&(a.array.set(i),a.needsUpdate=!0)}return o}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({strategy:bH,maxDepth:40,maxLeafTris:10,verbose:!0,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,[a1]:!1},t),t.useSharedArrayBuffer&&typeof SharedArrayBuffer>"u")throw new Error("MeshBVH: SharedArrayBuffer is not available.");this._roots=null,t[a1]||(this._roots=ode(e,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new ws))),this.geometry=e}refit(e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=this.geometry,r=t.index.array,i=t.attributes.position;let s,o,a,l,A=0;const c=this._roots;for(let f=0,d=c.length;fb&&(b=K),_E&&(E=_),Bx&&(x=B)}return l[f+0]!==y||l[f+1]!==w||l[f+2]!==C||l[f+3]!==b||l[f+4]!==E||l[f+5]!==x?(l[f+0]=y,l[f+1]=w,l[f+2]=C,l[f+3]=b,l[f+4]=E,l[f+5]=x,!0):!1}else{const g=f+8,v=o[f+6],y=g+d,w=v+d;let C=h,b=!1,E=!1;e?C||(b=e.has(y),E=e.has(w),C=!b&&!E):(b=!0,E=!0);const x=C||b,S=C||E;let M=!1;x&&(M=u(g,d,C));let Z=!1;S&&(Z=u(v,d,C));const K=M||Z;if(K)for(let _=0;_<3;_++){const B=g+_,F=v+_,R=l[B],k=l[B+3],T=l[F],V=l[F+3];l[f+_]=RV?k:V}return K}}}traverse(e,t=0){const r=this._roots[t],i=new Uint32Array(r),s=new Uint16Array(r);o(0);function o(a,l=0){const A=a*2,c=s[A+15]===qE;if(c){const u=i[a+6],f=s[A+14];e(l,c,new Float32Array(r,a*4,6),u,f)}else{const u=a+hB/4,f=i[a+6],d=i[a+7];e(l,c,new Float32Array(r,a*4,6),d)||(o(u,l+1),o(f,l+1))}}}raycast(e,t=Vo){const r=this._roots,i=this.geometry,s=[],o=t.isMaterial,a=Array.isArray(t),l=i.groups,A=o?t.side:t;for(let c=0,u=r.length;c{const g=h*3;return f(d,g,g+1,g+2,p,m)}}e={boundsTraverseOrder:r,intersectsBounds:e,intersectsTriangle:t,intersectsRange:null},console.warn("MeshBVH: Shapecast function signature has changed and now takes an object of callbacks as a second argument. See docs for new signature.")}const s=Xo.getPrimitive();let{boundsTraverseOrder:o,intersectsBounds:a,intersectsRange:l,intersectsTriangle:A}=e;if(l&&A){const f=l;l=(d,h,p,m,g)=>f(d,h,p,m,g)?!0:mk(d,h,i,A,p,m,s)}else l||(A?l=(f,d,h,p)=>mk(f,d,i,A,h,p,s):l=(f,d,h)=>h);let c=!1,u=0;for(const f of this._roots){if(Cg(f),c=gde(0,i,a,l,o,u),cy(),c)break;u+=f.byteLength}return Xo.releasePrimitive(s),c}bvhcast(e,t,r){let{intersectsRanges:i,intersectsTriangles:s}=r;const o=this.geometry.index,a=this.geometry.attributes.position,l=e.geometry.index,A=e.geometry.attributes.position;xf.copy(t).invert();const c=Xo.getPrimitive(),u=Xo.getPrimitive();if(s){let d=function(h,p,m,g,v,y,w,C){for(let b=m,E=m+g;bA1.intersectsBox(d),intersectsRange:(d,h,p,m,g,v)=>(l1.copy(v),l1.applyMatrix4(xf),e.shapecast({intersectsBounds:y=>l1.intersectsBox(y),intersectsRange:(y,w,C,b,E)=>i(d,h,y,w,m,g,b,E)}))});return Xo.releasePrimitive(c),Xo.releasePrimitive(u),f}intersectsBox(e,t){return Uc.set(e.min,e.max,t),Uc.needsUpdate=!0,this.shapecast({intersectsBounds:r=>Uc.intersectsBox(r),intersectsTriangle:r=>Uc.intersectsTriangle(r)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,r={},i={},s=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Uc.set(e.boundingBox.min,e.boundingBox.max,t),Uc.needsUpdate=!0;const a=this.geometry,l=a.attributes.position,A=a.index,c=e.attributes.position,u=e.index,f=Xo.getPrimitive(),d=Xo.getPrimitive();let h=uy,p=vde,m=null,g=null;i&&(m=yde,g=Bde);let v=1/0,y=null,w=null;return xf.copy(t).invert(),Wp.matrix.copy(xf),this.shapecast({boundsTraverseOrder:C=>Uc.distanceToBox(C),intersectsBounds:(C,b,E)=>E{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:E=>Wp.distanceToBox(E),intersectsBounds:(E,x,S)=>S{for(let S=E*3,M=(E+x)*3;S(Op.copy(e).clamp(c.min,c.max),Op.distanceToSquared(e)),intersectsBounds:(c,u,f)=>f{c.closestPointToPoint(e,Op);const f=e.distanceToSquared(Op);return f{fa(0,new Float32Array(r),vk),e.union(vk)}),e}}const c1=new l0,yk=new Le,wde=In.prototype.raycast;function Cde(n,e){if(this.geometry.boundsTree){if(this.material===void 0)return;yk.copy(this.matrixWorld).invert(),c1.copy(n.ray).applyMatrix4(yk);const t=this.geometry.boundsTree;if(n.firstHitOnly===!0){const r=gk(t.raycastFirst(c1,this.material),this,n);r&&e.push(r)}else{const r=t.raycast(c1,this.material);for(let i=0,s=r.length;i{const e=n.attributes.position,t=n.index,r=new ns,i=new z,s=new z,o=new z,a=[];for(let l=0;l{const e=n.geometry.clone();let t=[];if(Array.isArray(n.material))for(let i=0;i{n.isMesh&&(n.geometry.userData.faceNormals=null,n.geometry.dispose(),n.geometry.disposeBoundsTree(),n.parent&&n.parent.remove(n),n.userData.cancelMesh&&gB(n.userData.cancelMesh))},EH=n=>{var e,t;n.userData.cullingClone&&(gB(n.userData.cullingClone),n.userData.cullingClone=null,gB(n.userData.cullingCloneP),n.userData.cullingCloneP=null,gB(n.userData.cullingCloneN),n.userData.cullingCloneN=null,((e=n.userData)==null?void 0:e.clippedIndexGeometry)!=null&&(n.userData.clippedIndexGeometry=null),((t=n.userData)==null?void 0:t.origIndexBuffer)!=null&&(n.userData.origIndexBuffer=null))},Qde=async n=>{if(n==null){console.warn("Null parameter for meshes was provided. Skipping mesh culling.");return}if(!Array.isArray(n)){console.warn("No valid mesh array was provided. Skipping mesh culling.");return}if(n.length==0){console.warn("No mesh array with elements was provided. Skipping mesh culling.");return}const e=[];bg=n[0].parent,bg.lines!=null&&(bg.lines.forEach(i=>{i.visible=!1}),bg.lines.length=0),n.forEach(i=>{if(i.userData.cullLayer!=null){i.userData.origIndexBuffer==null&&(i.userData.origIndexBuffer=i.geometry.index.clone()),e[i.userData.cullLayer]==null&&(e[i.userData.cullLayer]={origMeshes:[],cloneMeshes:[],posMeshes:[],negMeshes:[],scaleMeshes:[],positionMeshes:[]}),i.userData.cullingClone==null&&(i.userData.cullingClone=_de(i),i.userData.cullingCloneP=i.userData.cullingClone.clone(),i.userData.cullingCloneN=i.userData.cullingClone.clone());const s=i.userData.cullingClone,o=i.userData.cullingCloneP,a=i.userData.cullingCloneN;o.material=Ede,a.userData.cancelMesh=o,a.material=Ude,o.userData.maxCullDistance=a.userData.maxCullDistance=i.userData.maxCullDistance,e[i.userData.cullLayer].origMeshes.push(i),e[i.userData.cullLayer].cloneMeshes.push(s),e[i.userData.cullLayer].posMeshes.push(o),e[i.userData.cullLayer].negMeshes.push(a),i.geometry.setIndex(i.userData.origIndexBuffer)}});for(let i=e.length-1;i>=0;i--)e[i]==null&&e.splice(i,1);let t=[];const r=[];for(let i=e.length-1;i>=0;i--){if(t.length!=0||e.length>=1)for(let s=0;s{i.geom.setIndex(i.index)})},Rde=n=>{let e=Ide,t=Fde;return n&&(isNaN(n)?Array.isArray(n)&&(isNaN(n[0])||(e=n[0]),isNaN(n[1])||(t=n[1])):e=n),[e,t]},Mde=(n,e,t,r,i,s,o=!1)=>{const a=[],l=Rde(s);let A=l[0],c=l[1];fy.far=A+c;for(let f=0;f=0;v--)A-g[v].distance>=g[v].object.userData.maxCullDistance&&g.splice(v,1);if(g.length===0){for(let v=0;v<3;v++)a.push(n[d+v]);break}else{const v=g.map(y=>y.object);for(let y=0;yy).length===0){for(let y=0;y<3;y++)a.push(n[d+y]);break}if(p===0)h=g.map(y=>y.object);else if(h=g.map(y=>{if(h.indexOf(y.object)!==-1)return y.object}),h=h.filter(y=>y),p===2&&h.filter(y=>y).length===0)for(let y=0;y<3;y++)a.push(n[d+y]);o&&Tde(u1,Gp.clone().multiplyScalar(-1),fy.far,16711680,bg)}}}const u=new Uint32Array(a);return new At(u,1,!1)};function Tde(n,e,t,r,i){i.lines==null&&(i.lines=[]);let s=new z;s.addVectors(n,e.clone().multiplyScalar(t));const o=[];o.push(n),o.push(s);const a=new Ht().setFromPoints(o),l=[];l.push(new Re(0)),l.push(new Re(16777215));let A=new Wl({color:r});var c=new kh(a,A);c.renderOrder=100,i.add(c),i.lines.push(c)}function UH(n){let e,t,r,i=0;for(let a=0;atypeof window>"u"?await Lde({meshes:e,atlasSize:t,mtoon:r,transparentMaterial:i,transparentTexture:s}):await Pde({backColor:n,meshes:e,atlasSize:t,mtoon:r,transparentMaterial:i,transparentTexture:s,twoSidedMaterial:o}),Lde=async({meshes:n,atlasSize:e,mtoon:t,transparentMaterial:r,transparentTexture:i})=>{const s=e,o=["diffuse"],a=[];n.forEach(E=>{const x=E.material;let S=a.find(M=>M.material===x);if(!S)a.push({material:x,mesh:E});else{const{dest:M}=K_({meshes:[S.mesh,E]});S.mesh.geometry=M}});const l=Object.fromEntries(o.map(E=>[E,SH({width:s,height:s,transparent:i})])),A=Math.floor(Math.sqrt(n.length)+1),c=s/A,u=new Map(a.map((E,x)=>{const S=new We(x%A,Math.floor(x/A)).multiplyScalar(1/A),M=new We(S.x+1/A,S.y+1/A);return[E.mesh,{min:S,max:M}]})),f={diffuse:["map"],normal:["normalMap"],orm:["ormMap","aoMap","roughnessMap","metalnessMap"]},d=[],h=[];a.forEach(E=>{const{min:x,max:S}=u.get(E.mesh);h.push(S),d.push(x)});const p=new We(Math.max(...h.map(E=>E.x)),Math.max(...h.map(E=>E.y))),m=new We(Math.min(...d.map(E=>E.x)),Math.min(...d.map(E=>E.y))),g=1/(p.x-m.x),v=1/(p.y-m.y),y=c*g,w=c*v,C=new Map(a.map(E=>{let{min:x,max:S}=u.get(E.mesh);return x.x=x.x*g,x.y=x.y*v,S.x=S.x*g,S.y=S.y*v,[E.mesh,{min:x,max:S}]}));a.forEach(E=>{const{material:x,mesh:S}=E,{min:M,max:Z}=C.get(S);o.forEach(F=>{const R=l[F];R.globalCompositeOperation="source-over";let k=rU(x,f[F].find(T=>rU(x,T)));if(k!==""&&k!==void 0)try{const T=new Uint8ClampedArray(k.data),V=new ImageData(T,y,w),O=document.createElement("canvas");O.width=y,O.height=w;const L=O.getContext("2d");L.putImageData(V,0,0),L.save(),R.drawImage(O,M.x*s,M.y*s,y,w)}catch(T){console.error("error",T)}else R.fillStyle=F==="diffuse"?`#${x.color.clone().getHexString()}`:F==="normal"?"#8080ff":F==="orm"?`#${new Re(x.aoMapIntensity,x.roughness,x.metalness).getHexString()}`:"#7F7F7F",R.fillRect(M.x*s,M.y*s,y,w)});const K=S.geometry,_=K.attributes.uv;if(_)for(let F=0;F<_.array.length;F+=2)_.array[F]=_A(_.array[F],0,1,M.x,Z.x),_.array[F+1]=_A(_.array[F+1],0,1,M.y,Z.y);const B=K.attributes.uv2;if(B)for(let F=0;F{const x=new ir(l[E].canvas);return x.flipY=!1,[E,x]})));return{bakeObjects:a,textures:b,uvs:C}},Pde=async({backColor:n,meshes:e,atlasSize:t,mtoon:r,transparentMaterial:i,transparentTexture:s,twoSidedMaterial:o})=>{Nde();const a=t,l=r?["diffuse"]:["diffuse","orm"],A=[];let c=null;e.forEach(_=>{_=_.clone();const B=_.material.length==null?_.material:_.material[0];r&&c==null&&B.type=="ShaderMaterial"&&(c=B.clone());let F=A.find(R=>{R.material});if(!F)A.push({material:B,mesh:_});else{const{dest:R}=K_({meshes:[F.mesh,_]});F.mesh.geometry=R}});const u=Object.fromEntries(l.map(_=>[_,SH({width:a,height:a,transparent:s&&_=="diffuse"})])),f=Math.floor(Math.sqrt(e.length)+1),d=a/f,h=new Map(A.map((_,B)=>{const F=new We(B%f,Math.floor(B/f)).multiplyScalar(1/f),R=new We(F.x+1/f,F.y+1/f);return[_.mesh,{min:F,max:R}]})),p={diffuse:["map"],normal:["normalMap"],orm:["ormMap","aoMap","roughnessMap","metalnessMap"]},m=[],g=[];A.forEach(_=>{const{min:B,max:F}=h.get(_.mesh);g.push(F),m.push(B)});const v=new We(Math.max(...g.map(_=>_.x)),Math.max(...g.map(_=>_.y))),y=new We(Math.min(...m.map(_=>_.x)),Math.min(...m.map(_=>_.y))),w=1/(v.x-y.x),C=1/(v.y-y.y),b=d*w,E=d*C,x=new Map(A.map(_=>{let{min:B,max:F}=h.get(_.mesh);return B.x=B.x*w,B.y=B.y*C,F.x=F.x*w,F.y=F.y*C,[_.mesh,{min:B,max:F}]}));A.forEach(_=>{const{material:B,mesh:F}=_,{min:R,max:k}=x.get(F);l.forEach(L=>{var oe;const U=u[L];U.globalCompositeOperation="source-over";let H,le=new Re(1,1,1);switch(L){case"diffuse":H=B.color||n,(oe=B.uniforms)!=null&&oe.litFactor?le=B.uniforms.litFactor.value:le=B.color;break;case"normal":H=new Re(8421631);break;case"orm":H=new Re(0,B.roughness,B.metalness);break;default:H=new Re(1,1,1);break}let N=kde(B,p[L].find(ie=>rU(B,ie)));const j=Dde(N,le,H,a,a,L=="diffuse"&&s);createImageBitmap(j).then(ie=>U.drawImage(ie,R.x*a,R.y*a,b,E))});const T=F.geometry.clone();F.geometry=T;const V=T.attributes.uv.clone();if(T.attributes.uv=V,V)for(let L=0;L{const B=new ir(u[_].canvas);return B.flipY=!1,[_,B]}))),M=o?pi:Vo;let Z;const K=i?"transparent":"opaque";return r?(Z=new mu({map:S.diffuse,transparent:i,side:M}),c==null&&(c=new dB),c.side=M,c.uniforms.map=S.diffuse,c.uniforms.shadeMultiplyTexture=S.diffuse,c.transparent=i,s&&!i&&(Z.alphaTest=.5,c.alphaTest=.5),Z.userData.vrmMaterial=c,Z.userData.shadeTexture=S.uniformColor,Z.name="mToon_"+K,Z.map.name=Z.name):(Z=new mu({map:S.diffuse,roughnessMap:S.orm,metalnessMap:S.orm,normalMap:S.normal,transparent:i,side:M}),s&&!i&&(Z.alphaTest=.5),Z.name="standard_"+K,Z.roughnessMap!=null&&(Z.roughnessMap.name=Z.name+"_orm"),Z.normalMap!=null&&(Z.normalMap.name=Z.name+"_normal")),{bakeObjects:A,material:Z}};function _H(n){const e=new Map;for(const r of n.skeleton.bones){const i=r.clone(!1);e.set(r,i)}n.skeleton.bones[0].traverse(r=>{if(r.type!=="Bone")return;const i=e.get(r);for(const s of r.children){const o=e.get(s);o&&i.add(o)}});const t=new hc(n.skeleton.bones.map(r=>e.get(r)));return t.boneInverses=n.skeleton.boneInverses,t.pose(),t}function QH(n,e){const t=new Map;new z(-1,1,-1),new Le,new z;let r=0;n.forEach(l=>{if(l.skeleton){var A=_H(l);const c=A.bones;A.bones.forEach((u,f)=>{var d;if(c.indexOf(u)!==-1){const h=t.get(u.name);if(h==null){const p={index:r,boneInverses:A.boneInverses[f],bone:u.clone(!1),parentName:((d=u.parent)==null?void 0:d.type)=="Bone"?u.parent.name:null};r++,t.set(u.name,p)}else u.userData.VRMcolliders!=null&&(h.bone.userData.VRMcolliders==null?h.bone.userData.VRMcolliders=u.userData.VRMcolliders:h.bone.userData.VRMcolliders=[...h.bone.userData.VRMcolliders,...u.userData.VRMcolliders])}})}});const i=[],s=[];[...t.values()].forEach(l=>{var A;if(i.push(l.bone),s.push(l.boneInverses),l.parentName!=null){const c=(A=t.get(l.parentName))==null?void 0:A.bone;c&&c.add(l.bone)}});const a=new hc(i,s);return a.bones.forEach(l=>{var c;const A=(c=l.userData)==null?void 0:c.vrm0RestPosition;A&&l.position.set(-A.x,A.y,-A.z),l.position.set(l.position.x*e,l.position.y*e,l.position.z*e)}),a}function Wde(n,e){if(!e.skeleton)return;const t=new Map;if(e.skeleton){e.skeleton.bones.forEach((o,a)=>{const l=n.bones.filter(c=>c.name===o.name),A=l.length>0?n.bones.indexOf(l[0]):-1;t.set(a,A)});const r=[],i=e.geometry.attributes.skinIndex.array;for(let o=0;oe.indexOf(t)===r)}function Ode(n){const t=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array].filter(r=>n.constructor===r);return t.length&&t[0]||null}function Zw(n,e){const t=[];for(let s=0;ss.name===r.name);return i?t.bones.indexOf(i):-1}async function Jde(n,e){const{scale:t,isVrm0:r}=e,i=[],s=[];Ih(n,"SkinnedMesh").forEach(A=>{const c=A.clone();i.push(c),Array.isArray(A.material)?s.push(...A.material):s.push(A.material)});const a=QH(i,t),l=new kt;return l.name="AvatarRoot",i.forEach(A=>{var b;const c=new Ht,u={};for(const E in A.geometry.attributes){const x=A.geometry.attributes[E];u[E]=x.clone()}if((b=A.userData)!=null&&b.isVRM0)for(let E=0;E[E,E.geometry.morphAttributes])),h=new Map([A].map(E=>[E,E.morphTargetDictionary||{}]));if(f.morphAttributes=MH({meshes:[A],sourceMorphAttributes:d,sourceMorphTargetDictionaries:h,destMorphTargetDictionary:f.morphTargetDictionary,scale:t},r),r)for(let E=0;Ed.name===e.userData.boneName),s=e.userData.globalPosition,o=e.userData.globalScale||new z(1,1,1),a=e.userData.globalRotationMatrix;t.add(r.bones[0]);const l=[],A=[],c=t.geometry.attributes.position.array,u=new z,f=e.userData.isVRM0?-1:1;for(let d=0;d0){const{bakeObjects:M,material:Z}=await Vde({transparentColor:t,atlasSize:x.size,meshes:S,mtoon:x.isMtoon,transparentMaterial:x.transparentMaterial,transparentTexture:y,twoSidedMaterial:u}),K=M.map(T=>T.mesh),_=[];K.forEach(T=>{T.type=="Mesh"&&(T=zde(C,T)),_.push(T);const V=T.geometry,O=V.index.array,L=RH(T.geometry.index.array),U=[];for(let N=0;N{const o=n.find(l=>e.get(l).hasOwnProperty(i)),a=o.morphTargetDictionary[i];r[s]=o.morphTargetInfluences[a]}),r}function Kde({sourceAttributes:n}){const e=new Set,t=Array.from(n.values());t.forEach(i=>{Object.keys(i).forEach(s=>e.add(s))});const r={};return Array.from(e.keys()).map(i=>{r[i]=UH(t.map(s=>s[i]).flat().filter(s=>s!==void 0))}),r}function jde({sourceMorphTargetDictionaries:n}){const e=new Set;Array.from(n.values()).forEach(i=>{Object.keys(i).forEach(s=>e.add(s))});const r={};return Array.from(e.keys()).map((i,s)=>{r[i]=s}),r}function MH({meshes:n,sourceMorphTargetDictionaries:e,sourceMorphAttributes:t,destMorphTargetDictionary:r,scale:i},s=!1){const o=new Set;Array.from(t.values()).forEach(u=>{Object.keys(u).forEach(f=>o.add(f))});const l=Array.from(o),A={};l.forEach(u=>{A[u]=[],Object.entries(r).forEach(([f,d])=>{A[u][d]=[],n.forEach(h=>{let p;const m=e.get(h);if(m.hasOwnProperty(f)&&h.geometry.morphAttributes[u]){const g=m[f];p=h.geometry.morphAttributes[u][g]}else{const g=h.geometry.attributes[u],v=new g.array.constructor(new Array(g.array.length).fill(0));p=new At(v,g.itemSize,g.normalized)}A[u][d].push(p)})})});const c={};return l.forEach(u=>{c[u]=[];for(let f=0;f{const i=r.geometry.index;for(var s=0;s{var l;if(r+=a.geometry.attributes.uv.count,(l=a.userData)!=null&&l.isVRM0)for(let A=0;A[a,a.geometry.attributes])),morphAttributes:new Map(n.map(a=>[a,a.geometry.morphAttributes])),morphTargetDictionaries:new Map(n.map(a=>[a,a.morphTargetDictionary||{}])),morphTargetInfluences:new Map(n.map(a=>[a,a.morphTargetInfluences||[]]))},s={attributes:null,morphTargetDictionary:null,morphAttributes:null,morphTargetInfluences:null,index:null,animations:{}};s.attributes=Kde({sourceAttributes:i.attributes});const o=jde({sourceMorphTargetDictionaries:i.morphTargetDictionaries});return s.morphTargetDictionary=o,s.morphAttributes=MH({meshes:n,sourceMorphAttributes:i.morphAttributes,sourceMorphTargetDictionaries:i.morphTargetDictionaries,destMorphTargetDictionary:o,scale:e},t),s.morphTargetInfluences=Xde({meshes:n,sourceMorphTargetDictionaries:i.morphTargetDictionaries,destMorphTargetDictionary:o}),s.index=$de({meshes:n}),s.animations={},{source:i,dest:s}}function Yt(n){return n==null?[]:Array.isArray(n)?n:[n]}async function qde(n,e){const r=await new Nu().load(e);r.encoding=ht,r.flipY=!1,n.traverse(i=>{if(i instanceof In){const s=Array.isArray(i.material)?i.material:[i.material];for(let o=0;o{const e=[];for(const t in n){const r=n[t].vrm;if(r){const i=r.data.cullingLayer;i>=0&&r.data.cullingMeshes.map(s=>{s.userData.cullLayer=i,s.userData.cullDistance=r.data.cullingDistance,s.userData.maxCullDistance=r.data.maxCullingDistance,e.push(s)})}}Qde(e)};function nhe(n){const e=[],t=[],r=[],i=[];let s=!1;return n.forEach(o=>{var A;const l=Yt(o.material)[0];l.type=="ShaderMaterial"?l.transparent==!0?(i.push(o),s=!0):(r.push(o),((A=l.uniforms.alphaTest)==null?void 0:A.value)!=0&&(s=!0)):l.transparent==!0?(t.push(o),s=!0):(e.push(o),l.alphaTest!=0&&(s=!0))}),{stdMesh:e,stdTranspMesh:t,mToonMesh:r,mToonTranspMesh:i,requiresTransparency:s}}function rhe(n){const e=[],t=[],r=[],i=[],s=[],o=[];return n.forEach(a=>{Yt(a.material).forEach(A=>{A.type=="ShaderMaterial"?A.transparent==!0?o.push(A):A.uniforms.alphaTest.value!=0?s.push(A):i.push(A):A.transparent==!0?r.push(A):A.alphaTest!=0?t.push(A):e.push(A)})}),{stdMats:e,stdCutoutpMats:t,stdTranspMats:r,mToonMats:i,mToonCutoutMats:s,mToonTranspMats:o}}function wk(n,e){n.data==null?n.data=e:n.data={...n.data,...e}}function ihe(n,e){if(n.data!=null)return n.data[e]}function she(n){const e=ihe(n,"cullingMeshes");e&&(e.forEach(t=>{EH(t)}),n.data.cullingMeshes=null)}function Cn(n){switch(n){case 1:return 128;case 2:return 256;case 3:return 512;case 4:return 1024;case 5:return 2048;case 6:return 4096;case 7:return 8192;case 8:return 16384;default:return 4096}}function ohe(n){const e=n.scene;she(n),e.traverse(t=>{t.material&&iU(t.material),t.geometry&&(EH(t),t.geometry.dispose(),t.geometry.disposeBoundsTree())}),e.parent&&e.parent.remove(e),Xh.deepDispose(e),n.expressionManager&&n.expressionManager.expressions.forEach(t=>{t._binds&&t._binds.forEach(r=>{r.primitives&&r.primitives.forEach(i=>{i.geometry.dispose(),i.material&&iU(i.material)})})});for(const t in n)n[t]=null}const iU=n=>{var e,t,r,i,s,o;if(n.length)for(let a=0;a{const t=new Blob([n],{type:"text/plain"}),r=document.createElement("a");r.href=window.URL.createObjectURL(t),r.download=e+".txt",document.body.appendChild(r),r.click(),document.body.removeChild(r)},TH=n=>{let e,t,r=0;return Array.isArray(n)?(e=n[0]||0,t=n[1]||0,r=n[2]||0):(typeof n=="string"||n instanceof String)&&n.split("-").forEach(s=>{switch(s=s.toLowerCase(),s){case"left":e=-1;break;case"right":e=1;break;case"bottom":case"down":t=-1;break;case"top":case"up":t=1;break;case"back":case"backward":r=-1;break;case"front":case"forward":r=1;break;default:console.warn("unkown cameraPosition name: "+s+" in: "+n+". Please use left, right, bottom, top, back or front");break}}),new z(e,t,r)},lhe=n=>{var t,r,i,s,o,a,l,A,c,u,f;const e=n.humanoid.humanBones;e.upperChest==null&&e.neck.node.parent!=e.chest&&(e.neck.node.parent!=e.chest.node?e.upperChest={node:e.neck.node.parent}:e.upperChest!=null&&(e.upperChest={node:e.neck.node.parent},e.chest={node:e.neck.node.parent.parent})),e.leftShoulder==null&&(e.leftUpperArm.node.parent!=((t=e.chest)==null?void 0:t.node)&&e.leftUpperArm.node.parent!=((r=e.upperChest)==null?void 0:r.node)&&e.leftUpperArm.node.parent!=((i=e.spine)==null?void 0:i.node)&&e.leftUpperArm.node.parent!=((s=e.neck)==null?void 0:s.node)&&e.leftUpperArm.node.parent!=((o=e.head)==null?void 0:o.node),e.leftShoulder={node:e.leftUpperArm.node.parent}),e.rightShoulder==null&&(e.rightUpperArm.node.parent!=((a=e.chest)==null?void 0:a.node)&&e.rightUpperArm.node.parent!=((l=e.upperChest)==null?void 0:l.node)&&e.rightUpperArm.node.parent!=((A=e.spine)==null?void 0:A.node)&&e.rightUpperArm.node.parent!=((c=e.neck)==null?void 0:c.node)&&e.rightUpperArm.node.parent!=((u=e.head)==null?void 0:u.node),e.rightShoulder={node:e.rightUpperArm.node.parent});for(let d in Lm)d=d.charAt(0).toLowerCase()+d.slice(1),(f=e[d])!=null&&f.node&&(e[d].node.name=d)};function NH({candidates:n,predicate:e}){if(!n.length)return null;const t=n.shift();return e(t)?t:(n=n.concat(t.children),NH({candidates:n,predicate:e}))}function DH(n,e){return NH({candidates:[n],predicate:t=>t.name===e})}function kH({candidates:n,predicate:e,results:t=[]}){if(!n.length)return t;const r=n.shift();return e(r)&&t.push(r),n=n.concat(r.children),kH({candidates:n,predicate:e,results:t})}function Ih(n,e){return kH({candidates:[n],predicate:t=>Yt(e).includes(t.type)})}function Ahe(n,e,t){const r=Ih(n,"SkinnedMesh");return{humanBones:uhe(r[0]),materials:n.userData.atlasMaterial,meta:che(e,t)}}function che(n,e){return e=e||{},{...{authors:["CharacterStudio"],metaVersion:"1",version:"v1",name:n,licenseUrl:"https://vrm.dev/licenses/1.0/",commercialUssageName:"personalNonProfit",contactInformation:"https://m3org.com/",allowExcessivelyViolentUsage:!1,allowExcessivelySexualUsage:!1,allowPoliticalOrReligiousUsage:!1,allowAntisocialOrHateUsage:!1,creditNotation:"required",allowRedistribution:!1,modification:"prohibited"},...e}}function uhe(n){const e={};return n.skeleton.bones.map(t=>{for(const r in Lm)if(Lm[r]===t.name){e[t.name]={node:t};break}}),e}const fhe={mixamorigHips:"hips",mixamorigSpine:"spine",mixamorigSpine1:"chest",mixamorigSpine2:"upperChest",mixamorigNeck:"neck",mixamorigHead:"head",mixamorigLeftShoulder:"leftShoulder",mixamorigLeftArm:"leftUpperArm",mixamorigLeftForeArm:"leftLowerArm",mixamorigLeftHand:"leftHand",mixamorigLeftHandThumb1:"leftThumbMetacarpal",mixamorigLeftHandThumb2:"leftThumbProximal",mixamorigLeftHandThumb3:"leftThumbDistal",mixamorigLeftHandIndex1:"leftIndexProximal",mixamorigLeftHandIndex2:"leftIndexIntermediate",mixamorigLeftHandIndex3:"leftIndexDistal",mixamorigLeftHandMiddle1:"leftMiddleProximal",mixamorigLeftHandMiddle2:"leftMiddleIntermediate",mixamorigLeftHandMiddle3:"leftMiddleDistal",mixamorigLeftHandRing1:"leftRingProximal",mixamorigLeftHandRing2:"leftRingIntermediate",mixamorigLeftHandRing3:"leftRingDistal",mixamorigLeftHandPinky1:"leftLittleProximal",mixamorigLeftHandPinky2:"leftLittleIntermediate",mixamorigLeftHandPinky3:"leftLittleDistal",mixamorigRightShoulder:"rightShoulder",mixamorigRightArm:"rightUpperArm",mixamorigRightForeArm:"rightLowerArm",mixamorigRightHand:"rightHand",mixamorigRightHandPinky1:"rightLittleProximal",mixamorigRightHandPinky2:"rightLittleIntermediate",mixamorigRightHandPinky3:"rightLittleDistal",mixamorigRightHandRing1:"rightRingProximal",mixamorigRightHandRing2:"rightRingIntermediate",mixamorigRightHandRing3:"rightRingDistal",mixamorigRightHandMiddle1:"rightMiddleProximal",mixamorigRightHandMiddle2:"rightMiddleIntermediate",mixamorigRightHandMiddle3:"rightMiddleDistal",mixamorigRightHandIndex1:"rightIndexProximal",mixamorigRightHandIndex2:"rightIndexIntermediate",mixamorigRightHandIndex3:"rightIndexDistal",mixamorigRightHandThumb1:"rightThumbMetacarpal",mixamorigRightHandThumb2:"rightThumbProximal",mixamorigRightHandThumb3:"rightThumbDistal",mixamorigLeftUpLeg:"leftUpperLeg",mixamorigLeftLeg:"leftLowerLeg",mixamorigLeftFoot:"leftFoot",mixamorigLeftToeBase:"leftToes",mixamorigRightUpLeg:"rightUpperLeg",mixamorigRightLeg:"rightLowerLeg",mixamorigRightFoot:"rightFoot",mixamorigRightToeBase:"rightToes"};function VH(n,e,t){var p;const r=vu.findByName(n,"mixamo.com");if(r==null)return null;const i=[],s=new tt,o=new tt,a=new tt,l=new z,A=e.getObjectByName("mixamorigHips").position.y,c=(p=t.humanoid)==null?void 0:p.getNormalizedBoneNode("hips").getWorldPosition(l).y,u=t.scene.getWorldPosition(l).y,d=Math.abs(c-u)/A;return r.tracks.forEach(m=>{const g=m.clone(),v=g.name.split("."),y=v[0],C=fhe[y],b=e.getObjectByName(y);if(C!=null){const E=v[1];if(b.getWorldQuaternion(s).invert(),b.parent.getWorldQuaternion(o),g instanceof Qa){for(let x=0;x{g.values[Z+x]=M})}i.push(new Qa(`${C}.${E}`,g.times,g.values.map((x,S)=>{var M;return((M=t.meta)==null?void 0:M.metaVersion)==="0"&&S%2===0?-x:x})))}else if(g instanceof ec){const x=g.values.map((S,M)=>{var Z;return(((Z=t.meta)==null?void 0:Z.metaVersion)==="0"&&M%3!==1?-S:S)*d});i.push(new ec(`${C}.${E}`,g.times,x))}}}),new vu("vrmAnimation",r.duration,i)}const dhe=new Ese,hhe=new x_,h1=.2,phe=n=>Math.floor(Math.random()*n);class Ck{constructor(e,t,r,i,s,o,a){var l,A,c,u;this.mixer=new wie(t),this.actions=[],this.to=null,this.from=null,this.vrm=r,this.animationManager=e,this.mixamoModel=null,this.fadeOutActions=null,this.newAnimationWeight=1,this.neckBone=(A=(l=r==null?void 0:r.humanoid)==null?void 0:l.humanBones)==null?void 0:A.neck,this.spineBone=(u=(c=r==null?void 0:r.humanoid)==null?void 0:c.humanBones)==null?void 0:u.spine,this.timeScale=1,i&&(this.setAnimations(i,null,null,a),this.to=this.actions[s],o!=-1&&(this.from=this.actions[o],this.from.reset(),this.from.time=e.getFromActionTime(),this.from.play(),this.to.weight=e.getWeightIn(),this.from.weight=e.getWeightOut()),this.actions[s].reset(),this.actions[s].time=e.getToActionTime(),this.actions[s].play())}setTimeScale(e){this.timeScale=e,this.actions.forEach(t=>{t.timeScale=e})}setMouseLookEnabled(e){this.setAnimations(this.animations,this.mixamoModel,e)}setAnimations(e,t=null,r=null,i=!1){if(r=r??this.animationManager.mouseLookEnabled,this.animations=e,t!=null){if(this.vrm!=null){const s=VH(e,t,this.vrm);s&&(e=[s],this.mixamoModel=t)}}else{const s=[];e.forEach(o=>{s.push(o.clone())}),e=s}if(r&&e[0].tracks.map((s,o)=>{(s.name==="neck.quaternion"||s.name==="spine.quaternion")&&e[0].tracks.splice(o,1)}),i){this.actions.forEach(s=>{s.weight=0,s.stop()}),this.actions=[],this.newAnimationWeight=1;for(let s=0;s{r.weight=1-this.newAnimationWeight}),this.newAnimationWeight>=1&&(this.newAnimationWeight=1,this.fadeOutActions.forEach(r=>{r.weight=0,r.stop()}),this.fadeOutActions=null),this.actions.forEach(r=>{r.weight=this.newAnimationWeight})),this.from!=null&&(this.from.weight=t),this.to!=null&&(this.to.weight=e),this.mixer.update(1/30)}reset(){this.mixer.setTime(0),this.to.paused=!0}resume(){this.to.paused=!1}setTime(e){this.mixer.setTime(e)}dispose(){this.animationManager.disposeAnimation(this)}}class ghe{constructor(){this.animationPaths=null,this.lastAnimID=null,this.mainControl=null,this.animationControl=null,this.animations=null,this.paused=!1,this.scale=1,this.curLoadAnim=0,this.currentAnimationName="",this.weightIn=NaN,this.weightOut=NaN,this.lastAnimID=-1,this.curAnimID=0,this.animationControls=[],this.started=!1,this.mouseLookEnabled=!1,this.mixamoModel=null,this.mixamoAnimations=null,this.currentClip=null,setInterval(()=>{this.update()},1e3/30)}enableMouseLook(e){this.mouseLookEnabled=e,this.animationControls.forEach(t=>{t.setMouseLookEnabled(e)})}setScale(e){this.scale=e}async loadAnimation(e,t,r=0,i=!0,s="",o=""){const a=s+(s!=""?"/":"")+Yt(e)[0];o=o==""?rc(a):o,this.currentAnimationName=o;const A=await(i?dhe:hhe).loadAsync(a);A.scale.set(this.scale,this.scale,this.scale),this._scaleOffsetHips(A.animations);const c=vu.findByName(A.animations,"mixamo.com");c!=null?(this.mixamoModel=A.clone(),this.mixamoAnimations=A.animations,this.currentClip=c):(this.mixamoModel=null,this.animations=A.animations,this.currentClip=A.animations[0]),this.mainControl==null&&(this.curAnimID=0,this.lastAnimID=-1,this.mainControl=new Ck(this,A,null,A.animations,this.curAnimID,this.lastAnimID,t),this.animationControls.push(this.mainControl)),this.animationControls.forEach(u=>{u.setAnimations(A.animations,this.mixamoModel,this.mouseLookEnabled,t)}),this.setTime(r),t?this.pause():this.play()}getCurrentClip(){return this.currentClip}getCurrentAnimationName(){return this.currentAnimationName}clearCurrentAnimations(){this.animationPaths=null,this.animationControls=[],this.mainControl=null}storeAnimationPaths(e,t){const r=Yt(e);this.animationPaths=r.map(i=>`${t}/${i}`)}loadNextAnimation(){this.curLoadAnim==this.animationPaths.length-1?this.curLoadAnim=0:this.curLoadAnim++,this.loadAnimation(this.animationPaths[this.curLoadAnim])}loadPreviousAnimation(){this.curLoadAnim==0?this.curLoadAnim=this.animationPaths.length-1:this.curLoadAnim--,this.loadAnimation(this.animationPaths[this.curLoadAnim])}enableScreenshot(){this.animationControls.forEach(e=>{e.reset()})}disableScreenshot(){this.animationControls.forEach(e=>{e.resume()})}_scaleOffsetHips(e){e.forEach(t=>{for(let r=0;rr.vrm===e);t!==-1&&this.animationControls.splice(t,1)[0].dispose()}getFromActionTime(){return this.mainControl.actions[this.lastAnimID].time}getToActionTime(){return this.mainControl?this.mainControl.actions[this.curAnimID].time:.1}getWeightIn(){return this.weightIn}getWeightOut(){return this.weightOut}disposeAnimation(e){if(e!=null){const t=this.animationControls.indexOf(e);t!=-1&&this.animationControls.splice(t,1)}}dispose(){this.animationControls.forEach(e=>{e.dispose()})}animRandomizer(e){setTimeout(()=>{this.lastAnimID=this.curAnimID,this.curAnimID=phe(this.animations.length),this.curAnimID!=this.lastAnimID&&this.animationControls.forEach(t=>{t.from=t.actions[this.lastAnimID],t.to=t.actions[this.curAnimID],this.weightIn=0,this.weightOut=1,t.to.play(),t.to.reset()}),this.animRandomizer(this.animations[this.curAnimID].duration-h1)},e*1e3)}pause(){this.paused=!0}play(){this.paused=!1}isPaused(){return this.paused}setTime(e){this.mainControl&&this.animationControls.forEach(t=>{t.setTime(e)})}setSpeed(e){this.mainControl&&this.animationControls.forEach(t=>{t.setTimeScale(e)})}update(){this.mainControl&&!this.paused&&(this.animationControls.forEach(e=>{e.update(this.weightIn,this.weightOut)}),this.weightIn<1?this.weightIn+=1/(30*h1):this.weightIn=1,this.weightOut>0?this.weightOut-=1/(30*h1):this.weightOut=0)}}const bk={uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:` varying vec2 vUv; @@ -4214,7 +4214,7 @@ void main() { texel.rgb = pow(texel.rgb, vec3(1.0 / 2.2)); gl_FragColor = texel; } - `})}}const Jw=4096,Zp=new z;class bhe{constructor(e,t,r){const i=new c0({preserveDrawingBuffer:!0,antialias:!1,alpha:!0});this.pixelSize=r,this.domElement=i.domElement;const s=new We(Jw,Jw);i.setClearColor(0,0),i.outputEncoding=ps,i.setSize(s.x,s.y),i.setPixelRatio(window.devicePixelRatio);let o=s.clone().divideScalar(r);o.x|=0,o.y|=0;const a=new yhe(i);a.addPass(new Bhe(e,t)),this._renderPixelPass=new whe(o,e,t),this._pixelPass=new Che(o),a.addPass(this._renderPixelPass),a.addPass(this._pixelPass),this.renderer=i,this.composer=a}setSize(e,t){let i=new We(e,t).clone().divideScalar(this.pixelSize);i.x|=0,i.y|=0,this.renderer.setSize(e,t),this._renderPixelPass.setResolution(i),this._pixelPass.setResolution(i)}setPixelSize(e){this.pixelSize=e}render(){this.composer.render()}}class xhe{constructor(e,t){this.renderer=new c0({preserveDrawingBuffer:!0,antialias:!0,alpha:!0}),this.renderer.setClearAlpha(0),this.renderer.premultipliedAlpha=!1,this.scene=t,this.characterManager=e,this.renderer.outputEncoding=ht,this.renderer.setSize(Jw,Jw),this.camera=new Mr(30,1,.1,1e3),this.textureLoader=new Nu,this.sceneBackground=new Re(.1,.1,.1),this.sceneBackgroundAlpha=1,this.frameOffset={min:.2,max:.2},this.usesBackgroundImage=!1,this.backgroundMaterial=new Qi({color:16777215,transparent:!0,opacity:.5});const r=new Ru(1e3,1e3),i=new In(r,this.backgroundMaterial);i.renderOrder=-1,this.backgroundPlane=i,this.pixelRenderer=new bhe(t,this.camera,20),this.boneOffsets={head:null,chest:null,hips:null,leftUpperLeg:null,leftFoot:null,rightUpperLeg:null,rightFoot:null}}setScene(e){this.scene=e}setupCamera(e,t,r=30){this.camera.position.copy(e),this.camera.lookAt(t),this.camera.fov=r}_getCharacterMinMax(){let e=Number.POSITIVE_INFINITY,t=Number.NEGATIVE_INFINITY;return this.characterManager.characterModel.traverse(r=>{r.geometry&&(r.geometry.computeBoundingBox(),r.geometry.boundingBox&&(r.geometry.boundingBox.applyMatrix4(r.matrixWorld),r.geometry.boundingBox.min.yt&&(t=r.geometry.boundingBox.max.y)))}),{minY:e,maxY:t}}frameCloseupShot(){this.frameShot("head","head")}frameMediumShot(){this.frameShot("chest","head")}frameCowboyShot(){this.frameShot("hips","head")}frameFullShot(){this.frameShot("leftFoot","head")}frameShot(e,t,r=null,i=!1,s=!0){const o=this._getBoneWorldPositionWithOffset(e,i),a=this._getBoneWorldPositionWithOffset(t,s);o.y-=this.frameOffset.max,a.y+=this.frameOffset.min,r=r||new z(0,0,0),this.positionCameraBetweenPoints(o,a,r)}setBottomFrameOffset(e){this.frameOffset.min=e}setTopFrameOffset(e){this.frameOffset.max=e}_setBonesOffset(e){for(const t in this.boneOffsets){const r=this._getMinMaxOffsetByBone(this.characterManager.characterModel,t,e);this.boneOffsets[t]=r}}_getBoneWorldPositionWithOffset(e,t){const r=this._getFirstBoneWithName(e);if(!r||!this.boneOffsets[e])return new z;const i=new z;r.getWorldPosition(i);const s=t?this.boneOffsets[e].max:this.boneOffsets[e].min;return i.y+=s.y,i}_getBoneWorldPosition(e){const t=this._getFirstBoneWithName(e);return t!=null?new z().setFromMatrixPosition(t.matrixWorld):(console.warn(`Bone with name '${e}' not found in one of the skinned meshes.`),new z(0,0,0))}_getFirstBoneWithName(e){let t=null;return this.characterManager.characterModel.traverse(r=>{if(r instanceof qA){if(!r.geometry){console.error("Invalid skinned mesh found in children.");return}const i=r.skeleton.bones.findIndex(s=>s.name===e);if(i!==-1){t=r.skeleton.bones[i];return}}}),t}setCameraFrameWithName(e,t){switch(e.toLowerCase()){case"fullshot":this.frameShot("leftFoot","head",t);break;case"cowboyshot":this.frameShot("hips","head",t);break;case"mediumshot":this.frameShot("chest","head",t);break;case"mediumcloseup":case"mediumcloseupshot":this.frameShot("chest","head",t,!0);break;case"closeup":case"closeupshot":this.frameShot("head","head",t);break;default:console.warn("unkown cameraFrame: "+e+". Please use fullShot, cowboyShot, mediumShot, mediumCloseup or closeup"),this.frameShot("leftFoot","head",t);break}}_getMinMaxOffsetByBone(e,t,r){if(!e||!e.traverse)return console.error("Invalid parent object provided."),null;const i=new z(1/0,1/0,1/0),s=new z(-1/0,-1/0,-1/0);return e.traverse(async o=>{if(o instanceof qA){const a=this._saveBonesPos(o.skeleton),l=d=>new Promise(h=>setTimeout(h,d));if(o.skeleton.pose(),await l(10),!o.geometry){console.error("Invalid skinned mesh found in children.");return}const A=o.skeleton.bones.findIndex(d=>d.name===t);if(A===-1){console.error(`Bone with name '${t}' not found in one of the skinned meshes.`);return}const c=o.geometry.getAttribute("position"),u=o.geometry.getAttribute("skinWeight"),f=o.geometry.getAttribute("skinIndex");for(let d=0;d=r){const g=o.skeleton.bones[A],v=new z().setFromMatrixPosition(g.matrixWorld),y=h.clone().sub(v);i.min(y),s.max(y)}}this._restoreSavedPose(a,o.skeleton)}}),{min:i,max:s}}_saveBonesPos(e){let t=[];return e.bones.forEach(r=>{t.push({position:r.position.clone(),rotation:r.rotation.clone(),scale:r.scale.clone()})}),t}_restoreSavedPose(e,t){e&&t.bones.forEach((r,i)=>{r.position.copy(e[i].position),r.rotation.copy(e[i].rotation),r.scale.copy(e[i].scale)})}positionCameraBetweenPoints(e,t,r,i=30){const s=new ws;s.expandByPoint(e),s.expandByPoint(t),this.camera.fov=i;const o=this.camera.fov*(Math.PI/180),l=s.getSize(new z).length()/(2*Math.tan(o/2));s.getCenter(Zp),this.camera.position.copy(Zp),r.y*=.5,this.camera.lookAt(Zp.clone().sub(r));const A=new z;this.camera.getWorldDirection(A),this.camera.position.addScaledVector(A,-l),this.camera.updateProjectionMatrix()}setCamera(e,t,r=30){this.camera.position.copy(e),this.camera.fov=r,Zp.set(0,0,-1),this.cameraDir=Zp.applyQuaternion(this.camera.quaternion),this.cameraDir.normalize(),this.camera.position.x-=this.cameraDir.x*t,this.camera.position.z-=this.cameraDir.z*t}setBackground(e){if(Array.isArray(e)){const t=e[3]==null?1:e[3];this.setBackgroundColor(e[0],e[1],e[2],t)}else this.setBackgroundImage(e)}setBackgroundColor(e,t,r,i){const s=new Re(e,t,r,i);this.sceneBackground=s,i==null&&(i=1),i>1&&(i=1),i<0&&(i=0),this.sceneBackgroundAlpha=i,this.backgroundMaterial.color=s,this.usesBackgroundImage=!1}setBackgroundImage(e){return new Promise(async(t,r)=>{try{const i=await this.texureLoader.load(e);i&&(i.wrapS=i.wrapT=hs,this.sceneBackground=i,this.usesBackgroundImage=!0,this.sceneBackgroundAlpha=1,t())}catch(i){console.error("Error loading background image: ",i),r(i)}})}_setBackground(){if(this.usesBackgroundImage==!1&&this.sceneBackgroundAlpha!=1)if(this.sceneBackgroundAlpha==0)this.scene.background=null;else{this.scene.background=null,this.scene.add(this.backgroundPlane),this.backgroundPlane.position.copy(this.camera.position);var e=new z(0,0,-1);e.applyQuaternion(this.camera.quaternion);var t=100;this.backgroundPlane.position.addScaledVector(e,t),this.backgroundPlane.lookAt(this.camera.position)}else this.scene.background=this.sceneBackground}_restoreBackground(){this.scene.background=null,this.usesBackgroundImage==!1&&this.sceneBackgroundAlpha!=1&&this.scene.remove(this.backgroundPlane)}_createImage(e,t,r=!1){const i=e/t;this.renderer.setSize(e,t);const s="image/png";this.camera.aspect=i,this.camera.updateProjectionMatrix();const o=r?this.pixelRenderer:this.renderer;try{this._setBackground(),o.render(this.scene,this.camera);let a=o.domElement.toDataURL(s);return this._restoreBackground(),a}catch(a){return console.error(a),null}}savePixelScreenshot(e,t,r,i){this.pixelRenderer.setPixelSize(i),this.pixelRenderer.setSize(t,r);const s=this._createImage(t,r,!0),o="image/octet-stream",a="image/png";this.saveFile(s.replace(a,o),e+".png")}saveScreenshot(e,t,r){const i=this._createImage(t,r),s="image/octet-stream",o="image/png";this.saveFile(i.replace(o,s),e+".png")}getScreenshotImage(e,t){const r=this._createImage(e,t),i=new Image;return i.src=r,i}getScreenshotTexture(e,t){const r=this.getScreenshotImage(e,t),i=new ir(r);return i.needsUpdate=!0,i}getScreenshotBlob(e,t){const r=this._createImage(e,t),i=hJ.Buffer.from(r.replace(/^data:image\/\w+;base64,/,""),"base64");return new Blob([i],{type:"image/jpeg"})}saveFile(e,t){const r=document.createElement("a");typeof r.download=="string"?(document.body.appendChild(r),r.download=t,r.href=e,r.click(),document.body.removeChild(r)):window.open(e,"_blank").document.write(""+t+"")}}const Ihe=2;class Fhe{constructor(e=.5,t=.5,r=1,i=5){this.vrmBlinkers=[],this.mode="ready",this.clock=new xZ,this.closeTime=e,this.openTime=t,this.continuity=r,this.randomness=i,this._eyeOpen=1,this._blinkCounter=0,this.isTakingScreenShot=!1,this.update()}addVRM(e){this.vrmBlinkers.push(e)}removeVRM(e){const t=this.vrmBlinkers.indexOf(e);t!==-1&&this.vrmBlinkers.splice(t,1)}enableScreenshot(){this.isTakingScreenShot=!0,this._eyeOpen=Ihe,this._updateBlinkers()}disableScreenshot(){this.isTakingScreenShot=!1}update(){setInterval(()=>{if(this.isTakingScreenShot)return;const e=this.clock.getDelta();switch(this.mode){case"closing":this._eyeOpen>0?this._eyeOpen-=e/this.closeTime:(this._eyeOpen=0,this.mode="open"),this._updateBlinkers();break;case"open":this._eyeOpen<1?this._eyeOpen+=e/this.openTime:(this._eyeOpen=1,this.mode="ready"),this._updateBlinkers();break;case"ready":this._blinkCounter+=e,this._blinkCounter>=this.continuity&&(Math.floor(Math.random()*this.randomness)===0&&(this.mode="closing"),this._blinkCounter=0);break}},1e3/30)}_updateBlinkers(){this.vrmBlinkers.forEach(e=>{e.expressionManager.setValue(ci.Blink,1-this._eyeOpen),e.expressionManager.update()})}}var Nn;(function(n){n[n.ARRAY_BUFFER=34962]="ARRAY_BUFFER",n[n.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",n[n.BYTE=5120]="BYTE",n[n.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",n[n.SHORT=5122]="SHORT",n[n.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",n[n.UNSIGNED_INT=5125]="UNSIGNED_INT",n[n.FLOAT=5126]="FLOAT",n[n.LINEAR=9729]="LINEAR",n[n.REPEAT=10497]="REPEAT"})(Nn||(Nn={}));const sU="blend_",Fk="vrmColliderSphere";function Ehe(n){return{title:n.name,version:"v0",author:n.authors[0]||"",contactInformation:n.contactInformation,allowedUserName:n.allowedUserName,violentUssageName:n.allowExcessivelyViolentUsage?"Allow":"Disallow",sexualUssageName:n.allowExcessivelySexualUsage?"Allow":"Disallow",commercialUssageName:"Disallow"}}function Uhe(n){const e=[];for(const t in n.humanBones)e.push({bone:t,node:n.humanBones[t].node});return{humanBones:e}}function She(n){switch(n){case"happy":return"joy";case"sad":return"sorrow";case"relaxed":return"fun";case"aa":return"a";case"ih":return"i";case"ou":return"u";case"ee":return"e";case"oh":return"o";default:return n}}function _he(n){if(n.includes("Thumb")){if(n.includes("Metacarpal"))return n.replace("Metacarpal","Proximal");if(n.includes("Proximal"))return n.replace("Proximal","Intermediate")}return n}class Qhe{parse(e,t,r,i,s,o,a){var Xe;const l=Ehe(e.meta),A=Uhe(e.humanoid),c=e.materials,u=[],f={generator:"UniGLTF-2.0.0",version:"2.0"};if(t)if(A)if(l){if(!c)throw new Error("materials is undefined or null")}else throw new Error("meta is undefined or null");else throw new Error("humanoid is undefined or null");else throw new Error("avatar is undefined or null");const d=c.filter((G,J,se)=>se.findIndex(fe=>fe.name===G.name.replace(" (Outline)",""))===J).map(G=>G),h=d.map(G=>G.name),p=r?{name:"icon",imageBitmap:r.image}:null,m=d.filter(G=>G.map).map(G=>{if(!G.map)throw new Error(G.name+" map is null");return{name:G.name,imageBitmap:G.map.image}}),g=d.filter(G=>G.userData.shadeTexture).map(G=>{if(!G.userData.shadeTexture)throw new Error(G.userData.shadeTexture+" map is null");return{name:G.name+"_shade",imageBitmap:G.userData.shadeTexture.image}}),v=d.filter(G=>G.roughnessMap).map(G=>G.roughnessMap?{name:G.name+"_orm",imageBitmap:G.roughnessMap.image}:null),y=d.filter(G=>G.roughnessMap).map(G=>G.normalMap?{name:G.name+"_normal",imageBitmap:G.normalMap.image}:null),w=[...m,...g,...v,...y].filter(G=>G!==null),C=Dhe(w,p),b=khe(C),E=Vhe(C),x=Nhe(d,w),S=t.children.filter(G=>G.children.length>0&&G.children[0].type===fi.Bone)[0],M=PH(S).filter(G=>G.name!==Fk),Z=M.map(G=>G.name),K=M.map(G=>({children:G.children.filter(J=>J.name!==Fk).map(J=>Z.indexOf(J.name)),name:G.name,rotation:[G.quaternion.x,G.quaternion.y,G.quaternion.z,G.quaternion.w],scale:[G.scale.x,G.scale.y,G.scale.z],translation:[G.position.x,G.position.y,G.position.z]})),_=[],B=t.children.filter(G=>G.type===fi.Group||G.type===fi.SkinnedMesh),F=[];B.forEach(G=>{const J=G.type===fi.Group?G.children[0]:G,se=J.geometry.attributes,fe=new aA(se.position,Nn.FLOAT,Lt.POSITION,ra.VEC3,J.name,void 0);F.push(fe);const ve=F.length-1,W=new aA(se.normal,Nn.FLOAT,Lt.NORMAL,ra.VEC3,J.name,void 0);F.push(W),F.push(new aA(se.uv,Nn.FLOAT,Lt.UV,ra.VEC2,J.name,void 0)),F.push(new aA(se.skinWeight,Nn.FLOAT,Lt.SKIN_WEIGHT,ra.VEC4,J.name,void 0)),F.push(new aA(se.skinIndex,Nn.UNSIGNED_SHORT,Lt.SKIN_INDEX,ra.VEC4,J.name,void 0)),(G.type===fi.Group?G.children.map(D=>D):[G]).forEach(D=>{if(!D.geometry.index)throw new Error(D.name+" geometry.index is null");F.push(new aA(D.geometry.index,Nn.UNSIGNED_INT,Lt.INDEX,ra.SCALAR,J.name,D.name))}),J.morphTargetDictionary||(J.morphTargetDictionary={},J.morphTargetInfluences=[],J.geometry.morphAttributes={},J.updateMorphTargets()),J.geometry.userData.targetNames=[],console.warn("taking only mesh 0 for morph targets now, take the correct mesh");for(const D in e.expressionManager.expressionMap){const $=e.expressionManager.expressionMap[D],ee=$._binds.map(te=>({mesh:0,index:te.index,weight:te.weight*100}));if(ee.length>0){let te=!1;for(const we in ci)if(D===ci[we]&&D!=="surprised"){u.push({name:D,presetName:She(D),binds:ee,isBinary:$.isBinary}),te=!0;break}te===!1&&u.push({name:D,presetName:"unknown",binds:ee,isBinary:$.isBinary})}}const I=(D,$,ee,te)=>{const we=[],Ce=[];for(let Ee=0;Ee0){const Ve=we.length%4,_e=Ve===0?0:4-Ve;if(_e>0)for(let ye=0;ye<_e;ye++)we.push(0),Ce.push(0,0,0);const re={targetMeshDataIndex:ve,count:we.length,indices:new Uint32Array(we),values:new Float32Array(Ce)};F.push(new aA(te,Nn.FLOAT,ee,ra.VEC3,J.name,sU+$,re))}};for(const D in J.morphTargetDictionary){J.geometry.userData.targetNames.push(D);const $=J.morphTargetDictionary[D],ee=J.geometry.morphAttributes;I(ee.position[$].array,D,Lt.BLEND_POSITION,se.position),ee.normal&&I(ee.normal[$].array,D,Lt.BLEND_NORMAL,se.normal)}}),B.forEach(G=>{const J=G.type===fi.Group?G.children[0]:G,se=new Float32Array(J.skeleton.boneInverses.map(fe=>fe.elements).flat());F.push(new aA(new At(se,16),Nn.FLOAT,Lt.BIND_MATRIX,ra.MAT4,J.name,J.name))}),_.push(...F.map(G=>({byteOffset:0,componentType:G.valueType,count:G.attribute.count,max:G.max,min:G.min,normalized:!1,type:G.accessorsType})));const R=Mhe(B,F,h);B.forEach((G,J)=>{K.push({mesh:J,name:G.name,rotation:[G.quaternion.x,G.quaternion.y,G.quaternion.z,G.quaternion.w],scale:[G.scale.x,G.scale.y,G.scale.z],skin:J,translation:[G.position.x,G.position.y,G.position.z]})});const k=The(B,F,Z),T={humanBones:[]};A.humanBones.forEach(G=>{Z.indexOf(G.node.name)!=-1&&T.humanBones.push({bone:_he(G.bone),node:Z.indexOf(G.node.name),useDefaultValues:!0})});const V={floatProperties:{_DstBlend:.5,_ShadeShift:.5,_ShadeToony:.5,_ShadingGradeRate:.5},keywordMap:{_NORMALMAP:!1,MTOON_OUTLINE_COLOR_FIXED:!0,MTOON_OUTLINE_WIDTH_WORLD:!0},name:"VRMCombinedMat",renderQueue:2e3,shader:"VRM/MToon",tagMap:{RenderType:"Opaque"},textureProperties:{_MainTex:0,_ShadeTexture:0},vectorProperties:{_Color:[1,1,1,1],_EmissionColor:[0,0,0,1],_EmissionMap:[0,0,1,1],_MainTex:[0,0,1,1],_OutlineColor:[0,0,0,1],_OutlineWidthTexture:[0,0,1,1],_ReceiveShadowTexture:[0,0,1,1],_RimColor:[0,0,0,1],_RimTexture:[0,0,1,1],_ShadeColor:[.9,.9,.9,1]}},O={name:"STDCombinedMat",shader:"VRM_USE_GLTFSHADER"},L=[];d.forEach(G=>{G.type=="ShaderMaterial"?L.push(L.push(Object.assign({},V))):L.push(L.push(Object.assign({},O)))});const U=l;i.forEach(G=>{for(let J=0;JG.isSkinnedMesh))==null?void 0:Xe.skeleton)||null;for(let G=0;G{const ve=fe.sphere;se.colliders.push({radius:ve.radius*o,offset:{x:ve.offset[0]*o,y:ve.offset[1]*o,z:ve.offset[2]*o}})}),H.push(se)}}console.log("COLLIDER GROUPS",H);const N=G=>{for(let J=0;J{const J=N(G);if(J==-1)return[-1];{const se=[];return M[J].traverse(ve=>{ve.isBone&&se.push(N(ve.name))}),se}},oe=[];i.forEach(G=>{var W;const J=j(G.name),se=[];if(G.colliderGroups.forEach(Q=>{const I=Q.colliders[0];if(I!=null){const D=I.parent,$=H.findIndex(ee=>ee.name===D.name);$!=-1?se.push($):console.warn("No collider group for bone name: ",D.name+" was found")}else console.log("No colliders definition were present in vrm file file for: ",G.name+" spring bones")}),J===[-1]){console.warn("No bone found for spring bone "+G.name);return}let fe=N((W=G.center)==null?void 0:W.name);fe==-1&&console.warn("no center bone for spring bone "+G.name);const ve=G.settings;oe.push({bones:J,center:fe,colliderGroups:se,dragForce:ve.dragForce,gravityDir:{x:ve.gravityDir.x,y:ve.gravityDir.y,z:ve.gravityDir.z},gravityPower:ve.gravityPower,hitRadius:ve.hitRadius,stiffiness:ve.stiffness})});const ie={boneGroups:oe,colliderGroups:H};console.log(ie),U.texture=p?C.length-1:void 0;const de=[];de.push(...w.map(G=>({buffer:Ek(G.imageBitmap),type:Lt.IMAGE}))),F.forEach((G,J)=>{G.buffer?de.push({buffer:G.buffer,typeString:"",type:G.type}):G.sparse&&(de.push({buffer:G.sparse.indices,typeString:"indices",type:G.type,count:G.sparse.count}),de.push({buffer:G.sparse.values,typeString:"values",type:G.type}))}),p&&de.push({buffer:Ek(p.imageBitmap),type:Lt.IMAGE});let X=0,ne=0,ae=0,Be=0;const pe=de.map(G=>{const J={buffer:0,byteLength:G.buffer.byteLength,byteOffset:X,target:G.type===Lt.IMAGE||G.type===Lt.BIND_MATRIX?void 0:G.type===Lt.INDEX?Nn.ELEMENT_ARRAY_BUFFER:Nn.ARRAY_BUFFER};return X+=G.buffer.byteLength,G.type===Lt.IMAGE?(C[ne++].bufferView=Be,Be++):F[ae].sparse?(_[ae].sparse==null&&(_[ae].sparse={}),G.typeString==="indices"&&(_[ae].sparse.count=G.count,_[ae].sparse[G.typeString]={bufferView:Be,byteOffset:0,componentType:Nn.UNSIGNED_INT}),G.typeString==="values"&&(_[ae].sparse[G.typeString]={bufferView:Be,byteOffset:0}),G.typeString==="values"&&ae++,Be++):(F[ae].bufferIndex=Be,_[ae].bufferView=Be,ae++,Be++),J}),Fe=Lhe(t,K);Rhe(U);const rt={accessors:_,asset:f,buffers:[{byteLength:X}],bufferViews:pe,extensions:{VRM:{blendShapeMaster:{blendShapeGroups:u},firstPerson:{firstPersonBone:44,firstPersonBoneOffset:new z,lookAtHorizontalInner:{curve:[0,0,0,1,1,1,1,0],xRange:90,yRange:10},lookAtHorizontalOuter:{curve:[0,0,0,1,1,1,1,0],xRange:90,yRange:10},lookAtTypeName:"Bone",lookAtVerticalDown:{curve:[0,0,0,1,1,1,1,0],xRange:90,yRange:10},lookAtVerticalUp:{curve:[0,0,0,1,1,1,1,0],xRange:90,yRange:10}},materialProperties:L,humanoid:T,meta:U,secondaryAnimation:ie,specVersion:"0.0"}},extensionsUsed:["KHR_materials_unlit","KHR_texture_transform","VRM"],images:C,materials:x,meshes:R,nodes:K,samplers:b,scenes:Fe,skins:k,textures:E};console.log(rt);const Oe=new Uk(aU(JSON.stringify(rt,void 0,2)),"JSON"),ke=new Uk(xg(de.map(G=>G.buffer)),"BIN\0"),Qe=xg([Oe.buffer,ke.buffer]),Ge=xg([aU("glTF"),oU(2,4),oU(Qe.byteLength+12,4)]);a(xg([Ge,Qe]))}}function Rhe(n){n.title=n.title||"Character",n.version=n.version||"1",n.author=n.author||"Anon",n.contactInformation=n.contactInformation||"",n.reference=n.reference||"",n.allowedUserName=n.allowedUserName||"Everyone",n.violentUssageName=n.violentUssageName||"Disallow",n.sexualUssageName=n.sexualUssageName||"Disallow",n.commercialUssageName=n.commercialUssageName||"Disallow",n.otherPermissionUrl=n.otherPermissionUrl||"",n.licenseName=n.licenseName||"Redistribution_Prohibited",n.otherLicenseUrl=n.otherLicenseUrl||""}function PH(n){return n.children.length<=0?[n]:[n].concat(n.children.map(e=>PH(e)).flat())}function Ek(n){const e=document.createElement("canvas");e.width=n.width,e.height=n.height,e.getContext("2d").drawImage(n,0,0);const t=e.toDataURL("image/png"),r=atob(t.split(",")[1]),i=(4-r.length%4)%4,s=new ArrayBuffer(r.length+i),o=new DataView(s);for(let a=0;a4?A=r[a*n.itemSize+l]:l===0?A=n.getX(a):l===1?A=n.getY(a):l===2?A=n.getZ(a):A=n.getW(a),e===Nn.UNSIGNED_SHORT?o.setUint16(i,A,!0):e===Nn.UNSIGNED_INT?o.setUint32(i,A,!0):o.setFloat32(i,A,!0),i+=t}return s}class Uk{constructor(e,t){this.data=e,this.type=t;const r=this.data;this.buffer=xg([oU(r.byteLength,4),aU(this.type),r])}paddingBinary(e,t){const r=Math.ceil(e.byteLength/4)*4;if(e.byteLength===r)return e;const i=new Uint8Array(r);i.set(new Uint8Array(e),0);for(let s=e.byteLength;sp%3===0)),Math.max.apply(null,Array.from(A).filter((h,p)=>p%3===1)),Math.max.apply(null,Array.from(A).filter((h,p)=>p%3===2))]:void 0,this.min=r===Lt.POSITION||r===Lt.BLEND_POSITION?[Math.min.apply(null,Array.from(A).filter((h,p)=>p%3===0)),Math.min.apply(null,Array.from(A).filter((h,p)=>p%3===1)),Math.min.apply(null,Array.from(A).filter((h,p)=>p%3===2))]:void 0}else this.buffer=p1(this.attribute,this.valueType),this.max=r===Lt.POSITION||r===Lt.BLEND_POSITION?[Math.max.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===0)),Math.max.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===1)),Math.max.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===2))]:void 0,this.min=r===Lt.POSITION||r===Lt.BLEND_POSITION?[Math.min.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===0)),Math.min.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===1)),Math.min.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===2))]:void 0}}var Fd;(function(n){n.MeshBasicMaterial="MeshBasicMaterial",n.MeshStandardMaterial="MeshStandardMaterial",n.MToonMaterial="MToonMaterial"})(Fd||(Fd={}));var ra;(function(n){n.SCALAR="SCALAR",n.VEC2="VEC2",n.VEC3="VEC3",n.VEC4="VEC4",n.MAT4="MAT4"})(ra||(ra={}));var Lt;(function(n){n.POSITION="POSITION",n.NORMAL="NORMAL",n.UV="UV",n.INDEX="INDEX",n.SKIN_WEIGHT="SKIN_WEIGHT",n.SKIN_INDEX="SKIN_INDEX",n.BLEND_POSITION="BLEND_POSITION",n.BLEND_NORMAL="BLEND_NORMAL",n.BIND_MATRIX="BIND_MATRIX",n.IMAGE="IMAGE"})(Lt||(Lt={}));var fi;(function(n){n.Group="Group",n.SkinnedMesh="SkinnedMesh",n.Object3D="Object3D",n.Bone="Bone"})(fi||(fi={}));const Mhe=(n,e,t)=>n.map(r=>{const i=r.type===fi.Group?r.children[0]:r,s=r.type===fi.Group?r.children.map(o=>o):[r];return{name:r.name,primitives:s.map(o=>{const a=e.map(A=>A.meshName===i.name?A.type:null),l=Array.isArray(o.material)?o.material[0].name:o.material.name;return{attributes:{JOINTS_0:a.indexOf(Lt.SKIN_INDEX),NORMAL:a.indexOf(Lt.NORMAL),POSITION:a.indexOf(Lt.POSITION),TEXCOORD_0:a.indexOf(Lt.UV),WEIGHTS_0:a.indexOf(Lt.SKIN_WEIGHT)},extras:{targetNames:o.geometry.userData.targetNames},indices:e.map(A=>A.type===Lt.INDEX&&A.meshName===i.name?A.name:null).indexOf(o.name),material:t.indexOf(l),mode:4,targets:i.geometry.userData.targetNames?i.geometry.userData.targetNames.map(A=>{const c=e.map(d=>d.type===Lt.BLEND_NORMAL&&d.meshName===i.name?d.name:null).indexOf(sU+A),u=e.map(d=>d.type===Lt.BLEND_POSITION&&d.meshName===i.name?d.name:null).indexOf(sU+A),f={};return u!==-1&&(f.POSITION=u),c!==-1&&(f.NORMAL=c),f}):void 0}})}}),The=(n,e,t)=>n.map(r=>{const i=r.type===fi.Group?r.children[0]:r;return{inverseBindMatrices:e.map(s=>s.type===Lt.BIND_MATRIX?s.meshName:null).indexOf(i.name),joints:i.skeleton.bones.map(s=>t.indexOf(s.name)).filter(s=>s!==-1),skeleton:t.indexOf(i.skeleton.bones[0].name)}}),Nhe=(n,e)=>n.map(t=>{let r,i=null;if(t=t.userData.vrmMaterial?t.userData.vrmMaterial:t,t.type==="ShaderMaterial")i={},i.shadeMultiplyTexture={index:e.map(h=>h.name).indexOf(t.uniforms.shadeMultiplyTexture.name)},r=t.color?[1,1,1,1]:void 0;else{const d=t;r=d.color?[d.color.r,d.color.g,d.color.b,1]:void 0}let s=-1;t.map?s=e.map(d=>d.name).indexOf(t.name):t.uniforms&&t.uniforms.map&&(s=e.map(d=>d.name).indexOf(t.uniforms.map.name));let o=-1;t.roughnessMap&&(o=e.map(d=>d.name).indexOf(t.name+"_orm"));let a=-1;t.normalMap&&(a=e.map(d=>d.name).indexOf(t.name+"_normal"));const l=s>=0?{extensions:{KHR_texture_transform:{offset:[0,0],scale:[1,1]}},index:s,texCoord:0}:void 0,A={baseColorFactor:r,baseColorTexture:l},c=o>=0?{index:o,texCoord:0}:void 0,u=a>=0?{index:a,texCoord:0}:void 0;if(c)A.metallicRoughnessTexture=c;else{const d=(()=>{switch(t.type){case Fd.MeshStandardMaterial:return t.metalness;case Fd.MeshBasicMaterial:return 0;default:return 0}})(),h=(()=>{switch(t.type){case Fd.MeshStandardMaterial:return t.roughness;case Fd.MeshBasicMaterial:return .9;default:return .9}})();A.metallicFactor=d,A.roughnessFactor=h}const f={alphaCutoff:t.alphaTest>0?t.alphaTest:void 0,alphaMode:t.transparent?"BLEND":t.alphaTest>0?"MASK":"OPAQUE",doubleSided:t.side===2,extensions:t.type==="ShaderMaterial"?{KHR_materials_unlit:{},VRMC_materials_mtoon:i}:void 0,name:t.name,pbrMetallicRoughness:A};return u&&(f.normalTexture=u),f}),Dhe=(n,e)=>(e?n.concat(e):n).filter(t=>t&&t.imageBitmap).map(t=>({bufferView:-1,mimeType:"image/png",name:t.name})),khe=n=>n.map(()=>({magFilter:Nn.LINEAR,minFilter:Nn.LINEAR,wrapS:Nn.REPEAT,wrapT:Nn.REPEAT})),Vhe=n=>n.map((e,t)=>({sampler:0,source:t})),Lhe=(n,e)=>{const t=e.map(r=>r.name);return[{nodes:n.children.filter(r=>r.type===fi.Object3D||r.type===fi.SkinnedMesh||r.type===fi.Group||r.type===fi.Bone).map(r=>t.indexOf(r.name))}]};function WH(){return(WH=Object.assign||function(n){for(var e=1;e0?u+s.byteLength:0;f%8&&(f+=8-f%8);let d=[],h=new DataView(new ArrayBuffer(24*n.levels.length)),p=(f||u+s.byteLength)+t.byteLength;for(let v=0;v0?f:0),!0),g.setBigUint64(60,BigInt(t.byteLength),!0),new Uint8Array(Hp([new Uint8Array(_r).buffer,m,h.buffer,a,s,new ArrayBuffer(f>0?f-(u+s.byteLength):0),t,...d]))}var AU,cU,Hhe={enableDebug:!1,isUASTC:!0,isKTX2File:!0,isInputSRGB:!0,generateMipmap:!0,needSupercompression:!0,isSetKTX2SRGBTransferFunc:!0},uU=new OffscreenCanvas(128,128),Rk=uU.getContext("2d",{willReadFrequently:!0}),OH=typeof document>"u";function zhe(n){return createImageBitmap(n).then(function(e){return uU.width=e.width,uU.height=e.height,Rk.drawImage(e,0,0),Rk.getImageData(0,0,e.width,e.height)})}function GH(n,e){return e===void 0&&(e={}),Xhe().then(function(t){var r=new t.BasisEncoder;return Yhe(e,r),r.setTexType(AU.cBASISTexType2D),Whe(n,ArrayBuffer)&&(n=new Blob([n])),zhe(n).then(function(i){r.setSliceSourceImage(0,new Uint8Array(i.data),i.width,i.height,cU.RAW);var s=new Uint8Array(10485760),o=r.encode(s);if(o===0)throw"encode failed";var a=new Uint8Array(s.buffer,0,o),l=Ghe(s);if(e.kvData){for(var A in e.kvData)l.keyValue[A]=e.kvData[A];a=Jhe(l,{keepWriter:!0})}return a})})}function Yhe(n,e){n===void 0&&(n={}),(n=Phe({},Hhe,n)).enableDebug!==void 0&&e.setDebug(n.enableDebug),n.isUASTC!==void 0&&e.setUASTC(n.isUASTC),n.isKTX2File!==void 0&&e.setCreateKTX2File(n.isKTX2File),n.isSetKTX2SRGBTransferFunc!==void 0&&e.setKTX2SRGBTransferFunc(n.isSetKTX2SRGBTransferFunc),n.generateMipmap!==void 0&&e.setMipGen(n.generateMipmap),n.isYFlip!==void 0&&e.setYFlip(n.isYFlip),n.qualityLevel!==void 0&&e.setQualityLevel(n.qualityLevel),n.compressionLevel!==void 0&&e.setCompressionLevel(n.compressionLevel),n.needSupercompression!==void 0&&e.setKTX2UASTCSupercompression(n.needSupercompression),n.isNormalMap!==void 0&&e.setNormalMap(n.isNormalMap)}var g1=null;function Xhe(){return g1||(g1=new Promise(function(n,e){OH?(importScripts("https://mdn.alipayobjects.com/rms/afts/file/A*SrRkQarYYl4AAAAAAAAAAAAAARQnAQ/basis_encoder.js"),fetch("https://mdn.alipayobjects.com/rms/afts/file/A*qFWbTrA0hZYAAAAAAAAAAAAAARQnAQ/basis_encoder.wasm").then(function(t){return t.arrayBuffer()}).then(function(t){BASIS({wasmBinary:t}).then(function(r){r.initializeBasis(),n(r)}).catch(e)}).catch(e)):Promise.all([fetch("https://mdn.alipayobjects.com/rms/afts/file/A*SrRkQarYYl4AAAAAAAAAAAAAARQnAQ/basis_encoder.js").then(function(t){return t.text()}),fetch("https://mdn.alipayobjects.com/rms/afts/file/A*qFWbTrA0hZYAAAAAAAAAAAAAARQnAQ/basis_encoder.wasm").then(function(t){return t.arrayBuffer()})]).then(function(t){var r=t[0],i=t[1],s=document.createElement("script");s.onload=function(){BASIS({wasmBinary:i}).then(function(o){o.initializeBasis(),n(o)}).catch(e)},s.src=URL.createObjectURL(new Blob([r])),s.onerror=e,document.body.appendChild(s)}).catch(e)})),g1}OH&&self.addEventListener("message",function(n){GH(n.data).then(function(e){self.postMessage(e)}).catch(function(e){self.postMessage({error:e})})});function ZH(n){const e=n.clone(),t=[];return n.traverse(r=>{r.userData.origIndexBuffer&&t.push(r.userData.origIndexBuffer)}),e.traverse(r=>{r.userData.origIndexBuffer&&(r.userData.origIndexBuffer=t.shift())}),e}function Khe(n){const e=ZH(n);let t;const r=[];e.traverse(s=>{if(!t&&s.isSkinnedMesh&&(t=_H(s)),s.isSkinnedMesh){if(s.geometry=s.geometry.clone(),s.skeleton=t,r.push(s),Array.isArray(s.material)){const o=s.material;s.material=new mu,s.material.map=o[0].map}s.userData.origIndexBuffer&&s.geometry.setIndex(s.userData.origIndexBuffer)}});const i=new Tr;return r.forEach(s=>{i.add(s)}),i.add(t.bones[0]),i}async function jhe(n,e,t){const r=await q_(n,t),i=await JH(r,e,t);return new Blob([i],{type:"model/gltf-binary"})}function $he(n,e,t,r){return new Promise(async(i,s)=>{const o=`${t&&t!==""?t:"AvatarCreatorModel"}`;qhe(n,e,r).then(a=>{zH(a,`${o}.vrm`),i()})})}async function qhe(n,e,t){const r=await q_(n,t);return JH(r,e,t)}function q_(n,e){const t=ZH(n),{createTextureAtlas:r=!0}=e;return r?Yde(t,e):(console.log("no atlas"),Jde(t,e))}async function epe(n,e="",t){const r=`${e&&e!==""?e:"AvatarCreatorModel"}`,{optimized:i=!0}=t,s=i?await q_(n,t):Khe(n);tpe(s).then(o=>{if(o instanceof ArrayBuffer)zH(o,`${r}.glb`);else{const a=JSON.stringify(o,null,2);rpe(a,`${r}.gltf`)}})}function tpe(n){return new Promise(e=>new V_().parse(n,r=>{e(r)},r=>{console.error("Error parsing",r)},{trs:!1,onlyVisible:!1,truncateDrawRange:!0,binary:!0,forcePowerOfTwoTextures:!1,maxTextureSize:1024}))}function npe(n){var r,i;const e=[];for(const s in n)if(((i=(r=n[s])==null?void 0:r.vrm)==null?void 0:i.springBoneManager)!=null){const o=n[s].vrm.springBoneManager.joints;for(const a of o)e.some(A=>A.name===a.bone.name)||e.push({name:a.bone.name,settings:a.settings,bone:a.bone,colliderGroups:a.colliderGroups,center:a.center})}const t=[];return e.forEach(s=>{for(const o in Lm)if(s.bone.parent.name==Lm[o]){t.push(s);break}}),t}function JH(n,e,t){const{screenshot:r=null,isVrm0:i=!1,vrmMeta:s=null,scale:o=1}=t;return new Promise(async a=>{const l=i?new Qhe:new Pfe,A={...spe(e),...Ahe(n,"CharacterCreator",s)};if(t.ktxCompression){console.log("ktx compression");for(let h=0;hw.toBlob(M)),E=await GH(b),x=new Blob(E,{type:"image/ktx2"}),S=await createImageBitmap(x);A.materials[h].map.source=S}}}}let c;n.traverse(h=>{h.isSkinnedMesh&&(c=h)}),(()=>{for(let h=0;h{h.updateMatrix(),h.updateMatrixWorld()}),c.skeleton.calculateInverses(),c.skeleton.computeBoneTexture(),c.skeleton.update()})(),c.skeleton.bones.filter(h=>h.name==="head")[0];const f=npe(e),d=[];l.parse(A,n,r,f,d,o,h=>{a(h)})})}function HH(n,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),t.href=URL.createObjectURL(n),t.download=e,t.click()}function rpe(n,e){HH(new Blob([n],{type:"text/plain"}),e)}function zH(n,e){HH(ipe(n),e)}function ipe(n){return new Blob([n],{type:"application/octet-stream"})}function spe(n){for(const e in n)if(n[e].vrm)return n[e].vrm}const ope=n=>{var e,t;(e=n.parser.json.extensions)!=null&&e.VRM?ape(n):(t=n.parser.json.extensions)!=null&&t.VRMC_vrm?lpe(n):console.warn("No valid vrm file was provided")},ape=n=>{var a,l,A;const e=n.parser.json,t=n.scene,r=e.nodes,i=(A=(l=(a=e.extensions)==null?void 0:a.VRM)==null?void 0:l.secondaryAnimation)==null?void 0:A.colliderGroups,s=[],o=r.map(c=>YH(c.name,s));i!=null&&i.forEach(c=>{const u=o[c.node],f=DH(t,u);if(f!=null){const d=c.colliders;f.userData.VRMcolliders=d.map(h=>({sphere:{radius:h.radius,offset:[h.offset.x,h.offset.y,h.offset.z]}}))}})},lpe=n=>{var l,A,c,u;const e=n.parser.json,t=n.scene,r=e.nodes,i=(A=(l=e.extensions)==null?void 0:l.VRMC_springBone)==null?void 0:A.colliderGroups,s=(u=(c=e.extensions)==null?void 0:c.VRMC_springBone)==null?void 0:u.colliders,o=[],a=r.map(f=>YH(f.name,o));i!=null&&i.forEach(f=>{const d=Yt(f.colliders);let h=-1,p=null;d.forEach(m=>{if(h!=s[m].node){h=s[m].node;const g=a[h];p=DH(t,g),p.userData.VRMcolliders=[]}if(p!=null){const g=s[m].shape;for(const v in g){const y=g[v];y!=null&&y.offset&&(y.offset[0]=-y.offset[0])}p.userData.VRMcolliders.push(g)}else console.error("no node with name "+a[h]+" was found")})})},YH=(n,e)=>{const t=Bt.sanitizeNodeName(n||"");return t in e?t+"_"+ ++e[t]:(e[t]=0,t)},Hw=[0,400,560,2400,4800],zw=[0,500,700,3e3,6e3],fU=[],il=[],eQ=1024,XH=44100;for(let n=0;n{requestAnimationFrame(t),this.update(r,i)};t()}start(e){this.audioContext=new AudioContext,this.mediaStreamSource=this.audioContext.createMediaStreamSource(e),this.meter=Yw.createAudioMeter(this.audioContext),this.mediaStreamSource.connect(this.meter)}startFromAudioFile(e){this.audioContext||(this.audioContext=new AudioContext),this.userSpeechAnalyzer||(this.userSpeechAnalyzer=this.audioContext.createAnalyser()),this.userSpeechAnalyzer.smoothingTimeConstant=.5,this.userSpeechAnalyzer.fftSize=eQ,this.mediaStreamSource&&this.mediaStreamSource.stop(),this.audioContext.decodeAudioData(e).then(t=>{this.mediaStreamSource=this.audioContext.createBufferSource(),this.mediaStreamSource.buffer=t,this.meter=Yw.createAudioMeter(this.audioContext),this.mediaStreamSource.connect(this.meter),this.mediaStreamSource.connect(this.audioContext.destination),this.mediaStreamSource.start(),this.mediaStreamSource.connect(this.userSpeechAnalyzer)})}destroy(){var e,t,r;return(e=this.meter)==null||e.shutdown(),this.meter=null,(t=this.mediaStreamSource)==null||t.disconnect(),((r=this.audioContext)==null?void 0:r.close().catch(()=>{}))||Promise.resolve()}update(e){if(this.meter){const{volume:t}=this.meter;if(t<.01)this.vrm.expressionManager.setValue(ci.Oh,0),this.vrm.expressionManager.setValue(ci.Ah,0),this.vrm.expressionManager.setValue(ci.Ee,0);else{const{ah:r,oh:i,ee:s}=this.update2();this.vrm.expressionManager.setValue(ci.Oh,i),this.vrm.expressionManager.setValue(ci.Ah,r),this.vrm.expressionManager.setValue(ci.Ee,s),this.vrm.expressionManager.update(e)}}}update2(){function e(A){const u=new Float32Array(A.length);for(let f=0;f0&&(i[A]+=r[c]);i[A]/=il[A+1]-il[A]}for(let A=0;A0&&(s[A]+=r[c]);i[A]/=il[A+1]-il[A],s[A]=s[A]/(fU[A+1]-fU[A])}const o=Math.max(s[1],i[1])>.2?1-2*Math.max(i[2],s[2]):(1-2*Math.max(i[2],s[2]))*5*Math.max(i[1],s[1]),a=3*Math.max(i[3],s[3]),l=.8*(Math.max(i[1],s[1])-Math.max(i[3],s[3]));return{oh:o,ee:l,ah:a}}static createAudioMeter(e){const t=e.createScriptProcessor(512);return t.onaudioprocess=r=>{const i=r.inputBuffer.getChannelData(0),s=i.length;let o=0,a;for(let A=0;A=t.clipLevel&&(t.clipping=!0,t.lastClip=window.performance.now()),o+=a*a;const l=Math.sqrt(o/s);t.volume=Math.max(l,t.volume*t.averaging)},t.clipping=!1,t.lastClip=0,t.volume=0,t.clipLevel=.98,t.averaging=.95,t.clipLag=750,t.connect(e.destination),t.checkClipping=()=>t.clipping?(t.lastClip+t.clipLag{t.disconnect(),t.onaudioprocess=null},t}}const m1=new z;class Ape{constructor(e,t,r){this.bonesInfo=[],this.curMousePos=new We,this.hotzoneSection=s(),this.enabled=!1,this.userActivated=!1,this.lookInterest=1,this.hasInterest=!0,this.interestSpeed=.3,this.onCanvas=!0,this.camera=r,this.maxLookPercent={neck:{maxy:15,miny:10,maxx:30,minx:10},spine:{maxy:0,miny:0,maxx:30,minx:10},left:{maxy:15,miny:20,maxx:35,minx:35},right:{maxy:15,miny:20,maxx:35,minx:35}},window.addEventListener("mousemove",o=>{this.curMousePos={x:o.clientX,y:o.clientY}});const i=document.getElementById(t);i&&(i.addEventListener("mouseleave",()=>{this.onCanvas=!1}),i.addEventListener("mouseenter",()=>{this.onCanvas=!0})),window.addEventListener("resize",()=>{this.hotzoneSection=s()});function s(){const o=window.innerWidth*e/100,a=(window.innerWidth-o)/2;return{xStart:a,xEnd:window.innerWidth-a,yStart:50,yEnd:window.innerHeight-80}}}setActive(e){console.log("is activating"),this.userActivated=e}setCamera(e){this.camera=e}addVRM(e){const t=e.data.isVRM0||!1,r=e.humanoid.humanBones;t||(r.neck.node.userData.inverseLookAt=!0,r.spine.node.userData.inverseLookAt=!0,r.leftEye&&(r.leftEye.node.userData.inverseLookAt=!0),r.rightEye&&(r.rightEye.node.userData.inverseLookAt=!0));const i={vrm:e,neckBone:r.neck.node,spineBone:r.spine.node,leftEyeBone:r.leftEye?r.leftEye.node:null,rightEyeBone:r.rightEye?r.rightEye.node:null};this.bonesInfo.push(i)}removeVRM(e){const t=this.bonesInfo.find(r=>r.vrm===e);if(t){const r=this.bonesInfo.indexOf(t);this.bonesInfo.splice(r,1)}}_getMouseDegrees(e,t,r){let i=0,s=0,o,a,l,A,c={x:window.innerWidth,y:window.innerHeight};return e<=c.x/2&&(o=c.x/2-e,a=o/(c.x/2)*100,i=r.maxx*a/100*-1),e>=c.x/2&&(o=e-c.x/2,a=o/(c.x/2)*100,i=r.minx*a/100),t<=c.y/2&&(l=c.y/2-t,A=l/(c.y/2)*100,s=r.maxy*.5*A/100*-1),t>=c.y/2&&(l=t-c.y/2,A=l/(c.y/2)*100,s=r.miny*A/100),{x:i,y:s}}lerp(e,t,r){return(1-r)*e+r*t}_moveJoint(e,t){const r=e.userData.inverseLookAt===!0?1:-1;if(Object.keys(e).length!==0){const i=(this.camera.position.y-1.8)*window.innerHeight/2;let s=this._getMouseDegrees(this.curMousePos.x,this.curMousePos.y-i,t);const o=.8;e.rotation.y=this.lerp(Wt.degToRad(s.x),e.rotation.y,o),e.rotation.x=this.lerp(Wt.degToRad(s.y*r),e.rotation.x,o)}}update(){m1.set(0,0,1),m1.applyQuaternion(this.camera.quaternion);const e=m1.z>0;this.curMousePos.x>this.hotzoneSection.xStart&&this.curMousePos.xthis.hotzoneSection.yStart&&this.curMousePos.y{this._moveJoint(t.neckBone,this.maxLookPercent.neck),this._moveJoint(t.spineBone,this.maxLookPercent.spine),this._moveJoint(t.leftEyeBone,this.maxLookPercent.left),this._moveJoint(t.rightEyeBone,this.maxLookPercent.right)})}}class v1{constructor(e){const{assetsLocation:t,traitsDirectory:r,thumbnailsDirectory:i,traitIconsDirectorySvg:s,animationPath:o,exportScale:a,displayScale:l,initialTraits:A,requiredTraits:c,randomTraits:u,colliderTraits:f,lipSyncTraits:d,blinkerTraits:h,typeRestrictions:p,defaultCullingLayer:m,defaultCullingDistance:g,offset:v,vrmMeta:y,traits:w,textureCollections:C,colorCollections:b,canDownload:E=!0,downloadOptions:x={}}=e;this.assetsLocation=t,this.traitsDirectory=r,this.thumbnailsDirectory=i,this.traitIconsDirectorySvg=s,this.displayScale=l||a||1,this.animationPath=Yt(o),this.requiredTraits=Yt(c),this.randomTraits=Yt(u),this.initialTraits=A||[...new Set(this.requiredTraits.concat(this.randomTraits))],this.colliderTraits=Yt(f),this.lipSyncTraits=Yt(d),this.blinkerTraits=Yt(h),this.typeRestrictions=p,this.defaultCullingLayer=m,this.defaultCullingDistance=g,this.offset=v,this.canDownload=E,this.downloadOptions=x;const S=()=>{const K=[];for(const _ in w)K.push(w[_].trait);return K};this.allTraits=S(),S(),(()=>{if(this.typeRestrictions)for(const K in this.typeRestrictions)Yt(this.typeRestrictions[K]).forEach(B=>{this.typeRestrictions[B]==null&&(this.typeRestrictions[B]=[]),this.typeRestrictions[B].indexOf(K)==-1&&this.typeRestrictions[B].push(K)})})(),(()=>{x.vrmMeta=x.vrmMeta||y,x.scale=x.scale||a||1,x.mToonAtlasSize=x.mToonAtlasSize||2048,x.mToonAtlasSizeTransp=x.mToonAtlasSizeTransp||1024,x.stdAtlasSize=x.stdAtlasSize||2048,x.stdAtlasSizeTransp=x.stdAtlasSizeTransp||1024,x.exportStdAtlas=x.exportStdAtlas||!1,x.exportMtoonAtlas=x.exportMtoonAtlas||!0,x.screenshotFaceDistance=x.screenshotFaceDistance||1,x.screenshotFaceOffset=x.screenshotFaceOffset||[0,0,0],x.screenshotResolution=x.screenshotResolution||[512,512],x.screenshotBackground=x.screenshotBackground||[.1,.1,.1],x.screenshotFOV=x.screenshotFOV||75,!x.exportStdAtlas&&!x.exportMtoonAtlas&&(x.exportMtoonAtlas=!0)})(),this.textureTraits=[],this.textureTraitsMap=null,this.createTextureTraits(C),this.colorTraits=[],this.colorTraitsMap=null,this.createColorTraits(b),this.modelTraits=[],this.modelTraitsMap=null,this.createModelTraits(w)}appendManifestData(e,t){e.textureTraits.forEach(r=>{const i=this.getTextureGroup(r.trait);i!=null?i.appendCollection(r,t):(this.textureTraits.push(r),this.textureTraitsMap.set(r.trait,r))}),e.colorTraits.forEach(r=>{const i=this.getColorGroup(r.trait);i!=null?i.appendCollection(r,t):(this.colorTraits.push(r),this.colorTraitsMap.set(r.trait,r))}),e.modelTraits.forEach(r=>{const i=this.getModelGroup(r.trait);i!=null?i.appendCollection(r,t):(this.modelTraits.push(r),this.modelTraitsMap.set(r.trait,r))}),console.log(e)}getExportOptions(){return this.downloadOptions}getGroupModelTraits(){return this.modelTraits}getInitialTraits(){return this.getRandomTraits(this.initialTraits)}getAllTraits(){return this.getRandomTraits(this.allTraits)}isColliderRequired(e){return this.colliderTraits.indexOf(e)!=-1}isLipsyncTrait(e){return this.lipSyncTraits.indexOf(e)!=-1}async getNFTraitOptionsFromURL(e,t){const r=await this._fetchJson(e);return this.getNFTraitOptionsFromObject(r,t)}getNFTraitOptionsFromObject(e,t){const r=e.attributes;if(r){t=Yt(t);const i=[];return r.forEach(s=>{if(t.indexOf(s.trait_type)==-1){const o=this.getTraitOption(s.trait_type,s.value);o&&i.push(o)}}),i}else return console.warn("No attiributes parameter was found in ",e),null}getRandomTraits(e){const t=[];return(e||this.randomTraits).forEach(i=>{const s=this.getRandomTrait(i);s&&t.push(s)}),this._filterTraitOptions(t)}getRandomTrait(e){var r,i;const t=this.getModelGroup(e);if(t){const s=t.getRandomTrait();if(s){const o=(r=s.targetTextureCollection)==null?void 0:r.getRandomTrait(),a=(i=s.targetColorCollection)==null?void 0:i.getRandomTrait();return new y1(s,o,a)}else return null}else return console.warn("No trait group with name "+e+" was found."),null}async _fetchJson(e){return await(await fetch(e)).json()}getTraitOption(e,t){var i,s;const r=this.getModelTrait(e,t);if(r){const o=(i=r.targetTextureCollection)==null?void 0:i.getRandomTrait(),a=(s=r.targetColorCollection)==null?void 0:s.getRandomTrait();return new y1(r,o,a)}return null}_filterTraitOptions(e){const t=[],r=[];for(let i=0;i0&&console.log("options were filtered to fullfill restrictions: ",r),t}getCustomTraitOption(e,t){const r=this.getCustomModelTrait(e,t);return r?new y1(r,null,null):null}getCustomModelTrait(e,t){var r;return(r=this.getModelGroup(e))==null?void 0:r.getCustomTrait(t)}getModelTrait(e,t){var r;return(r=this.getModelGroup(e))==null?void 0:r.getTrait(t)}getModelTraits(e){const t=this.getModelGroup(e);return t?t.getCollection():(console.warn("No model group with name "+e),null)}getModelGroup(e){return this.modelTraitsMap.get(e)}getTextureTrait(e,t){var r;return(r=this.getTextureGroup(e))==null?void 0:r.getTrait(t)}getTextureGroup(e){return this.textureTraitsMap.get(e)}getColorTrait(e,t){var r;return(r=this.getColorGroup(e))==null?void 0:r.getTrait(t)}getColorGroup(e){return this.colorTraitsMap.get(e)}getTraitsDirectory(){let e=(this.assetsLocation||"")+(this.traitsDirectory||"");return!e.endsWith("/")&&!e.endsWith("\\")&&(e+="/"),e}getThumbnailsDirectory(){let e=(this.assetsLocation||"")+(this.thumbnailsDirectory||"");return!e.endsWith("/")&&!e.endsWith("\\")&&(e+="/"),e}getTraitIconsDirectorySvg(){let e=(this.assetsLocation||"")+(this.traitIconsDirectorySvg||"");return!e.endsWith("/")&&!e.endsWith("\\")&&(e+="/"),e}getAssetsDirectory(){let e=this.assetsLocation||"";return!e.endsWith("/")&&!e.endsWith("\\")&&(e+="/"),e}createModelTraits(e,t=!1){t&&(this.modelTraits=[]),Yt(e).forEach(r=>{this.modelTraits.push(new cpe(this,r))}),this.modelTraitsMap=new Map(this.modelTraits.map(r=>[r.trait,r])),this.modelTraits.forEach(r=>{r.restrictedTraits.forEach(i=>{const s=this.getModelGroup(i);console.log(s),s&&s.addTraitRestriction(r.trait)})})}createTextureTraits(e,t=!1){t&&(this.textureTraits=[]),Yt(e).forEach(r=>{this.textureTraits.push(new upe(this,r))}),this.textureTraitsMap=new Map(this.textureTraits.map(r=>[r.trait,r]))}createColorTraits(e,t=!1){t&&(this.colorTraits=[]),Yt(e).forEach(r=>{this.colorTraits.push(new fpe(this,r))}),this.colorTraitsMap=new Map(this.colorTraits.map(r=>[r.trait,r]))}}class cpe{constructor(e,t){const{trait:r,name:i,iconSvg:s,cameraTarget:o={distance:3,height:1},cullingDistance:a,cullingLayer:l,collection:A,restrictedTraits:c=[],restrictedTypes:u=[]}=t;this.manifestData=e,this.isRequired=e.requiredTraits.indexOf(r)!==-1,this.trait=r,this.name=i,this.iconSvg=s,this.fullIconSvg=e.getTraitIconsDirectorySvg()+s,this.restrictedTraits=c,this.restrictedTypes=u,this.cameraTarget=o,this.cullingDistance=a,this.cullingLayer=l,this.collection=[],this.collectionMap=null,this.createCollection(A)}appendCollection(e,t){e.collection.forEach(r=>{const i=this.getTrait(r.id);if(i!=null)if(t){console.log(`Model with id ${r.id} exists and will be replaced with new one`),this.collectionMap.set(r.id,r);const s=this.collection.indexOf(i);this.collection[s]=r}else console.log(`Model with id ${r.id} exists, skipping`);else this.collection.push(r),this.collectionMap.set(r.id,r)})}addTraitRestriction(e){this.restrictedTraits.indexOf(e)==-1&&this.restrictedTraits.push(e)}createCollection(e,t=!1){t&&(this.collection=[]),Yt(e).forEach(r=>{this.collection.push(new Mk(this,r))}),this.collectionMap=new Map(this.collection.map(r=>[r.id,r]))}getCustomTrait(e){return new Mk(this,{directory:e,fullDirectory:e,id:"_custom",name:"Custom"})}getTrait(e){return this.collectionMap.get(e)}getTraitByIndex(e){return this.collection[e]}getRandomTrait(){return this.collection.length>0?this.collection[Math.floor(Math.random()*this.collection.length)]:null}getCollection(){return this.collection}}class upe{constructor(e,t){const{trait:r,collection:i}=t;this.manifestData=e,this.trait=r,this.collection=[],this.collectionMap=null,this.createCollection(i)}appendCollection(e,t){e.collection.forEach(r=>{const i=this.getTrait(r.id);if(i!=null)if(t){console.log(`Texture with id ${r.id} exists and will be replaced with new one`),this.collectionMap.set(r.id,r);const s=this.collection.indexOf(i);this.collection[s]=r}else console.log(`Texture with id ${r.id} exists, skipping`);else this.collection.push(r),this.collectionMap.set(r.id,r)})}createCollection(e,t=!1){t&&(this.collection=[]),Yt(e).forEach(r=>{this.collection.push(new dpe(this,r))}),this.collectionMap=new Map(this.collection.map(r=>[r.id,r]))}getTrait(e){return this.collectionMap.get(e)}getTraitByIndex(e){return this.collection[e]}getRandomTrait(){return this.collection.length>0?this.collection[Math.floor(Math.random()*this.collection.length)]:null}}class fpe{constructor(e,t){const{trait:r,collection:i}=t;this.manifestData=e,this.trait=r,this.collection=[],this.collectionMap=null,this.createCollection(i)}appendCollection(e,t){e.collection.forEach(r=>{const i=this.getTrait(r.id);if(i!=null)if(t){console.log(`Color with id ${r.id} exists and will be replaced with new one`),this.collectionMap.set(r.id,r);const s=this.collection.indexOf(i);this.collection[s]=r}else console.log(`Color with id ${r.id} exists, skipping`);else this.collection.push(r),this.collectionMap.set(r.id,r)})}createCollection(e,t=!1){t&&(this.collection=[]),Yt(e).forEach(r=>{this.collection.push(new hpe(this,r))}),this.collectionMap=new Map(this.collection.map(r=>[r.id,r]))}getTrait(e){return this.collectionMap.get(e)}getTraitByIndex(e){return this.collection[e]}getRandomTrait(){return this.collection.length>0?this.collection[Math.floor(Math.random()*this.collection.length)]:null}}class Mk{constructor(e,t){const{id:r,directory:i,name:s,thumbnail:o,cullingDistance:a,cullingLayer:l,type:A=[],textureCollection:c,colorCollection:u,fullDirectory:f,fullThumbnail:d}=t;if(this.manifestData=e.manifestData,this.traitGroup=e,this.id=r,this.directory=i,f)this.fullDirectory=f;else if(Array.isArray(i)){this.fullDirectory=[];for(let h=0;h0&&this.manifestData.restrictedTypes>0){haveCommonValue=(i,s)=>{if(i==null||s==null)return!1;for(let o=0;ohaveCommonValue(r[i],traitTypes))}return!1}}class dpe{constructor(e,t){const{id:r,directory:i,fullDirectory:s,name:o,thumbnail:a}=t;if(this.traitGroup=e,this.id=r,this.directory=i,s)this.fullDirectory=s;else if(Array.isArray(i)){this.fullDirectory=[];for(let l=0;l{o.isSkinnedMesh&&o.skeleton.bones.filter(l=>l.name==="head")[0].getWorldPosition(el)}),el.z+=.3,el.y+=s,this.screenshotManager.setCamera(el,i),this.screenshotManager.saveScreenshot(e,t,r),this.blinkManager.disableScreenshot()}cameraRaycastCulling(e,t,r=!0){if(this.renderCamera==null){console.warn("No camera was set in character manager. Please call setRenderCamera(camera) before calling this function");return}const i=()=>{this.characterModel.traverse(A=>{A.isMesh&&A.userData.origIndexBuffer&&(A.userData.clippedIndexGeometry=A.geometry.index.clone(),A.geometry.setIndex(A.userData.origIndexBuffer))})},s=()=>{this.characterModel.traverse(A=>{A.isMesh&&A.userData.origIndexBuffer&&A.geometry.setIndex(A.userData.clippedIndexGeometry)})},o=(A,c)=>{for(let u=0;u{var p,m;const u=A.object,f=A.face,d=[f.a,f.b,f.c],h=(m=(p=u.userData)==null?void 0:p.clippedIndexGeometry)==null?void 0:m.array;if(h!=null){const g=o(h,d),v=Array.from(h);if(g==-1&&!c){const y=[...v,...d];u.userData.clippedIndexGeometry=new At(new Uint32Array(y),1,!1)}g!=1&&c&&(v.splice(g,3),u.userData.clippedIndexGeometry=new At(new Uint32Array(v),1,!1))}};B1.x=e,B1.y=t,i(),Tk.setFromCamera(B1,this.renderCamera);const l=Tk.intersectObjects(this.characterModel.children);if(l.length>0){const A=l[0];a(A,r)}s()}removeCurrentCharacter(){const e=[];for(const t in this.avatar)e.push(new mB({traitGroupID:t,traitModel:null}));e.forEach(t=>{this._addLoadedData(t)}),this.avatar={}}removeCurrentManifest(){this.removeCurrentCharacter(),this.manifest=null,this.manifestData=null,this.animationManager&&this.animationManager.clearCurrentAnimations()}canDownload(){var e;return((e=this.manifestData)==null?void 0:e.canDownload)||!0}downloadVRM(e,t=null){return new Promise(async(r,i)=>{if(this.canDownload())try{t=t||{};const o={...this.manifestData.getExportOptions(),...t};o.isVrm0=!0,o.screenshot=this._getPortaitScreenshotTexture(!1,o),console.log(o),await $he(this.characterModel,this.avatar,e,o),r()}catch(s){console.error("Error downloading VRM:",s.message),i(new Error("Failed to download VRM."))}else{const s="Download not supported.";console.error(s),i(new Error(s))}})}downloadGLB(e,t=null){if(console.log("XXX fix glb downloader"),this.canDownload()){t=t||{};const r={...this.manifestData.getExportOptions(),...t};epe(this.characterModel,e,r)}else console.error("Download not supported")}getAvatarSelection(){var t;var e={};for(const r in this.avatar)e[r]={name:this.avatar[r].name,id:(t=this.avatar[r].traitInfo)==null?void 0:t.id};return e}getGroupTraits(){if(this.manifestData)return this.manifestData.getGroupModelTraits()}getCurrentCharacterModel(){return this.characterModel}isTraitGroupRequired(e){const t=this.manifestData.getModelGroup(e);return!!(t!=null&&t.isRequired)}getTraits(e){return this.manifestData?this.manifestData.getModelTraits(e):(console.warn("No manifest file has been loaded, please load it before trait models."),null)}getCurrentTraitID(e){var t,r;return(r=(t=this.avatar[e])==null?void 0:t.traitInfo)==null?void 0:r.id}getCurrentTraitData(e){var t;return(t=this.avatar[e])==null?void 0:t.traitInfo}getCurrentTraitVRM(e){var t;return(t=this.avatar[e])==null?void 0:t.vrm}setParentModel(e){e.add(this.rootModel),this.parentModel=e,this.screenshotManager&&this.screenshotManager.setScene(this.parentModel)}setRenderCamera(e){this.renderCamera=e}loadRandomTraits(){return new Promise(async(e,t)=>{if(this.manifestData){const r=this.manifestData.getRandomTraits();await this._loadTraits(r),e()}else{const r="No manifest was loaded, random traits cannot be loaded.";console.error(r),t(new Error(r))}})}loadRandomTrait(e){return new Promise(async(t,r)=>{if(this.manifestData){const i=this.manifestData.getRandomTrait(e);await this._loadTraits(Yt(i)),t()}else{const i="No manifest was loaded, random traits cannot be loaded.";console.error(i),r(new Error(i))}})}loadTraitsFromNFT(e,t=!0,r=null){return new Promise(async(i,s)=>{try{if(this.manifestData){const o=this.manifestData.getNFTraitOptionsFromURL(e,r);await this._loadTraits(o,t),i()}else{const o="No manifest was loaded, NFT traits cannot be loaded.";console.error(o),s(new Error(o))}}catch(o){s(o)}})}loadTraitsFromNFTObject(e,t=!0,r=null){return new Promise(async(i,s)=>{if(this.manifestData)try{const o=this.manifestData.getNFTraitOptionsFromObject(e,r);await this._loadTraits(o,t),i()}catch(o){console.error("Error loading traits from NFT object:",o.message),s(new Error("Failed to load traits from NFT object."))}else{const o="No manifest was loaded, NFT traits cannot be loaded.";console.error(o),s(new Error(o))}})}loadInitialTraits(){return new Promise(async(e,t)=>{if(this.manifestData)await this._loadTraits(this.manifestData.getInitialTraits()),e();else{const r="No manifest was loaded, initial traits cannot be loaded.";console.error(r),t(new Error(r))}})}loadAllTraits(){return console.log("load all"),new Promise(async(e,t)=>{if(this.manifestData)await this._loadTraits(this.manifestData.getAllTraits()),e();else{const r="No manifest was loaded, initial traits cannot be loaded.";console.error(r),t(new Error(r))}})}loadTrait(e,t){return new Promise(async(r,i)=>{if(this.manifestData)try{const s=this.manifestData.getTraitOption(e,t);s&&(await this._loadTraits(Yt(s)),r())}catch(s){console.error("Error loading specific trait:",s.message),i(new Error("Failed to load specific trait."))}else{const s="No manifest was loaded, specific trait cannot be loaded.";console.error(s),i(new Error(s))}})}loadCustomTrait(e,t){return new Promise(async(r,i)=>{if(this.manifestData)try{const s=this.manifestData.getCustomTraitOption(e,t);s&&(await this._loadTraits(Yt(s)),r())}catch(s){console.error("Error loading custom trait:",s.message),i(new Error("Failed to load custom trait."))}else{const s="No manifest was loaded, custom trait cannot be loaded.";console.error(s),i(new Error(s))}})}loadCustomTexture(e,t){return new Promise(async(r,i)=>{var o;const s=(o=this.avatar[e])==null?void 0:o.model;if(s)await qde(s,t),r();else{const a="No Group Trait with name "+e+" was found.";console.warn(a),i(new Error(a))}})}setTraitColor(e,t){var i;const r=(i=this.avatar[e])==null?void 0:i.model;if(r)try{const s=new Re(t);r.traverse(o=>{o.isMesh&&(o.material.type==="MeshStandardMaterial"?Array.isArray(o.material)?o.material.forEach(a=>{a.color=s}):o.material.color=s:(o.material[0].uniforms.litFactor.value=s,o.material[0].uniforms.shadeColorFactor.value=new Re(s.r*.8,s.g*.8,s.b*.8)))})}catch(s){throw console.error("Error setting trait color:",s.message),new Error("Failed to set trait color.")}else{const s="No Group Trait with name "+e+" was found.";throw console.warn(s),new Error(s)}}removeTrait(e,t=!1){if(this.isTraitGroupRequired(e)&&!t){console.warn(`No trait with name: ${e} is not removable.`);return}if(this.manifestData.getModelGroup(e)){const i=new mB({traitGroupID:e,traitModel:null});this._addLoadedData(i),d1(this.avatar)}else console.warn(`No trait with name: ${e} was found.`)}updateCullHiddenMeshes(){d1(this.avatar)}loadOptimizerManifest(){this.manifest={colliderTraits:["CUSTOM"],traits:[{name:"Custom",trait:"CUSTOM",collection:[]}]},this.manifestData=new v1(this.manifest)}getCurrentOptimizerCharacterModel(){var e;return(e=this.avatar.CUSTOM)==null?void 0:e.vrm}loadOptimizerCharacter(e){return this.loadCustomTrait("CUSTOM",e)}setManifest(e){return this.removeCurrentCharacter(),new Promise(async(t,r)=>{try{if(this.manifest=e,this.manifest){if(this.manifestData=new v1(this.manifest),this.animationManager)try{await this._animationManagerSetup(this.manifest.animationPath,this.manifest.assetsLocation,this.manifestData.displayScale)}catch(i){console.error("Error loading animations: "+i)}t()}else{const i="Failed to fetch or parse the manifest.";console.error(i),r(new Error(i))}}catch(i){console.error("Error setting manifest:",i.message),r(new Error("Failed to set the manifest."))}})}appendManifest(e,t){return new Promise(async(r,i)=>{try{t?this.manifest={...this.manifest||{},manifest:e}:this.manifest={manifest:e,...this.manifest||{}};const s=new v1(e);this.manifestData.appendManifestData(s),r()}catch(s){console.error("Error setting manifest:",s.message),i(new Error("Failed to set the manifest."))}})}loadManifest(e){return new Promise(async(t,r)=>{try{const i=await this._fetchManifest(e);this.setManifest(i).then(()=>{t()})}catch(i){console.error("Error loading manifest:",i.message),r(new Error("Failed to load the manifest."))}})}loadAppendManifest(e,t){return new Promise(async(r,i)=>{try{const s=await this._fetchManifest(e);this.appendManifest(s,t).then(()=>{r()})}catch(s){console.error("Error loading manifest:",s.message),i(new Error("Failed to load the manifest."))}})}async _loadTraits(e,t=!1){await this.traitLoadManager.loadTraitOptions(Yt(e)).then(r=>{t&&this.getGroupTraits().forEach(s=>{r.some(a=>{var l;return((l=a.traitModel)==null?void 0:l.traitGroup.trait)===s.trait})||this.avatar[s.trait]!=null&&r.push(new mB({traitGroupID:s.trait,traitModel:null}))}),r.forEach(i=>{this._addLoadedData(i)}),d1(this.avatar)})}async _animationManagerSetup(e,t,r){const i=Yt(e);this.animationManager&&(this.animationManager.setScale(r),e.length>0&&(this.animationManager.storeAnimationPaths(i,t||""),await this.animationManager.loadAnimation(i,!1,0,i[0].endsWith(".fbx"),t||"")))}async _fetchManifest(e){return await(await fetch(e)).json()}_getPortaitScreenshotTexture(e,t){this.blinkManager.enableScreenshot(),this.characterModel.traverse(u=>{u.isSkinnedMesh&&u.skeleton.bones.filter(d=>d.name==="head")[0].getWorldPosition(el)});const{screenshotResolution:r,screenshotFaceDistance:i,screenshotFaceOffset:s,screenshotBackground:o,screenshotFOV:a}=t,l=r[0],A=r[1];el.x+=s[0],el.y+=s[1],el.z+=s[2],this.screenshotManager.setBackground(o),this.screenshotManager.setCamera(el,i,a);const c=e?this.screenshotManager.getScreenshotBlob(l,A):this.screenshotManager.getScreenshotTexture(l,A);return this.blinkManager.disableScreenshot(),c}_setupWireframeMaterial(e){e.origMat=e.material;const t=()=>{const o=.1+Math.random()*.9,a=.1+Math.random()*(1-.1),l=.1+Math.random()*(1-.1);return new Re(o,a,l)},r=new Qi({color:t(),wireframe:!0,wireframeLinewidth:.2}),i=e.material;e.setDebugMode=s=>{s?e.material.length?(e.material[0]=r,e.material[1]=r):e.material=r:e.material=i}}_VRMBaseSetup(e,t,r,i,s){var a,l;let o=e.userData.vrm;return e.userData.vrm==null?(console.error("No valid VRM was provided for "+r+" trait, skipping file."),null):(wk(o,{isVRM0:((a=o.meta)==null?void 0:a.metaVersion)==="0"}),this.manifestData.isColliderRequired(r)&&ope(e),lhe(o),this.manifestData.isLipsyncTrait(r)&&(this.lipSync=new Yw(o)),this._modelBaseSetup(o,t,r,i,s),((l=o.meta)==null?void 0:l.metaVersion)==="0"&&o.scene.traverse(A=>{if(A.isSkinnedMesh){Xh.rotateVRM0(o),console.log("Loaded VRM0 file ",o);for(let c=0;c{const f=e.scene.getObjectByName(u);f!=null&&f.isMesh&&o.push(f)}),e.scene.traverse(u=>{!t.meshTargets&&u.isMesh&&o.push(u),u.frustumCulled=!1,u.isMesh&&(this._setupWireframeMaterial(u),a.indexOf(u.name)===-1&&l.push(u))});const A=this.manifest,c=this.manifestData.getModelGroup(r);wk(e,{cullingLayer:t.cullingLayer!=null?t.cullingLayer:c.cullingLayer!=null?c.cullingLayer:A.defaultCullingLayer!=null?A.defaultCullingLayer:-1,cullingDistance:t.cullingDistance!=null?t.cullingDistance:c.cullingDistance!=null?c.cullingDistance:A.defaultCullingDistance!=null?A.defaultCullingDistance:null,maxCullingDistance:t.maxCullingDistance!=null?t.maxCullingDistance:c.maxCullingDistance!=null?c.maxCullingDistance:A.maxCullingDistance!=null?A.maxCullingDistance:1/0,cullingMeshes:l}),o.map((u,f)=>{if(i){const d=i[f]||i[0];d!=null&&(u.material.type==="MeshStandardMaterial"?Array.isArray(u.material)?u.material.forEach(h=>{h.map=d}):u.material.map=d:console.warn("XXX set material texture to shader material",u.material))}if(s){const d=s[f]||s[0];d!=null&&(u.material[0].uniforms.litFactor.value=d,u.material[0].uniforms.shadeColorFactor.value=new Re(d.r*.8,d.g*.8,d.b*.8))}})}_applyManagers(e){this.blinkManager.addVRM(e),this.lookAtManager&&this.lookAtManager.addVRM(e),this.animationManager&&this.animationManager.addVRM(e)}_displayModel(e){if(e){const t=e.scene;this.characterModel.attach(t)}}_positionModel(e){const t=this.manifestData.displayScale;e.scene.scale.set(t,t,t)}_disposeTrait(e){this.blinkManager.removeVRM(e),this.lookAtManager&&this.lookAtManager.removeVRM(e),this.animationManager&&this.animationManager.removeVRM(e),ohe(e)}_addLoadedData(e){const{traitGroupID:t,traitModel:r,textureTrait:i,colorTrait:s,models:o,textures:a,colors:l}=e;if(r==null){this.avatar[t]&&this.avatar[t].vrm&&(this._disposeTrait(this.avatar[t].vrm),this.avatar[t]={});return}let A=null;o.map(c=>{c!=null&&(A=this._VRMBaseSetup(c,r,t,a,l))}),A!=null&&(this.avatar[t]&&this.avatar[t].vrm&&this._disposeTrait(this.avatar[t].vrm),this._positionModel(A),this._displayModel(A),this._applyManagers(A),console.log(this.characterModel),this.avatar[t]={traitInfo:r,textureInfo:i,colorInfo:s,name:r.name,model:A&&A.scene,vrm:A})}}class gpe{constructor(){const e=new BZ;e.onProgress=(i,s,o)=>{this.setLoadPercentage(Math.round(s/o*100))};const t=new x_(e);t.crossOrigin="anonymous",t.register(i=>new Tfe(i,{autoUpdateHumanBones:!0}));const r=new Nu(e);this.loadPercentager=0,this.loadingManager=e,this.gltfLoader=t,this.textureLoader=r,this.isLoading=!1}setLoadPercentage(e){this.loadPercentager=e}loadTraitOptions(e){return new Promise(t=>{this.isLoading=!0;const r=[],i=e.map(async(s,o)=>{var c,u,f;if(s==null){r[o]=null;return}const a=await Promise.all(Yt((c=s==null?void 0:s.traitModel)==null?void 0:c.fullDirectory).map(async d=>{try{return await this.gltfLoader.loadAsync(d)}catch(h){return console.error(`Error loading modelsss ${d}:`,h),null}})),l=await Promise.all(Yt((u=s==null?void 0:s.traitTexture)==null?void 0:u.fullDirectory).map(d=>new Promise(h=>{this.textureLoader.load(d,p=>{p.flipY=!1,p.encoding=ht,h(p)},null,p=>{console.error("error loading texture: ",p),h(null)})}))),A=Yt((f=s==null?void 0:s.traitColor)==null?void 0:f.value).map(d=>new Re(d));r[o]=new mB({traitGroupID:s==null?void 0:s.traitModel.traitGroup.trait,traitModel:s==null?void 0:s.traitModel,textureTrait:s==null?void 0:s.traitTexture,colorTrait:s==null?void 0:s.traitColor,models:a,textures:l,colors:A})});Promise.allSettled(i).then(()=>{this.setLoadPercentage(100),t(r),this.isLoading=!1}).catch(s=>{this.setLoadPercentage(100),console.error("An error occurred:",s),t(r),this.isLoading=!1})})}}class mB{constructor(e){const{traitGroupID:t,traitModel:r,textureTrait:i,colorTrait:s,models:o,textures:a,colors:l}=e;this.traitGroupID=t,this.traitModel=r,this.textureTrait=i,this.colorTrait=s,this.models=o,this.textures=a,this.colors=l}}function mpe(n){const e=new yw,t=new bZ(16777215,.5);e.add(t);const r=new w_(16777215,.5);r.position.set(0,1,1),e.add(r);const i=new kt;e.add(i);const s=new Mr(30,window.innerWidth/window.innerHeight,.1,1e3);s.position.set(0,1.3,2);const o=new ppe({parentModel:e,createAnimationManager:!0,renderCamera:s});o.addLookAtMouse(80,n,s,!0);const a=document.getElementById(n),l=new c0({canvas:a,antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),A=new bie(s,l.domElement);A.minDistance=1,A.maxDistance=4,A.maxPolarAngle=Math.PI/2,A.enablePan=!0,A.target=new z(0,1,0),A.enableDamping=!0,A.dampingFactor=.1;const c=new z(-.5,0,-.5),u=new z(.5,1.5,.5),f=()=>{l.setSize(window.innerWidth,window.innerHeight),s.aspect=window.innerWidth/window.innerHeight,s.updateProjectionMatrix()};window.addEventListener("resize",f),l.setSize(window.innerWidth,window.innerHeight),l.setPixelRatio(window.devicePixelRatio),l.outputEncoding=ht;const d=()=>{requestAnimationFrame(d),A.target.clamp(c,u),A==null||A.update(),o.update(),l.render(e,s)};d();const h=m=>{const g=m.ctrlKey,v=a.getBoundingClientRect(),y=(m.clientX-v.left)/v.width*2-1,w=-((m.clientY-v.top)/v.height)*2+1;o.cameraRaycastCulling(y,w,g)};async function p(){const m="./3d/Platform.glb",v=await new x_().loadAsync(m);i.add(v.scene)}return p(),a.addEventListener("click",h),{scene:e,camera:s,controls:A,characterManager:o,sceneElements:i}}new z;class vpe{constructor(e){this.characterManager=e,this.screenshotManager=e.screenshotManager,this.blinkManager=e.blinkManager,this.animationManager=this.characterManager.animationManager,console.log(this.characterManager),console.log(this.screenshotManager),this.temptime=0}async createLoraData(e,t){const r=await this._fetchManifest(e),{assetsLocation:i="",animationsDirectory:s="",backgroundGrayscale:o=1,topFrameOffsetPixels:a=64,bottomFrameOffsetPixels:l=64,backgroundDescription:A="",width:c=512,height:u=512,dataCollection:f}=r,d=i+s+"/";this.screenshotManager.setBackground([o,o,o]),this.blinkManager.enableScreenshot(),this.screenshotManager._setBonesOffset(.2);const h=g=>new Promise(v=>setTimeout(v,g));let p=0;const m=this;Array.isArray(f)&&await(async()=>{if(Array.isArray(f))for(let v=0;vnew Promise(v=>setTimeout(v,g));this.screenshotManager.setBottomFrameOffset(l),this.screenshotManager.setTopFrameOffset(a),this.screenshotManager.setBackground(s),this.blinkManager.enableScreenshot(),this.screenshotManager._setBonesOffset(.2);let p=0;console.log(t);const m=this;if(Array.isArray(f)){console.log("e");async function g(){var v;if(Array.isArray(f))for(const y of f){const{animationName:w,animationPath:C,framesNumber:b,lookAtCamera:E,expression:x,cameraPosition:S,cameraFrame:M}=y;p++;const Z=w||p.toString().padStart(2,"0");await m.animationManager.loadAnimation(d+C,!0,0);const K=TH(S);m.screenshotManager.setCameraFrameWithName(M,K);const _=(v=m.animationManager.getCurrentClip())==null?void 0:v.duration;if(_){console.log(_);const B=_/b;for(let F=0;F{const[e,t]=me.useState(null),[r,i]=me.useState(null),[s,o]=me.useState(null),[a,l]=me.useState(null),[A,c]=me.useState(null),[u,f]=me.useState(null),[d,h]=me.useState(null),[p,m]=me.useState(null),[g,v]=me.useState(null),[y,w]=me.useState(null),[C,b]=me.useState(!1);let E=!1,[x,S]=me.useState(!1);me.useEffect(()=>{if(E||x)return;S(!0),E=!0;const{scene:_,camera:B,controls:F,characterManager:R,sceneElements:k}=mpe("editor-scene");m(B),h(_),t(R),l(k),c(R.animationManager),f(R.lookAtManager),v(F),i(new vpe(R)),o(new ype(R))},[]);const M=_=>{_==null&&(_=!C),b(_),d.traverse(B=>{B.isMesh&&B.setDebugMode&&B.setDebugMode(_)})},Z=_=>{_?d.add(a):d.remove(a)},K=_=>{g&&(fE.to(g.target,{x:_.targetX??0,y:_.targetY??0,z:_.targetZ??0,duration:1}),fE.fromTo(g,{maxDistance:g.getDistance(),minDistance:g.getDistance(),minPolarAngle:g.getPolarAngle(),maxPolarAngle:g.getPolarAngle(),minAzimuthAngle:g.getAzimuthalAngle(),maxAzimuthAngle:g.getAzimuthalAngle()},{maxDistance:_.distance,minDistance:_.distance,minPolarAngle:Math.PI/2-.11,maxPolarAngle:Math.PI/2-.11,minAzimuthAngle:-.78,maxAzimuthAngle:-.78,duration:1}).then(()=>{g.minPolarAngle=0,g.maxPolarAngle=3.1415,g.minDistance=.5,g.maxDistance=10,g.minAzimuthAngle=1/0,g.maxAzimuthAngle=1/0}))};return P.jsx(ni.Provider,{value:{manifest:y,setManifest:w,scene:d,characterManager:e,loraDataGenerator:r,spriteAtlasGenerator:s,showEnvironmentModels:Z,debugMode:C,toggleDebugMode:M,animationManager:A,lookAtManager:u,camera:p,moveCamera:K,controls:g,sceneElements:a},children:n.children})},wpe={NORMAL:"NORMAL",AR:"AR",AR_FRONT:"AR_FRONT",VR:"VR"},ot={LANDING:"LANDING",CREATE:"CREATE",CLAIM:"CLAIM",LOAD:"LOAD",APPEARANCE:"APPEARANCE",BATCHDOWNLOAD:"BATCHDOWNLOAD",BIO:"BIO",SAVE:"SAVE",MINT:"MINT",CHAT:"CHAT",OPTIMIZER:"OPTIMIZER",BATCHMANIFEST:"BATCHMANIFEST",WALLET:"WALLET"},Bi=Y.createContext(),Cpe=n=>{const[e,t]=Y.useState(wpe.NORMAL),[r,i]=Y.useState(ot.LANDING),[s,o]=Y.useState(!1),[a,l]=Y.useState(!1);return P.jsx(Bi.Provider,{value:{viewMode:r,setViewMode:i,isLoading:s,setIsLoading:o,mouseIsOverUI:a,setMouseIsOverUI:l,currentCameraMode:e,setCurrentCameraMode:t},children:n.children})},bpe="modulepreload",xpe=function(n){return"/CharacterStudio/"+n},Nk={},Ipe=function(e,t,r){if(!t||t.length===0)return e();const i=document.getElementsByTagName("link");return Promise.all(t.map(s=>{if(s=xpe(s),s in Nk)return;Nk[s]=!0;const o=s.endsWith(".css"),a=o?'[rel="stylesheet"]':"";if(!!r)for(let c=i.length-1;c>=0;c--){const u=i[c];if(u.href===s&&(!o||u.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${s}"]${a}`))return;const A=document.createElement("link");if(A.rel=o?"stylesheet":bpe,o||(A.as="script",A.crossOrigin=""),A.href=s,document.head.appendChild(A),o)return new Promise((c,u)=>{A.addEventListener("load",c),A.addEventListener("error",()=>u(new Error(`Unable to preload CSS for ${s}`)))})})).then(()=>e()).catch(s=>{const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=s,window.dispatchEvent(o),!o.defaultPrevented)throw s})};function Xw(){return Xw=Object.assign||function(n){for(var e=1;e=0)&&(t[i]=n[i]);return t}function Epe(n){me.useEffect(n,[])}function Upe(n,e){e===void 0&&(e={});var t=e,r=t.volume,i=r===void 0?1:r,s=t.playbackRate,o=s===void 0?1:s,a=t.soundEnabled,l=a===void 0?!0:a,A=t.interrupt,c=A===void 0?!1:A,u=t.onload,f=Fpe(t,["id","volume","playbackRate","soundEnabled","interrupt","onload"]),d=Y.useRef(null),h=Y.useRef(!1),p=Y.useState(null),m=p[0],g=p[1],v=Y.useState(null),y=v[0],w=v[1],C=function(){typeof u=="function"&&u.call(this),h.current&&g(this.duration()*1e3),w(this)};Epe(function(){return Ipe(()=>import("./howler-ccbf4ffc.js").then(M=>M.h),[]).then(function(M){if(!h.current){var Z;d.current=(Z=M.Howl)!==null&&Z!==void 0?Z:M.default.Howl,h.current=!0,new d.current(Xw({src:Array.isArray(n)?n:[n],volume:i,rate:o,onload:C},f))}}),function(){h.current=!1}}),Y.useEffect(function(){d.current&&y&&w(new d.current(Xw({src:Array.isArray(n)?n:[n],volume:i,onload:C},f)))},[JSON.stringify(n)]),Y.useEffect(function(){y&&(y.volume(i),y.rate(o))},[i,o]);var b=Y.useCallback(function(M){typeof M>"u"&&(M={}),!(!y||!l&&!M.forceSoundEnabled)&&(c&&y.stop(),M.playbackRate&&y.rate(M.playbackRate),y.play(M.id))},[y,l,c]),E=Y.useCallback(function(M){y&&y.stop(M)},[y]),x=Y.useCallback(function(M){y&&y.pause(M)},[y]),S=[b,{sound:y,stop:E,pause:x,duration:m}];return S}const Spe=[{name:"background/cc_bgm.wav",offset:0,duration:123458.58333333334},{name:"background/cc_bgm_balanced.wav",offset:123458.58333333334,duration:123458.60416666666},{name:"effect/character-load.wav",offset:246917.1875,duration:3030},{name:"effect/class-select.wav",offset:249947.1875,duration:2780},{name:"effect/switchingItem.wav",offset:252727.1875,duration:623.75},{name:"ui/back-next-button.wav",offset:253350.9375,duration:155.02083333333334},{name:"ui/class-mouse-over.wav",offset:253505.95833333334,duration:217.52083333333334},{name:"ui/class_click.wav",offset:253723.4791666667,duration:3123.75},{name:"ui/class_pass.wav",offset:256847.2291666667,duration:155},{name:"ui/option_click.wav",offset:257002.2291666667,duration:155.02083333333334},{name:"ui/randomize-button.wav",offset:257157.25000000003,duration:342.5208333333333},{name:"ui/section_click.wav",offset:257499.77083333337,duration:155}],_pe="/CharacterStudio/assets/sounds-3322d50e.mp3",Cs=me.createContext(),Qpe=n=>{const e=i=>Spe.find(s=>i.test(s.name)),[t]=Upe(_pe,{sprite:{switchItem:[e(/switchingItem/).offset,e(/switchingItem/).duration],classSelect:[e(/class-select/).offset,e(/class-select/).duration],characterLoad:[e(/character-load/).offset,e(/character-load/).duration],randomizeButton:[e(/randomize-button/).offset,e(/randomize-button/).duration],classMouseOver:[e(/class-mouse-over/).offset,e(/class-mouse-over/).duration],backNextButton:[e(/back-next-button/).offset,e(/back-next-button/).duration]}}),r=(i,s=0)=>{s===0?t({id:i}):setTimeout(()=>{t({id:i})},s)};return P.jsx(Cs.Provider,{value:{playSound:r},children:n.children})};function $s(n){"@babel/helpers - typeof";return $s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},$s(n)}function lo(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}function Rpe(n,e){if($s(n)!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var r=t.call(n,e||"default");if($s(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function KH(n){var e=Rpe(n,"string");return $s(e)=="symbol"?e:String(e)}function Dk(n,e){for(var t=0;tn.length)&&(e=n.length);for(var t=0,r=new Array(e);t{r.geometry&&(r.geometry.computeBoundingBox(),r.geometry.boundingBox&&(r.geometry.boundingBox.applyMatrix4(r.matrixWorld),r.geometry.boundingBox.min.yt&&(t=r.geometry.boundingBox.max.y)))}),{minY:e,maxY:t}}frameCloseupShot(){this.frameShot("head","head")}frameMediumShot(){this.frameShot("chest","head")}frameCowboyShot(){this.frameShot("hips","head")}frameFullShot(){this.frameShot("leftFoot","head")}frameShot(e,t,r=null,i=!1,s=!0){const o=this._getBoneWorldPositionWithOffset(e,i),a=this._getBoneWorldPositionWithOffset(t,s);o.y-=this.frameOffset.max,a.y+=this.frameOffset.min,r=r||new z(0,0,0),this.positionCameraBetweenPoints(o,a,r)}setBottomFrameOffset(e){this.frameOffset.min=e}setTopFrameOffset(e){this.frameOffset.max=e}_setBonesOffset(e){for(const t in this.boneOffsets){const r=this._getMinMaxOffsetByBone(this.characterManager.characterModel,t,e);this.boneOffsets[t]=r}}_getBoneWorldPositionWithOffset(e,t){const r=this._getFirstBoneWithName(e);if(!r||!this.boneOffsets[e])return new z;const i=new z;r.getWorldPosition(i);const s=t?this.boneOffsets[e].max:this.boneOffsets[e].min;return i.y+=s.y,i}_getBoneWorldPosition(e){const t=this._getFirstBoneWithName(e);return t!=null?new z().setFromMatrixPosition(t.matrixWorld):(console.warn(`Bone with name '${e}' not found in one of the skinned meshes.`),new z(0,0,0))}_getFirstBoneWithName(e){let t=null;return this.characterManager.characterModel.traverse(r=>{if(r instanceof qA){if(!r.geometry){console.error("Invalid skinned mesh found in children.");return}const i=r.skeleton.bones.findIndex(s=>s.name===e);if(i!==-1){t=r.skeleton.bones[i];return}}}),t}setCameraFrameWithName(e,t){switch(e.toLowerCase()){case"fullshot":this.frameShot("leftFoot","head",t);break;case"cowboyshot":this.frameShot("hips","head",t);break;case"mediumshot":this.frameShot("chest","head",t);break;case"mediumcloseup":case"mediumcloseupshot":this.frameShot("chest","head",t,!0);break;case"closeup":case"closeupshot":this.frameShot("head","head",t);break;default:console.warn("unkown cameraFrame: "+e+". Please use fullShot, cowboyShot, mediumShot, mediumCloseup or closeup"),this.frameShot("leftFoot","head",t);break}}_getMinMaxOffsetByBone(e,t,r){if(!e||!e.traverse)return console.error("Invalid parent object provided."),null;const i=new z(1/0,1/0,1/0),s=new z(-1/0,-1/0,-1/0);return e.traverse(async o=>{if(o instanceof qA){const a=this._saveBonesPos(o.skeleton),l=d=>new Promise(h=>setTimeout(h,d));if(o.skeleton.pose(),await l(10),!o.geometry){console.error("Invalid skinned mesh found in children.");return}const A=o.skeleton.bones.findIndex(d=>d.name===t);if(A===-1){console.error(`Bone with name '${t}' not found in one of the skinned meshes.`);return}const c=o.geometry.getAttribute("position"),u=o.geometry.getAttribute("skinWeight"),f=o.geometry.getAttribute("skinIndex");for(let d=0;d=r){const g=o.skeleton.bones[A],v=new z().setFromMatrixPosition(g.matrixWorld),y=h.clone().sub(v);i.min(y),s.max(y)}}this._restoreSavedPose(a,o.skeleton)}}),{min:i,max:s}}_saveBonesPos(e){let t=[];return e.bones.forEach(r=>{t.push({position:r.position.clone(),rotation:r.rotation.clone(),scale:r.scale.clone()})}),t}_restoreSavedPose(e,t){e&&t.bones.forEach((r,i)=>{r.position.copy(e[i].position),r.rotation.copy(e[i].rotation),r.scale.copy(e[i].scale)})}positionCameraBetweenPoints(e,t,r,i=30){const s=new ws;s.expandByPoint(e),s.expandByPoint(t),this.camera.fov=i;const o=this.camera.fov*(Math.PI/180),l=s.getSize(new z).length()/(2*Math.tan(o/2));s.getCenter(Zp),this.camera.position.copy(Zp),r.y*=.5,this.camera.lookAt(Zp.clone().sub(r));const A=new z;this.camera.getWorldDirection(A),this.camera.position.addScaledVector(A,-l),this.camera.updateProjectionMatrix()}setCamera(e,t,r=30){this.camera.position.copy(e),this.camera.fov=r,Zp.set(0,0,-1),this.cameraDir=Zp.applyQuaternion(this.camera.quaternion),this.cameraDir.normalize(),this.camera.position.x-=this.cameraDir.x*t,this.camera.position.z-=this.cameraDir.z*t}setBackground(e){if(Array.isArray(e)){const t=e[3]==null?1:e[3];this.setBackgroundColor(e[0],e[1],e[2],t)}else this.setBackgroundImage(e)}setBackgroundColor(e,t,r,i){const s=new Re(e,t,r,i);this.sceneBackground=s,i==null&&(i=1),i>1&&(i=1),i<0&&(i=0),this.sceneBackgroundAlpha=i,this.backgroundMaterial.color=s,this.usesBackgroundImage=!1}setBackgroundImage(e){return new Promise(async(t,r)=>{try{const i=await this.texureLoader.load(e);i&&(i.wrapS=i.wrapT=hs,this.sceneBackground=i,this.usesBackgroundImage=!0,this.sceneBackgroundAlpha=1,t())}catch(i){console.error("Error loading background image: ",i),r(i)}})}_setBackground(){if(this.usesBackgroundImage==!1&&this.sceneBackgroundAlpha!=1)if(this.sceneBackgroundAlpha==0)this.scene.background=null;else{this.scene.background=null,this.scene.add(this.backgroundPlane),this.backgroundPlane.position.copy(this.camera.position);var e=new z(0,0,-1);e.applyQuaternion(this.camera.quaternion);var t=100;this.backgroundPlane.position.addScaledVector(e,t),this.backgroundPlane.lookAt(this.camera.position)}else this.scene.background=this.sceneBackground}_restoreBackground(){this.scene.background=null,this.usesBackgroundImage==!1&&this.sceneBackgroundAlpha!=1&&this.scene.remove(this.backgroundPlane)}_createImage(e,t,r=!1){const i=e/t;this.renderer.setSize(e,t);const s="image/png";this.camera.aspect=i,this.camera.updateProjectionMatrix();const o=r?this.pixelRenderer:this.renderer;try{this._setBackground(),o.render(this.scene,this.camera);let a=o.domElement.toDataURL(s);return this._restoreBackground(),a}catch(a){return console.error(a),null}}savePixelScreenshot(e,t,r,i){this.pixelRenderer.setPixelSize(i),this.pixelRenderer.setSize(t,r);const s=this._createImage(t,r,!0),o="image/octet-stream",a="image/png";this.saveFile(s.replace(a,o),e+".png")}saveScreenshot(e,t,r){const i=this._createImage(t,r),s="image/octet-stream",o="image/png";this.saveFile(i.replace(o,s),e+".png")}getScreenshotImage(e,t){const r=this._createImage(e,t),i=new Image;return i.src=r,i}getScreenshotTexture(e,t){const r=this.getScreenshotImage(e,t),i=new ir(r);return i.needsUpdate=!0,i}getScreenshotBlob(e,t){const r=this._createImage(e,t),i=hJ.Buffer.from(r.replace(/^data:image\/\w+;base64,/,""),"base64");return new Blob([i],{type:"image/jpeg"})}saveFile(e,t){const r=document.createElement("a");typeof r.download=="string"?(document.body.appendChild(r),r.download=t,r.href=e,r.click(),document.body.removeChild(r)):window.open(e,"_blank").document.write(""+t+"")}}const Ihe=2;class Fhe{constructor(e=.5,t=.5,r=1,i=5){this.vrmBlinkers=[],this.mode="ready",this.clock=new xZ,this.closeTime=e,this.openTime=t,this.continuity=r,this.randomness=i,this._eyeOpen=1,this._blinkCounter=0,this.isTakingScreenShot=!1,this.update()}addVRM(e){this.vrmBlinkers.push(e)}removeVRM(e){const t=this.vrmBlinkers.indexOf(e);t!==-1&&this.vrmBlinkers.splice(t,1)}enableScreenshot(){this.isTakingScreenShot=!0,this._eyeOpen=Ihe,this._updateBlinkers()}disableScreenshot(){this.isTakingScreenShot=!1}update(){setInterval(()=>{if(this.isTakingScreenShot)return;const e=this.clock.getDelta();switch(this.mode){case"closing":this._eyeOpen>0?this._eyeOpen-=e/this.closeTime:(this._eyeOpen=0,this.mode="open"),this._updateBlinkers();break;case"open":this._eyeOpen<1?this._eyeOpen+=e/this.openTime:(this._eyeOpen=1,this.mode="ready"),this._updateBlinkers();break;case"ready":this._blinkCounter+=e,this._blinkCounter>=this.continuity&&(Math.floor(Math.random()*this.randomness)===0&&(this.mode="closing"),this._blinkCounter=0);break}},1e3/30)}_updateBlinkers(){this.vrmBlinkers.forEach(e=>{e.expressionManager.setValue(ci.Blink,1-this._eyeOpen),e.expressionManager.update()})}}var Nn;(function(n){n[n.ARRAY_BUFFER=34962]="ARRAY_BUFFER",n[n.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",n[n.BYTE=5120]="BYTE",n[n.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",n[n.SHORT=5122]="SHORT",n[n.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",n[n.UNSIGNED_INT=5125]="UNSIGNED_INT",n[n.FLOAT=5126]="FLOAT",n[n.LINEAR=9729]="LINEAR",n[n.REPEAT=10497]="REPEAT"})(Nn||(Nn={}));const sU="blend_",Fk="vrmColliderSphere";function Ehe(n){return{title:n.name,version:"v0",author:n.authors[0]||"",contactInformation:n.contactInformation,allowedUserName:n.allowedUserName,violentUssageName:n.allowExcessivelyViolentUsage?"Allow":"Disallow",sexualUssageName:n.allowExcessivelySexualUsage?"Allow":"Disallow",commercialUssageName:"Disallow"}}function Uhe(n){const e=[];for(const t in n.humanBones)e.push({bone:t,node:n.humanBones[t].node});return{humanBones:e}}function She(n){switch(n){case"happy":return"joy";case"sad":return"sorrow";case"relaxed":return"fun";case"aa":return"a";case"ih":return"i";case"ou":return"u";case"ee":return"e";case"oh":return"o";default:return n}}function _he(n){if(n.includes("Thumb")){if(n.includes("Metacarpal"))return n.replace("Metacarpal","Proximal");if(n.includes("Proximal"))return n.replace("Proximal","Intermediate")}return n}class Qhe{parse(e,t,r,i,s,o,a){var Xe;const l=Ehe(e.meta),A=Uhe(e.humanoid),c=e.materials,u=[],f={generator:"UniGLTF-2.0.0",version:"2.0"};if(t)if(A)if(l){if(!c)throw new Error("materials is undefined or null")}else throw new Error("meta is undefined or null");else throw new Error("humanoid is undefined or null");else throw new Error("avatar is undefined or null");const d=c.filter((G,J,se)=>se.findIndex(fe=>fe.name===G.name.replace(" (Outline)",""))===J).map(G=>G),h=d.map(G=>G.name),p=r?{name:"icon",imageBitmap:r.image}:null,m=d.filter(G=>G.map).map(G=>{if(!G.map)throw new Error(G.name+" map is null");return{name:G.name,imageBitmap:G.map.image}}),g=d.filter(G=>G.userData.shadeTexture).map(G=>{if(!G.userData.shadeTexture)throw new Error(G.userData.shadeTexture+" map is null");return{name:G.name+"_shade",imageBitmap:G.userData.shadeTexture.image}}),v=d.filter(G=>G.roughnessMap).map(G=>G.roughnessMap?{name:G.name+"_orm",imageBitmap:G.roughnessMap.image}:null),y=d.filter(G=>G.roughnessMap).map(G=>G.normalMap?{name:G.name+"_normal",imageBitmap:G.normalMap.image}:null),w=[...m,...g,...v,...y].filter(G=>G!==null),C=Dhe(w,p),b=khe(C),E=Vhe(C),x=Nhe(d,w),S=t.children.filter(G=>G.children.length>0&&G.children[0].type===fi.Bone)[0],M=PH(S).filter(G=>G.name!==Fk),Z=M.map(G=>G.name),K=M.map(G=>({children:G.children.filter(J=>J.name!==Fk).map(J=>Z.indexOf(J.name)),name:G.name,rotation:[G.quaternion.x,G.quaternion.y,G.quaternion.z,G.quaternion.w],scale:[G.scale.x,G.scale.y,G.scale.z],translation:[G.position.x,G.position.y,G.position.z]})),_=[],B=t.children.filter(G=>G.type===fi.Group||G.type===fi.SkinnedMesh),F=[];B.forEach(G=>{const J=G.type===fi.Group?G.children[0]:G,se=J.geometry.attributes,fe=new aA(se.position,Nn.FLOAT,Lt.POSITION,ra.VEC3,J.name,void 0);F.push(fe);const ve=F.length-1,W=new aA(se.normal,Nn.FLOAT,Lt.NORMAL,ra.VEC3,J.name,void 0);F.push(W),F.push(new aA(se.uv,Nn.FLOAT,Lt.UV,ra.VEC2,J.name,void 0)),F.push(new aA(se.skinWeight,Nn.FLOAT,Lt.SKIN_WEIGHT,ra.VEC4,J.name,void 0)),F.push(new aA(se.skinIndex,Nn.UNSIGNED_SHORT,Lt.SKIN_INDEX,ra.VEC4,J.name,void 0)),(G.type===fi.Group?G.children.map(D=>D):[G]).forEach(D=>{if(!D.geometry.index)throw new Error(D.name+" geometry.index is null");F.push(new aA(D.geometry.index,Nn.UNSIGNED_INT,Lt.INDEX,ra.SCALAR,J.name,D.name))}),J.morphTargetDictionary||(J.morphTargetDictionary={},J.morphTargetInfluences=[],J.geometry.morphAttributes={},J.updateMorphTargets()),J.geometry.userData.targetNames=[],console.warn("taking only mesh 0 for morph targets now, take the correct mesh");for(const D in e.expressionManager.expressionMap){const $=e.expressionManager.expressionMap[D],ee=$._binds.map(te=>({mesh:0,index:te.index,weight:te.weight*100}));if(ee.length>0){let te=!1;for(const we in ci)if(D===ci[we]&&D!=="surprised"){u.push({name:D,presetName:She(D),binds:ee,isBinary:$.isBinary}),te=!0;break}te===!1&&u.push({name:D,presetName:"unknown",binds:ee,isBinary:$.isBinary})}}const I=(D,$,ee,te)=>{const we=[],Ce=[];for(let Ee=0;Ee0){const Ve=we.length%4,_e=Ve===0?0:4-Ve;if(_e>0)for(let ye=0;ye<_e;ye++)we.push(0),Ce.push(0,0,0);const re={targetMeshDataIndex:ve,count:we.length,indices:new Uint32Array(we),values:new Float32Array(Ce)};F.push(new aA(te,Nn.FLOAT,ee,ra.VEC3,J.name,sU+$,re))}};for(const D in J.morphTargetDictionary){J.geometry.userData.targetNames.push(D);const $=J.morphTargetDictionary[D],ee=J.geometry.morphAttributes;I(ee.position[$].array,D,Lt.BLEND_POSITION,se.position),ee.normal&&I(ee.normal[$].array,D,Lt.BLEND_NORMAL,se.normal)}}),B.forEach(G=>{const J=G.type===fi.Group?G.children[0]:G,se=new Float32Array(J.skeleton.boneInverses.map(fe=>fe.elements).flat());F.push(new aA(new At(se,16),Nn.FLOAT,Lt.BIND_MATRIX,ra.MAT4,J.name,J.name))}),_.push(...F.map(G=>({byteOffset:0,componentType:G.valueType,count:G.attribute.count,max:G.max,min:G.min,normalized:!1,type:G.accessorsType})));const R=Mhe(B,F,h);B.forEach((G,J)=>{K.push({mesh:J,name:G.name,rotation:[G.quaternion.x,G.quaternion.y,G.quaternion.z,G.quaternion.w],scale:[G.scale.x,G.scale.y,G.scale.z],skin:J,translation:[G.position.x,G.position.y,G.position.z]})});const k=The(B,F,Z),T={humanBones:[]};A.humanBones.forEach(G=>{Z.indexOf(G.node.name)!=-1&&T.humanBones.push({bone:_he(G.bone),node:Z.indexOf(G.node.name),useDefaultValues:!0})});const V={floatProperties:{_DstBlend:.5,_ShadeShift:.5,_ShadeToony:.5,_ShadingGradeRate:.5},keywordMap:{_NORMALMAP:!1,MTOON_OUTLINE_COLOR_FIXED:!0,MTOON_OUTLINE_WIDTH_WORLD:!0},name:"VRMCombinedMat",renderQueue:2e3,shader:"VRM/MToon",tagMap:{RenderType:"Opaque"},textureProperties:{_MainTex:0,_ShadeTexture:0},vectorProperties:{_Color:[1,1,1,1],_EmissionColor:[0,0,0,1],_EmissionMap:[0,0,1,1],_MainTex:[0,0,1,1],_OutlineColor:[0,0,0,1],_OutlineWidthTexture:[0,0,1,1],_ReceiveShadowTexture:[0,0,1,1],_RimColor:[0,0,0,1],_RimTexture:[0,0,1,1],_ShadeColor:[.9,.9,.9,1]}},O={name:"STDCombinedMat",shader:"VRM_USE_GLTFSHADER"},L=[];d.forEach(G=>{G.type=="ShaderMaterial"?L.push(L.push(Object.assign({},V))):L.push(L.push(Object.assign({},O)))});const U=l;i.forEach(G=>{for(let J=0;JG.isSkinnedMesh))==null?void 0:Xe.skeleton)||null;for(let G=0;G{const ve=fe.sphere;se.colliders.push({radius:ve.radius*o,offset:{x:ve.offset[0]*o,y:ve.offset[1]*o,z:ve.offset[2]*o}})}),H.push(se)}}console.log("COLLIDER GROUPS",H);const N=G=>{for(let J=0;J{const J=N(G);if(J==-1)return[-1];{const se=[];return M[J].traverse(ve=>{ve.isBone&&se.push(N(ve.name))}),se}},oe=[];i.forEach(G=>{var W;const J=j(G.name),se=[];if(G.colliderGroups.forEach(Q=>{const I=Q.colliders[0];if(I!=null){const D=I.parent,$=H.findIndex(ee=>ee.name===D.name);$!=-1?se.push($):console.warn("No collider group for bone name: ",D.name+" was found")}else console.log("No colliders definition were present in vrm file file for: ",G.name+" spring bones")}),J===[-1]){console.warn("No bone found for spring bone "+G.name);return}let fe=N((W=G.center)==null?void 0:W.name);fe==-1&&console.warn("no center bone for spring bone "+G.name);const ve=G.settings;oe.push({bones:J,center:fe,colliderGroups:se,dragForce:ve.dragForce,gravityDir:{x:ve.gravityDir.x,y:ve.gravityDir.y,z:ve.gravityDir.z},gravityPower:ve.gravityPower,hitRadius:ve.hitRadius,stiffiness:ve.stiffness})});const ie={boneGroups:oe,colliderGroups:H};console.log(ie),U.texture=p?C.length-1:void 0;const de=[];de.push(...w.map(G=>({buffer:Ek(G.imageBitmap),type:Lt.IMAGE}))),F.forEach((G,J)=>{G.buffer?de.push({buffer:G.buffer,typeString:"",type:G.type}):G.sparse&&(de.push({buffer:G.sparse.indices,typeString:"indices",type:G.type,count:G.sparse.count}),de.push({buffer:G.sparse.values,typeString:"values",type:G.type}))}),p&&de.push({buffer:Ek(p.imageBitmap),type:Lt.IMAGE});let X=0,ne=0,ae=0,Be=0;const pe=de.map(G=>{const J={buffer:0,byteLength:G.buffer.byteLength,byteOffset:X,target:G.type===Lt.IMAGE||G.type===Lt.BIND_MATRIX?void 0:G.type===Lt.INDEX?Nn.ELEMENT_ARRAY_BUFFER:Nn.ARRAY_BUFFER};return X+=G.buffer.byteLength,G.type===Lt.IMAGE?(C[ne++].bufferView=Be,Be++):F[ae].sparse?(_[ae].sparse==null&&(_[ae].sparse={}),G.typeString==="indices"&&(_[ae].sparse.count=G.count,_[ae].sparse[G.typeString]={bufferView:Be,byteOffset:0,componentType:Nn.UNSIGNED_INT}),G.typeString==="values"&&(_[ae].sparse[G.typeString]={bufferView:Be,byteOffset:0}),G.typeString==="values"&&ae++,Be++):(F[ae].bufferIndex=Be,_[ae].bufferView=Be,ae++,Be++),J}),Fe=Lhe(t,K);Rhe(U);const rt={accessors:_,asset:f,buffers:[{byteLength:X}],bufferViews:pe,extensions:{VRM:{blendShapeMaster:{blendShapeGroups:u},firstPerson:{firstPersonBone:44,firstPersonBoneOffset:new z,lookAtHorizontalInner:{curve:[0,0,0,1,1,1,1,0],xRange:90,yRange:10},lookAtHorizontalOuter:{curve:[0,0,0,1,1,1,1,0],xRange:90,yRange:10},lookAtTypeName:"Bone",lookAtVerticalDown:{curve:[0,0,0,1,1,1,1,0],xRange:90,yRange:10},lookAtVerticalUp:{curve:[0,0,0,1,1,1,1,0],xRange:90,yRange:10}},materialProperties:L,humanoid:T,meta:U,secondaryAnimation:ie,specVersion:"0.0"}},extensionsUsed:["KHR_materials_unlit","KHR_texture_transform","VRM"],images:C,materials:x,meshes:R,nodes:K,samplers:b,scenes:Fe,skins:k,textures:E};console.log(rt);const Oe=new Uk(aU(JSON.stringify(rt,void 0,2)),"JSON"),ke=new Uk(xg(de.map(G=>G.buffer)),"BIN\0"),Qe=xg([Oe.buffer,ke.buffer]),Ge=xg([aU("glTF"),oU(2,4),oU(Qe.byteLength+12,4)]);a(xg([Ge,Qe]))}}function Rhe(n){n.title=n.title||"Character",n.version=n.version||"1",n.author=n.author||"Anon",n.contactInformation=n.contactInformation||"",n.reference=n.reference||"",n.allowedUserName=n.allowedUserName||"Everyone",n.violentUssageName=n.violentUssageName||"Disallow",n.sexualUssageName=n.sexualUssageName||"Disallow",n.commercialUssageName=n.commercialUssageName||"Disallow",n.otherPermissionUrl=n.otherPermissionUrl||"",n.licenseName=n.licenseName||"Redistribution_Prohibited",n.otherLicenseUrl=n.otherLicenseUrl||""}function PH(n){return n.children.length<=0?[n]:[n].concat(n.children.map(e=>PH(e)).flat())}function Ek(n){const e=document.createElement("canvas");e.width=n.width,e.height=n.height,e.getContext("2d").drawImage(n,0,0);const t=e.toDataURL("image/png"),r=atob(t.split(",")[1]),i=(4-r.length%4)%4,s=new ArrayBuffer(r.length+i),o=new DataView(s);for(let a=0;a4?A=r[a*n.itemSize+l]:l===0?A=n.getX(a):l===1?A=n.getY(a):l===2?A=n.getZ(a):A=n.getW(a),e===Nn.UNSIGNED_SHORT?o.setUint16(i,A,!0):e===Nn.UNSIGNED_INT?o.setUint32(i,A,!0):o.setFloat32(i,A,!0),i+=t}return s}class Uk{constructor(e,t){this.data=e,this.type=t;const r=this.data;this.buffer=xg([oU(r.byteLength,4),aU(this.type),r])}paddingBinary(e,t){const r=Math.ceil(e.byteLength/4)*4;if(e.byteLength===r)return e;const i=new Uint8Array(r);i.set(new Uint8Array(e),0);for(let s=e.byteLength;sp%3===0)),Math.max.apply(null,Array.from(A).filter((h,p)=>p%3===1)),Math.max.apply(null,Array.from(A).filter((h,p)=>p%3===2))]:void 0,this.min=r===Lt.POSITION||r===Lt.BLEND_POSITION?[Math.min.apply(null,Array.from(A).filter((h,p)=>p%3===0)),Math.min.apply(null,Array.from(A).filter((h,p)=>p%3===1)),Math.min.apply(null,Array.from(A).filter((h,p)=>p%3===2))]:void 0}else this.buffer=p1(this.attribute,this.valueType),this.max=r===Lt.POSITION||r===Lt.BLEND_POSITION?[Math.max.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===0)),Math.max.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===1)),Math.max.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===2))]:void 0,this.min=r===Lt.POSITION||r===Lt.BLEND_POSITION?[Math.min.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===0)),Math.min.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===1)),Math.min.apply(null,Array.from(this.attribute.array).filter((l,A)=>A%3===2))]:void 0}}var Fd;(function(n){n.MeshBasicMaterial="MeshBasicMaterial",n.MeshStandardMaterial="MeshStandardMaterial",n.MToonMaterial="MToonMaterial"})(Fd||(Fd={}));var ra;(function(n){n.SCALAR="SCALAR",n.VEC2="VEC2",n.VEC3="VEC3",n.VEC4="VEC4",n.MAT4="MAT4"})(ra||(ra={}));var Lt;(function(n){n.POSITION="POSITION",n.NORMAL="NORMAL",n.UV="UV",n.INDEX="INDEX",n.SKIN_WEIGHT="SKIN_WEIGHT",n.SKIN_INDEX="SKIN_INDEX",n.BLEND_POSITION="BLEND_POSITION",n.BLEND_NORMAL="BLEND_NORMAL",n.BIND_MATRIX="BIND_MATRIX",n.IMAGE="IMAGE"})(Lt||(Lt={}));var fi;(function(n){n.Group="Group",n.SkinnedMesh="SkinnedMesh",n.Object3D="Object3D",n.Bone="Bone"})(fi||(fi={}));const Mhe=(n,e,t)=>n.map(r=>{const i=r.type===fi.Group?r.children[0]:r,s=r.type===fi.Group?r.children.map(o=>o):[r];return{name:r.name,primitives:s.map(o=>{const a=e.map(A=>A.meshName===i.name?A.type:null),l=Array.isArray(o.material)?o.material[0].name:o.material.name;return{attributes:{JOINTS_0:a.indexOf(Lt.SKIN_INDEX),NORMAL:a.indexOf(Lt.NORMAL),POSITION:a.indexOf(Lt.POSITION),TEXCOORD_0:a.indexOf(Lt.UV),WEIGHTS_0:a.indexOf(Lt.SKIN_WEIGHT)},extras:{targetNames:o.geometry.userData.targetNames},indices:e.map(A=>A.type===Lt.INDEX&&A.meshName===i.name?A.name:null).indexOf(o.name),material:t.indexOf(l),mode:4,targets:i.geometry.userData.targetNames?i.geometry.userData.targetNames.map(A=>{const c=e.map(d=>d.type===Lt.BLEND_NORMAL&&d.meshName===i.name?d.name:null).indexOf(sU+A),u=e.map(d=>d.type===Lt.BLEND_POSITION&&d.meshName===i.name?d.name:null).indexOf(sU+A),f={};return u!==-1&&(f.POSITION=u),c!==-1&&(f.NORMAL=c),f}):void 0}})}}),The=(n,e,t)=>n.map(r=>{const i=r.type===fi.Group?r.children[0]:r;return{inverseBindMatrices:e.map(s=>s.type===Lt.BIND_MATRIX?s.meshName:null).indexOf(i.name),joints:i.skeleton.bones.map(s=>t.indexOf(s.name)).filter(s=>s!==-1),skeleton:t.indexOf(i.skeleton.bones[0].name)}}),Nhe=(n,e)=>n.map(t=>{let r,i=null;if(t=t.userData.vrmMaterial?t.userData.vrmMaterial:t,t.type==="ShaderMaterial")i={},i.shadeMultiplyTexture={index:e.map(h=>h.name).indexOf(t.uniforms.shadeMultiplyTexture.name)},r=t.color?[1,1,1,1]:void 0;else{const d=t;r=d.color?[d.color.r,d.color.g,d.color.b,1]:void 0}let s=-1;t.map?s=e.map(d=>d.name).indexOf(t.name):t.uniforms&&t.uniforms.map&&(s=e.map(d=>d.name).indexOf(t.uniforms.map.name));let o=-1;t.roughnessMap&&(o=e.map(d=>d.name).indexOf(t.name+"_orm"));let a=-1;t.normalMap&&(a=e.map(d=>d.name).indexOf(t.name+"_normal"));const l=s>=0?{extensions:{KHR_texture_transform:{offset:[0,0],scale:[1,1]}},index:s,texCoord:0}:void 0,A={baseColorFactor:r,baseColorTexture:l},c=o>=0?{index:o,texCoord:0}:void 0,u=a>=0?{index:a,texCoord:0}:void 0;if(c)A.metallicRoughnessTexture=c;else{const d=(()=>{switch(t.type){case Fd.MeshStandardMaterial:return t.metalness;case Fd.MeshBasicMaterial:return 0;default:return 0}})(),h=(()=>{switch(t.type){case Fd.MeshStandardMaterial:return t.roughness;case Fd.MeshBasicMaterial:return .9;default:return .9}})();A.metallicFactor=d,A.roughnessFactor=h}const f={alphaCutoff:t.alphaTest>0?t.alphaTest:void 0,alphaMode:t.transparent?"BLEND":t.alphaTest>0?"MASK":"OPAQUE",doubleSided:t.side===2,extensions:t.type==="ShaderMaterial"?{KHR_materials_unlit:{},VRMC_materials_mtoon:i}:void 0,name:t.name,pbrMetallicRoughness:A};return u&&(f.normalTexture=u),f}),Dhe=(n,e)=>(e?n.concat(e):n).filter(t=>t&&t.imageBitmap).map(t=>({bufferView:-1,mimeType:"image/png",name:t.name})),khe=n=>n.map(()=>({magFilter:Nn.LINEAR,minFilter:Nn.LINEAR,wrapS:Nn.REPEAT,wrapT:Nn.REPEAT})),Vhe=n=>n.map((e,t)=>({sampler:0,source:t})),Lhe=(n,e)=>{const t=e.map(r=>r.name);return[{nodes:n.children.filter(r=>r.type===fi.Object3D||r.type===fi.SkinnedMesh||r.type===fi.Group||r.type===fi.Bone).map(r=>t.indexOf(r.name))}]};function WH(){return(WH=Object.assign||function(n){for(var e=1;e0?u+s.byteLength:0;f%8&&(f+=8-f%8);let d=[],h=new DataView(new ArrayBuffer(24*n.levels.length)),p=(f||u+s.byteLength)+t.byteLength;for(let v=0;v0?f:0),!0),g.setBigUint64(60,BigInt(t.byteLength),!0),new Uint8Array(Hp([new Uint8Array(_r).buffer,m,h.buffer,a,s,new ArrayBuffer(f>0?f-(u+s.byteLength):0),t,...d]))}var AU,cU,Hhe={enableDebug:!1,isUASTC:!0,isKTX2File:!0,isInputSRGB:!0,generateMipmap:!0,needSupercompression:!0,isSetKTX2SRGBTransferFunc:!0},uU=new OffscreenCanvas(128,128),Rk=uU.getContext("2d",{willReadFrequently:!0}),OH=typeof document>"u";function zhe(n){return createImageBitmap(n).then(function(e){return uU.width=e.width,uU.height=e.height,Rk.drawImage(e,0,0),Rk.getImageData(0,0,e.width,e.height)})}function GH(n,e){return e===void 0&&(e={}),Xhe().then(function(t){var r=new t.BasisEncoder;return Yhe(e,r),r.setTexType(AU.cBASISTexType2D),Whe(n,ArrayBuffer)&&(n=new Blob([n])),zhe(n).then(function(i){r.setSliceSourceImage(0,new Uint8Array(i.data),i.width,i.height,cU.RAW);var s=new Uint8Array(10485760),o=r.encode(s);if(o===0)throw"encode failed";var a=new Uint8Array(s.buffer,0,o),l=Ghe(s);if(e.kvData){for(var A in e.kvData)l.keyValue[A]=e.kvData[A];a=Jhe(l,{keepWriter:!0})}return a})})}function Yhe(n,e){n===void 0&&(n={}),(n=Phe({},Hhe,n)).enableDebug!==void 0&&e.setDebug(n.enableDebug),n.isUASTC!==void 0&&e.setUASTC(n.isUASTC),n.isKTX2File!==void 0&&e.setCreateKTX2File(n.isKTX2File),n.isSetKTX2SRGBTransferFunc!==void 0&&e.setKTX2SRGBTransferFunc(n.isSetKTX2SRGBTransferFunc),n.generateMipmap!==void 0&&e.setMipGen(n.generateMipmap),n.isYFlip!==void 0&&e.setYFlip(n.isYFlip),n.qualityLevel!==void 0&&e.setQualityLevel(n.qualityLevel),n.compressionLevel!==void 0&&e.setCompressionLevel(n.compressionLevel),n.needSupercompression!==void 0&&e.setKTX2UASTCSupercompression(n.needSupercompression),n.isNormalMap!==void 0&&e.setNormalMap(n.isNormalMap)}var g1=null;function Xhe(){return g1||(g1=new Promise(function(n,e){OH?(importScripts("https://mdn.alipayobjects.com/rms/afts/file/A*SrRkQarYYl4AAAAAAAAAAAAAARQnAQ/basis_encoder.js"),fetch("https://mdn.alipayobjects.com/rms/afts/file/A*qFWbTrA0hZYAAAAAAAAAAAAAARQnAQ/basis_encoder.wasm").then(function(t){return t.arrayBuffer()}).then(function(t){BASIS({wasmBinary:t}).then(function(r){r.initializeBasis(),n(r)}).catch(e)}).catch(e)):Promise.all([fetch("https://mdn.alipayobjects.com/rms/afts/file/A*SrRkQarYYl4AAAAAAAAAAAAAARQnAQ/basis_encoder.js").then(function(t){return t.text()}),fetch("https://mdn.alipayobjects.com/rms/afts/file/A*qFWbTrA0hZYAAAAAAAAAAAAAARQnAQ/basis_encoder.wasm").then(function(t){return t.arrayBuffer()})]).then(function(t){var r=t[0],i=t[1],s=document.createElement("script");s.onload=function(){BASIS({wasmBinary:i}).then(function(o){o.initializeBasis(),n(o)}).catch(e)},s.src=URL.createObjectURL(new Blob([r])),s.onerror=e,document.body.appendChild(s)}).catch(e)})),g1}OH&&self.addEventListener("message",function(n){GH(n.data).then(function(e){self.postMessage(e)}).catch(function(e){self.postMessage({error:e})})});function ZH(n){const e=n.clone(),t=[];return n.traverse(r=>{r.userData.origIndexBuffer&&t.push(r.userData.origIndexBuffer)}),e.traverse(r=>{r.userData.origIndexBuffer&&(r.userData.origIndexBuffer=t.shift())}),e}function Khe(n){const e=ZH(n);let t;const r=[];e.traverse(s=>{if(!t&&s.isSkinnedMesh&&(t=_H(s)),s.isSkinnedMesh){if(s.geometry=s.geometry.clone(),s.skeleton=t,r.push(s),Array.isArray(s.material)){const o=s.material;s.material=new mu,s.material.map=o[0].map}s.userData.origIndexBuffer&&s.geometry.setIndex(s.userData.origIndexBuffer)}});const i=new Tr;return r.forEach(s=>{i.add(s)}),i.add(t.bones[0]),i}async function jhe(n,e,t){const r=await q_(n,t),i=await JH(r,e,t);return new Blob([i],{type:"model/gltf-binary"})}function $he(n,e,t,r){return new Promise(async(i,s)=>{const o=`${t&&t!==""?t:"AvatarCreatorModel"}`;qhe(n,e,r).then(a=>{zH(a,`${o}.vrm`),i()})})}async function qhe(n,e,t){const r=await q_(n,t);return JH(r,e,t)}function q_(n,e){const t=ZH(n),{createTextureAtlas:r=!0}=e;return r?Yde(t,e):(console.log("no atlas"),Jde(t,e))}async function epe(n,e="",t){const r=`${e&&e!==""?e:"AvatarCreatorModel"}`,{optimized:i=!0}=t,s=i?await q_(n,t):Khe(n);tpe(s).then(o=>{if(o instanceof ArrayBuffer)zH(o,`${r}.glb`);else{const a=JSON.stringify(o,null,2);rpe(a,`${r}.gltf`)}})}function tpe(n){return new Promise(e=>new V_().parse(n,r=>{e(r)},r=>{console.error("Error parsing",r)},{trs:!1,onlyVisible:!1,truncateDrawRange:!0,binary:!0,forcePowerOfTwoTextures:!1,maxTextureSize:1024}))}function npe(n){var r,i;const e=[];for(const s in n)if(((i=(r=n[s])==null?void 0:r.vrm)==null?void 0:i.springBoneManager)!=null){const o=n[s].vrm.springBoneManager.joints;for(const a of o)e.some(A=>A.name===a.bone.name)||e.push({name:a.bone.name,settings:a.settings,bone:a.bone,colliderGroups:a.colliderGroups,center:a.center})}const t=[];return e.forEach(s=>{for(const o in Lm)if(s.bone.parent.name==Lm[o]){t.push(s);break}}),t}function JH(n,e,t){const{screenshot:r=null,isVrm0:i=!1,vrmMeta:s=null,scale:o=1}=t;return new Promise(async a=>{const l=i?new Qhe:new Pfe,A={...spe(e),...Ahe(n,"CharacterCreator",s)};if(t.ktxCompression){console.log("ktx compression");for(let h=0;hw.toBlob(M)),E=await GH(b),x=new Blob(E,{type:"image/ktx2"}),S=await createImageBitmap(x);A.materials[h].map.source=S}}}}let c;n.traverse(h=>{h.isSkinnedMesh&&(c=h)}),(()=>{for(let h=0;h{h.updateMatrix(),h.updateMatrixWorld()}),c.skeleton.calculateInverses(),c.skeleton.computeBoneTexture(),c.skeleton.update()})(),c.skeleton.bones.filter(h=>h.name==="head")[0];const f=npe(e),d=[];l.parse(A,n,r,f,d,o,h=>{a(h)})})}function HH(n,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),t.href=URL.createObjectURL(n),t.download=e,t.click()}function rpe(n,e){HH(new Blob([n],{type:"text/plain"}),e)}function zH(n,e){HH(ipe(n),e)}function ipe(n){return new Blob([n],{type:"application/octet-stream"})}function spe(n){for(const e in n)if(n[e].vrm)return n[e].vrm}const ope=n=>{var e,t;(e=n.parser.json.extensions)!=null&&e.VRM?ape(n):(t=n.parser.json.extensions)!=null&&t.VRMC_vrm?lpe(n):console.warn("No valid vrm file was provided")},ape=n=>{var a,l,A;const e=n.parser.json,t=n.scene,r=e.nodes,i=(A=(l=(a=e.extensions)==null?void 0:a.VRM)==null?void 0:l.secondaryAnimation)==null?void 0:A.colliderGroups,s=[],o=r.map(c=>YH(c.name,s));i!=null&&i.forEach(c=>{const u=o[c.node],f=DH(t,u);if(f!=null){const d=c.colliders;f.userData.VRMcolliders=d.map(h=>({sphere:{radius:h.radius,offset:[h.offset.x,h.offset.y,h.offset.z]}}))}})},lpe=n=>{var l,A,c,u;const e=n.parser.json,t=n.scene,r=e.nodes,i=(A=(l=e.extensions)==null?void 0:l.VRMC_springBone)==null?void 0:A.colliderGroups,s=(u=(c=e.extensions)==null?void 0:c.VRMC_springBone)==null?void 0:u.colliders,o=[],a=r.map(f=>YH(f.name,o));i!=null&&i.forEach(f=>{const d=Yt(f.colliders);let h=-1,p=null;d.forEach(m=>{if(h!=s[m].node){h=s[m].node;const g=a[h];p=DH(t,g),p.userData.VRMcolliders=[]}if(p!=null){const g=s[m].shape;for(const v in g){const y=g[v];y!=null&&y.offset&&(y.offset[0]=-y.offset[0])}p.userData.VRMcolliders.push(g)}else console.error("no node with name "+a[h]+" was found")})})},YH=(n,e)=>{const t=Bt.sanitizeNodeName(n||"");return t in e?t+"_"+ ++e[t]:(e[t]=0,t)},Hw=[0,400,560,2400,4800],zw=[0,500,700,3e3,6e3],fU=[],il=[],eQ=1024,XH=44100;for(let n=0;n{requestAnimationFrame(t),this.update(r,i)};t()}start(e){this.audioContext=new AudioContext,this.mediaStreamSource=this.audioContext.createMediaStreamSource(e),this.meter=Yw.createAudioMeter(this.audioContext),this.mediaStreamSource.connect(this.meter)}startFromAudioFile(e){this.audioContext||(this.audioContext=new AudioContext),this.userSpeechAnalyzer||(this.userSpeechAnalyzer=this.audioContext.createAnalyser()),this.userSpeechAnalyzer.smoothingTimeConstant=.5,this.userSpeechAnalyzer.fftSize=eQ,this.mediaStreamSource&&this.mediaStreamSource.stop(),this.audioContext.decodeAudioData(e).then(t=>{this.mediaStreamSource=this.audioContext.createBufferSource(),this.mediaStreamSource.buffer=t,this.meter=Yw.createAudioMeter(this.audioContext),this.mediaStreamSource.connect(this.meter),this.mediaStreamSource.connect(this.audioContext.destination),this.mediaStreamSource.start(),this.mediaStreamSource.connect(this.userSpeechAnalyzer)})}destroy(){var e,t,r;return(e=this.meter)==null||e.shutdown(),this.meter=null,(t=this.mediaStreamSource)==null||t.disconnect(),((r=this.audioContext)==null?void 0:r.close().catch(()=>{}))||Promise.resolve()}update(e){if(this.meter){const{volume:t}=this.meter;if(t<.01)this.vrm.expressionManager.setValue(ci.Oh,0),this.vrm.expressionManager.setValue(ci.Ah,0),this.vrm.expressionManager.setValue(ci.Ee,0);else{const{ah:r,oh:i,ee:s}=this.update2();this.vrm.expressionManager.setValue(ci.Oh,i),this.vrm.expressionManager.setValue(ci.Ah,r),this.vrm.expressionManager.setValue(ci.Ee,s),this.vrm.expressionManager.update(e)}}}update2(){function e(A){const u=new Float32Array(A.length);for(let f=0;f0&&(i[A]+=r[c]);i[A]/=il[A+1]-il[A]}for(let A=0;A0&&(s[A]+=r[c]);i[A]/=il[A+1]-il[A],s[A]=s[A]/(fU[A+1]-fU[A])}const o=Math.max(s[1],i[1])>.2?1-2*Math.max(i[2],s[2]):(1-2*Math.max(i[2],s[2]))*5*Math.max(i[1],s[1]),a=3*Math.max(i[3],s[3]),l=.8*(Math.max(i[1],s[1])-Math.max(i[3],s[3]));return{oh:o,ee:l,ah:a}}static createAudioMeter(e){const t=e.createScriptProcessor(512);return t.onaudioprocess=r=>{const i=r.inputBuffer.getChannelData(0),s=i.length;let o=0,a;for(let A=0;A=t.clipLevel&&(t.clipping=!0,t.lastClip=window.performance.now()),o+=a*a;const l=Math.sqrt(o/s);t.volume=Math.max(l,t.volume*t.averaging)},t.clipping=!1,t.lastClip=0,t.volume=0,t.clipLevel=.98,t.averaging=.95,t.clipLag=750,t.connect(e.destination),t.checkClipping=()=>t.clipping?(t.lastClip+t.clipLag{t.disconnect(),t.onaudioprocess=null},t}}const m1=new z;class Ape{constructor(e,t,r){this.bonesInfo=[],this.curMousePos=new We,this.hotzoneSection=s(),this.enabled=!1,this.userActivated=!1,this.lookInterest=1,this.hasInterest=!0,this.interestSpeed=.3,this.onCanvas=!0,this.camera=r,this.maxLookPercent={neck:{maxy:15,miny:10,maxx:30,minx:10},spine:{maxy:0,miny:0,maxx:30,minx:10},left:{maxy:15,miny:20,maxx:35,minx:35},right:{maxy:15,miny:20,maxx:35,minx:35}},window.addEventListener("mousemove",o=>{this.curMousePos={x:o.clientX,y:o.clientY}});const i=document.getElementById(t);i&&(i.addEventListener("mouseleave",()=>{this.onCanvas=!1}),i.addEventListener("mouseenter",()=>{this.onCanvas=!0})),window.addEventListener("resize",()=>{this.hotzoneSection=s()});function s(){const o=window.innerWidth*e/100,a=(window.innerWidth-o)/2;return{xStart:a,xEnd:window.innerWidth-a,yStart:50,yEnd:window.innerHeight-80}}}setActive(e){console.log("is activating"),this.userActivated=e}setCamera(e){this.camera=e}addVRM(e){const t=e.data.isVRM0||!1,r=e.humanoid.humanBones;t||(r.neck.node.userData.inverseLookAt=!0,r.spine.node.userData.inverseLookAt=!0,r.leftEye&&(r.leftEye.node.userData.inverseLookAt=!0),r.rightEye&&(r.rightEye.node.userData.inverseLookAt=!0));const i={vrm:e,neckBone:r.neck.node,spineBone:r.spine.node,leftEyeBone:r.leftEye?r.leftEye.node:null,rightEyeBone:r.rightEye?r.rightEye.node:null};this.bonesInfo.push(i)}removeVRM(e){const t=this.bonesInfo.find(r=>r.vrm===e);if(t){const r=this.bonesInfo.indexOf(t);this.bonesInfo.splice(r,1)}}_getMouseDegrees(e,t,r){let i=0,s=0,o,a,l,A,c={x:window.innerWidth,y:window.innerHeight};return e<=c.x/2&&(o=c.x/2-e,a=o/(c.x/2)*100,i=r.maxx*a/100*-1),e>=c.x/2&&(o=e-c.x/2,a=o/(c.x/2)*100,i=r.minx*a/100),t<=c.y/2&&(l=c.y/2-t,A=l/(c.y/2)*100,s=r.maxy*.5*A/100*-1),t>=c.y/2&&(l=t-c.y/2,A=l/(c.y/2)*100,s=r.miny*A/100),{x:i,y:s}}lerp(e,t,r){return(1-r)*e+r*t}_moveJoint(e,t){const r=e.userData.inverseLookAt===!0?1:-1;if(Object.keys(e).length!==0){const i=(this.camera.position.y-1.8)*window.innerHeight/2;let s=this._getMouseDegrees(this.curMousePos.x,this.curMousePos.y-i,t);const o=.8;e.rotation.y=this.lerp(Wt.degToRad(s.x),e.rotation.y,o),e.rotation.x=this.lerp(Wt.degToRad(s.y*r),e.rotation.x,o)}}update(){m1.set(0,0,1),m1.applyQuaternion(this.camera.quaternion);const e=m1.z>0;this.curMousePos.x>this.hotzoneSection.xStart&&this.curMousePos.xthis.hotzoneSection.yStart&&this.curMousePos.y{this._moveJoint(t.neckBone,this.maxLookPercent.neck),this._moveJoint(t.spineBone,this.maxLookPercent.spine),this._moveJoint(t.leftEyeBone,this.maxLookPercent.left),this._moveJoint(t.rightEyeBone,this.maxLookPercent.right)})}}class v1{constructor(e){const{assetsLocation:t,traitsDirectory:r,thumbnailsDirectory:i,traitIconsDirectorySvg:s,animationPath:o,exportScale:a,displayScale:l,initialTraits:A,requiredTraits:c,randomTraits:u,colliderTraits:f,lipSyncTraits:d,blinkerTraits:h,typeRestrictions:p,defaultCullingLayer:m,defaultCullingDistance:g,offset:v,vrmMeta:y,traits:w,textureCollections:C,colorCollections:b,canDownload:E=!0,downloadOptions:x={}}=e;this.assetsLocation=t,this.traitsDirectory=r,this.thumbnailsDirectory=i,this.traitIconsDirectorySvg=s,this.displayScale=l||a||1,this.animationPath=Yt(o),this.requiredTraits=Yt(c),this.randomTraits=Yt(u),this.initialTraits=A||[...new Set(this.requiredTraits.concat(this.randomTraits))],this.colliderTraits=Yt(f),this.lipSyncTraits=Yt(d),this.blinkerTraits=Yt(h),this.typeRestrictions=p,this.defaultCullingLayer=m,this.defaultCullingDistance=g,this.offset=v,this.canDownload=E,this.downloadOptions=x;const S=()=>{const K=[];for(const _ in w)K.push(w[_].trait);return K};this.allTraits=S(),S(),(()=>{if(this.typeRestrictions)for(const K in this.typeRestrictions)Yt(this.typeRestrictions[K]).forEach(B=>{this.typeRestrictions[B]==null&&(this.typeRestrictions[B]=[]),this.typeRestrictions[B].indexOf(K)==-1&&this.typeRestrictions[B].push(K)})})(),(()=>{x.vrmMeta=x.vrmMeta||y,x.scale=x.scale||a||1,x.mToonAtlasSize=x.mToonAtlasSize||2048,x.mToonAtlasSizeTransp=x.mToonAtlasSizeTransp||1024,x.stdAtlasSize=x.stdAtlasSize||2048,x.stdAtlasSizeTransp=x.stdAtlasSizeTransp||1024,x.exportStdAtlas=x.exportStdAtlas||!1,x.exportMtoonAtlas=x.exportMtoonAtlas||!0,x.screenshotFaceDistance=x.screenshotFaceDistance||1,x.screenshotFaceOffset=x.screenshotFaceOffset||[0,0,0],x.screenshotResolution=x.screenshotResolution||[512,512],x.screenshotBackground=x.screenshotBackground||[.1,.1,.1],x.screenshotFOV=x.screenshotFOV||75,!x.exportStdAtlas&&!x.exportMtoonAtlas&&(x.exportMtoonAtlas=!0)})(),this.textureTraits=[],this.textureTraitsMap=null,this.createTextureTraits(C),this.colorTraits=[],this.colorTraitsMap=null,this.createColorTraits(b),this.modelTraits=[],this.modelTraitsMap=null,this.createModelTraits(w)}appendManifestData(e,t){e.textureTraits.forEach(r=>{const i=this.getTextureGroup(r.trait);i!=null?i.appendCollection(r,t):(this.textureTraits.push(r),this.textureTraitsMap.set(r.trait,r))}),e.colorTraits.forEach(r=>{const i=this.getColorGroup(r.trait);i!=null?i.appendCollection(r,t):(this.colorTraits.push(r),this.colorTraitsMap.set(r.trait,r))}),e.modelTraits.forEach(r=>{const i=this.getModelGroup(r.trait);i!=null?i.appendCollection(r,t):(this.modelTraits.push(r),this.modelTraitsMap.set(r.trait,r))}),console.log(e)}getExportOptions(){return this.downloadOptions}getGroupModelTraits(){return this.modelTraits}getInitialTraits(){return this.getRandomTraits(this.initialTraits)}getAllTraits(){return this.getRandomTraits(this.allTraits)}isColliderRequired(e){return this.colliderTraits.indexOf(e)!=-1}isLipsyncTrait(e){return this.lipSyncTraits.indexOf(e)!=-1}async getNFTraitOptionsFromURL(e,t){const r=await this._fetchJson(e);return this.getNFTraitOptionsFromObject(r,t)}getNFTraitOptionsFromObject(e,t){const r=e.attributes;if(r){t=Yt(t);const i=[];return r.forEach(s=>{if(t.indexOf(s.trait_type)==-1){const o=this.getTraitOption(s.trait_type,s.value);o&&i.push(o)}}),i}else return console.warn("No attiributes parameter was found in ",e),null}getRandomTraits(e){const t=[];return(e||this.randomTraits).forEach(i=>{const s=this.getRandomTrait(i);s&&t.push(s)}),this._filterTraitOptions(t)}getRandomTrait(e){var r,i;const t=this.getModelGroup(e);if(t){const s=t.getRandomTrait();if(s){const o=(r=s.targetTextureCollection)==null?void 0:r.getRandomTrait(),a=(i=s.targetColorCollection)==null?void 0:i.getRandomTrait();return new y1(s,o,a)}else return null}else return console.warn("No trait group with name "+e+" was found."),null}async _fetchJson(e){return await(await fetch(e)).json()}getTraitOption(e,t){var i,s;const r=this.getModelTrait(e,t);if(r){const o=(i=r.targetTextureCollection)==null?void 0:i.getRandomTrait(),a=(s=r.targetColorCollection)==null?void 0:s.getRandomTrait();return new y1(r,o,a)}return null}_filterTraitOptions(e){const t=[],r=[];for(let i=0;i0&&console.log("options were filtered to fullfill restrictions: ",r),t}getCustomTraitOption(e,t){const r=this.getCustomModelTrait(e,t);return r?new y1(r,null,null):null}getCustomModelTrait(e,t){var r;return(r=this.getModelGroup(e))==null?void 0:r.getCustomTrait(t)}getModelTrait(e,t){var r;return(r=this.getModelGroup(e))==null?void 0:r.getTrait(t)}getModelTraits(e){const t=this.getModelGroup(e);return t?t.getCollection():(console.warn("No model group with name "+e),null)}getModelGroup(e){return this.modelTraitsMap.get(e)}getTextureTrait(e,t){var r;return(r=this.getTextureGroup(e))==null?void 0:r.getTrait(t)}getTextureGroup(e){return this.textureTraitsMap.get(e)}getColorTrait(e,t){var r;return(r=this.getColorGroup(e))==null?void 0:r.getTrait(t)}getColorGroup(e){return this.colorTraitsMap.get(e)}getTraitsDirectory(){let e=(this.assetsLocation||"")+(this.traitsDirectory||"");return!e.endsWith("/")&&!e.endsWith("\\")&&(e+="/"),e}getThumbnailsDirectory(){let e=(this.assetsLocation||"")+(this.thumbnailsDirectory||"");return!e.endsWith("/")&&!e.endsWith("\\")&&(e+="/"),e}getTraitIconsDirectorySvg(){let e=(this.assetsLocation||"")+(this.traitIconsDirectorySvg||"");return!e.endsWith("/")&&!e.endsWith("\\")&&(e+="/"),e}getAssetsDirectory(){let e=this.assetsLocation||"";return!e.endsWith("/")&&!e.endsWith("\\")&&(e+="/"),e}createModelTraits(e,t=!1){t&&(this.modelTraits=[]),Yt(e).forEach(r=>{this.modelTraits.push(new cpe(this,r))}),this.modelTraitsMap=new Map(this.modelTraits.map(r=>[r.trait,r])),this.modelTraits.forEach(r=>{r.restrictedTraits.forEach(i=>{const s=this.getModelGroup(i);console.log(s),s&&s.addTraitRestriction(r.trait)})})}createTextureTraits(e,t=!1){t&&(this.textureTraits=[]),Yt(e).forEach(r=>{this.textureTraits.push(new upe(this,r))}),this.textureTraitsMap=new Map(this.textureTraits.map(r=>[r.trait,r]))}createColorTraits(e,t=!1){t&&(this.colorTraits=[]),Yt(e).forEach(r=>{this.colorTraits.push(new fpe(this,r))}),this.colorTraitsMap=new Map(this.colorTraits.map(r=>[r.trait,r]))}}class cpe{constructor(e,t){const{trait:r,name:i,iconSvg:s,cameraTarget:o={distance:3,height:1},cullingDistance:a,cullingLayer:l,collection:A,restrictedTraits:c=[],restrictedTypes:u=[]}=t;this.manifestData=e,this.isRequired=e.requiredTraits.indexOf(r)!==-1,this.trait=r,this.name=i,this.iconSvg=s,this.fullIconSvg=e.getTraitIconsDirectorySvg()+s,this.restrictedTraits=c,this.restrictedTypes=u,this.cameraTarget=o,this.cullingDistance=a,this.cullingLayer=l,this.collection=[],this.collectionMap=null,this.createCollection(A)}appendCollection(e,t){e.collection.forEach(r=>{const i=this.getTrait(r.id);if(i!=null)if(t){console.log(`Model with id ${r.id} exists and will be replaced with new one`),this.collectionMap.set(r.id,r);const s=this.collection.indexOf(i);this.collection[s]=r}else console.log(`Model with id ${r.id} exists, skipping`);else this.collection.push(r),this.collectionMap.set(r.id,r)})}addTraitRestriction(e){this.restrictedTraits.indexOf(e)==-1&&this.restrictedTraits.push(e)}createCollection(e,t=!1){t&&(this.collection=[]),Yt(e).forEach(r=>{this.collection.push(new Mk(this,r))}),this.collectionMap=new Map(this.collection.map(r=>[r.id,r]))}getCustomTrait(e){return new Mk(this,{directory:e,fullDirectory:e,id:"_custom",name:"Custom"})}getTrait(e){return this.collectionMap.get(e)}getTraitByIndex(e){return this.collection[e]}getRandomTrait(){return this.collection.length>0?this.collection[Math.floor(Math.random()*this.collection.length)]:null}getCollection(){return this.collection}}class upe{constructor(e,t){const{trait:r,collection:i}=t;this.manifestData=e,this.trait=r,this.collection=[],this.collectionMap=null,this.createCollection(i)}appendCollection(e,t){e.collection.forEach(r=>{const i=this.getTrait(r.id);if(i!=null)if(t){console.log(`Texture with id ${r.id} exists and will be replaced with new one`),this.collectionMap.set(r.id,r);const s=this.collection.indexOf(i);this.collection[s]=r}else console.log(`Texture with id ${r.id} exists, skipping`);else this.collection.push(r),this.collectionMap.set(r.id,r)})}createCollection(e,t=!1){t&&(this.collection=[]),Yt(e).forEach(r=>{this.collection.push(new dpe(this,r))}),this.collectionMap=new Map(this.collection.map(r=>[r.id,r]))}getTrait(e){return this.collectionMap.get(e)}getTraitByIndex(e){return this.collection[e]}getRandomTrait(){return this.collection.length>0?this.collection[Math.floor(Math.random()*this.collection.length)]:null}}class fpe{constructor(e,t){const{trait:r,collection:i}=t;this.manifestData=e,this.trait=r,this.collection=[],this.collectionMap=null,this.createCollection(i)}appendCollection(e,t){e.collection.forEach(r=>{const i=this.getTrait(r.id);if(i!=null)if(t){console.log(`Color with id ${r.id} exists and will be replaced with new one`),this.collectionMap.set(r.id,r);const s=this.collection.indexOf(i);this.collection[s]=r}else console.log(`Color with id ${r.id} exists, skipping`);else this.collection.push(r),this.collectionMap.set(r.id,r)})}createCollection(e,t=!1){t&&(this.collection=[]),Yt(e).forEach(r=>{this.collection.push(new hpe(this,r))}),this.collectionMap=new Map(this.collection.map(r=>[r.id,r]))}getTrait(e){return this.collectionMap.get(e)}getTraitByIndex(e){return this.collection[e]}getRandomTrait(){return this.collection.length>0?this.collection[Math.floor(Math.random()*this.collection.length)]:null}}class Mk{constructor(e,t){const{id:r,directory:i,name:s,thumbnail:o,cullingDistance:a,cullingLayer:l,type:A=[],textureCollection:c,colorCollection:u,fullDirectory:f,fullThumbnail:d}=t;if(this.manifestData=e.manifestData,this.traitGroup=e,this.id=r,this.directory=i,f)this.fullDirectory=f;else if(Array.isArray(i)){this.fullDirectory=[];for(let h=0;h0&&this.manifestData.restrictedTypes>0){haveCommonValue=(i,s)=>{if(i==null||s==null)return!1;for(let o=0;ohaveCommonValue(r[i],traitTypes))}return!1}}class dpe{constructor(e,t){const{id:r,directory:i,fullDirectory:s,name:o,thumbnail:a}=t;if(this.traitGroup=e,this.id=r,this.directory=i,s)this.fullDirectory=s;else if(Array.isArray(i)){this.fullDirectory=[];for(let l=0;l{o.isSkinnedMesh&&o.skeleton.bones.filter(l=>l.name==="head")[0].getWorldPosition(el)}),el.z+=.3,el.y+=s,this.screenshotManager.setCamera(el,i),this.screenshotManager.saveScreenshot(e,t,r),this.blinkManager.disableScreenshot()}cameraRaycastCulling(e,t,r=!0){if(this.renderCamera==null){console.warn("No camera was set in character manager. Please call setRenderCamera(camera) before calling this function");return}const i=()=>{this.characterModel.traverse(A=>{A.isMesh&&A.userData.origIndexBuffer&&(A.userData.clippedIndexGeometry=A.geometry.index.clone(),A.geometry.setIndex(A.userData.origIndexBuffer))})},s=()=>{this.characterModel.traverse(A=>{A.isMesh&&A.userData.origIndexBuffer&&A.geometry.setIndex(A.userData.clippedIndexGeometry)})},o=(A,c)=>{for(let u=0;u{var p,m;const u=A.object,f=A.face,d=[f.a,f.b,f.c],h=(m=(p=u.userData)==null?void 0:p.clippedIndexGeometry)==null?void 0:m.array;if(h!=null){const g=o(h,d),v=Array.from(h);if(g==-1&&!c){const y=[...v,...d];u.userData.clippedIndexGeometry=new At(new Uint32Array(y),1,!1)}g!=1&&c&&(v.splice(g,3),u.userData.clippedIndexGeometry=new At(new Uint32Array(v),1,!1))}};B1.x=e,B1.y=t,i(),Tk.setFromCamera(B1,this.renderCamera);const l=Tk.intersectObjects(this.characterModel.children);if(l.length>0){const A=l[0];a(A,r)}s()}removeCurrentCharacter(){const e=[];for(const t in this.avatar)e.push(new mB({traitGroupID:t,traitModel:null}));e.forEach(t=>{this._addLoadedData(t)}),this.avatar={}}removeCurrentManifest(){this.removeCurrentCharacter(),this.manifest=null,this.manifestData=null,this.animationManager&&this.animationManager.clearCurrentAnimations()}canDownload(){var e;return((e=this.manifestData)==null?void 0:e.canDownload)||!0}downloadVRM(e,t=null){return new Promise(async(r,i)=>{if(this.canDownload())try{t=t||{};const o={...this.manifestData.getExportOptions(),...t};o.isVrm0=!0,o.screenshot=this._getPortaitScreenshotTexture(!1,o),console.log(o),await $he(this.characterModel,this.avatar,e,o),r()}catch(s){console.error("Error downloading VRM:",s.message),i(new Error("Failed to download VRM."))}else{const s="Download not supported.";console.error(s),i(new Error(s))}})}downloadGLB(e,t=null){if(console.log("XXX fix glb downloader"),this.canDownload()){t=t||{};const r={...this.manifestData.getExportOptions(),...t};epe(this.characterModel,e,r)}else console.error("Download not supported")}getAvatarSelection(){var t;var e={};for(const r in this.avatar)e[r]={name:this.avatar[r].name,id:(t=this.avatar[r].traitInfo)==null?void 0:t.id};return e}getGroupTraits(){if(this.manifestData)return this.manifestData.getGroupModelTraits()}getCurrentCharacterModel(){return this.characterModel}isTraitGroupRequired(e){const t=this.manifestData.getModelGroup(e);return!!(t!=null&&t.isRequired)}getTraits(e){return this.manifestData?this.manifestData.getModelTraits(e):(console.warn("No manifest file has been loaded, please load it before trait models."),null)}getCurrentTraitID(e){var t,r;return(r=(t=this.avatar[e])==null?void 0:t.traitInfo)==null?void 0:r.id}getCurrentTraitData(e){var t;return(t=this.avatar[e])==null?void 0:t.traitInfo}getCurrentTraitVRM(e){var t;return(t=this.avatar[e])==null?void 0:t.vrm}setParentModel(e){e.add(this.rootModel),this.parentModel=e,this.screenshotManager&&this.screenshotManager.setScene(this.parentModel)}setRenderCamera(e){this.renderCamera=e}loadRandomTraits(){return new Promise(async(e,t)=>{if(this.manifestData){const r=this.manifestData.getRandomTraits();await this._loadTraits(r),e()}else{const r="No manifest was loaded, random traits cannot be loaded.";console.error(r),t(new Error(r))}})}loadRandomTrait(e){return new Promise(async(t,r)=>{if(this.manifestData){const i=this.manifestData.getRandomTrait(e);await this._loadTraits(Yt(i)),t()}else{const i="No manifest was loaded, random traits cannot be loaded.";console.error(i),r(new Error(i))}})}loadTraitsFromNFT(e,t=!0,r=null){return new Promise(async(i,s)=>{try{if(this.manifestData){const o=this.manifestData.getNFTraitOptionsFromURL(e,r);await this._loadTraits(o,t),i()}else{const o="No manifest was loaded, NFT traits cannot be loaded.";console.error(o),s(new Error(o))}}catch(o){s(o)}})}loadTraitsFromNFTObject(e,t=!0,r=null){return new Promise(async(i,s)=>{if(this.manifestData)try{const o=this.manifestData.getNFTraitOptionsFromObject(e,r);await this._loadTraits(o,t),i()}catch(o){console.error("Error loading traits from NFT object:",o.message),s(new Error("Failed to load traits from NFT object."))}else{const o="No manifest was loaded, NFT traits cannot be loaded.";console.error(o),s(new Error(o))}})}loadInitialTraits(){return new Promise(async(e,t)=>{if(this.manifestData)await this._loadTraits(this.manifestData.getInitialTraits()),e();else{const r="No manifest was loaded, initial traits cannot be loaded.";console.error(r),t(new Error(r))}})}loadAllTraits(){return console.log("load all"),new Promise(async(e,t)=>{if(this.manifestData)await this._loadTraits(this.manifestData.getAllTraits()),e();else{const r="No manifest was loaded, initial traits cannot be loaded.";console.error(r),t(new Error(r))}})}loadTrait(e,t){return new Promise(async(r,i)=>{if(this.manifestData)try{const s=this.manifestData.getTraitOption(e,t);s&&(await this._loadTraits(Yt(s)),r())}catch(s){console.error("Error loading specific trait:",s.message),i(new Error("Failed to load specific trait."))}else{const s="No manifest was loaded, specific trait cannot be loaded.";console.error(s),i(new Error(s))}})}loadCustomTrait(e,t){return new Promise(async(r,i)=>{if(this.manifestData)try{const s=this.manifestData.getCustomTraitOption(e,t);s&&(await this._loadTraits(Yt(s)),r())}catch(s){console.error("Error loading custom trait:",s.message),i(new Error("Failed to load custom trait."))}else{const s="No manifest was loaded, custom trait cannot be loaded.";console.error(s),i(new Error(s))}})}loadCustomTexture(e,t){return new Promise(async(r,i)=>{var o;const s=(o=this.avatar[e])==null?void 0:o.model;if(s)await qde(s,t),r();else{const a="No Group Trait with name "+e+" was found.";console.warn(a),i(new Error(a))}})}setTraitColor(e,t){var i;const r=(i=this.avatar[e])==null?void 0:i.model;if(r)try{const s=new Re(t);r.traverse(o=>{o.isMesh&&(o.material.type==="MeshStandardMaterial"?Array.isArray(o.material)?o.material.forEach(a=>{a.color=s}):o.material.color=s:(o.material[0].uniforms.litFactor.value=s,o.material[0].uniforms.shadeColorFactor.value=new Re(s.r*.8,s.g*.8,s.b*.8)))})}catch(s){throw console.error("Error setting trait color:",s.message),new Error("Failed to set trait color.")}else{const s="No Group Trait with name "+e+" was found.";throw console.warn(s),new Error(s)}}removeTrait(e,t=!1){if(this.isTraitGroupRequired(e)&&!t){console.warn(`No trait with name: ${e} is not removable.`);return}if(this.manifestData.getModelGroup(e)){const i=new mB({traitGroupID:e,traitModel:null});this._addLoadedData(i),d1(this.avatar)}else console.warn(`No trait with name: ${e} was found.`)}updateCullHiddenMeshes(){d1(this.avatar)}loadOptimizerManifest(){this.manifest={colliderTraits:["CUSTOM"],traits:[{name:"Custom",trait:"CUSTOM",collection:[]}]},this.manifestData=new v1(this.manifest)}getCurrentOptimizerCharacterModel(){var e;return(e=this.avatar.CUSTOM)==null?void 0:e.vrm}loadOptimizerCharacter(e){return this.loadCustomTrait("CUSTOM",e)}setManifest(e){return this.removeCurrentCharacter(),new Promise(async(t,r)=>{try{if(this.manifest=e,this.manifest){if(this.manifestData=new v1(this.manifest),this.animationManager)try{await this._animationManagerSetup(this.manifest.animationPath,this.manifest.assetsLocation,this.manifestData.displayScale)}catch(i){console.error("Error loading animations: "+i)}t()}else{const i="Failed to fetch or parse the manifest.";console.error(i),r(new Error(i))}}catch(i){console.error("Error setting manifest:",i.message),r(new Error("Failed to set the manifest."))}})}appendManifest(e,t){return new Promise(async(r,i)=>{try{t?this.manifest={...this.manifest||{},manifest:e}:this.manifest={manifest:e,...this.manifest||{}};const s=new v1(e);this.manifestData.appendManifestData(s),r()}catch(s){console.error("Error setting manifest:",s.message),i(new Error("Failed to set the manifest."))}})}loadManifest(e){return new Promise(async(t,r)=>{try{const i=await this._fetchManifest(e);this.setManifest(i).then(()=>{t()})}catch(i){console.error("Error loading manifest:",i.message),r(new Error("Failed to load the manifest."))}})}loadAppendManifest(e,t){return new Promise(async(r,i)=>{try{const s=await this._fetchManifest(e);this.appendManifest(s,t).then(()=>{r()})}catch(s){console.error("Error loading manifest:",s.message),i(new Error("Failed to load the manifest."))}})}async _loadTraits(e,t=!1){await this.traitLoadManager.loadTraitOptions(Yt(e)).then(r=>{t&&this.getGroupTraits().forEach(s=>{r.some(a=>{var l;return((l=a.traitModel)==null?void 0:l.traitGroup.trait)===s.trait})||this.avatar[s.trait]!=null&&r.push(new mB({traitGroupID:s.trait,traitModel:null}))}),r.forEach(i=>{this._addLoadedData(i)}),d1(this.avatar)})}async _animationManagerSetup(e,t,r){const i=Yt(e);this.animationManager&&(this.animationManager.setScale(r),e.length>0&&(this.animationManager.storeAnimationPaths(i,t||""),await this.animationManager.loadAnimation(i,!1,0,i[0].endsWith(".fbx"),t||"")))}async _fetchManifest(e){return await(await fetch(e)).json()}_getPortaitScreenshotTexture(e,t){this.blinkManager.enableScreenshot(),this.characterModel.traverse(u=>{u.isSkinnedMesh&&u.skeleton.bones.filter(d=>d.name==="head")[0].getWorldPosition(el)});const{screenshotResolution:r,screenshotFaceDistance:i,screenshotFaceOffset:s,screenshotBackground:o,screenshotFOV:a}=t,l=r[0],A=r[1];el.x+=s[0],el.y+=s[1],el.z+=s[2],this.screenshotManager.setBackground(o),this.screenshotManager.setCamera(el,i,a);const c=e?this.screenshotManager.getScreenshotBlob(l,A):this.screenshotManager.getScreenshotTexture(l,A);return this.blinkManager.disableScreenshot(),c}_setupWireframeMaterial(e){e.origMat=e.material;const t=()=>{const o=.1+Math.random()*.9,a=.1+Math.random()*(1-.1),l=.1+Math.random()*(1-.1);return new Re(o,a,l)},r=new Qi({color:t(),wireframe:!0,wireframeLinewidth:.2}),i=e.material;e.setDebugMode=s=>{s?e.material.length?(e.material[0]=r,e.material[1]=r):e.material=r:e.material=i}}_VRMBaseSetup(e,t,r,i,s){var a,l;let o=e.userData.vrm;return e.userData.vrm==null?(console.error("No valid VRM was provided for "+r+" trait, skipping file."),null):(wk(o,{isVRM0:((a=o.meta)==null?void 0:a.metaVersion)==="0"}),this.manifestData.isColliderRequired(r)&&ope(e),lhe(o),this.manifestData.isLipsyncTrait(r)&&(this.lipSync=new Yw(o)),this._modelBaseSetup(o,t,r,i,s),((l=o.meta)==null?void 0:l.metaVersion)==="0"&&o.scene.traverse(A=>{if(A.isSkinnedMesh){Xh.rotateVRM0(o),console.log("Loaded VRM0 file ",o);for(let c=0;c{const f=e.scene.getObjectByName(u);f!=null&&f.isMesh&&o.push(f)}),e.scene.traverse(u=>{!t.meshTargets&&u.isMesh&&o.push(u),u.frustumCulled=!1,u.isMesh&&(this._setupWireframeMaterial(u),a.indexOf(u.name)===-1&&l.push(u))});const A=this.manifest,c=this.manifestData.getModelGroup(r);wk(e,{cullingLayer:t.cullingLayer!=null?t.cullingLayer:c.cullingLayer!=null?c.cullingLayer:A.defaultCullingLayer!=null?A.defaultCullingLayer:-1,cullingDistance:t.cullingDistance!=null?t.cullingDistance:c.cullingDistance!=null?c.cullingDistance:A.defaultCullingDistance!=null?A.defaultCullingDistance:null,maxCullingDistance:t.maxCullingDistance!=null?t.maxCullingDistance:c.maxCullingDistance!=null?c.maxCullingDistance:A.maxCullingDistance!=null?A.maxCullingDistance:1/0,cullingMeshes:l}),o.map((u,f)=>{if(i){const d=i[f]||i[0];d!=null&&(u.material.type==="MeshStandardMaterial"?Array.isArray(u.material)?u.material.forEach(h=>{h.map=d}):u.material.map=d:console.warn("XXX set material texture to shader material",u.material))}if(s){const d=s[f]||s[0];d!=null&&(u.material[0].uniforms.litFactor.value=d,u.material[0].uniforms.shadeColorFactor.value=new Re(d.r*.8,d.g*.8,d.b*.8))}})}_applyManagers(e){this.blinkManager.addVRM(e),this.lookAtManager&&this.lookAtManager.addVRM(e),this.animationManager&&this.animationManager.addVRM(e)}_displayModel(e){if(e){const t=e.scene;this.characterModel.attach(t)}}_positionModel(e){const t=this.manifestData.displayScale;e.scene.scale.set(t,t,t)}_disposeTrait(e){this.blinkManager.removeVRM(e),this.lookAtManager&&this.lookAtManager.removeVRM(e),this.animationManager&&this.animationManager.removeVRM(e),ohe(e)}_addLoadedData(e){const{traitGroupID:t,traitModel:r,textureTrait:i,colorTrait:s,models:o,textures:a,colors:l}=e;if(r==null){this.avatar[t]&&this.avatar[t].vrm&&(this._disposeTrait(this.avatar[t].vrm),this.avatar[t]={});return}let A=null;o.map(c=>{c!=null&&(A=this._VRMBaseSetup(c,r,t,a,l))}),A!=null&&(this.avatar[t]&&this.avatar[t].vrm&&this._disposeTrait(this.avatar[t].vrm),this._positionModel(A),this._displayModel(A),this._applyManagers(A),console.log(this.characterModel),this.avatar[t]={traitInfo:r,textureInfo:i,colorInfo:s,name:r.name,model:A&&A.scene,vrm:A})}}class gpe{constructor(){const e=new BZ;e.onProgress=(i,s,o)=>{this.setLoadPercentage(Math.round(s/o*100))};const t=new x_(e);t.crossOrigin="anonymous",t.register(i=>new Tfe(i,{autoUpdateHumanBones:!0}));const r=new Nu(e);this.loadPercentager=0,this.loadingManager=e,this.gltfLoader=t,this.textureLoader=r,this.isLoading=!1}setLoadPercentage(e){this.loadPercentager=e}loadTraitOptions(e){return new Promise(t=>{this.isLoading=!0;const r=[],i=e.map(async(s,o)=>{var c,u,f;if(s==null){r[o]=null;return}const a=await Promise.all(Yt((c=s==null?void 0:s.traitModel)==null?void 0:c.fullDirectory).map(async d=>{try{return await this.gltfLoader.loadAsync(d)}catch(h){return console.error(`Error loading modelsss ${d}:`,h),null}})),l=await Promise.all(Yt((u=s==null?void 0:s.traitTexture)==null?void 0:u.fullDirectory).map(d=>new Promise(h=>{this.textureLoader.load(d,p=>{p.flipY=!1,p.encoding=ht,h(p)},null,p=>{console.error("error loading texture: ",p),h(null)})}))),A=Yt((f=s==null?void 0:s.traitColor)==null?void 0:f.value).map(d=>new Re(d));r[o]=new mB({traitGroupID:s==null?void 0:s.traitModel.traitGroup.trait,traitModel:s==null?void 0:s.traitModel,textureTrait:s==null?void 0:s.traitTexture,colorTrait:s==null?void 0:s.traitColor,models:a,textures:l,colors:A})});Promise.allSettled(i).then(()=>{this.setLoadPercentage(100),t(r),this.isLoading=!1}).catch(s=>{this.setLoadPercentage(100),console.error("An error occurred:",s),t(r),this.isLoading=!1})})}}class mB{constructor(e){const{traitGroupID:t,traitModel:r,textureTrait:i,colorTrait:s,models:o,textures:a,colors:l}=e;this.traitGroupID=t,this.traitModel=r,this.textureTrait=i,this.colorTrait=s,this.models=o,this.textures=a,this.colors=l}}function mpe(n){const e=new yw,t=new bZ(16777215,.5);e.add(t);const r=new w_(16777215,.5);r.position.set(0,1,1),e.add(r);const i=new kt;e.add(i);const s=new Mr(30,window.innerWidth/window.innerHeight,.1,1e3);s.position.set(0,1.3,2);const o=new ppe({parentModel:e,createAnimationManager:!0,renderCamera:s});o.addLookAtMouse(80,n,s,!0);const a=document.getElementById(n),l=new c0({canvas:a,antialias:!0,alpha:!0,preserveDrawingBuffer:!0}),A=new bie(s,l.domElement);A.minDistance=1,A.maxDistance=4,A.maxPolarAngle=Math.PI/2,A.enablePan=!0,A.target=new z(0,1,0),A.enableDamping=!0,A.dampingFactor=.1;const c=new z(-.5,0,-.5),u=new z(.5,1.5,.5),f=()=>{l.setSize(window.innerWidth,window.innerHeight),s.aspect=window.innerWidth/window.innerHeight,s.updateProjectionMatrix()};window.addEventListener("resize",f),l.setSize(window.innerWidth,window.innerHeight),l.setPixelRatio(window.devicePixelRatio),l.outputEncoding=ht;const d=()=>{requestAnimationFrame(d),A.target.clamp(c,u),A==null||A.update(),o.update(),l.render(e,s)};d();const h=m=>{const g=m.ctrlKey,v=a.getBoundingClientRect(),y=(m.clientX-v.left)/v.width*2-1,w=-((m.clientY-v.top)/v.height)*2+1;o.cameraRaycastCulling(y,w,g)};async function p(){const m="./3d/Platform.glb",v=await new x_().loadAsync(m);i.add(v.scene)}return p(),a.addEventListener("click",h),{scene:e,camera:s,controls:A,characterManager:o,sceneElements:i}}new z;class vpe{constructor(e){this.characterManager=e,this.screenshotManager=e.screenshotManager,this.blinkManager=e.blinkManager,this.animationManager=this.characterManager.animationManager,console.log(this.characterManager),console.log(this.screenshotManager),this.temptime=0}async createLoraData(e,t){const r=await this._fetchManifest(e),{assetsLocation:i="",animationsDirectory:s="",backgroundGrayscale:o=1,topFrameOffsetPixels:a=64,bottomFrameOffsetPixels:l=64,backgroundDescription:A="",width:c=512,height:u=512,dataCollection:f}=r,d=i+s+"/";this.screenshotManager.setBackground([o,o,o]),this.blinkManager.enableScreenshot(),this.screenshotManager._setBonesOffset(.2);const h=g=>new Promise(v=>setTimeout(v,g));let p=0;const m=this;Array.isArray(f)&&await(async()=>{if(Array.isArray(f))for(let v=0;vnew Promise(v=>setTimeout(v,g));this.screenshotManager.setBottomFrameOffset(l),this.screenshotManager.setTopFrameOffset(a),this.screenshotManager.setBackground(s),this.blinkManager.enableScreenshot(),this.screenshotManager._setBonesOffset(.2);let p=0;console.log(t);const m=this;if(Array.isArray(f)){console.log("e");async function g(){var v;if(Array.isArray(f))for(const y of f){const{animationName:w,animationPath:C,framesNumber:b,lookAtCamera:E,expression:x,cameraPosition:S,cameraFrame:M}=y;p++;const Z=w||p.toString().padStart(2,"0");await m.animationManager.loadAnimation(d+C,!0,0);const K=TH(S);m.screenshotManager.setCameraFrameWithName(M,K);const _=(v=m.animationManager.getCurrentClip())==null?void 0:v.duration;if(_){console.log(_);const B=_/b;for(let F=0;F{const[e,t]=me.useState(null),[r,i]=me.useState(null),[s,o]=me.useState(null),[a,l]=me.useState(null),[A,c]=me.useState(null),[u,f]=me.useState(null),[d,h]=me.useState(null),[p,m]=me.useState(null),[g,v]=me.useState(null),[y,w]=me.useState(null),[C,b]=me.useState(!1);let E=!1,[x,S]=me.useState(!1);me.useEffect(()=>{if(E||x)return;S(!0),E=!0;const{scene:_,camera:B,controls:F,characterManager:R,sceneElements:k}=mpe("editor-scene");m(B),h(_),t(R),l(k),c(R.animationManager),f(R.lookAtManager),v(F),i(new vpe(R)),o(new ype(R))},[]);const M=_=>{_==null&&(_=!C),b(_),d.traverse(B=>{B.isMesh&&B.setDebugMode&&B.setDebugMode(_)})},Z=_=>{_?d.add(a):d.remove(a)},K=_=>{g&&(fE.to(g.target,{x:_.targetX??0,y:_.targetY??0,z:_.targetZ??0,duration:1}),fE.fromTo(g,{maxDistance:g.getDistance(),minDistance:g.getDistance(),minPolarAngle:g.getPolarAngle(),maxPolarAngle:g.getPolarAngle(),minAzimuthAngle:g.getAzimuthalAngle(),maxAzimuthAngle:g.getAzimuthalAngle()},{maxDistance:_.distance,minDistance:_.distance,minPolarAngle:Math.PI/2-.11,maxPolarAngle:Math.PI/2-.11,minAzimuthAngle:-.78,maxAzimuthAngle:-.78,duration:1}).then(()=>{g.minPolarAngle=0,g.maxPolarAngle=3.1415,g.minDistance=.5,g.maxDistance=10,g.minAzimuthAngle=1/0,g.maxAzimuthAngle=1/0}))};return P.jsx(ni.Provider,{value:{manifest:y,setManifest:w,scene:d,characterManager:e,loraDataGenerator:r,spriteAtlasGenerator:s,showEnvironmentModels:Z,debugMode:C,toggleDebugMode:M,animationManager:A,lookAtManager:u,camera:p,moveCamera:K,controls:g,sceneElements:a},children:n.children})},wpe={NORMAL:"NORMAL",AR:"AR",AR_FRONT:"AR_FRONT",VR:"VR"},ot={LANDING:"LANDING",CREATE:"CREATE",CLAIM:"CLAIM",LOAD:"LOAD",APPEARANCE:"APPEARANCE",BATCHDOWNLOAD:"BATCHDOWNLOAD",BIO:"BIO",SAVE:"SAVE",MINT:"MINT",CHAT:"CHAT",OPTIMIZER:"OPTIMIZER",BATCHMANIFEST:"BATCHMANIFEST",WALLET:"WALLET"},Bi=Y.createContext(),Cpe=n=>{const[e,t]=Y.useState(wpe.NORMAL),[r,i]=Y.useState(ot.LANDING),[s,o]=Y.useState(!1),[a,l]=Y.useState(!1);return P.jsx(Bi.Provider,{value:{viewMode:r,setViewMode:i,isLoading:s,setIsLoading:o,mouseIsOverUI:a,setMouseIsOverUI:l,currentCameraMode:e,setCurrentCameraMode:t},children:n.children})},bpe="modulepreload",xpe=function(n){return"/CharacterStudio/"+n},Nk={},Ipe=function(e,t,r){if(!t||t.length===0)return e();const i=document.getElementsByTagName("link");return Promise.all(t.map(s=>{if(s=xpe(s),s in Nk)return;Nk[s]=!0;const o=s.endsWith(".css"),a=o?'[rel="stylesheet"]':"";if(!!r)for(let c=i.length-1;c>=0;c--){const u=i[c];if(u.href===s&&(!o||u.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${s}"]${a}`))return;const A=document.createElement("link");if(A.rel=o?"stylesheet":bpe,o||(A.as="script",A.crossOrigin=""),A.href=s,document.head.appendChild(A),o)return new Promise((c,u)=>{A.addEventListener("load",c),A.addEventListener("error",()=>u(new Error(`Unable to preload CSS for ${s}`)))})})).then(()=>e()).catch(s=>{const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=s,window.dispatchEvent(o),!o.defaultPrevented)throw s})};function Xw(){return Xw=Object.assign||function(n){for(var e=1;e=0)&&(t[i]=n[i]);return t}function Epe(n){me.useEffect(n,[])}function Upe(n,e){e===void 0&&(e={});var t=e,r=t.volume,i=r===void 0?1:r,s=t.playbackRate,o=s===void 0?1:s,a=t.soundEnabled,l=a===void 0?!0:a,A=t.interrupt,c=A===void 0?!1:A,u=t.onload,f=Fpe(t,["id","volume","playbackRate","soundEnabled","interrupt","onload"]),d=Y.useRef(null),h=Y.useRef(!1),p=Y.useState(null),m=p[0],g=p[1],v=Y.useState(null),y=v[0],w=v[1],C=function(){typeof u=="function"&&u.call(this),h.current&&g(this.duration()*1e3),w(this)};Epe(function(){return Ipe(()=>import("./howler-a528f2ae.js").then(M=>M.h),[]).then(function(M){if(!h.current){var Z;d.current=(Z=M.Howl)!==null&&Z!==void 0?Z:M.default.Howl,h.current=!0,new d.current(Xw({src:Array.isArray(n)?n:[n],volume:i,rate:o,onload:C},f))}}),function(){h.current=!1}}),Y.useEffect(function(){d.current&&y&&w(new d.current(Xw({src:Array.isArray(n)?n:[n],volume:i,onload:C},f)))},[JSON.stringify(n)]),Y.useEffect(function(){y&&(y.volume(i),y.rate(o))},[i,o]);var b=Y.useCallback(function(M){typeof M>"u"&&(M={}),!(!y||!l&&!M.forceSoundEnabled)&&(c&&y.stop(),M.playbackRate&&y.rate(M.playbackRate),y.play(M.id))},[y,l,c]),E=Y.useCallback(function(M){y&&y.stop(M)},[y]),x=Y.useCallback(function(M){y&&y.pause(M)},[y]),S=[b,{sound:y,stop:E,pause:x,duration:m}];return S}const Spe=[{name:"background/cc_bgm.wav",offset:0,duration:123458.58333333334},{name:"background/cc_bgm_balanced.wav",offset:123458.58333333334,duration:123458.60416666666},{name:"effect/character-load.wav",offset:246917.1875,duration:3030},{name:"effect/class-select.wav",offset:249947.1875,duration:2780},{name:"effect/switchingItem.wav",offset:252727.1875,duration:623.75},{name:"ui/back-next-button.wav",offset:253350.9375,duration:155.02083333333334},{name:"ui/class-mouse-over.wav",offset:253505.95833333334,duration:217.52083333333334},{name:"ui/class_click.wav",offset:253723.4791666667,duration:3123.75},{name:"ui/class_pass.wav",offset:256847.2291666667,duration:155},{name:"ui/option_click.wav",offset:257002.2291666667,duration:155.02083333333334},{name:"ui/randomize-button.wav",offset:257157.25000000003,duration:342.5208333333333},{name:"ui/section_click.wav",offset:257499.77083333337,duration:155}],_pe="/CharacterStudio/assets/sounds-3322d50e.mp3",Cs=me.createContext(),Qpe=n=>{const e=i=>Spe.find(s=>i.test(s.name)),[t]=Upe(_pe,{sprite:{switchItem:[e(/switchingItem/).offset,e(/switchingItem/).duration],classSelect:[e(/class-select/).offset,e(/class-select/).duration],characterLoad:[e(/character-load/).offset,e(/character-load/).duration],randomizeButton:[e(/randomize-button/).offset,e(/randomize-button/).duration],classMouseOver:[e(/class-mouse-over/).offset,e(/class-mouse-over/).duration],backNextButton:[e(/back-next-button/).offset,e(/back-next-button/).duration]}}),r=(i,s=0)=>{s===0?t({id:i}):setTimeout(()=>{t({id:i})},s)};return P.jsx(Cs.Provider,{value:{playSound:r},children:n.children})};function $s(n){"@babel/helpers - typeof";return $s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},$s(n)}function lo(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}function Rpe(n,e){if($s(n)!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var r=t.call(n,e||"default");if($s(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function KH(n){var e=Rpe(n,"string");return $s(e)=="symbol"?e:String(e)}function Dk(n,e){for(var t=0;tn.length)&&(e=n.length);for(var t=0,r=new Array(e);t1&&arguments[1]!==void 0?arguments[1]:{};lo(this,n),this.init(e,t)}return Ao(n,[{key:"init",value:function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=r.prefix||"i18next:",this.logger=t||Npe,this.options=r,this.debug=r.debug}},{key:"setDebug",value:function(t){this.debug=t}},{key:"log",value:function(){for(var t=arguments.length,r=new Array(t),i=0;i1?r-1:0),s=1;s-1?a.replace(/###/g,"."):a}function i(){return!n||typeof n=="string"}for(var s=typeof e!="string"?[].concat(e):e.split(".");s.length>1;){if(i())return{};var o=r(s.shift());!n[o]&&t&&(n[o]=new t),Object.prototype.hasOwnProperty.call(n,o)?n=n[o]:n={}}return i()?{}:{obj:n,k:r(s.shift())}}function Wk(n,e,t){var r=tQ(n,e,Object),i=r.obj,s=r.k;i[s]=t}function Vpe(n,e,t,r){var i=tQ(n,e,Object),s=i.obj,o=i.k;s[o]=s[o]||[],r&&(s[o]=s[o].concat(t)),r||s[o].push(t)}function Kw(n,e){var t=tQ(n,e),r=t.obj,i=t.k;if(r)return r[i]}function Ok(n,e,t){var r=Kw(n,t);return r!==void 0?r:Kw(e,t)}function e4(n,e,t){for(var r in e)r!=="__proto__"&&r!=="constructor"&&(r in n?typeof n[r]=="string"||n[r]instanceof String||typeof e[r]=="string"||e[r]instanceof String?t&&(n[r]=e[r]):e4(n[r],e[r],t):n[r]=e[r]);return n}function Ff(n){return n.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var Lpe={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};function Ppe(n){return typeof n=="string"?n.replace(/[&<>"'\/]/g,function(e){return Lpe[e]}):n}var pb=typeof window<"u"&&window.navigator&&typeof window.navigator.userAgentData>"u"&&window.navigator.userAgent&&window.navigator.userAgent.indexOf("MSIE")>-1,Wpe=[" ",",","?","!",";"];function Ope(n,e,t){e=e||"",t=t||"";var r=Wpe.filter(function(a){return e.indexOf(a)<0&&t.indexOf(a)<0});if(r.length===0)return!0;var i=new RegExp("(".concat(r.map(function(a){return a==="?"?"\\?":a}).join("|"),")")),s=!i.test(n);if(!s){var o=n.indexOf(t);o>0&&!i.test(n.substring(0,o))&&(s=!0)}return s}function Gk(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function my(n){for(var e=1;e"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function t4(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(n){if(n[e])return n[e];for(var r=e.split(t),i=n,s=0;ss+o;)o++,a=r.slice(s,s+o).join(t),l=i[a];if(l===void 0)return;if(l===null)return null;if(e.endsWith(a)){if(typeof l=="string")return l;if(a&&typeof l[a]=="string")return l[a]}var A=r.slice(s+o).join(t);return A?t4(l,A,t):void 0}i=i[r[s]]}return i}}var Jpe=function(n){hb(t,n);var e=Gpe(t);function t(r){var i,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};return lo(this,t),i=e.call(this),pb&&ic.call(HA(i)),i.data=r||{},i.options=s,i.options.keySeparator===void 0&&(i.options.keySeparator="."),i.options.ignoreJSONStructure===void 0&&(i.options.ignoreJSONStructure=!0),i}return Ao(t,[{key:"addNamespaces",value:function(i){this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}},{key:"removeNamespaces",value:function(i){var s=this.options.ns.indexOf(i);s>-1&&this.options.ns.splice(s,1)}},{key:"getResource",value:function(i,s,o){var a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},l=a.keySeparator!==void 0?a.keySeparator:this.options.keySeparator,A=a.ignoreJSONStructure!==void 0?a.ignoreJSONStructure:this.options.ignoreJSONStructure,c=[i,s];o&&typeof o!="string"&&(c=c.concat(o)),o&&typeof o=="string"&&(c=c.concat(l?o.split(l):o)),i.indexOf(".")>-1&&(c=i.split("."));var u=Kw(this.data,c);return u||!A||typeof o!="string"?u:t4(this.data&&this.data[i]&&this.data[i][s],o,l)}},{key:"addResource",value:function(i,s,o,a){var l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1},A=this.options.keySeparator;A===void 0&&(A=".");var c=[i,s];o&&(c=c.concat(A?o.split(A):o)),i.indexOf(".")>-1&&(c=i.split("."),a=s,s=c[1]),this.addNamespaces(s),Wk(this.data,c,a),l.silent||this.emit("added",i,s,o,a)}},{key:"addResources",value:function(i,s,o){var a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(var l in o)(typeof o[l]=="string"||Object.prototype.toString.apply(o[l])==="[object Array]")&&this.addResource(i,s,l,o[l],{silent:!0});a.silent||this.emit("added",i,s,o)}},{key:"addResourceBundle",value:function(i,s,o,a,l){var A=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1},c=[i,s];i.indexOf(".")>-1&&(c=i.split("."),a=o,o=s,s=c[1]),this.addNamespaces(s);var u=Kw(this.data,c)||{};a?e4(u,o,l):u=my(my({},u),o),Wk(this.data,c,u),A.silent||this.emit("added",i,s,o)}},{key:"removeResourceBundle",value:function(i,s){this.hasResourceBundle(i,s)&&delete this.data[i][s],this.removeNamespaces(s),this.emit("removed",i,s)}},{key:"hasResourceBundle",value:function(i,s){return this.getResource(i,s)!==void 0}},{key:"getResourceBundle",value:function(i,s){return s||(s=this.options.defaultNS),this.options.compatibilityAPI==="v1"?my(my({},{}),this.getResource(i,s)):this.getResource(i,s)}},{key:"getDataByLanguage",value:function(i){return this.data[i]}},{key:"hasLanguageSomeTranslations",value:function(i){var s=this.getDataByLanguage(i),o=s&&Object.keys(s)||[];return!!o.find(function(a){return s[a]&&Object.keys(s[a]).length>0})}},{key:"toJSON",value:function(){return this.data}}]),t}(ic),n4={processors:{},addPostProcessor:function(e){this.processors[e.name]=e},handle:function(e,t,r,i,s){var o=this;return e.forEach(function(a){o.processors[a]&&(t=o.processors[a].process(t,r,i,s))}),t}};function Zk(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function si(n){for(var e=1;e"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Jk={},Hk=function(n){hb(t,n);var e=Hpe(t);function t(r){var i,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return lo(this,t),i=e.call(this),pb&&ic.call(HA(i)),kpe(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],r,HA(i)),i.options=s,i.options.keySeparator===void 0&&(i.options.keySeparator="."),i.logger=pa.create("translator"),i}return Ao(t,[{key:"changeLanguage",value:function(i){i&&(this.language=i)}},{key:"exists",value:function(i){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(i==null)return!1;var o=this.resolve(i,s);return o&&o.res!==void 0}},{key:"extractFromKey",value:function(i,s){var o=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;o===void 0&&(o=":");var a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,l=s.ns||this.options.defaultNS||[],A=o&&i.indexOf(o)>-1,c=!this.options.userDefinedKeySeparator&&!s.keySeparator&&!this.options.userDefinedNsSeparator&&!s.nsSeparator&&!Ope(i,o,a);if(A&&!c){var u=i.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:i,namespaces:l};var f=i.split(o);(o!==a||o===a&&this.options.ns.indexOf(f[0])>-1)&&(l=f.shift()),i=f.join(a)}return typeof l=="string"&&(l=[l]),{key:i,namespaces:l}}},{key:"translate",value:function(i,s,o){var a=this;if($s(s)!=="object"&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),s||(s={}),i==null)return"";Array.isArray(i)||(i=[String(i)]);var l=s.returnDetails!==void 0?s.returnDetails:this.options.returnDetails,A=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,c=this.extractFromKey(i[i.length-1],s),u=c.key,f=c.namespaces,d=f[f.length-1],h=s.lng||this.language,p=s.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(h&&h.toLowerCase()==="cimode"){if(p){var m=s.nsSeparator||this.options.nsSeparator;return l?{res:"".concat(d).concat(m).concat(u),usedKey:u,exactUsedKey:u,usedLng:h,usedNS:d}:"".concat(d).concat(m).concat(u)}return l?{res:u,usedKey:u,exactUsedKey:u,usedLng:h,usedNS:d}:u}var g=this.resolve(i,s),v=g&&g.res,y=g&&g.usedKey||u,w=g&&g.exactUsedKey||u,C=Object.prototype.toString.apply(v),b=["[object Number]","[object Function]","[object RegExp]"],E=s.joinArrays!==void 0?s.joinArrays:this.options.joinArrays,x=!this.i18nFormat||this.i18nFormat.handleAsObject,S=typeof v!="string"&&typeof v!="boolean"&&typeof v!="number";if(x&&v&&S&&b.indexOf(C)<0&&!(typeof E=="string"&&C==="[object Array]")){if(!s.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");var M=this.options.returnedObjectHandler?this.options.returnedObjectHandler(y,v,si(si({},s),{},{ns:f})):"key '".concat(u," (").concat(this.language,")' returned an object instead of string.");return l?(g.res=M,g):M}if(A){var Z=C==="[object Array]",K=Z?[]:{},_=Z?w:y;for(var B in v)if(Object.prototype.hasOwnProperty.call(v,B)){var F="".concat(_).concat(A).concat(B);K[B]=this.translate(F,si(si({},s),{joinArrays:!1,ns:f})),K[B]===F&&(K[B]=v[B])}v=K}}else if(x&&typeof E=="string"&&C==="[object Array]")v=v.join(E),v&&(v=this.extendTranslation(v,i,s,o));else{var R=!1,k=!1,T=s.count!==void 0&&typeof s.count!="string",V=t.hasDefaultValue(s),O=T?this.pluralResolver.getSuffix(h,s.count,s):"",L=s["defaultValue".concat(O)]||s.defaultValue;!this.isValidLookup(v)&&V&&(R=!0,v=L),this.isValidLookup(v)||(k=!0,v=u);var U=s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey,H=U&&k?void 0:v,le=V&&L!==v&&this.options.updateMissing;if(k||R||le){if(this.logger.log(le?"updateKey":"missingKey",h,d,u,le?L:v),A){var N=this.resolve(u,si(si({},s),{},{keySeparator:!1}));N&&N.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}var j=[],oe=this.languageUtils.getFallbackCodes(this.options.fallbackLng,s.lng||this.language);if(this.options.saveMissingTo==="fallback"&&oe&&oe[0])for(var ie=0;ie1&&arguments[1]!==void 0?arguments[1]:{},a,l,A,c,u;return typeof i=="string"&&(i=[i]),i.forEach(function(f){if(!s.isValidLookup(a)){var d=s.extractFromKey(f,o),h=d.key;l=h;var p=d.namespaces;s.options.fallbackNS&&(p=p.concat(s.options.fallbackNS));var m=o.count!==void 0&&typeof o.count!="string",g=m&&!o.ordinal&&o.count===0&&s.pluralResolver.shouldUseIntlApi(),v=o.context!==void 0&&(typeof o.context=="string"||typeof o.context=="number")&&o.context!=="",y=o.lngs?o.lngs:s.languageUtils.toResolveHierarchy(o.lng||s.language,o.fallbackLng);p.forEach(function(w){s.isValidLookup(a)||(u=w,!Jk["".concat(y[0],"-").concat(w)]&&s.utils&&s.utils.hasLoadedNamespace&&!s.utils.hasLoadedNamespace(u)&&(Jk["".concat(y[0],"-").concat(w)]=!0,s.logger.warn('key "'.concat(l,'" for languages "').concat(y.join(", "),`" won't get resolved as namespace "`).concat(u,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),y.forEach(function(C){if(!s.isValidLookup(a)){c=C;var b=[h];if(s.i18nFormat&&s.i18nFormat.addLookupKeys)s.i18nFormat.addLookupKeys(b,h,C,w,o);else{var E;m&&(E=s.pluralResolver.getSuffix(C,o.count,o));var x="".concat(s.options.pluralSeparator,"zero");if(m&&(b.push(h+E),g&&b.push(h+x)),v){var S="".concat(h).concat(s.options.contextSeparator).concat(o.context);b.push(S),m&&(b.push(S+E),g&&b.push(S+x))}}for(var M;M=b.pop();)s.isValidLookup(a)||(A=M,a=s.getResource(C,w,M,o))}}))})}}),{res:a,usedKey:l,exactUsedKey:A,usedLng:c,usedNS:u}}},{key:"isValidLookup",value:function(i){return i!==void 0&&!(!this.options.returnNull&&i===null)&&!(!this.options.returnEmptyString&&i==="")}},{key:"getResource",value:function(i,s,o){var a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(i,s,o,a):this.resourceStore.getResource(i,s,o,a)}}],[{key:"hasDefaultValue",value:function(i){var s="defaultValue";for(var o in i)if(Object.prototype.hasOwnProperty.call(i,o)&&s===o.substring(0,s.length)&&i[o]!==void 0)return!0;return!1}}]),t}(ic);function w1(n){return n.charAt(0).toUpperCase()+n.slice(1)}var zk=function(){function n(e){lo(this,n),this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=pa.create("languageUtils")}return Ao(n,[{key:"getScriptPartFromCode",value:function(t){if(!t||t.indexOf("-")<0)return null;var r=t.split("-");return r.length===2||(r.pop(),r[r.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(r.join("-"))}},{key:"getLanguagePartFromCode",value:function(t){if(!t||t.indexOf("-")<0)return t;var r=t.split("-");return this.formatLanguageCode(r[0])}},{key:"formatLanguageCode",value:function(t){if(typeof t=="string"&&t.indexOf("-")>-1){var r=["hans","hant","latn","cyrl","cans","mong","arab"],i=t.split("-");return this.options.lowerCaseLng?i=i.map(function(s){return s.toLowerCase()}):i.length===2?(i[0]=i[0].toLowerCase(),i[1]=i[1].toUpperCase(),r.indexOf(i[1].toLowerCase())>-1&&(i[1]=w1(i[1].toLowerCase()))):i.length===3&&(i[0]=i[0].toLowerCase(),i[1].length===2&&(i[1]=i[1].toUpperCase()),i[0]!=="sgn"&&i[2].length===2&&(i[2]=i[2].toUpperCase()),r.indexOf(i[1].toLowerCase())>-1&&(i[1]=w1(i[1].toLowerCase())),r.indexOf(i[2].toLowerCase())>-1&&(i[2]=w1(i[2].toLowerCase()))),i.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}},{key:"isSupportedCode",value:function(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}},{key:"getBestMatchFromCodes",value:function(t){var r=this;if(!t)return null;var i;return t.forEach(function(s){if(!i){var o=r.formatLanguageCode(s);(!r.options.supportedLngs||r.isSupportedCode(o))&&(i=o)}}),!i&&this.options.supportedLngs&&t.forEach(function(s){if(!i){var o=r.getLanguagePartFromCode(s);if(r.isSupportedCode(o))return i=o;i=r.options.supportedLngs.find(function(a){if(a.indexOf(o)===0)return a})}}),i||(i=this.getFallbackCodes(this.options.fallbackLng)[0]),i}},{key:"getFallbackCodes",value:function(t,r){if(!t)return[];if(typeof t=="function"&&(t=t(r)),typeof t=="string"&&(t=[t]),Object.prototype.toString.apply(t)==="[object Array]")return t;if(!r)return t.default||[];var i=t[r];return i||(i=t[this.getScriptPartFromCode(r)]),i||(i=t[this.formatLanguageCode(r)]),i||(i=t[this.getLanguagePartFromCode(r)]),i||(i=t.default),i||[]}},{key:"toResolveHierarchy",value:function(t,r){var i=this,s=this.getFallbackCodes(r||this.options.fallbackLng||[],t),o=[],a=function(A){A&&(i.isSupportedCode(A)?o.push(A):i.logger.warn("rejecting language code not found in supportedLngs: ".concat(A)))};return typeof t=="string"&&t.indexOf("-")>-1?(this.options.load!=="languageOnly"&&a(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&a(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&a(this.getLanguagePartFromCode(t))):typeof t=="string"&&a(this.formatLanguageCode(t)),s.forEach(function(l){o.indexOf(l)<0&&a(i.formatLanguageCode(l))}),o}}]),n}(),Ype=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],Xpe={1:function(e){return+(e>1)},2:function(e){return+(e!=1)},3:function(e){return 0},4:function(e){return e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2},5:function(e){return e==0?0:e==1?1:e==2?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5},6:function(e){return e==1?0:e>=2&&e<=4?1:2},7:function(e){return e==1?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2},8:function(e){return e==1?0:e==2?1:e!=8&&e!=11?2:3},9:function(e){return+(e>=2)},10:function(e){return e==1?0:e==2?1:e<7?2:e<11?3:4},11:function(e){return e==1||e==11?0:e==2||e==12?1:e>2&&e<20?2:3},12:function(e){return+(e%10!=1||e%100==11)},13:function(e){return+(e!==0)},14:function(e){return e==1?0:e==2?1:e==3?2:3},15:function(e){return e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2},16:function(e){return e%10==1&&e%100!=11?0:e!==0?1:2},17:function(e){return e==1||e%10==1&&e%100!=11?0:1},18:function(e){return e==0?0:e==1?1:2},19:function(e){return e==1?0:e==0||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3},20:function(e){return e==1?0:e==0||e%100>0&&e%100<20?1:2},21:function(e){return e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0},22:function(e){return e==1?0:e==2?1:(e<0||e>10)&&e%10==0?2:3}},Kpe=["v1","v2","v3"],Yk={zero:0,one:1,two:2,few:3,many:4,other:5};function jpe(){var n={};return Ype.forEach(function(e){e.lngs.forEach(function(t){n[t]={numbers:e.nr,plurals:Xpe[e.fc]}})}),n}var $pe=function(){function n(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};lo(this,n),this.languageUtils=e,this.options=t,this.logger=pa.create("pluralResolver"),(!this.options.compatibilityJSON||this.options.compatibilityJSON==="v4")&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=jpe()}return Ao(n,[{key:"addRule",value:function(t,r){this.rules[t]=r}},{key:"getRule",value:function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi())try{return new Intl.PluralRules(t,{type:r.ordinal?"ordinal":"cardinal"})}catch{return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}},{key:"needsPlural",value:function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=this.getRule(t,r);return this.shouldUseIntlApi()?i&&i.resolvedOptions().pluralCategories.length>1:i&&i.numbers.length>1}},{key:"getPluralFormsOfKey",value:function(t,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(t,i).map(function(s){return"".concat(r).concat(s)})}},{key:"getSuffixes",value:function(t){var r=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=this.getRule(t,i);return s?this.shouldUseIntlApi()?s.resolvedOptions().pluralCategories.sort(function(o,a){return Yk[o]-Yk[a]}).map(function(o){return"".concat(r.options.prepend).concat(o)}):s.numbers.map(function(o){return r.getSuffix(t,o,i)}):[]}},{key:"getSuffix",value:function(t,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=this.getRule(t,i);return s?this.shouldUseIntlApi()?"".concat(this.options.prepend).concat(s.select(r)):this.getSuffixRetroCompatible(s,r):(this.logger.warn("no plural rule found for: ".concat(t)),"")}},{key:"getSuffixRetroCompatible",value:function(t,r){var i=this,s=t.noAbs?t.plurals(r):t.plurals(Math.abs(r)),o=t.numbers[s];this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1&&(o===2?o="plural":o===1&&(o=""));var a=function(){return i.options.prepend&&o.toString()?i.options.prepend+o.toString():o.toString()};return this.options.compatibilityJSON==="v1"?o===1?"":typeof o=="number"?"_plural_".concat(o.toString()):a():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1?a():this.options.prepend&&s.toString()?this.options.prepend+s.toString():s.toString()}},{key:"shouldUseIntlApi",value:function(){return!Kpe.includes(this.options.compatibilityJSON)}}]),n}();function Xk(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function Bo(n){for(var e=1;e0&&arguments[0]!==void 0?arguments[0]:{};lo(this,n),this.logger=pa.create("interpolator"),this.options=e,this.format=e.interpolation&&e.interpolation.format||function(t){return t},this.init(e)}return Ao(n,[{key:"init",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});var r=t.interpolation;this.escape=r.escape!==void 0?r.escape:Ppe,this.escapeValue=r.escapeValue!==void 0?r.escapeValue:!0,this.useRawValueToEscape=r.useRawValueToEscape!==void 0?r.useRawValueToEscape:!1,this.prefix=r.prefix?Ff(r.prefix):r.prefixEscaped||"{{",this.suffix=r.suffix?Ff(r.suffix):r.suffixEscaped||"}}",this.formatSeparator=r.formatSeparator?r.formatSeparator:r.formatSeparator||",",this.unescapePrefix=r.unescapeSuffix?"":r.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":r.unescapeSuffix||"",this.nestingPrefix=r.nestingPrefix?Ff(r.nestingPrefix):r.nestingPrefixEscaped||Ff("$t("),this.nestingSuffix=r.nestingSuffix?Ff(r.nestingSuffix):r.nestingSuffixEscaped||Ff(")"),this.nestingOptionsSeparator=r.nestingOptionsSeparator?r.nestingOptionsSeparator:r.nestingOptionsSeparator||",",this.maxReplaces=r.maxReplaces?r.maxReplaces:1e3,this.alwaysFormat=r.alwaysFormat!==void 0?r.alwaysFormat:!1,this.resetRegExp()}},{key:"reset",value:function(){this.options&&this.init(this.options)}},{key:"resetRegExp",value:function(){var t="".concat(this.prefix,"(.+?)").concat(this.suffix);this.regexp=new RegExp(t,"g");var r="".concat(this.prefix).concat(this.unescapePrefix,"(.+?)").concat(this.unescapeSuffix).concat(this.suffix);this.regexpUnescape=new RegExp(r,"g");var i="".concat(this.nestingPrefix,"(.+?)").concat(this.nestingSuffix);this.nestingRegexp=new RegExp(i,"g")}},{key:"interpolate",value:function(t,r,i,s){var o=this,a,l,A,c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function u(m){return m.replace(/\$/g,"$$$$")}var f=function(g){if(g.indexOf(o.formatSeparator)<0){var v=Ok(r,c,g);return o.alwaysFormat?o.format(v,void 0,i,Bo(Bo(Bo({},s),r),{},{interpolationkey:g})):v}var y=g.split(o.formatSeparator),w=y.shift().trim(),C=y.join(o.formatSeparator).trim();return o.format(Ok(r,c,w),C,i,Bo(Bo(Bo({},s),r),{},{interpolationkey:w}))};this.resetRegExp();var d=s&&s.missingInterpolationHandler||this.options.missingInterpolationHandler,h=s&&s.interpolation&&s.interpolation.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables,p=[{regex:this.regexpUnescape,safeValue:function(g){return u(g)}},{regex:this.regexp,safeValue:function(g){return o.escapeValue?u(o.escape(g)):u(g)}}];return p.forEach(function(m){for(A=0;a=m.regex.exec(t);){var g=a[1].trim();if(l=f(g),l===void 0)if(typeof d=="function"){var v=d(t,a,s);l=typeof v=="string"?v:""}else if(s&&Object.prototype.hasOwnProperty.call(s,g))l="";else if(h){l=a[0];continue}else o.logger.warn("missed to pass in variable ".concat(g," for interpolating ").concat(t)),l="";else typeof l!="string"&&!o.useRawValueToEscape&&(l=Pk(l));var y=m.safeValue(l);if(t=t.replace(a[0],y),h?(m.regex.lastIndex+=l.length,m.regex.lastIndex-=a[0].length):m.regex.lastIndex=0,A++,A>=o.maxReplaces)break}}),t}},{key:"nest",value:function(t,r){var i=this,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o,a,l;function A(d,h){var p=this.nestingOptionsSeparator;if(d.indexOf(p)<0)return d;var m=d.split(new RegExp("".concat(p,"[ ]*{"))),g="{".concat(m[1]);d=m[0],g=this.interpolate(g,l);var v=g.match(/'/g),y=g.match(/"/g);(v&&v.length%2===0&&!y||y.length%2!==0)&&(g=g.replace(/'/g,'"'));try{l=JSON.parse(g),h&&(l=Bo(Bo({},h),l))}catch(w){return this.logger.warn("failed parsing options string in nesting for key ".concat(d),w),"".concat(d).concat(p).concat(g)}return delete l.defaultValue,d}for(;o=this.nestingRegexp.exec(t);){var c=[];l=Bo({},s),l=l.replace&&typeof l.replace!="string"?l.replace:l,l.applyPostProcessor=!1,delete l.defaultValue;var u=!1;if(o[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(o[1])){var f=o[1].split(this.formatSeparator).map(function(d){return d.trim()});o[1]=f.shift(),c=f,u=!0}if(a=r(A.call(this,o[1].trim(),l),l),a&&o[0]===t&&typeof a!="string")return a;typeof a!="string"&&(a=Pk(a)),a||(this.logger.warn("missed to resolve ".concat(o[1]," for nesting ").concat(t)),a=""),u&&(a=c.reduce(function(d,h){return i.format(d,h,s.lng,Bo(Bo({},s),{},{interpolationkey:o[1].trim()}))},a.trim())),t=t.replace(o[0],a),this.regexp.lastIndex=0}return t}}]),n}();function Kk(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function tl(n){for(var e=1;e-1){var r=n.split("(");e=r[0].toLowerCase().trim();var i=r[1].substring(0,r[1].length-1);if(e==="currency"&&i.indexOf(":")<0)t.currency||(t.currency=i.trim());else if(e==="relativetime"&&i.indexOf(":")<0)t.range||(t.range=i.trim());else{var s=i.split(";");s.forEach(function(o){if(o){var a=o.split(":"),l=Tpe(a),A=l[0],c=l.slice(1),u=c.join(":").trim().replace(/^'+|'+$/g,"");t[A.trim()]||(t[A.trim()]=u),u==="false"&&(t[A.trim()]=!1),u==="true"&&(t[A.trim()]=!0),isNaN(u)||(t[A.trim()]=parseInt(u,10))}})}}return{formatName:e,formatOptions:t}}function Ef(n){var e={};return function(r,i,s){var o=i+JSON.stringify(s),a=e[o];return a||(a=n(i,s),e[o]=a),a(r)}}var tge=function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};lo(this,n),this.logger=pa.create("formatter"),this.options=e,this.formats={number:Ef(function(t,r){var i=new Intl.NumberFormat(t,tl({},r));return function(s){return i.format(s)}}),currency:Ef(function(t,r){var i=new Intl.NumberFormat(t,tl(tl({},r),{},{style:"currency"}));return function(s){return i.format(s)}}),datetime:Ef(function(t,r){var i=new Intl.DateTimeFormat(t,tl({},r));return function(s){return i.format(s)}}),relativetime:Ef(function(t,r){var i=new Intl.RelativeTimeFormat(t,tl({},r));return function(s){return i.format(s,r.range||"day")}}),list:Ef(function(t,r){var i=new Intl.ListFormat(t,tl({},r));return function(s){return i.format(s)}})},this.init(e)}return Ao(n,[{key:"init",value:function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}},i=r.interpolation;this.formatSeparator=i.formatSeparator?i.formatSeparator:i.formatSeparator||","}},{key:"add",value:function(t,r){this.formats[t.toLowerCase().trim()]=r}},{key:"addCached",value:function(t,r){this.formats[t.toLowerCase().trim()]=Ef(r)}},{key:"format",value:function(t,r,i){var s=this,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},a=r.split(this.formatSeparator),l=a.reduce(function(A,c){var u=ege(c),f=u.formatName,d=u.formatOptions;if(s.formats[f]){var h=A;try{var p=o&&o.formatParams&&o.formatParams[o.interpolationkey]||{},m=p.locale||p.lng||o.locale||o.lng||i;h=s.formats[f](A,m,tl(tl(tl({},d),o),p))}catch(g){s.logger.warn(g)}return h}else s.logger.warn("there was no format function for ".concat(f));return A},t);return l}}]),n}();function jk(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function $k(n){for(var e=1;e"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function ige(n,e){n.pending[e]!==void 0&&(delete n.pending[e],n.pendingCount--)}var sge=function(n){hb(t,n);var e=nge(t);function t(r,i,s){var o,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return lo(this,t),o=e.call(this),pb&&ic.call(HA(o)),o.backend=r,o.store=i,o.services=s,o.languageUtils=s.languageUtils,o.options=a,o.logger=pa.create("backendConnector"),o.waitingReads=[],o.maxParallelReads=a.maxParallelReads||10,o.readingCalls=0,o.maxRetries=a.maxRetries>=0?a.maxRetries:5,o.retryTimeout=a.retryTimeout>=1?a.retryTimeout:350,o.state={},o.queue=[],o.backend&&o.backend.init&&o.backend.init(s,a.backend,a),o}return Ao(t,[{key:"queueLoad",value:function(i,s,o,a){var l=this,A={},c={},u={},f={};return i.forEach(function(d){var h=!0;s.forEach(function(p){var m="".concat(d,"|").concat(p);!o.reload&&l.store.hasResourceBundle(d,p)?l.state[m]=2:l.state[m]<0||(l.state[m]===1?c[m]===void 0&&(c[m]=!0):(l.state[m]=1,h=!1,c[m]===void 0&&(c[m]=!0),A[m]===void 0&&(A[m]=!0),f[p]===void 0&&(f[p]=!0)))}),h||(u[d]=!0)}),(Object.keys(A).length||Object.keys(c).length)&&this.queue.push({pending:c,pendingCount:Object.keys(c).length,loaded:{},errors:[],callback:a}),{toLoad:Object.keys(A),pending:Object.keys(c),toLoadLanguages:Object.keys(u),toLoadNamespaces:Object.keys(f)}}},{key:"loaded",value:function(i,s,o){var a=i.split("|"),l=a[0],A=a[1];s&&this.emit("failedLoading",l,A,s),o&&this.store.addResourceBundle(l,A,o),this.state[i]=s?-1:2;var c={};this.queue.forEach(function(u){Vpe(u.loaded,[l],A),ige(u,i),s&&u.errors.push(s),u.pendingCount===0&&!u.done&&(Object.keys(u.loaded).forEach(function(f){c[f]||(c[f]={});var d=u.loaded[f];d.length&&d.forEach(function(h){c[f][h]===void 0&&(c[f][h]=!0)})}),u.done=!0,u.errors.length?u.callback(u.errors):u.callback())}),this.emit("loaded",c),this.queue=this.queue.filter(function(u){return!u.done})}},{key:"read",value:function(i,s,o){var a=this,l=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,A=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,c=arguments.length>5?arguments[5]:void 0;if(!i.length)return c(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:i,ns:s,fcName:o,tried:l,wait:A,callback:c});return}this.readingCalls++;var u=function(p,m){if(a.readingCalls--,a.waitingReads.length>0){var g=a.waitingReads.shift();a.read(g.lng,g.ns,g.fcName,g.tried,g.wait,g.callback)}if(p&&m&&l2&&arguments[2]!==void 0?arguments[2]:{},l=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),l&&l();typeof i=="string"&&(i=this.languageUtils.toResolveHierarchy(i)),typeof s=="string"&&(s=[s]);var A=this.queueLoad(i,s,a,l);if(!A.toLoad.length)return A.pending.length||l(),null;A.toLoad.forEach(function(c){o.loadOne(c)})}},{key:"load",value:function(i,s,o){this.prepareLoading(i,s,{},o)}},{key:"reload",value:function(i,s,o){this.prepareLoading(i,s,{reload:!0},o)}},{key:"loadOne",value:function(i){var s=this,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",a=i.split("|"),l=a[0],A=a[1];this.read(l,A,"read",void 0,void 0,function(c,u){c&&s.logger.warn("".concat(o,"loading namespace ").concat(A," for language ").concat(l," failed"),c),!c&&u&&s.logger.log("".concat(o,"loaded namespace ").concat(A," for language ").concat(l),u),s.loaded(i,c,u)})}},{key:"saveMissing",value:function(i,s,o,a,l){var A=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},c=arguments.length>6&&arguments[6]!==void 0?arguments[6]:function(){};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(s)){this.logger.warn('did not save key "'.concat(o,'" as the namespace "').concat(s,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(o==null||o==="")){if(this.backend&&this.backend.create){var u=$k($k({},A),{},{isUpdate:l}),f=this.backend.create.bind(this.backend);if(f.length<6)try{var d;f.length===5?d=f(i,s,o,a,u):d=f(i,s,o,a),d&&typeof d.then=="function"?d.then(function(h){return c(null,h)}).catch(c):c(null,d)}catch(h){c(h)}else f(i,s,o,a,c,u)}!i||!i[0]||this.store.addResource(i[0],s,o,a)}}}]),t}(ic);function qk(){return{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!0,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(e){var t={};if($s(e[1])==="object"&&(t=e[1]),typeof e[1]=="string"&&(t.defaultValue=e[1]),typeof e[2]=="string"&&(t.tDescription=e[2]),$s(e[2])==="object"||$s(e[3])==="object"){var r=e[3]||e[2];Object.keys(r).forEach(function(i){t[i]=r[i]})}return t},interpolation:{escapeValue:!0,format:function(e,t,r,i){return e},prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}}function eV(n){return typeof n.ns=="string"&&(n.ns=[n.ns]),typeof n.fallbackLng=="string"&&(n.fallbackLng=[n.fallbackLng]),typeof n.fallbackNS=="string"&&(n.fallbackNS=[n.fallbackNS]),n.supportedLngs&&n.supportedLngs.indexOf("cimode")<0&&(n.supportedLngs=n.supportedLngs.concat(["cimode"])),n}function tV(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function Ko(n){for(var e=1;e"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function vy(){}function lge(n){var e=Object.getOwnPropertyNames(Object.getPrototypeOf(n));e.forEach(function(t){typeof n[t]=="function"&&(n[t]=n[t].bind(n))})}var jw=function(n){hb(t,n);var e=oge(t);function t(){var r,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0;if(lo(this,t),r=e.call(this),pb&&ic.call(HA(r)),r.options=eV(i),r.services={},r.logger=pa,r.modules={external:[]},lge(HA(r)),s&&!r.isInitialized&&!i.isClone){if(!r.options.initImmediate)return r.init(i,s),y0(r,HA(r));setTimeout(function(){r.init(i,s)},0)}return r}return Ao(t,[{key:"init",value:function(){var i=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},o=arguments.length>1?arguments[1]:void 0;typeof s=="function"&&(o=s,s={}),!s.defaultNS&&s.defaultNS!==!1&&s.ns&&(typeof s.ns=="string"?s.defaultNS=s.ns:s.ns.indexOf("translation")<0&&(s.defaultNS=s.ns[0]));var a=qk();this.options=Ko(Ko(Ko({},a),this.options),eV(s)),this.options.compatibilityAPI!=="v1"&&(this.options.interpolation=Ko(Ko({},a.interpolation),this.options.interpolation)),s.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=s.keySeparator),s.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=s.nsSeparator);function l(g){return g?typeof g=="function"?new g:g:null}if(!this.options.isClone){this.modules.logger?pa.init(l(this.modules.logger),this.options):pa.init(null,this.options);var A;this.modules.formatter?A=this.modules.formatter:typeof Intl<"u"&&(A=tge);var c=new zk(this.options);this.store=new Jpe(this.options.resources,this.options);var u=this.services;u.logger=pa,u.resourceStore=this.store,u.languageUtils=c,u.pluralResolver=new $pe(c,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),A&&(!this.options.interpolation.format||this.options.interpolation.format===a.interpolation.format)&&(u.formatter=l(A),u.formatter.init(u,this.options),this.options.interpolation.format=u.formatter.format.bind(u.formatter)),u.interpolator=new qpe(this.options),u.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},u.backendConnector=new sge(l(this.modules.backend),u.resourceStore,u,this.options),u.backendConnector.on("*",function(g){for(var v=arguments.length,y=new Array(v>1?v-1:0),w=1;w1?v-1:0),w=1;w0&&f[0]!=="dev"&&(this.options.lng=f[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined");var d=["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"];d.forEach(function(g){i[g]=function(){var v;return(v=i.store)[g].apply(v,arguments)}});var h=["addResource","addResources","addResourceBundle","removeResourceBundle"];h.forEach(function(g){i[g]=function(){var v;return(v=i.store)[g].apply(v,arguments),i}});var p=zp(),m=function(){var v=function(w,C){i.isInitialized&&!i.initializedStoreOnce&&i.logger.warn("init: i18next is already initialized. You should call init just once!"),i.isInitialized=!0,i.options.isClone||i.logger.log("initialized",i.options),i.emit("initialized",i.options),p.resolve(C),o(w,C)};if(i.languages&&i.options.compatibilityAPI!=="v1"&&!i.isInitialized)return v(null,i.t.bind(i));i.changeLanguage(i.options.lng,v)};return this.options.resources||!this.options.initImmediate?m():setTimeout(m,0),p}},{key:"loadResources",value:function(i){var s=this,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:vy,a=o,l=typeof i=="string"?i:this.language;if(typeof i=="function"&&(a=i),!this.options.resources||this.options.partialBundledLanguages){if(l&&l.toLowerCase()==="cimode")return a();var A=[],c=function(d){if(d){var h=s.services.languageUtils.toResolveHierarchy(d);h.forEach(function(p){A.indexOf(p)<0&&A.push(p)})}};if(l)c(l);else{var u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.forEach(function(f){return c(f)})}this.options.preload&&this.options.preload.forEach(function(f){return c(f)}),this.services.backendConnector.load(A,this.options.ns,function(f){!f&&!s.resolvedLanguage&&s.language&&s.setResolvedLanguage(s.language),a(f)})}else a(null)}},{key:"reloadResources",value:function(i,s,o){var a=zp();return i||(i=this.languages),s||(s=this.options.ns),o||(o=vy),this.services.backendConnector.reload(i,s,function(l){a.resolve(),o(l)}),a}},{key:"use",value:function(i){if(!i)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!i.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return i.type==="backend"&&(this.modules.backend=i),(i.type==="logger"||i.log&&i.warn&&i.error)&&(this.modules.logger=i),i.type==="languageDetector"&&(this.modules.languageDetector=i),i.type==="i18nFormat"&&(this.modules.i18nFormat=i),i.type==="postProcessor"&&n4.addPostProcessor(i),i.type==="formatter"&&(this.modules.formatter=i),i.type==="3rdParty"&&this.modules.external.push(i),this}},{key:"setResolvedLanguage",value:function(i){if(!(!i||!this.languages)&&!(["cimode","dev"].indexOf(i)>-1))for(var s=0;s-1)&&this.store.hasLanguageSomeTranslations(o)){this.resolvedLanguage=o;break}}}},{key:"changeLanguage",value:function(i,s){var o=this;this.isLanguageChangingTo=i;var a=zp();this.emit("languageChanging",i);var l=function(f){o.language=f,o.languages=o.services.languageUtils.toResolveHierarchy(f),o.resolvedLanguage=void 0,o.setResolvedLanguage(f)},A=function(f,d){d?(l(d),o.translator.changeLanguage(d),o.isLanguageChangingTo=void 0,o.emit("languageChanged",d),o.logger.log("languageChanged",d)):o.isLanguageChangingTo=void 0,a.resolve(function(){return o.t.apply(o,arguments)}),s&&s(f,function(){return o.t.apply(o,arguments)})},c=function(f){!i&&!f&&o.services.languageDetector&&(f=[]);var d=typeof f=="string"?f:o.services.languageUtils.getBestMatchFromCodes(f);d&&(o.language||l(d),o.translator.language||o.translator.changeLanguage(d),o.services.languageDetector&&o.services.languageDetector.cacheUserLanguage&&o.services.languageDetector.cacheUserLanguage(d)),o.loadResources(d,function(h){A(h,d)})};return!i&&this.services.languageDetector&&!this.services.languageDetector.async?c(this.services.languageDetector.detect()):!i&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(c):this.services.languageDetector.detect(c):c(i),a}},{key:"getFixedT",value:function(i,s,o){var a=this,l=function A(c,u){var f;if($s(u)!=="object"){for(var d=arguments.length,h=new Array(d>2?d-2:0),p=2;p1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;var a=this.resolvedLanguage||this.languages[0],l=this.options?this.options.fallbackLng:!1,A=this.languages[this.languages.length-1];if(a.toLowerCase()==="cimode")return!0;var c=function(d,h){var p=s.services.backendConnector.state["".concat(d,"|").concat(h)];return p===-1||p===2};if(o.precheck){var u=o.precheck(this,c);if(u!==void 0)return u}return!!(this.hasResourceBundle(a,i)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||c(a,i)&&(!l||c(A,i)))}},{key:"loadNamespaces",value:function(i,s){var o=this,a=zp();return this.options.ns?(typeof i=="string"&&(i=[i]),i.forEach(function(l){o.options.ns.indexOf(l)<0&&o.options.ns.push(l)}),this.loadResources(function(l){a.resolve(),s&&s(l)}),a):(s&&s(),Promise.resolve())}},{key:"loadLanguages",value:function(i,s){var o=zp();typeof i=="string"&&(i=[i]);var a=this.options.preload||[],l=i.filter(function(A){return a.indexOf(A)<0});return l.length?(this.options.preload=a.concat(l),this.loadResources(function(A){o.resolve(),s&&s(A)}),o):(s&&s(),Promise.resolve())}},{key:"dir",value:function(i){if(i||(i=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!i)return"rtl";var s=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],o=this.services&&this.services.languageUtils||new zk(qk());return s.indexOf(o.getLanguagePartFromCode(i))>-1||i.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}},{key:"cloneInstance",value:function(){var i=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:vy,a=Ko(Ko(Ko({},this.options),s),{isClone:!0}),l=new t(a);(s.debug!==void 0||s.prefix!==void 0)&&(l.logger=l.logger.clone(s));var A=["store","services","language"];return A.forEach(function(c){l[c]=i[c]}),l.services=Ko({},this.services),l.services.utils={hasLoadedNamespace:l.hasLoadedNamespace.bind(l)},l.translator=new Hk(l.services,l.options),l.translator.on("*",function(c){for(var u=arguments.length,f=new Array(u>1?u-1:0),d=1;d0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;return new jw(n,e)});var ri=jw.createInstance();ri.createInstance=jw.createInstance;ri.createInstance;ri.dir;ri.init;ri.loadResources;ri.reloadResources;ri.use;ri.changeLanguage;ri.getFixedT;ri.t;ri.exists;ri.setDefaultNamespace;ri.hasLoadedNamespace;ri.loadNamespaces;ri.loadLanguages;function Age(){if(console&&console.warn){for(var n,e=arguments.length,t=new Array(e),r=0;r2&&arguments[2]!==void 0?arguments[2]:{},r=e.languages[0],i=e.options?e.options.fallbackLng:!1,s=e.languages[e.languages.length-1];if(r.toLowerCase()==="cimode")return!0;var o=function(l,A){var c=e.services.backendConnector.state["".concat(l,"|").concat(A)];return c===-1||c===2};return t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&e.services.backendConnector.backend&&e.isLanguageChangingTo&&!o(e.isLanguageChangingTo,n)?!1:!!(e.hasResourceBundle(r,n)||!e.services.backendConnector.backend||e.options.resources&&!e.options.partialBundledLanguages||o(r,n)&&(!i||o(s,n)))}function uge(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!e.languages||!e.languages.length)return hU("i18n.languages were undefined or empty",e.languages),!0;var r=e.options.ignoreJSONStructure!==void 0;return r?e.hasLoadedNamespace(n,{precheck:function(s,o){if(t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&s.services.backendConnector.backend&&s.isLanguageChangingTo&&!o(s.isLanguageChangingTo,n))return!1}}):cge(n,e,t)}var fge=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,dge={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},hge=function(e){return dge[e]},pge=function(e){return e.replace(fge,hge)};function iV(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function sV(n){for(var e=1;e0&&arguments[0]!==void 0?arguments[0]:{};pU=sV(sV({},pU),n)}function mge(){return pU}var r4;function vge(n){r4=n}function yge(){return r4}var Bge={type:"3rdParty",init:function(e){gge(e.options.react),vge(e)}},wge=me.createContext(),Cge=function(){function n(){lo(this,n),this.usedNamespaces={}}return Ao(n,[{key:"addUsedNamespaces",value:function(t){var r=this;t.forEach(function(i){r.usedNamespaces[i]||(r.usedNamespaces[i]=!0)})}},{key:"getUsedNamespaces",value:function(){return Object.keys(this.usedNamespaces)}}]),n}();function bge(n,e){var t=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(t!=null){var r,i,s,o,a=[],l=!0,A=!1;try{if(s=(t=t.call(n)).next,e===0){if(Object(t)!==t)return;l=!1}else for(;!(l=(r=s.call(t)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(c){A=!0,i=c}finally{try{if(!l&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(A)throw i}}return a}}function xge(n,e){return jH(n)||bge(n,e)||$H(n,e)||qH()}function oV(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function C1(n){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:{},t=e.i18n,r=me.useContext(wge)||{},i=r.i18n,s=r.defaultNS,o=t||i||yge();if(o&&!o.reportNamespaces&&(o.reportNamespaces=new Cge),!o){hU("You will need to pass in an i18next instance by using initReactI18next");var a=function(S,M){return typeof M=="string"?M:M&&$s(M)==="object"&&typeof M.defaultValue=="string"?M.defaultValue:Array.isArray(S)?S[S.length-1]:S},l=[a,{},!1];return l.t=a,l.i18n={},l.ready=!1,l}o.options.react&&o.options.react.wait!==void 0&&hU("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");var A=C1(C1(C1({},mge()),o.options.react),e),c=A.useSuspense,u=A.keyPrefix,f=n||s||o.options&&o.options.defaultNS;f=typeof f=="string"?[f]:f||["translation"],o.reportNamespaces.addUsedNamespaces&&o.reportNamespaces.addUsedNamespaces(f);var d=(o.isInitialized||o.initializedStoreOnce)&&f.every(function(x){return uge(x,o,A)});function h(){return o.getFixedT(null,A.nsMode==="fallback"?f:f[0],u)}var p=me.useState(h),m=xge(p,2),g=m[0],v=m[1],y=f.join(),w=Ige(y),C=me.useRef(!0);me.useEffect(function(){var x=A.bindI18n,S=A.bindI18nStore;C.current=!0,!d&&!c&&rV(o,f,function(){C.current&&v(h)}),d&&w&&w!==y&&C.current&&v(h);function M(){C.current&&v(h)}return x&&o&&o.on(x,M),S&&o&&o.store.on(S,M),function(){C.current=!1,x&&o&&x.split(" ").forEach(function(Z){return o.off(Z,M)}),S&&o&&S.split(" ").forEach(function(Z){return o.store.off(Z,M)})}},[o,y]);var b=me.useRef(!0);me.useEffect(function(){C.current&&!b.current&&v(h),b.current=!1},[o,u]);var E=[g,o,d];if(E.t=g,E.i18n=o,E.ready=d,d||!d&&!c)return E;throw new Promise(function(x){rV(o,f,function(){x()})})}var s4=[],Fge=s4.forEach,Ege=s4.slice;function Uge(n){return Fge.call(Ege.call(arguments,1),function(e){if(e)for(var t in e)n[t]===void 0&&(n[t]=e[t])}),n}var aV=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Sge=function(e,t,r){var i=r||{};i.path=i.path||"/";var s=encodeURIComponent(t),o="".concat(e,"=").concat(s);if(i.maxAge>0){var a=i.maxAge-0;if(Number.isNaN(a))throw new Error("maxAge should be a Number");o+="; Max-Age=".concat(Math.floor(a))}if(i.domain){if(!aV.test(i.domain))throw new TypeError("option domain is invalid");o+="; Domain=".concat(i.domain)}if(i.path){if(!aV.test(i.path))throw new TypeError("option path is invalid");o+="; Path=".concat(i.path)}if(i.expires){if(typeof i.expires.toUTCString!="function")throw new TypeError("option expires is invalid");o+="; Expires=".concat(i.expires.toUTCString())}if(i.httpOnly&&(o+="; HttpOnly"),i.secure&&(o+="; Secure"),i.sameSite){var l=typeof i.sameSite=="string"?i.sameSite.toLowerCase():i.sameSite;switch(l){case!0:o+="; SameSite=Strict";break;case"lax":o+="; SameSite=Lax";break;case"strict":o+="; SameSite=Strict";break;case"none":o+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return o},lV={create:function(e,t,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};r&&(s.expires=new Date,s.expires.setTime(s.expires.getTime()+r*60*1e3)),i&&(s.domain=i),document.cookie=Sge(e,encodeURIComponent(t),s)},read:function(e){for(var t="".concat(e,"="),r=document.cookie.split(";"),i=0;i-1&&(r=window.location.hash.substring(window.location.hash.indexOf("?")));for(var i=r.substring(1),s=i.split("&"),o=0;o0){var l=s[o].substring(0,a);l===e.lookupQuerystring&&(t=s[o].substring(a+1))}}}return t}},Yp=null,AV=function(){if(Yp!==null)return Yp;try{Yp=window!=="undefined"&&window.localStorage!==null;var e="i18next.translate.boo";window.localStorage.setItem(e,"foo"),window.localStorage.removeItem(e)}catch{Yp=!1}return Yp},Rge={name:"localStorage",lookup:function(e){var t;if(e.lookupLocalStorage&&AV()){var r=window.localStorage.getItem(e.lookupLocalStorage);r&&(t=r)}return t},cacheUserLanguage:function(e,t){t.lookupLocalStorage&&AV()&&window.localStorage.setItem(t.lookupLocalStorage,e)}},Xp=null,cV=function(){if(Xp!==null)return Xp;try{Xp=window!=="undefined"&&window.sessionStorage!==null;var e="i18next.translate.boo";window.sessionStorage.setItem(e,"foo"),window.sessionStorage.removeItem(e)}catch{Xp=!1}return Xp},Mge={name:"sessionStorage",lookup:function(e){var t;if(e.lookupSessionStorage&&cV()){var r=window.sessionStorage.getItem(e.lookupSessionStorage);r&&(t=r)}return t},cacheUserLanguage:function(e,t){t.lookupSessionStorage&&cV()&&window.sessionStorage.setItem(t.lookupSessionStorage,e)}},Tge={name:"navigator",lookup:function(e){var t=[];if(typeof navigator<"u"){if(navigator.languages)for(var r=0;r0?t:void 0}},Nge={name:"htmlTag",lookup:function(e){var t,r=e.htmlTag||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(t=r.getAttribute("lang")),t}},Dge={name:"path",lookup:function(e){var t;if(typeof window<"u"){var r=window.location.pathname.match(/\/([a-zA-Z-]*)/g);if(r instanceof Array)if(typeof e.lookupFromPathIndex=="number"){if(typeof r[e.lookupFromPathIndex]!="string")return;t=r[e.lookupFromPathIndex].replace("/","")}else t=r[0].replace("/","")}return t}},kge={name:"subdomain",lookup:function(e){var t=typeof e.lookupFromSubdomainIndex=="number"?e.lookupFromSubdomainIndex+1:1,r=typeof window<"u"&&window.location&&window.location.hostname&&window.location.hostname.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(r)return r[t]}};function Vge(){return{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"]}}var o4=function(){function n(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};lo(this,n),this.type="languageDetector",this.detectors={},this.init(e,t)}return Ao(n,[{key:"init",value:function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=t,this.options=Uge(r,this.options||{},Vge()),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=i,this.addDetector(_ge),this.addDetector(Qge),this.addDetector(Rge),this.addDetector(Mge),this.addDetector(Tge),this.addDetector(Nge),this.addDetector(Dge),this.addDetector(kge)}},{key:"addDetector",value:function(t){this.detectors[t.name]=t}},{key:"detect",value:function(t){var r=this;t||(t=this.options.order);var i=[];return t.forEach(function(s){if(r.detectors[s]){var o=r.detectors[s].lookup(r.options);o&&typeof o=="string"&&(o=[o]),o&&(i=i.concat(o))}}),this.services.languageUtils.getBestMatchFromCodes?i:i.length>0?i[0]:null}},{key:"cacheUserLanguage",value:function(t,r){var i=this;r||(r=this.options.caches),r&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(t)>-1||r.forEach(function(s){i.detectors[s]&&i.detectors[s].cacheUserLanguage(t,i.options)}))}}]),n}();o4.type="languageDetector";const Lge={translation:{pageTitles:{chooseClass:"Choose Character Class",chooseAppearance:"Choose Appearance",createBio:"Create Bio",saveCharacter:"Save Your Character",chat:"Chat With Your Character"},classes:{beastPainter:{name:"Beast Painter",description:"Paints beasts"},engineer:{name:"Engineer",description:"Builds things"},dropHunter:{name:"Drop Hunter",description:"Hunts drops"},theDegen:{name:"The Degen",description:"Degens"},neuralHacker:{name:"Neural Hacker",description:"Hacks neural networks"},liskWitch:{name:"Lisk Witch",description:"Witches lisk"},bruiser:{name:"Bruiser",description:"Bruises things"}},callToAction:{next:"Next",back:"Back",randomize:"Randomize",chat:"Chat",send:"Send"},editor:{title:"Appearance",head:"Head",body:"Body",eyes:"Eyes",outer:"Outer",chest:"Chest",legs:"Legs",feet:"Feet",accessories:"Accessories"},labels:{name:"Name",voice:"Voice",favoriteColor:"Favorite Color",preferredGreeting:"Preferred Greeting",bio:"Bio",question:"Question",yourName:"Your Name",conversation:"Conversation"},text:{unoptimized:"Unoptimized",apiUnderMaintnance:"Voice generation API is temporarily disabled for maintenance!"}}},Pge={translation:{pageTitles:{chooseClass:"Выбрать Класс Персонажа",chooseAppearance:"Выбрать Внешность",createBio:"Создать Биографию",saveCharacter:"Сохранить Персонажа",chat:"Общаться Со Своим Персонажем"},classes:{beastPainter:{name:"Анималист",description:"Рисует зверей"},engineer:{name:"Инженер",description:"Строит вещи"},dropHunter:{name:"Охотник за дропами",description:"Охотится на дропы"},theDegen:{name:"Деген",description:"Дегены"},neuralHacker:{name:"Нейронный Хакер",description:"Взламывает нейр. сети"},liskWitch:{name:"Лиск Ведьма",description:"Лиск Ведьмы"},bruiser:{name:"Громила",description:"Громит вещи"}},callToAction:{next:"Далее",back:"Назад",randomize:"Рандомизировать",chat:"Чат",send:"Отправить"},editor:{title:"Внешность",head:"Голова",body:"Тело",eyes:"Глаза",outer:"Внешний",chest:"Грудь",legs:"Ноги",feet:"Стопы",accessories:"Аксессуары"},labels:{name:"Имя",voice:"Голос",favoriteColor:"Любимый Цвет",preferredGreeting:"Предпочитаемое Приветствие",bio:"Биография",question:"Вопрос",yourName:"Ваше Имя",conversation:"Разговор"},text:{unoptimized:"Неоптимизи­рованный",apiUnderMaintnance:"API генерации голоса временно отключен на техническое обслуживание."}}},Wge={translation:{pageTitles:{chooseClass:"选择角色类型",chooseAppearance:"选择外观",createBio:"创建简介",saveCharacter:"保存角色",chat:"与你的角色聊天"},classes:{beastPainter:{name:"野兽画家",description:"画野兽"},engineer:{name:"工程师",description:"建造物品"},dropHunter:{name:"投放猎手",description:"猎取投放品"},theDegen:{name:"豪赌家",description:"资深赌徒"},neuralHacker:{name:"神经黑客",description:"侵入神经网络"},liskWitch:{name:"Lisk 巫师",description:"施法于 Lisk"},bruiser:{name:"碾压者",description:"碾碎一切"}},callToAction:{next:"下一步",back:"返回",randomize:"随机",chat:"聊天",send:"发送"},editor:{title:"外观",head:"头部",body:"身体",eyes:"眼睛",outer:"外套",chest:"上身",legs:"腿部",feet:"脚部",accessories:"配件"},labels:{name:"名字",voice:"语音",favoriteColor:"颜色偏好",preferredGreeting:"首选问候语",bio:"简介",question:"问题",yourName:"你的名字",conversation:"对话"},text:{unoptimized:"未优化",apiUnderMaintnance:"语音生成API暂时关闭进行维护!"}}},Oge={en:Lge,ru:Pge,zh:Wge};ri.use(o4).use(Bge).init({debug:!0,fallbackLng:"en",interpolation:{escapeValue:!1},resources:Oge});const bs=me.createContext(),Gge=n=>{const{t:e}=i4();return P.jsx(bs.Provider,{value:{t:e},children:n.children})},Zge=` uniform vec3 cameraDir; uniform vec3 eye; diff --git a/index.html b/index.html index 7c8757ea..d57ade75 100644 --- a/index.html +++ b/index.html @@ -7,7 +7,7 @@ Character Studio - +