@streamoji/avatar-widget 0.2.0 → 0.2.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.
- package/dist/avatar-widget.cjs +8 -0
- package/dist/avatar-widget.cjs.map +1 -0
- package/dist/{style.css → avatar-widget.css} +1 -1
- package/dist/avatar-widget.js +1125 -2385
- package/dist/avatar-widget.js.map +1 -1
- package/dist/avatar-widget.umd.css +1 -1
- package/dist/avatar-widget.umd.js +158 -158
- package/dist/avatar-widget.umd.js.map +1 -1
- package/package.json +2 -2
- package/dist/avatar-widget.umd.cjs +0 -9
- package/dist/avatar-widget.umd.cjs.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@streamoji/avatar-widget",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Plug-and-play React avatar widget for token-based AI conversations.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/avatar-widget.cjs",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"dist"
|
|
20
20
|
],
|
|
21
21
|
"scripts": {
|
|
22
|
-
"build": "vite build && cp declarations.d.ts dist/index.d.ts",
|
|
22
|
+
"build": "cp ../../src/components/AvatarWidget.css src/avatar-widget.css && vite build && cp declarations.d.ts dist/index.d.ts && rm -f src/avatar-widget.css",
|
|
23
23
|
"build:html": "vite build --config vite.config.html.ts",
|
|
24
24
|
"build:js": "vite build",
|
|
25
25
|
"build:types": "tsc -p tsconfig.build.json"
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
(function(ce,S){typeof exports=="object"&&typeof module<"u"?S(exports,require("react/jsx-runtime"),require("react"),require("@react-three/fiber"),require("@react-three/drei"),require("three")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","@react-three/fiber","@react-three/drei","three"],S):(ce=typeof globalThis<"u"?globalThis:ce||self,S(ce.StreamojiAvatarWidget={},ce.jsxRuntime,ce.React,ce.ReactThreeFiber,ce.Drei,ce.THREE))})(this,(function(ce,S,m,We,Ee,f){"use strict";var ot=document.createElement("style");ot.textContent=`.avatar-widget-container{position:fixed;bottom:0;right:0;z-index:1000;display:flex;flex-direction:column;align-items:flex-end;gap:1rem;width:280px}.avatar-bubble{z-index:10002;background:#fff;padding:1.25rem 1.5rem 1.5rem;min-height:3em;border-radius:24px;color:#1e293b;font-family:Inter,system-ui,-apple-system,sans-serif;font-size:1rem;font-weight:500;line-height:1.5;box-shadow:0 10px 25px -5px #0000001a,0 8px 10px -6px #0000001a;border:1px solid rgba(0,0,0,.05);position:absolute;top:64px;left:50%;transform:translate(-50%,-100%);max-width:min(320px,85vw);width:100%;pointer-events:none;-webkit-user-select:text;user-select:text;overflow:visible;word-break:break-word}.avatar-bubble:after{content:"";position:absolute;bottom:0;right:18%;width:29px;height:33px;background-image:url("data:image/svg+xml,%3Csvg width='29' height='33' viewBox='0 0 29 33' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M5.5%209C3.55459%207.42985%204.13875e-07%208%204.13875e-07%208L0.517701%20-9.50694e-06L28.5%200.995422L28.2689%207.49131C28.2689%207.49131%2023.754%207.83102%2022.2194%208.77706C20.6848%209.7231%2019.1146%2011.6685%2018.5794%2012.6501C18.0442%2013.6317%206.37564%2032.2286%206.37564%2032.2286C6.37564%2032.2286%207.46192%2015.7568%207.53302%2013.7581C7.60412%2011.7594%207.44541%2010.5702%205.5%209Z' fill='white'/%3E%3C/svg%3E");background-size:100% 100%;background-repeat:no-repeat;filter:drop-shadow(0 2px 2px rgba(0,0,0,.08));transform:translateY(78%) rotate(0)}.avatar-bubble__content{max-height:45px;overflow-y:auto;word-break:break-word;scrollbar-width:none;-ms-overflow-style:none}.avatar-bubble__content::-webkit-scrollbar{display:none}.avatar-bubble--entering{animation:avatarBubbleEnter .35s ease-out forwards}.avatar-bubble--exiting{animation:avatarBubbleExit .6s ease-in 2s forwards}@keyframes avatarBubbleEnter{0%{transform:translate(120%,-100%);opacity:0}to{transform:translate(-50%,-100%);opacity:1}}@keyframes avatarBubbleExit{0%{transform:translate(-50%,-100%);opacity:1}to{transform:translate(120%,-100%);opacity:0}}.avatar-wrapper{pointer-events:none;width:300px;height:400px;cursor:pointer;transition:transform .3s ease;z-index:1000}.avatar-wrapper:hover{transform:scale(1.05)}.avatar-circle-bg{width:100%;height:100%;border-radius:50%;border:2px solid white;background:linear-gradient(135deg,#008b8b,#38bdf8);box-shadow:0 4px 20px #0000004d;position:absolute;top:0;left:0;z-index:1}.avatar-circle-bg:before{content:"";position:absolute;inset:0;border-radius:50%;box-shadow:0 0 #ffffffb3;animation:pulse-white 2s infinite;z-index:-1}.avatar-scene-wrapper{z-index:2;pointer-events:none;overflow:visible}.avatar-scene-wrapper .avatar-canvas-layer{position:absolute;bottom:0;right:0;pointer-events:none!important;overflow:visible}.avatar-canvas-layer{width:400px;height:400px;z-index:2;pointer-events:none!important;overflow:visible}.avatar-canvas-layer canvas{pointer-events:none!important}@keyframes pulse-white{0%{transform:scale(.95);box-shadow:0 0 #ffffffb3}70%{transform:scale(1);box-shadow:0 0 0 10px #fff0}to{transform:scale(.95);box-shadow:0 0 #fff0}}@keyframes popIn{0%{opacity:0;transform:scale(.8) translateY(10px)}to{opacity:1;transform:scale(1) translateY(0)}}.avatar-input-area{position:absolute;bottom:4px;right:4px;z-index:10001;display:flex;flex-direction:column;align-items:flex-end;gap:6px}@keyframes thinkingTabPopUp{0%{transform:translateY(28px);opacity:0}to{transform:translateY(0);opacity:1}}@keyframes thinkingTabPopDown{0%{transform:translateY(0);opacity:1}to{transform:translateY(28px);opacity:0}}.avatar-thinking-tab{background:#1e4a5e;color:#fff;font-size:.8rem;font-weight:500;padding:6px 14px;border-radius:12px 12px 0 0;font-family:Inter,system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 8px #0000001a;position:absolute;bottom:45px;left:25px}.avatar-thinking-tab--entering{animation:thinkingTabPopUp .25s ease-out forwards}.avatar-thinking-tab--exiting{animation:thinkingTabPopDown .25s ease-in forwards}.avatar-input-container{position:relative;bottom:auto;right:auto;z-index:10001;width:100%;min-width:280px;height:48px;min-height:48px;pointer-events:auto;display:flex;flex-direction:column;justify-content:center;align-items:stretch;overflow:hidden;background:#fff;border-radius:50px;padding:0 4px 0 20px;box-shadow:0 2px 12px #00000014}.avatar-input-container>div:first-child{display:flex;align-items:center;width:100%;height:100%;min-height:0}.avatar-input-container .avatar-input-loader{height:30px;aspect-ratio:2.5;--_g: no-repeat radial-gradient(farthest-side, #1e4a5e 90%, #0000);background:var(--_g),var(--_g),var(--_g),var(--_g);background-size:20% 50%;animation:avatar-input-l44 1s infinite linear alternate}@keyframes avatar-input-l44{0%,5%{background-position:0% 50%,calc(1*100%/3) 50%,calc(2*100%/3) 50%,100% 50%}12.5%{background-position:0% 0,calc(1*100%/3) 50%,calc(2*100%/3) 50%,100% 50%}25%{background-position:0% 0,calc(1*100%/3) 0,calc(2*100%/3) 50%,100% 50%}37.5%{background-position:0% 100%,calc(1*100%/3) 0,calc(2*100%/3) 0,100% 50%}50%{background-position:0% 100%,calc(1*100%/3) 100%,calc(2*100%/3) 0,100% 0}62.5%{background-position:0% 50%,calc(1*100%/3) 100%,calc(2*100%/3) 100%,100% 0}75%{background-position:0% 50%,calc(1*100%/3) 50%,calc(2*100%/3) 100%,100% 100%}87.5%{background-position:0% 50%,calc(1*100%/3) 50%,calc(2*100%/3) 50%,100% 100%}95%,to{background-position:0% 50%,calc(1*100%/3) 50%,calc(2*100%/3) 50%,100% 50%}}.avatar-input-header{background:#1e4a5e;color:#fff;padding:6px 16px;width:fit-content;min-width:35%;margin-left:8%;border-radius:12px 12px 0 0;font-family:Inter,system-ui,sans-serif;font-size:11px;font-weight:500;letter-spacing:-.01em;text-align:center;white-space:nowrap}.avatar-input-body{background:#fff;padding:6px;border-radius:50px;display:flex;flex-direction:column}.avatar-input-body form{display:flex;align-items:center;width:100%}#avatar-text-input{background:transparent;border:none;color:#334155;font-size:.95rem;line-height:1.25;outline:none;padding:0 2px 0 12px;flex:1;min-width:0;font-family:Inter,system-ui,sans-serif}#avatar-text-input::placeholder{color:#94a3b8}.avatar-input-container .mic-button{background:#1e4a5e;color:#fff;border:none;width:38px;height:38px;border-radius:50%!important;display:flex;justify-content:center;align-items:center;cursor:pointer;transition:all .2s cubic-bezier(.4,0,.2,1);flex-shrink:0;margin-right:0;margin-left:8px}.avatar-input-container .mic-button:hover{background:#163a4a;transform:translateY(-1px)}.avatar-input-recording{flex:1;display:flex;align-items:center;width:100%;height:100%;min-height:36px;gap:8px}.avatar-input-recording .avatar-recording-cancel,.avatar-input-recording .avatar-recording-confirm{width:32px;height:32px;min-width:32px;min-height:32px;border-radius:50%;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;padding:0;line-height:0;align-self:center;box-sizing:border-box}.avatar-input-recording .avatar-recording-cancel{background:#cbd5e1;color:#fff}.avatar-input-recording .avatar-recording-confirm{background:#1e4a5e;color:#fff}.avatar-input-recording .avatar-recording-cancel:hover,.avatar-input-recording .avatar-recording-confirm:hover{opacity:.9}.avatar-status-text{font-size:.75rem;color:#64748b;text-align:center;padding-bottom:4px;font-family:Inter,sans-serif}@media(max-width:480px){.avatar-widget-container{bottom:.5rem;right:.5rem}.avatar-bubble{font-size:.9rem;padding:.75rem 1rem;max-width:250px}.avatar-wrapper{width:56px;height:56px}.avatar-scene-wrapper{width:400px;height:400px}.avatar-input-container{right:0;bottom:0;min-width:220px;filter:drop-shadow(0 5px 15px rgba(0,0,0,.2))}.avatar-input-header{padding:8px 12px;font-size:14px}}.speech-bubble{background:#fff;border-radius:40px 40px 0/40px 40px 0px;padding:16px 24px;color:#1e293b;font-family:Inter,system-ui,-apple-system,sans-serif;font-size:16px;font-weight:500;line-height:1.4;max-width:320px;width:max-content;box-shadow:0 10px 25px -5px #0000001a,0 8px 10px -6px #0000001a;pointer-events:none;-webkit-user-select:none;user-select:none;position:relative;text-align:center;z-index:10002;transform:translate(-50%,-100%);margin-bottom:20px}@keyframes bubbleFadeIn{0%{opacity:0;transform:translate(-50%) scale(.9)}to{opacity:1;transform:translate(-50%) scale(1)}}.thinking-dots{display:flex;justify-content:center;align-items:center;gap:4px;height:12px}.thinking-dots span{width:6px;height:6px;background-color:#94a3b8;border-radius:50%;display:inline-block;animation:thinking-dot-pulse 1.4s infinite ease-in-out both}.thinking-dots span:nth-child(1){animation-delay:-.32s}.thinking-dots span:nth-child(2){animation-delay:-.16s}@keyframes thinking-dot-pulse{0%,80%,to{transform:scale(0);opacity:.3}40%{transform:scale(1);opacity:1}}
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(ot);function Mt(d){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(d){for(const e in d)if(e!=="default"){const s=Object.getOwnPropertyDescriptor(d,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:()=>d[e]})}}return t.default=d,Object.freeze(t)}const Ce=Mt(f);function at(d,t){if(t===f.TrianglesDrawMode)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),d;if(t===f.TriangleFanDrawMode||t===f.TriangleStripDrawMode){let e=d.getIndex();if(e===null){const r=[],a=d.getAttribute("position");if(a!==void 0){for(let o=0;o<a.count;o++)r.push(o);d.setIndex(r),e=d.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),d}const s=e.count-2,n=[];if(t===f.TriangleFanDrawMode)for(let r=1;r<=s;r++)n.push(e.getX(0)),n.push(e.getX(r)),n.push(e.getX(r+1));else for(let r=0;r<s;r++)r%2===0?(n.push(e.getX(r)),n.push(e.getX(r+1)),n.push(e.getX(r+2))):(n.push(e.getX(r+2)),n.push(e.getX(r+1)),n.push(e.getX(r)));n.length/3!==s&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const i=d.clone();return i.setIndex(n),i.clearGroups(),i}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),d}class kt extends f.Loader{constructor(t){super(t),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new Ot(e)}),this.register(function(e){return new Dt(e)}),this.register(function(e){return new Kt(e)}),this.register(function(e){return new Wt(e)}),this.register(function(e){return new zt(e)}),this.register(function(e){return new Pt(e)}),this.register(function(e){return new Ut(e)}),this.register(function(e){return new Et(e)}),this.register(function(e){return new Bt(e)}),this.register(function(e){return new Nt(e)}),this.register(function(e){return new Gt(e)}),this.register(function(e){return new Ft(e)}),this.register(function(e){return new Vt(e)}),this.register(function(e){return new jt(e)}),this.register(function(e){return new Rt(e)}),this.register(function(e){return new Xt(e)}),this.register(function(e){return new qt(e)})}load(t,e,s,n){const i=this;let r;if(this.resourcePath!=="")r=this.resourcePath;else if(this.path!==""){const c=f.LoaderUtils.extractUrlBase(t);r=f.LoaderUtils.resolveURL(c,this.path)}else r=f.LoaderUtils.extractUrlBase(t);this.manager.itemStart(t);const a=function(c){n?n(c):console.error(c),i.manager.itemError(t),i.manager.itemEnd(t)},o=new f.FileLoader(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(t,function(c){try{i.parse(c,r,function(l){e(l),i.manager.itemEnd(t)},a)}catch(l){a(l)}},s,a)}setDRACOLoader(t){return this.dracoLoader=t,this}setKTX2Loader(t){return this.ktx2Loader=t,this}setMeshoptDecoder(t){return this.meshoptDecoder=t,this}register(t){return this.pluginCallbacks.indexOf(t)===-1&&this.pluginCallbacks.push(t),this}unregister(t){return this.pluginCallbacks.indexOf(t)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(t),1),this}parse(t,e,s,n){let i;const r={},a={},o=new TextDecoder;if(typeof t=="string")i=JSON.parse(t);else if(t instanceof ArrayBuffer)if(o.decode(new Uint8Array(t,0,4))===ct){try{r[N.KHR_BINARY_GLTF]=new $t(t)}catch(u){n&&n(u);return}i=JSON.parse(r[N.KHR_BINARY_GLTF].content)}else i=JSON.parse(o.decode(t));else i=t;if(i.asset===void 0||i.asset.version[0]<2){n&&n(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const c=new cn(i,{path:e||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let l=0;l<this.pluginCallbacks.length;l++){const u=this.pluginCallbacks[l](c);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[u.name]=u,r[u.name]=!0}if(i.extensionsUsed)for(let l=0;l<i.extensionsUsed.length;++l){const u=i.extensionsUsed[l],h=i.extensionsRequired||[];switch(u){case N.KHR_MATERIALS_UNLIT:r[u]=new Ct;break;case N.KHR_DRACO_MESH_COMPRESSION:r[u]=new Yt(i,this.dracoLoader);break;case N.KHR_TEXTURE_TRANSFORM:r[u]=new Ht;break;case N.KHR_MESH_QUANTIZATION:r[u]=new Jt;break;default:h.indexOf(u)>=0&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}c.setExtensions(r),c.setPlugins(a),c.parse(s,n)}parseAsync(t,e){const s=this;return new Promise(function(n,i){s.parse(t,e,n,i)})}}function It(){let d={};return{get:function(t){return d[t]},add:function(t,e){d[t]=e},remove:function(t){delete d[t]},removeAll:function(){d={}}}}const N={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 Rt{constructor(t){this.parser=t,this.name=N.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const t=this.parser,e=this.parser.json.nodes||[];for(let s=0,n=e.length;s<n;s++){const i=e[s];i.extensions&&i.extensions[this.name]&&i.extensions[this.name].light!==void 0&&t._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(t){const e=this.parser,s="light:"+t;let n=e.cache.get(s);if(n)return n;const i=e.json,o=((i.extensions&&i.extensions[this.name]||{}).lights||[])[t];let c;const l=new f.Color(16777215);o.color!==void 0&&l.setRGB(o.color[0],o.color[1],o.color[2],f.LinearSRGBColorSpace);const u=o.range!==void 0?o.range:0;switch(o.type){case"directional":c=new f.DirectionalLight(l),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new f.PointLight(l),c.distance=u;break;case"spot":c=new f.SpotLight(l),c.distance=u,o.spot=o.spot||{},o.spot.innerConeAngle=o.spot.innerConeAngle!==void 0?o.spot.innerConeAngle:0,o.spot.outerConeAngle=o.spot.outerConeAngle!==void 0?o.spot.outerConeAngle:Math.PI/4,c.angle=o.spot.outerConeAngle,c.penumbra=1-o.spot.innerConeAngle/o.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+o.type)}return c.position.set(0,0,0),de(c,o),o.intensity!==void 0&&(c.intensity=o.intensity),c.name=e.createUniqueName(o.name||"light_"+t),n=Promise.resolve(c),e.cache.add(s,n),n}getDependency(t,e){if(t==="light")return this._loadLight(e)}createNodeAttachment(t){const e=this,s=this.parser,i=s.json.nodes[t],a=(i.extensions&&i.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(o){return s._getNodeRef(e.cache,a,o)})}}class Ct{constructor(){this.name=N.KHR_MATERIALS_UNLIT}getMaterialType(){return f.MeshBasicMaterial}extendParams(t,e,s){const n=[];t.color=new f.Color(1,1,1),t.opacity=1;const i=e.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){const r=i.baseColorFactor;t.color.setRGB(r[0],r[1],r[2],f.LinearSRGBColorSpace),t.opacity=r[3]}i.baseColorTexture!==void 0&&n.push(s.assignTexture(t,"map",i.baseColorTexture,f.SRGBColorSpace))}return Promise.all(n)}}class Nt{constructor(t){this.parser=t,this.name=N.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(t,e){const n=this.parser.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=n.extensions[this.name].emissiveStrength;return i!==void 0&&(e.emissiveIntensity=i),Promise.resolve()}}class Ot{constructor(t){this.parser=t,this.name=N.KHR_MATERIALS_CLEARCOAT}getMaterialType(t){const s=this.parser.json.materials[t];return!s.extensions||!s.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(t,e){const s=this.parser,n=s.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];if(r.clearcoatFactor!==void 0&&(e.clearcoat=r.clearcoatFactor),r.clearcoatTexture!==void 0&&i.push(s.assignTexture(e,"clearcoatMap",r.clearcoatTexture)),r.clearcoatRoughnessFactor!==void 0&&(e.clearcoatRoughness=r.clearcoatRoughnessFactor),r.clearcoatRoughnessTexture!==void 0&&i.push(s.assignTexture(e,"clearcoatRoughnessMap",r.clearcoatRoughnessTexture)),r.clearcoatNormalTexture!==void 0&&(i.push(s.assignTexture(e,"clearcoatNormalMap",r.clearcoatNormalTexture)),r.clearcoatNormalTexture.scale!==void 0)){const a=r.clearcoatNormalTexture.scale;e.clearcoatNormalScale=new f.Vector2(a,a)}return Promise.all(i)}}class Dt{constructor(t){this.parser=t,this.name=N.KHR_MATERIALS_DISPERSION}getMaterialType(t){const s=this.parser.json.materials[t];return!s.extensions||!s.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(t,e){const n=this.parser.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=n.extensions[this.name];return e.dispersion=i.dispersion!==void 0?i.dispersion:0,Promise.resolve()}}class Ft{constructor(t){this.parser=t,this.name=N.KHR_MATERIALS_IRIDESCENCE}getMaterialType(t){const s=this.parser.json.materials[t];return!s.extensions||!s.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(t,e){const s=this.parser,n=s.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];return r.iridescenceFactor!==void 0&&(e.iridescence=r.iridescenceFactor),r.iridescenceTexture!==void 0&&i.push(s.assignTexture(e,"iridescenceMap",r.iridescenceTexture)),r.iridescenceIor!==void 0&&(e.iridescenceIOR=r.iridescenceIor),e.iridescenceThicknessRange===void 0&&(e.iridescenceThicknessRange=[100,400]),r.iridescenceThicknessMinimum!==void 0&&(e.iridescenceThicknessRange[0]=r.iridescenceThicknessMinimum),r.iridescenceThicknessMaximum!==void 0&&(e.iridescenceThicknessRange[1]=r.iridescenceThicknessMaximum),r.iridescenceThicknessTexture!==void 0&&i.push(s.assignTexture(e,"iridescenceThicknessMap",r.iridescenceThicknessTexture)),Promise.all(i)}}class Pt{constructor(t){this.parser=t,this.name=N.KHR_MATERIALS_SHEEN}getMaterialType(t){const s=this.parser.json.materials[t];return!s.extensions||!s.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(t,e){const s=this.parser,n=s.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[];e.sheenColor=new f.Color(0,0,0),e.sheenRoughness=0,e.sheen=1;const r=n.extensions[this.name];if(r.sheenColorFactor!==void 0){const a=r.sheenColorFactor;e.sheenColor.setRGB(a[0],a[1],a[2],f.LinearSRGBColorSpace)}return r.sheenRoughnessFactor!==void 0&&(e.sheenRoughness=r.sheenRoughnessFactor),r.sheenColorTexture!==void 0&&i.push(s.assignTexture(e,"sheenColorMap",r.sheenColorTexture,f.SRGBColorSpace)),r.sheenRoughnessTexture!==void 0&&i.push(s.assignTexture(e,"sheenRoughnessMap",r.sheenRoughnessTexture)),Promise.all(i)}}class Ut{constructor(t){this.parser=t,this.name=N.KHR_MATERIALS_TRANSMISSION}getMaterialType(t){const s=this.parser.json.materials[t];return!s.extensions||!s.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(t,e){const s=this.parser,n=s.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];return r.transmissionFactor!==void 0&&(e.transmission=r.transmissionFactor),r.transmissionTexture!==void 0&&i.push(s.assignTexture(e,"transmissionMap",r.transmissionTexture)),Promise.all(i)}}class Et{constructor(t){this.parser=t,this.name=N.KHR_MATERIALS_VOLUME}getMaterialType(t){const s=this.parser.json.materials[t];return!s.extensions||!s.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(t,e){const s=this.parser,n=s.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];e.thickness=r.thicknessFactor!==void 0?r.thicknessFactor:0,r.thicknessTexture!==void 0&&i.push(s.assignTexture(e,"thicknessMap",r.thicknessTexture)),e.attenuationDistance=r.attenuationDistance||1/0;const a=r.attenuationColor||[1,1,1];return e.attenuationColor=new f.Color().setRGB(a[0],a[1],a[2],f.LinearSRGBColorSpace),Promise.all(i)}}class Bt{constructor(t){this.parser=t,this.name=N.KHR_MATERIALS_IOR}getMaterialType(t){const s=this.parser.json.materials[t];return!s.extensions||!s.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(t,e){const n=this.parser.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=n.extensions[this.name];return e.ior=i.ior!==void 0?i.ior:1.5,Promise.resolve()}}class Gt{constructor(t){this.parser=t,this.name=N.KHR_MATERIALS_SPECULAR}getMaterialType(t){const s=this.parser.json.materials[t];return!s.extensions||!s.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(t,e){const s=this.parser,n=s.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];e.specularIntensity=r.specularFactor!==void 0?r.specularFactor:1,r.specularTexture!==void 0&&i.push(s.assignTexture(e,"specularIntensityMap",r.specularTexture));const a=r.specularColorFactor||[1,1,1];return e.specularColor=new f.Color().setRGB(a[0],a[1],a[2],f.LinearSRGBColorSpace),r.specularColorTexture!==void 0&&i.push(s.assignTexture(e,"specularColorMap",r.specularColorTexture,f.SRGBColorSpace)),Promise.all(i)}}class jt{constructor(t){this.parser=t,this.name=N.EXT_MATERIALS_BUMP}getMaterialType(t){const s=this.parser.json.materials[t];return!s.extensions||!s.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(t,e){const s=this.parser,n=s.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];return e.bumpScale=r.bumpFactor!==void 0?r.bumpFactor:1,r.bumpTexture!==void 0&&i.push(s.assignTexture(e,"bumpMap",r.bumpTexture)),Promise.all(i)}}class Vt{constructor(t){this.parser=t,this.name=N.KHR_MATERIALS_ANISOTROPY}getMaterialType(t){const s=this.parser.json.materials[t];return!s.extensions||!s.extensions[this.name]?null:f.MeshPhysicalMaterial}extendMaterialParams(t,e){const s=this.parser,n=s.json.materials[t];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const i=[],r=n.extensions[this.name];return r.anisotropyStrength!==void 0&&(e.anisotropy=r.anisotropyStrength),r.anisotropyRotation!==void 0&&(e.anisotropyRotation=r.anisotropyRotation),r.anisotropyTexture!==void 0&&i.push(s.assignTexture(e,"anisotropyMap",r.anisotropyTexture)),Promise.all(i)}}class Kt{constructor(t){this.parser=t,this.name=N.KHR_TEXTURE_BASISU}loadTexture(t){const e=this.parser,s=e.json,n=s.textures[t];if(!n.extensions||!n.extensions[this.name])return null;const i=n.extensions[this.name],r=e.options.ktx2Loader;if(!r){if(s.extensionsRequired&&s.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return e.loadTextureImage(t,i.source,r)}}class Wt{constructor(t){this.parser=t,this.name=N.EXT_TEXTURE_WEBP}loadTexture(t){const e=this.name,s=this.parser,n=s.json,i=n.textures[t];if(!i.extensions||!i.extensions[e])return null;const r=i.extensions[e],a=n.images[r.source];let o=s.textureLoader;if(a.uri){const c=s.options.manager.getHandler(a.uri);c!==null&&(o=c)}return s.loadTextureImage(t,r.source,o)}}class zt{constructor(t){this.parser=t,this.name=N.EXT_TEXTURE_AVIF}loadTexture(t){const e=this.name,s=this.parser,n=s.json,i=n.textures[t];if(!i.extensions||!i.extensions[e])return null;const r=i.extensions[e],a=n.images[r.source];let o=s.textureLoader;if(a.uri){const c=s.options.manager.getHandler(a.uri);c!==null&&(o=c)}return s.loadTextureImage(t,r.source,o)}}class Xt{constructor(t){this.name=N.EXT_MESHOPT_COMPRESSION,this.parser=t}loadBufferView(t){const e=this.parser.json,s=e.bufferViews[t];if(s.extensions&&s.extensions[this.name]){const n=s.extensions[this.name],i=this.parser.getDependency("buffer",n.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.supported){if(e.extensionsRequired&&e.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return i.then(function(a){const o=n.byteOffset||0,c=n.byteLength||0,l=n.count,u=n.byteStride,h=new Uint8Array(a,o,c);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(l,u,h,n.mode,n.filter).then(function(p){return p.buffer}):r.ready.then(function(){const p=new ArrayBuffer(l*u);return r.decodeGltfBuffer(new Uint8Array(p),l,u,h,n.mode,n.filter),p})})}else return null}}class qt{constructor(t){this.name=N.EXT_MESH_GPU_INSTANCING,this.parser=t}createNodeMesh(t){const e=this.parser.json,s=e.nodes[t];if(!s.extensions||!s.extensions[this.name]||s.mesh===void 0)return null;const n=e.meshes[s.mesh];for(const c of n.primitives)if(c.mode!==ie.TRIANGLES&&c.mode!==ie.TRIANGLE_STRIP&&c.mode!==ie.TRIANGLE_FAN&&c.mode!==void 0)return null;const r=s.extensions[this.name].attributes,a=[],o={};for(const c in r)a.push(this.parser.getDependency("accessor",r[c]).then(l=>(o[c]=l,o[c])));return a.length<1?null:(a.push(this.parser.createNodeMesh(t)),Promise.all(a).then(c=>{const l=c.pop(),u=l.isGroup?l.children:[l],h=c[0].count,p=[];for(const _ of u){const b=new f.Matrix4,w=new f.Vector3,L=new f.Quaternion,E=new f.Vector3(1,1,1),P=new f.InstancedMesh(_.geometry,_.material,h);for(let M=0;M<h;M++)o.TRANSLATION&&w.fromBufferAttribute(o.TRANSLATION,M),o.ROTATION&&L.fromBufferAttribute(o.ROTATION,M),o.SCALE&&E.fromBufferAttribute(o.SCALE,M),P.setMatrixAt(M,b.compose(w,L,E));for(const M in o)if(M==="_COLOR_0"){const U=o[M];P.instanceColor=new f.InstancedBufferAttribute(U.array,U.itemSize,U.normalized)}else M!=="TRANSLATION"&&M!=="ROTATION"&&M!=="SCALE"&&_.geometry.setAttribute(M,o[M]);f.Object3D.prototype.copy.call(P,_),this.parser.assignFinalMaterial(P),p.push(P)}return l.isGroup?(l.clear(),l.add(...p),l):p[0]}))}}const ct="glTF",Ne=12,lt={JSON:1313821514,BIN:5130562};class $t{constructor(t){this.name=N.KHR_BINARY_GLTF,this.content=null,this.body=null;const e=new DataView(t,0,Ne),s=new TextDecoder;if(this.header={magic:s.decode(new Uint8Array(t.slice(0,4))),version:e.getUint32(4,!0),length:e.getUint32(8,!0)},this.header.magic!==ct)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const n=this.header.length-Ne,i=new DataView(t,Ne);let r=0;for(;r<n;){const a=i.getUint32(r,!0);r+=4;const o=i.getUint32(r,!0);if(r+=4,o===lt.JSON){const c=new Uint8Array(t,Ne+r,a);this.content=s.decode(c)}else if(o===lt.BIN){const c=Ne+r;this.body=t.slice(c,c+a)}r+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class Yt{constructor(t,e){if(!e)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=N.KHR_DRACO_MESH_COMPRESSION,this.json=t,this.dracoLoader=e,this.dracoLoader.preload()}decodePrimitive(t,e){const s=this.json,n=this.dracoLoader,i=t.extensions[this.name].bufferView,r=t.extensions[this.name].attributes,a={},o={},c={};for(const l in r){const u=Xe[l]||l.toLowerCase();a[u]=r[l]}for(const l in t.attributes){const u=Xe[l]||l.toLowerCase();if(r[l]!==void 0){const h=s.accessors[t.attributes[l]],p=Me[h.componentType];c[u]=p.name,o[u]=h.normalized===!0}}return e.getDependency("bufferView",i).then(function(l){return new Promise(function(u,h){n.decodeDracoFile(l,function(p){for(const _ in p.attributes){const b=p.attributes[_],w=o[_];w!==void 0&&(b.normalized=w)}u(p)},a,c,f.LinearSRGBColorSpace,h)})})}}class Ht{constructor(){this.name=N.KHR_TEXTURE_TRANSFORM}extendTexture(t,e){return(e.texCoord===void 0||e.texCoord===t.channel)&&e.offset===void 0&&e.rotation===void 0&&e.scale===void 0||(t=t.clone(),e.texCoord!==void 0&&(t.channel=e.texCoord),e.offset!==void 0&&t.offset.fromArray(e.offset),e.rotation!==void 0&&(t.rotation=e.rotation),e.scale!==void 0&&t.repeat.fromArray(e.scale),t.needsUpdate=!0),t}}class Jt{constructor(){this.name=N.KHR_MESH_QUANTIZATION}}class ut extends f.Interpolant{constructor(t,e,s,n){super(t,e,s,n)}copySampleValue_(t){const e=this.resultBuffer,s=this.sampleValues,n=this.valueSize,i=t*n*3+n;for(let r=0;r!==n;r++)e[r]=s[i+r];return e}interpolate_(t,e,s,n){const i=this.resultBuffer,r=this.sampleValues,a=this.valueSize,o=a*2,c=a*3,l=n-e,u=(s-e)/l,h=u*u,p=h*u,_=t*c,b=_-c,w=-2*p+3*h,L=p-h,E=1-w,P=L-h+u;for(let M=0;M!==a;M++){const U=r[b+M+a],D=r[b+M+o]*l,G=r[_+M+a],j=r[_+M]*l;i[M]=E*U+P*D+w*G+L*j}return i}}const Qt=new f.Quaternion;class Zt extends ut{interpolate_(t,e,s,n){const i=super.interpolate_(t,e,s,n);return Qt.fromArray(i).normalize().toArray(i),i}}const ie={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Me={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},dt={9728:f.NearestFilter,9729:f.LinearFilter,9984:f.NearestMipmapNearestFilter,9985:f.LinearMipmapNearestFilter,9986:f.NearestMipmapLinearFilter,9987:f.LinearMipmapLinearFilter},ft={33071:f.ClampToEdgeWrapping,33648:f.MirroredRepeatWrapping,10497:f.RepeatWrapping},ze={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Xe={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"},we={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},en={CUBICSPLINE:void 0,LINEAR:f.InterpolateLinear,STEP:f.InterpolateDiscrete},qe={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function tn(d){return d.DefaultMaterial===void 0&&(d.DefaultMaterial=new f.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:f.FrontSide})),d.DefaultMaterial}function ye(d,t,e){for(const s in e.extensions)d[s]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[s]=e.extensions[s])}function de(d,t){t.extras!==void 0&&(typeof t.extras=="object"?Object.assign(d.userData,t.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras))}function nn(d,t,e){let s=!1,n=!1,i=!1;for(let c=0,l=t.length;c<l;c++){const u=t[c];if(u.POSITION!==void 0&&(s=!0),u.NORMAL!==void 0&&(n=!0),u.COLOR_0!==void 0&&(i=!0),s&&n&&i)break}if(!s&&!n&&!i)return Promise.resolve(d);const r=[],a=[],o=[];for(let c=0,l=t.length;c<l;c++){const u=t[c];if(s){const h=u.POSITION!==void 0?e.getDependency("accessor",u.POSITION):d.attributes.position;r.push(h)}if(n){const h=u.NORMAL!==void 0?e.getDependency("accessor",u.NORMAL):d.attributes.normal;a.push(h)}if(i){const h=u.COLOR_0!==void 0?e.getDependency("accessor",u.COLOR_0):d.attributes.color;o.push(h)}}return Promise.all([Promise.all(r),Promise.all(a),Promise.all(o)]).then(function(c){const l=c[0],u=c[1],h=c[2];return s&&(d.morphAttributes.position=l),n&&(d.morphAttributes.normal=u),i&&(d.morphAttributes.color=h),d.morphTargetsRelative=!0,d})}function sn(d,t){if(d.updateMorphTargets(),t.weights!==void 0)for(let e=0,s=t.weights.length;e<s;e++)d.morphTargetInfluences[e]=t.weights[e];if(t.extras&&Array.isArray(t.extras.targetNames)){const e=t.extras.targetNames;if(d.morphTargetInfluences.length===e.length){d.morphTargetDictionary={};for(let s=0,n=e.length;s<n;s++)d.morphTargetDictionary[e[s]]=s}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function rn(d){let t;const e=d.extensions&&d.extensions[N.KHR_DRACO_MESH_COMPRESSION];if(e?t="draco:"+e.bufferView+":"+e.indices+":"+$e(e.attributes):t=d.indices+":"+$e(d.attributes)+":"+d.mode,d.targets!==void 0)for(let s=0,n=d.targets.length;s<n;s++)t+=":"+$e(d.targets[s]);return t}function $e(d){let t="";const e=Object.keys(d).sort();for(let s=0,n=e.length;s<n;s++)t+=e[s]+":"+d[e[s]]+";";return t}function Ye(d){switch(d){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function on(d){return d.search(/\.jpe?g($|\?)/i)>0||d.search(/^data\:image\/jpeg/)===0?"image/jpeg":d.search(/\.webp($|\?)/i)>0||d.search(/^data\:image\/webp/)===0?"image/webp":d.search(/\.ktx2($|\?)/i)>0||d.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const an=new f.Matrix4;class cn{constructor(t={},e={}){this.json=t,this.extensions={},this.plugins={},this.options=e,this.cache=new It,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 s=!1,n=-1,i=!1,r=-1;if(typeof navigator<"u"){const a=navigator.userAgent;s=/^((?!chrome|android).)*safari/i.test(a)===!0;const o=a.match(/Version\/(\d+)/);n=s&&o?parseInt(o[1],10):-1,i=a.indexOf("Firefox")>-1,r=i?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||s&&n<17||i&&r<98?this.textureLoader=new f.TextureLoader(this.options.manager):this.textureLoader=new f.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new f.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(t){this.extensions=t}setPlugins(t){this.plugins=t}parse(t,e){const s=this,n=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(r){return r._markDefs&&r._markDefs()}),Promise.all(this._invokeAll(function(r){return r.beforeRoot&&r.beforeRoot()})).then(function(){return Promise.all([s.getDependencies("scene"),s.getDependencies("animation"),s.getDependencies("camera")])}).then(function(r){const a={scene:r[0][n.scene||0],scenes:r[0],animations:r[1],cameras:r[2],asset:n.asset,parser:s,userData:{}};return ye(i,a,n),de(a,n),Promise.all(s._invokeAll(function(o){return o.afterRoot&&o.afterRoot(a)})).then(function(){for(const o of a.scenes)o.updateMatrixWorld();t(a)})}).catch(e)}_markDefs(){const t=this.json.nodes||[],e=this.json.skins||[],s=this.json.meshes||[];for(let n=0,i=e.length;n<i;n++){const r=e[n].joints;for(let a=0,o=r.length;a<o;a++)t[r[a]].isBone=!0}for(let n=0,i=t.length;n<i;n++){const r=t[n];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(s[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(t,e){e!==void 0&&(t.refs[e]===void 0&&(t.refs[e]=t.uses[e]=0),t.refs[e]++)}_getNodeRef(t,e,s){if(t.refs[e]<=1)return s;const n=s.clone(),i=(r,a)=>{const o=this.associations.get(r);o!=null&&this.associations.set(a,o);for(const[c,l]of r.children.entries())i(l,a.children[c])};return i(s,n),n.name+="_instance_"+t.uses[e]++,n}_invokeOne(t){const e=Object.values(this.plugins);e.push(this);for(let s=0;s<e.length;s++){const n=t(e[s]);if(n)return n}return null}_invokeAll(t){const e=Object.values(this.plugins);e.unshift(this);const s=[];for(let n=0;n<e.length;n++){const i=t(e[n]);i&&s.push(i)}return s}getDependency(t,e){const s=t+":"+e;let n=this.cache.get(s);if(!n){switch(t){case"scene":n=this.loadScene(e);break;case"node":n=this._invokeOne(function(i){return i.loadNode&&i.loadNode(e)});break;case"mesh":n=this._invokeOne(function(i){return i.loadMesh&&i.loadMesh(e)});break;case"accessor":n=this.loadAccessor(e);break;case"bufferView":n=this._invokeOne(function(i){return i.loadBufferView&&i.loadBufferView(e)});break;case"buffer":n=this.loadBuffer(e);break;case"material":n=this._invokeOne(function(i){return i.loadMaterial&&i.loadMaterial(e)});break;case"texture":n=this._invokeOne(function(i){return i.loadTexture&&i.loadTexture(e)});break;case"skin":n=this.loadSkin(e);break;case"animation":n=this._invokeOne(function(i){return i.loadAnimation&&i.loadAnimation(e)});break;case"camera":n=this.loadCamera(e);break;default:if(n=this._invokeOne(function(i){return i!=this&&i.getDependency&&i.getDependency(t,e)}),!n)throw new Error("Unknown type: "+t);break}this.cache.add(s,n)}return n}getDependencies(t){let e=this.cache.get(t);if(!e){const s=this,n=this.json[t+(t==="mesh"?"es":"s")]||[];e=Promise.all(n.map(function(i,r){return s.getDependency(t,r)})),this.cache.add(t,e)}return e}loadBuffer(t){const e=this.json.buffers[t],s=this.fileLoader;if(e.type&&e.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+e.type+" buffer type is not supported.");if(e.uri===void 0&&t===0)return Promise.resolve(this.extensions[N.KHR_BINARY_GLTF].body);const n=this.options;return new Promise(function(i,r){s.load(f.LoaderUtils.resolveURL(e.uri,n.path),i,void 0,function(){r(new Error('THREE.GLTFLoader: Failed to load buffer "'+e.uri+'".'))})})}loadBufferView(t){const e=this.json.bufferViews[t];return this.getDependency("buffer",e.buffer).then(function(s){const n=e.byteLength||0,i=e.byteOffset||0;return s.slice(i,i+n)})}loadAccessor(t){const e=this,s=this.json,n=this.json.accessors[t];if(n.bufferView===void 0&&n.sparse===void 0){const r=ze[n.type],a=Me[n.componentType],o=n.normalized===!0,c=new a(n.count*r);return Promise.resolve(new f.BufferAttribute(c,r,o))}const i=[];return n.bufferView!==void 0?i.push(this.getDependency("bufferView",n.bufferView)):i.push(null),n.sparse!==void 0&&(i.push(this.getDependency("bufferView",n.sparse.indices.bufferView)),i.push(this.getDependency("bufferView",n.sparse.values.bufferView))),Promise.all(i).then(function(r){const a=r[0],o=ze[n.type],c=Me[n.componentType],l=c.BYTES_PER_ELEMENT,u=l*o,h=n.byteOffset||0,p=n.bufferView!==void 0?s.bufferViews[n.bufferView].byteStride:void 0,_=n.normalized===!0;let b,w;if(p&&p!==u){const L=Math.floor(h/p),E="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+L+":"+n.count;let P=e.cache.get(E);P||(b=new c(a,L*p,n.count*p/l),P=new f.InterleavedBuffer(b,p/l),e.cache.add(E,P)),w=new f.InterleavedBufferAttribute(P,o,h%p/l,_)}else a===null?b=new c(n.count*o):b=new c(a,h,n.count*o),w=new f.BufferAttribute(b,o,_);if(n.sparse!==void 0){const L=ze.SCALAR,E=Me[n.sparse.indices.componentType],P=n.sparse.indices.byteOffset||0,M=n.sparse.values.byteOffset||0,U=new E(r[1],P,n.sparse.count*L),D=new c(r[2],M,n.sparse.count*o);a!==null&&(w=new f.BufferAttribute(w.array.slice(),w.itemSize,w.normalized)),w.normalized=!1;for(let G=0,j=U.length;G<j;G++){const F=U[G];if(w.setX(F,D[G*o]),o>=2&&w.setY(F,D[G*o+1]),o>=3&&w.setZ(F,D[G*o+2]),o>=4&&w.setW(F,D[G*o+3]),o>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}w.normalized=_}return w})}loadTexture(t){const e=this.json,s=this.options,i=e.textures[t].source,r=e.images[i];let a=this.textureLoader;if(r.uri){const o=s.manager.getHandler(r.uri);o!==null&&(a=o)}return this.loadTextureImage(t,i,a)}loadTextureImage(t,e,s){const n=this,i=this.json,r=i.textures[t],a=i.images[e],o=(a.uri||a.bufferView)+":"+r.sampler;if(this.textureCache[o])return this.textureCache[o];const c=this.loadImageSource(e,s).then(function(l){l.flipY=!1,l.name=r.name||a.name||"",l.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(l.name=a.uri);const h=(i.samplers||{})[r.sampler]||{};return l.magFilter=dt[h.magFilter]||f.LinearFilter,l.minFilter=dt[h.minFilter]||f.LinearMipmapLinearFilter,l.wrapS=ft[h.wrapS]||f.RepeatWrapping,l.wrapT=ft[h.wrapT]||f.RepeatWrapping,l.generateMipmaps=!l.isCompressedTexture&&l.minFilter!==f.NearestFilter&&l.minFilter!==f.LinearFilter,n.associations.set(l,{textures:t}),l}).catch(function(){return null});return this.textureCache[o]=c,c}loadImageSource(t,e){const s=this,n=this.json,i=this.options;if(this.sourceCache[t]!==void 0)return this.sourceCache[t].then(u=>u.clone());const r=n.images[t],a=self.URL||self.webkitURL;let o=r.uri||"",c=!1;if(r.bufferView!==void 0)o=s.getDependency("bufferView",r.bufferView).then(function(u){c=!0;const h=new Blob([u],{type:r.mimeType});return o=a.createObjectURL(h),o});else if(r.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+t+" is missing URI and bufferView");const l=Promise.resolve(o).then(function(u){return new Promise(function(h,p){let _=h;e.isImageBitmapLoader===!0&&(_=function(b){const w=new f.Texture(b);w.needsUpdate=!0,h(w)}),e.load(f.LoaderUtils.resolveURL(u,i.path),_,void 0,p)})}).then(function(u){return c===!0&&a.revokeObjectURL(o),de(u,r),u.userData.mimeType=r.mimeType||on(r.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",o),u});return this.sourceCache[t]=l,l}assignTexture(t,e,s,n){const i=this;return this.getDependency("texture",s.index).then(function(r){if(!r)return null;if(s.texCoord!==void 0&&s.texCoord>0&&(r=r.clone(),r.channel=s.texCoord),i.extensions[N.KHR_TEXTURE_TRANSFORM]){const a=s.extensions!==void 0?s.extensions[N.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const o=i.associations.get(r);r=i.extensions[N.KHR_TEXTURE_TRANSFORM].extendTexture(r,a),i.associations.set(r,o)}}return n!==void 0&&(r.colorSpace=n),t[e]=r,r})}assignFinalMaterial(t){const e=t.geometry;let s=t.material;const n=e.attributes.tangent===void 0,i=e.attributes.color!==void 0,r=e.attributes.normal===void 0;if(t.isPoints){const a="PointsMaterial:"+s.uuid;let o=this.cache.get(a);o||(o=new f.PointsMaterial,f.Material.prototype.copy.call(o,s),o.color.copy(s.color),o.map=s.map,o.sizeAttenuation=!1,this.cache.add(a,o)),s=o}else if(t.isLine){const a="LineBasicMaterial:"+s.uuid;let o=this.cache.get(a);o||(o=new f.LineBasicMaterial,f.Material.prototype.copy.call(o,s),o.color.copy(s.color),o.map=s.map,this.cache.add(a,o)),s=o}if(n||i||r){let a="ClonedMaterial:"+s.uuid+":";n&&(a+="derivative-tangents:"),i&&(a+="vertex-colors:"),r&&(a+="flat-shading:");let o=this.cache.get(a);o||(o=s.clone(),i&&(o.vertexColors=!0),r&&(o.flatShading=!0),n&&(o.normalScale&&(o.normalScale.y*=-1),o.clearcoatNormalScale&&(o.clearcoatNormalScale.y*=-1)),this.cache.add(a,o),this.associations.set(o,this.associations.get(s))),s=o}t.material=s}getMaterialType(){return f.MeshStandardMaterial}loadMaterial(t){const e=this,s=this.json,n=this.extensions,i=s.materials[t];let r;const a={},o=i.extensions||{},c=[];if(o[N.KHR_MATERIALS_UNLIT]){const u=n[N.KHR_MATERIALS_UNLIT];r=u.getMaterialType(),c.push(u.extendParams(a,i,e))}else{const u=i.pbrMetallicRoughness||{};if(a.color=new f.Color(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){const h=u.baseColorFactor;a.color.setRGB(h[0],h[1],h[2],f.LinearSRGBColorSpace),a.opacity=h[3]}u.baseColorTexture!==void 0&&c.push(e.assignTexture(a,"map",u.baseColorTexture,f.SRGBColorSpace)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(c.push(e.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),c.push(e.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),r=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(t)}),c.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(t,a)})))}i.doubleSided===!0&&(a.side=f.DoubleSide);const l=i.alphaMode||qe.OPAQUE;if(l===qe.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,l===qe.MASK&&(a.alphaTest=i.alphaCutoff!==void 0?i.alphaCutoff:.5)),i.normalTexture!==void 0&&r!==f.MeshBasicMaterial&&(c.push(e.assignTexture(a,"normalMap",i.normalTexture)),a.normalScale=new f.Vector2(1,1),i.normalTexture.scale!==void 0)){const u=i.normalTexture.scale;a.normalScale.set(u,u)}if(i.occlusionTexture!==void 0&&r!==f.MeshBasicMaterial&&(c.push(e.assignTexture(a,"aoMap",i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&r!==f.MeshBasicMaterial){const u=i.emissiveFactor;a.emissive=new f.Color().setRGB(u[0],u[1],u[2],f.LinearSRGBColorSpace)}return i.emissiveTexture!==void 0&&r!==f.MeshBasicMaterial&&c.push(e.assignTexture(a,"emissiveMap",i.emissiveTexture,f.SRGBColorSpace)),Promise.all(c).then(function(){const u=new r(a);return i.name&&(u.name=i.name),de(u,i),e.associations.set(u,{materials:t}),i.extensions&&ye(n,u,i),u})}createUniqueName(t){const e=f.PropertyBinding.sanitizeNodeName(t||"");return e in this.nodeNamesUsed?e+"_"+ ++this.nodeNamesUsed[e]:(this.nodeNamesUsed[e]=0,e)}loadGeometries(t){const e=this,s=this.extensions,n=this.primitiveCache;function i(a){return s[N.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,e).then(function(o){return ht(o,a,e)})}const r=[];for(let a=0,o=t.length;a<o;a++){const c=t[a],l=rn(c),u=n[l];if(u)r.push(u.promise);else{let h;c.extensions&&c.extensions[N.KHR_DRACO_MESH_COMPRESSION]?h=i(c):h=ht(new f.BufferGeometry,c,e),n[l]={primitive:c,promise:h},r.push(h)}}return Promise.all(r)}loadMesh(t){const e=this,s=this.json,n=this.extensions,i=s.meshes[t],r=i.primitives,a=[];for(let o=0,c=r.length;o<c;o++){const l=r[o].material===void 0?tn(this.cache):this.getDependency("material",r[o].material);a.push(l)}return a.push(e.loadGeometries(r)),Promise.all(a).then(function(o){const c=o.slice(0,o.length-1),l=o[o.length-1],u=[];for(let p=0,_=l.length;p<_;p++){const b=l[p],w=r[p];let L;const E=c[p];if(w.mode===ie.TRIANGLES||w.mode===ie.TRIANGLE_STRIP||w.mode===ie.TRIANGLE_FAN||w.mode===void 0)L=i.isSkinnedMesh===!0?new f.SkinnedMesh(b,E):new f.Mesh(b,E),L.isSkinnedMesh===!0&&L.normalizeSkinWeights(),w.mode===ie.TRIANGLE_STRIP?L.geometry=at(L.geometry,f.TriangleStripDrawMode):w.mode===ie.TRIANGLE_FAN&&(L.geometry=at(L.geometry,f.TriangleFanDrawMode));else if(w.mode===ie.LINES)L=new f.LineSegments(b,E);else if(w.mode===ie.LINE_STRIP)L=new f.Line(b,E);else if(w.mode===ie.LINE_LOOP)L=new f.LineLoop(b,E);else if(w.mode===ie.POINTS)L=new f.Points(b,E);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+w.mode);Object.keys(L.geometry.morphAttributes).length>0&&sn(L,i),L.name=e.createUniqueName(i.name||"mesh_"+t),de(L,i),w.extensions&&ye(n,L,w),e.assignFinalMaterial(L),u.push(L)}for(let p=0,_=u.length;p<_;p++)e.associations.set(u[p],{meshes:t,primitives:p});if(u.length===1)return i.extensions&&ye(n,u[0],i),u[0];const h=new f.Group;i.extensions&&ye(n,h,i),e.associations.set(h,{meshes:t});for(let p=0,_=u.length;p<_;p++)h.add(u[p]);return h})}loadCamera(t){let e;const s=this.json.cameras[t],n=s[s.type];if(!n){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return s.type==="perspective"?e=new f.PerspectiveCamera(f.MathUtils.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):s.type==="orthographic"&&(e=new f.OrthographicCamera(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),s.name&&(e.name=this.createUniqueName(s.name)),de(e,s),Promise.resolve(e)}loadSkin(t){const e=this.json.skins[t],s=[];for(let n=0,i=e.joints.length;n<i;n++)s.push(this._loadNodeShallow(e.joints[n]));return e.inverseBindMatrices!==void 0?s.push(this.getDependency("accessor",e.inverseBindMatrices)):s.push(null),Promise.all(s).then(function(n){const i=n.pop(),r=n,a=[],o=[];for(let c=0,l=r.length;c<l;c++){const u=r[c];if(u){a.push(u);const h=new f.Matrix4;i!==null&&h.fromArray(i.array,c*16),o.push(h)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',e.joints[c])}return new f.Skeleton(a,o)})}loadAnimation(t){const e=this.json,s=this,n=e.animations[t],i=n.name?n.name:"animation_"+t,r=[],a=[],o=[],c=[],l=[];for(let u=0,h=n.channels.length;u<h;u++){const p=n.channels[u],_=n.samplers[p.sampler],b=p.target,w=b.node,L=n.parameters!==void 0?n.parameters[_.input]:_.input,E=n.parameters!==void 0?n.parameters[_.output]:_.output;b.node!==void 0&&(r.push(this.getDependency("node",w)),a.push(this.getDependency("accessor",L)),o.push(this.getDependency("accessor",E)),c.push(_),l.push(b))}return Promise.all([Promise.all(r),Promise.all(a),Promise.all(o),Promise.all(c),Promise.all(l)]).then(function(u){const h=u[0],p=u[1],_=u[2],b=u[3],w=u[4],L=[];for(let P=0,M=h.length;P<M;P++){const U=h[P],D=p[P],G=_[P],j=b[P],F=w[P];if(U===void 0)continue;U.updateMatrix&&U.updateMatrix();const B=s._createAnimationTracks(U,D,G,j,F);if(B)for(let Z=0;Z<B.length;Z++)L.push(B[Z])}const E=new f.AnimationClip(i,void 0,L);return de(E,n),E})}createNodeMesh(t){const e=this.json,s=this,n=e.nodes[t];return n.mesh===void 0?null:s.getDependency("mesh",n.mesh).then(function(i){const r=s._getNodeRef(s.meshCache,n.mesh,i);return n.weights!==void 0&&r.traverse(function(a){if(a.isMesh)for(let o=0,c=n.weights.length;o<c;o++)a.morphTargetInfluences[o]=n.weights[o]}),r})}loadNode(t){const e=this.json,s=this,n=e.nodes[t],i=s._loadNodeShallow(t),r=[],a=n.children||[];for(let c=0,l=a.length;c<l;c++)r.push(s.getDependency("node",a[c]));const o=n.skin===void 0?Promise.resolve(null):s.getDependency("skin",n.skin);return Promise.all([i,Promise.all(r),o]).then(function(c){const l=c[0],u=c[1],h=c[2];h!==null&&l.traverse(function(p){p.isSkinnedMesh&&p.bind(h,an)});for(let p=0,_=u.length;p<_;p++)l.add(u[p]);return l})}_loadNodeShallow(t){const e=this.json,s=this.extensions,n=this;if(this.nodeCache[t]!==void 0)return this.nodeCache[t];const i=e.nodes[t],r=i.name?n.createUniqueName(i.name):"",a=[],o=n._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(t)});return o&&a.push(o),i.camera!==void 0&&a.push(n.getDependency("camera",i.camera).then(function(c){return n._getNodeRef(n.cameraCache,i.camera,c)})),n._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(t)}).forEach(function(c){a.push(c)}),this.nodeCache[t]=Promise.all(a).then(function(c){let l;if(i.isBone===!0?l=new f.Bone:c.length>1?l=new f.Group:c.length===1?l=c[0]:l=new f.Object3D,l!==c[0])for(let u=0,h=c.length;u<h;u++)l.add(c[u]);if(i.name&&(l.userData.name=i.name,l.name=r),de(l,i),i.extensions&&ye(s,l,i),i.matrix!==void 0){const u=new f.Matrix4;u.fromArray(i.matrix),l.applyMatrix4(u)}else i.translation!==void 0&&l.position.fromArray(i.translation),i.rotation!==void 0&&l.quaternion.fromArray(i.rotation),i.scale!==void 0&&l.scale.fromArray(i.scale);if(!n.associations.has(l))n.associations.set(l,{});else if(i.mesh!==void 0&&n.meshCache.refs[i.mesh]>1){const u=n.associations.get(l);n.associations.set(l,{...u})}return n.associations.get(l).nodes=t,l}),this.nodeCache[t]}loadScene(t){const e=this.extensions,s=this.json.scenes[t],n=this,i=new f.Group;s.name&&(i.name=n.createUniqueName(s.name)),de(i,s),s.extensions&&ye(e,i,s);const r=s.nodes||[],a=[];for(let o=0,c=r.length;o<c;o++)a.push(n.getDependency("node",r[o]));return Promise.all(a).then(function(o){for(let l=0,u=o.length;l<u;l++)i.add(o[l]);const c=l=>{const u=new Map;for(const[h,p]of n.associations)(h instanceof f.Material||h instanceof f.Texture)&&u.set(h,p);return l.traverse(h=>{const p=n.associations.get(h);p!=null&&u.set(h,p)}),u};return n.associations=c(i),i})}_createAnimationTracks(t,e,s,n,i){const r=[],a=t.name?t.name:t.uuid,o=[];we[i.path]===we.weights?t.traverse(function(h){h.morphTargetInfluences&&o.push(h.name?h.name:h.uuid)}):o.push(a);let c;switch(we[i.path]){case we.weights:c=f.NumberKeyframeTrack;break;case we.rotation:c=f.QuaternionKeyframeTrack;break;case we.translation:case we.scale:c=f.VectorKeyframeTrack;break;default:s.itemSize===1?c=f.NumberKeyframeTrack:c=f.VectorKeyframeTrack;break}const l=n.interpolation!==void 0?en[n.interpolation]:f.InterpolateLinear,u=this._getArrayFromAccessor(s);for(let h=0,p=o.length;h<p;h++){const _=new c(o[h]+"."+we[i.path],e.array,u,l);n.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(_),r.push(_)}return r}_getArrayFromAccessor(t){let e=t.array;if(t.normalized){const s=Ye(e.constructor),n=new Float32Array(e.length);for(let i=0,r=e.length;i<r;i++)n[i]=e[i]*s;e=n}return e}_createCubicSplineTrackInterpolant(t){t.createInterpolant=function(s){const n=this instanceof f.QuaternionKeyframeTrack?Zt:ut;return new n(this.times,this.values,this.getValueSize()/3,s)},t.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function ln(d,t,e){const s=t.attributes,n=new f.Box3;if(s.POSITION!==void 0){const a=e.json.accessors[s.POSITION],o=a.min,c=a.max;if(o!==void 0&&c!==void 0){if(n.set(new f.Vector3(o[0],o[1],o[2]),new f.Vector3(c[0],c[1],c[2])),a.normalized){const l=Ye(Me[a.componentType]);n.min.multiplyScalar(l),n.max.multiplyScalar(l)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const i=t.targets;if(i!==void 0){const a=new f.Vector3,o=new f.Vector3;for(let c=0,l=i.length;c<l;c++){const u=i[c];if(u.POSITION!==void 0){const h=e.json.accessors[u.POSITION],p=h.min,_=h.max;if(p!==void 0&&_!==void 0){if(o.setX(Math.max(Math.abs(p[0]),Math.abs(_[0]))),o.setY(Math.max(Math.abs(p[1]),Math.abs(_[1]))),o.setZ(Math.max(Math.abs(p[2]),Math.abs(_[2]))),h.normalized){const b=Ye(Me[h.componentType]);o.multiplyScalar(b)}a.max(o)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(a)}d.boundingBox=n;const r=new f.Sphere;n.getCenter(r.center),r.radius=n.min.distanceTo(n.max)/2,d.boundingSphere=r}function ht(d,t,e){const s=t.attributes,n=[];function i(r,a){return e.getDependency("accessor",r).then(function(o){d.setAttribute(a,o)})}for(const r in s){const a=Xe[r]||r.toLowerCase();a in d.attributes||n.push(i(s[r],a))}if(t.indices!==void 0&&!d.index){const r=e.getDependency("accessor",t.indices).then(function(a){d.setIndex(a)});n.push(r)}return f.ColorManagement.workingColorSpace!==f.LinearSRGBColorSpace&&"COLOR_0"in s&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${f.ColorManagement.workingColorSpace}" not supported.`),de(d,t),ln(d,t,e),Promise.all(n).then(function(){return t.targets!==void 0?nn(d,t.targets,e):d})}const Y=(...d)=>{},un=(...d)=>{},pt=({analyser:d})=>{const t=m.useRef(null),e=m.useRef(null);return m.useEffect(()=>{const s=t.current;if(!s)return;const n=s.getContext("2d",{alpha:!0});if(!n)return;let i,r=null;d&&(d.fftSize=128,r=new Uint8Array(d.frequencyBinCount));const a=()=>{i=requestAnimationFrame(a),(s.width!==s.offsetWidth||s.height!==s.offsetHeight)&&(s.width=s.offsetWidth,s.height=s.offsetHeight);const o=s.width,c=s.height;if(o===0||c===0)return;const l=c/2;n.clearRect(0,0,o,c),n.fillStyle="#1e293b";const u=2,p=u+2,_=o*.95,b=Math.floor(_/p);(!e.current||e.current.length!==b)&&(e.current=new Float32Array(b).fill(2));const w=b*p,L=(o-w)/2;d&&r&&d.getByteFrequencyData(r);const E=r?r.length:0,M=Math.floor(E*.7)/b,U=new Float32Array(b);for(let D=0;D<b;D++){let G=0;if(r&&M>0){const B=Math.floor(D*M),Z=Math.floor((D+1)*M);for(let le=B;le<Z;le++){const me=r[le]||0;me>G&&(G=me)}}G<10&&(G=0);const j=G/255,F=G>0?Math.max(2,Math.pow(j,1.4)*c*.25):2;U[D]=F}for(let D=0;D<b;D++){const G=b-1-D,j=Math.max(U[D],U[G]),F=e.current[D]+(j-e.current[D])*.3;e.current[D]=F;const B=L+D*p,Z=l-F/2;n.beginPath(),n.roundRect?n.roundRect(B,Z,u,F,4):n.fillRect(B,Z,u,F),n.fill()}};return a(),()=>{cancelAnimationFrame(i)}},[d]),S.jsx("canvas",{ref:t,style:{width:"100%",height:"100%",display:"block"}})},mt="https://ai.streamoji.com",dn="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev";async function fn(d){const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(d));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}function hn(d){const[t,e]=m.useState(null);return m.useEffect(()=>{if(!d){e(null);return}let s=!1;return fn(d).then(n=>{if(s)return;const i=`${dn}/${n}.glb`;fetch(i,{method:"HEAD"}).then(r=>{s||e(r.ok?i:null)}).catch(()=>{s||e(null)})}),()=>{s=!0}},[d]),t}const pn=["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"],mn=[{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"}],gn=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"],bn={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},xn=[-.45,1.9,.1],_n={browInnerUp:.2},He=.18,wn=1,Be={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}},yn=[{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:{}}],Sn={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 Tn(d){if(!d)return[{v:"sil",w:1}];const t=d.toLowerCase();return Sn[t]??[{v:"sil",w:1}]}function vn({target:d}){const{camera:t}=We.useThree();return m.useEffect(()=>{t.lookAt(...d)},[t,d]),null}function te(d,t,e){if(!d||!d.morphTargetDictionary)return;const s=d,n=s.morphTargetDictionary,i=s.morphTargetInfluences;if(i)for(const r in n)r.toLowerCase()===t.toLowerCase()&&(i[n[r]]=e)}function gt(d,t=.97){if(!d)return;const e=d;if(e.morphTargetInfluences)for(let s=0;s<e.morphTargetInfluences.length;s++)e.morphTargetInfluences[s]*=t}const An=m.memo(({avatarUrl:d,isPlayingRef:t,visemeQueueRef:e,audioContextRef:s,responseAudioStartTimeRef:n,adjustments:i,mood:r,expression:a,agentResponse:o,isSpeaking:c,nextStartTimeRef:l,stopPlayback:u,setIsSpeaking:h,expressionUrl:p,onExpressionFinished:_})=>{const{scene:b}=Ee.useGLTF(d),w=Ee.useGLTF(pn),L=m.useMemo(()=>w.flatMap(O=>O.animations),[w]),E=Ee.useGLTF(gn),P=m.useMemo(()=>E.flatMap(O=>O.animations),[E]),M=m.useRef(null),U=m.useRef(null),D=m.useRef(null),G=m.useRef([]),[j]=m.useState(()=>new Ce.AnimationMixer(b)),F=m.useRef({}),B=m.useRef(null),Z=m.useRef(0),le=m.useRef(!1),me=m.useRef(0),Se=m.useRef(null);m.useEffect(()=>{if(!(!L||!b)){if(L.forEach((O,k)=>{const T=`idle_${k}`;if(!F.current[T]){const x=j.clipAction(O,b);x.name=T,x.setLoop(Ce.LoopOnce,1),x.clampWhenFinished=!0,F.current[T]=x}}),P.forEach((O,k)=>{const T=`talk_${k}`;if(!F.current[T]){const x=j.clipAction(O,b);x.name=T,x.setLoop(Ce.LoopOnce,1),x.clampWhenFinished=!0,F.current[T]=x}}),L.length>0){const O=F.current.idle_0,k=B.current&&j.existingAction(B.current.getClip());O&&!k&&(O.reset().fadeIn(.5).play(),B.current=O)}return()=>{j.stopAllAction(),F.current={},B.current=null}}},[L,P,b,j]);const Ge=m.useRef("");m.useEffect(()=>{if(!p||!b||p===Ge.current)return;Ge.current=p,Se.current=p,new kt().load(p,k=>{if(k.animations&&k.animations.length>0){const T=k.animations[0],x=j.clipAction(T,b);if(x.name=`EXPR_${p}`,x.setLoop(Ce.LoopOnce,1),x.clampWhenFinished=!0,F.current[`EXPR_${p}`]=x,c&&Se.current===p){const R=B.current;x.reset().fadeIn(.3).play(),R&&R!==x&&R.crossFadeTo(x,.3,!0),B.current=x,Se.current=null}}},void 0,k=>{console.error(`[ANIMATION] Failed to load ${p}`,k)})},[p,b,j,c]),m.useEffect(()=>{const O=k=>{const T=k.action,x=T.name||"";if(x.startsWith("idle_")){const ee=(parseInt(x.split("_")[1])+1)%L.length,X=F.current[`idle_${ee}`];X&&(X.reset().fadeIn(.5).play(),T.crossFadeTo(X,.5,!0),B.current=X)}else if(x.startsWith("EXPR_")){if(c){const R=F.current.talk_0;R&&(R.reset().fadeIn(.5).play(),T.crossFadeTo(R,.5,!0),B.current=R)}else{const R=F.current.idle_0;R&&(R.reset().fadeIn(.5).play(),T.crossFadeTo(R,.5,!0),B.current=R)}_&&_()}else if(x.startsWith("talk_"))if(c){const ee=(parseInt(x.split("_")[1])+1)%P.length,X=F.current[`talk_${ee}`];X&&(X.reset().fadeIn(.3).play(),T.crossFadeTo(X,.3,!0),B.current=X)}else{const R=F.current.idle_0;R&&(R.reset().fadeIn(.5).play(),T.crossFadeTo(R,.5,!0),B.current=R)}};return j.addEventListener("finished",O),()=>j.removeEventListener("finished",O)},[j,L,P,c,_]),m.useEffect(()=>{if(c&&b){const O=B.current,k=O?.name||"";if(k.startsWith("idle_")||k.startsWith("talk_")||k===""){const T=Se.current;if(T){const x=F.current[`EXPR_${T}`];if(x){x.reset().fadeIn(.3).play(),O&&O!==x&&O.crossFadeTo(x,.3,!0),B.current=x,Se.current=null;return}}if(k.startsWith("idle_")||k===""){const x=F.current.talk_0;x&&(x.reset().fadeIn(.5).play(),O&&O.crossFadeTo(x,.5,!0),B.current=x)}}}else if(!c&&b){const O=B.current,k=O?.name||"";if(k.startsWith("talk_")||k.startsWith("EXPR_")){const T=F.current.idle_0;T&&(T.reset().fadeIn(.5).play(),O&&O.crossFadeTo(T,.5,!0),B.current=T)}}},[c,b,p]),m.useEffect(()=>{if(!b)return;b.traverse(T=>{if(T.isMesh&&T.morphTargetDictionary){const x=T.name.toLowerCase();(x.includes("head")||x.includes("avatar"))&&(U.current=T,Y(`[ANIMATION] Found head mesh: ${T.name}`)),x.includes("teeth")&&(D.current=T,Y(`[ANIMATION] Found teeth mesh: ${T.name}`))}});const O=U.current?.morphTargetDictionary;O&&Object.keys(O).filter(T=>T.toLowerCase().includes("brow"));const k=[];b.traverse(T=>{if(T.isMesh){const R=T.morphTargetDictionary;R&&Object.keys(R).some(ee=>ee.toLowerCase().includes("brow"))&&k.push(T)}}),G.current=k,k.length>0&&Y("[ANIMATION] Meshes with brow morphs:",k.length)},[b]);const Je=(O,k=1)=>{const T=`viseme_${O}`.toLowerCase(),x=yn.find(R=>R.key.toLowerCase()===T);if(x)for(const R in x.mix){const ee=x.mix[R]*k;te(U.current,R,ee),te(D.current,R,ee)}},Qe=O=>{const k=Be[O]??Be.neutral;for(const T in k)te(U.current,T,k[T]),te(D.current,T,k[T])};return We.useFrame((O,k)=>{const T=Math.pow(.88,60*k);gt(U.current,T),gt(D.current,T),Qe(r);const x=O.clock.elapsedTime;let R=0;if(Math.floor(x)%5===0&&Math.floor((x-k)%5)!==0){let ne=null;b.traverse(se=>{se.name.toLowerCase().includes("hips")&&(ne=se)});const be=ne?`Hips Y: ${ne.position.y.toFixed(4)}`:"Hips not found";Y(`[ANIMATION] Mixer Time: ${j.time.toFixed(2)}, ${be}`)}if(j.update(k),x>Z.current&&!le.current&&(le.current=!0,me.current=x),le.current){const be=(x-me.current)/.3;if(be>=1)le.current=!1,Z.current=x+2+Math.random()*5;else{const se=be<.5?be*2:(1-be)*2;te(U.current,"eyeBlinkLeft",se),te(U.current,"eyeBlinkRight",se),te(D.current,"eyeBlinkLeft",se),te(D.current,"eyeBlinkRight",se),R=se*_n.browInnerUp}}const ee=Be[r]??Be.neutral,X=ee.browInnerUp??0,Te=ee.browOuterUpLeft??0,Oe=ee.browOuterUpRight??0,ke=x*wn,De=He*Math.sin(ke),Fe=He*.7*Math.sin(ke+.7),bt=He*.7*Math.sin(ke+1.3),Ie=ne=>Math.max(0,Math.min(1,ne)),Pe=Ie(X+De),Ue=Ie(Te+Fe),ge=Ie(Oe+bt),ve=Ie(Pe+R);if(te(U.current,"browInnerUp",ve),te(D.current,"browInnerUp",ve),te(U.current,"browOuterUpLeft",Ue),te(D.current,"browOuterUpLeft",Ue),te(U.current,"browOuterUpRight",ge),te(D.current,"browOuterUpRight",ge),M.current){const ne=t.current?0:i.rotation[1];M.current.rotation.y=Ce.MathUtils.lerp(M.current.rotation.y,ne,.1),M.current.position.set(...i.position),M.current.scale.setScalar(i.scale),M.current.rotation.x=i.rotation[0],M.current.rotation.z=i.rotation[2]}if(t.current&&s.current){const ne=s.current.currentTime,oe=(ne-n.current)*1e3- -150;for(let fe=0;fe<e.current.length;fe++){const ae=e.current[fe];oe>=ae.vtime&&oe<ae.vtime+ae.vduration&&Je(ae.viseme,ae.weight??1)}ne>l.current+.5&&(u(),h(!1))}}),S.jsx("group",{ref:M,children:S.jsx("primitive",{object:b})})});function Ln(d){return d?d.charAt(0).toUpperCase()+d.slice(1).toLowerCase():""}const Mn=({token:d,agentToken:t,onNavigationRequested:e}={})=>{const s=d??t??"",n=hn(s||void 0),[i,r]=m.useState(""),[a,o]=m.useState(""),[c,l]=m.useState("Ready"),[u,h]=m.useState(!1),[p,_]=m.useState(!1),b=m.useRef(!1),w=m.useRef([]),L=m.useRef(0),E=m.useRef(!1),P=m.useRef([]),M=m.useRef(null),U=m.useRef([]);m.useRef([]);const D=m.useRef([]),G=m.useRef(0),j=m.useRef(0),F=m.useRef(0),B=m.useRef(0),[Z,le]=m.useState(null),me=m.useRef(null),[Se,Ge]=m.useState("neutral"),[Je,Qe]=m.useState(""),[O,k]=m.useState(""),[T,x]=m.useState("Chat with us"),[R,ee]=m.useState(null),[X,Te]=m.useState("hidden"),[Oe,ke]=m.useState(""),De=m.useRef(null),Fe=m.useRef(X);Fe.current=X;const[bt,Ie]=m.useState(null),Pe=m.useRef(null),Ue=m.useRef(null),[ge,ve]=m.useState("hidden"),[ne,be]=m.useState(""),se=m.useRef(ge);se.current=ge;const oe=m.useRef(""),fe=m.useRef(!1),ae=m.useRef(""),Re=m.useMemo(()=>c==="Thinking..."||c==="Processing Voice..."?c:R!=null&&R!==""&&R!=="none"&&R!=="<none>"?`Enter ${Ln(R)}`:null,[c,R]),je=Re!=null&&Re!=="";m.useEffect(()=>{const g=Fe.current;if(!(g==="exiting"||g==="entering")){if(g==="hidden"){je&&(ke(Re??""),Te("entering"));return}g==="visible"&&(!je||Re!==Oe)&&(De.current=je?Re:null,Te("exiting"))}},[je,Re,X,Oe]);const In=m.useCallback(()=>{const g=Fe.current;if(g==="exiting"){Te("hidden");const v=De.current;De.current=null,v!=null&&v!==""&&(ke(v),Te("entering"))}else g==="entering"&&Te("visible")},[]),Rn=g=>{if(!g)return;if(g.mood!=null){const y=String(g.mood).toLowerCase();Ge(y)}if(g.expression!=null){const y=String(g.expression).trim();Qe(y);const C=mn.find(V=>V.name.toLowerCase()===y.toLowerCase());Y(`[STREAM] Animation match for "${y}": ${C?C.name:"NONE"}`),k(C?.url??"")}if(g.navigation!=null){const y=String(g.navigation).trim();y!==""&&(e?e(y):window.location.href=y)}const v=g.ask_for||g.lead_capture?.ask_for,A=v?String(v).trim().toLowerCase():"",I=A==="none"||A==="<none>";if(v&&!I){const y=A;ee(y||null),x(y==="email"?"Enter your email":y==="name"?"Enter your name":y==="phone"?"Enter your phone number":"Chat with us")}else(I||g.ask_for===null||g.lead_capture&&g.lead_capture.ask_for===null||g.ask_for==="none")&&(ee(null),T!=="Chat with us"&&x("Chat with us"));g.collected,g.valid},Cn=g=>{const v=g.trim();if(!v)return null;if(v.startsWith("{"))try{return JSON.parse(v)}catch{return null}if(v.includes(":")){const A=v.split(":"),I=A[0].trim().toLowerCase(),y=A.slice(1).join(":").trim();return{[I]:y}}return null},Nn=m.useCallback(()=>{},[]),xt=g=>{if(fe.current)g==="§"?fe.current=!1:(ae.current+=g,o(v=>v+g));else if(g==="§"){fe.current=!0;return}else for(oe.current+=g;oe.current.includes(`
|
|
3
|
-
`);){const v=oe.current.indexOf(`
|
|
4
|
-
`),A=oe.current.slice(0,v).trim();oe.current=oe.current.slice(v+1);const I=Cn(A);I&&Rn(I)}};m.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const A="secret",I=Math.floor(Date.now()/1e3).toString();try{const y=new TextEncoder,C=await crypto.subtle.importKey("raw",y.encode(A),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),V=await crypto.subtle.sign("HMAC",C,y.encode(I)),H=Array.from(new Uint8Array(V)).map(K=>K.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",H),Y("[SESSION] New HMAC UID generated and saved:",H)}catch(y){console.error("[SESSION] HMAC generation failed:",y);const C=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",C)}}sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[]);const _t=()=>{try{return JSON.parse(sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||"[]")}catch{return[]}},On=g=>{sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(g))},[Ze,et]=m.useState(!1),[wt,tt]=m.useState(0),he=m.useRef(null),Ve=m.useRef([]),yt=m.useRef(0),[St,Dn]=m.useState(null),[Fn,nt]=m.useState(null),xe=m.useRef(null),Ae=m.useRef(null),st=m.useCallback(()=>{P.current=[],E.current=!1,_(!1),G.current=0,j.current=0,F.current=0,U.current.forEach(g=>{try{g.stop()}catch{}}),Pe.current&&(clearTimeout(Pe.current),Pe.current=null),Ie(null),k(""),U.current=[]},[]),Pn=async()=>{try{const g=await navigator.mediaDevices.getUserMedia({audio:!0}),v=window.AudioContext||window.webkitAudioContext,A=new v,I=A.createMediaStreamSource(g),y=A.createAnalyser();y.fftSize=64,I.connect(y),xe.current=A,Ae.current=I,nt(y);const C=new MediaRecorder(g);he.current=C,Ve.current=[],C.ondataavailable=V=>{V.data.size>0&&Ve.current.push(V.data)},C.onstop=async()=>{const V=Date.now()-yt.current;if(nt(null),Ae.current&&(Ae.current.disconnect(),Ae.current=null),xe.current&&xe.current.state!=="closed"&&(xe.current.close(),xe.current=null),V<1e3){l("Recording too short. Hold or click longer."),h(!1);return}const W=new Blob(Ve.current,{type:"audio/wav"});await Gn(W)},yt.current=Date.now(),C.start(100),et(!0),l("Listening...")}catch(g){console.error("Error accessing microphone:",g),l("Mic Access Error")}},Un=()=>{he.current&&he.current.state!=="inactive"&&(he.current.stop(),he.current.stream.getTracks().forEach(g=>g.stop()),et(!1))},En=()=>{he.current&&he.current.state!=="inactive"&&(he.current.onstop=null,he.current.stop(),he.current.stream.getTracks().forEach(g=>g.stop()),nt(null),Ae.current&&(Ae.current.disconnect(),Ae.current=null),xe.current&&xe.current.state!=="closed"&&(xe.current.close(),xe.current=null),et(!1),Ve.current=[],l("Ready"))};m.useEffect(()=>{if(!p)return;const g=()=>{const v=F.current;if(v<=0)return;const A=M.current,I=G.current;if(!A)return;const y=A.currentTime-I,C=Math.min(Math.max(0,y),v),V=a.trim().length;if(V<=0)return;const W=Math.min(Math.round(C/v*V),V);le(W)};return clearInterval(me.current??void 0),me.current=setInterval(g,90),()=>clearInterval(me.current??void 0)},[p,a,F.current]),m.useEffect(()=>{let g;return Ze?(tt(0),g=window.setInterval(()=>{tt(v=>v+1)},1e3)):tt(0),()=>clearInterval(g)},[Ze]);const Bn=g=>{const v=g.numberOfChannels,A=g.length*v*2+44,I=new ArrayBuffer(A),y=new DataView(I);let C=0;const V=q=>{y.setUint16(C,q,!0),C+=2},W=q=>{y.setUint32(C,q,!0),C+=4};W(1179011410),W(A-8),W(1163280727),W(544501094),W(16),V(1),V(v),W(g.sampleRate),W(g.sampleRate*2*v),V(v*2),V(16),W(1635017060),W(A-C-4);const H=[];for(let q=0;q<v;q++)H.push(g.getChannelData(q));let K=0;for(;C<A;){for(let q=0;q<v;q++){let J=Math.max(-1,Math.min(1,H[q][K]));J=J<0?J*32768:J*32767,y.setInt16(C,J,!0),C+=2}K++}return new Blob([I],{type:"audio/wav"})},rt=async(g,v,A=!1)=>{if(b.current){w.current.push({audio:g,visemes:v,isNewSegment:A});return}b.current=!0;try{const I=window.AudioContext||window.webkitAudioContext,y=M.current??new I;y.state==="suspended"&&await y.resume(),M.current=y;const C=window.atob(g),V=new Uint8Array(C.length);for(let $=0;$<C.length;$++)V[$]=C.charCodeAt($);const W=await y.decodeAudioData(V.buffer.slice(0));F.current+=W.duration;const H=y.currentTime;let K=j.current;const q=!E.current;K<H&&(K=H+.1),j.current=K+W.duration;const J=y.createBufferSource();J.buffer=W;let Q=St;if((!Q||Q.context!==y)&&(Q=y.createAnalyser(),Q.fftSize=64,Q.connect(y.destination),Dn(Q)),J.connect(Q),U.current.push(J),q){E.current=!0,_(!0),Y(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${K.toFixed(3)}`),G.current=K;const $=(K-H)*1e3;L.current=performance.now()+$,Y(`[AUDIO] Response started. Initial startTime: ${K.toFixed(3)}, CT: ${H.toFixed(3)}`)}J.start(K);const re=(K-G.current)*1e3;A&&(B.current=re,Y(`[AUDIO] New segment detected at +${re.toFixed(0)}ms. Resetting segment offset.`)),v.forEach(($,_e)=>{const z=$.symbol??"";if(z){const ue=Tn(z),pe=Math.round($.start*1e3),Le=Math.round(($.duration??0)*1e3),At=B.current+pe;_e<3&&Y(`[AUDIO] Viseme "${z}": segment_relative=${pe}ms, segment_offset=${B.current.toFixed(0)}ms => vtime=${At}ms`),ue.forEach(Lt=>{P.current.push({viseme:Lt.v,weight:Lt.w,vtime:At,vduration:Le})})}}),l("Speaking...")}finally{if(b.current=!1,w.current.length>0){const I=w.current.shift();I&&rt(I.audio,I.visemes,I.isNewSegment)}}},Gn=async g=>{try{h(!0),ae.current="",o(""),l("Processing Voice...");const v=await g.arrayBuffer(),I=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(v),y=Bn(I),C=new FileReader;C.readAsDataURL(y),C.onloadend=async()=>{const V=C.result.split(",")[1];st(),r(""),oe.current="",fe.current=!1;const W=`${mt}/stt?token=${encodeURIComponent(s)}`,H=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:V,audio_format:"wav"})});if(!H.ok){const _e=await H.text();let z="STT Failed";try{z=JSON.parse(_e).error||z}catch{_e&&(z=_e.slice(0,200))}throw new Error(z)}const K=H.body;if(Y("this is body"+K),!K){l("STT Failed"),h(!1);return}const q=K.getReader(),J=new TextDecoder;let Q="",re=!1;const $=async(_e,z)=>{switch(_e){case"transcript":z.transcript!=null&&r(String(z.transcript));break;case"text":{const ue=z.delta??z.text??"";ue&&xt(ue);break}case"audio":{const ue=z.chunk,pe=z.visemes??[],Le=!!z.is_new_segment;ue&&await rt(ue,pe,Le);break}case"done":{re=!0,l("Ready"),h(!1);break}case"error":{re=!0,l("STT Failed"),h(!1);break}default:break}};for(;;){const{done:_e,value:z}=await q.read();z&&(Q+=J.decode(z,{stream:!0}));const ue=Q.split(`
|
|
5
|
-
|
|
6
|
-
`);Q=ue.pop()??"";for(const pe of ue){const Le=Ke(pe);Le&&await $(Le.event,Le.data)}if(_e){if(Q.trim()){const pe=Ke(Q.trim());pe&&await $(pe.event,pe.data)}re||(l("Ready"),h(!1));break}}}}catch(v){console.error("Audio Submission Error:",v),l("STT Failed"),h(!1)}},jn=async g=>{g&&g.preventDefault(),ae.current="",o(""),!(!i||u)&&await Vn(i)},Ke=g=>{const v=g.split(/\r?\n/);let A="",I="";for(const C of v)C.startsWith("event:")?A=C.slice(6).trim():C.startsWith("data:")&&(I=C.slice(5).trim());if(!A)return null;let y={};if(I)try{y=JSON.parse(I)}catch{y={raw:I}}return{event:A,data:y}},Tt=(g,v)=>{switch(g){case"connected":oe.current="",fe.current=!1;break;case"text":{const A=v.delta??"";A&&xt(A);break}case"audio":{const A=v.chunk,I=v.visemes??[];A&&rt(A,I);break}case"done":{const A=_t(),I=ae.current.trim(),y=[...A,{role:"user",content:i||"..."},{role:"assistant",content:I}];On(y),D.current=[...P.current],l("Ready"),h(!1),r("");break}case"error":{const A=v.message??"Unknown error";ae.current=A,o(A),l("Agent Failed"),h(!1);break}}},Vn=async g=>{h(!0),l("Thinking..."),ae.current="",oe.current="",fe.current=!1,st(),F.current=0,le(0);const v=`${mt}/agent/chat?token=${encodeURIComponent(s)}`;try{const A=_t();let I=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID");I||(un("[CHAT] Session UID missing at send time! Generating emergency backup."),I="emergency-"+Math.random().toString(36).substring(7),sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",I));const y={history:A,question:g,lead_id:I};Y("[CHAT] Sending payload:",y);const C=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y),cache:"default"});if(!C.ok)throw new Error("Agent request failed");const V=C.body;if(!V){l("Agent Failed"),h(!1);return}const W=V.getReader(),H=new TextDecoder;let K="";for(;;){const{done:q,value:J}=await W.read();Y(`[SSE] Chunk received. done=${q}, length=${J?.length||0}`),J&&(K+=H.decode(J,{stream:!0}));const Q=K.split(`
|
|
7
|
-
|
|
8
|
-
`);K=Q.pop()??"";for(const re of Q){Y(`[SSE] Processing block: ${re.slice(0,50)}...`);const $=Ke(re);$&&(Y(`[SSE] Event: ${$.event}`),Tt($.event,$.data))}if(q){if(Y("[SSE] Stream finished"),K.trim()){const re=Ke(K.trim());re&&Tt(re.event,re.data)}l("Ready"),h(!1),r("");break}}}catch(A){console.error("Chat Error:",A),l("Agent Failed"),h(!1)}},vt=a.trim(),it=vt&&p?vt.slice(0,Z!=null&&Z>0?Z:0):"";m.useEffect(()=>{const g=se.current;g!=="exiting"&&(it?(be(it),g==="hidden"&&ve("entering")):(g==="visible"||g==="entering")&&ve("exiting"))},[it,ge]);const Kn=m.useCallback(()=>{const g=se.current;g==="entering"?ve("visible"):g==="exiting"&&ve("hidden")},[]);return m.useLayoutEffect(()=>{const g=Ue.current;g&&(g.scrollTop=g.scrollHeight)},[ne]),S.jsxs("div",{className:"avatar-widget-container",children:[S.jsxs("div",{className:"avatar-input-area",children:[X!=="hidden"?S.jsx("div",{className:`avatar-thinking-tab${X==="exiting"?" avatar-thinking-tab--exiting":X==="entering"?" avatar-thinking-tab--entering":""}`,onAnimationEnd:In,children:Oe}):null,S.jsx("div",{className:"avatar-input-container",children:S.jsx("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"100%"},children:Ze?S.jsxs("div",{className:"avatar-input-recording",children:[S.jsx("button",{type:"button",className:"avatar-recording-cancel",onClick:En,title:"Cancel",children:S.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},children:[S.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),S.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),S.jsxs("div",{style:{flex:1,height:"100%",position:"relative",display:"flex",alignItems:"center",minWidth:0},children:[S.jsx("div",{style:{flex:1,height:"100%"},children:S.jsx(pt,{analyser:Fn})}),S.jsxs("span",{style:{fontSize:"0.75rem",color:"#64748b",fontWeight:500,marginLeft:"4px",minWidth:"32px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:[Math.floor(wt/60),":",String(wt%60).padStart(2,"0")]})]}),S.jsx("button",{type:"button",className:"avatar-recording-confirm",onClick:Un,title:"Send",children:S.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},children:S.jsx("polyline",{points:"20 6 9 17 4 12"})})})]}):p?S.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",paddingRight:"8px"},children:S.jsx(pt,{analyser:St})}):u?S.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:S.jsx("div",{className:"avatar-input-loader"})}):S.jsxs("form",{onSubmit:jn,style:{flex:1,display:"flex",height:"100%",alignItems:"center"},children:[S.jsx("input",{id:"avatar-text-input",type:"text",value:i,onChange:g=>r(g.target.value),placeholder:"Ask me anything",disabled:u,autoComplete:"off",style:{width:"100%",height:"100%"}}),i.trim()===""?S.jsx("button",{type:"button",className:"mic-button",onClick:Pn,disabled:u,style:{backgroundColor:"#1e4a5e"},children:S.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[S.jsx("path",{d:"M12 14C13.66 14 15 12.66 15 11V5C15 3.34 13.66 2 12 2C10.34 2 9 3.34 9 5V11C9 12.66 10.34 14 12 14Z",fill:"white"}),S.jsx("path",{d:"M17 11C17 13.76 14.76 16 12 16C9.24 16 7 13.76 7 11H5C5 14.53 7.61 17.43 11 17.93V21H13V17.93C16.39 17.43 19 14.53 19 11H17Z",fill:"white"})]})}):S.jsx("button",{type:"submit",className:"mic-button",disabled:u,style:{backgroundColor:"#1e4a5e"},title:"Send",children:S.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[S.jsx("path",{d:"M22 2L11 13",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),S.jsx("path",{d:"M22 2L15 22L11 13L2 9L22 2Z",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})})})]}),S.jsx("div",{className:"avatar-wrapper",children:S.jsxs("div",{className:"avatar-scene-wrapper",children:[ge!=="hidden"&&S.jsx("div",{className:`avatar-bubble${ge==="entering"?" avatar-bubble--entering":ge==="exiting"?" avatar-bubble--exiting":""}`,onAnimationEnd:Kn,children:S.jsx("div",{ref:Ue,className:"avatar-bubble__content",children:ne})}),S.jsx("div",{className:"avatar-canvas-layer",style:{width:600,height:600},children:S.jsxs(We.Canvas,{shadows:!0,camera:{position:[.2,1.4,3],fov:42},gl:{alpha:!0},dpr:1.8,style:{pointerEvents:"none",width:"100%",height:"100%"},children:[S.jsx(vn,{target:xn}),S.jsx("ambientLight",{intensity:.7}),S.jsx("directionalLight",{position:[0,2,2],intensity:1}),S.jsx(Ee.Environment,{preset:"city"}),S.jsx(m.Suspense,{fallback:null,children:n!==null&&S.jsx(An,{avatarUrl:n,isPlayingRef:E,visemeQueueRef:P,audioContextRef:M,responseAudioStartTimeRef:G,adjustments:bn,mood:Se,expression:Je,agentResponse:a,isSpeaking:p,nextStartTimeRef:j,stopPlayback:st,setIsSpeaking:_,expressionUrl:O,onExpressionFinished:Nn})})]})})]})})]})},kn=({token:d,onNavigationRequested:t})=>S.jsx(Mn,{token:d,onNavigationRequested:t});ce.AvatarWidget=kn,Object.defineProperty(ce,Symbol.toStringTag,{value:"Module"})}));
|
|
9
|
-
//# sourceMappingURL=avatar-widget.umd.cjs.map
|