@streamoji/avatar-widget 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4146,7 +4146,7 @@ void main() {
4146
4146
  vec3 clampedHdrColor = max( HALF_FLOAT_MIN, min( HALF_FLOAT_MAX, hdrColor ));
4147
4147
  gl_FragColor = vec4( clampedHdrColor , 1.0 );
4148
4148
  }
4149
- `;class HI extends gs{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;constructor({gamma:e,offsetHdr:t,offsetSdr:n,gainMapMin:i,gainMapMax:o,maxDisplayBoost:l,hdrCapacityMin:h,hdrCapacityMax:d,sdr:p,gainMap:_}){super({name:"GainMapDecoderMaterial",vertexShader:II,fragmentShader:FI,uniforms:{sdr:{value:p},gainMap:{value:_},gamma:{value:new Z(1/e[0],1/e[1],1/e[2])},offsetHdr:{value:new Z().fromArray(t)},offsetSdr:{value:new Z().fromArray(n)},gainMapMin:{value:new Z().fromArray(i)},gainMapMax:{value:new Z().fromArray(o)},weightFactor:{value:(Math.log2(l)-h)/(d-h)}},blending:Jr,depthTest:!1,depthWrite:!1}),this._maxDisplayBoost=l,this._hdrCapacityMin=h,this._hdrCapacityMax=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get sdr(){return this.uniforms.sdr.value}set sdr(e){this.uniforms.sdr.value=e}get gainMap(){return this.uniforms.gainMap.value}set gainMap(e){this.uniforms.gainMap.value=e}get offsetHdr(){return this.uniforms.offsetHdr.value.toArray()}set offsetHdr(e){this.uniforms.offsetHdr.value.fromArray(e)}get offsetSdr(){return this.uniforms.offsetSdr.value.toArray()}set offsetSdr(e){this.uniforms.offsetSdr.value.fromArray(e)}get gainMapMin(){return this.uniforms.gainMapMin.value.toArray()}set gainMapMin(e){this.uniforms.gainMapMin.value.fromArray(e)}get gainMapMax(){return this.uniforms.gainMapMax.value.toArray()}set gainMapMax(e){this.uniforms.gainMapMax.value.fromArray(e)}get gamma(){const e=this.uniforms.gamma.value;return[1/e.x,1/e.y,1/e.z]}set gamma(e){const t=this.uniforms.gamma.value;t.x=1/e[0],t.y=1/e[1],t.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this.uniforms.weightFactor.value=Math.max(0,Math.min(1,e))}}class tC extends OI{constructor(e,t){super({renderer:e,createMaterial:n=>new HI(n),createQuadRenderer:n=>new CS(n)},t)}async render(e,t,n,i){const{sdrImage:o,gainMapImage:l,needsFlip:h}=await this.processImages(n,i,"flipY"),{gainMap:d,sdr:p}=this.createTextures(o,l,h);this.updateQuadRenderer(e,o,d,p,t),e.render()}}class PI extends tC{load([e,t,n],i,o,l){const h=this.prepareQuadRenderer();let d,p,_;const v=async()=>{if(d&&p&&_){try{await this.render(h,_,d,p)}catch(U){this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(n),typeof l=="function"&&l(U),h.disposeOnDemandRenderer();return}typeof i=="function"&&i(h),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(n),h.disposeOnDemandRenderer()}};let y=!0,x=0,b=0,R=!0,T=0,M=0,w=!0,D=0,N=0;const F=()=>{if(typeof o=="function"){const U=x+T+D,I=b+M+N,W=y&&R&&w;o(new ProgressEvent("progress",{lengthComputable:W,loaded:I,total:U}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(n);const O=new da(this._internalLoadingManager);O.setResponseType("arraybuffer"),O.setRequestHeader(this.requestHeader),O.setPath(this.path),O.setWithCredentials(this.withCredentials),O.load(e,async U=>{if(typeof U=="string")throw new Error("Invalid sdr buffer");d=U,await v()},U=>{y=U.lengthComputable,b=U.loaded,x=U.total,F()},U=>{this.manager.itemError(e),typeof l=="function"&&l(U)});const z=new da(this._internalLoadingManager);z.setResponseType("arraybuffer"),z.setRequestHeader(this.requestHeader),z.setPath(this.path),z.setWithCredentials(this.withCredentials),z.load(t,async U=>{if(typeof U=="string")throw new Error("Invalid gainmap buffer");p=U,await v()},U=>{R=U.lengthComputable,M=U.loaded,T=U.total,F()},U=>{this.manager.itemError(t),typeof l=="function"&&l(U)});const V=new da(this._internalLoadingManager);return V.setRequestHeader(this.requestHeader),V.setPath(this.path),V.setWithCredentials(this.withCredentials),V.load(n,async U=>{if(typeof U!="string")throw new Error("Invalid metadata string");_=JSON.parse(U),await v()},U=>{w=U.lengthComputable,N=U.loaded,D=U.total,F()},U=>{this.manager.itemError(n),typeof l=="function"&&l(U)}),h}}class GI extends tC{load(e,t,n,i){const o=this.prepareQuadRenderer(),l=new da(this._internalLoadingManager);return l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setPath(this.path),l.setWithCredentials(this.withCredentials),this.manager.itemStart(e),l.load(e,async h=>{if(typeof h=="string")throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const d=new Uint8Array(h);let p,_,v;try{const y=await LI(d);p=y.sdr,_=y.gainMap,v=y.metadata}catch(y){if(y instanceof $T||y instanceof QT)console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),v={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},p=d;else throw y}try{await this.render(o,v,p.buffer,_?.buffer)}catch(y){this.manager.itemError(e),typeof i=="function"&&i(y),o.disposeOnDemandRenderer();return}typeof t=="function"&&t(o),this.manager.itemEnd(e),o.disposeOnDemandRenderer()},n,h=>{this.manager.itemError(e),typeof i=="function"&&i(h)}),o}}const nm={apartment:"lebombo_1k.hdr",city:"potsdamer_platz_1k.hdr",dawn:"kiara_1_dawn_1k.hdr",forest:"forest_slope_1k.hdr",lobby:"st_fagans_interior_1k.hdr",night:"dikhololo_night_1k.hdr",park:"rooitou_park_1k.hdr",studio:"studio_small_03_1k.hdr",sunset:"venice_sunset_1k.hdr",warehouse:"empty_warehouse_01_1k.hdr"},nC="https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/",Vh=s=>Array.isArray(s),RS=["/px.png","/nx.png","/py.png","/ny.png","/pz.png","/nz.png"];function p_({files:s=RS,path:e="",preset:t=void 0,colorSpace:n=void 0,extensions:i}={}){t&&(wS(t),s=nm[t],e=nC);const o=Vh(s),{extension:l,isCubemap:h}=BS(s),d=DS(l);if(!d)throw new Error("useEnvironment: Unrecognized file extension: "+s);const p=Ih(x=>x.gl);Me.useLayoutEffect(()=>{if(l!=="webp"&&l!=="jpg"&&l!=="jpeg")return;function x(){Rl.clear(d,o?[s]:s)}p.domElement.addEventListener("webglcontextlost",x,{once:!0})},[s,p.domElement]);const _=Rl(d,o?[s]:s,x=>{(l==="webp"||l==="jpg"||l==="jpeg")&&x.setRenderer(p),x.setPath==null||x.setPath(e),i&&i(x)});let v=o?_[0]:_;if(l==="jpg"||l==="jpeg"||l==="webp"){var y;v=(y=v.renderTarget)==null?void 0:y.texture}return v.mapping=h?qr:Wf,v.colorSpace=n??(h?"srgb":"srgb-linear"),v}const zI={files:RS,path:"",preset:void 0,extensions:void 0};p_.preload=s=>{const e={...zI,...s};let{files:t,path:n=""}=e;const{preset:i,extensions:o}=e;i&&(wS(i),t=nm[i],n=nC);const{extension:l}=BS(t);if(l==="webp"||l==="jpg"||l==="jpeg")throw new Error("useEnvironment: Preloading gainmaps is not supported");const h=DS(l);if(!h)throw new Error("useEnvironment: Unrecognized file extension: "+t);Rl.preload(h,Vh(t)?[t]:t,d=>{d.setPath==null||d.setPath(n),o&&o(d)})};const VI={files:RS,preset:void 0};p_.clear=s=>{const e={...VI,...s};let{files:t}=e;const{preset:n}=e;n&&(wS(n),t=nm[n]);const{extension:i}=BS(t),o=DS(i);if(!o)throw new Error("useEnvironment: Unrecognized file extension: "+t);Rl.clear(o,Vh(t)?[t]:t)};function wS(s){if(!(s in nm))throw new Error("Preset must be one of: "+Object.keys(nm).join(", "))}function BS(s){var e;const t=Vh(s)&&s.length===6,n=Vh(s)&&s.length===3&&s.some(l=>l.endsWith("json")),i=Vh(s)?s[0]:s;return{extension:t?"cube":n?"webp":i.startsWith("data:application/exr")?"exr":i.startsWith("data:application/hdr")?"hdr":i.startsWith("data:image/jpeg")?"jpg":(e=i.split(".").pop())==null||(e=e.split("?"))==null||(e=e.shift())==null?void 0:e.toLowerCase(),isCubemap:t,isGainmap:n}}function DS(s){return s==="cube"?P1:s==="hdr"?CI:s==="exr"?RI:s==="jpg"||s==="jpeg"?GI:s==="webp"?PI:null}const kI=s=>s.current&&s.current.isScene,XI=s=>kI(s)?s.current:s;function NS(s,e,t,n,i={}){var o,l,h,d;i={backgroundBlurriness:0,backgroundIntensity:1,backgroundRotation:[0,0,0],environmentIntensity:1,environmentRotation:[0,0,0],...i};const p=XI(e||t),_=p.background,v=p.environment,y={backgroundBlurriness:p.backgroundBlurriness,backgroundIntensity:p.backgroundIntensity,backgroundRotation:(o=(l=p.backgroundRotation)==null||l.clone==null?void 0:l.clone())!==null&&o!==void 0?o:[0,0,0],environmentIntensity:p.environmentIntensity,environmentRotation:(h=(d=p.environmentRotation)==null||d.clone==null?void 0:d.clone())!==null&&h!==void 0?h:[0,0,0]};return s!=="only"&&(p.environment=n),s&&(p.background=n),No(p,i),()=>{s!=="only"&&(p.environment=v),s&&(p.background=_),No(p,y)}}function US({scene:s,background:e=!1,map:t,...n}){const i=Ih(o=>o.scene);return Me.useLayoutEffect(()=>{if(t)return NS(e,s,i,t,n)}),null}function iC({background:s=!1,scene:e,blur:t,backgroundBlurriness:n,backgroundIntensity:i,backgroundRotation:o,environmentIntensity:l,environmentRotation:h,...d}){const p=p_(d),_=Ih(v=>v.scene);return Me.useLayoutEffect(()=>NS(s,e,_,p,{backgroundBlurriness:t??n,backgroundIntensity:i,backgroundRotation:o,environmentIntensity:l,environmentRotation:h})),Me.useEffect(()=>()=>{p.dispose()},[p]),null}function YI({children:s,near:e=.1,far:t=1e3,resolution:n=256,frames:i=1,map:o,background:l=!1,blur:h,backgroundBlurriness:d,backgroundIntensity:p,backgroundRotation:_,environmentIntensity:v,environmentRotation:y,scene:x,files:b,path:R,preset:T=void 0,extensions:M}){const w=Ih(V=>V.gl),D=Ih(V=>V.scene),N=Me.useRef(null),[F]=Me.useState(()=>new Mp),O=Me.useMemo(()=>{const V=new Y0(n);return V.texture.type=ki,V},[n]);Me.useEffect(()=>()=>{O.dispose()},[O]),Me.useLayoutEffect(()=>{if(i===1){const V=w.autoClear;w.autoClear=!0,N.current.update(w,F),w.autoClear=V}return NS(l,x,D,O.texture,{backgroundBlurriness:h??d,backgroundIntensity:p,backgroundRotation:_,environmentIntensity:v,environmentRotation:y})},[s,F,O.texture,x,D,l,i,w]);let z=1;return yT(()=>{if(i===1/0||z<i){const V=w.autoClear;w.autoClear=!0,N.current.update(w,F),w.autoClear=V,z++}}),Me.createElement(Me.Fragment,null,_O(Me.createElement(Me.Fragment,null,s,Me.createElement("cubeCamera",{ref:N,args:[e,t,O]}),b||T?Me.createElement(iC,{background:!0,files:b,preset:T,path:R,extensions:M}):o?Me.createElement(US,{background:!0,map:o,extensions:M}):null),F))}function JI(s){var e,t,n,i;const o=p_(s),l=s.map||o;Me.useMemo(()=>MT({GroundProjectedEnvImpl:YO}),[]),Me.useEffect(()=>()=>{o.dispose()},[o]);const h=Me.useMemo(()=>[l],[l]),d=(e=s.ground)==null?void 0:e.height,p=(t=s.ground)==null?void 0:t.radius,_=(n=(i=s.ground)==null?void 0:i.scale)!==null&&n!==void 0?n:1e3;return Me.createElement(Me.Fragment,null,Me.createElement(US,ky({},s,{map:l})),Me.createElement("groundProjectedEnvImpl",{args:h,scale:_,height:d,radius:p}))}function qI(s){return s.ground?Me.createElement(JI,s):s.map?Me.createElement(US,s):s.children?Me.createElement(YI,s):Me.createElement(iC,s)}function aC(s,e){if(e===ox)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===bu||e===fp){let t=s.getIndex();if(t===null){const l=[],h=s.getAttribute("position");if(h!==void 0){for(let d=0;d<h.count;d++)l.push(d);s.setIndex(l),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const n=t.count-2,i=[];if(e===bu)for(let l=1;l<=n;l++)i.push(t.getX(0)),i.push(t.getX(l)),i.push(t.getX(l+1));else for(let l=0;l<n;l++)l%2===0?(i.push(t.getX(l)),i.push(t.getX(l+1)),i.push(t.getX(l+2))):(i.push(t.getX(l+2)),i.push(t.getX(l+1)),i.push(t.getX(l)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=s.clone();return o.setIndex(i),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class KI extends wa{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new $I(t)}),this.register(function(t){return new eF(t)}),this.register(function(t){return new cF(t)}),this.register(function(t){return new uF(t)}),this.register(function(t){return new fF(t)}),this.register(function(t){return new nF(t)}),this.register(function(t){return new iF(t)}),this.register(function(t){return new aF(t)}),this.register(function(t){return new sF(t)}),this.register(function(t){return new QI(t)}),this.register(function(t){return new rF(t)}),this.register(function(t){return new tF(t)}),this.register(function(t){return new lF(t)}),this.register(function(t){return new oF(t)}),this.register(function(t){return new jI(t)}),this.register(function(t){return new hF(t)}),this.register(function(t){return new dF(t)})}load(e,t,n,i){const o=this;let l;if(this.resourcePath!=="")l=this.resourcePath;else if(this.path!==""){const p=ir.extractUrlBase(e);l=ir.resolveURL(p,this.path)}else l=ir.extractUrlBase(e);this.manager.itemStart(e);const h=function(p){i?i(p):console.error(p),o.manager.itemError(e),o.manager.itemEnd(e)},d=new da(this.manager);d.setPath(this.path),d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setWithCredentials(this.withCredentials),d.load(e,function(p){try{o.parse(p,l,function(_){t(_),o.manager.itemEnd(e)},h)}catch(_){h(_)}},n,h)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,i){let o;const l={},h={},d=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(d.decode(new Uint8Array(e,0,4))===sC){try{l[Fn.KHR_BINARY_GLTF]=new pF(e)}catch(v){i&&i(v);return}o=JSON.parse(l[Fn.KHR_BINARY_GLTF].content)}else o=JSON.parse(d.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const p=new CF(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});p.fileLoader.setRequestHeader(this.requestHeader);for(let _=0;_<this.pluginCallbacks.length;_++){const v=this.pluginCallbacks[_](p);v.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),h[v.name]=v,l[v.name]=!0}if(o.extensionsUsed)for(let _=0;_<o.extensionsUsed.length;++_){const v=o.extensionsUsed[_],y=o.extensionsRequired||[];switch(v){case Fn.KHR_MATERIALS_UNLIT:l[v]=new ZI;break;case Fn.KHR_DRACO_MESH_COMPRESSION:l[v]=new mF(o,this.dracoLoader);break;case Fn.KHR_TEXTURE_TRANSFORM:l[v]=new gF;break;case Fn.KHR_MESH_QUANTIZATION:l[v]=new vF;break;default:y.indexOf(v)>=0&&h[v]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+v+'".')}}p.setExtensions(l),p.setPlugins(h),p.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,o){n.parse(e,t,i,o)})}}function WI(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const Fn={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class jI{constructor(e){this.parser=e,this.name=Fn.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){const o=t[n];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const o=t.json,d=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e];let p;const _=new Ct(16777215);d.color!==void 0&&_.setRGB(d.color[0],d.color[1],d.color[2],na);const v=d.range!==void 0?d.range:0;switch(d.type){case"directional":p=new Pv(_),p.target.position.set(0,0,-1),p.add(p.target);break;case"point":p=new Hv(_),p.distance=v;break;case"spot":p=new Fv(_),p.distance=v,d.spot=d.spot||{},d.spot.innerConeAngle=d.spot.innerConeAngle!==void 0?d.spot.innerConeAngle:0,d.spot.outerConeAngle=d.spot.outerConeAngle!==void 0?d.spot.outerConeAngle:Math.PI/4,p.angle=d.spot.outerConeAngle,p.penumbra=1-d.spot.innerConeAngle/d.spot.outerConeAngle,p.target.position.set(0,0,-1),p.add(p.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+d.type)}return p.position.set(0,0,0),Uo(p,d),d.intensity!==void 0&&(p.intensity=d.intensity),p.name=t.createUniqueName(d.name||"light_"+e),i=Promise.resolve(p),t.cache.add(n,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,o=n.json.nodes[e],h=(o.extensions&&o.extensions[this.name]||{}).light;return h===void 0?null:this._loadLight(h).then(function(d){return n._getNodeRef(t.cache,h,d)})}}class ZI{constructor(){this.name=Fn.KHR_MATERIALS_UNLIT}getMaterialType(){return ha}extendParams(e,t,n){const i=[];e.color=new Ct(1,1,1),e.opacity=1;const o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const l=o.baseColorFactor;e.color.setRGB(l[0],l[1],l[2],na),e.opacity=l[3]}o.baseColorTexture!==void 0&&i.push(n.assignTexture(e,"map",o.baseColorTexture,Xi))}return Promise.all(i)}}class QI{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name].emissiveStrength;return o!==void 0&&(t.emissiveIntensity=o),Promise.resolve()}}class $I{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];if(l.clearcoatFactor!==void 0&&(t.clearcoat=l.clearcoatFactor),l.clearcoatTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatMap",l.clearcoatTexture)),l.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=l.clearcoatRoughnessFactor),l.clearcoatRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatRoughnessMap",l.clearcoatRoughnessTexture)),l.clearcoatNormalTexture!==void 0&&(o.push(n.assignTexture(t,"clearcoatNormalMap",l.clearcoatNormalTexture)),l.clearcoatNormalTexture.scale!==void 0)){const h=l.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new tt(h,h)}return Promise.all(o)}}class eF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name];return t.dispersion=o.dispersion!==void 0?o.dispersion:0,Promise.resolve()}}class tF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.iridescenceFactor!==void 0&&(t.iridescence=l.iridescenceFactor),l.iridescenceTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceMap",l.iridescenceTexture)),l.iridescenceIor!==void 0&&(t.iridescenceIOR=l.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),l.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=l.iridescenceThicknessMinimum),l.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=l.iridescenceThicknessMaximum),l.iridescenceThicknessTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceThicknessMap",l.iridescenceThicknessTexture)),Promise.all(o)}}class nF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[];t.sheenColor=new Ct(0,0,0),t.sheenRoughness=0,t.sheen=1;const l=i.extensions[this.name];if(l.sheenColorFactor!==void 0){const h=l.sheenColorFactor;t.sheenColor.setRGB(h[0],h[1],h[2],na)}return l.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=l.sheenRoughnessFactor),l.sheenColorTexture!==void 0&&o.push(n.assignTexture(t,"sheenColorMap",l.sheenColorTexture,Xi)),l.sheenRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"sheenRoughnessMap",l.sheenRoughnessTexture)),Promise.all(o)}}class iF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.transmissionFactor!==void 0&&(t.transmission=l.transmissionFactor),l.transmissionTexture!==void 0&&o.push(n.assignTexture(t,"transmissionMap",l.transmissionTexture)),Promise.all(o)}}class aF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];t.thickness=l.thicknessFactor!==void 0?l.thicknessFactor:0,l.thicknessTexture!==void 0&&o.push(n.assignTexture(t,"thicknessMap",l.thicknessTexture)),t.attenuationDistance=l.attenuationDistance||1/0;const h=l.attenuationColor||[1,1,1];return t.attenuationColor=new Ct().setRGB(h[0],h[1],h[2],na),Promise.all(o)}}class sF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name];return t.ior=o.ior!==void 0?o.ior:1.5,Promise.resolve()}}class rF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];t.specularIntensity=l.specularFactor!==void 0?l.specularFactor:1,l.specularTexture!==void 0&&o.push(n.assignTexture(t,"specularIntensityMap",l.specularTexture));const h=l.specularColorFactor||[1,1,1];return t.specularColor=new Ct().setRGB(h[0],h[1],h[2],na),l.specularColorTexture!==void 0&&o.push(n.assignTexture(t,"specularColorMap",l.specularColorTexture,Xi)),Promise.all(o)}}class oF{constructor(e){this.parser=e,this.name=Fn.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return t.bumpScale=l.bumpFactor!==void 0?l.bumpFactor:1,l.bumpTexture!==void 0&&o.push(n.assignTexture(t,"bumpMap",l.bumpTexture)),Promise.all(o)}}class lF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.anisotropyStrength!==void 0&&(t.anisotropy=l.anisotropyStrength),l.anisotropyRotation!==void 0&&(t.anisotropyRotation=l.anisotropyRotation),l.anisotropyTexture!==void 0&&o.push(n.assignTexture(t,"anisotropyMap",l.anisotropyTexture)),Promise.all(o)}}class cF{constructor(e){this.parser=e,this.name=Fn.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const o=i.extensions[this.name],l=t.options.ktx2Loader;if(!l){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,o.source,l)}}class uF{constructor(e){this.parser=e,this.name=Fn.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const l=o.extensions[t],h=i.images[l.source];let d=n.textureLoader;if(h.uri){const p=n.options.manager.getHandler(h.uri);p!==null&&(d=p)}return n.loadTextureImage(e,l.source,d)}}class fF{constructor(e){this.parser=e,this.name=Fn.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const l=o.extensions[t],h=i.images[l.source];let d=n.textureLoader;if(h.uri){const p=n.options.manager.getHandler(h.uri);p!==null&&(d=p)}return n.loadTextureImage(e,l.source,d)}}class hF{constructor(e){this.name=Fn.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const i=n.extensions[this.name],o=this.parser.getDependency("buffer",i.buffer),l=this.parser.options.meshoptDecoder;if(!l||!l.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(h){const d=i.byteOffset||0,p=i.byteLength||0,_=i.count,v=i.byteStride,y=new Uint8Array(h,d,p);return l.decodeGltfBufferAsync?l.decodeGltfBufferAsync(_,v,y,i.mode,i.filter).then(function(x){return x.buffer}):l.ready.then(function(){const x=new ArrayBuffer(_*v);return l.decodeGltfBuffer(new Uint8Array(x),_,v,y,i.mode,i.filter),x})})}else return null}}class dF{constructor(e){this.name=Fn.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const i=t.meshes[n.mesh];for(const p of i.primitives)if(p.mode!==Mr.TRIANGLES&&p.mode!==Mr.TRIANGLE_STRIP&&p.mode!==Mr.TRIANGLE_FAN&&p.mode!==void 0)return null;const l=n.extensions[this.name].attributes,h=[],d={};for(const p in l)h.push(this.parser.getDependency("accessor",l[p]).then(_=>(d[p]=_,d[p])));return h.length<1?null:(h.push(this.parser.createNodeMesh(e)),Promise.all(h).then(p=>{const _=p.pop(),v=_.isGroup?_.children:[_],y=p[0].count,x=[];for(const b of v){const R=new tn,T=new Z,M=new Ta,w=new Z(1,1,1),D=new nv(b.geometry,b.material,y);for(let N=0;N<y;N++)d.TRANSLATION&&T.fromBufferAttribute(d.TRANSLATION,N),d.ROTATION&&M.fromBufferAttribute(d.ROTATION,N),d.SCALE&&w.fromBufferAttribute(d.SCALE,N),D.setMatrixAt(N,R.compose(T,M,w));for(const N in d)if(N==="_COLOR_0"){const F=d[N];D.instanceColor=new xc(F.array,F.itemSize,F.normalized)}else N!=="TRANSLATION"&&N!=="ROTATION"&&N!=="SCALE"&&b.geometry.setAttribute(N,d[N]);On.prototype.copy.call(D,b),this.parser.assignFinalMaterial(D),x.push(D)}return _.isGroup?(_.clear(),_.add(...x),_):x[0]}))}}const sC="glTF",im=12,rC={JSON:1313821514,BIN:5130562};class pF{constructor(e){this.name=Fn.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,im),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==sC)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-im,o=new DataView(e,im);let l=0;for(;l<i;){const h=o.getUint32(l,!0);l+=4;const d=o.getUint32(l,!0);if(l+=4,d===rC.JSON){const p=new Uint8Array(e,im+l,h);this.content=n.decode(p)}else if(d===rC.BIN){const p=im+l;this.body=e.slice(p,p+h)}l+=h}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class mF{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Fn.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,o=e.extensions[this.name].bufferView,l=e.extensions[this.name].attributes,h={},d={},p={};for(const _ in l){const v=OS[_]||_.toLowerCase();h[v]=l[_]}for(const _ in e.attributes){const v=OS[_]||_.toLowerCase();if(l[_]!==void 0){const y=n.accessors[e.attributes[_]],x=kh[y.componentType];p[v]=x.name,d[v]=y.normalized===!0}}return t.getDependency("bufferView",o).then(function(_){return new Promise(function(v,y){i.decodeDracoFile(_,function(x){for(const b in x.attributes){const R=x.attributes[b],T=d[b];T!==void 0&&(R.normalized=T)}v(x)},h,p,na,y)})})}}class gF{constructor(){this.name=Fn.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class vF{constructor(){this.name=Fn.KHR_MESH_QUANTIZATION}}class oC extends Pu{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,o=e*i*3+i;for(let l=0;l!==i;l++)t[l]=n[o+l];return t}interpolate_(e,t,n,i){const o=this.resultBuffer,l=this.sampleValues,h=this.valueSize,d=h*2,p=h*3,_=i-t,v=(n-t)/_,y=v*v,x=y*v,b=e*p,R=b-p,T=-2*x+3*y,M=x-y,w=1-T,D=M-y+v;for(let N=0;N!==h;N++){const F=l[R+N+h],O=l[R+N+d]*_,z=l[b+N+h],V=l[b+N]*_;o[N]=w*F+D*O+T*z+M*V}return o}}const _F=new Ta;class yF extends oC{interpolate_(e,t,n,i){const o=super.interpolate_(e,t,n,i);return _F.fromArray(o).normalize().toArray(o),o}}const Mr={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},kh={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},lC={9728:Ti,9729:wn,9984:tp,9985:yu,9986:lc,9987:Is},cC={33071:Ei,33648:_u,10497:Kr},LS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},OS={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Bc={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},xF={CUBICSPLINE:void 0,LINEAR:uc,STEP:Au},IS={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function AF(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new Fu({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Yr})),s.DefaultMaterial}function nf(s,e,t){for(const n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Uo(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function SF(s,e,t){let n=!1,i=!1,o=!1;for(let p=0,_=e.length;p<_;p++){const v=e[p];if(v.POSITION!==void 0&&(n=!0),v.NORMAL!==void 0&&(i=!0),v.COLOR_0!==void 0&&(o=!0),n&&i&&o)break}if(!n&&!i&&!o)return Promise.resolve(s);const l=[],h=[],d=[];for(let p=0,_=e.length;p<_;p++){const v=e[p];if(n){const y=v.POSITION!==void 0?t.getDependency("accessor",v.POSITION):s.attributes.position;l.push(y)}if(i){const y=v.NORMAL!==void 0?t.getDependency("accessor",v.NORMAL):s.attributes.normal;h.push(y)}if(o){const y=v.COLOR_0!==void 0?t.getDependency("accessor",v.COLOR_0):s.attributes.color;d.push(y)}}return Promise.all([Promise.all(l),Promise.all(h),Promise.all(d)]).then(function(p){const _=p[0],v=p[1],y=p[2];return n&&(s.morphAttributes.position=_),i&&(s.morphAttributes.normal=v),o&&(s.morphAttributes.color=y),s.morphTargetsRelative=!0,s})}function MF(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,i=t.length;n<i;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function bF(s){let e;const t=s.extensions&&s.extensions[Fn.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+FS(t.attributes):e=s.indices+":"+FS(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,i=s.targets.length;n<i;n++)e+=":"+FS(s.targets[n]);return e}function FS(s){let e="";const t=Object.keys(s).sort();for(let n=0,i=t.length;n<i;n++)e+=t[n]+":"+s[t[n]]+";";return e}function HS(s){switch(s){case Int8Array:return .007874015748031496;case Uint8Array:return .00392156862745098;case Int16Array:return 3051850947599719e-20;case Uint16Array:return 15259021896696422e-21;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function EF(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const TF=new tn;class CF{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new WI,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,o=!1,l=-1;if(typeof navigator<"u"){const h=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(h)===!0;const d=h.match(/Version\/(\d+)/);i=n&&d?parseInt(d[1],10):-1,o=h.indexOf("Firefox")>-1,l=o?h.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||o&&l<98?this.textureLoader=new uA(this.options.manager):this.textureLoader=new mA(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new da(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,i=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(l){return l._markDefs&&l._markDefs()}),Promise.all(this._invokeAll(function(l){return l.beforeRoot&&l.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(l){const h={scene:l[0][i.scene||0],scenes:l[0],animations:l[1],cameras:l[2],asset:i.asset,parser:n,userData:{}};return nf(o,h,i),Uo(h,i),Promise.all(n._invokeAll(function(d){return d.afterRoot&&d.afterRoot(h)})).then(function(){for(const d of h.scenes)d.updateMatrixWorld();e(h)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,o=t.length;i<o;i++){const l=t[i].joints;for(let h=0,d=l.length;h<d;h++)e[l[h]].isBone=!0}for(let i=0,o=e.length;i<o;i++){const l=e[i];l.mesh!==void 0&&(this._addNodeRef(this.meshCache,l.mesh),l.skin!==void 0&&(n[l.mesh].isSkinnedMesh=!0)),l.camera!==void 0&&this._addNodeRef(this.cameraCache,l.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const i=n.clone(),o=(l,h)=>{const d=this.associations.get(l);d!=null&&this.associations.set(h,d);for(const[p,_]of l.children.entries())o(_,h.children[p])};return o(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const i=e(t[n]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let i=0;i<t.length;i++){const o=e(t[i]);o&&n.push(o)}return n}getDependency(e,t){const n=e+":"+t;let i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":i=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(o,l){return n.getDependency(e,l)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Fn.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(o,l){n.load(ir.resolveURL(t.uri,i.path),o,void 0,function(){l(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const i=t.byteLength||0,o=t.byteOffset||0;return n.slice(o,o+i)})}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const l=LS[i.type],h=kh[i.componentType],d=i.normalized===!0,p=new h(i.count*l);return Promise.resolve(new zn(p,l,d))}const o=[];return i.bufferView!==void 0?o.push(this.getDependency("bufferView",i.bufferView)):o.push(null),i.sparse!==void 0&&(o.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(o).then(function(l){const h=l[0],d=LS[i.type],p=kh[i.componentType],_=p.BYTES_PER_ELEMENT,v=_*d,y=i.byteOffset||0,x=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,b=i.normalized===!0;let R,T;if(x&&x!==v){const M=Math.floor(y/x),w="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+M+":"+i.count;let D=t.cache.get(w);D||(R=new p(h,M*x,i.count*x/_),D=new yh(R,x/_),t.cache.add(w,D)),T=new Al(D,d,y%x/_,b)}else h===null?R=new p(i.count*d):R=new p(h,y,i.count*d),T=new zn(R,d,b);if(i.sparse!==void 0){const M=LS.SCALAR,w=kh[i.sparse.indices.componentType],D=i.sparse.indices.byteOffset||0,N=i.sparse.values.byteOffset||0,F=new w(l[1],D,i.sparse.count*M),O=new p(l[2],N,i.sparse.count*d);h!==null&&(T=new zn(T.array.slice(),T.itemSize,T.normalized)),T.normalized=!1;for(let z=0,V=F.length;z<V;z++){const U=F[z];if(T.setX(U,O[z*d]),d>=2&&T.setY(U,O[z*d+1]),d>=3&&T.setZ(U,O[z*d+2]),d>=4&&T.setW(U,O[z*d+3]),d>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}T.normalized=b}return T})}loadTexture(e){const t=this.json,n=this.options,o=t.textures[e].source,l=t.images[o];let h=this.textureLoader;if(l.uri){const d=n.manager.getHandler(l.uri);d!==null&&(h=d)}return this.loadTextureImage(e,o,h)}loadTextureImage(e,t,n){const i=this,o=this.json,l=o.textures[e],h=o.images[t],d=(h.uri||h.bufferView)+":"+l.sampler;if(this.textureCache[d])return this.textureCache[d];const p=this.loadImageSource(t,n).then(function(_){_.flipY=!1,_.name=l.name||h.name||"",_.name===""&&typeof h.uri=="string"&&h.uri.startsWith("data:image/")===!1&&(_.name=h.uri);const y=(o.samplers||{})[l.sampler]||{};return _.magFilter=lC[y.magFilter]||wn,_.minFilter=lC[y.minFilter]||Is,_.wrapS=cC[y.wrapS]||Kr,_.wrapT=cC[y.wrapT]||Kr,_.generateMipmaps=!_.isCompressedTexture&&_.minFilter!==Ti&&_.minFilter!==wn,i.associations.set(_,{textures:e}),_}).catch(function(){return null});return this.textureCache[d]=p,p}loadImageSource(e,t){const n=this,i=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(v=>v.clone());const l=i.images[e],h=self.URL||self.webkitURL;let d=l.uri||"",p=!1;if(l.bufferView!==void 0)d=n.getDependency("bufferView",l.bufferView).then(function(v){p=!0;const y=new Blob([v],{type:l.mimeType});return d=h.createObjectURL(y),d});else if(l.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const _=Promise.resolve(d).then(function(v){return new Promise(function(y,x){let b=y;t.isImageBitmapLoader===!0&&(b=function(R){const T=new $n(R);T.needsUpdate=!0,y(T)}),t.load(ir.resolveURL(v,o.path),b,void 0,x)})}).then(function(v){return p===!0&&h.revokeObjectURL(d),Uo(v,l),v.userData.mimeType=l.mimeType||EF(l.uri),v}).catch(function(v){throw console.error("THREE.GLTFLoader: Couldn't load texture",d),v});return this.sourceCache[e]=_,_}assignTexture(e,t,n,i){const o=this;return this.getDependency("texture",n.index).then(function(l){if(!l)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(l=l.clone(),l.channel=n.texCoord),o.extensions[Fn.KHR_TEXTURE_TRANSFORM]){const h=n.extensions!==void 0?n.extensions[Fn.KHR_TEXTURE_TRANSFORM]:void 0;if(h){const d=o.associations.get(l);l=o.extensions[Fn.KHR_TEXTURE_TRANSFORM].extendTexture(l,h),o.associations.set(l,d)}}return i!==void 0&&(l.colorSpace=i),e[t]=l,l})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,l=t.attributes.normal===void 0;if(e.isPoints){const h="PointsMaterial:"+n.uuid;let d=this.cache.get(h);d||(d=new Np,Yi.prototype.copy.call(d,n),d.color.copy(n.color),d.map=n.map,d.sizeAttenuation=!1,this.cache.add(h,d)),n=d}else if(e.isLine){const h="LineBasicMaterial:"+n.uuid;let d=this.cache.get(h);d||(d=new za,Yi.prototype.copy.call(d,n),d.color.copy(n.color),d.map=n.map,this.cache.add(h,d)),n=d}if(i||o||l){let h="ClonedMaterial:"+n.uuid+":";i&&(h+="derivative-tangents:"),o&&(h+="vertex-colors:"),l&&(h+="flat-shading:");let d=this.cache.get(h);d||(d=n.clone(),o&&(d.vertexColors=!0),l&&(d.flatShading=!0),i&&(d.normalScale&&(d.normalScale.y*=-1),d.clearcoatNormalScale&&(d.clearcoatNormalScale.y*=-1)),this.cache.add(h,d),this.associations.set(d,this.associations.get(n))),n=d}e.material=n}getMaterialType(){return Fu}loadMaterial(e){const t=this,n=this.json,i=this.extensions,o=n.materials[e];let l;const h={},d=o.extensions||{},p=[];if(d[Fn.KHR_MATERIALS_UNLIT]){const v=i[Fn.KHR_MATERIALS_UNLIT];l=v.getMaterialType(),p.push(v.extendParams(h,o,t))}else{const v=o.pbrMetallicRoughness||{};if(h.color=new Ct(1,1,1),h.opacity=1,Array.isArray(v.baseColorFactor)){const y=v.baseColorFactor;h.color.setRGB(y[0],y[1],y[2],na),h.opacity=y[3]}v.baseColorTexture!==void 0&&p.push(t.assignTexture(h,"map",v.baseColorTexture,Xi)),h.metalness=v.metallicFactor!==void 0?v.metallicFactor:1,h.roughness=v.roughnessFactor!==void 0?v.roughnessFactor:1,v.metallicRoughnessTexture!==void 0&&(p.push(t.assignTexture(h,"metalnessMap",v.metallicRoughnessTexture)),p.push(t.assignTexture(h,"roughnessMap",v.metallicRoughnessTexture))),l=this._invokeOne(function(y){return y.getMaterialType&&y.getMaterialType(e)}),p.push(Promise.all(this._invokeAll(function(y){return y.extendMaterialParams&&y.extendMaterialParams(e,h)})))}o.doubleSided===!0&&(h.side=js);const _=o.alphaMode||IS.OPAQUE;if(_===IS.BLEND?(h.transparent=!0,h.depthWrite=!1):(h.transparent=!1,_===IS.MASK&&(h.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&l!==ha&&(p.push(t.assignTexture(h,"normalMap",o.normalTexture)),h.normalScale=new tt(1,1),o.normalTexture.scale!==void 0)){const v=o.normalTexture.scale;h.normalScale.set(v,v)}if(o.occlusionTexture!==void 0&&l!==ha&&(p.push(t.assignTexture(h,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(h.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&l!==ha){const v=o.emissiveFactor;h.emissive=new Ct().setRGB(v[0],v[1],v[2],na)}return o.emissiveTexture!==void 0&&l!==ha&&p.push(t.assignTexture(h,"emissiveMap",o.emissiveTexture,Xi)),Promise.all(p).then(function(){const v=new l(h);return o.name&&(v.name=o.name),Uo(v,o),t.associations.set(v,{materials:e}),o.extensions&&nf(i,v,o),v})}createUniqueName(e){const t=Yn.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function o(h){return n[Fn.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(h,t).then(function(d){return uC(d,h,t)})}const l=[];for(let h=0,d=e.length;h<d;h++){const p=e[h],_=bF(p),v=i[_];if(v)l.push(v.promise);else{let y;p.extensions&&p.extensions[Fn.KHR_DRACO_MESH_COMPRESSION]?y=o(p):y=uC(new pn,p,t),i[_]={primitive:p,promise:y},l.push(y)}}return Promise.all(l)}loadMesh(e){const t=this,n=this.json,i=this.extensions,o=n.meshes[e],l=o.primitives,h=[];for(let d=0,p=l.length;d<p;d++){const _=l[d].material===void 0?AF(this.cache):this.getDependency("material",l[d].material);h.push(_)}return h.push(t.loadGeometries(l)),Promise.all(h).then(function(d){const p=d.slice(0,d.length-1),_=d[d.length-1],v=[];for(let x=0,b=_.length;x<b;x++){const R=_[x],T=l[x];let M;const w=p[x];if(T.mode===Mr.TRIANGLES||T.mode===Mr.TRIANGLE_STRIP||T.mode===Mr.TRIANGLE_FAN||T.mode===void 0)M=o.isSkinnedMesh===!0?new ev(R,w):new Ai(R,w),M.isSkinnedMesh===!0&&M.normalizeSkinWeights(),T.mode===Mr.TRIANGLE_STRIP?M.geometry=aC(M.geometry,fp):T.mode===Mr.TRIANGLE_FAN&&(M.geometry=aC(M.geometry,bu));else if(T.mode===Mr.LINES)M=new yr(R,w);else if(T.mode===Mr.LINE_STRIP)M=new wo(R,w);else if(T.mode===Mr.LINE_LOOP)M=new fv(R,w);else if(T.mode===Mr.POINTS)M=new pv(R,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+T.mode);Object.keys(M.geometry.morphAttributes).length>0&&MF(M,o),M.name=t.createUniqueName(o.name||"mesh_"+e),Uo(M,o),T.extensions&&nf(i,M,T),t.assignFinalMaterial(M),v.push(M)}for(let x=0,b=v.length;x<b;x++)t.associations.set(v[x],{meshes:e,primitives:x});if(v.length===1)return o.extensions&&nf(i,v[0],o),v[0];const y=new vr;o.extensions&&nf(i,y,o),t.associations.set(y,{meshes:e});for(let x=0,b=v.length;x<b;x++)y.add(v[x]);return y})}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new aa(E0.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(t=new Tl(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Uo(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let i=0,o=t.joints.length;i<o;i++)n.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){const o=i.pop(),l=i,h=[],d=[];for(let p=0,_=l.length;p<_;p++){const v=l[p];if(v){h.push(v);const y=new tn;o!==null&&y.fromArray(o.array,p*16),d.push(y)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[p])}return new bh(h,d)})}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],o=i.name?i.name:"animation_"+e,l=[],h=[],d=[],p=[],_=[];for(let v=0,y=i.channels.length;v<y;v++){const x=i.channels[v],b=i.samplers[x.sampler],R=x.target,T=R.node,M=i.parameters!==void 0?i.parameters[b.input]:b.input,w=i.parameters!==void 0?i.parameters[b.output]:b.output;R.node!==void 0&&(l.push(this.getDependency("node",T)),h.push(this.getDependency("accessor",M)),d.push(this.getDependency("accessor",w)),p.push(b),_.push(R))}return Promise.all([Promise.all(l),Promise.all(h),Promise.all(d),Promise.all(p),Promise.all(_)]).then(function(v){const y=v[0],x=v[1],b=v[2],R=v[3],T=v[4],M=[];for(let D=0,N=y.length;D<N;D++){const F=y[D],O=x[D],z=b[D],V=R[D],U=T[D];if(F===void 0)continue;F.updateMatrix&&F.updateMatrix();const I=n._createAnimationTracks(F,O,z,V,U);if(I)for(let W=0;W<I.length;W++)M.push(I[W])}const w=new Vu(o,void 0,M);return Uo(w,i),w})}createNodeMesh(e){const t=this.json,n=this,i=t.nodes[e];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(o){const l=n._getNodeRef(n.meshCache,i.mesh,o);return i.weights!==void 0&&l.traverse(function(h){if(h.isMesh)for(let d=0,p=i.weights.length;d<p;d++)h.morphTargetInfluences[d]=i.weights[d]}),l})}loadNode(e){const t=this.json,n=this,i=t.nodes[e],o=n._loadNodeShallow(e),l=[],h=i.children||[];for(let p=0,_=h.length;p<_;p++)l.push(n.getDependency("node",h[p]));const d=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([o,Promise.all(l),d]).then(function(p){const _=p[0],v=p[1],y=p[2];y!==null&&_.traverse(function(x){x.isSkinnedMesh&&x.bind(y,TF)});for(let x=0,b=v.length;x<b;x++)_.add(v[x]);return _})}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const o=t.nodes[e],l=o.name?i.createUniqueName(o.name):"",h=[],d=i._invokeOne(function(p){return p.createNodeMesh&&p.createNodeMesh(e)});return d&&h.push(d),o.camera!==void 0&&h.push(i.getDependency("camera",o.camera).then(function(p){return i._getNodeRef(i.cameraCache,o.camera,p)})),i._invokeAll(function(p){return p.createNodeAttachment&&p.createNodeAttachment(e)}).forEach(function(p){h.push(p)}),this.nodeCache[e]=Promise.all(h).then(function(p){let _;if(o.isBone===!0?_=new Cp:p.length>1?_=new vr:p.length===1?_=p[0]:_=new On,_!==p[0])for(let v=0,y=p.length;v<y;v++)_.add(p[v]);if(o.name&&(_.userData.name=o.name,_.name=l),Uo(_,o),o.extensions&&nf(n,_,o),o.matrix!==void 0){const v=new tn;v.fromArray(o.matrix),_.applyMatrix4(v)}else o.translation!==void 0&&_.position.fromArray(o.translation),o.rotation!==void 0&&_.quaternion.fromArray(o.rotation),o.scale!==void 0&&_.scale.fromArray(o.scale);if(!i.associations.has(_))i.associations.set(_,{});else if(o.mesh!==void 0&&i.meshCache.refs[o.mesh]>1){const v=i.associations.get(_);i.associations.set(_,{...v})}return i.associations.get(_).nodes=e,_}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,o=new vr;n.name&&(o.name=i.createUniqueName(n.name)),Uo(o,n),n.extensions&&nf(t,o,n);const l=n.nodes||[],h=[];for(let d=0,p=l.length;d<p;d++)h.push(i.getDependency("node",l[d]));return Promise.all(h).then(function(d){for(let _=0,v=d.length;_<v;_++)o.add(d[_]);const p=_=>{const v=new Map;for(const[y,x]of i.associations)(y instanceof Yi||y instanceof $n)&&v.set(y,x);return _.traverse(y=>{const x=i.associations.get(y);x!=null&&v.set(y,x)}),v};return i.associations=p(o),o})}_createAnimationTracks(e,t,n,i,o){const l=[],h=e.name?e.name:e.uuid,d=[];Bc[o.path]===Bc.weights?e.traverse(function(y){y.morphTargetInfluences&&d.push(y.name?y.name:y.uuid)}):d.push(h);let p;switch(Bc[o.path]){case Bc.weights:p=Sl;break;case Bc.rotation:p=Ml;break;case Bc.translation:case Bc.scale:p=bl;break;default:n.itemSize===1?p=Sl:p=bl;break}const _=i.interpolation!==void 0?xF[i.interpolation]:uc,v=this._getArrayFromAccessor(n);for(let y=0,x=d.length;y<x;y++){const b=new p(d[y]+"."+Bc[o.path],t.array,v,_);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),l.push(b)}return l}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=HS(t.constructor),i=new Float32Array(t.length);for(let o=0,l=t.length;o<l;o++)i[o]=t[o]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const i=this instanceof Ml?yF:oC;return new i(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function RF(s,e,t){const n=e.attributes,i=new Ca;if(n.POSITION!==void 0){const h=t.json.accessors[n.POSITION],d=h.min,p=h.max;if(d!==void 0&&p!==void 0){if(i.set(new Z(d[0],d[1],d[2]),new Z(p[0],p[1],p[2])),h.normalized){const _=HS(kh[h.componentType]);i.min.multiplyScalar(_),i.max.multiplyScalar(_)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const o=e.targets;if(o!==void 0){const h=new Z,d=new Z;for(let p=0,_=o.length;p<_;p++){const v=o[p];if(v.POSITION!==void 0){const y=t.json.accessors[v.POSITION],x=y.min,b=y.max;if(x!==void 0&&b!==void 0){if(d.setX(Math.max(Math.abs(x[0]),Math.abs(b[0]))),d.setY(Math.max(Math.abs(x[1]),Math.abs(b[1]))),d.setZ(Math.max(Math.abs(x[2]),Math.abs(b[2]))),y.normalized){const R=HS(kh[y.componentType]);d.multiplyScalar(R)}h.max(d)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(h)}s.boundingBox=i;const l=new fa;i.getCenter(l.center),l.radius=i.min.distanceTo(i.max)/2,s.boundingSphere=l}function uC(s,e,t){const n=e.attributes,i=[];function o(l,h){return t.getDependency("accessor",l).then(function(d){s.setAttribute(h,d)})}for(const l in n){const h=OS[l]||l.toLowerCase();h in s.attributes||i.push(o(n[l],h))}if(e.indices!==void 0&&!s.index){const l=t.getDependency("accessor",e.indices).then(function(h){s.setIndex(h)});i.push(l)}return Nn.workingColorSpace!==na&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Nn.workingColorSpace}" not supported.`),Uo(s,e),RF(s,e,t),Promise.all(i).then(function(){return e.targets!==void 0?SF(s,e.targets,t):s})}const PS="https://ai.streamoji.com",ga=(...s)=>{},wF=(...s)=>{},fC=({analyser:s})=>{const e=Me.useRef(null),t=Me.useRef(null);return Me.useEffect(()=>{const n=e.current;if(!n)return;const i=n.getContext("2d",{alpha:!0});if(!i)return;let o,l=null;s&&(s.fftSize=128,l=new Uint8Array(s.frequencyBinCount));const h=()=>{o=requestAnimationFrame(h),(n.width!==n.offsetWidth||n.height!==n.offsetHeight)&&(n.width=n.offsetWidth,n.height=n.offsetHeight);const d=n.width,p=n.height;if(d===0||p===0)return;const _=p/2;i.clearRect(0,0,d,p),i.fillStyle="#1e293b";const v=2,x=v+2,b=d*.95,R=Math.floor(b/x);(!t.current||t.current.length!==R)&&(t.current=new Float32Array(R).fill(2));const T=R*x,M=(d-T)/2;s&&l&&s.getByteFrequencyData(l);const w=l?l.length:0,N=Math.floor(w*.7)/R,F=new Float32Array(R);for(let O=0;O<R;O++){let z=0;if(l&&N>0){const I=Math.floor(O*N),W=Math.floor((O+1)*N);for(let ne=I;ne<W;ne++){const $=l[ne]||0;$>z&&(z=$)}}z<10&&(z=0);const V=z/255,U=z>0?Math.max(2,Math.pow(V,1.4)*p*.25):2;F[O]=U}for(let O=0;O<R;O++){const z=R-1-O,V=Math.max(F[O],F[z]),U=t.current[O]+(V-t.current[O])*.3;t.current[O]=U;const I=M+O*x,W=_-U/2;i.beginPath(),i.roundRect?i.roundRect(I,W,v,U,4):i.fillRect(I,W,v,U),i.fill()}};return h(),()=>{cancelAnimationFrame(o)}},[s]),Vt.jsx("canvas",{ref:e,style:{width:"100%",height:"100%",display:"block"}})},BF="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev",hC="https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/default-models/fullbodyavatarmale.glb";async function DF(s){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s));return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}function NF(s){const[e,t]=Me.useState(null);return Me.useEffect(()=>{if(!s){t(null);return}let n=!1;return DF(s).then(i=>{if(n)return;const o=`${BF}/${i}.glb`;fetch(o,{method:"HEAD"}).then(l=>{n||t(l.ok?o:hC)}).catch(()=>{n||t(hC)})}),()=>{n=!0}},[s]),e}const UF=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_005.glb"],LF=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb"],OF=[{id:"m_expr_01",name:"Friendly Wave",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_001.glb"},{id:"m_expr_02",name:"You There",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_002.glb"},{id:"m_expr_04",name:"Awkward Agreement",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_004.glb"},{id:"m_expr_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_005.glb"},{id:"m_expr_06",name:"Tired Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_006.glb"},{id:"m_expr_07",name:"Conceilied Laughter",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_007.glb"},{id:"m_expr_08",name:"You Come Here",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_008.glb"},{id:"m_expr_09",name:"Come Here Kid",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_009.glb"},{id:"m_expr_10",name:"Come Here Everyone",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_010.glb"},{id:"m_expr_11",name:"No Freaking Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_011.glb"},{id:"m_expr_12",name:"Cheerful Approval",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_012.glb"},{id:"m_expr_13",name:"Waving Hello",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_013.glb"},{id:"m_expr_14",name:"Checking Surroundings",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_014.glb"},{id:"m_expr_15",name:"Referee Warning",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_015.glb"},{id:"m_expr_16",name:"You Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_016.glb"},{id:"m_expr_17",name:"Side Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_017.glb"},{id:"m_expr_18",name:"You're Finished",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_018.glb"},{id:"m_talk_01",name:"Oh God, Why Me?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_001.glb"},{id:"m_talk_02",name:"What Are You Doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_002.glb"},{id:"m_talk_03",name:"What Am I doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_003.glb"},{id:"m_talk_04",name:"No Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_004.glb"},{id:"m_talk_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb"},{id:"m_talk_06",name:"I have no idea",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"},{id:"m_talk_07",name:"What's going on here?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"},{id:"m_talk_08",name:"Let's stop",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_008.glb"},{id:"m_talk_09",name:"Fed Up Moment",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_009.glb"},{id:"m_talk_10",name:"What's This? Hold On",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_010.glb"},{id:"f_talk_01",name:"Great Job Clap",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_001.glb"},{id:"f_talk_02",name:"Chill Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"},{id:"f_talk_03",name:"This Is Me",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_003.glb"},{id:"f_talk_04",name:"Empathize",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb"},{id:"f_talk_05",name:"Loose Hands Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb"},{id:"f_talk_06",name:"Take It Easy",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb"}],IF=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"],FF={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},HF=[-.45,1.9,.1],PF={browInnerUp:.2},GS=.18,GF=1,dC="__branding__",m_={neutral:{eyeLookDownLeft:.1,eyeLookDownRight:.1},happy:{mouthSmileLeft:.2,mouthSmileRight:.2,eyeLookDownLeft:.1,eyeLookDownRight:.1},sad:{eyeLookDownLeft:.2,eyeLookDownRight:.2,browDownRight:.1,browInnerUp:.6,browOuterUpRight:.2,eyeSquintLeft:.7,eyeSquintRight:.7,mouthFrownLeft:.8,mouthFrownRight:.8,mouthLeft:.2,mouthPucker:.5,mouthRollLower:.2,mouthRollUpper:.2,mouthShrugLower:.2,mouthShrugUpper:.2,mouthStretchLeft:.4},angry:{eyeLookDownLeft:.1,eyeLookDownRight:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3},fear:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},disgust:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},love:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmileLeft:.2,mouthSmileRight:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1}},zF=[{key:"viseme_aa",mix:{jawOpen:.6}},{key:"viseme_E",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3}},{key:"viseme_I",mix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2}},{key:"viseme_O",mix:{mouthPucker:1,jawForward:.6,jawOpen:.2}},{key:"viseme_U",mix:{mouthFunnel:1}},{key:"viseme_PP",mix:{mouthRollLower:.3,mouthRollUpper:.3,mouthUpperUpLeft:.3,mouthUpperUpRight:.3}},{key:"viseme_FF",mix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:.3}},{key:"viseme_DD",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2}},{key:"viseme_SS",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1}},{key:"viseme_TH",mix:{mouthRollUpper:.3,jawOpen:.2,tongueOut:.4}},{key:"viseme_CH",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_RR",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_kk",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15}},{key:"viseme_nn",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15,tongueOut:.2}},{key:"viseme_sil",mix:{}}],VF={aei:[{v:"E",w:.8},{v:"I",w:.2}],ee:[{v:"I",w:1}],oo:[{v:"O",w:1}],u:[{v:"U",w:1}],aa:[{v:"aa",w:1}],ah:[{v:"aa",w:.7},{v:"O",w:.3}],bmp:[{v:"PP",w:1}],fv:[{v:"FF",w:1}],th:[{v:"TH",w:1}],l:[{v:"nn",w:1}],r:[{v:"RR",w:1}],qw:[{v:"U",w:.6},{v:"O",w:.4}],chjsh:[{v:"CH",w:1}],cdgknstxyz:[{v:"DD",w:.6},{v:"SS",w:.4}],sil:[{v:"sil",w:1}]};function kF(s){if(!s)return[{v:"sil",w:1}];const e=s.toLowerCase();return VF[e]??[{v:"sil",w:1}]}function XF({target:s}){const{camera:e}=Ih();return Me.useEffect(()=>{e.lookAt(...s)},[e,s]),null}function Gs(s,e,t){if(!s||!s.morphTargetDictionary)return;const n=s,i=n.morphTargetDictionary,o=n.morphTargetInfluences;if(o)for(const l in i)l.toLowerCase()===e.toLowerCase()&&(o[i[l]]=t)}function pC(s,e=.97){if(!s)return;const t=s;if(t.morphTargetInfluences)for(let n=0;n<t.morphTargetInfluences.length;n++)t.morphTargetInfluences[n]*=e}const YF=Me.memo(({avatarUrl:s,isPlayingRef:e,visemeQueueRef:t,audioContextRef:n,responseAudioStartTimeRef:i,adjustments:o,mood:l,expression:h,agentResponse:d,isSpeaking:p,nextStartTimeRef:_,stopPlayback:v,setIsSpeaking:y,expressionUrl:x,onExpressionFinished:b,isNudgeResponse:R,avatarGender:T})=>{const{scene:M}=zh(s),D=zh(T==="female"?LF:UF),N=Me.useMemo(()=>D.flatMap(X=>X.animations),[D]),F=zh(IF),O=Me.useMemo(()=>F.flatMap(X=>X.animations),[F]),z=Me.useRef(null),V=Me.useRef(null),U=Me.useRef(null),I=Me.useRef([]),[W]=Me.useState(()=>new iE(M)),ne=Me.useRef({}),$=Me.useRef(null),ae=Me.useRef(0),ge=Me.useRef(!1),H=Me.useRef(0),K=Me.useRef(null);Me.useEffect(()=>{if(!(!N||!M)){if(N.forEach((X,ee)=>{const le=`idle_${ee}`;if(!ne.current[le]){const ve=W.clipAction(X,M);ve.name=le,ve.setLoop(cp,1),ve.clampWhenFinished=!0,ne.current[le]=ve}}),O.forEach((X,ee)=>{const le=`talk_${ee}`;if(!ne.current[le]){const ve=W.clipAction(X,M);ve.name=le,ve.setLoop(cp,1),ve.clampWhenFinished=!0,ne.current[le]=ve}}),N.length>0){const X=ne.current.idle_0,ee=$.current&&W.existingAction($.current.getClip());X&&!ee&&(X.reset().fadeIn(.5).play(),$.current=X)}return()=>{W.stopAllAction(),ne.current={},$.current=null}}},[N,O,M,W]);const te=Me.useRef("");Me.useEffect(()=>{if(!x||!M||x===te.current)return;te.current=x,K.current=x,new KI().load(x,ee=>{if(ee.animations&&ee.animations.length>0){const le=ee.animations[0],ve=W.clipAction(le,M);if(ve.name=`EXPR_${x}`,ve.setLoop(cp,1),ve.clampWhenFinished=!0,ne.current[`EXPR_${x}`]=ve,p&&K.current===x){const Pe=$.current;ve.reset().fadeIn(.3).play(),Pe&&Pe!==ve&&Pe.crossFadeTo(ve,.3,!0),$.current=ve,K.current=null}}},void 0,ee=>{console.error(`[ANIMATION] Failed to load ${x}`,ee)})},[x,M,W,p]),Me.useEffect(()=>{const X=ee=>{const le=ee.action,ve=le.name||"";if(ve.startsWith("idle_")){const de=(parseInt(ve.split("_")[1])+1)%N.length,Ee=ne.current[`idle_${de}`];Ee&&(Ee.reset().fadeIn(.5).play(),le.crossFadeTo(Ee,.5,!0),$.current=Ee)}else if(ve.startsWith("EXPR_")){if(p){const Pe=ne.current.talk_0;Pe&&(Pe.reset().fadeIn(.5).play(),le.crossFadeTo(Pe,.5,!0),$.current=Pe)}else{const Pe=ne.current.idle_0;Pe&&(Pe.reset().fadeIn(.5).play(),le.crossFadeTo(Pe,.5,!0),$.current=Pe)}b&&b()}else if(ve.startsWith("talk_"))if(p&&!R){const de=(parseInt(ve.split("_")[1])+1)%O.length,Ee=ne.current[`talk_${de}`];Ee&&(Ee.reset().fadeIn(.3).play(),le.crossFadeTo(Ee,.3,!0),$.current=Ee)}else{const Pe=ne.current.idle_0;Pe&&(Pe.reset().fadeIn(.5).play(),le.crossFadeTo(Pe,.5,!0),$.current=Pe)}};return W.addEventListener("finished",X),()=>W.removeEventListener("finished",X)},[W,N,O,p,R,b]),Me.useEffect(()=>{if(p&&M){const X=$.current,ee=X?.name||"";if(ee.startsWith("idle_")||ee.startsWith("talk_")||ee===""){const le=K.current;if(le){const ve=ne.current[`EXPR_${le}`];if(ve){ve.reset().fadeIn(.3).play(),X&&X!==ve&&X.crossFadeTo(ve,.3,!0),$.current=ve,K.current=null;return}}if(ee.startsWith("idle_")||ee===""){const ve=ne.current.talk_0;ve&&(ve.reset().fadeIn(.5).play(),X&&X.crossFadeTo(ve,.5,!0),$.current=ve)}}}else if(!p&&M){const X=$.current,ee=X?.name||"";if(ee.startsWith("talk_")||ee.startsWith("EXPR_")){const le=ne.current.idle_0;le&&(le.reset().fadeIn(.5).play(),X&&X.crossFadeTo(le,.5,!0),$.current=le)}}},[p,M,x]),Me.useEffect(()=>{if(!M)return;M.traverse(le=>{if(le.isMesh&&le.morphTargetDictionary){const ve=le.name.toLowerCase();(ve.includes("head")||ve.includes("avatar"))&&(V.current=le,ga(`[ANIMATION] Found head mesh: ${le.name}`)),ve.includes("teeth")&&(U.current=le,ga(`[ANIMATION] Found teeth mesh: ${le.name}`))}});const X=V.current?.morphTargetDictionary;X&&Object.keys(X).filter(le=>le.toLowerCase().includes("brow"));const ee=[];M.traverse(le=>{if(le.isMesh){const Pe=le.morphTargetDictionary;Pe&&Object.keys(Pe).some(de=>de.toLowerCase().includes("brow"))&&ee.push(le)}}),I.current=ee,ee.length>0&&ga("[ANIMATION] Meshes with brow morphs:",ee.length)},[M]);const ye=(X,ee=1)=>{const le=`viseme_${X}`.toLowerCase(),ve=zF.find(Pe=>Pe.key.toLowerCase()===le);if(ve)for(const Pe in ve.mix){const de=ve.mix[Pe]*ee;Gs(V.current,Pe,de),Gs(U.current,Pe,de)}},xe=X=>{const ee=m_[X]??m_.neutral;for(const le in ee)Gs(V.current,le,ee[le]),Gs(U.current,le,ee[le])};return yT((X,ee)=>{const le=Math.pow(.88,60*ee);pC(V.current,le),pC(U.current,le),xe(l);const ve=X.clock.elapsedTime;let Pe=0;if(Math.floor(ve)%5===0&&Math.floor((ve-ee)%5)!==0){let Dt=null;M.traverse(It=>{It.name.toLowerCase().includes("hips")&&(Dt=It)});const pt=Dt?`Hips Y: ${Dt.position.y.toFixed(4)}`:"Hips not found";ga(`[ANIMATION] Mixer Time: ${W.time.toFixed(2)}, ${pt}`)}if(W.update(ee),ve>ae.current&&!ge.current&&(ge.current=!0,H.current=ve),ge.current){const Dt=p?.2:.3,pt=(ve-H.current)/Dt;if(pt>=1){ge.current=!1;const It=p?1:2.5;ae.current=ve+It}else{const It=pt<.5?pt*2:(1-pt)*2;Gs(V.current,"eyeBlinkLeft",It),Gs(V.current,"eyeBlinkRight",It),Gs(U.current,"eyeBlinkLeft",It),Gs(U.current,"eyeBlinkRight",It),Pe=It*PF.browInnerUp}}const de=m_[l]??m_.neutral,Ee=de.browInnerUp??0,lt=de.browOuterUpLeft??0,Bt=de.browOuterUpRight??0,Rt=ve*GF,rn=GS*Math.sin(Rt),hn=GS*.7*Math.sin(Rt+.7),Xt=GS*.7*Math.sin(Rt+1.3),ze=Dt=>Math.max(0,Math.min(1,Dt)),$e=ze(Ee+rn),Je=ze(lt+hn),vt=ze(Bt+Xt),Q=ze($e+Pe);if(Gs(V.current,"browInnerUp",Q),Gs(U.current,"browInnerUp",Q),Gs(V.current,"browOuterUpLeft",Je),Gs(U.current,"browOuterUpLeft",Je),Gs(V.current,"browOuterUpRight",vt),Gs(U.current,"browOuterUpRight",vt),z.current){const Dt=e.current?0:o.rotation[1];z.current.rotation.y=E0.lerp(z.current.rotation.y,Dt,.1),z.current.position.set(...o.position),z.current.scale.setScalar(o.scale),z.current.rotation.x=o.rotation[0],z.current.rotation.z=o.rotation[2]}if(e.current&&n.current){const Dt=n.current.currentTime,yt=(Dt-i.current)*1e3- -150;for(let j=0;j<t.current.length;j++){const P=t.current[j];yt>=P.vtime&&yt<P.vtime+P.vduration&&ye(P.viseme,P.weight??1)}Dt>_.current+.5&&(v(),y(!1))}}),Vt.jsx("group",{ref:z,children:Vt.jsx("primitive",{object:M})})});function JF(s){return s?s.charAt(0).toUpperCase()+s.slice(1).toLowerCase():""}const qF=({token:s,agentToken:e,onNavigationRequested:t,avatarGender:n,presetUserDetails:i}={})=>{const o=s??e??"",l=NF(o||void 0),[h,d]=Me.useState(""),[p,_]=Me.useState(""),[v,y]=Me.useState("Ready"),[x,b]=Me.useState(!1),[R,T]=Me.useState(!1),[M,w]=Me.useState([]),[D,N]=Me.useState(""),F=Me.useRef(null),[O,z]=Me.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 480px)").matches:!1);Me.useEffect(()=>{const _e=window.matchMedia("(max-width: 480px)"),Ge=()=>z(_e.matches);return _e.addEventListener("change",Ge),()=>_e.removeEventListener("change",Ge)},[]);const V=O?80:600,U=Me.useRef(!1),I=Me.useRef([]),W=Me.useRef(0),ne=Me.useRef(!1),$=Me.useRef([]),ae=Me.useRef(null),ge=Me.useRef([]);Me.useRef([]);const H=Me.useRef([]),K=Me.useRef(0),te=Me.useRef(0),ye=Me.useRef(0),xe=Me.useRef(0),X=Me.useRef(!1),[ee,le]=Me.useState(null),ve=Me.useRef(null),[Pe,de]=Me.useState("neutral"),[Ee,lt]=Me.useState(""),[Bt,Rt]=Me.useState(""),[rn,hn]=Me.useState("Chat with us"),[Xt,ze]=Me.useState(null),[$e,Je]=Me.useState("hidden"),[vt,Q]=Me.useState(""),Dt=Me.useRef(null),pt=Me.useRef($e);pt.current=$e;const[It,yt]=Me.useState(null),j=Me.useRef(null),P=Me.useRef(null),[ue,Ie]=Me.useState(!1),We=Me.useRef(null),[Ne,Ht]=Me.useState("hidden"),[St,zt]=Me.useState(""),qt=Me.useRef(Ne);qt.current=Ne;const Ve=Me.useRef(""),qe=Me.useRef(!1),bt=Me.useRef(""),Et=Me.useRef(Date.now()),ct=Me.useRef([]),kt=Me.useRef(!1),[pe,Be]=Me.useState(!1),[rt,Nt]=Me.useState(!1),Ze=Me.useRef(null),Xe=Me.useMemo(()=>ue?"Try again":v==="Busy"?"Busy":v==="Thinking..."||v==="Processing Voice..."?v:Xt!=null&&Xt!==""&&Xt!=="none"&&Xt!=="<none>"?`Enter ${JF(Xt)}`:Ne!=="hidden"||!rt?null:dC,[v,Xt,ue,Ne,rt]),xt=!ue&&v!=="Busy"&&v!=="Thinking..."&&v!=="Processing Voice..."&&(Xt==null||Xt===""||Xt==="none"||Xt==="<none>");Me.useEffect(()=>{if(Ne!=="hidden"||!xt){Nt(!1),Ze.current!=null&&(clearTimeout(Ze.current),Ze.current=null);return}return Ze.current=setTimeout(()=>{Ze.current=null,Nt(!0)},400),()=>{Ze.current!=null&&(clearTimeout(Ze.current),Ze.current=null)}},[Ne,xt]);const Qt=Xe!=null&&Xe!=="";Me.useEffect(()=>{const _e=pt.current;if(!(_e==="exiting"||_e==="entering")){if(_e==="hidden"){Qt&&(Q(Xe??""),Je("entering"));return}_e==="visible"&&(!Qt||Xe!==vt)&&(Dt.current=Qt?Xe:null,Je("exiting"))}},[Qt,Xe,$e,vt]),Me.useEffect(()=>{if(v!=="Busy"){P.current!=null&&(clearTimeout(P.current),P.current=null);return}return P.current=setTimeout(()=>{P.current=null,y("Ready"),Ie(!0)},12e3),()=>{P.current!=null&&(clearTimeout(P.current),P.current=null)}},[v]),Me.useEffect(()=>{if(!ue)return;const _e=setTimeout(()=>Ie(!1),2500);return()=>clearTimeout(_e)},[ue]);const Dn=Me.useCallback(()=>{const _e=pt.current;if(_e==="exiting"){Je("hidden");const Ge=Dt.current;Dt.current=null,Ge!=null&&Ge!==""&&(Q(Ge),Je("entering"))}else _e==="entering"&&Je("visible")},[]),En=_e=>{if(!_e)return;if(_e.mood!=null){const ot=String(_e.mood).toLowerCase();de(ot)}if(_e.expression!=null){const ot=String(_e.expression).trim();lt(ot);const Ut=OF.find(Ot=>Ot.name.toLowerCase()===ot.toLowerCase());ga(`[STREAM] Animation match for "${ot}": ${Ut?Ut.name:"NONE"}`),Rt(Ut?.url??"")}if(_e.navigation!=null){const ot=String(_e.navigation).trim();ot!==""&&(t?t(ot):window.open(ot,"_blank"))}const Ge=_e.ask_for||_e.lead_capture?.ask_for,Le=Ge?String(Ge).trim().toLowerCase():"",Ye=Le==="none"||Le==="<none>";if(Ge&&!Ye){const ot=Le;if(i&&(ot==="email"&&i.email||ot==="name"&&i.name||ot==="phone"&&i.phone))return;ze(ot||null),hn(ot==="email"?"Enter your email":ot==="name"?"Enter your name":ot==="phone"?"Enter your phone number":"Chat with us")}else(Ye||_e.ask_for===null||_e.lead_capture&&_e.lead_capture.ask_for===null||_e.ask_for==="none")&&(ze(null),rn!=="Chat with us"&&hn("Chat with us"));_e.collected,_e.valid},Ii=_e=>{const Ge=_e.trim();if(!Ge)return null;if(Ge.startsWith("{"))try{return JSON.parse(Ge)}catch{return null}if(Ge.includes(":")){const Le=Ge.split(":"),Ye=Le[0].trim().toLowerCase(),ot=Le.slice(1).join(":").trim();return{[Ye]:ot}}return null},Ba=Me.useCallback(()=>{},[]),br=_e=>{if(qe.current)_e==="§"?qe.current=!1:(bt.current+=_e,_(Ge=>Ge+_e));else if(_e==="§"){qe.current=!0;return}else for(Ve.current+=_e;Ve.current.includes(`
4149
+ `;class HI extends gs{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;constructor({gamma:e,offsetHdr:t,offsetSdr:n,gainMapMin:i,gainMapMax:o,maxDisplayBoost:l,hdrCapacityMin:h,hdrCapacityMax:d,sdr:p,gainMap:_}){super({name:"GainMapDecoderMaterial",vertexShader:II,fragmentShader:FI,uniforms:{sdr:{value:p},gainMap:{value:_},gamma:{value:new Z(1/e[0],1/e[1],1/e[2])},offsetHdr:{value:new Z().fromArray(t)},offsetSdr:{value:new Z().fromArray(n)},gainMapMin:{value:new Z().fromArray(i)},gainMapMax:{value:new Z().fromArray(o)},weightFactor:{value:(Math.log2(l)-h)/(d-h)}},blending:Jr,depthTest:!1,depthWrite:!1}),this._maxDisplayBoost=l,this._hdrCapacityMin=h,this._hdrCapacityMax=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get sdr(){return this.uniforms.sdr.value}set sdr(e){this.uniforms.sdr.value=e}get gainMap(){return this.uniforms.gainMap.value}set gainMap(e){this.uniforms.gainMap.value=e}get offsetHdr(){return this.uniforms.offsetHdr.value.toArray()}set offsetHdr(e){this.uniforms.offsetHdr.value.fromArray(e)}get offsetSdr(){return this.uniforms.offsetSdr.value.toArray()}set offsetSdr(e){this.uniforms.offsetSdr.value.fromArray(e)}get gainMapMin(){return this.uniforms.gainMapMin.value.toArray()}set gainMapMin(e){this.uniforms.gainMapMin.value.fromArray(e)}get gainMapMax(){return this.uniforms.gainMapMax.value.toArray()}set gainMapMax(e){this.uniforms.gainMapMax.value.fromArray(e)}get gamma(){const e=this.uniforms.gamma.value;return[1/e.x,1/e.y,1/e.z]}set gamma(e){const t=this.uniforms.gamma.value;t.x=1/e[0],t.y=1/e[1],t.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this.uniforms.weightFactor.value=Math.max(0,Math.min(1,e))}}class tC extends OI{constructor(e,t){super({renderer:e,createMaterial:n=>new HI(n),createQuadRenderer:n=>new CS(n)},t)}async render(e,t,n,i){const{sdrImage:o,gainMapImage:l,needsFlip:h}=await this.processImages(n,i,"flipY"),{gainMap:d,sdr:p}=this.createTextures(o,l,h);this.updateQuadRenderer(e,o,d,p,t),e.render()}}class PI extends tC{load([e,t,n],i,o,l){const h=this.prepareQuadRenderer();let d,p,_;const v=async()=>{if(d&&p&&_){try{await this.render(h,_,d,p)}catch(U){this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(n),typeof l=="function"&&l(U),h.disposeOnDemandRenderer();return}typeof i=="function"&&i(h),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(n),h.disposeOnDemandRenderer()}};let y=!0,x=0,b=0,R=!0,T=0,M=0,w=!0,D=0,N=0;const F=()=>{if(typeof o=="function"){const U=x+T+D,I=b+M+N,W=y&&R&&w;o(new ProgressEvent("progress",{lengthComputable:W,loaded:I,total:U}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(n);const O=new da(this._internalLoadingManager);O.setResponseType("arraybuffer"),O.setRequestHeader(this.requestHeader),O.setPath(this.path),O.setWithCredentials(this.withCredentials),O.load(e,async U=>{if(typeof U=="string")throw new Error("Invalid sdr buffer");d=U,await v()},U=>{y=U.lengthComputable,b=U.loaded,x=U.total,F()},U=>{this.manager.itemError(e),typeof l=="function"&&l(U)});const z=new da(this._internalLoadingManager);z.setResponseType("arraybuffer"),z.setRequestHeader(this.requestHeader),z.setPath(this.path),z.setWithCredentials(this.withCredentials),z.load(t,async U=>{if(typeof U=="string")throw new Error("Invalid gainmap buffer");p=U,await v()},U=>{R=U.lengthComputable,M=U.loaded,T=U.total,F()},U=>{this.manager.itemError(t),typeof l=="function"&&l(U)});const V=new da(this._internalLoadingManager);return V.setRequestHeader(this.requestHeader),V.setPath(this.path),V.setWithCredentials(this.withCredentials),V.load(n,async U=>{if(typeof U!="string")throw new Error("Invalid metadata string");_=JSON.parse(U),await v()},U=>{w=U.lengthComputable,N=U.loaded,D=U.total,F()},U=>{this.manager.itemError(n),typeof l=="function"&&l(U)}),h}}class GI extends tC{load(e,t,n,i){const o=this.prepareQuadRenderer(),l=new da(this._internalLoadingManager);return l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setPath(this.path),l.setWithCredentials(this.withCredentials),this.manager.itemStart(e),l.load(e,async h=>{if(typeof h=="string")throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const d=new Uint8Array(h);let p,_,v;try{const y=await LI(d);p=y.sdr,_=y.gainMap,v=y.metadata}catch(y){if(y instanceof $T||y instanceof QT)console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),v={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},p=d;else throw y}try{await this.render(o,v,p.buffer,_?.buffer)}catch(y){this.manager.itemError(e),typeof i=="function"&&i(y),o.disposeOnDemandRenderer();return}typeof t=="function"&&t(o),this.manager.itemEnd(e),o.disposeOnDemandRenderer()},n,h=>{this.manager.itemError(e),typeof i=="function"&&i(h)}),o}}const nm={apartment:"lebombo_1k.hdr",city:"potsdamer_platz_1k.hdr",dawn:"kiara_1_dawn_1k.hdr",forest:"forest_slope_1k.hdr",lobby:"st_fagans_interior_1k.hdr",night:"dikhololo_night_1k.hdr",park:"rooitou_park_1k.hdr",studio:"studio_small_03_1k.hdr",sunset:"venice_sunset_1k.hdr",warehouse:"empty_warehouse_01_1k.hdr"},nC="https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/",Vh=s=>Array.isArray(s),RS=["/px.png","/nx.png","/py.png","/ny.png","/pz.png","/nz.png"];function p_({files:s=RS,path:e="",preset:t=void 0,colorSpace:n=void 0,extensions:i}={}){t&&(wS(t),s=nm[t],e=nC);const o=Vh(s),{extension:l,isCubemap:h}=BS(s),d=DS(l);if(!d)throw new Error("useEnvironment: Unrecognized file extension: "+s);const p=Ih(x=>x.gl);Me.useLayoutEffect(()=>{if(l!=="webp"&&l!=="jpg"&&l!=="jpeg")return;function x(){Rl.clear(d,o?[s]:s)}p.domElement.addEventListener("webglcontextlost",x,{once:!0})},[s,p.domElement]);const _=Rl(d,o?[s]:s,x=>{(l==="webp"||l==="jpg"||l==="jpeg")&&x.setRenderer(p),x.setPath==null||x.setPath(e),i&&i(x)});let v=o?_[0]:_;if(l==="jpg"||l==="jpeg"||l==="webp"){var y;v=(y=v.renderTarget)==null?void 0:y.texture}return v.mapping=h?qr:Wf,v.colorSpace=n??(h?"srgb":"srgb-linear"),v}const zI={files:RS,path:"",preset:void 0,extensions:void 0};p_.preload=s=>{const e={...zI,...s};let{files:t,path:n=""}=e;const{preset:i,extensions:o}=e;i&&(wS(i),t=nm[i],n=nC);const{extension:l}=BS(t);if(l==="webp"||l==="jpg"||l==="jpeg")throw new Error("useEnvironment: Preloading gainmaps is not supported");const h=DS(l);if(!h)throw new Error("useEnvironment: Unrecognized file extension: "+t);Rl.preload(h,Vh(t)?[t]:t,d=>{d.setPath==null||d.setPath(n),o&&o(d)})};const VI={files:RS,preset:void 0};p_.clear=s=>{const e={...VI,...s};let{files:t}=e;const{preset:n}=e;n&&(wS(n),t=nm[n]);const{extension:i}=BS(t),o=DS(i);if(!o)throw new Error("useEnvironment: Unrecognized file extension: "+t);Rl.clear(o,Vh(t)?[t]:t)};function wS(s){if(!(s in nm))throw new Error("Preset must be one of: "+Object.keys(nm).join(", "))}function BS(s){var e;const t=Vh(s)&&s.length===6,n=Vh(s)&&s.length===3&&s.some(l=>l.endsWith("json")),i=Vh(s)?s[0]:s;return{extension:t?"cube":n?"webp":i.startsWith("data:application/exr")?"exr":i.startsWith("data:application/hdr")?"hdr":i.startsWith("data:image/jpeg")?"jpg":(e=i.split(".").pop())==null||(e=e.split("?"))==null||(e=e.shift())==null?void 0:e.toLowerCase(),isCubemap:t,isGainmap:n}}function DS(s){return s==="cube"?P1:s==="hdr"?CI:s==="exr"?RI:s==="jpg"||s==="jpeg"?GI:s==="webp"?PI:null}const kI=s=>s.current&&s.current.isScene,XI=s=>kI(s)?s.current:s;function NS(s,e,t,n,i={}){var o,l,h,d;i={backgroundBlurriness:0,backgroundIntensity:1,backgroundRotation:[0,0,0],environmentIntensity:1,environmentRotation:[0,0,0],...i};const p=XI(e||t),_=p.background,v=p.environment,y={backgroundBlurriness:p.backgroundBlurriness,backgroundIntensity:p.backgroundIntensity,backgroundRotation:(o=(l=p.backgroundRotation)==null||l.clone==null?void 0:l.clone())!==null&&o!==void 0?o:[0,0,0],environmentIntensity:p.environmentIntensity,environmentRotation:(h=(d=p.environmentRotation)==null||d.clone==null?void 0:d.clone())!==null&&h!==void 0?h:[0,0,0]};return s!=="only"&&(p.environment=n),s&&(p.background=n),No(p,i),()=>{s!=="only"&&(p.environment=v),s&&(p.background=_),No(p,y)}}function US({scene:s,background:e=!1,map:t,...n}){const i=Ih(o=>o.scene);return Me.useLayoutEffect(()=>{if(t)return NS(e,s,i,t,n)}),null}function iC({background:s=!1,scene:e,blur:t,backgroundBlurriness:n,backgroundIntensity:i,backgroundRotation:o,environmentIntensity:l,environmentRotation:h,...d}){const p=p_(d),_=Ih(v=>v.scene);return Me.useLayoutEffect(()=>NS(s,e,_,p,{backgroundBlurriness:t??n,backgroundIntensity:i,backgroundRotation:o,environmentIntensity:l,environmentRotation:h})),Me.useEffect(()=>()=>{p.dispose()},[p]),null}function YI({children:s,near:e=.1,far:t=1e3,resolution:n=256,frames:i=1,map:o,background:l=!1,blur:h,backgroundBlurriness:d,backgroundIntensity:p,backgroundRotation:_,environmentIntensity:v,environmentRotation:y,scene:x,files:b,path:R,preset:T=void 0,extensions:M}){const w=Ih(V=>V.gl),D=Ih(V=>V.scene),N=Me.useRef(null),[F]=Me.useState(()=>new Mp),O=Me.useMemo(()=>{const V=new Y0(n);return V.texture.type=ki,V},[n]);Me.useEffect(()=>()=>{O.dispose()},[O]),Me.useLayoutEffect(()=>{if(i===1){const V=w.autoClear;w.autoClear=!0,N.current.update(w,F),w.autoClear=V}return NS(l,x,D,O.texture,{backgroundBlurriness:h??d,backgroundIntensity:p,backgroundRotation:_,environmentIntensity:v,environmentRotation:y})},[s,F,O.texture,x,D,l,i,w]);let z=1;return yT(()=>{if(i===1/0||z<i){const V=w.autoClear;w.autoClear=!0,N.current.update(w,F),w.autoClear=V,z++}}),Me.createElement(Me.Fragment,null,_O(Me.createElement(Me.Fragment,null,s,Me.createElement("cubeCamera",{ref:N,args:[e,t,O]}),b||T?Me.createElement(iC,{background:!0,files:b,preset:T,path:R,extensions:M}):o?Me.createElement(US,{background:!0,map:o,extensions:M}):null),F))}function JI(s){var e,t,n,i;const o=p_(s),l=s.map||o;Me.useMemo(()=>MT({GroundProjectedEnvImpl:YO}),[]),Me.useEffect(()=>()=>{o.dispose()},[o]);const h=Me.useMemo(()=>[l],[l]),d=(e=s.ground)==null?void 0:e.height,p=(t=s.ground)==null?void 0:t.radius,_=(n=(i=s.ground)==null?void 0:i.scale)!==null&&n!==void 0?n:1e3;return Me.createElement(Me.Fragment,null,Me.createElement(US,ky({},s,{map:l})),Me.createElement("groundProjectedEnvImpl",{args:h,scale:_,height:d,radius:p}))}function qI(s){return s.ground?Me.createElement(JI,s):s.map?Me.createElement(US,s):s.children?Me.createElement(YI,s):Me.createElement(iC,s)}function aC(s,e){if(e===ox)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===bu||e===fp){let t=s.getIndex();if(t===null){const l=[],h=s.getAttribute("position");if(h!==void 0){for(let d=0;d<h.count;d++)l.push(d);s.setIndex(l),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const n=t.count-2,i=[];if(e===bu)for(let l=1;l<=n;l++)i.push(t.getX(0)),i.push(t.getX(l)),i.push(t.getX(l+1));else for(let l=0;l<n;l++)l%2===0?(i.push(t.getX(l)),i.push(t.getX(l+1)),i.push(t.getX(l+2))):(i.push(t.getX(l+2)),i.push(t.getX(l+1)),i.push(t.getX(l)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=s.clone();return o.setIndex(i),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class KI extends wa{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new $I(t)}),this.register(function(t){return new eF(t)}),this.register(function(t){return new cF(t)}),this.register(function(t){return new uF(t)}),this.register(function(t){return new fF(t)}),this.register(function(t){return new nF(t)}),this.register(function(t){return new iF(t)}),this.register(function(t){return new aF(t)}),this.register(function(t){return new sF(t)}),this.register(function(t){return new QI(t)}),this.register(function(t){return new rF(t)}),this.register(function(t){return new tF(t)}),this.register(function(t){return new lF(t)}),this.register(function(t){return new oF(t)}),this.register(function(t){return new jI(t)}),this.register(function(t){return new hF(t)}),this.register(function(t){return new dF(t)})}load(e,t,n,i){const o=this;let l;if(this.resourcePath!=="")l=this.resourcePath;else if(this.path!==""){const p=ir.extractUrlBase(e);l=ir.resolveURL(p,this.path)}else l=ir.extractUrlBase(e);this.manager.itemStart(e);const h=function(p){i?i(p):console.error(p),o.manager.itemError(e),o.manager.itemEnd(e)},d=new da(this.manager);d.setPath(this.path),d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setWithCredentials(this.withCredentials),d.load(e,function(p){try{o.parse(p,l,function(_){t(_),o.manager.itemEnd(e)},h)}catch(_){h(_)}},n,h)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,i){let o;const l={},h={},d=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(d.decode(new Uint8Array(e,0,4))===sC){try{l[Fn.KHR_BINARY_GLTF]=new pF(e)}catch(v){i&&i(v);return}o=JSON.parse(l[Fn.KHR_BINARY_GLTF].content)}else o=JSON.parse(d.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const p=new CF(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});p.fileLoader.setRequestHeader(this.requestHeader);for(let _=0;_<this.pluginCallbacks.length;_++){const v=this.pluginCallbacks[_](p);v.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),h[v.name]=v,l[v.name]=!0}if(o.extensionsUsed)for(let _=0;_<o.extensionsUsed.length;++_){const v=o.extensionsUsed[_],y=o.extensionsRequired||[];switch(v){case Fn.KHR_MATERIALS_UNLIT:l[v]=new ZI;break;case Fn.KHR_DRACO_MESH_COMPRESSION:l[v]=new mF(o,this.dracoLoader);break;case Fn.KHR_TEXTURE_TRANSFORM:l[v]=new gF;break;case Fn.KHR_MESH_QUANTIZATION:l[v]=new vF;break;default:y.indexOf(v)>=0&&h[v]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+v+'".')}}p.setExtensions(l),p.setPlugins(h),p.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,o){n.parse(e,t,i,o)})}}function WI(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const Fn={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class jI{constructor(e){this.parser=e,this.name=Fn.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){const o=t[n];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const o=t.json,d=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e];let p;const _=new Ct(16777215);d.color!==void 0&&_.setRGB(d.color[0],d.color[1],d.color[2],na);const v=d.range!==void 0?d.range:0;switch(d.type){case"directional":p=new Pv(_),p.target.position.set(0,0,-1),p.add(p.target);break;case"point":p=new Hv(_),p.distance=v;break;case"spot":p=new Fv(_),p.distance=v,d.spot=d.spot||{},d.spot.innerConeAngle=d.spot.innerConeAngle!==void 0?d.spot.innerConeAngle:0,d.spot.outerConeAngle=d.spot.outerConeAngle!==void 0?d.spot.outerConeAngle:Math.PI/4,p.angle=d.spot.outerConeAngle,p.penumbra=1-d.spot.innerConeAngle/d.spot.outerConeAngle,p.target.position.set(0,0,-1),p.add(p.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+d.type)}return p.position.set(0,0,0),Uo(p,d),d.intensity!==void 0&&(p.intensity=d.intensity),p.name=t.createUniqueName(d.name||"light_"+e),i=Promise.resolve(p),t.cache.add(n,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,o=n.json.nodes[e],h=(o.extensions&&o.extensions[this.name]||{}).light;return h===void 0?null:this._loadLight(h).then(function(d){return n._getNodeRef(t.cache,h,d)})}}class ZI{constructor(){this.name=Fn.KHR_MATERIALS_UNLIT}getMaterialType(){return ha}extendParams(e,t,n){const i=[];e.color=new Ct(1,1,1),e.opacity=1;const o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const l=o.baseColorFactor;e.color.setRGB(l[0],l[1],l[2],na),e.opacity=l[3]}o.baseColorTexture!==void 0&&i.push(n.assignTexture(e,"map",o.baseColorTexture,Xi))}return Promise.all(i)}}class QI{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name].emissiveStrength;return o!==void 0&&(t.emissiveIntensity=o),Promise.resolve()}}class $I{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];if(l.clearcoatFactor!==void 0&&(t.clearcoat=l.clearcoatFactor),l.clearcoatTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatMap",l.clearcoatTexture)),l.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=l.clearcoatRoughnessFactor),l.clearcoatRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatRoughnessMap",l.clearcoatRoughnessTexture)),l.clearcoatNormalTexture!==void 0&&(o.push(n.assignTexture(t,"clearcoatNormalMap",l.clearcoatNormalTexture)),l.clearcoatNormalTexture.scale!==void 0)){const h=l.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new tt(h,h)}return Promise.all(o)}}class eF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name];return t.dispersion=o.dispersion!==void 0?o.dispersion:0,Promise.resolve()}}class tF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.iridescenceFactor!==void 0&&(t.iridescence=l.iridescenceFactor),l.iridescenceTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceMap",l.iridescenceTexture)),l.iridescenceIor!==void 0&&(t.iridescenceIOR=l.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),l.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=l.iridescenceThicknessMinimum),l.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=l.iridescenceThicknessMaximum),l.iridescenceThicknessTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceThicknessMap",l.iridescenceThicknessTexture)),Promise.all(o)}}class nF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[];t.sheenColor=new Ct(0,0,0),t.sheenRoughness=0,t.sheen=1;const l=i.extensions[this.name];if(l.sheenColorFactor!==void 0){const h=l.sheenColorFactor;t.sheenColor.setRGB(h[0],h[1],h[2],na)}return l.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=l.sheenRoughnessFactor),l.sheenColorTexture!==void 0&&o.push(n.assignTexture(t,"sheenColorMap",l.sheenColorTexture,Xi)),l.sheenRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"sheenRoughnessMap",l.sheenRoughnessTexture)),Promise.all(o)}}class iF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.transmissionFactor!==void 0&&(t.transmission=l.transmissionFactor),l.transmissionTexture!==void 0&&o.push(n.assignTexture(t,"transmissionMap",l.transmissionTexture)),Promise.all(o)}}class aF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];t.thickness=l.thicknessFactor!==void 0?l.thicknessFactor:0,l.thicknessTexture!==void 0&&o.push(n.assignTexture(t,"thicknessMap",l.thicknessTexture)),t.attenuationDistance=l.attenuationDistance||1/0;const h=l.attenuationColor||[1,1,1];return t.attenuationColor=new Ct().setRGB(h[0],h[1],h[2],na),Promise.all(o)}}class sF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name];return t.ior=o.ior!==void 0?o.ior:1.5,Promise.resolve()}}class rF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];t.specularIntensity=l.specularFactor!==void 0?l.specularFactor:1,l.specularTexture!==void 0&&o.push(n.assignTexture(t,"specularIntensityMap",l.specularTexture));const h=l.specularColorFactor||[1,1,1];return t.specularColor=new Ct().setRGB(h[0],h[1],h[2],na),l.specularColorTexture!==void 0&&o.push(n.assignTexture(t,"specularColorMap",l.specularColorTexture,Xi)),Promise.all(o)}}class oF{constructor(e){this.parser=e,this.name=Fn.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return t.bumpScale=l.bumpFactor!==void 0?l.bumpFactor:1,l.bumpTexture!==void 0&&o.push(n.assignTexture(t,"bumpMap",l.bumpTexture)),Promise.all(o)}}class lF{constructor(e){this.parser=e,this.name=Fn.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Ji}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.anisotropyStrength!==void 0&&(t.anisotropy=l.anisotropyStrength),l.anisotropyRotation!==void 0&&(t.anisotropyRotation=l.anisotropyRotation),l.anisotropyTexture!==void 0&&o.push(n.assignTexture(t,"anisotropyMap",l.anisotropyTexture)),Promise.all(o)}}class cF{constructor(e){this.parser=e,this.name=Fn.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const o=i.extensions[this.name],l=t.options.ktx2Loader;if(!l){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,o.source,l)}}class uF{constructor(e){this.parser=e,this.name=Fn.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const l=o.extensions[t],h=i.images[l.source];let d=n.textureLoader;if(h.uri){const p=n.options.manager.getHandler(h.uri);p!==null&&(d=p)}return n.loadTextureImage(e,l.source,d)}}class fF{constructor(e){this.parser=e,this.name=Fn.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const l=o.extensions[t],h=i.images[l.source];let d=n.textureLoader;if(h.uri){const p=n.options.manager.getHandler(h.uri);p!==null&&(d=p)}return n.loadTextureImage(e,l.source,d)}}class hF{constructor(e){this.name=Fn.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const i=n.extensions[this.name],o=this.parser.getDependency("buffer",i.buffer),l=this.parser.options.meshoptDecoder;if(!l||!l.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(h){const d=i.byteOffset||0,p=i.byteLength||0,_=i.count,v=i.byteStride,y=new Uint8Array(h,d,p);return l.decodeGltfBufferAsync?l.decodeGltfBufferAsync(_,v,y,i.mode,i.filter).then(function(x){return x.buffer}):l.ready.then(function(){const x=new ArrayBuffer(_*v);return l.decodeGltfBuffer(new Uint8Array(x),_,v,y,i.mode,i.filter),x})})}else return null}}class dF{constructor(e){this.name=Fn.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const i=t.meshes[n.mesh];for(const p of i.primitives)if(p.mode!==Mr.TRIANGLES&&p.mode!==Mr.TRIANGLE_STRIP&&p.mode!==Mr.TRIANGLE_FAN&&p.mode!==void 0)return null;const l=n.extensions[this.name].attributes,h=[],d={};for(const p in l)h.push(this.parser.getDependency("accessor",l[p]).then(_=>(d[p]=_,d[p])));return h.length<1?null:(h.push(this.parser.createNodeMesh(e)),Promise.all(h).then(p=>{const _=p.pop(),v=_.isGroup?_.children:[_],y=p[0].count,x=[];for(const b of v){const R=new tn,T=new Z,M=new Ta,w=new Z(1,1,1),D=new nv(b.geometry,b.material,y);for(let N=0;N<y;N++)d.TRANSLATION&&T.fromBufferAttribute(d.TRANSLATION,N),d.ROTATION&&M.fromBufferAttribute(d.ROTATION,N),d.SCALE&&w.fromBufferAttribute(d.SCALE,N),D.setMatrixAt(N,R.compose(T,M,w));for(const N in d)if(N==="_COLOR_0"){const F=d[N];D.instanceColor=new xc(F.array,F.itemSize,F.normalized)}else N!=="TRANSLATION"&&N!=="ROTATION"&&N!=="SCALE"&&b.geometry.setAttribute(N,d[N]);On.prototype.copy.call(D,b),this.parser.assignFinalMaterial(D),x.push(D)}return _.isGroup?(_.clear(),_.add(...x),_):x[0]}))}}const sC="glTF",im=12,rC={JSON:1313821514,BIN:5130562};class pF{constructor(e){this.name=Fn.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,im),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==sC)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-im,o=new DataView(e,im);let l=0;for(;l<i;){const h=o.getUint32(l,!0);l+=4;const d=o.getUint32(l,!0);if(l+=4,d===rC.JSON){const p=new Uint8Array(e,im+l,h);this.content=n.decode(p)}else if(d===rC.BIN){const p=im+l;this.body=e.slice(p,p+h)}l+=h}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class mF{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Fn.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,o=e.extensions[this.name].bufferView,l=e.extensions[this.name].attributes,h={},d={},p={};for(const _ in l){const v=OS[_]||_.toLowerCase();h[v]=l[_]}for(const _ in e.attributes){const v=OS[_]||_.toLowerCase();if(l[_]!==void 0){const y=n.accessors[e.attributes[_]],x=kh[y.componentType];p[v]=x.name,d[v]=y.normalized===!0}}return t.getDependency("bufferView",o).then(function(_){return new Promise(function(v,y){i.decodeDracoFile(_,function(x){for(const b in x.attributes){const R=x.attributes[b],T=d[b];T!==void 0&&(R.normalized=T)}v(x)},h,p,na,y)})})}}class gF{constructor(){this.name=Fn.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class vF{constructor(){this.name=Fn.KHR_MESH_QUANTIZATION}}class oC extends Pu{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,o=e*i*3+i;for(let l=0;l!==i;l++)t[l]=n[o+l];return t}interpolate_(e,t,n,i){const o=this.resultBuffer,l=this.sampleValues,h=this.valueSize,d=h*2,p=h*3,_=i-t,v=(n-t)/_,y=v*v,x=y*v,b=e*p,R=b-p,T=-2*x+3*y,M=x-y,w=1-T,D=M-y+v;for(let N=0;N!==h;N++){const F=l[R+N+h],O=l[R+N+d]*_,z=l[b+N+h],V=l[b+N]*_;o[N]=w*F+D*O+T*z+M*V}return o}}const _F=new Ta;class yF extends oC{interpolate_(e,t,n,i){const o=super.interpolate_(e,t,n,i);return _F.fromArray(o).normalize().toArray(o),o}}const Mr={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},kh={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},lC={9728:Ti,9729:wn,9984:tp,9985:yu,9986:lc,9987:Is},cC={33071:Ei,33648:_u,10497:Kr},LS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},OS={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Bc={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},xF={CUBICSPLINE:void 0,LINEAR:uc,STEP:Au},IS={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function AF(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new Fu({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Yr})),s.DefaultMaterial}function nf(s,e,t){for(const n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Uo(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function SF(s,e,t){let n=!1,i=!1,o=!1;for(let p=0,_=e.length;p<_;p++){const v=e[p];if(v.POSITION!==void 0&&(n=!0),v.NORMAL!==void 0&&(i=!0),v.COLOR_0!==void 0&&(o=!0),n&&i&&o)break}if(!n&&!i&&!o)return Promise.resolve(s);const l=[],h=[],d=[];for(let p=0,_=e.length;p<_;p++){const v=e[p];if(n){const y=v.POSITION!==void 0?t.getDependency("accessor",v.POSITION):s.attributes.position;l.push(y)}if(i){const y=v.NORMAL!==void 0?t.getDependency("accessor",v.NORMAL):s.attributes.normal;h.push(y)}if(o){const y=v.COLOR_0!==void 0?t.getDependency("accessor",v.COLOR_0):s.attributes.color;d.push(y)}}return Promise.all([Promise.all(l),Promise.all(h),Promise.all(d)]).then(function(p){const _=p[0],v=p[1],y=p[2];return n&&(s.morphAttributes.position=_),i&&(s.morphAttributes.normal=v),o&&(s.morphAttributes.color=y),s.morphTargetsRelative=!0,s})}function MF(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,i=t.length;n<i;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function bF(s){let e;const t=s.extensions&&s.extensions[Fn.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+FS(t.attributes):e=s.indices+":"+FS(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,i=s.targets.length;n<i;n++)e+=":"+FS(s.targets[n]);return e}function FS(s){let e="";const t=Object.keys(s).sort();for(let n=0,i=t.length;n<i;n++)e+=t[n]+":"+s[t[n]]+";";return e}function HS(s){switch(s){case Int8Array:return .007874015748031496;case Uint8Array:return .00392156862745098;case Int16Array:return 3051850947599719e-20;case Uint16Array:return 15259021896696422e-21;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function EF(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const TF=new tn;class CF{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new WI,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,o=!1,l=-1;if(typeof navigator<"u"){const h=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(h)===!0;const d=h.match(/Version\/(\d+)/);i=n&&d?parseInt(d[1],10):-1,o=h.indexOf("Firefox")>-1,l=o?h.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||o&&l<98?this.textureLoader=new uA(this.options.manager):this.textureLoader=new mA(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new da(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,i=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(l){return l._markDefs&&l._markDefs()}),Promise.all(this._invokeAll(function(l){return l.beforeRoot&&l.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(l){const h={scene:l[0][i.scene||0],scenes:l[0],animations:l[1],cameras:l[2],asset:i.asset,parser:n,userData:{}};return nf(o,h,i),Uo(h,i),Promise.all(n._invokeAll(function(d){return d.afterRoot&&d.afterRoot(h)})).then(function(){for(const d of h.scenes)d.updateMatrixWorld();e(h)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,o=t.length;i<o;i++){const l=t[i].joints;for(let h=0,d=l.length;h<d;h++)e[l[h]].isBone=!0}for(let i=0,o=e.length;i<o;i++){const l=e[i];l.mesh!==void 0&&(this._addNodeRef(this.meshCache,l.mesh),l.skin!==void 0&&(n[l.mesh].isSkinnedMesh=!0)),l.camera!==void 0&&this._addNodeRef(this.cameraCache,l.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const i=n.clone(),o=(l,h)=>{const d=this.associations.get(l);d!=null&&this.associations.set(h,d);for(const[p,_]of l.children.entries())o(_,h.children[p])};return o(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const i=e(t[n]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let i=0;i<t.length;i++){const o=e(t[i]);o&&n.push(o)}return n}getDependency(e,t){const n=e+":"+t;let i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":i=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(o,l){return n.getDependency(e,l)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Fn.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(o,l){n.load(ir.resolveURL(t.uri,i.path),o,void 0,function(){l(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const i=t.byteLength||0,o=t.byteOffset||0;return n.slice(o,o+i)})}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const l=LS[i.type],h=kh[i.componentType],d=i.normalized===!0,p=new h(i.count*l);return Promise.resolve(new zn(p,l,d))}const o=[];return i.bufferView!==void 0?o.push(this.getDependency("bufferView",i.bufferView)):o.push(null),i.sparse!==void 0&&(o.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(o).then(function(l){const h=l[0],d=LS[i.type],p=kh[i.componentType],_=p.BYTES_PER_ELEMENT,v=_*d,y=i.byteOffset||0,x=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,b=i.normalized===!0;let R,T;if(x&&x!==v){const M=Math.floor(y/x),w="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+M+":"+i.count;let D=t.cache.get(w);D||(R=new p(h,M*x,i.count*x/_),D=new yh(R,x/_),t.cache.add(w,D)),T=new Al(D,d,y%x/_,b)}else h===null?R=new p(i.count*d):R=new p(h,y,i.count*d),T=new zn(R,d,b);if(i.sparse!==void 0){const M=LS.SCALAR,w=kh[i.sparse.indices.componentType],D=i.sparse.indices.byteOffset||0,N=i.sparse.values.byteOffset||0,F=new w(l[1],D,i.sparse.count*M),O=new p(l[2],N,i.sparse.count*d);h!==null&&(T=new zn(T.array.slice(),T.itemSize,T.normalized)),T.normalized=!1;for(let z=0,V=F.length;z<V;z++){const U=F[z];if(T.setX(U,O[z*d]),d>=2&&T.setY(U,O[z*d+1]),d>=3&&T.setZ(U,O[z*d+2]),d>=4&&T.setW(U,O[z*d+3]),d>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}T.normalized=b}return T})}loadTexture(e){const t=this.json,n=this.options,o=t.textures[e].source,l=t.images[o];let h=this.textureLoader;if(l.uri){const d=n.manager.getHandler(l.uri);d!==null&&(h=d)}return this.loadTextureImage(e,o,h)}loadTextureImage(e,t,n){const i=this,o=this.json,l=o.textures[e],h=o.images[t],d=(h.uri||h.bufferView)+":"+l.sampler;if(this.textureCache[d])return this.textureCache[d];const p=this.loadImageSource(t,n).then(function(_){_.flipY=!1,_.name=l.name||h.name||"",_.name===""&&typeof h.uri=="string"&&h.uri.startsWith("data:image/")===!1&&(_.name=h.uri);const y=(o.samplers||{})[l.sampler]||{};return _.magFilter=lC[y.magFilter]||wn,_.minFilter=lC[y.minFilter]||Is,_.wrapS=cC[y.wrapS]||Kr,_.wrapT=cC[y.wrapT]||Kr,_.generateMipmaps=!_.isCompressedTexture&&_.minFilter!==Ti&&_.minFilter!==wn,i.associations.set(_,{textures:e}),_}).catch(function(){return null});return this.textureCache[d]=p,p}loadImageSource(e,t){const n=this,i=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(v=>v.clone());const l=i.images[e],h=self.URL||self.webkitURL;let d=l.uri||"",p=!1;if(l.bufferView!==void 0)d=n.getDependency("bufferView",l.bufferView).then(function(v){p=!0;const y=new Blob([v],{type:l.mimeType});return d=h.createObjectURL(y),d});else if(l.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const _=Promise.resolve(d).then(function(v){return new Promise(function(y,x){let b=y;t.isImageBitmapLoader===!0&&(b=function(R){const T=new $n(R);T.needsUpdate=!0,y(T)}),t.load(ir.resolveURL(v,o.path),b,void 0,x)})}).then(function(v){return p===!0&&h.revokeObjectURL(d),Uo(v,l),v.userData.mimeType=l.mimeType||EF(l.uri),v}).catch(function(v){throw console.error("THREE.GLTFLoader: Couldn't load texture",d),v});return this.sourceCache[e]=_,_}assignTexture(e,t,n,i){const o=this;return this.getDependency("texture",n.index).then(function(l){if(!l)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(l=l.clone(),l.channel=n.texCoord),o.extensions[Fn.KHR_TEXTURE_TRANSFORM]){const h=n.extensions!==void 0?n.extensions[Fn.KHR_TEXTURE_TRANSFORM]:void 0;if(h){const d=o.associations.get(l);l=o.extensions[Fn.KHR_TEXTURE_TRANSFORM].extendTexture(l,h),o.associations.set(l,d)}}return i!==void 0&&(l.colorSpace=i),e[t]=l,l})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,l=t.attributes.normal===void 0;if(e.isPoints){const h="PointsMaterial:"+n.uuid;let d=this.cache.get(h);d||(d=new Np,Yi.prototype.copy.call(d,n),d.color.copy(n.color),d.map=n.map,d.sizeAttenuation=!1,this.cache.add(h,d)),n=d}else if(e.isLine){const h="LineBasicMaterial:"+n.uuid;let d=this.cache.get(h);d||(d=new za,Yi.prototype.copy.call(d,n),d.color.copy(n.color),d.map=n.map,this.cache.add(h,d)),n=d}if(i||o||l){let h="ClonedMaterial:"+n.uuid+":";i&&(h+="derivative-tangents:"),o&&(h+="vertex-colors:"),l&&(h+="flat-shading:");let d=this.cache.get(h);d||(d=n.clone(),o&&(d.vertexColors=!0),l&&(d.flatShading=!0),i&&(d.normalScale&&(d.normalScale.y*=-1),d.clearcoatNormalScale&&(d.clearcoatNormalScale.y*=-1)),this.cache.add(h,d),this.associations.set(d,this.associations.get(n))),n=d}e.material=n}getMaterialType(){return Fu}loadMaterial(e){const t=this,n=this.json,i=this.extensions,o=n.materials[e];let l;const h={},d=o.extensions||{},p=[];if(d[Fn.KHR_MATERIALS_UNLIT]){const v=i[Fn.KHR_MATERIALS_UNLIT];l=v.getMaterialType(),p.push(v.extendParams(h,o,t))}else{const v=o.pbrMetallicRoughness||{};if(h.color=new Ct(1,1,1),h.opacity=1,Array.isArray(v.baseColorFactor)){const y=v.baseColorFactor;h.color.setRGB(y[0],y[1],y[2],na),h.opacity=y[3]}v.baseColorTexture!==void 0&&p.push(t.assignTexture(h,"map",v.baseColorTexture,Xi)),h.metalness=v.metallicFactor!==void 0?v.metallicFactor:1,h.roughness=v.roughnessFactor!==void 0?v.roughnessFactor:1,v.metallicRoughnessTexture!==void 0&&(p.push(t.assignTexture(h,"metalnessMap",v.metallicRoughnessTexture)),p.push(t.assignTexture(h,"roughnessMap",v.metallicRoughnessTexture))),l=this._invokeOne(function(y){return y.getMaterialType&&y.getMaterialType(e)}),p.push(Promise.all(this._invokeAll(function(y){return y.extendMaterialParams&&y.extendMaterialParams(e,h)})))}o.doubleSided===!0&&(h.side=js);const _=o.alphaMode||IS.OPAQUE;if(_===IS.BLEND?(h.transparent=!0,h.depthWrite=!1):(h.transparent=!1,_===IS.MASK&&(h.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&l!==ha&&(p.push(t.assignTexture(h,"normalMap",o.normalTexture)),h.normalScale=new tt(1,1),o.normalTexture.scale!==void 0)){const v=o.normalTexture.scale;h.normalScale.set(v,v)}if(o.occlusionTexture!==void 0&&l!==ha&&(p.push(t.assignTexture(h,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(h.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&l!==ha){const v=o.emissiveFactor;h.emissive=new Ct().setRGB(v[0],v[1],v[2],na)}return o.emissiveTexture!==void 0&&l!==ha&&p.push(t.assignTexture(h,"emissiveMap",o.emissiveTexture,Xi)),Promise.all(p).then(function(){const v=new l(h);return o.name&&(v.name=o.name),Uo(v,o),t.associations.set(v,{materials:e}),o.extensions&&nf(i,v,o),v})}createUniqueName(e){const t=Yn.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function o(h){return n[Fn.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(h,t).then(function(d){return uC(d,h,t)})}const l=[];for(let h=0,d=e.length;h<d;h++){const p=e[h],_=bF(p),v=i[_];if(v)l.push(v.promise);else{let y;p.extensions&&p.extensions[Fn.KHR_DRACO_MESH_COMPRESSION]?y=o(p):y=uC(new pn,p,t),i[_]={primitive:p,promise:y},l.push(y)}}return Promise.all(l)}loadMesh(e){const t=this,n=this.json,i=this.extensions,o=n.meshes[e],l=o.primitives,h=[];for(let d=0,p=l.length;d<p;d++){const _=l[d].material===void 0?AF(this.cache):this.getDependency("material",l[d].material);h.push(_)}return h.push(t.loadGeometries(l)),Promise.all(h).then(function(d){const p=d.slice(0,d.length-1),_=d[d.length-1],v=[];for(let x=0,b=_.length;x<b;x++){const R=_[x],T=l[x];let M;const w=p[x];if(T.mode===Mr.TRIANGLES||T.mode===Mr.TRIANGLE_STRIP||T.mode===Mr.TRIANGLE_FAN||T.mode===void 0)M=o.isSkinnedMesh===!0?new ev(R,w):new Ai(R,w),M.isSkinnedMesh===!0&&M.normalizeSkinWeights(),T.mode===Mr.TRIANGLE_STRIP?M.geometry=aC(M.geometry,fp):T.mode===Mr.TRIANGLE_FAN&&(M.geometry=aC(M.geometry,bu));else if(T.mode===Mr.LINES)M=new yr(R,w);else if(T.mode===Mr.LINE_STRIP)M=new wo(R,w);else if(T.mode===Mr.LINE_LOOP)M=new fv(R,w);else if(T.mode===Mr.POINTS)M=new pv(R,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+T.mode);Object.keys(M.geometry.morphAttributes).length>0&&MF(M,o),M.name=t.createUniqueName(o.name||"mesh_"+e),Uo(M,o),T.extensions&&nf(i,M,T),t.assignFinalMaterial(M),v.push(M)}for(let x=0,b=v.length;x<b;x++)t.associations.set(v[x],{meshes:e,primitives:x});if(v.length===1)return o.extensions&&nf(i,v[0],o),v[0];const y=new vr;o.extensions&&nf(i,y,o),t.associations.set(y,{meshes:e});for(let x=0,b=v.length;x<b;x++)y.add(v[x]);return y})}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new aa(E0.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(t=new Tl(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Uo(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let i=0,o=t.joints.length;i<o;i++)n.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){const o=i.pop(),l=i,h=[],d=[];for(let p=0,_=l.length;p<_;p++){const v=l[p];if(v){h.push(v);const y=new tn;o!==null&&y.fromArray(o.array,p*16),d.push(y)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[p])}return new bh(h,d)})}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],o=i.name?i.name:"animation_"+e,l=[],h=[],d=[],p=[],_=[];for(let v=0,y=i.channels.length;v<y;v++){const x=i.channels[v],b=i.samplers[x.sampler],R=x.target,T=R.node,M=i.parameters!==void 0?i.parameters[b.input]:b.input,w=i.parameters!==void 0?i.parameters[b.output]:b.output;R.node!==void 0&&(l.push(this.getDependency("node",T)),h.push(this.getDependency("accessor",M)),d.push(this.getDependency("accessor",w)),p.push(b),_.push(R))}return Promise.all([Promise.all(l),Promise.all(h),Promise.all(d),Promise.all(p),Promise.all(_)]).then(function(v){const y=v[0],x=v[1],b=v[2],R=v[3],T=v[4],M=[];for(let D=0,N=y.length;D<N;D++){const F=y[D],O=x[D],z=b[D],V=R[D],U=T[D];if(F===void 0)continue;F.updateMatrix&&F.updateMatrix();const I=n._createAnimationTracks(F,O,z,V,U);if(I)for(let W=0;W<I.length;W++)M.push(I[W])}const w=new Vu(o,void 0,M);return Uo(w,i),w})}createNodeMesh(e){const t=this.json,n=this,i=t.nodes[e];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(o){const l=n._getNodeRef(n.meshCache,i.mesh,o);return i.weights!==void 0&&l.traverse(function(h){if(h.isMesh)for(let d=0,p=i.weights.length;d<p;d++)h.morphTargetInfluences[d]=i.weights[d]}),l})}loadNode(e){const t=this.json,n=this,i=t.nodes[e],o=n._loadNodeShallow(e),l=[],h=i.children||[];for(let p=0,_=h.length;p<_;p++)l.push(n.getDependency("node",h[p]));const d=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([o,Promise.all(l),d]).then(function(p){const _=p[0],v=p[1],y=p[2];y!==null&&_.traverse(function(x){x.isSkinnedMesh&&x.bind(y,TF)});for(let x=0,b=v.length;x<b;x++)_.add(v[x]);return _})}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const o=t.nodes[e],l=o.name?i.createUniqueName(o.name):"",h=[],d=i._invokeOne(function(p){return p.createNodeMesh&&p.createNodeMesh(e)});return d&&h.push(d),o.camera!==void 0&&h.push(i.getDependency("camera",o.camera).then(function(p){return i._getNodeRef(i.cameraCache,o.camera,p)})),i._invokeAll(function(p){return p.createNodeAttachment&&p.createNodeAttachment(e)}).forEach(function(p){h.push(p)}),this.nodeCache[e]=Promise.all(h).then(function(p){let _;if(o.isBone===!0?_=new Cp:p.length>1?_=new vr:p.length===1?_=p[0]:_=new On,_!==p[0])for(let v=0,y=p.length;v<y;v++)_.add(p[v]);if(o.name&&(_.userData.name=o.name,_.name=l),Uo(_,o),o.extensions&&nf(n,_,o),o.matrix!==void 0){const v=new tn;v.fromArray(o.matrix),_.applyMatrix4(v)}else o.translation!==void 0&&_.position.fromArray(o.translation),o.rotation!==void 0&&_.quaternion.fromArray(o.rotation),o.scale!==void 0&&_.scale.fromArray(o.scale);if(!i.associations.has(_))i.associations.set(_,{});else if(o.mesh!==void 0&&i.meshCache.refs[o.mesh]>1){const v=i.associations.get(_);i.associations.set(_,{...v})}return i.associations.get(_).nodes=e,_}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,o=new vr;n.name&&(o.name=i.createUniqueName(n.name)),Uo(o,n),n.extensions&&nf(t,o,n);const l=n.nodes||[],h=[];for(let d=0,p=l.length;d<p;d++)h.push(i.getDependency("node",l[d]));return Promise.all(h).then(function(d){for(let _=0,v=d.length;_<v;_++)o.add(d[_]);const p=_=>{const v=new Map;for(const[y,x]of i.associations)(y instanceof Yi||y instanceof $n)&&v.set(y,x);return _.traverse(y=>{const x=i.associations.get(y);x!=null&&v.set(y,x)}),v};return i.associations=p(o),o})}_createAnimationTracks(e,t,n,i,o){const l=[],h=e.name?e.name:e.uuid,d=[];Bc[o.path]===Bc.weights?e.traverse(function(y){y.morphTargetInfluences&&d.push(y.name?y.name:y.uuid)}):d.push(h);let p;switch(Bc[o.path]){case Bc.weights:p=Sl;break;case Bc.rotation:p=Ml;break;case Bc.translation:case Bc.scale:p=bl;break;default:n.itemSize===1?p=Sl:p=bl;break}const _=i.interpolation!==void 0?xF[i.interpolation]:uc,v=this._getArrayFromAccessor(n);for(let y=0,x=d.length;y<x;y++){const b=new p(d[y]+"."+Bc[o.path],t.array,v,_);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),l.push(b)}return l}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=HS(t.constructor),i=new Float32Array(t.length);for(let o=0,l=t.length;o<l;o++)i[o]=t[o]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const i=this instanceof Ml?yF:oC;return new i(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function RF(s,e,t){const n=e.attributes,i=new Ca;if(n.POSITION!==void 0){const h=t.json.accessors[n.POSITION],d=h.min,p=h.max;if(d!==void 0&&p!==void 0){if(i.set(new Z(d[0],d[1],d[2]),new Z(p[0],p[1],p[2])),h.normalized){const _=HS(kh[h.componentType]);i.min.multiplyScalar(_),i.max.multiplyScalar(_)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const o=e.targets;if(o!==void 0){const h=new Z,d=new Z;for(let p=0,_=o.length;p<_;p++){const v=o[p];if(v.POSITION!==void 0){const y=t.json.accessors[v.POSITION],x=y.min,b=y.max;if(x!==void 0&&b!==void 0){if(d.setX(Math.max(Math.abs(x[0]),Math.abs(b[0]))),d.setY(Math.max(Math.abs(x[1]),Math.abs(b[1]))),d.setZ(Math.max(Math.abs(x[2]),Math.abs(b[2]))),y.normalized){const R=HS(kh[y.componentType]);d.multiplyScalar(R)}h.max(d)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(h)}s.boundingBox=i;const l=new fa;i.getCenter(l.center),l.radius=i.min.distanceTo(i.max)/2,s.boundingSphere=l}function uC(s,e,t){const n=e.attributes,i=[];function o(l,h){return t.getDependency("accessor",l).then(function(d){s.setAttribute(h,d)})}for(const l in n){const h=OS[l]||l.toLowerCase();h in s.attributes||i.push(o(n[l],h))}if(e.indices!==void 0&&!s.index){const l=t.getDependency("accessor",e.indices).then(function(h){s.setIndex(h)});i.push(l)}return Nn.workingColorSpace!==na&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Nn.workingColorSpace}" not supported.`),Uo(s,e),RF(s,e,t),Promise.all(i).then(function(){return e.targets!==void 0?SF(s,e.targets,t):s})}const PS="https://ai.streamoji.com",ga=(...s)=>{},wF=(...s)=>{},fC=({analyser:s})=>{const e=Me.useRef(null),t=Me.useRef(null);return Me.useEffect(()=>{const n=e.current;if(!n)return;const i=n.getContext("2d",{alpha:!0});if(!i)return;let o,l=null;s&&(s.fftSize=128,l=new Uint8Array(s.frequencyBinCount));const h=()=>{o=requestAnimationFrame(h),(n.width!==n.offsetWidth||n.height!==n.offsetHeight)&&(n.width=n.offsetWidth,n.height=n.offsetHeight);const d=n.width,p=n.height;if(d===0||p===0)return;const _=p/2;i.clearRect(0,0,d,p),i.fillStyle="#1e293b";const v=2,x=v+2,b=d*.95,R=Math.floor(b/x);(!t.current||t.current.length!==R)&&(t.current=new Float32Array(R).fill(2));const T=R*x,M=(d-T)/2;s&&l&&s.getByteFrequencyData(l);const w=l?l.length:0,N=Math.floor(w*.7)/R,F=new Float32Array(R);for(let O=0;O<R;O++){let z=0;if(l&&N>0){const I=Math.floor(O*N),W=Math.floor((O+1)*N);for(let ne=I;ne<W;ne++){const $=l[ne]||0;$>z&&(z=$)}}z<10&&(z=0);const V=z/255,U=z>0?Math.max(2,Math.pow(V,1.4)*p*.25):2;F[O]=U}for(let O=0;O<R;O++){const z=R-1-O,V=Math.max(F[O],F[z]),U=t.current[O]+(V-t.current[O])*.3;t.current[O]=U;const I=M+O*x,W=_-U/2;i.beginPath(),i.roundRect?i.roundRect(I,W,v,U,4):i.fillRect(I,W,v,U),i.fill()}};return h(),()=>{cancelAnimationFrame(o)}},[s]),Vt.jsx("canvas",{ref:e,style:{width:"100%",height:"100%",display:"block"}})},BF="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev",hC="https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/default-models/avatar-dSbBDKwvmOkpTCZcwdjs.glb";async function DF(s){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s));return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}function NF(s){const[e,t]=Me.useState(null);return Me.useEffect(()=>{if(!s){t(null);return}let n=!1;return DF(s).then(i=>{if(n)return;const o=`${BF}/${i}.glb`;fetch(o,{method:"HEAD"}).then(l=>{n||t(l.ok?o:hC)}).catch(()=>{n||t(hC)})}),()=>{n=!0}},[s]),e}const UF=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_005.glb"],LF=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb"],OF=[{id:"m_expr_01",name:"Friendly Wave",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_001.glb"},{id:"m_expr_02",name:"You There",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_002.glb"},{id:"m_expr_04",name:"Awkward Agreement",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_004.glb"},{id:"m_expr_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_005.glb"},{id:"m_expr_06",name:"Tired Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_006.glb"},{id:"m_expr_07",name:"Conceilied Laughter",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_007.glb"},{id:"m_expr_08",name:"You Come Here",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_008.glb"},{id:"m_expr_09",name:"Come Here Kid",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_009.glb"},{id:"m_expr_10",name:"Come Here Everyone",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_010.glb"},{id:"m_expr_11",name:"No Freaking Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_011.glb"},{id:"m_expr_12",name:"Cheerful Approval",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_012.glb"},{id:"m_expr_13",name:"Waving Hello",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_013.glb"},{id:"m_expr_14",name:"Checking Surroundings",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_014.glb"},{id:"m_expr_15",name:"Referee Warning",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_015.glb"},{id:"m_expr_16",name:"You Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_016.glb"},{id:"m_expr_17",name:"Side Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_017.glb"},{id:"m_expr_18",name:"You're Finished",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_018.glb"},{id:"m_talk_01",name:"Oh God, Why Me?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_001.glb"},{id:"m_talk_02",name:"What Are You Doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_002.glb"},{id:"m_talk_03",name:"What Am I doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_003.glb"},{id:"m_talk_04",name:"No Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_004.glb"},{id:"m_talk_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb"},{id:"m_talk_06",name:"I have no idea",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"},{id:"m_talk_07",name:"What's going on here?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"},{id:"m_talk_08",name:"Let's stop",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_008.glb"},{id:"m_talk_09",name:"Fed Up Moment",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_009.glb"},{id:"m_talk_10",name:"What's This? Hold On",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_010.glb"},{id:"f_talk_01",name:"Great Job Clap",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_001.glb"},{id:"f_talk_02",name:"Chill Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"},{id:"f_talk_03",name:"This Is Me",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_003.glb"},{id:"f_talk_04",name:"Empathize",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb"},{id:"f_talk_05",name:"Loose Hands Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb"},{id:"f_talk_06",name:"Take It Easy",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb"}],IF=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"],FF={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},HF=[-.45,1.9,.1],PF={browInnerUp:.2},GS=.18,GF=1,dC="__branding__",m_={neutral:{eyeLookDownLeft:.1,eyeLookDownRight:.1},happy:{mouthSmileLeft:.2,mouthSmileRight:.2,eyeLookDownLeft:.1,eyeLookDownRight:.1},sad:{eyeLookDownLeft:.2,eyeLookDownRight:.2,browDownRight:.1,browInnerUp:.6,browOuterUpRight:.2,eyeSquintLeft:.7,eyeSquintRight:.7,mouthFrownLeft:.8,mouthFrownRight:.8,mouthLeft:.2,mouthPucker:.5,mouthRollLower:.2,mouthRollUpper:.2,mouthShrugLower:.2,mouthShrugUpper:.2,mouthStretchLeft:.4},angry:{eyeLookDownLeft:.1,eyeLookDownRight:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3},fear:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},disgust:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},love:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmileLeft:.2,mouthSmileRight:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1}},zF=[{key:"viseme_aa",mix:{jawOpen:.6}},{key:"viseme_E",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3}},{key:"viseme_I",mix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2}},{key:"viseme_O",mix:{mouthPucker:1,jawForward:.6,jawOpen:.2}},{key:"viseme_U",mix:{mouthFunnel:1}},{key:"viseme_PP",mix:{mouthRollLower:.3,mouthRollUpper:.3,mouthUpperUpLeft:.3,mouthUpperUpRight:.3}},{key:"viseme_FF",mix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:.3}},{key:"viseme_DD",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2}},{key:"viseme_SS",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1}},{key:"viseme_TH",mix:{mouthRollUpper:.3,jawOpen:.2,tongueOut:.4}},{key:"viseme_CH",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_RR",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_kk",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15}},{key:"viseme_nn",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15,tongueOut:.2}},{key:"viseme_sil",mix:{}}],VF={aei:[{v:"E",w:.8},{v:"I",w:.2}],ee:[{v:"I",w:1}],oo:[{v:"O",w:1}],u:[{v:"U",w:1}],aa:[{v:"aa",w:1}],ah:[{v:"aa",w:.7},{v:"O",w:.3}],bmp:[{v:"PP",w:1}],fv:[{v:"FF",w:1}],th:[{v:"TH",w:1}],l:[{v:"nn",w:1}],r:[{v:"RR",w:1}],qw:[{v:"U",w:.6},{v:"O",w:.4}],chjsh:[{v:"CH",w:1}],cdgknstxyz:[{v:"DD",w:.6},{v:"SS",w:.4}],sil:[{v:"sil",w:1}]};function kF(s){if(!s)return[{v:"sil",w:1}];const e=s.toLowerCase();return VF[e]??[{v:"sil",w:1}]}function XF({target:s}){const{camera:e}=Ih();return Me.useEffect(()=>{e.lookAt(...s)},[e,s]),null}function Gs(s,e,t){if(!s||!s.morphTargetDictionary)return;const n=s,i=n.morphTargetDictionary,o=n.morphTargetInfluences;if(o)for(const l in i)l.toLowerCase()===e.toLowerCase()&&(o[i[l]]=t)}function pC(s,e=.97){if(!s)return;const t=s;if(t.morphTargetInfluences)for(let n=0;n<t.morphTargetInfluences.length;n++)t.morphTargetInfluences[n]*=e}const YF=Me.memo(({avatarUrl:s,isPlayingRef:e,visemeQueueRef:t,audioContextRef:n,responseAudioStartTimeRef:i,adjustments:o,mood:l,expression:h,agentResponse:d,isSpeaking:p,nextStartTimeRef:_,stopPlayback:v,setIsSpeaking:y,expressionUrl:x,onExpressionFinished:b,isNudgeResponse:R,avatarGender:T})=>{const{scene:M}=zh(s),D=zh(T==="female"?LF:UF),N=Me.useMemo(()=>D.flatMap(X=>X.animations),[D]),F=zh(IF),O=Me.useMemo(()=>F.flatMap(X=>X.animations),[F]),z=Me.useRef(null),V=Me.useRef(null),U=Me.useRef(null),I=Me.useRef([]),[W]=Me.useState(()=>new iE(M)),ne=Me.useRef({}),$=Me.useRef(null),ae=Me.useRef(0),ge=Me.useRef(!1),H=Me.useRef(0),K=Me.useRef(null);Me.useEffect(()=>{if(!(!N||!M)){if(N.forEach((X,ee)=>{const le=`idle_${ee}`;if(!ne.current[le]){const ve=W.clipAction(X,M);ve.name=le,ve.setLoop(cp,1),ve.clampWhenFinished=!0,ne.current[le]=ve}}),O.forEach((X,ee)=>{const le=`talk_${ee}`;if(!ne.current[le]){const ve=W.clipAction(X,M);ve.name=le,ve.setLoop(cp,1),ve.clampWhenFinished=!0,ne.current[le]=ve}}),N.length>0){const X=ne.current.idle_0,ee=$.current&&W.existingAction($.current.getClip());X&&!ee&&(X.reset().fadeIn(.5).play(),$.current=X)}return()=>{W.stopAllAction(),ne.current={},$.current=null}}},[N,O,M,W]);const te=Me.useRef("");Me.useEffect(()=>{if(!x||!M||x===te.current)return;te.current=x,K.current=x,new KI().load(x,ee=>{if(ee.animations&&ee.animations.length>0){const le=ee.animations[0],ve=W.clipAction(le,M);if(ve.name=`EXPR_${x}`,ve.setLoop(cp,1),ve.clampWhenFinished=!0,ne.current[`EXPR_${x}`]=ve,p&&K.current===x){const Pe=$.current;ve.reset().fadeIn(.3).play(),Pe&&Pe!==ve&&Pe.crossFadeTo(ve,.3,!0),$.current=ve,K.current=null}}},void 0,ee=>{console.error(`[ANIMATION] Failed to load ${x}`,ee)})},[x,M,W,p]),Me.useEffect(()=>{const X=ee=>{const le=ee.action,ve=le.name||"";if(ve.startsWith("idle_")){const de=(parseInt(ve.split("_")[1])+1)%N.length,Ee=ne.current[`idle_${de}`];Ee&&(Ee.reset().fadeIn(.5).play(),le.crossFadeTo(Ee,.5,!0),$.current=Ee)}else if(ve.startsWith("EXPR_")){if(p){const Pe=ne.current.talk_0;Pe&&(Pe.reset().fadeIn(.5).play(),le.crossFadeTo(Pe,.5,!0),$.current=Pe)}else{const Pe=ne.current.idle_0;Pe&&(Pe.reset().fadeIn(.5).play(),le.crossFadeTo(Pe,.5,!0),$.current=Pe)}b&&b()}else if(ve.startsWith("talk_"))if(p&&!R){const de=(parseInt(ve.split("_")[1])+1)%O.length,Ee=ne.current[`talk_${de}`];Ee&&(Ee.reset().fadeIn(.3).play(),le.crossFadeTo(Ee,.3,!0),$.current=Ee)}else{const Pe=ne.current.idle_0;Pe&&(Pe.reset().fadeIn(.5).play(),le.crossFadeTo(Pe,.5,!0),$.current=Pe)}};return W.addEventListener("finished",X),()=>W.removeEventListener("finished",X)},[W,N,O,p,R,b]),Me.useEffect(()=>{if(p&&M){const X=$.current,ee=X?.name||"";if(ee.startsWith("idle_")||ee.startsWith("talk_")||ee===""){const le=K.current;if(le){const ve=ne.current[`EXPR_${le}`];if(ve){ve.reset().fadeIn(.3).play(),X&&X!==ve&&X.crossFadeTo(ve,.3,!0),$.current=ve,K.current=null;return}}if(ee.startsWith("idle_")||ee===""){const ve=ne.current.talk_0;ve&&(ve.reset().fadeIn(.5).play(),X&&X.crossFadeTo(ve,.5,!0),$.current=ve)}}}else if(!p&&M){const X=$.current,ee=X?.name||"";if(ee.startsWith("talk_")||ee.startsWith("EXPR_")){const le=ne.current.idle_0;le&&(le.reset().fadeIn(.5).play(),X&&X.crossFadeTo(le,.5,!0),$.current=le)}}},[p,M,x]),Me.useEffect(()=>{if(!M)return;M.traverse(le=>{if(le.isMesh&&le.morphTargetDictionary){const ve=le.name.toLowerCase();(ve.includes("head")||ve.includes("avatar"))&&(V.current=le,ga(`[ANIMATION] Found head mesh: ${le.name}`)),ve.includes("teeth")&&(U.current=le,ga(`[ANIMATION] Found teeth mesh: ${le.name}`))}});const X=V.current?.morphTargetDictionary;X&&Object.keys(X).filter(le=>le.toLowerCase().includes("brow"));const ee=[];M.traverse(le=>{if(le.isMesh){const Pe=le.morphTargetDictionary;Pe&&Object.keys(Pe).some(de=>de.toLowerCase().includes("brow"))&&ee.push(le)}}),I.current=ee,ee.length>0&&ga("[ANIMATION] Meshes with brow morphs:",ee.length)},[M]);const ye=(X,ee=1)=>{const le=`viseme_${X}`.toLowerCase(),ve=zF.find(Pe=>Pe.key.toLowerCase()===le);if(ve)for(const Pe in ve.mix){const de=ve.mix[Pe]*ee;Gs(V.current,Pe,de),Gs(U.current,Pe,de)}},xe=X=>{const ee=m_[X]??m_.neutral;for(const le in ee)Gs(V.current,le,ee[le]),Gs(U.current,le,ee[le])};return yT((X,ee)=>{const le=Math.pow(.88,60*ee);pC(V.current,le),pC(U.current,le),xe(l);const ve=X.clock.elapsedTime;let Pe=0;if(Math.floor(ve)%5===0&&Math.floor((ve-ee)%5)!==0){let Dt=null;M.traverse(It=>{It.name.toLowerCase().includes("hips")&&(Dt=It)});const pt=Dt?`Hips Y: ${Dt.position.y.toFixed(4)}`:"Hips not found";ga(`[ANIMATION] Mixer Time: ${W.time.toFixed(2)}, ${pt}`)}if(W.update(ee),ve>ae.current&&!ge.current&&(ge.current=!0,H.current=ve),ge.current){const Dt=p?.2:.3,pt=(ve-H.current)/Dt;if(pt>=1){ge.current=!1;const It=p?1:2.5;ae.current=ve+It}else{const It=pt<.5?pt*2:(1-pt)*2;Gs(V.current,"eyeBlinkLeft",It),Gs(V.current,"eyeBlinkRight",It),Gs(U.current,"eyeBlinkLeft",It),Gs(U.current,"eyeBlinkRight",It),Pe=It*PF.browInnerUp}}const de=m_[l]??m_.neutral,Ee=de.browInnerUp??0,lt=de.browOuterUpLeft??0,Bt=de.browOuterUpRight??0,Rt=ve*GF,rn=GS*Math.sin(Rt),hn=GS*.7*Math.sin(Rt+.7),Xt=GS*.7*Math.sin(Rt+1.3),ze=Dt=>Math.max(0,Math.min(1,Dt)),$e=ze(Ee+rn),Je=ze(lt+hn),vt=ze(Bt+Xt),Q=ze($e+Pe);if(Gs(V.current,"browInnerUp",Q),Gs(U.current,"browInnerUp",Q),Gs(V.current,"browOuterUpLeft",Je),Gs(U.current,"browOuterUpLeft",Je),Gs(V.current,"browOuterUpRight",vt),Gs(U.current,"browOuterUpRight",vt),z.current){const Dt=e.current?0:o.rotation[1];z.current.rotation.y=E0.lerp(z.current.rotation.y,Dt,.1),z.current.position.set(...o.position),z.current.scale.setScalar(o.scale),z.current.rotation.x=o.rotation[0],z.current.rotation.z=o.rotation[2]}if(e.current&&n.current){const Dt=n.current.currentTime,yt=(Dt-i.current)*1e3- -150;for(let j=0;j<t.current.length;j++){const P=t.current[j];yt>=P.vtime&&yt<P.vtime+P.vduration&&ye(P.viseme,P.weight??1)}Dt>_.current+.5&&(v(),y(!1))}}),Vt.jsx("group",{ref:z,children:Vt.jsx("primitive",{object:M})})});function JF(s){return s?s.charAt(0).toUpperCase()+s.slice(1).toLowerCase():""}const qF=({token:s,agentToken:e,onNavigationRequested:t,avatarGender:n,presetUserDetails:i}={})=>{const o=s??e??"",l=NF(o||void 0),[h,d]=Me.useState(""),[p,_]=Me.useState(""),[v,y]=Me.useState("Ready"),[x,b]=Me.useState(!1),[R,T]=Me.useState(!1),[M,w]=Me.useState([]),[D,N]=Me.useState(""),F=Me.useRef(null),[O,z]=Me.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 480px)").matches:!1);Me.useEffect(()=>{const _e=window.matchMedia("(max-width: 480px)"),Ge=()=>z(_e.matches);return _e.addEventListener("change",Ge),()=>_e.removeEventListener("change",Ge)},[]);const V=O?80:600,U=Me.useRef(!1),I=Me.useRef([]),W=Me.useRef(0),ne=Me.useRef(!1),$=Me.useRef([]),ae=Me.useRef(null),ge=Me.useRef([]);Me.useRef([]);const H=Me.useRef([]),K=Me.useRef(0),te=Me.useRef(0),ye=Me.useRef(0),xe=Me.useRef(0),X=Me.useRef(!1),[ee,le]=Me.useState(null),ve=Me.useRef(null),[Pe,de]=Me.useState("neutral"),[Ee,lt]=Me.useState(""),[Bt,Rt]=Me.useState(""),[rn,hn]=Me.useState("Chat with us"),[Xt,ze]=Me.useState(null),[$e,Je]=Me.useState("hidden"),[vt,Q]=Me.useState(""),Dt=Me.useRef(null),pt=Me.useRef($e);pt.current=$e;const[It,yt]=Me.useState(null),j=Me.useRef(null),P=Me.useRef(null),[ue,Ie]=Me.useState(!1),We=Me.useRef(null),[Ne,Ht]=Me.useState("hidden"),[St,zt]=Me.useState(""),qt=Me.useRef(Ne);qt.current=Ne;const Ve=Me.useRef(""),qe=Me.useRef(!1),bt=Me.useRef(""),Et=Me.useRef(Date.now()),ct=Me.useRef([]),kt=Me.useRef(!1),[pe,Be]=Me.useState(!1),[rt,Nt]=Me.useState(!1),Ze=Me.useRef(null),Xe=Me.useMemo(()=>ue?"Try again":v==="Busy"?"Busy":v==="Thinking..."||v==="Processing Voice..."?v:Xt!=null&&Xt!==""&&Xt!=="none"&&Xt!=="<none>"?`Enter ${JF(Xt)}`:Ne!=="hidden"||!rt?null:dC,[v,Xt,ue,Ne,rt]),xt=!ue&&v!=="Busy"&&v!=="Thinking..."&&v!=="Processing Voice..."&&(Xt==null||Xt===""||Xt==="none"||Xt==="<none>");Me.useEffect(()=>{if(Ne!=="hidden"||!xt){Nt(!1),Ze.current!=null&&(clearTimeout(Ze.current),Ze.current=null);return}return Ze.current=setTimeout(()=>{Ze.current=null,Nt(!0)},400),()=>{Ze.current!=null&&(clearTimeout(Ze.current),Ze.current=null)}},[Ne,xt]);const Qt=Xe!=null&&Xe!=="";Me.useEffect(()=>{const _e=pt.current;if(!(_e==="exiting"||_e==="entering")){if(_e==="hidden"){Qt&&(Q(Xe??""),Je("entering"));return}_e==="visible"&&(!Qt||Xe!==vt)&&(Dt.current=Qt?Xe:null,Je("exiting"))}},[Qt,Xe,$e,vt]),Me.useEffect(()=>{if(v!=="Busy"){P.current!=null&&(clearTimeout(P.current),P.current=null);return}return P.current=setTimeout(()=>{P.current=null,y("Ready"),Ie(!0)},12e3),()=>{P.current!=null&&(clearTimeout(P.current),P.current=null)}},[v]),Me.useEffect(()=>{if(!ue)return;const _e=setTimeout(()=>Ie(!1),2500);return()=>clearTimeout(_e)},[ue]);const Dn=Me.useCallback(()=>{const _e=pt.current;if(_e==="exiting"){Je("hidden");const Ge=Dt.current;Dt.current=null,Ge!=null&&Ge!==""&&(Q(Ge),Je("entering"))}else _e==="entering"&&Je("visible")},[]),En=_e=>{if(!_e)return;if(_e.mood!=null){const ot=String(_e.mood).toLowerCase();de(ot)}if(_e.expression!=null){const ot=String(_e.expression).trim();lt(ot);const Ut=OF.find(Ot=>Ot.name.toLowerCase()===ot.toLowerCase());ga(`[STREAM] Animation match for "${ot}": ${Ut?Ut.name:"NONE"}`),Rt(Ut?.url??"")}if(_e.navigation!=null){const ot=String(_e.navigation).trim();ot!==""&&(t?t(ot):window.open(ot,"_blank"))}const Ge=_e.ask_for||_e.lead_capture?.ask_for,Le=Ge?String(Ge).trim().toLowerCase():"",Ye=Le==="none"||Le==="<none>";if(Ge&&!Ye){const ot=Le;if(i&&(ot==="email"&&i.email||ot==="name"&&i.name||ot==="phone"&&i.phone))return;ze(ot||null),hn(ot==="email"?"Enter your email":ot==="name"?"Enter your name":ot==="phone"?"Enter your phone number":"Chat with us")}else(Ye||_e.ask_for===null||_e.lead_capture&&_e.lead_capture.ask_for===null||_e.ask_for==="none")&&(ze(null),rn!=="Chat with us"&&hn("Chat with us"));_e.collected,_e.valid},Ii=_e=>{const Ge=_e.trim();if(!Ge)return null;if(Ge.startsWith("{"))try{return JSON.parse(Ge)}catch{return null}if(Ge.includes(":")){const Le=Ge.split(":"),Ye=Le[0].trim().toLowerCase(),ot=Le.slice(1).join(":").trim();return{[Ye]:ot}}return null},Ba=Me.useCallback(()=>{},[]),br=_e=>{if(qe.current)_e==="§"?qe.current=!1:(bt.current+=_e,_(Ge=>Ge+_e));else if(_e==="§"){qe.current=!0;return}else for(Ve.current+=_e;Ve.current.includes(`
4150
4150
  `);){const Ge=Ve.current.indexOf(`
4151
4151
  `),Le=Ve.current.slice(0,Ge).trim();Ve.current=Ve.current.slice(Ge+1);const Ye=Ii(Le);Ye&&En(Ye)}};Me.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const ot="secret",Ut=Math.floor(Date.now()/1e3).toString();try{const Ot=new TextEncoder,Mt=await crypto.subtle.importKey("raw",Ot.encode(ot),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),ht=await crypto.subtle.sign("HMAC",Mt,Ot.encode(Ut)),dt=Array.from(new Uint8Array(ht)).map(an=>an.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",dt),ga("[SESSION] New HMAC UID generated and saved:",dt)}catch(Ot){console.error("[SESSION] HMAC generation failed:",Ot);const Mt=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",Mt)}}const Le=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES");let Ye=[];if(Le)try{Ye=JSON.parse(Le)}catch{Ye=[]}Ye.length===0&&i&&(i.name||i.email)?(Ye=[{role:"user",content:`PRESET_USER_DETAILS: Name is "${i.name||""}" , Email is "${i.email||""}"`}],sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(Ye))):Le||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[i]),Me.useEffect(()=>{const _e=()=>{Et.current=Date.now(),kt.current&&(kt.current=!1,Be(!1),w([]),N(""),_(""),T(!1))};window.addEventListener("mousemove",_e),window.addEventListener("keydown",_e),window.addEventListener("mousedown",_e),window.addEventListener("touchstart",_e);const Ge=setInterval(async()=>{if(Date.now()-Et.current>=3e4&&!R&&!x&&v==="Ready"&&!kt.current)if(kt.current=!0,ct.current.length>0)Be(!0),w(ct.current);else try{const ot=`${PS}/nudgeUser`,Ut={navigationUrl:window.location.href,token:o},Ot=await fetch(ot,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ut)});if(Ot.ok){const ht=(await Ot.json()).nudge_questions;ht&&ht.length>0&&(ga("[NUDGE] Received nudge questions from API:",ht),ct.current=ht,Be(!0),w(ht))}}catch(ot){console.error("[NUDGE] Error calling /nudgeUser:",ot),kt.current=!1}},1e3);return()=>{window.removeEventListener("mousemove",_e),window.removeEventListener("keydown",_e),window.removeEventListener("mousedown",_e),window.removeEventListener("touchstart",_e),clearInterval(Ge)}},[o,R,x,v]),Me.useEffect(()=>{if(M.length===0)return;let _e=0,Ge=0,Le=!1,Ye=100;const ot=()=>{const Ut=M[_e];if(Le){const Ot=Ut.substring(0,Ge-1);N(Ot),Ge--,Ye=50}else{const Ot=Ut.substring(0,Ge+1);N(Ot),Ge++,Ye=100}!Le&&Ge===Ut.length?(Le=!0,Ye=3e3):Le&&Ge===0&&(Le=!1,_e=(_e+1)%M.length,Ye=500),F.current=setTimeout(ot,Ye)};return ot(),()=>{F.current&&clearTimeout(F.current)}},[M]);const zs=()=>{try{return JSON.parse(sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||"[]")}catch{return[]}},Va=_e=>{sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(_e))},[sa,va]=Me.useState(!1),[Fi,Wt]=Me.useState(0),si=Me.useRef(null),fn=Me.useRef([]),G=Me.useRef(0),[J,oe]=Me.useState(null),[Re,Fe]=Me.useState(null),Ue=Me.useRef(null),at=Me.useRef(null),it=Me.useCallback((_e=!1)=>{_e&&(X.current=!0,b(!1),y("Ready")),$.current=[],I.current=[],ne.current=!1,T(!1),K.current=0,te.current=0,ye.current=0,ge.current.forEach(Ge=>{try{Ge.stop()}catch{}}),j.current&&(clearTimeout(j.current),j.current=null),yt(null),Rt(""),ge.current=[]},[]),st=async()=>{try{const _e=await navigator.mediaDevices.getUserMedia({audio:!0}),Ge=window.AudioContext||window.webkitAudioContext,Le=new Ge,Ye=Le.createMediaStreamSource(_e),ot=Le.createAnalyser();ot.fftSize=64,Ye.connect(ot),Ue.current=Le,at.current=Ye,Fe(ot);const Ut=new MediaRecorder(_e);si.current=Ut,fn.current=[],Ut.ondataavailable=Ot=>{Ot.data.size>0&&fn.current.push(Ot.data)},Ut.onstop=async()=>{const Ot=Date.now()-G.current;if(Fe(null),at.current&&(at.current.disconnect(),at.current=null),Ue.current&&Ue.current.state!=="closed"&&(Ue.current.close(),Ue.current=null),Ot<1e3){y("Recording too short. Hold or click longer."),b(!1);return}const Mt=new Blob(fn.current,{type:"audio/wav"});await ie(Mt)},G.current=Date.now(),Ut.start(100),va(!0),y("Listening...")}catch(_e){console.error("Error accessing microphone:",_e),y("Mic Access Error")}},et=()=>{si.current&&si.current.state!=="inactive"&&(si.current.stop(),si.current.stream.getTracks().forEach(_e=>_e.stop()),va(!1))},_t=()=>{si.current&&si.current.state!=="inactive"&&(si.current.onstop=null,si.current.stop(),si.current.stream.getTracks().forEach(_e=>_e.stop()),Fe(null),at.current&&(at.current.disconnect(),at.current=null),Ue.current&&Ue.current.state!=="closed"&&(Ue.current.close(),Ue.current=null),va(!1),fn.current=[],y("Ready"))};Me.useEffect(()=>{if(!R)return;const _e=()=>{const Ge=ye.current;if(Ge<=0)return;const Le=ae.current,Ye=K.current;if(!Le)return;const ot=Le.currentTime-Ye,Ut=Math.min(Math.max(0,ot),Ge),Ot=p.trim().length;if(Ot<=0)return;const Mt=Math.min(Math.round(Ut/Ge*Ot),Ot);le(Mt)};return clearInterval(ve.current??void 0),ve.current=setInterval(_e,90),()=>clearInterval(ve.current??void 0)},[R,p,ye.current]),Me.useEffect(()=>{let _e;return sa?(Wt(0),_e=window.setInterval(()=>{Wt(Ge=>Ge+1)},1e3)):Wt(0),()=>clearInterval(_e)},[sa]);const gt=_e=>{const Ge=_e.numberOfChannels,Le=_e.length*Ge*2+44,Ye=new ArrayBuffer(Le),ot=new DataView(Ye);let Ut=0;const Ot=dt=>{ot.setUint16(Ut,dt,!0),Ut+=2},Mt=dt=>{ot.setUint32(Ut,dt,!0),Ut+=4};Mt(1179011410),Mt(Le-8),Mt(1163280727),Mt(544501094),Mt(16),Ot(1),Ot(Ge),Mt(_e.sampleRate),Mt(_e.sampleRate*2*Ge),Ot(Ge*2),Ot(16),Mt(1635017060),Mt(Le-Ut-4);const ht=[];for(let dt=0;dt<Ge;dt++)ht.push(_e.getChannelData(dt));let wt=0;for(;Ut<Le;){for(let dt=0;dt<Ge;dt++){let an=Math.max(-1,Math.min(1,ht[dt][wt]));an=an<0?an*32768:an*32767,ot.setInt16(Ut,an,!0),Ut+=2}wt++}return new Blob([Ye],{type:"audio/wav"})},k=async(_e,Ge,Le=!1)=>{if(!X.current){if(U.current){I.current.push({audio:_e,visemes:Ge,isNewSegment:Le});return}U.current=!0;try{const Ye=window.AudioContext||window.webkitAudioContext,ot=ae.current??new Ye;ot.state==="suspended"&&await ot.resume(),ae.current=ot;const Ut=window.atob(_e),Ot=new Uint8Array(Ut.length);for(let yn=0;yn<Ut.length;yn++)Ot[yn]=Ut.charCodeAt(yn);const Mt=await ot.decodeAudioData(Ot.buffer.slice(0));ye.current+=Mt.duration;const ht=ot.currentTime;let wt=te.current;const dt=!ne.current;wt<ht&&(wt=ht+.1),te.current=wt+Mt.duration;const an=ot.createBufferSource();an.buffer=Mt;let Hn=J;if((!Hn||Hn.context!==ot)&&(Hn=ot.createAnalyser(),Hn.fftSize=64,Hn.connect(ot.destination),oe(Hn)),an.connect(Hn),ge.current.push(an),X.current){ge.current=ge.current.filter(yn=>yn!==an);return}if(dt){ne.current=!0,T(!0),ga(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${wt.toFixed(3)}`),K.current=wt;const yn=(wt-ht)*1e3;W.current=performance.now()+yn,ga(`[AUDIO] Response started. Initial startTime: ${wt.toFixed(3)}, CT: ${ht.toFixed(3)}`)}an.start(wt);const dn=(wt-K.current)*1e3;Le&&(xe.current=dn,ga(`[AUDIO] New segment detected at +${dn.toFixed(0)}ms. Resetting segment offset.`)),Ge.forEach((yn,xn)=>{const gn=yn.symbol??"";if(gn){const jn=kF(gn),Zn=Math.round(yn.start*1e3),li=Math.round((yn.duration??0)*1e3),Er=xe.current+Zn;xn<3&&ga(`[AUDIO] Viseme "${gn}": segment_relative=${Zn}ms, segment_offset=${xe.current.toFixed(0)}ms => vtime=${Er}ms`),jn.forEach(Da=>{$.current.push({viseme:Da.v,weight:Da.w,vtime:Er,vduration:li})})}}),y("Speaking...")}finally{if(U.current=!1,I.current.length>0){const Ye=I.current.shift();Ye&&k(Ye.audio,Ye.visemes,Ye.isNewSegment)}}}},ie=async _e=>{try{b(!0),Be(!1),bt.current="",_(""),y("Processing Voice...");const Ge=await _e.arrayBuffer(),Ye=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(Ge),ot=gt(Ye),Ut=new FileReader;Ut.readAsDataURL(ot),Ut.onloadend=async()=>{const Ot=Ut.result.split(",")[1];it(),d(""),Ve.current="",qe.current=!1;const Mt=`${PS}/stt?token=${encodeURIComponent(o)}`,ht=await fetch(Mt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:Ot,audio_format:"wav"})});if(ht.status===429){try{const xn=await ht.text(),gn=JSON.parse(xn);ga("[STT] 429 agent at capacity:",gn?.detail)}catch{}d(""),y("Busy"),b(!1);return}if(!ht.ok){const xn=await ht.text();let gn="STT Failed";try{gn=JSON.parse(xn).error||gn}catch{xn&&(gn=xn.slice(0,200))}throw new Error(gn)}const wt=ht.body;if(ga("this is body"+wt),!wt){y("STT Failed"),b(!1);return}const dt=wt.getReader();X.current=!1;const an=new TextDecoder;let Hn="",dn=!1;const yn=async(xn,gn)=>{switch(xn){case"transcript":gn.transcript!=null&&d(String(gn.transcript));break;case"text":{const jn=gn.delta??gn.text??"";jn&&br(jn);break}case"audio":{const jn=gn.chunk,Zn=gn.visemes??[],li=!!gn.is_new_segment;jn&&await k(jn,Zn,li);break}case"done":{dn=!0,y("Ready"),b(!1);break}case"error":{dn=!0,y("STT Failed"),b(!1);break}default:break}};for(;;){const{done:xn,value:gn}=await dt.read();gn&&(Hn+=an.decode(gn,{stream:!0}));const jn=Hn.split(`
4152
4152