cozyclay 2.0.0 → 2.0.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/CHANGELOG.md +56 -0
- package/bin/agent/agent-routes.mjs +8 -2
- package/bin/codex-auth.mjs +2 -1
- package/bin/cozyclay.mjs +12 -3
- package/bin/mcp-runtime.mjs +10 -0
- package/dist/app/index.html +3 -3
- package/dist/assets/app-BxBLC6GT.js +4876 -0
- package/dist/assets/app-CJdxvnrl.css +1 -0
- package/dist/assets/{shot-prompt-Yrt99wZx.js → shot-prompt-hN0j_O-p.js} +3 -3
- package/dist/assets/{workflow-dNPGY9xz.js → workflow-B5XZwVfe.js} +1 -1
- package/dist/cozyclay-package.json +1 -1
- package/dist/sitemap.xml +4 -4
- package/dist/workflow/index.html +2 -2
- package/package.json +1 -1
- package/src/App.jsx +27 -11
- package/src/ardy/timeline.css +15 -0
- package/src/ardy/timeline.jsx +4 -1
- package/src/ardy/waypoints.js +1 -1
- package/src/camera-tutorial.jsx +38 -18
- package/src/commands/project.js +1 -1
- package/src/domains/scenes.js +10 -4
- package/src/motion/generation.js +1 -1
- package/src/project-browser.jsx +4 -0
- package/src/scenes.js +4 -8
- package/src/styles.css +19 -1
- package/src/theme.js +1 -1
- package/src/timeline-fps.js +13 -0
- package/src/workflow/AgentPanel.jsx +4 -2
- package/tools/run-tests.mjs +2 -0
- package/dist/assets/app-C1sdVbg4.css +0 -1
- package/dist/assets/app-CA55tcI3.js +0 -4876
- package/tools/ardy/__pycache__/cclay_gvhmr_worker.cpython-313.pyc +0 -0
|
@@ -10,8 +10,8 @@ Error generating stack: `+e.message+`
|
|
|
10
10
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
11
11
|
}`,wl=`void main() {
|
|
12
12
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
13
|
-
}`,Tl=class extends aa{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Cl,this.fragmentShader=wl,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=_l(e.uniforms),this.uniformsGroups=bl(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let r=e.uniforms[n];switch(this.uniforms[n]={},r.type){case`t`:this.uniforms[n].value=t[r.value]||null;break;case`c`:this.uniforms[n].value=new H().setHex(r.value);break;case`v2`:this.uniforms[n].value=new R().fromArray(r.value);break;case`v3`:this.uniforms[n].value=new B().fromArray(r.value);break;case`v4`:this.uniforms[n].value=new sr().fromArray(r.value);break;case`m3`:this.uniforms[n].value=new Gn().fromArray(r.value);break;case`m4`:this.uniforms[n].value=new V().fromArray(r.value);break;default:this.uniforms[n].value=r.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let t in e.extensions)this.extensions[t]=e.extensions[t];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},El=class extends Tl{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},Dl=class extends aa{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type=`MeshStandardMaterial`,this.defines={STANDARD:``},this.color=new H(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new H(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Cr,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:``},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Ol=class extends Dl{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:``,PHYSICAL:``},this.type=`MeshPhysicalMaterial`,this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new R(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return I(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new H(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new H(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new H(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:``,PHYSICAL:``},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},kl=class extends aa{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type=`MeshPhongMaterial`,this.color=new H(16777215),this.specular=new H(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new H(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Cr,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Al=class extends aa{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:``},this.type=`MeshToonMaterial`,this.color=new H(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new H(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},jl=class extends aa{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type=`MeshNormalMaterial`,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}},Ml=class extends aa{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type=`MeshLambertMaterial`,this.color=new H(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new H(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Cr,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Nl=class extends aa{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=wt,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},Pl=class extends aa{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}},Fl=class extends aa{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:``},this.type=`MeshMatcapMaterial`,this.color=new H(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:``},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}},Il=class extends qo{constructor(e){super(),this.isLineDashedMaterial=!0,this.type=`LineDashedMaterial`,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}};function Ll(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function Rl(e){function t(t,n){return e[t]-e[n]}let n=e.length,r=Array(n);for(let e=0;e!==n;++e)r[e]=e;return r.sort(t),r}function zl(e,t,n){let r=e.length,i=new e.constructor(r);for(let a=0,o=0;o!==r;++a){let r=n[a]*t;for(let n=0;n!==t;++n)i[o++]=e[r+n]}return i}function Bl(e,t,n,r){let i=1,a=e[0];for(;a!==void 0&&a[r]===void 0;)a=e[i++];if(a===void 0)return;let o=a[r];if(o!==void 0)if(Array.isArray(o))do o=a[r],o!==void 0&&(t.push(a.time),n.push(...o)),a=e[i++];while(a!==void 0);else if(o.toArray!==void 0)do o=a[r],o!==void 0&&(t.push(a.time),o.toArray(n,n.length)),a=e[i++];while(a!==void 0);else do o=a[r],o!==void 0&&(t.push(a.time),n.push(o)),a=e[i++];while(a!==void 0)}function K(e,t,n,r,i=30){let a=e.clone();a.name=t;let o=[];for(let e=0;e<a.tracks.length;++e){let t=a.tracks[e],s=t.getValueSize(),c=[],l=[];for(let e=0;e<t.times.length;++e){let a=t.times[e]*i;if(!(a<n||a>=r)){c.push(t.times[e]);for(let n=0;n<s;++n)l.push(t.values[e*s+n])}}c.length!==0&&(t.times=Ll(c,t.times.constructor),t.values=Ll(l,t.values.constructor),o.push(t))}a.tracks=o;let s=1/0;for(let e=0;e<a.tracks.length;++e)s>a.tracks[e].times[0]&&(s=a.tracks[e].times[0]);for(let e=0;e<a.tracks.length;++e)a.tracks[e].shift(-1*s);return a.resetDuration(),a}function q(e,t=0,n=e,r=30){r<=0&&(r=30);let i=n.tracks.length,a=t/r;for(let t=0;t<i;++t){let r=n.tracks[t],i=r.ValueTypeName;if(i===`bool`||i===`string`)continue;let o=e.tracks.find(function(e){return e.name===r.name&&e.ValueTypeName===i});if(o===void 0)continue;let s=0,c=r.getValueSize();r.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(s=c/3);let l=0,u=o.getValueSize();o.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(l=u/3);let d=r.times.length-1,f;if(a<=r.times[0]){let e=s,t=c-s;f=r.values.slice(e,t)}else if(a>=r.times[d]){let e=d*c+s,t=e+c-s;f=r.values.slice(e,t)}else{let e=r.createInterpolant(),t=s,n=c-s;e.evaluate(a),f=e.resultBuffer.slice(t,n)}i===`quaternion`&&new z().fromArray(f).normalize().conjugate().toArray(f);let p=o.times.length;for(let e=0;e<p;++e){let t=e*u+l;if(i===`quaternion`)z.multiplyQuaternionsFlat(o.values,t,f,0,o.values,t);else{let e=u-l*2;for(let n=0;n<e;++n)o.values[t+n]-=f[n]}}}return e.blendMode=Ct,e}var Vl=class{static convertArray(e,t){return Ll(e,t)}static isTypedArray(e){return an(e)}static getKeyframeOrder(e){return Rl(e)}static sortedArray(e,t,n){return zl(e,t,n)}static flattenJSON(e,t,n,r){Bl(e,t,n,r)}static subclip(e,t,n,r,i=30){return K(e,t,n,r,i)}static makeClipAdditive(e,t=0,n=e,r=30){return q(e,t,n,r)}},Hl=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`THREE.Interpolant: Call to abstract method.`)}intervalChanged_(){}},Ul=class extends Hl{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:yt,endingEnd:yt}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case bt:i=e,o=2*t-n;break;case xt:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case bt:a=e,s=2*n-t;break;case xt:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},Wl=class extends Hl{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},Gl=class extends Hl{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},Kl=class extends Hl{interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this.inTangents,u=this.outTangents;if(!l||!u){let e=(n-t)/(r-t),l=1-e;for(let t=0;t!==o;++t)i[t]=a[c+t]*l+a[s+t]*e;return i}let d=o*2,f=e-1;for(let p=0;p!==o;++p){let o=a[c+p],m=a[s+p],h=f*d+p*2,g=u[h],_=u[h+1],v=e*d+p*2,y=l[v],b=l[v+1],x=(n-t)/(r-t),S,C,w,T,E;for(let e=0;e<8;e++){S=x*x,C=S*x,w=1-x,T=w*w,E=T*w;let e=E*t+3*T*x*g+3*w*S*y+C*r-n;if(Math.abs(e)<1e-10)break;let i=3*T*(g-t)+6*w*x*(y-g)+3*S*(r-y);if(Math.abs(i)<1e-10)break;x-=e/i,x=Math.max(0,Math.min(1,x))}i[p]=E*o+3*T*x*_+3*w*S*b+C*m}return i}},ql=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=Ll(t,this.TimeBufferType),this.values=Ll(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:Ll(e.times,Array),values:Ll(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Gl(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Wl(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Ul(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new Kl(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.inTangents=this.settings.inTangents,t.outTangents=this.settings.outTangents),t}setInterpolation(e){let t;switch(e){case ht:t=this.InterpolantFactoryMethodDiscrete;break;case gt:t=this.InterpolantFactoryMethodLinear;break;case _t:t=this.InterpolantFactoryMethodSmooth;break;case vt:t=this.InterpolantFactoryMethodBezier}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t);return P(`KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return ht;case this.InterpolantFactoryMethodLinear:return gt;case this.InterpolantFactoryMethodSmooth:return _t;case this.InterpolantFactoryMethodBezier:return vt}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(F(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(F(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){F(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){F(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&an(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){F(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===_t,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0]))if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};ql.prototype.ValueTypeName=``,ql.prototype.TimeBufferType=Float32Array,ql.prototype.ValueBufferType=Float32Array,ql.prototype.DefaultInterpolation=gt;var Jl=class extends ql{constructor(e,t,n){super(e,t,n)}};Jl.prototype.ValueTypeName=`bool`,Jl.prototype.ValueBufferType=Array,Jl.prototype.DefaultInterpolation=ht,Jl.prototype.InterpolantFactoryMethodLinear=void 0,Jl.prototype.InterpolantFactoryMethodSmooth=void 0;var Yl=class extends ql{constructor(e,t,n,r){super(e,t,n,r)}};Yl.prototype.ValueTypeName=`color`;var Xl=class extends ql{constructor(e,t,n,r){super(e,t,n,r)}};Xl.prototype.ValueTypeName=`number`;var Zl=class extends Hl{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)z.slerpFlat(i,0,a,c-o,a,c,s);return i}},Ql=class extends ql{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new Zl(this.times,this.values,this.getValueSize(),e)}};Ql.prototype.ValueTypeName=`quaternion`,Ql.prototype.InterpolantFactoryMethodSmooth=void 0;var $l=class extends ql{constructor(e,t,n){super(e,t,n)}};$l.prototype.ValueTypeName=`string`,$l.prototype.ValueBufferType=Array,$l.prototype.DefaultInterpolation=ht,$l.prototype.InterpolantFactoryMethodLinear=void 0,$l.prototype.InterpolantFactoryMethodSmooth=void 0;var eu=class extends ql{constructor(e,t,n,r){super(e,t,n,r)}};eu.prototype.ValueTypeName=`vector`;var tu=class{constructor(e=``,t=-1,n=[],r=St){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=Sn(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,r=1/(e.fps||1);for(let e=0,i=n.length;e!==i;++e)t.push(ru(n[e]).scale(r));let i=new this(e.name,e.duration,t,e.blendMode);return i.uuid=e.uuid,i.userData=JSON.parse(e.userData||`{}`),i}static toJSON(e){let t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let e=0,r=n.length;e!==r;++e)t.push(ql.toJSON(n[e]));return r}static CreateFromMorphTargetSequence(e,t,n,r){let i=t.length,a=[];for(let e=0;e<i;e++){let o=[],s=[];o.push((e+i-1)%i,e,(e+1)%i),s.push(0,1,0);let c=Rl(o);o=zl(o,1,c),s=zl(s,1,c),!r&&o[0]===0&&(o.push(i),s.push(s[0])),a.push(new Xl(`.morphTargetInfluences[`+t[e].name+`]`,o,s).scale(1/n))}return new this(e,-1,a)}static findByName(e,t){let n=e;if(!Array.isArray(e)){let t=e;n=t.geometry&&t.geometry.animations||t.animations}for(let e=0;e<n.length;e++)if(n[e].name===t)return n[e];return null}static CreateClipsFromMorphTargetSequences(e,t,n){let r={},i=/^([\w-]*?)([\d]+)$/;for(let t=0,n=e.length;t<n;t++){let n=e[t],a=n.name.match(i);if(a&&a.length>1){let e=a[1],t=r[e];t||(r[e]=t=[]),t.push(n)}}let a=[];for(let e in r)a.push(this.CreateFromMorphTargetSequence(e,r[e],t,n));return a}resetDuration(){let e=this.tracks,t=0;for(let n=0,r=e.length;n!==r;++n){let e=this.tracks[n];t=Math.max(t,e.times[e.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e&&=this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){let e=[];for(let t=0;t<this.tracks.length;t++)e.push(this.tracks[t].clone());let t=new this.constructor(this.name,this.duration,e,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}};function nu(e){switch(e.toLowerCase()){case`scalar`:case`double`:case`float`:case`number`:case`integer`:return Xl;case`vector`:case`vector2`:case`vector3`:case`vector4`:return eu;case`color`:return Yl;case`quaternion`:return Ql;case`bool`:case`boolean`:return Jl;case`string`:return $l}throw Error(`THREE.KeyframeTrack: Unsupported typeName: `+e)}function ru(e){if(e.type===void 0)throw Error(`THREE.KeyframeTrack: track type undefined, can not parse`);let t=nu(e.type);if(e.times===void 0){let t=[],n=[];Bl(e.keys,t,n,`value`),e.times=t,e.values=n}return t.parse===void 0?new t(e.name,e.times,e.values,e.interpolation):t.parse(e)}var iu={enabled:!1,files:{},add:function(e,t){this.enabled!==!1&&(au(e)||(this.files[e]=t))},get:function(e){if(this.enabled!==!1&&!au(e))return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function au(e){try{let t=e.slice(e.indexOf(`:`)+1);return new URL(t).protocol===`blob:`}catch{return!1}}var ou=class{constructor(e,t,n){let r=this,i=!1,a=0,o=0,s,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(e){o++,i===!1&&r.onStart!==void 0&&r.onStart(e,a,o),i=!0},this.itemEnd=function(e){a++,r.onProgress!==void 0&&r.onProgress(e,a,o),a===o&&(i=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(e){r.onError!==void 0&&r.onError(e)},this.resolveURL=function(e){return e=e.normalize(`NFC`),s?s(e):e},this.setURLModifier=function(e){return s=e,this},this.addHandler=function(e,t){return c.push(e,t),this},this.removeHandler=function(e){let t=c.indexOf(e);return t!==-1&&c.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=c.length;t<n;t+=2){let n=c[t],r=c[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return r}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||=new AbortController,this._abortController}},su=new ou,cu=class{constructor(e){this.manager=e===void 0?su:e,this.crossOrigin=`anonymous`,this.withCredentials=!1,this.path=``,this.resourcePath=``,this.requestHeader={},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}load(){}loadAsync(e,t){let n=this;return new Promise(function(r,i){n.load(e,r,t,i)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}};cu.DEFAULT_MATERIAL_NAME=`__DEFAULT`;var lu={},uu=class extends Error{constructor(e,t){super(e),this.response=t}},du=class extends cu{constructor(e){super(e),this.mimeType=``,this.responseType=``,this._abortController=new AbortController}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=iu.get(`file:${e}`);if(i!==void 0){this.manager.itemStart(e),setTimeout(()=>{t&&t(i),this.manager.itemEnd(e)},0);return}if(lu[e]!==void 0){lu[e].push({onLoad:t,onProgress:n,onError:r});return}lu[e]=[],lu[e].push({onLoad:t,onProgress:n,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?`include`:`same-origin`,signal:typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,s=this.responseType;fetch(a).then(t=>{if(t.status===200||t.status===0){if(t.status===0&&P(`FileLoader: HTTP Status 0 received.`),typeof ReadableStream>`u`||t.body===void 0||t.body.getReader===void 0)return t;let n=lu[e],r=t.body.getReader(),i=t.headers.get(`X-File-Size`)||t.headers.get(`Content-Length`),a=i?parseInt(i):0,o=a!==0,s=0,c=new ReadableStream({start(e){t();function t(){r.read().then(({done:r,value:i})=>{if(r)e.close();else{s+=i.byteLength;let r=new ProgressEvent(`progress`,{lengthComputable:o,loaded:s,total:a});for(let e=0,t=n.length;e<t;e++){let t=n[e];t.onProgress&&t.onProgress(r)}e.enqueue(i),t()}},t=>{e.error(t)})}}});return new Response(c)}throw new uu(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(s){case`arraybuffer`:return e.arrayBuffer();case`blob`:return e.blob();case`document`:return e.text().then(e=>new DOMParser().parseFromString(e,o));case`json`:return e.json();default:if(o===``)return e.text();{let t=/charset="?([^;"\s]*)"?/i.exec(o),n=t&&t[1]?t[1].toLowerCase():void 0,r=new TextDecoder(n);return e.arrayBuffer().then(e=>r.decode(e))}}}).then(t=>{iu.add(`file:${e}`,t);let n=lu[e];delete lu[e];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.onLoad&&r.onLoad(t)}}).catch(t=>{let n=lu[e];if(n===void 0)throw this.manager.itemError(e),t;delete lu[e];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.onError&&r.onError(t)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},fu=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new du(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(n){try{t(i.parse(JSON.parse(n)))}catch(t){r?r(t):F(t),i.manager.itemError(e)}},n,r)}parse(e){let t=[];for(let n=0;n<e.length;n++){let r=tu.parse(e[n]);t.push(r)}return t}},pu=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=[],o=new _s,s=new du(this.manager);s.setPath(this.path),s.setResponseType(`arraybuffer`),s.setRequestHeader(this.requestHeader),s.setWithCredentials(i.withCredentials);let c=0;function l(l){s.load(e[l],function(e){let n=i.parse(e,!0);a[l]={width:n.width,height:n.height,format:n.format,mipmaps:n.mipmaps},c+=1,c===6&&(n.mipmapCount===1&&(o.minFilter=A),o.image=a,o.format=n.format,o.needsUpdate=!0,t&&t(o))},n,r)}if(Array.isArray(e))for(let t=0,n=e.length;t<n;++t)l(t);else s.load(e,function(e){let n=i.parse(e,!0);if(n.isCubemap){let e=n.mipmaps.length/n.mipmapCount;for(let t=0;t<e;t++){a[t]={mipmaps:[]};for(let e=0;e<n.mipmapCount;e++)a[t].mipmaps.push(n.mipmaps[t*n.mipmapCount+e]),a[t].format=n.format,a[t].width=n.width,a[t].height=n.height}o.image=a}else o.image.width=n.width,o.image.height=n.height,o.mipmaps=n.mipmaps;n.mipmapCount===1&&(o.minFilter=A),o.format=n.format,o.needsUpdate=!0,t&&t(o)},n,r);return o}},mu=new WeakMap,hu=class extends cu{constructor(e){super(e)}load(e,t,n,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=iu.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)i.manager.itemStart(e),setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);else{let e=mu.get(a);e===void 0&&(e=[],mu.set(a,e)),e.push({onLoad:t,onError:r})}return a}let o=on(`img`);function s(){l(),t&&t(this);let n=mu.get(this)||[];for(let e=0;e<n.length;e++){let t=n[e];t.onLoad&&t.onLoad(this)}mu.delete(this),i.manager.itemEnd(e)}function c(t){l(),r&&r(t),iu.remove(`image:${e}`);let n=mu.get(this)||[];for(let e=0;e<n.length;e++){let r=n[e];r.onError&&r.onError(t)}mu.delete(this),i.manager.itemError(e),i.manager.itemEnd(e)}function l(){o.removeEventListener(`load`,s,!1),o.removeEventListener(`error`,c,!1)}return o.addEventListener(`load`,s,!1),o.addEventListener(`error`,c,!1),e.slice(0,5)!==`data:`&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),iu.add(`image:${e}`,o),i.manager.itemStart(e),o.src=e,o}},gu=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=new bs;i.colorSpace=Ot;let a=new hu(this.manager);a.setCrossOrigin(this.crossOrigin),a.setPath(this.path);let o=0;function s(n){a.load(e[n],function(e){i.images[n]=e,o++,o===6&&(i.needsUpdate=!0,t&&t(i))},void 0,r)}for(let t=0;t<e.length;++t)s(t);return i}},_u=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new ao,o=new du(this.manager);return o.setResponseType(`arraybuffer`),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(i.withCredentials),o.load(e,function(e){let n;try{n=i.parse(e)}catch(e){r===void 0?F(e):r(e);return}i._applyTexData(a,n),t&&t(a,n)},n,r),a}createDataTexture(e){let t=new ao;return this._applyTexData(t,this.parse(e)),t}_applyTexData(e,t){t.image===void 0?t.data!==void 0&&(e.image.width=t.width,e.image.height=t.height,e.image.data=t.data):e.image=t.image,e.wrapS=t.wrapS===void 0?O:t.wrapS,e.wrapT=t.wrapT===void 0?O:t.wrapT,e.magFilter=t.magFilter===void 0?A:t.magFilter,e.minFilter=t.minFilter===void 0?A:t.minFilter,e.anisotropy=t.anisotropy===void 0?1:t.anisotropy,t.colorSpace!==void 0&&(e.colorSpace=t.colorSpace),t.flipY!==void 0&&(e.flipY=t.flipY),t.format!==void 0&&(e.format=t.format),t.type!==void 0&&(e.type=t.type),t.mipmaps!==void 0&&(e.mipmaps=t.mipmaps,e.minFilter=ae),t.mipmapCount===1&&(e.minFilter=A),t.generateMipmaps!==void 0&&(e.generateMipmaps=t.generateMipmaps),e.needsUpdate=!0}},vu=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=new or,a=new hu(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(e){i.image=e,i.needsUpdate=!0,t!==void 0&&t(i)},n,r),i}},yu=class extends Br{constructor(e,t=1){super(),this.isLight=!0,this.type=`Light`,this.color=new H(e),this.intensity=t}dispose(){this.dispatchEvent({type:`dispose`})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}},bu=class extends yu{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type=`HemisphereLight`,this.position.copy(Br.DEFAULT_UP),this.updateMatrix(),this.groundColor=new H(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){let t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}},xu=new V,Su=new B,Cu=new B,wu=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new R(512,512),this.mapType=se,this.map=null,this.mapPass=null,this.matrix=new V,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new To,this._frameExtents=new R(1,1),this._viewportCount=1,this._viewports=[new sr(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;Su.setFromMatrixPosition(e.matrixWorld),t.position.copy(Su),Cu.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Cu),t.updateMatrixWorld(),xu.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(xu,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===2001||t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(xu)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},Tu=new B,Eu=new z,Du=new B,Ou=class extends Br{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new V,this.projectionMatrix=new V,this.projectionMatrixInverse=new V,this.coordinateSystem=Yt,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(Tu,Eu,Du),Du.x===1&&Du.y===1&&Du.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Tu,Eu,Du.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(Tu,Eu,Du),Du.x===1&&Du.y===1&&Du.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Tu,Eu,Du.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},ku=new B,Au=new R,ju=new R,Mu=class extends Ou{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=xn*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(bn*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return xn*2*Math.atan(Math.tan(bn*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){ku.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ku.x,ku.y).multiplyScalar(-e/ku.z),ku.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ku.x,ku.y).multiplyScalar(-e/ku.z)}getViewSize(e,t){return this.getViewBounds(e,Au,ju),t.subVectors(ju,Au)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(bn*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},Nu=class extends wu{constructor(){super(new Mu(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=xn*2*e.angle*this.focus,r=this.mapSize.width/this.mapSize.height*this.aspect,i=e.distance||t.far;(n!==t.fov||r!==t.aspect||i!==t.far)&&(t.fov=n,t.aspect=r,t.far=i,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},Pu=class extends yu{constructor(e,t,n=0,r=Math.PI/3,i=0,a=2){super(e,t),this.isSpotLight=!0,this.type=`SpotLight`,this.position.copy(Br.DEFAULT_UP),this.updateMatrix(),this.target=new Br,this.distance=n,this.angle=r,this.penumbra=i,this.decay=a,this.map=null,this.shadow=new Nu}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}},Fu=class extends wu{constructor(){super(new Mu(90,1,.5,500)),this.isPointLightShadow=!0}},Iu=class extends yu{constructor(e,t,n=0,r=2){super(e,t),this.isPointLight=!0,this.type=`PointLight`,this.distance=n,this.decay=r,this.shadow=new Fu}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}},Lu=class extends Ou{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},Ru=class extends wu{constructor(){super(new Lu(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},zu=class extends yu{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type=`DirectionalLight`,this.position.copy(Br.DEFAULT_UP),this.updateMatrix(),this.target=new Br,this.shadow=new Ru}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}},Bu=class extends yu{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type=`AmbientLight`}},Vu=class extends yu{constructor(e,t,n=10,r=10){super(e,t),this.isRectAreaLight=!0,this.type=`RectAreaLight`,this.width=n,this.height=r}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){let t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}},Hu=class{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new B)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){let n=e.x,r=e.y,i=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.282095),t.addScaledVector(a[1],.488603*r),t.addScaledVector(a[2],.488603*i),t.addScaledVector(a[3],.488603*n),t.addScaledVector(a[4],n*r*1.092548),t.addScaledVector(a[5],r*i*1.092548),t.addScaledVector(a[6],.315392*(3*i*i-1)),t.addScaledVector(a[7],n*i*1.092548),t.addScaledVector(a[8],.546274*(n*n-r*r)),t}getIrradianceAt(e,t){let n=e.x,r=e.y,i=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.886227),t.addScaledVector(a[1],1.023328*r),t.addScaledVector(a[2],1.023328*i),t.addScaledVector(a[3],1.023328*n),t.addScaledVector(a[4],.858086*n*r),t.addScaledVector(a[5],.858086*r*i),t.addScaledVector(a[6],.743125*i*i-.247708),t.addScaledVector(a[7],.858086*n*i),t.addScaledVector(a[8],.429043*(n*n-r*r)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(e.coefficients[n],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let n=0;n<9;n++)this.coefficients[n].lerp(e.coefficients[n],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){let n=this.coefficients;for(let r=0;r<9;r++)n[r].fromArray(e,t+r*3);return this}toArray(e=[],t=0){let n=this.coefficients;for(let r=0;r<9;r++)n[r].toArray(e,t+r*3);return e}static getBasisAt(e,t){let n=e.x,r=e.y,i=e.z;t[0]=.282095,t[1]=.488603*r,t[2]=.488603*i,t[3]=.488603*n,t[4]=1.092548*n*r,t[5]=1.092548*r*i,t[6]=.315392*(3*i*i-1),t[7]=1.092548*n*i,t[8]=.546274*(n*n-r*r)}},Uu=class extends yu{constructor(e=new Hu,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){let t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}},Wu={},Gu=class e extends cu{constructor(e){super(e),this.textures={}}load(e,t,n,r){let i=this,a=new du(i.manager);a.setPath(i.path),a.setRequestHeader(i.requestHeader),a.setWithCredentials(i.withCredentials),a.load(e,function(n){try{t(i.parse(JSON.parse(n)))}catch(t){r?r(t):F(t),i.manager.itemError(e)}},n,r)}parse(e){let t=this.createMaterialFromType(e.type);return t.fromJSON(e,this.textures),t}setTextures(e){return this.textures=e,this}createMaterialFromType(t){return e.createMaterialFromType(t)}static createMaterialFromType(e){let t={ShadowMaterial:gl,SpriteMaterial:oa,RawShaderMaterial:El,ShaderMaterial:Tl,PointsMaterial:ss,MeshPhysicalMaterial:Ol,MeshStandardMaterial:Dl,MeshPhongMaterial:kl,MeshToonMaterial:Al,MeshNormalMaterial:jl,MeshLambertMaterial:Ml,MeshDepthMaterial:Nl,MeshDistanceMaterial:Pl,MeshBasicMaterial:Na,MeshMatcapMaterial:Fl,LineDashedMaterial:Il,LineBasicMaterial:qo,Material:aa,...Wu}[e],n;return t===void 0?(mn(`MaterialLoader: Unknown material type "${e}". Use .registerMaterial() before starting the deserialization process.`),n=new aa):n=new t,n}static registerMaterial(e,t){Wu[e]=t}},Ku=class{static extractUrlBase(e){let t=e.lastIndexOf(`/`);return t===-1?`./`:e.slice(0,t+1)}static resolveURL(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},qu=class extends W{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type=`InstancedBufferGeometry`,this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){let e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}},Ju=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new du(i.manager);a.setPath(i.path),a.setRequestHeader(i.requestHeader),a.setWithCredentials(i.withCredentials),a.load(e,function(n){try{t(i.parse(JSON.parse(n)))}catch(t){r?r(t):F(t),i.manager.itemError(e)}},n,r)}parse(e){let t={},n={};function r(e,n){if(t[n]!==void 0)return t[n];let r=e.interleavedBuffers[n],a=i(e,r.buffer),o=new ta(rn(r.type,a),r.stride);return o.uuid=r.uuid,t[n]=o,o}function i(e,t){if(n[t]!==void 0)return n[t];let r=e.arrayBuffers[t],i=new Uint32Array(r).buffer;return n[t]=i,i}let a=e.isInstancedBufferGeometry?new qu:new W,o=e.data.index;if(o!==void 0){let e=rn(o.type,o.array);a.setIndex(new Fi(e,1))}let s=e.data.attributes;for(let t in s){let n=s[t],i;if(n.isInterleavedBufferAttribute)i=new ra(r(e.data,n.data),n.itemSize,n.offset,n.normalized);else{let e=rn(n.type,n.array);i=new(n.isInstancedBufferAttribute?co:Fi)(e,n.itemSize,n.normalized)}n.name!==void 0&&(i.name=n.name),n.usage!==void 0&&i.setUsage(n.usage),a.setAttribute(t,i)}let c=e.data.morphAttributes;if(c)for(let t in c){let n=c[t],i=[];for(let t=0,a=n.length;t<a;t++){let a=n[t],o;o=a.isInterleavedBufferAttribute?new ra(r(e.data,a.data),a.itemSize,a.offset,a.normalized):new Fi(rn(a.type,a.array),a.itemSize,a.normalized),a.name!==void 0&&(o.name=a.name),i.push(o)}a.morphAttributes[t]=i}e.data.morphTargetsRelative&&(a.morphTargetsRelative=!0);let l=e.data.groups||e.data.drawcalls||e.data.offsets;if(l!==void 0)for(let e=0,t=l.length;e!==t;++e){let t=l[e];a.addGroup(t.start,t.count,t.materialIndex)}let u=e.data.boundingSphere;return u!==void 0&&(a.boundingSphere=new qi().fromJSON(u)),e.name&&(a.name=e.name),e.userData&&(a.userData=e.userData),a}},Yu={},Xu=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=this.path===``?Ku.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||a;let o=new du(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(n){let a=null;try{a=JSON.parse(n)}catch(t){r!==void 0&&r(t),F(`ObjectLoader: Can't parse `+e+`.`,t.message);return}let o=a.metadata;if(o===void 0||o.type===void 0||o.type.toLowerCase()===`geometry`){r!==void 0&&r(Error(`THREE.ObjectLoader: Can't load `+e)),F(`ObjectLoader: Can't load `+e);return}i.parse(a,t)},n,r)}async loadAsync(e,t){let n=this,r=this.path===``?Ku.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||r;let i=new du(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials);let a=await i.loadAsync(e,t),o;try{o=JSON.parse(a)}catch(t){throw Error(`THREE.ObjectLoader: Can't parse `+e+`. `+t.message)}let s=o.metadata;if(s===void 0||s.type===void 0||s.type.toLowerCase()===`geometry`)throw Error(`THREE.ObjectLoader: Can't load `+e);return await n.parseAsync(o)}parse(e,t){let n=this.parseAnimations(e.animations),r=this.parseShapes(e.shapes),i=this.parseGeometries(e.geometries,r),a=this.parseImages(e.images,function(){t!==void 0&&t(c)}),o=this.parseTextures(e.textures,a),s=this.parseMaterials(e.materials,o),c=this.parseObject(e.object,i,s,o,n),l=this.parseSkeletons(e.skeletons,c);if(this.bindSkeletons(c,l),this.bindLightTargets(c),t!==void 0){let e=!1;for(let t in a)if(a[t].data instanceof HTMLImageElement){e=!0;break}e===!1&&t(c)}return c}async parseAsync(e){let t=this.parseAnimations(e.animations),n=this.parseShapes(e.shapes),r=this.parseGeometries(e.geometries,n),i=await this.parseImagesAsync(e.images),a=this.parseTextures(e.textures,i),o=this.parseMaterials(e.materials,a),s=this.parseObject(e.object,r,o,a,t),c=this.parseSkeletons(e.skeletons,s);return this.bindSkeletons(s,c),this.bindLightTargets(s),s}static registerGeometry(e,t){Yu[e]=t}parseShapes(e){let t={};if(e!==void 0)for(let n=0,r=e.length;n<r;n++){let r=new mc().fromJSON(e[n]);t[r.uuid]=r}return t}parseSkeletons(e,t){let n={},r={};if(t.traverse(function(e){e.isBone&&(r[e.uuid]=e)}),e!==void 0)for(let t=0,i=e.length;t<i;t++){let i=new G().fromJSON(e[t],r);n[i.uuid]=i}return n}parseGeometries(e,t){let n={};if(e!==void 0){let r=new Ju;for(let i=0,a=e.length;i<a;i++){let a,o=e[i];switch(o.type){case`BufferGeometry`:case`InstancedBufferGeometry`:a=r.parse(o);break;default:o.type in hl?a=hl[o.type].fromJSON(o,t):o.type in Yu?a=Yu[o.type].fromJSON(o,t):P(`ObjectLoader: Unknown geometry type "${o.type}". Use .registerGeometry() before starting the deserialization process.`)}a.uuid=o.uuid,o.name!==void 0&&(a.name=o.name),o.userData!==void 0&&(a.userData=o.userData),n[o.uuid]=a}}return n}parseMaterials(e,t){let n={},r={};if(e!==void 0){let i=new Gu;i.setTextures(t);for(let t=0,a=e.length;t<a;t++){let a=e[t];n[a.uuid]===void 0&&(n[a.uuid]=i.parse(a)),r[a.uuid]=n[a.uuid]}}return r}parseAnimations(e){let t={};if(e!==void 0)for(let n=0;n<e.length;n++){let r=e[n],i=tu.parse(r);t[i.uuid]=i}return t}parseImages(e,t){let n=this,r={},i;function a(e){return e=n.manager.resolveURL(e),n.manager.itemStart(e),i.load(e,function(){n.manager.itemEnd(e)},void 0,function(){n.manager.itemError(e),n.manager.itemEnd(e)})}function o(e){if(typeof e==`string`){let t=e;return a(/^(\/\/)|([a-z]+:(\/\/)?)/i.test(t)?t:n.resourcePath+t)}return e.data?{data:rn(e.type,e.data),width:e.width,height:e.height}:null}if(e!==void 0&&e.length>0){i=new hu(new ou(t)),i.setCrossOrigin(this.crossOrigin);for(let t=0,n=e.length;t<n;t++){let n=e[t],i=n.url;if(Array.isArray(i)){let e=[];for(let t=0,n=i.length;t<n;t++){let n=i[t],r=o(n);r!==null&&(r instanceof HTMLImageElement?e.push(r):e.push(new ao(r.data,r.width,r.height)))}r[n.uuid]=new nr(e)}else{let e=o(n.url);r[n.uuid]=new nr(e)}}}return r}async parseImagesAsync(e){let t=this,n={},r;async function i(e){if(typeof e==`string`){let n=e,i=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(n)?n:t.resourcePath+n;return await r.loadAsync(i)}return e.data?{data:rn(e.type,e.data),width:e.width,height:e.height}:null}if(e!==void 0&&e.length>0){r=new hu(this.manager),r.setCrossOrigin(this.crossOrigin);for(let t=0,r=e.length;t<r;t++){let r=e[t],a=r.url;if(Array.isArray(a)){let e=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=await i(n);r!==null&&(r instanceof HTMLImageElement?e.push(r):e.push(new ao(r.data,r.width,r.height)))}n[r.uuid]=new nr(e)}else{let e=await i(r.url);n[r.uuid]=new nr(e)}}}return n}parseTextures(e,t){function n(e,t){return typeof e==`number`?e:(P(`ObjectLoader.parseTexture: Constant should be in numeric form.`,e),t[e])}let r={};if(e!==void 0)for(let i=0,a=e.length;i<a;i++){let a=e[i];a.image===void 0&&P(`ObjectLoader: No "image" specified for`,a.uuid),t[a.image]===void 0&&P(`ObjectLoader: Undefined image`,a.image);let o=t[a.image],s=o.data,c;Array.isArray(s)?(c=new bs,s.length===6&&(c.needsUpdate=!0)):(c=s&&s.data?new ao:new or,s&&(c.needsUpdate=!0)),c.source=o,c.uuid=a.uuid,a.name!==void 0&&(c.name=a.name),a.mapping!==void 0&&(c.mapping=n(a.mapping,Zu)),a.channel!==void 0&&(c.channel=a.channel),a.offset!==void 0&&c.offset.fromArray(a.offset),a.repeat!==void 0&&c.repeat.fromArray(a.repeat),a.center!==void 0&&c.center.fromArray(a.center),a.rotation!==void 0&&(c.rotation=a.rotation),a.wrap!==void 0&&(c.wrapS=n(a.wrap[0],Qu),c.wrapT=n(a.wrap[1],Qu)),a.format!==void 0&&(c.format=a.format),a.internalFormat!==void 0&&(c.internalFormat=a.internalFormat),a.type!==void 0&&(c.type=a.type),a.colorSpace!==void 0&&(c.colorSpace=a.colorSpace),a.minFilter!==void 0&&(c.minFilter=n(a.minFilter,$u)),a.magFilter!==void 0&&(c.magFilter=n(a.magFilter,$u)),a.anisotropy!==void 0&&(c.anisotropy=a.anisotropy),a.flipY!==void 0&&(c.flipY=a.flipY),a.generateMipmaps!==void 0&&(c.generateMipmaps=a.generateMipmaps),a.premultiplyAlpha!==void 0&&(c.premultiplyAlpha=a.premultiplyAlpha),a.unpackAlignment!==void 0&&(c.unpackAlignment=a.unpackAlignment),a.compareFunction!==void 0&&(c.compareFunction=a.compareFunction),a.normalized!==void 0&&(c.normalized=a.normalized),a.userData!==void 0&&(c.userData=a.userData),r[a.uuid]=c}return r}parseObject(e,t,n,r,i){let a;function o(e){return t[e]===void 0&&P(`ObjectLoader: Undefined geometry`,e),t[e]}function s(e){if(e!==void 0){if(Array.isArray(e)){let t=[];for(let r=0,i=e.length;r<i;r++){let i=e[r];n[i]===void 0&&P(`ObjectLoader: Undefined material`,i),t.push(n[i])}return t}return n[e]===void 0&&P(`ObjectLoader: Undefined material`,e),n[e]}}function c(e){return r[e]===void 0&&P(`ObjectLoader: Undefined texture`,e),r[e]}let l,u;switch(e.type){case`Scene`:a=new Zr,e.background!==void 0&&(Number.isInteger(e.background)?a.background=new H(e.background):a.background=c(e.background)),e.environment!==void 0&&(a.environment=c(e.environment)),e.fog!==void 0&&(e.fog.type===`Fog`?a.fog=new Xr(e.fog.color,e.fog.near,e.fog.far):e.fog.type===`FogExp2`&&(a.fog=new Yr(e.fog.color,e.fog.density)),e.fog.name!==``&&(a.fog.name=e.fog.name)),e.backgroundBlurriness!==void 0&&(a.backgroundBlurriness=e.backgroundBlurriness),e.backgroundIntensity!==void 0&&(a.backgroundIntensity=e.backgroundIntensity),e.backgroundRotation!==void 0&&a.backgroundRotation.fromArray(e.backgroundRotation),e.environmentIntensity!==void 0&&(a.environmentIntensity=e.environmentIntensity),e.environmentRotation!==void 0&&a.environmentRotation.fromArray(e.environmentRotation);break;case`PerspectiveCamera`:a=new Mu(e.fov,e.aspect,e.near,e.far),e.focus!==void 0&&(a.focus=e.focus),e.zoom!==void 0&&(a.zoom=e.zoom),e.filmGauge!==void 0&&(a.filmGauge=e.filmGauge),e.filmOffset!==void 0&&(a.filmOffset=e.filmOffset),e.view!==void 0&&(a.view=Object.assign({},e.view));break;case`OrthographicCamera`:a=new Lu(e.left,e.right,e.top,e.bottom,e.near,e.far),e.zoom!==void 0&&(a.zoom=e.zoom),e.view!==void 0&&(a.view=Object.assign({},e.view));break;case`AmbientLight`:a=new Bu(e.color,e.intensity);break;case`DirectionalLight`:a=new zu(e.color,e.intensity),a.target=e.target||``;break;case`PointLight`:a=new Iu(e.color,e.intensity,e.distance,e.decay);break;case`RectAreaLight`:a=new Vu(e.color,e.intensity,e.width,e.height);break;case`SpotLight`:a=new Pu(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay),a.target=e.target||``;break;case`HemisphereLight`:a=new bu(e.color,e.groundColor,e.intensity);break;case`LightProbe`:a=new Uu(new Hu().fromArray(e.sh),e.intensity);break;case`SkinnedMesh`:l=o(e.geometry),u=s(e.material),a=new ro(l,u),e.bindMode!==void 0&&(a.bindMode=e.bindMode),e.bindMatrix!==void 0&&a.bindMatrix.fromArray(e.bindMatrix),e.skeleton!==void 0&&(a.skeleton=e.skeleton);break;case`Mesh`:l=o(e.geometry),u=s(e.material),a=new Ga(l,u);break;case`InstancedMesh`:l=o(e.geometry),u=s(e.material);let t=e.count,n=e.instanceMatrix,r=e.instanceColor;a=new _o(l,u,t),a.instanceMatrix=new co(new Float32Array(n.array),16),r!==void 0&&(a.instanceColor=new co(new Float32Array(r.array),r.itemSize));break;case`BatchedMesh`:l=o(e.geometry),u=s(e.material),a=new Ko(e.maxInstanceCount,e.maxVertexCount,e.maxIndexCount,u),a.geometry=l,a.perObjectFrustumCulled=e.perObjectFrustumCulled,a.sortObjects=e.sortObjects,a._drawRanges=e.drawRanges,a._reservedRanges=e.reservedRanges,a._geometryInfo=e.geometryInfo.map(e=>{let t=null,n=null;return e.boundingBox!==void 0&&(t=new fi().fromJSON(e.boundingBox)),e.boundingSphere!==void 0&&(n=new qi().fromJSON(e.boundingSphere)),{...e,boundingBox:t,boundingSphere:n}}),a._instanceInfo=e.instanceInfo,a._availableInstanceIds=e._availableInstanceIds,a._availableGeometryIds=e._availableGeometryIds,a._nextIndexStart=e.nextIndexStart,a._nextVertexStart=e.nextVertexStart,a._geometryCount=e.geometryCount,a._maxInstanceCount=e.maxInstanceCount,a._maxVertexCount=e.maxVertexCount,a._maxIndexCount=e.maxIndexCount,a._geometryInitialized=e.geometryInitialized,a._matricesTexture=c(e.matricesTexture.uuid),a._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(a._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(a.boundingSphere=new qi().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(a.boundingBox=new fi().fromJSON(e.boundingBox));break;case`LOD`:a=new wa;break;case`Line`:a=new ts(o(e.geometry),s(e.material));break;case`LineLoop`:a=new os(o(e.geometry),s(e.material));break;case`LineSegments`:a=new as(o(e.geometry),s(e.material));break;case`PointCloud`:case`Points`:a=new fs(o(e.geometry),s(e.material));break;case`Sprite`:a=new ba(s(e.material));break;case`Group`:a=new Vr;break;case`Bone`:a=new io;break;default:a=new Br}if(a.uuid=e.uuid,e.name!==void 0&&(a.name=e.name),e.matrix===void 0?(e.position!==void 0&&a.position.fromArray(e.position),e.rotation!==void 0&&a.rotation.fromArray(e.rotation),e.quaternion!==void 0&&a.quaternion.fromArray(e.quaternion),e.scale!==void 0&&a.scale.fromArray(e.scale)):(a.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(a.matrixAutoUpdate=e.matrixAutoUpdate),a.matrixAutoUpdate&&a.matrix.decompose(a.position,a.quaternion,a.scale)),e.up!==void 0&&a.up.fromArray(e.up),e.pivot!==void 0&&(a.pivot=new B().fromArray(e.pivot)),e.morphTargetDictionary!==void 0&&(a.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),e.morphTargetInfluences!==void 0&&(a.morphTargetInfluences=e.morphTargetInfluences.slice()),e.castShadow!==void 0&&(a.castShadow=e.castShadow),e.receiveShadow!==void 0&&(a.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(a.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(a.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(a.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(a.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&a.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(a.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(a.visible=e.visible),e.frustumCulled!==void 0&&(a.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(a.renderOrder=e.renderOrder),e.static!==void 0&&(a.static=e.static),e.userData!==void 0&&(a.userData=e.userData),e.layers!==void 0&&(a.layers.mask=e.layers),e.children!==void 0){let o=e.children;for(let e=0;e<o.length;e++)a.add(this.parseObject(o[e],t,n,r,i))}if(e.animations!==void 0){let t=e.animations;for(let e=0;e<t.length;e++){let n=t[e];a.animations.push(i[n])}}if(e.type===`LOD`){e.autoUpdate!==void 0&&(a.autoUpdate=e.autoUpdate);let t=e.levels;for(let e=0;e<t.length;e++){let n=t[e],r=a.getObjectByProperty(`uuid`,n.object);r!==void 0&&a.addLevel(r,n.distance,n.hysteresis)}}return a}bindSkeletons(e,t){Object.keys(t).length!==0&&e.traverse(function(e){if(e.isSkinnedMesh===!0&&e.skeleton!==void 0){let n=t[e.skeleton];n===void 0?P(`ObjectLoader: No skeleton found with UUID:`,e.skeleton):e.bind(n,e.bindMatrix)}})}bindLightTargets(e){e.traverse(function(t){if(t.isDirectionalLight||t.isSpotLight){let n=t.target,r=e.getObjectByProperty(`uuid`,n);t.target=r===void 0?new Br:r}})}},Zu={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,CubeUVReflectionMapping:306},Qu={RepeatWrapping:D,ClampToEdgeWrapping:O,MirroredRepeatWrapping:ee},$u={NearestFilter:k,NearestMipmapNearestFilter:te,NearestMipmapLinearFilter:re,LinearFilter:A,LinearMipmapNearestFilter:j,LinearMipmapLinearFilter:ae},ed=new WeakMap,td=class extends cu{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>`u`&&P(`ImageBitmapLoader: createImageBitmap() not supported.`),typeof fetch>`u`&&P(`ImageBitmapLoader: fetch() not supported.`),this.options={premultiplyAlpha:`none`},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=iu.get(`image-bitmap:${e}`);if(a!==void 0){if(i.manager.itemStart(e),a.then){a.then(n=>{ed.has(a)===!0?(r&&r(ed.get(a)),i.manager.itemError(e),i.manager.itemEnd(e)):(t&&t(n),i.manager.itemEnd(e))});return}setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);return}let o={};o.credentials=this.crossOrigin===`anonymous`?`same-origin`:`include`,o.headers=this.requestHeader,o.signal=typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let s=fetch(e,o).then(function(e){return e.blob()}).then(function(e){return createImageBitmap(e,Object.assign(i.options,{colorSpaceConversion:`none`}))}).then(function(n){iu.add(`image-bitmap:${e}`,n),t&&t(n),i.manager.itemEnd(e)}).catch(function(t){r&&r(t),ed.set(s,t),iu.remove(`image-bitmap:${e}`),i.manager.itemError(e),i.manager.itemEnd(e)});iu.add(`image-bitmap:${e}`,s),i.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},nd,rd=class{static getContext(){return nd===void 0&&(nd=new(window.AudioContext||window.webkitAudioContext)),nd}static setContext(e){nd=e}},id=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new du(this.manager);a.setResponseType(`arraybuffer`),a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(n){try{let r=n.slice(0),a=rd.getContext(),s=e+`#decode`;i.manager.itemStart(s),a.decodeAudioData(r,function(e){t(e),i.manager.itemEnd(s)}).catch(function(e){o(e),i.manager.itemEnd(s)})}catch(e){o(e)}},n,r);function o(t){r?r(t):F(t),i.manager.itemError(e)}}},ad=new V,od=new V,sd=new V,cd=class{constructor(){this.type=`StereoCamera`,this.aspect=1,this.eyeSep=.064,this.cameraL=new Mu,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Mu,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){let t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,sd.copy(e.projectionMatrix);let n=t.eyeSep/2,r=n*t.near/t.focus,i=t.near*Math.tan(bn*t.fov*.5)/t.zoom,a,o;od.elements[12]=-n,ad.elements[12]=n,a=-i*t.aspect+r,o=i*t.aspect+r,sd.elements[0]=2*t.near/(o-a),sd.elements[8]=(o+a)/(o-a),this.cameraL.projectionMatrix.copy(sd),a=-i*t.aspect-r,o=i*t.aspect-r,sd.elements[0]=2*t.near/(o-a),sd.elements[8]=(o+a)/(o-a),this.cameraR.projectionMatrix.copy(sd)}this.cameraL.matrix.copy(e.matrixWorld).multiply(od),this.cameraL.matrixWorldNeedsUpdate=!0,this.cameraR.matrix.copy(e.matrixWorld).multiply(ad),this.cameraR.matrixWorldNeedsUpdate=!0}},ld=-90,ud=1,dd=class extends Br{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new Mu(ld,ud,e,t);r.layers=this.layers,this.add(r);let i=new Mu(ld,ud,e,t);i.layers=this.layers,this.add(i);let a=new Mu(ld,ud,e,t);a.layers=this.layers,this.add(a);let o=new Mu(ld,ud,e,t);o.layers=this.layers,this.add(o);let s=new Mu(ld,ud,e,t);s.layers=this.layers,this.add(s);let c=new Mu(ld,ud,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},fd=class extends Mu{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},pd=class{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=md.bind(this),e.addEventListener(`visibilitychange`,this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener(`visibilitychange`,this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e===void 0?performance.now():e)-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function md(){this._document.hidden===!1&&this.reset()}var hd=new B,gd=new z,_d=new B,vd=new B,yd=new B,bd=class extends Br{constructor(){super(),this.type=`AudioListener`,this.context=rd.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._timer=new pd}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter===null?this.gain.disconnect(this.context.destination):(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e),this._timer.update();let t=this.context.listener;if(this.timeDelta=this._timer.getDelta(),this.matrixWorld.decompose(hd,gd,_d),vd.set(0,0,-1).applyQuaternion(gd),yd.set(0,1,0).applyQuaternion(gd),t.positionX){let e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(hd.x,e),t.positionY.linearRampToValueAtTime(hd.y,e),t.positionZ.linearRampToValueAtTime(hd.z,e),t.forwardX.linearRampToValueAtTime(vd.x,e),t.forwardY.linearRampToValueAtTime(vd.y,e),t.forwardZ.linearRampToValueAtTime(vd.z,e),t.upX.linearRampToValueAtTime(yd.x,e),t.upY.linearRampToValueAtTime(yd.y,e),t.upZ.linearRampToValueAtTime(yd.z,e)}else t.setPosition(hd.x,hd.y,hd.z),t.setOrientation(vd.x,vd.y,vd.z,yd.x,yd.y,yd.z)}},xd=class extends Br{constructor(e){super(),this.type=`Audio`,this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType=`empty`,this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType=`audioNode`,this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType=`mediaNode`,this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType=`mediaStreamNode`,this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType=`buffer`,this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){P(`Audio: Audio is already playing.`);return}if(this.hasPlaybackControl===!1){P(`Audio: this Audio has no playback control.`);return}this._startedAt=this.context.currentTime+e;let t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){P(`Audio: this Audio has no playback control.`);return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress%=this.duration||this.buffer.duration),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){P(`Audio: this Audio has no playback control.`);return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].connect(this.filters[e]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this._connected=!0,this}disconnect(){if(this._connected!==!1){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].disconnect(this.filters[e]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this._connected=!1,this}}getFilters(){return this.filters}setFilters(e){return e||=[],this._connected===!0?(this.disconnect(),this.filters=e.slice(),this.connect()):this.filters=e.slice(),this}setDetune(e){return this.detune=e,this.isPlaying===!0&&this.source.detune!==void 0&&this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,.01),this}getDetune(){return this.detune}getFilter(){return this.getFilters()[0]}setFilter(e){return this.setFilters(e?[e]:[])}setPlaybackRate(e){if(this.hasPlaybackControl===!1){P(`Audio: this Audio has no playback control.`);return}return this.playbackRate=e,this.isPlaying===!0&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1,this._progress=0}getLoop(){return this.hasPlaybackControl===!1?(P(`Audio: this Audio has no playback control.`),!1):this.loop}setLoop(e){if(this.hasPlaybackControl===!1){P(`Audio: this Audio has no playback control.`);return}return this.loop=e,this.isPlaying===!0&&(this.source.loop=this.loop),this}setLoopStart(e){return this.loopStart=e,this}setLoopEnd(e){return this.loopEnd=e,this}getVolume(){return this.gain.gain.value}setVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}copy(e,t){return super.copy(e,t),e.sourceType===`buffer`?(this.autoplay=e.autoplay,this.buffer=e.buffer,this.detune=e.detune,this.loop=e.loop,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.offset=e.offset,this.duration=e.duration,this.playbackRate=e.playbackRate,this.hasPlaybackControl=e.hasPlaybackControl,this.sourceType=e.sourceType,this.filters=e.filters.slice(),this):(P(`Audio: Audio source type cannot be copied.`),this)}clone(e){return new this.constructor(this.listener).copy(this,e)}},Sd=new B,Cd=new z,J=new B,wd=new B,Td=class extends xd{constructor(e){super(e),this.panner=this.context.createPanner(),this.panner.panningModel=`HRTF`,this.panner.connect(this.gain)}connect(){return super.connect(),this.panner.connect(this.gain),this}disconnect(){return super.disconnect(),this.panner.disconnect(this.gain),this}getOutput(){return this.panner}getRefDistance(){return this.panner.refDistance}setRefDistance(e){return this.panner.refDistance=e,this}getRolloffFactor(){return this.panner.rolloffFactor}setRolloffFactor(e){return this.panner.rolloffFactor=e,this}getDistanceModel(){return this.panner.distanceModel}setDistanceModel(e){return this.panner.distanceModel=e,this}getMaxDistance(){return this.panner.maxDistance}setMaxDistance(e){return this.panner.maxDistance=e,this}setDirectionalCone(e,t,n){return this.panner.coneInnerAngle=e,this.panner.coneOuterAngle=t,this.panner.coneOuterGain=n,this}updateMatrixWorld(e){if(super.updateMatrixWorld(e),this.hasPlaybackControl===!0&&this.isPlaying===!1)return;this.matrixWorld.decompose(Sd,Cd,J),wd.set(0,0,1).applyQuaternion(Cd);let t=this.panner;if(t.positionX){let e=this.context.currentTime+this.listener.timeDelta;t.positionX.linearRampToValueAtTime(Sd.x,e),t.positionY.linearRampToValueAtTime(Sd.y,e),t.positionZ.linearRampToValueAtTime(Sd.z,e),t.orientationX.linearRampToValueAtTime(wd.x,e),t.orientationY.linearRampToValueAtTime(wd.y,e),t.orientationZ.linearRampToValueAtTime(wd.z,e)}else t.setPosition(Sd.x,Sd.y,Sd.z),t.setOrientation(wd.x,wd.y,wd.z)}},Ed=class{constructor(e,t=2048){this.analyser=e.context.createAnalyser(),this.analyser.fftSize=t,this.data=new Uint8Array(this.analyser.frequencyBinCount),e.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let e=0,t=this.getFrequencyData();for(let n=0;n<t.length;n++)e+=t[n];return e/t.length}},Dd=class{constructor(e,t,n){this.binding=e,this.valueSize=n;let r,i,a;switch(t){case`quaternion`:r=this._slerp,i=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case`string`:case`bool`:r=this._select,i=this._select,a=this._setAdditiveIdentityOther,this.buffer=Array(n*5);break;default:r=this._lerp,i=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=r,this._mixBufferRegionAdditive=i,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let n=this.buffer,r=this.valueSize,i=e*r+r,a=this.cumulativeWeight;if(a===0){for(let e=0;e!==r;++e)n[i+e]=n[e];a=t}else{a+=t;let e=t/a;this._mixBufferRegion(n,i,0,e,r)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,r=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,r,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,r=e*t+t,i=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,i<1){let e=t*this._origIndex;this._mixBufferRegion(n,r,e,1-i,t)}a>0&&this._mixBufferRegionAdditive(n,r,this._addIndex*t,1,t);for(let e=t,i=t+t;e!==i;++e)if(n[e]!==n[e+t]){o.setValue(n,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,r=n*this._origIndex;e.getValue(t,r);for(let e=n,i=r;e!==i;++e)t[e]=t[r+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n<t;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[t+n]=this.buffer[e+n]}_select(e,t,n,r,i){if(r>=.5)for(let r=0;r!==i;++r)e[t+r]=e[n+r]}_slerp(e,t,n,r){z.slerpFlat(e,t,e,t,e,n,r)}_slerpAdditive(e,t,n,r,i){let a=this._workIndex*i;z.multiplyQuaternionsFlat(e,a,e,t,e,n),z.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,n,r,i){let a=1-r;for(let o=0;o!==i;++o){let i=t+o;e[i]=e[i]*a+e[n+o]*r}}_lerpAdditive(e,t,n,r,i){for(let a=0;a!==i;++a){let i=t+a;e[i]=e[i]+e[n+a]*r}}},Od=`\\[\\]\\.:\\/`,kd=RegExp(`[\\[\\]\\.:\\/]`,`g`),Ad=`[^\\[\\]\\.:\\/]`,jd=`[^`+Od.replace(`\\.`,``)+`]`,Md=`((?:WC+[\\/:])*)`.replace(`WC`,Ad),Nd=`(WCOD+)?`.replace(`WCOD`,jd),Pd=`(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,Ad),Fd=`\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,Ad),Id=RegExp(`^`+Md+Nd+Pd+Fd+`$`),Ld=[`material`,`materials`,`bones`,`map`],Rd=class{constructor(e,t,n){let r=n||Y.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},Y=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(kd,``)}static parseTrackName(e){let t=Id.exec(e);if(t===null)throw Error(`THREE.PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);Ld.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`THREE.PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){P(`PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){F(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){F(`PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){F(`PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){F(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){F(`PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){F(`PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){F(`PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;F(`PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){F(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){F(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};Y.Composite=Rd,Y.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Y.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Y.prototype.GetterByBindingType=[Y.prototype._getValue_direct,Y.prototype._getValue_array,Y.prototype._getValue_arrayElement,Y.prototype._getValue_toArray],Y.prototype.SetterByBindingTypeAndVersioning=[[Y.prototype._setValue_direct,Y.prototype._setValue_direct_setNeedsUpdate,Y.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Y.prototype._setValue_array,Y.prototype._setValue_array_setNeedsUpdate,Y.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Y.prototype._setValue_arrayElement,Y.prototype._setValue_arrayElement_setNeedsUpdate,Y.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Y.prototype._setValue_fromArray,Y.prototype._setValue_fromArray_setNeedsUpdate,Y.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var zd=class{constructor(){this.isAnimationObjectGroup=!0,this.uuid=Sn(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;let e={};this._indicesByUUID=e;for(let t=0,n=arguments.length;t!==n;++t)e[arguments[t].uuid]=t;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};let t=this;this.stats={objects:{get total(){return t._objects.length},get inUse(){return this.total-t.nCachedObjects_}},get bindingsPerObject(){return t._bindings.length}}}add(){let e=this._objects,t=this._indicesByUUID,n=this._paths,r=this._parsedPaths,i=this._bindings,a=i.length,o,s=e.length,c=this.nCachedObjects_;for(let l=0,u=arguments.length;l!==u;++l){let u=arguments[l],d=u.uuid,f=t[d];if(f===void 0){f=s++,t[d]=f,e.push(u);for(let e=0,t=a;e!==t;++e)i[e].push(new Y(u,n[e],r[e]))}else if(f<c){o=e[f];let s=--c,l=e[s];t[l.uuid]=f,e[f]=l,t[d]=s,e[s]=u;for(let e=0,t=a;e!==t;++e){let t=i[e],a=t[s],o=t[f];t[f]=a,o===void 0&&(o=new Y(u,n[e],r[e])),t[s]=o}}else e[f]!==o&&F(`AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.`)}this.nCachedObjects_=c}remove(){let e=this._objects,t=this._indicesByUUID,n=this._bindings,r=n.length,i=this.nCachedObjects_;for(let a=0,o=arguments.length;a!==o;++a){let o=arguments[a],s=o.uuid,c=t[s];if(c!==void 0&&c>=i){let a=i++,l=e[a];t[l.uuid]=c,e[c]=l,t[s]=a,e[a]=o;for(let e=0,t=r;e!==t;++e){let t=n[e],r=t[a],i=t[c];t[c]=r,t[a]=i}}}this.nCachedObjects_=i}uncache(){let e=this._objects,t=this._indicesByUUID,n=this._bindings,r=n.length,i=this.nCachedObjects_,a=e.length;for(let o=0,s=arguments.length;o!==s;++o){let s=arguments[o].uuid,c=t[s];if(c!==void 0)if(delete t[s],c<i){let o=--i,s=e[o],l=--a,u=e[l];t[s.uuid]=c,e[c]=s,t[u.uuid]=o,e[o]=u,e.pop();for(let e=0,t=r;e!==t;++e){let t=n[e],r=t[o],i=t[l];t[c]=r,t[o]=i,t.pop()}}else{let i=--a,o=e[i];i>0&&(t[o.uuid]=c),e[c]=o,e.pop();for(let e=0,t=r;e!==t;++e){let t=n[e];t[c]=t[i],t.pop()}}}this.nCachedObjects_=i}subscribe_(e,t){let n=this._bindingsIndicesByPath,r=n[e],i=this._bindings;if(r!==void 0)return i[r];let a=this._paths,o=this._parsedPaths,s=this._objects,c=s.length,l=this.nCachedObjects_,u=Array(c);r=i.length,n[e]=r,a.push(e),o.push(t),i.push(u);for(let n=l,r=s.length;n!==r;++n){let r=s[n];u[n]=new Y(r,e,t)}return u}unsubscribe_(e){let t=this._bindingsIndicesByPath,n=t[e];if(n!==void 0){let r=this._paths,i=this._parsedPaths,a=this._bindings,o=a.length-1,s=a[o],c=e[o];t[c]=n,a[n]=s,a.pop(),i[n]=i[o],i.pop(),r[n]=r[o],r.pop()}}},Bd=class{constructor(e,t,n=null,r=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=r;let i=t.tracks,a=i.length,o=Array(a),s={endingStart:yt,endingEnd:yt};for(let e=0;e!==a;++e){let t=i[e].createInterpolant(null);o[e]=t,t.settings=s}this._interpolantSettings=s,this._interpolants=o,this._propertyBindings=Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._restoreTimeScale=null,this._weightInterpolant=null,this.loop=pt,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),n===!0){let n=this._clip.duration,r=e._clip.duration,i=r/n,a=n/r;e._restoreTimeScale=e.timeScale,this._restoreTimeScale=this.timeScale,e.warp(1,i,t),this.warp(a,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){let r=this._mixer,i=r.time,a=this.timeScale,o=this._timeScaleInterpolant;o===null&&(o=r._lendControlInterpolant(),this._timeScaleInterpolant=o);let s=o.parameterPositions,c=o.sampleValues;return s[0]=i,s[1]=i+n,c[0]=e/a,c[1]=t/a,this}stopWarping(){let e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this._restoreTimeScale=null,this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,r){if(!this.enabled){this._updateWeight(e);return}let i=this._startTime;if(i!==null){let r=(e-i)*n;r<0||n===0?t=0:(this._startTime=null,t=n*r)}t*=this._updateTimeScale(e);let a=this._updateTime(t),o=this._updateWeight(e);if(o>0){let e=this._interpolants,t=this._propertyBindings;switch(this.blendMode){case Ct:for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(a),t[n].accumulateAdditive(o);break;case St:default:for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(a),t[n].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(t===0?this.paused=!0:(this._restoreTimeScale!==null&&(t=this._restoreTimeScale),this.timeScale=t),this.stopWarping())}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,r=this.time+e,i=this._loopCount,a=n===mt;if(e===0)return i===-1?r:a&&(i&1)==1?t-r:r;if(n===2200){i===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));handle_stop:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break handle_stop}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e<0?-1:1})}}else{if(i===-1&&(e>=0?(i=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let n=Math.floor(r/t);r-=t*n,i+=Math.abs(n);let o=this.repetitions-i;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e>0?1:-1});else{if(o===1){let t=e<0;this._setEndings(t,!t,a)}else this._setEndings(!1,!1,a);this._loopCount=i,this.time=r,this._mixer.dispatchEvent({type:`loop`,action:this,loopDelta:n})}}else this._loopCount=i,this.time=r;if(a&&(i&1)==1)return t-r}return r}_setEndings(e,t,n){let r=this._interpolantSettings;n?(r.endingStart=bt,r.endingEnd=bt):(r.endingStart=e?this.zeroSlopeAtStart?bt:yt:xt,r.endingEnd=t?this.zeroSlopeAtEnd?bt:yt:xt)}_scheduleFading(e,t,n){let r=this._mixer,i=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,s=a.sampleValues;return o[0]=i,s[0]=t,o[1]=i+e,s[1]=n,this}},Vd=new Float32Array(1),Hd=class extends _n{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}_bindAction(e,t){let n=e._localRoot||this._root,r=e._clip.tracks,i=r.length,a=e._propertyBindings,o=e._interpolants,s=n.uuid,c=this._bindingsByRootAndName,l=c[s];l===void 0&&(l={},c[s]=l);for(let e=0;e!==i;++e){let i=r[e],c=i.name,u=l[c];if(u!==void 0)++u.referenceCount,a[e]=u;else{if(u=a[e],u!==void 0){u._cacheIndex===null&&(++u.referenceCount,this._addInactiveBinding(u,s,c));continue}let r=t&&t._propertyBindings[e].binding.parsedPath;u=new Dd(Y.create(n,c,r),i.ValueTypeName,i.getValueSize()),++u.referenceCount,this._addInactiveBinding(u,s,c),a[e]=u}o[e].resultBuffer=u.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let t=(e._localRoot||this._root).uuid,n=e._clip.uuid,r=this._actionsByClip[n];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,n,t)}let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];n.useCount++===0&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.useCount===0&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,n){let r=this._actions,i=this._actionsByClip,a=i[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,i[t]=a;else{let t=a.knownActions;e._byClipCacheIndex=t.length,t.push(e)}e._cacheIndex=r.length,r.push(e),a.actionByRoot[n]=e}_removeInactiveAction(e){let t=this._actions,n=t[t.length-1],r=e._cacheIndex;n._cacheIndex=r,t[r]=n,t.pop(),e._cacheIndex=null;let i=e._clip.uuid,a=this._actionsByClip,o=a[i],s=o.knownActions,c=s[s.length-1],l=e._byClipCacheIndex;c._byClipCacheIndex=l,s[l]=c,s.pop(),e._byClipCacheIndex=null;let u=o.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],s.length===0&&delete a[i],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.referenceCount===0&&this._removeInactiveBinding(n)}}_lendAction(e){let t=this._actions,n=e._cacheIndex,r=this._nActiveActions++,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_takeBackAction(e){let t=this._actions,n=e._cacheIndex,r=--this._nActiveActions,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_addInactiveBinding(e,t,n){let r=this._bindingsByRootAndName,i=this._bindings,a=r[t];a===void 0&&(a={},r[t]=a),a[n]=e,e._cacheIndex=i.length,i.push(e)}_removeInactiveBinding(e){let t=this._bindings,n=e.binding,r=n.rootNode.uuid,i=n.path,a=this._bindingsByRootAndName,o=a[r],s=t[t.length-1],c=e._cacheIndex;s._cacheIndex=c,t[c]=s,t.pop(),delete o[i],Object.keys(o).length===0&&delete a[r]}_lendBinding(e){let t=this._bindings,n=e._cacheIndex,r=this._nActiveBindings++,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_takeBackBinding(e){let t=this._bindings,n=e._cacheIndex,r=--this._nActiveBindings,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,n=e[t];return n===void 0&&(n=new Wl(new Float32Array(2),new Float32Array(2),1,Vd),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){let t=this._controlInterpolants,n=e.__cacheIndex,r=--this._nActiveControlInterpolants,i=t[r];e.__cacheIndex=r,t[r]=e,i.__cacheIndex=n,t[n]=i}clipAction(e,t,n){let r=t||this._root,i=r.uuid,a=typeof e==`string`?tu.findByName(r,e):e,o=a===null?e:a.uuid,s=this._actionsByClip[o],c=null;if(n===void 0&&(n=a===null?St:a.blendMode),s!==void 0){let e=s.actionByRoot[i];if(e!==void 0&&e.blendMode===n)return e;c=s.knownActions[0],a===null&&(a=c._clip)}if(a===null)return null;let l=new Bd(this,a,t,n);return this._bindAction(l,c),this._addInactiveAction(l,o,i),l}existingAction(e,t){let n=t||this._root,r=n.uuid,i=typeof e==`string`?tu.findByName(n,e):e,a=i?i.uuid:e,o=this._actionsByClip[a];return o===void 0?null:o.actionByRoot[r]||null}stopAllAction(){let e=this._actions,t=this._nActiveActions;for(let n=t-1;n>=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,r=this.time+=e,i=Math.sign(e),a=this._accuIndex^=1;for(let o=0;o!==n;++o)t[o]._update(r,e,i,a);let o=this._bindings,s=this._nActiveBindings;for(let e=0;e!==s;++e)o[e].apply(a);return this}setTime(e){this.time=0;for(let e=0;e<this._actions.length;e++)this._actions[e].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){let t=this._actions,n=e.uuid,r=this._actionsByClip,i=r[n];if(i!==void 0){let e=i.knownActions;for(let n=0,r=e.length;n!==r;++n){let r=e[n];this._deactivateAction(r);let i=r._cacheIndex,a=t[t.length-1];r._cacheIndex=null,r._byClipCacheIndex=null,a._cacheIndex=i,t[i]=a,t.pop(),this._removeInactiveBindingsForAction(r)}delete r[n]}}uncacheRoot(e){let t=e.uuid,n=this._actionsByClip;for(let e in n){let r=n[e].actionByRoot[t];r!==void 0&&(this._deactivateAction(r),this._removeInactiveAction(r))}let r=this._bindingsByRootAndName[t];if(r!==void 0)for(let e in r){let t=r[e];t.restoreOriginalState(),this._removeInactiveBinding(t)}}uncacheAction(e,t){let n=this.existingAction(e,t);n!==null&&(this._deactivateAction(n),this._removeInactiveAction(n))}},Ud=class extends cr{constructor(e=1,t=1,n=1,r={}){super(e,t,r),this.isRenderTarget3D=!0,this.depth=n,this.texture=new fr(null,e,t,n),this._setTextureOptions(r),this.texture.isRenderTargetTexture=!0}},Wd=class e{constructor(e){this.value=e}clone(){return new e(this.value.clone===void 0?this.value:this.value.clone())}},Gd=0,Kd=class extends _n{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:Gd++}),this.name=``,this.usage=zt,this.uniforms=[]}add(e){return this.uniforms.push(e),this}remove(e){let t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}setName(e){return this.name=e,this}setUsage(e){return this.usage=e,this}dispose(){this.dispatchEvent({type:`dispose`})}copy(e){this.name=e.name,this.usage=e.usage;let t=e.uniforms;this.uniforms.length=0;for(let e=0,n=t.length;e<n;e++){let n=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0;e<n.length;e++)this.uniforms.push(n[e].clone())}return this}clone(){return new this.constructor().copy(this)}},qd=class extends ta{constructor(e,t,n=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){let t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){let t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}},Jd=class{constructor(e,t,n,r,i,a=!1){this.isGLBufferAttribute=!0,this.name=``,this.buffer=e,this.type=t,this.itemSize=n,this.elementSize=r,this.count=i,this.normalized=a,this.version=0}set needsUpdate(e){e===!0&&this.version++}setBuffer(e){return this.buffer=e,this}setType(e,t){return this.type=e,this.elementSize=t,this}setItemSize(e){return this.itemSize=e,this}setCount(e){return this.count=e,this}},Yd=new V,Xd=class{constructor(e,t,n=0,r=1/0){this.ray=new Ma(e,t),this.near=n,this.far=r,this.camera=null,this.layers=new wr,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,t.projectionMatrix.elements[14]).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):F(`Raycaster: Unsupported camera type: `+t.type)}setFromXRController(e){return Yd.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(Yd),this}intersectObject(e,t=!0,n=[]){return Qd(e,this,n,t),n.sort(Zd),n}intersectObjects(e,t=!0,n=[]){for(let r=0,i=e.length;r<i;r++)Qd(e[r],this,n,t);return n.sort(Zd),n}};function Zd(e,t){return e.distance-t.distance}function Qd(e,t,n,r){let i=!0;if(e.layers.test(t.layers)&&e.raycast(t,n)===!1&&(i=!1),i===!0&&r===!0){let r=e.children;for(let e=0,i=r.length;e<i;e++)Qd(r[e],t,n,!0)}}var $d=class{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1,P(`Clock: This module has been deprecated. Please use THREE.Timer instead.`)}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){let t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}},ef=class{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){let e=1e-6;return this.phi=I(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(I(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}},tf=class{constructor(e=1,t=0,n=0){this.radius=e,this.theta=t,this.y=n}set(e,t,n){return this.radius=e,this.theta=t,this.y=n,this}copy(e){return this.radius=e.radius,this.theta=e.theta,this.y=e.y,this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+n*n),this.theta=Math.atan2(e,n),this.y=t,this}clone(){return new this.constructor().copy(this)}},nf=class e{static{e.prototype.isMatrix2=!0}constructor(e,t,n,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){let i=this.elements;return i[0]=e,i[2]=t,i[1]=n,i[3]=r,this}},rf=new R,af=class{constructor(e=new R(1/0,1/0),t=new R(-1/0,-1/0)){this.isBox2=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=rf.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y}getCenter(e){return this.isEmpty()?e.set(0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,rf).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}},of=new B,sf=new B,cf=new B,lf=new B,uf=new B,df=new B,ff=new B,pf=class{constructor(e=new B,t=new B){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){of.subVectors(e,this.start),sf.subVectors(this.end,this.start);let n=sf.dot(sf);if(n===0)return 0;let r=sf.dot(of)/n;return t&&(r=I(r,0,1)),r}closestPointToPoint(e,t,n){let r=this.closestPointToPointParameter(e,t);return this.delta(n).multiplyScalar(r).add(this.start)}distanceSqToLine3(e,t=df,n=ff){let r=1e-8*1e-8,i,a,o=this.start,s=e.start,c=this.end,l=e.end;cf.subVectors(c,o),lf.subVectors(l,s),uf.subVectors(o,s);let u=cf.dot(cf),d=lf.dot(lf),f=lf.dot(uf);if(u<=r&&d<=r)return t.copy(o),n.copy(s),t.sub(n),t.dot(t);if(u<=r)i=0,a=f/d,a=I(a,0,1);else{let e=cf.dot(uf);if(d<=r)a=0,i=I(-e/u,0,1);else{let t=cf.dot(lf),n=u*d-t*t;i=n===0?0:I((t*f-e*d)/n,0,1),a=(t*i+f)/d,a<0?(a=0,i=I(-e/u,0,1)):a>1&&(a=1,i=I((t-e)/u,0,1))}}return t.copy(o).addScaledVector(cf,i),n.copy(s).addScaledVector(lf,a),t.distanceToSquared(n)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}},mf=new B,hf=class extends Br{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type=`SpotLightHelper`;let n=new W,r=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let e=0,t=1;e<32;e++,t++){let n=e/32*Math.PI*2,i=t/32*Math.PI*2;r.push(Math.cos(n),Math.sin(n),1,Math.cos(i),Math.sin(i),1)}n.setAttribute(`position`,new U(r,3));let i=new qo({fog:!1,toneMapped:!1});this.cone=new as(n,i),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),this.parent?(this.parent.updateWorldMatrix(!0),this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)):this.matrix.copy(this.light.matrixWorld),this.matrixWorldNeedsUpdate=!0;let e=this.light.distance?this.light.distance:1e3,t=e*Math.tan(this.light.angle);this.cone.scale.set(t,t,e),mf.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(mf),this.color===void 0?this.cone.material.color.copy(this.light.color):this.cone.material.color.set(this.color)}},gf=new B,_f=new V,vf=new V,yf=class extends as{constructor(e){let t=bf(e),n=new W,r=[],i=[];for(let e=0;e<t.length;e++){let n=t[e];n.parent&&n.parent.isBone&&(r.push(0,0,0),r.push(0,0,0),i.push(0,0,0),i.push(0,0,0))}n.setAttribute(`position`,new U(r,3)),n.setAttribute(`color`,new U(i,3));let a=new qo({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});super(n,a),this.isSkeletonHelper=!0,this.type=`SkeletonHelper`,this.root=e,this.bones=t,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1;let o=new H(255),s=new H(65280);this.setColors(o,s)}updateMatrixWorld(e){let t=this.bones,n=this.geometry,r=n.getAttribute(`position`);vf.copy(this.root.matrixWorld).invert();for(let e=0,n=0;e<t.length;e++){let i=t[e];i.parent&&i.parent.isBone&&(_f.multiplyMatrices(vf,i.matrixWorld),gf.setFromMatrixPosition(_f),r.setXYZ(n,gf.x,gf.y,gf.z),_f.multiplyMatrices(vf,i.parent.matrixWorld),gf.setFromMatrixPosition(_f),r.setXYZ(n+1,gf.x,gf.y,gf.z),n+=2)}n.getAttribute(`position`).needsUpdate=!0,super.updateMatrixWorld(e)}setColors(e,t){let n=this.geometry.getAttribute(`color`);for(let r=0;r<n.count;r+=2)n.setXYZ(r,e.r,e.g,e.b),n.setXYZ(r+1,t.r,t.g,t.b);return n.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}};function bf(e){let t=[];e.isBone===!0&&t.push(e);for(let n=0;n<e.children.length;n++)t.push(...bf(e.children[n]));return t}var xf=class extends Ga{constructor(e,t,n){let r=new cl(t,4,2),i=new Na({wireframe:!0,fog:!1,toneMapped:!1});super(r,i),this.light=e,this.color=n,this.type=`PointLightHelper`,this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1,this.update()}dispose(){this.geometry.dispose(),this.material.dispose()}update(){this.matrixWorldNeedsUpdate=!0,this.light.updateWorldMatrix(!0,!1),this.color===void 0?this.material.color.copy(this.light.color):this.material.color.set(this.color)}},Sf=new B,Cf=new H,wf=new H,Tf=class extends Br{constructor(e,t,n){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=n,this.type=`HemisphereLightHelper`;let r=new rl(t);r.rotateY(Math.PI*.5),this.material=new Na({wireframe:!0,fog:!1,toneMapped:!1}),this.color===void 0&&(this.material.vertexColors=!0);let i=r.getAttribute(`position`),a=new Float32Array(i.count*3);r.setAttribute(`color`,new Fi(a,3)),this.add(new Ga(r,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){let e=this.children[0];if(this.color!==void 0)this.material.color.set(this.color);else{let t=e.geometry.getAttribute(`color`);Cf.copy(this.light.color),wf.copy(this.light.groundColor);for(let e=0,n=t.count;e<n;e++){let r=e<n/2?Cf:wf;t.setXYZ(e,r.r,r.g,r.b)}t.needsUpdate=!0}this.matrixWorldNeedsUpdate=!0,this.light.updateWorldMatrix(!0,!1),e.lookAt(Sf.setFromMatrixPosition(this.light.matrixWorld).negate())}},Ef=class extends as{constructor(e=10,t=10,n=4473924,r=8947848){n=new H(n),r=new H(r);let i=t/2,a=e/t,o=e/2,s=[],c=[];for(let e=0,l=0,u=-o;e<=t;e++,u+=a){s.push(-o,0,u,o,0,u),s.push(u,0,-o,u,0,o);let t=e===i?n:r;t.toArray(c,l),l+=3,t.toArray(c,l),l+=3,t.toArray(c,l),l+=3,t.toArray(c,l),l+=3}let l=new W;l.setAttribute(`position`,new U(s,3)),l.setAttribute(`color`,new U(c,3));let u=new qo({vertexColors:!0,toneMapped:!1});super(l,u),this.type=`GridHelper`}dispose(){this.geometry.dispose(),this.material.dispose()}},Df=class extends as{constructor(e=10,t=16,n=8,r=64,i=4473924,a=8947848){i=new H(i),a=new H(a);let o=[],s=[];if(t>1)for(let n=0;n<t;n++){let r=n/t*(Math.PI*2),c=Math.sin(r)*e,l=Math.cos(r)*e;o.push(0,0,0),o.push(c,0,l);let u=n&1?i:a;s.push(u.r,u.g,u.b),s.push(u.r,u.g,u.b)}for(let t=0;t<n;t++){let c=t&1?i:a,l=e-e/n*t;for(let e=0;e<r;e++){let t=e/r*(Math.PI*2),n=Math.sin(t)*l,i=Math.cos(t)*l;o.push(n,0,i),s.push(c.r,c.g,c.b),t=(e+1)/r*(Math.PI*2),n=Math.sin(t)*l,i=Math.cos(t)*l,o.push(n,0,i),s.push(c.r,c.g,c.b)}}let c=new W;c.setAttribute(`position`,new U(o,3)),c.setAttribute(`color`,new U(s,3));let l=new qo({vertexColors:!0,toneMapped:!1});super(c,l),this.type=`PolarGridHelper`}dispose(){this.geometry.dispose(),this.material.dispose()}},Of=new B,kf=new B,Af=new B,jf=class extends Br{constructor(e,t,n){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=n,this.type=`DirectionalLightHelper`,t===void 0&&(t=1);let r=new W;r.setAttribute(`position`,new U([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));let i=new qo({fog:!1,toneMapped:!1});this.lightPlane=new ts(r,i),this.add(this.lightPlane),r=new W,r.setAttribute(`position`,new U([0,0,0,0,0,1],3)),this.targetLine=new ts(r,i),this.add(this.targetLine),this.update()}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()}update(){this.matrixWorldNeedsUpdate=!0,this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),Of.setFromMatrixPosition(this.light.matrixWorld),kf.setFromMatrixPosition(this.light.target.matrixWorld),Af.subVectors(kf,Of),this.lightPlane.lookAt(kf),this.color===void 0?(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color)):(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)),this.targetLine.lookAt(kf),this.targetLine.scale.z=Af.length()}},Mf=new B,Nf=new Ou,Pf=class extends as{constructor(e){let t=new W,n=new qo({color:16777215,vertexColors:!0,toneMapped:!1}),r=[],i=[],a={};o(`n1`,`n2`),o(`n2`,`n4`),o(`n4`,`n3`),o(`n3`,`n1`),o(`f1`,`f2`),o(`f2`,`f4`),o(`f4`,`f3`),o(`f3`,`f1`),o(`n1`,`f1`),o(`n2`,`f2`),o(`n3`,`f3`),o(`n4`,`f4`),o(`p`,`n1`),o(`p`,`n2`),o(`p`,`n3`),o(`p`,`n4`),o(`u1`,`u2`),o(`u2`,`u3`),o(`u3`,`u1`),o(`c`,`t`),o(`p`,`c`),o(`cn1`,`cn2`),o(`cn3`,`cn4`),o(`cf1`,`cf2`),o(`cf3`,`cf4`);function o(e,t){s(e),s(t)}function s(e){r.push(0,0,0),i.push(0,0,0),a[e]===void 0&&(a[e]=[]),a[e].push(r.length/3-1)}t.setAttribute(`position`,new U(r,3)),t.setAttribute(`color`,new U(i,3)),super(t,n),this.type=`CameraHelper`,this.camera=e,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=a,this.update();let c=new H(16755200),l=new H(16711680),u=new H(43775),d=new H(16777215),f=new H(3355443);this.setColors(c,l,u,d,f)}setColors(e,t,n,r,i){let a=this.geometry.getAttribute(`color`);return a.setXYZ(0,e.r,e.g,e.b),a.setXYZ(1,e.r,e.g,e.b),a.setXYZ(2,e.r,e.g,e.b),a.setXYZ(3,e.r,e.g,e.b),a.setXYZ(4,e.r,e.g,e.b),a.setXYZ(5,e.r,e.g,e.b),a.setXYZ(6,e.r,e.g,e.b),a.setXYZ(7,e.r,e.g,e.b),a.setXYZ(8,e.r,e.g,e.b),a.setXYZ(9,e.r,e.g,e.b),a.setXYZ(10,e.r,e.g,e.b),a.setXYZ(11,e.r,e.g,e.b),a.setXYZ(12,e.r,e.g,e.b),a.setXYZ(13,e.r,e.g,e.b),a.setXYZ(14,e.r,e.g,e.b),a.setXYZ(15,e.r,e.g,e.b),a.setXYZ(16,e.r,e.g,e.b),a.setXYZ(17,e.r,e.g,e.b),a.setXYZ(18,e.r,e.g,e.b),a.setXYZ(19,e.r,e.g,e.b),a.setXYZ(20,e.r,e.g,e.b),a.setXYZ(21,e.r,e.g,e.b),a.setXYZ(22,e.r,e.g,e.b),a.setXYZ(23,e.r,e.g,e.b),a.setXYZ(24,t.r,t.g,t.b),a.setXYZ(25,t.r,t.g,t.b),a.setXYZ(26,t.r,t.g,t.b),a.setXYZ(27,t.r,t.g,t.b),a.setXYZ(28,t.r,t.g,t.b),a.setXYZ(29,t.r,t.g,t.b),a.setXYZ(30,t.r,t.g,t.b),a.setXYZ(31,t.r,t.g,t.b),a.setXYZ(32,n.r,n.g,n.b),a.setXYZ(33,n.r,n.g,n.b),a.setXYZ(34,n.r,n.g,n.b),a.setXYZ(35,n.r,n.g,n.b),a.setXYZ(36,n.r,n.g,n.b),a.setXYZ(37,n.r,n.g,n.b),a.setXYZ(38,r.r,r.g,r.b),a.setXYZ(39,r.r,r.g,r.b),a.setXYZ(40,i.r,i.g,i.b),a.setXYZ(41,i.r,i.g,i.b),a.setXYZ(42,i.r,i.g,i.b),a.setXYZ(43,i.r,i.g,i.b),a.setXYZ(44,i.r,i.g,i.b),a.setXYZ(45,i.r,i.g,i.b),a.setXYZ(46,i.r,i.g,i.b),a.setXYZ(47,i.r,i.g,i.b),a.setXYZ(48,i.r,i.g,i.b),a.setXYZ(49,i.r,i.g,i.b),a.needsUpdate=!0,this}update(){let e=this.geometry,t=this.pointMap,n,r;if(Nf.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),this.camera.reversedDepth===!0)n=1,r=0;else if(this.camera.coordinateSystem===2e3)n=-1,r=1;else if(this.camera.coordinateSystem===2001)n=0,r=1;else throw Error(`THREE.CameraHelper.update(): Invalid coordinate system: `+this.camera.coordinateSystem);Ff(`c`,t,e,Nf,0,0,n),Ff(`t`,t,e,Nf,0,0,r),Ff(`n1`,t,e,Nf,-1,-1,n),Ff(`n2`,t,e,Nf,1,-1,n),Ff(`n3`,t,e,Nf,-1,1,n),Ff(`n4`,t,e,Nf,1,1,n),Ff(`f1`,t,e,Nf,-1,-1,r),Ff(`f2`,t,e,Nf,1,-1,r),Ff(`f3`,t,e,Nf,-1,1,r),Ff(`f4`,t,e,Nf,1,1,r),Ff(`u1`,t,e,Nf,.7,1.1,n),Ff(`u2`,t,e,Nf,-.7,1.1,n),Ff(`u3`,t,e,Nf,0,2,n),Ff(`cf1`,t,e,Nf,-1,0,r),Ff(`cf2`,t,e,Nf,1,0,r),Ff(`cf3`,t,e,Nf,0,-1,r),Ff(`cf4`,t,e,Nf,0,1,r),Ff(`cn1`,t,e,Nf,-1,0,n),Ff(`cn2`,t,e,Nf,1,0,n),Ff(`cn3`,t,e,Nf,0,-1,n),Ff(`cn4`,t,e,Nf,0,1,n),e.getAttribute(`position`).needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}};function Ff(e,t,n,r,i,a,o){Mf.set(i,a,o).unproject(r);let s=t[e];if(s!==void 0){let e=n.getAttribute(`position`);for(let t=0,n=s.length;t<n;t++)e.setXYZ(s[t],Mf.x,Mf.y,Mf.z)}}var If=new fi,Lf=class extends as{constructor(e,t=16776960){let n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),r=new Float32Array(24),i=new W;i.setIndex(new Fi(n,1)),i.setAttribute(`position`,new Fi(r,3)),super(i,new qo({color:t,toneMapped:!1})),this.object=e,this.type=`BoxHelper`,this.matrixAutoUpdate=!1,this.update()}update(){if(this.object!==void 0&&If.setFromObject(this.object),If.isEmpty())return;let e=If.min,t=If.max,n=this.geometry.attributes.position,r=n.array;r[0]=t.x,r[1]=t.y,r[2]=t.z,r[3]=e.x,r[4]=t.y,r[5]=t.z,r[6]=e.x,r[7]=e.y,r[8]=t.z,r[9]=t.x,r[10]=e.y,r[11]=t.z,r[12]=t.x,r[13]=t.y,r[14]=e.z,r[15]=e.x,r[16]=t.y,r[17]=e.z,r[18]=e.x,r[19]=e.y,r[20]=e.z,r[21]=t.x,r[22]=e.y,r[23]=e.z,n.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(e){return this.object=e,this.update(),this}copy(e,t){return super.copy(e,t),this.object=e.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}},Rf=class extends as{constructor(e,t=16776960){let n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),r=[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],i=new W;i.setIndex(new Fi(n,1)),i.setAttribute(`position`,new U(r,3)),super(i,new qo({color:t,toneMapped:!1})),this.box=e,this.type=`Box3Helper`,this.geometry.computeBoundingSphere()}updateMatrixWorld(e){let t=this.box;t.isEmpty()||(t.getCenter(this.position),t.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(e))}dispose(){this.geometry.dispose(),this.material.dispose()}},zf=class extends ts{constructor(e,t=1,n=16776960){let r=n,i=[1,-1,0,-1,1,0,-1,-1,0,1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],a=new W;a.setAttribute(`position`,new U(i,3)),a.computeBoundingSphere(),super(a,new qo({color:r,toneMapped:!1})),this.type=`PlaneHelper`,this.plane=e,this.size=t;let o=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],s=new W;s.setAttribute(`position`,new U(o,3)),s.computeBoundingSphere(),this.add(new Ga(s,new Na({color:r,opacity:.2,transparent:!0,depthWrite:!1,toneMapped:!1})))}updateMatrixWorld(e){this.position.set(0,0,0),this.scale.set(.5*this.size,.5*this.size,1),this.lookAt(this.plane.normal),this.translateZ(-this.plane.constant),super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}},Bf=new B,Vf,Hf,Uf=class extends Br{constructor(e=new B(0,0,1),t=new B(0,0,0),n=1,r=16776960,i=n*.2,a=i*.2){super(),this.type=`ArrowHelper`,Vf===void 0&&(Vf=new W,Vf.setAttribute(`position`,new U([0,0,0,0,1,0],3)),Hf=new As(.5,1,5,1),Hf.translate(0,-.5,0)),this.position.copy(t),this.line=new ts(Vf,new qo({color:r,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new Ga(Hf,new Na({color:r,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(e),this.setLength(n,i,a)}setDirection(e){if(e.y>.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{Bf.set(e.z,0,-e.x).normalize();let t=Math.acos(e.y);this.quaternion.setFromAxisAngle(Bf,t)}}setLength(e,t=e*.2,n=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(n,t,n),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}},Wf=class extends as{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new W;r.setAttribute(`position`,new U(t,3)),r.setAttribute(`color`,new U(n,3));let i=new qo({vertexColors:!0,toneMapped:!1});super(r,i),this.type=`AxesHelper`}setColors(e,t,n){let r=new H,i=this.geometry.attributes.color.array;return r.set(e),r.toArray(i,0),r.toArray(i,3),r.set(t),r.toArray(i,6),r.toArray(i,9),r.set(n),r.toArray(i,12),r.toArray(i,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}},Gf=class{constructor(){this.type=`ShapePath`,this.color=new H,this.subPaths=[],this.currentPath=null,this.userData={}}moveTo(e,t){return this.currentPath=new pc,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,n,r){return this.currentPath.quadraticCurveTo(e,t,n,r),this}bezierCurveTo(e,t,n,r,i,a){return this.currentPath.bezierCurveTo(e,t,n,r,i,a),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(){function e(e,t){let n=!1,r=t.length;for(let i=0,a=r-1;i<r;a=i++){let r=t[i],o=t[a];r.y>e.y!=o.y>e.y&&e.x<(o.x-r.x)*(e.y-r.y)/(o.y-r.y)+r.x&&(n=!n)}return n}function t(t,n){let r=n.getCenter(new R);if(e(r,t))return r;let i=r.y,a=[],o=t.length;for(let e=0;e<o;e++){let n=t[e],r=t[(e+1)%o];if(n.y>i!=r.y>i){let e=n.x+(i-n.y)*(r.x-n.x)/(r.y-n.y);a.push(e)}}return a.length>1&&(a.sort((e,t)=>e-t),r.x=(a[0]+a[1])/2),r}let n=this.userData.style&&this.userData.style.fillRule||`nonzero`;n!==`nonzero`&&n!==`evenodd`&&(P(`Fill-rule "`+n+`" is not supported, falling back to "nonzero".`),n=`nonzero`);let r=n===`nonzero`?(e=>e!==0):(e=>!!(e&1)),i=[];for(let e of this.subPaths){let n=e.getPoints();if(n.length<3)continue;let r=Yc.area(n);if(r===0)continue;let a=new af;for(let e=0;e<n.length;e++)a.expandByPoint(n[e]);i.push({subPath:e,points:n,boundingBox:a,interiorPoint:t(n,a),absArea:Math.abs(r),winding:r<0?-1:1,container:null,exclude:!1,role:null})}i.sort((e,t)=>t.absArea-e.absArea);for(let t=0;t<i.length;t++){let n=i[t],a=0;for(let r=t-1;r>=0;r--){let t=i[r];if(t.boundingBox.containsBox(n.boundingBox)&&e(n.interiorPoint,t.points)){n.container=t.exclude?t.container:t,a=t.winding,n.winding+=a;break}}r(n.winding)===r(a)&&(n.exclude=!0)}for(let e of i)e.exclude||(e.role=e.container===null||e.container.role===`hole`?`outer`:`hole`);let a=[],o=new Map;for(let e of i){if(e.exclude||e.role!==`outer`)continue;let t=new mc;t.curves=e.subPath.curves,a.push(t),o.set(e,t)}for(let e of i){if(e.exclude||e.role!==`hole`)continue;let t=o.get(e.container);if(!t)continue;let n=new pc;n.curves=e.subPath.curves,t.holes.push(n)}return a}},Kf=class extends _n{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){P(`Controls: connect() now requires an element.`);return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}};function qf(e,t){let n=e.image&&e.image.width?e.image.width/e.image.height:1;return n>t?(e.repeat.x=1,e.repeat.y=n/t,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2):(e.repeat.x=t/n,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0),e}function Jf(e,t){let n=e.image&&e.image.width?e.image.width/e.image.height:1;return n>t?(e.repeat.x=t/n,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0):(e.repeat.x=1,e.repeat.y=n/t,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2),e}function Yf(e){return e.repeat.x=1,e.repeat.y=1,e.offset.x=0,e.offset.y=0,e}function Xf(e,t,n,r){let i=Zf(r);switch(n){case be:return e*t;case Te:return e*t/i.components*i.byteLength;case Ee:return e*t/i.components*i.byteLength;case De:return e*t*2/i.components*i.byteLength;case Oe:return e*t*2/i.components*i.byteLength;case xe:return e*t*3/i.components*i.byteLength;case Se:return e*t*4/i.components*i.byteLength;case Ae:return e*t*4/i.components*i.byteLength;case je:case Me:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Ne:case Pe:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ie:case N:return Math.max(e,16)*Math.max(t,8)/4;case Fe:case Le:return Math.max(e,8)*Math.max(t,8)/2;case Re:case ze:case Ve:case He:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Be:case Ue:case We:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ge:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ke:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case qe:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Je:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Ye:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case Xe:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Ze:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Qe:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case $e:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case et:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case tt:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case nt:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case rt:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case it:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case at:case ot:case st:return Math.ceil(e/4)*Math.ceil(t/4)*16;case ct:case lt:return Math.ceil(e/4)*Math.ceil(t/4)*8;case ut:case dt:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function Zf(e){switch(e){case se:case ce:return{byteLength:1,components:1};case ue:case le:case me:return{byteLength:2,components:1};case he:case ge:return{byteLength:2,components:4};case fe:case de:case pe:return{byteLength:4,components:1};case ve:case ye:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}var Qf=class{static contain(e,t){return qf(e,t)}static cover(e,t){return Jf(e,t)}static fill(e){return Yf(e)}static getByteLength(e,t,n,r){return Xf(e,t,n,r)}};typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`185`}})),typeof window<`u`&&(window.__THREE__?P(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`185`);var $f=[{id:`hips`,bone:`mixamorigHips`,label:`Hips`},{id:`spine`,bone:`mixamorigSpine`,label:`Spine`},{id:`chest`,bone:`mixamorigSpine1`,label:`Chest`},{id:`upperChest`,bone:`mixamorigSpine2`,label:`Upper Chest`},{id:`neck`,bone:`mixamorigNeck`,label:`Neck`},{id:`head`,bone:`mixamorigHead`,label:`Head`},{id:`lShoulder`,bone:`mixamorigLeftShoulder`,label:`L Shoulder`},{id:`rShoulder`,bone:`mixamorigRightShoulder`,label:`R Shoulder`},{id:`lArm`,bone:`mixamorigLeftArm`,label:`L Upper Arm`},{id:`rArm`,bone:`mixamorigRightArm`,label:`R Upper Arm`},{id:`lForeArm`,bone:`mixamorigLeftForeArm`,label:`L Forearm`},{id:`rForeArm`,bone:`mixamorigRightForeArm`,label:`R Forearm`},{id:`lHand`,bone:`mixamorigLeftHand`,label:`L Hand`},{id:`rHand`,bone:`mixamorigRightHand`,label:`R Hand`},{id:`lUpLeg`,bone:`mixamorigLeftUpLeg`,label:`L Thigh`},{id:`rUpLeg`,bone:`mixamorigRightUpLeg`,label:`R Thigh`},{id:`lLeg`,bone:`mixamorigLeftLeg`,label:`L Shin`},{id:`rLeg`,bone:`mixamorigRightLeg`,label:`R Shin`},{id:`lFoot`,bone:`mixamorigLeftFoot`,label:`L Foot`},{id:`rFoot`,bone:`mixamorigRightFoot`,label:`R Foot`}];function ep(e){return String(e??``).replace(/[^a-zA-Z0-9]/g,``).toLowerCase()}function tp(e,t){let n=ep(e),r=ep(t.bone);return n===r||n.endsWith(r)||r.endsWith(n)}var np={id:`default`,label:`Default`,prompt:`standing relaxed with arms hanging naturally at their sides`,bones:{lArm:[1.5632,.1164,-.2889],rArm:[1.5632,-.1164,.2889],lForeArm:[-.0076,3e-4,-.0874],rForeArm:[-.0076,-3e-4,.0874]}},rp=`cozyclay_poses`,ip=new WeakMap;function ap(e,t,n){let r=Math.cos(e/2),i=Math.cos(t/2),a=Math.cos(n/2),o=Math.sin(e/2),s=Math.sin(t/2),c=Math.sin(n/2);return{x:o*i*a+r*s*c,y:r*s*a-o*i*c,z:r*i*c+o*s*a,w:r*i*a-o*s*c}}function op(e,t){return{x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w,w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z}}function sp(e){return{x:-e.x,y:-e.y,z:-e.z,w:e.w}}function cp(e){let t=1-2*(e.y*e.y+e.z*e.z),n=2*(e.x*e.y-e.w*e.z),r=2*(e.x*e.z+e.w*e.y),i=1-2*(e.x*e.x+e.z*e.z),a=2*(e.y*e.z-e.w*e.x),o=2*(e.y*e.z+e.w*e.x),s=1-2*(e.x*e.x+e.y*e.y),c=Math.asin(Math.max(-1,Math.min(1,r)));return Math.abs(r)<.9999999?[Math.atan2(-a,s),c,Math.atan2(-n,t)]:[Math.atan2(o,i),c,0]}function lp(e){if(!e||e.userData?.poseBind)return;let t=new Map;e.traverse(e=>{if(e.isBone){let n=e.quaternion,r=e.position;t.set(e,{x:n.x,y:n.y,z:n.z,w:n.w,position:{x:r.x,y:r.y,z:r.z}})}}),e.userData.poseBind=t}function up(e){let t=e.userData&&e.userData.poseBind;if(t)return t;let n=ip.get(e);return n||(n=new Map,e.traverse(e=>{if(e.isBone){let t=e.quaternion,r=e.position;n.set(e,{x:t.x,y:t.y,z:t.z,w:t.w,position:{x:r.x,y:r.y,z:r.z}})}}),ip.set(e,n)),n}function dp(e,t){for(let n=e.parent;n;n=n.parent)if(t.includes(n))return!0;return!1}function fp(e,t){let n=$f.length,r=0;if(e&&t){let n=up(e),i=new Map;e.traverse(e=>{if(e.isBone){for(let t of $f)if(tp(e.name,t)){let n=i.get(t.id);n||i.set(t.id,n=[]),n.push(e)}}});for(let e of $f){let a=t[e.id],o=i.get(e.id);if(!o||!Array.isArray(a)||a.length<3)continue;let s=ap(a[0],a[1],a[2]),c=[];for(let e of o){if(c.length&&dp(e,c))continue;c.push(e);let t=op(s,n.get(e)??n.get(o[0])??{x:0,y:0,z:0,w:1});e.quaternion.set(t.x,t.y,t.z,t.w)}r++}e.updateMatrixWorld(!0)}return{applied:r,total:n}}function pp(e){let t={};if(e){let n=up(e),r=new Map;e.traverse(e=>{if(e.isBone){for(let t of $f)if(!r.has(t.id)&&tp(e.name,t)){r.set(t.id,e);break}}});for(let e of $f){let i=r.get(e.id);if(i){let r=i.quaternion,a=n.get(i),o=a?op({x:r.x,y:r.y,z:r.z,w:r.w},sp(a)):{x:r.x,y:r.y,z:r.z,w:r.w};t[e.id]=cp(o)}}}return t}function mp(e){let t=$f.find(e=>e.id===`hips`),n=null;return e.traverse(e=>{!n&&e.isBone&&tp(e.name,t)&&(n=e)}),n}function hp(e){if(!e)return 0;let t=mp(e);if(!t)return 0;let n=up(e).get(t);return n?.position?t.position.y-n.position.y:0}function gp(e){if(!e)return;let t=up(e);e.traverse(e=>{if(!e.isBone)return;let n=t.get(e)?.position;n&&e.position.set(n.x,n.y,n.z)}),e.updateMatrixWorld(!0)}function _p(e,t=0){if(!e)return;let n=mp(e);if(!n)return;let r=up(e).get(n);r?.position&&(n.position.y=r.position.y+(Number.isFinite(t)?t:0),n.updateMatrixWorld(!0))}function vp(){try{let e=localStorage.getItem(rp);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&typeof e.id==`string`&&e.bones&&typeof e.bones==`object`):[]}catch{return[]}}function yp(e){try{return localStorage.setItem(rp,JSON.stringify(e)),!0}catch{return!1}}var bp=240,xp=(e,t,n)=>Math.min(n,Math.max(t,e)),Sp=(e,t=0)=>typeof e==`number`&&Number.isFinite(e)?e:t;function Cp(e){let t=e&&typeof e==`object`?e:{};return{x:xp(Sp(t.x),-240,bp),y:xp(Sp(t.y),0,60),z:xp(Sp(t.z),-240,bp)}}function wp(e){if(!e||typeof e!=`object`)return null;let t=Array.isArray(e.points)?e.points:[],r=[];for(let e of t){let t=Cp(e),n=r[r.length-1];if(!(n&&Math.hypot(t.x-n.x,t.z-n.z,t.y-n.y)<1e-4)&&(r.push(t),r.length>=64))break}if(r.length<2)return null;let i=Sp(e.speed,0),a=n(e.timing);return{points:r,timing:u(a)?null:a,speed:i>0?xp(i,.01,50):0,faceTravel:e.faceTravel!==!1,loop:e.loop===!0,extend:e.extend===!0}}function Tp(e,t){let n=wp(e);if(!n)return null;let r=Sp(t?.x),i=Sp(t?.y),a=Sp(t?.z);return!r&&!i&&!a?n:wp({...n,points:n.points.map(e=>({x:e.x+r,y:e.y+i,z:e.z+a}))})}function Ep(e){let t=e?.points??[],n=[0];for(let e=1;e<t.length;e+=1){let r=t[e-1],i=t[e];n.push(n[e-1]+Math.hypot(i.x-r.x,i.y-r.y,i.z-r.z))}return{cumulative:n,length:n[n.length-1]??0}}function Dp(e,t,n){let{points:r}=e,{cumulative:i,length:a}=t;if(n<=0){let e=Op(r[0],r[1]);return{...r[0],heading:e}}if(n>=a){let t=r[r.length-1],i=Op(r[r.length-2],t);if(!e.extend)return{...t,heading:i};let o=n-a,s=r[r.length-2],c=Math.hypot(t.x-s.x,t.y-s.y,t.z-s.z)||1;return{x:t.x+(t.x-s.x)/c*o,y:Math.max(0,t.y+(t.y-s.y)/c*o),z:t.z+(t.z-s.z)/c*o,heading:i}}let o=1;for(;o<i.length-1&&i[o]<n;)o+=1;let s=r[o-1],c=r[o],l=i[o]-i[o-1],u=l>1e-9?(n-i[o-1])/l:0;return{x:s.x+(c.x-s.x)*u,y:s.y+(c.y-s.y)*u,z:s.z+(c.z-s.z)*u,heading:Op(s,c)}}function Op(e,t){if(!e||!t)return null;let n=t.x-e.x,r=t.z-e.z;return Math.abs(n)<1e-9&&Math.abs(r)<1e-9?null:Math.atan2(n,r)*180/Math.PI}function kp(e,t,n={}){let r=wp(e?.path);if(!r)return null;let i=Ep(r);if(i.length<=1e-9)return null;let a=Math.max(1,Math.round(Sp(n.frameCount,1))),s=Math.max(1,Sp(n.fps,24)),c=xp(Sp(t),0,Math.max(0,a-1))/s,l=Math.max(1e-6,(a-1)/s),u=r.speed>0?r.speed:i.length/l,d=i.length/u,f=c/Math.max(1e-6,d),p;p=r.loop&&i.length>1e-9?i.length*o(r.timing,f-Math.floor(f)):f>=1?i.length+(r.extend?u*(c-d):0):i.length*o(r.timing,f);let m=Dp(r,i,p);return{x:m.x,y:m.y,z:m.z,rot:r.faceTravel&&m.heading!==null?m.heading:null}}function Ap(e,t,{maxPoints:n=5,epsilon:r=.55}={}){if(!e||e.length<2)return[];let i=t(e,r);for(let a=0;a<12&&i.length>n;a+=1)r*=1.8,i=t(e,r);if(i.length>n){let e=[i[0]];for(let t=1;t<n-1;t+=1)e.push(i[Math.round(t*(i.length-1)/(n-1))]);e.push(i[i.length-1]),i=e}return i.map(e=>({x:e.x,y:0,z:e.z}))}var jp=`img-`,Mp=`mesh-`,Np=32,Pp=`cozyclay.assets`,Fp=`images`,Ip=Object.freeze([`image/png`,`image/webp`,`image/jpeg`,`image/gif`]),Lp=Object.freeze([`model/gltf-binary`,`model/obj`,`model/fbx`]),Rp=33554432,zp=2048;function Bp(e){return typeof e==`string`&&Ip.includes(e.toLowerCase())}function Vp(e){return typeof e==`string`&&Lp.includes(e.toLowerCase())}function Hp(e,t){if(typeof t!=`string`)return null;let n=t.trim().toLowerCase();return!/^[0-9a-f]+$/.test(n)||n.length<Np?null:`${e}${n.slice(0,Np)}`}function Up(e,t){return typeof t==`string`&&RegExp(`^${e}[0-9a-f]{${Np}}$`).test(t)}function Wp(e){return Hp(jp,e)}function Gp(e){return Hp(Mp,e)}function Kp(e){return Up(jp,e)}function qp(e){return Up(Mp,e)}function Jp(e){return Kp(e)||qp(e)}async function Yp(e,t){if(!t?.digest)throw Error(`SubtleCrypto is unavailable — a secure context is required to import images`);let n=e instanceof ArrayBuffer?e:e?.buffer?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):null;if(!n)return null;let r=await t.digest(`SHA-256`,n);return Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,`0`)).join(``)}async function Xp(e,t=globalThis.crypto?.subtle){let n=await Yp(e,t);if(!n)throw TypeError(`assetIdForBytes needs an ArrayBuffer or a typed array`);return Wp(n)}async function Zp(e,t=globalThis.crypto?.subtle){let n=await Yp(e,t);if(!n)throw TypeError(`meshIdForBytes needs an ArrayBuffer or a typed array`);return Gp(n)}function Qp(e,t,n=zp){let r=Math.max(0,Math.round(Number(e)||0)),i=Math.max(0,Math.round(Number(t)||0));if(!r||!i)return null;let a=Math.max(r,i);if(a<=n)return{width:r,height:i,scaled:!1};let o=n/a;return{width:Math.max(1,Math.round(r*o)),height:Math.max(1,Math.round(i*o)),scaled:!0}}function $p(e){let t=Number(e?.width),n=Number(e?.height);return!Number.isFinite(t)||!Number.isFinite(n)||t<=0||n<=0?null:t/n}function em(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e.bytes instanceof ArrayBuffer?e.bytes:null;if(!t||!t.byteLength)return null;if(qp(e.id))return Vp(e.type)?{id:e.id,type:e.type.toLowerCase(),bytes:t,name:typeof e.name==`string`?e.name:``,...typeof e.role==`string`?{role:e.role}:{}}:null;if(!Kp(e.id)||!Bp(e.type))return null;let n=Math.round(Number(e.width)),r=Math.round(Number(e.height));return!Number.isInteger(n)||!Number.isInteger(r)||n<=0||r<=0?null:{id:e.id,type:e.type.toLowerCase(),width:n,height:r,bytes:t,name:typeof e.name==`string`?e.name:``,...typeof e.role==`string`?{role:e.role}:{}}}function tm(e){return Array.from(e?.files??[]).filter(e=>{if(!e)return!1;if(Bp(e.type))return!0;if(e.type)return!1;let t=String(e.name??``).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];return[`png`,`webp`,`jpg`,`jpeg`,`gif`].includes(t)})}function nm(e){let t=[],n=Array.from(e?.items??[]);for(let e of n){if(e.kind!==`file`||!Bp(e.type))continue;let n=e.getAsFile?.();n&&t.push(n.name&&n.name!==`image.png`?n:new File([n],`pasted-${Date.now()}.${e.type.split(`/`)[1]||`png`}`,{type:e.type}))}return t.length?t:tm(e)}function rm(e){return e===`image/jpeg`?`image/jpeg`:`image/png`}function im(e,t){if(typeof OffscreenCanvas==`function`)return new OffscreenCanvas(e,t);throw Error(`this browser cannot resize images — OffscreenCanvas is unavailable`)}async function am(e,{subtle:t=globalThis.crypto?.subtle,createBitmap:n=globalThis.createImageBitmap,makeCanvas:r=im,maxDimension:i=zp,maxSourceBytes:a=Rp}={}){if(!e||typeof e.arrayBuffer!=`function`)throw TypeError(`importImageFile needs a File or Blob`);let o=typeof e.type==`string`?e.type.toLowerCase():``;if(!Bp(o))throw Error(`that file is not an image CozyClay can import (PNG, WebP, JPEG or GIF)`);if(Number(e.size)>a)throw Error(`that image is larger than ${Math.round(a/1048576)} MB`);if(typeof n!=`function`)throw Error(`this browser cannot decode images — createImageBitmap is unavailable`);let s=await n(e);try{let n=Qp(s.width,s.height,i);if(!n)throw Error(`that image has no usable size`);let a=o,c;if(n.scaled){let e=r(n.width,n.height),t=e.getContext(`2d`);if(!t)throw Error(`this browser cannot resize images — no 2D context`);t.drawImage(s,0,0,n.width,n.height),a=rm(o),c=await(await e.convertToBlob({type:a})).arrayBuffer()}else c=await e.arrayBuffer();let l=em({id:await Xp(c,t),type:a,width:n.width,height:n.height,bytes:c,name:typeof e.name==`string`?e.name:``});if(!l)throw Error(`that image could not be prepared for the set`);return l}finally{s?.close?.()}}function om(e){return new Set(sm(e).keys())}function sm(e){let t=new Map;for(let n of Array.isArray(e)?e:[])for(let e of Array.isArray(n?.objects)?n.objects:[]){let n=new Set;for(let t of[e?.assetId,e?.sourceAssetId,e?.matteAssetId])Jp(t)&&n.add(t);for(let e of n)t.set(e,(t.get(e)??0)+1)}return t}function cm(e){return JSON.stringify((Array.isArray(e)?e:[]).map(e=>[typeof e?.id==`string`?e.id:null,(Array.isArray(e?.objects)?e.objects:[]).map(e=>[typeof e?.id==`string`?e.id:null,...[e?.assetId,e?.sourceAssetId,e?.matteAssetId].map(e=>Jp(e)?e:null)])]))}async function lm({expectedGraphSignature:e,deleteRecord:t,restoreRecord:n,readGraphSignature:r}){return await t(),r()===e||(await n(),!1)}function um(e,t){let n=om(t);return(Array.isArray(e)?e:[]).filter(e=>Jp(e)&&!n.has(e))}var dm=e=>new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)});function fm(e=globalThis.indexedDB){return e?new Promise((t,n)=>{let r=e.open(Pp,1);r.onupgradeneeded=()=>{r.result.objectStoreNames.contains(`images`)||r.result.createObjectStore(Fp,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),r.onblocked=()=>n(Error(`the asset database is blocked by another tab`))}):Promise.reject(Error(`IndexedDB is unavailable`))}async function pm(e,t){let n=em(t);if(!n)throw TypeError(`putAsset needs a normalizable asset record`);let r=e.transaction(Fp,`readwrite`);return r.objectStore(Fp).put(n),await new Promise((e,t)=>{r.oncomplete=e,r.onerror=()=>t(r.error),r.onabort=()=>t(r.error)}),n}async function mm(e,t){return Jp(t)?em(await dm(e.transaction(Fp,`readonly`).objectStore(Fp).get(t))):null}async function hm(e){return(await dm(e.transaction(Fp,`readonly`).objectStore(`images`).getAllKeys())??[]).filter(Jp)}async function gm(e,t){if(!Jp(t))return!1;let n=e.transaction(Fp,`readwrite`);return n.objectStore(Fp).delete(t),await new Promise((e,t)=>{n.oncomplete=e,n.onerror=()=>t(n.error),n.onabort=()=>t(n.error)}),!0}var _m=Uint8Array,vm=Uint16Array,ym=Int32Array,bm=new _m([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),xm=new _m([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Sm=new _m([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cm=function(e,t){for(var n=new vm(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new ym(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},wm=Cm(bm,2),Tm=wm.b,Em=wm.r;Tm[28]=258,Em[258]=28;var Dm=Cm(xm,0),Om=Dm.b;Dm.r;for(var km=new vm(32768),Am=0;Am<32768;++Am){var jm=(Am&43690)>>1|(Am&21845)<<1;jm=(jm&52428)>>2|(jm&13107)<<2,jm=(jm&61680)>>4|(jm&3855)<<4,km[Am]=((jm&65280)>>8|(jm&255)<<8)>>1}for(var Mm=(function(e,t,n){for(var r=e.length,i=0,a=new vm(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new vm(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new vm(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[km[d]>>c]=l}else for(s=new vm(r),i=0;i<r;++i)e[i]&&(s[i]=km[o[e[i]-1]++]>>15-e[i]);return s}),Nm=new _m(288),Am=0;Am<144;++Am)Nm[Am]=8;for(var Am=144;Am<256;++Am)Nm[Am]=9;for(var Am=256;Am<280;++Am)Nm[Am]=7;for(var Am=280;Am<288;++Am)Nm[Am]=8;for(var Pm=new _m(32),Am=0;Am<32;++Am)Pm[Am]=5;var Fm=Mm(Nm,9,1),Im=Mm(Pm,5,1),Lm=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Rm=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},zm=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Bm=function(e){return(e+7)/8|0},Vm=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new _m(e.subarray(t,n))},Hm=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],Um=function(e,t,n){var r=Error(t||Hm[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Um),!n)throw r;return r},Wm=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new _m(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new _m(i*3));var l=function(e){var t=n.length;if(e>t){var r=new _m(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=Rm(e,d,1);var v=Rm(e,d+1,3);if(d+=3,!v){var y=Bm(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&Um(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}if(v==1)p=Fm,m=Im,h=9,g=5;else if(v==2){var S=Rm(e,d,31)+257,C=Rm(e,d+10,15)+4,w=S+Rm(e,d+5,31)+1;d+=14;for(var T=new _m(w),E=new _m(19),D=0;D<C;++D)E[Sm[D]]=Rm(e,d+D*3,7);d+=C*3;for(var O=Lm(E),ee=(1<<O)-1,k=Mm(E,O,1),D=0;D<w;){var te=k[Rm(e,d,ee)];d+=te&15;var y=te>>4;if(y<16)T[D++]=y;else{var ne=0,re=0;for(y==16?(re=3+Rm(e,d,3),d+=2,ne=T[D-1]):y==17?(re=3+Rm(e,d,7),d+=3):y==18&&(re=11+Rm(e,d,127),d+=7);re--;)T[D++]=ne}}var ie=T.subarray(0,S),A=T.subarray(S);h=Lm(ie),g=Lm(A),p=Mm(ie,h,1),m=Mm(A,g,1)}else Um(1);if(d>_){c&&Um(0);break}}s&&l(f+131072);for(var j=(1<<h)-1,M=(1<<g)-1,ae=d;;ae=d){var ne=p[zm(e,d)&j],oe=ne>>4;if(d+=ne&15,d>_){c&&Um(0);break}if(ne||Um(2),oe<256)n[f++]=oe;else if(oe==256){ae=d,p=null;break}else{var se=oe-254;if(oe>264){var D=oe-257,ce=bm[D];se=Rm(e,d,(1<<ce)-1)+Tm[D],d+=ce}var le=m[zm(e,d)&M],ue=le>>4;le||Um(3),d+=le&15;var A=Om[ue];if(ue>3){var ce=xm[ue];A+=zm(e,d)&(1<<ce)-1,d+=ce}if(d>_){c&&Um(0);break}s&&l(f+131072);var de=f+se;if(f<A){var fe=a-A,pe=Math.min(A,de);for(fe+f<0&&Um(3);f<pe;++f)n[f]=r[fe+f]}for(;f<de;++f)n[f]=n[f-A]}}t.l=p,t.p=ae,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?Vm(n,0,f):n.subarray(0,f)},Gm=new _m(0),Km=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&Um(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&Um(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function qm(e,t){return Wm(e.subarray(Km(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}var Jm=typeof TextDecoder<`u`&&new TextDecoder;try{Jm.decode(Gm,{stream:!0})}catch{}function Ym(e,t,n){let r=n.length-e-1;if(t>=n[r])return r-1;if(t<=n[e])return e;let i=e,a=r,o=Math.floor((i+a)/2);for(;t<n[o]||t>=n[o+1];)t<n[o]?a=o:i=o,o=Math.floor((i+a)/2);return o}function Xm(e,t,n,r){let i=[],a=[],o=[];i[0]=1;for(let s=1;s<=n;++s){a[s]=t-r[e+1-s],o[s]=r[e+s]-t;let n=0;for(let e=0;e<s;++e){let t=o[e+1],r=a[s-e],c=i[e]/(t+r);i[e]=n+t*c,n=r*c}i[s]=n}return i}function Zm(e,t,n,r){let i=Ym(e,r,t),a=Xm(i,r,e,t),o=new sr(0,0,0,0);for(let t=0;t<=e;++t){let r=n[i-e+t],s=a[t],c=r.w*s;o.x+=r.x*c,o.y+=r.y*c,o.z+=r.z*c,o.w+=r.w*s}return o}function Qm(e,t,n,r,i){let a=[];for(let e=0;e<=n;++e)a[e]=0;let o=[];for(let e=0;e<=r;++e)o[e]=a.slice(0);let s=[];for(let e=0;e<=n;++e)s[e]=a.slice(0);s[0][0]=1;let c=a.slice(0),l=a.slice(0);for(let r=1;r<=n;++r){c[r]=t-i[e+1-r],l[r]=i[e+r]-t;let n=0;for(let e=0;e<r;++e){let t=l[e+1],i=c[r-e];s[r][e]=t+i;let a=s[e][r-1]/s[r][e];s[e][r]=n+t*a,n=i*a}s[r][r]=n}for(let e=0;e<=n;++e)o[0][e]=s[e][n];for(let e=0;e<=n;++e){let t=0,i=1,c=[];for(let e=0;e<=n;++e)c[e]=a.slice(0);c[0][0]=1;for(let a=1;a<=r;++a){let r=0,l=e-a,u=n-a;e>=a&&(c[i][0]=c[t][0]/s[u+1][l],r=c[i][0]*s[l][u]);let d=l>=-1?1:-l,f=e-1<=u?a-1:n-e;for(let e=d;e<=f;++e)c[i][e]=(c[t][e]-c[t][e-1])/s[u+1][l+e],r+=c[i][e]*s[l+e][u];e<=u&&(c[i][a]=-c[t][a-1]/s[u+1][e],r+=c[i][a]*s[e][u]),o[a][e]=r;let p=t;t=i,i=p}}let u=n;for(let e=1;e<=r;++e){for(let t=0;t<=n;++t)o[e][t]*=u;u*=n-e}return o}function $m(e,t,n,r,i){let a=i<e?i:e,o=[],s=Ym(e,r,t),c=Qm(s,r,e,a,t),l=[];for(let e=0;e<n.length;++e){let t=n[e].clone(),r=t.w;t.x*=r,t.y*=r,t.z*=r,l[e]=t}for(let t=0;t<=a;++t){let n=l[s-e].clone().multiplyScalar(c[t][0]);for(let r=1;r<=e;++r)n.add(l[s-e+r].clone().multiplyScalar(c[t][r]));o[t]=n}for(let e=a+1;e<=i+1;++e)o[e]=new sr(0,0,0);return o}function eh(e,t){let n=1;for(let t=2;t<=e;++t)n*=t;let r=1;for(let e=2;e<=t;++e)r*=e;for(let n=2;n<=e-t;++n)r*=n;return n/r}function th(e){let t=e.length,n=[],r=[];for(let i=0;i<t;++i){let t=e[i];n[i]=new B(t.x,t.y,t.z),r[i]=t.w}let i=[];for(let e=0;e<t;++e){let t=n[e].clone();for(let n=1;n<=e;++n)t.sub(i[e-n].clone().multiplyScalar(eh(e,n)*r[n]));i[e]=t.divideScalar(r[0])}return i}function nh(e,t,n,r,i){return th($m(e,t,n,r,i))}var rh=class extends Rs{constructor(e,t,n,r,i){super();let a=t?t.length-1:0,o=n?n.length:0;this.degree=e,this.knots=t,this.controlPoints=[],this.startKnot=r||0,this.endKnot=i||a;for(let e=0;e<o;++e){let t=n[e];this.controlPoints[e]=new sr(t.x,t.y,t.z,t.w)}}getPoint(e,t=new B){let n=t,r=this.knots[this.startKnot]+e*(this.knots[this.endKnot]-this.knots[this.startKnot]),i=Zm(this.degree,this.knots,this.controlPoints,r);return i.w!==1&&i.divideScalar(i.w),n.set(i.x,i.y,i.z)}getTangent(e,t=new B){let n=t,r=this.knots[0]+e*(this.knots[this.knots.length-1]-this.knots[0]),i=nh(this.degree,this.knots,this.controlPoints,r,1);return n.copy(i[1]).normalize(),n}toJSON(){let e=super.toJSON();return e.degree=this.degree,e.knots=[...this.knots],e.controlPoints=this.controlPoints.map(e=>e.toArray()),e.startKnot=this.startKnot,e.endKnot=this.endKnot,e}fromJSON(e){return super.fromJSON(e),this.degree=e.degree,this.knots=[...e.knots],this.controlPoints=e.controlPoints.map(e=>new sr(e[0],e[1],e[2],e[3])),this.startKnot=e.startKnot,this.endKnot=e.endKnot,this}},X,ih,ah,oh=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=i.path===``?Ku.extractUrlBase(e):i.path,o=new du(this.manager);o.setPath(i.path),o.setResponseType(`arraybuffer`),o.setRequestHeader(i.requestHeader),o.setWithCredentials(i.withCredentials),o.load(e,function(n){try{t(i.parse(n,a))}catch(t){r?r(t):console.error(t),i.manager.itemError(e)}},n,r)}parse(e,t){if(mh(e))X=new dh().parse(e);else{let t=Th(e);if(!hh(t))throw Error(`THREE.FBXLoader: Unknown format.`);if(gh(t)<7e3)throw Error(`THREE.FBXLoader: FBX version not supported, FileVersion: `+gh(t));X=new uh().parse(t)}return new sh(new vu(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin),this.manager).parse(X)}},sh=class{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){ih=this.parseConnections();let e=this.parseImages(),t=this.parseTextures(e),n=this.parseMaterials(t),r=this.parseDeformers(),i=new ch().parse(r);return this.parseScene(r,i,n),ah}parseConnections(){let e=new Map;return`Connections`in X&&X.Connections.connections.forEach(function(t){let n=t[0],r=t[1],i=t[2];e.has(n)||e.set(n,{parents:[],children:[]});let a={ID:r,relationship:i};e.get(n).parents.push(a),e.has(r)||e.set(r,{parents:[],children:[]});let o={ID:n,relationship:i};e.get(r).children.push(o)}),e}parseImages(){let e={},t={};if(`Video`in X.Objects){let n=X.Objects.Video;for(let r in n){let i=n[r],a=parseInt(r);if(e[a]=i.RelativeFilename||i.Filename,`Content`in i){let e=i.Content instanceof ArrayBuffer&&i.Content.byteLength>0,a=typeof i.Content==`string`&&i.Content!==``;if(e||a){let e=this.parseImage(n[r]);t[i.RelativeFilename||i.Filename]=e}}}}for(let n in e){let r=e[n];e[n]=t[r]===void 0?e[n].split(`\\`).pop():t[r]}return e}parseImage(e){let t=e.Content,n=e.RelativeFilename||e.Filename,r=n.slice(n.lastIndexOf(`.`)+1).toLowerCase(),i;switch(r){case`bmp`:i=`image/bmp`;break;case`jpg`:case`jpeg`:i=`image/jpeg`;break;case`png`:i=`image/png`;break;case`tif`:i=`image/tiff`;break;case`tga`:this.manager.getHandler(`.tga`)===null&&console.warn(`FBXLoader: TGA loader not found, skipping `,n),i=`image/tga`;break;case`webp`:i=`image/webp`;break;default:console.warn(`FBXLoader: Image type "`+r+`" is not supported.`);return}if(typeof t==`string`)return`data:`+i+`;base64,`+t;{let e=new Uint8Array(t);return window.URL.createObjectURL(new Blob([e],{type:i}))}}parseTextures(e){let t=new Map;if(`Texture`in X.Objects){let n=X.Objects.Texture;for(let r in n){let i=this.parseTexture(n[r],e);t.set(parseInt(r),i)}}return t}parseTexture(e,t){let n=this.loadTexture(e,t);n.ID=e.id,n.name=e.attrName;let r=e.WrapModeU,i=e.WrapModeV,a=r===void 0?0:r.value,o=i===void 0?0:i.value;if(n.wrapS=a===0?D:O,n.wrapT=o===0?D:O,`Scaling`in e){let t=e.Scaling.value;n.repeat.x=t[0],n.repeat.y=t[1]}if(`Translation`in e){let t=e.Translation.value;n.offset.x=t[0],n.offset.y=t[1]}return n}loadTexture(e,t){let n=e.FileName.split(`.`).pop().toLowerCase(),r=this.manager.getHandler(`.${n}`);r===null&&(r=this.textureLoader);let i=r.path;i||r.setPath(this.textureLoader.path);let a=ih.get(e.id).children,o;if(a!==void 0&&a.length>0&&t[a[0].ID]!==void 0&&(o=t[a[0].ID],(o.indexOf(`blob:`)===0||o.indexOf(`data:`)===0)&&r.setPath(void 0)),o===void 0)return console.warn(`FBXLoader: Undefined filename, creating placeholder texture.`),new or;let s=r.load(o);return r.setPath(i),s}parseMaterials(e){let t=new Map;if(`Material`in X.Objects){let n=X.Objects.Material;for(let r in n){let i=this.parseMaterial(n[r],e);i!==null&&t.set(parseInt(r),i)}}return t}parseMaterial(e,t){let n=e.id,r=e.attrName,i=e.ShadingModel;if(typeof i==`object`&&(i=i.value),!ih.has(n))return null;let a=this.parseParameters(e,t,n),o;switch(i.toLowerCase()){case`phong`:o=new kl;break;case`lambert`:o=new Ml;break;default:console.warn(`THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.`,i),o=new kl}return o.setValues(a),o.name=r,o}parseParameters(e,t,n){let r={};e.BumpFactor&&(r.bumpScale=e.BumpFactor.value),e.Diffuse?r.color=Xn.colorSpaceToWorking(new H().fromArray(e.Diffuse.value),Ot):e.DiffuseColor&&(e.DiffuseColor.type===`Color`||e.DiffuseColor.type===`ColorRGB`)&&(r.color=Xn.colorSpaceToWorking(new H().fromArray(e.DiffuseColor.value),Ot)),e.DisplacementFactor&&(r.displacementScale=e.DisplacementFactor.value),e.Emissive?r.emissive=Xn.colorSpaceToWorking(new H().fromArray(e.Emissive.value),Ot):e.EmissiveColor&&(e.EmissiveColor.type===`Color`||e.EmissiveColor.type===`ColorRGB`)&&(r.emissive=Xn.colorSpaceToWorking(new H().fromArray(e.EmissiveColor.value),Ot)),e.EmissiveFactor&&(r.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),r.opacity=1-(e.TransparencyFactor?parseFloat(e.TransparencyFactor.value):0),(r.opacity===1||r.opacity===0)&&(r.opacity=e.Opacity?parseFloat(e.Opacity.value):null,r.opacity===null&&(r.opacity=1)),r.opacity<1&&(r.transparent=!0),e.ReflectionFactor&&(r.reflectivity=e.ReflectionFactor.value),e.Shininess&&(r.shininess=e.Shininess.value),e.Specular?r.specular=Xn.colorSpaceToWorking(new H().fromArray(e.Specular.value),Ot):e.SpecularColor&&e.SpecularColor.type===`Color`&&(r.specular=Xn.colorSpaceToWorking(new H().fromArray(e.SpecularColor.value),Ot));let i=this;return ih.get(n).children.forEach(function(e){let n=e.relationship;switch(n){case`Bump`:r.bumpMap=i.getTexture(t,e.ID);break;case`Maya|TEX_ao_map`:r.aoMap=i.getTexture(t,e.ID);break;case`DiffuseColor`:case`Maya|TEX_color_map`:r.map=i.getTexture(t,e.ID),r.map!==void 0&&(r.map.colorSpace=Ot);break;case`DisplacementColor`:r.displacementMap=i.getTexture(t,e.ID);break;case`EmissiveColor`:r.emissiveMap=i.getTexture(t,e.ID),r.emissiveMap!==void 0&&(r.emissiveMap.colorSpace=Ot);break;case`NormalMap`:case`Maya|TEX_normal_map`:r.normalMap=i.getTexture(t,e.ID);break;case`ReflectionColor`:r.envMap=i.getTexture(t,e.ID),r.envMap!==void 0&&(r.envMap.mapping=303,r.envMap.colorSpace=Ot);break;case`SpecularColor`:r.specularMap=i.getTexture(t,e.ID),r.specularMap!==void 0&&(r.specularMap.colorSpace=Ot);break;case`TransparentColor`:case`TransparencyFactor`:r.alphaMap=i.getTexture(t,e.ID),r.transparent=!0;break;default:console.warn(`THREE.FBXLoader: %s map is not supported in three.js, skipping texture.`,n)}}),r}getTexture(e,t){return`LayeredTexture`in X.Objects&&t in X.Objects.LayeredTexture&&(console.warn(`THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.`),t=ih.get(t).children[0].ID),e.get(t)}parseDeformers(){let e={},t={};if(`Deformer`in X.Objects){let n=X.Objects.Deformer;for(let r in n){let i=n[r],a=ih.get(parseInt(r));if(i.attrType===`Skin`){let t=this.parseSkeleton(a,n);t.ID=r,a.parents.length>1&&console.warn(`THREE.FBXLoader: skeleton attached to more than one geometry is not supported.`),t.geometryID=a.parents[0].ID,e[r]=t}else if(i.attrType===`BlendShape`){let e={id:r};e.rawTargets=this.parseMorphTargets(a,n),e.id=r,a.parents.length>1&&console.warn(`THREE.FBXLoader: morph target attached to more than one geometry is not supported.`),t[r]=e}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){let n=[];return e.children.forEach(function(e){let r=t[e.ID];if(r.attrType!==`Cluster`)return;let i={ID:e.ID,indices:[],weights:[],transformLink:new V().fromArray(r.TransformLink.a)};`Indexes`in r&&(i.indices=r.Indexes.a,i.weights=r.Weights.a),n.push(i)}),{rawBones:n,bones:[]}}parseMorphTargets(e,t){let n=[];for(let r=0;r<e.children.length;r++){let i=e.children[r],a=t[i.ID],o={name:a.attrName,initialWeight:a.DeformPercent,id:a.id,fullWeights:a.FullWeights.a};if(a.attrType!==`BlendShapeChannel`)return;o.geoID=ih.get(parseInt(i.ID)).children.filter(function(e){return e.relationship===void 0})[0].ID,n.push(o)}return n}parseScene(e,t,n){ah=new Vr;let r=this.parseModels(e.skeletons,t,n),i=X.Objects.Model,a=this;r.forEach(function(e){let t=i[e.ID];a.setLookAtProperties(e,t),ih.get(e.ID).parents.forEach(function(t){let n=r.get(t.ID);n!==void 0&&n.add(e)}),e.parent===null&&ah.add(e)}),this.addGlobalSceneSettings(),ah.traverse(function(e){if(e.userData.transformData){e.parent&&(e.userData.transformData.parentMatrix=e.parent.matrix,e.userData.transformData.parentMatrixWorld=e.parent.matrixWorld);let t=Sh(e.userData.transformData);e.applyMatrix4(t),e.updateWorldMatrix()}});let o=this.parsePoseNodes(),s=new Set;for(let t in e.skeletons)e.skeletons[t].rawBones.forEach(function(n,r){let i=e.skeletons[t].bones[r];i&&s.add(i.ID)});let c=new V;ah.traverse(function(e){if(e.isBone&&e.ID!==void 0&&!s.has(e.ID)){let t=o[e.ID];t!==void 0&&(e.parent?(c.copy(e.parent.matrixWorld).invert(),c.multiply(t)):c.copy(t),c.decompose(e.position,e.quaternion,e.scale),e.updateMatrix(),e.matrixWorld.copy(t))}}),this.bindSkeleton(e.skeletons,t,r);let l=new lh().parse();ah.children.length===1&&ah.children[0].isGroup&&(ah.children[0].animations=l,ah=ah.children[0]),ah.animations=l,`GlobalSettings`in X&&`UpAxis`in X.GlobalSettings&&X.GlobalSettings.UpAxis.value===2&&(console.warn(`THREE.FBXLoader: You are loading an asset with a Z-UP coordinate system. The loader just rotates the asset to transform it into Y-UP. The vertex data are not converted.`),ah.rotation.set(-Math.PI/2,0,0))}parseModels(e,t,n){let r=new Map,i=X.Objects.Model;for(let a in i){let o=parseInt(a),s=i[a],c=ih.get(o),l=this.buildSkeleton(c,e,o,s.attrName);if(!l){switch(s.attrType){case`Camera`:l=this.createCamera(c);break;case`Light`:l=this.createLight(c);break;case`Mesh`:l=this.createMesh(c,t,n);break;case`NurbsCurve`:l=this.createCurve(c,t);break;case`LimbNode`:case`Root`:l=new io;break;default:l=new Vr}l.name=s.attrName?Y.sanitizeNodeName(s.attrName):``,l.userData.originalName=s.attrName,l.ID=o}this.getTransformData(l,s),r.set(o,l)}return r}buildSkeleton(e,t,n,r){let i=null;return e.parents.forEach(function(e){for(let a in t){let o=t[a];o.rawBones.forEach(function(t,a){if(t.ID===e.ID){let e=i;i=new io,i.matrixWorld.copy(t.transformLink),i.name=r?Y.sanitizeNodeName(r):``,i.userData.originalName=r,i.ID=n,o.bones[a]=i,e!==null&&i.add(e)}})}}),i}createCamera(e){let t,n;if(e.children.forEach(function(e){let t=X.Objects.NodeAttribute[e.ID];t!==void 0&&(n=t)}),n===void 0)t=new Br;else{let e=0;n.CameraProjectionType!==void 0&&n.CameraProjectionType.value===1&&(e=1);let r=1;n.NearPlane!==void 0&&(r=n.NearPlane.value/1e3);let i=1e3;n.FarPlane!==void 0&&(i=n.FarPlane.value/1e3);let a=window.innerWidth,o=window.innerHeight;n.AspectWidth!==void 0&&n.AspectHeight!==void 0&&(a=n.AspectWidth.value,o=n.AspectHeight.value);let s=a/o,c=45;n.FieldOfView!==void 0&&(c=n.FieldOfView.value);let l=n.FocalLength?n.FocalLength.value:null;switch(e){case 0:t=new Mu(c,s,r,i),l!==null&&t.setFocalLength(l);break;case 1:console.warn(`THREE.FBXLoader: Orthographic cameras not supported yet.`),t=new Br;break;default:console.warn(`THREE.FBXLoader: Unknown camera type `+e+`.`),t=new Br}}return t}createLight(e){let t,n;if(e.children.forEach(function(e){let t=X.Objects.NodeAttribute[e.ID];t!==void 0&&(n=t)}),n===void 0)t=new Br;else{let e;e=n.LightType===void 0?0:n.LightType.value;let r=16777215;n.Color!==void 0&&(r=Xn.colorSpaceToWorking(new H().fromArray(n.Color.value),Ot));let i=n.Intensity===void 0?1:n.Intensity.value/100;n.CastLightOnObject!==void 0&&n.CastLightOnObject.value===0&&(i=0);let a=0;switch(n.FarAttenuationEnd!==void 0&&(a=n.EnableFarAttenuation!==void 0&&n.EnableFarAttenuation.value===0?0:n.FarAttenuationEnd.value),e){case 0:t=new Iu(r,i,a,1);break;case 1:t=new zu(r,i);break;case 2:let e=Math.PI/3,o=0;n.OuterAngle===void 0?n.InnerAngle!==void 0&&(e=Hn.degToRad(n.InnerAngle.value)):(e=Hn.degToRad(n.OuterAngle.value),n.InnerAngle!==void 0&&(o=1-n.InnerAngle.value/n.OuterAngle.value,o=Math.max(0,o))),t=new Pu(r,i,a,e,o,1);break;default:console.warn(`THREE.FBXLoader: Unknown light type `+n.LightType.value+`, defaulting to a PointLight.`),t=new Iu(r,i)}n.CastShadows!==void 0&&n.CastShadows.value===1&&(t.castShadow=!0)}return t}createMesh(e,t,n){let r,i=null,a=null,o=[];if(e.children.forEach(function(e){t.has(e.ID)&&(i=t.get(e.ID)),n.has(e.ID)&&o.push(n.get(e.ID))}),o.length>1?a=o:o.length>0?a=o[0]:(a=new kl({name:cu.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(a)),`color`in i.attributes&&o.forEach(function(e){e.vertexColors=!0}),i.groups.length>0){let e=!1;for(let t=0,n=i.groups.length;t<n;t++){let n=i.groups[t];(n.materialIndex<0||n.materialIndex>=o.length)&&(n.materialIndex=o.length,e=!0)}if(e){let e=new kl;o.push(e)}}return i.FBX_Deformer?(r=new ro(i,a),r.normalizeSkinWeights()):r=new Ga(i,a),r}createCurve(e,t){return new ts(e.children.reduce(function(e,n){return t.has(n.ID)&&(e=t.get(n.ID)),e},null),new qo({name:cu.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1}))}getTransformData(e,t){let n={};`InheritType`in t&&(n.inheritType=parseInt(t.InheritType.value)),n.eulerOrder=`RotationOrder`in t?Ch(t.RotationOrder.value):Ch(0),`Lcl_Translation`in t&&(n.translation=t.Lcl_Translation.value),`PreRotation`in t&&(n.preRotation=t.PreRotation.value),`Lcl_Rotation`in t&&(n.rotation=t.Lcl_Rotation.value),`PostRotation`in t&&(n.postRotation=t.PostRotation.value),`Lcl_Scaling`in t&&(n.scale=t.Lcl_Scaling.value),`ScalingOffset`in t&&(n.scalingOffset=t.ScalingOffset.value),`ScalingPivot`in t&&(n.scalingPivot=t.ScalingPivot.value),`RotationOffset`in t&&(n.rotationOffset=t.RotationOffset.value),`RotationPivot`in t&&(n.rotationPivot=t.RotationPivot.value),e.userData.transformData=n}setLookAtProperties(e,t){`LookAtProperty`in t&&ih.get(e.ID).children.forEach(function(t){if(t.relationship===`LookAtProperty`){let n=X.Objects.Model[t.ID];if(`Lcl_Translation`in n){let t=n.Lcl_Translation.value;e.target===void 0?e.lookAt(new B().fromArray(t)):(e.target.position.fromArray(t),ah.add(e.target))}}})}bindSkeleton(e,t,n){for(let r in e){let i=e[r],a=[];for(let e=0,t=i.bones.length;e<t;e++){let t=new V;i.bones[e]&&i.rawBones[e]&&t.copy(i.rawBones[e].transformLink).invert(),a.push(t)}ih.get(parseInt(i.ID)).parents.forEach(function(e){if(t.has(e.ID)){let t=e.ID;ih.get(t).parents.forEach(function(e){if(n.has(e.ID)){let t=n.get(e.ID);t.updateMatrixWorld(!0),t.bind(new G(i.bones,a),t.matrixWorld)}})}})}}parsePoseNodes(){let e={};if(`Pose`in X.Objects){let t=X.Objects.Pose;for(let n in t)if(t[n].attrType===`BindPose`&&t[n].NbPoseNodes>0){let r=t[n].PoseNode;Array.isArray(r)?r.forEach(function(t){e[t.Node]=new V().fromArray(t.Matrix.a)}):e[r.Node]=new V().fromArray(r.Matrix.a)}}return e}addGlobalSceneSettings(){if(`GlobalSettings`in X){if(`AmbientColor`in X.GlobalSettings){let e=X.GlobalSettings.AmbientColor.value,t=e[0],n=e[1],r=e[2];if(t!==0||n!==0||r!==0){let e=new H().setRGB(t,n,r,Ot);ah.add(new Bu(e,1))}}`UnitScaleFactor`in X.GlobalSettings&&(ah.userData.unitScaleFactor=X.GlobalSettings.UnitScaleFactor.value)}}},ch=class{constructor(){this.negativeMaterialIndices=!1}parse(e){let t=new Map;if(`Geometry`in X.Objects){let n=X.Objects.Geometry;for(let r in n){let i=ih.get(parseInt(r)),a=this.parseGeometry(i,n[r],e);t.set(parseInt(r),a)}}return this.negativeMaterialIndices===!0&&console.warn(`THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected.`),t}parseGeometry(e,t,n){switch(t.attrType){case`Mesh`:return this.parseMeshGeometry(e,t,n);case`NurbsCurve`:return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,n){let r=n.skeletons,i=[],a=e.parents.map(function(e){return X.Objects.Model[e.ID]});if(a.length===0)return;let o=e.children.reduce(function(e,t){return r[t.ID]!==void 0&&(e=r[t.ID]),e},null);e.children.forEach(function(e){n.morphTargets[e.ID]!==void 0&&i.push(n.morphTargets[e.ID])});let s=a[0],c={};`RotationOrder`in s&&(c.eulerOrder=Ch(s.RotationOrder.value)),`InheritType`in s&&(c.inheritType=parseInt(s.InheritType.value)),`GeometricTranslation`in s&&(c.translation=s.GeometricTranslation.value),`GeometricRotation`in s&&(c.rotation=s.GeometricRotation.value),`GeometricScaling`in s&&(c.scale=s.GeometricScaling.value);let l=Sh(c);return this.genGeometry(t,o,i,l)}genGeometry(e,t,n,r){let i=new W;e.attrName&&(i.name=e.attrName);let a=this.parseGeoNode(e,t),o=this.genBuffers(a),s=new U(o.vertex,3);if(s.applyMatrix4(r),i.setAttribute(`position`,s),o.colors.length>0&&i.setAttribute(`color`,new U(o.colors,3)),t&&(i.setAttribute(`skinIndex`,new Bi(o.weightsIndices,4)),i.setAttribute(`skinWeight`,new U(o.vertexWeights,4)),i.FBX_Deformer=t),o.normal.length>0){let e=new Gn().getNormalMatrix(r),t=new U(o.normal,3);t.applyNormalMatrix(e),i.setAttribute(`normal`,t)}if(o.uvs.forEach(function(e,t){let n=t===0?`uv`:`uv${t}`;i.setAttribute(n,new U(o.uvs[t],2))}),a.material&&a.material.mappingType!==`AllSame`){let e=o.materialIndex[0],t=0;if(o.materialIndex.forEach(function(n,r){n!==e&&(i.addGroup(t,r-t,e),e=n,t=r)}),i.groups.length>0){let t=i.groups[i.groups.length-1],n=t.start+t.count;n!==o.materialIndex.length&&i.addGroup(n,o.materialIndex.length-n,e)}i.groups.length===0&&i.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(i,e,n,r),i}parseGeoNode(e,t){let n={};if(n.vertexPositions=e.Vertices===void 0?[]:e.Vertices.a,n.vertexIndices=e.PolygonVertexIndex===void 0?[]:e.PolygonVertexIndex.a,e.LayerElementColor&&e.LayerElementColor[0].Colors&&(n.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(n.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(n.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){n.uv=[];let t=0;for(;e.LayerElementUV[t];)e.LayerElementUV[t].UV&&n.uv.push(this.parseUVs(e.LayerElementUV[t])),t++}return n.weightTable={},t!==null&&(n.skeleton=t,t.rawBones.forEach(function(e,t){e.indices.forEach(function(r,i){n.weightTable[r]===void 0&&(n.weightTable[r]=[]),n.weightTable[r].push({id:t,weight:e.weights[i]})})})),n}genBuffers(e){let t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]},n=0,r=0,i=!1,a=[],o=[],s=[],c=[],l=[],u=[],d=this;return e.vertexIndices.forEach(function(f,p){let m,h=!1;f<0&&(f^=-1,h=!0);let g=[],_=[];if(a.push(f*3,f*3+1,f*3+2),e.color){let t=yh(p,n,f,e.color);s.push(t[0],t[1],t[2])}if(e.skeleton){if(e.weightTable[f]!==void 0&&e.weightTable[f].forEach(function(e){_.push(e.weight),g.push(e.id)}),_.length>4){i||=(console.warn(`THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.`),!0);let e=[0,0,0,0],t=[0,0,0,0];_.forEach(function(n,r){let i=n,a=g[r];t.forEach(function(t,n,r){if(i>t){r[n]=i,i=t;let o=e[n];e[n]=a,a=o}})}),g=e,_=t}for(;_.length<4;)_.push(0),g.push(0);for(let e=0;e<4;++e)l.push(_[e]),u.push(g[e])}if(e.normal){let t=yh(p,n,f,e.normal);o.push(t[0],t[1],t[2])}e.material&&e.material.mappingType!==`AllSame`&&(m=yh(p,n,f,e.material)[0],m<0&&(d.negativeMaterialIndices=!0,m=0)),e.uv&&e.uv.forEach(function(e,t){let r=yh(p,n,f,e);c[t]===void 0&&(c[t]=[]),c[t].push(r[0]),c[t].push(r[1])}),r++,h&&(d.genFace(t,e,a,m,o,s,c,l,u,r),n++,r=0,a=[],o=[],s=[],c=[],l=[],u=[])}),t}getNormalNewell(e){let t=new B(0,0,0);for(let n=0;n<e.length;n++){let r=e[n],i=e[(n+1)%e.length];t.x+=(r.y-i.y)*(r.z+i.z),t.y+=(r.z-i.z)*(r.x+i.x),t.z+=(r.x-i.x)*(r.y+i.y)}return t.normalize(),t}getNormalTangentAndBitangent(e){let t=this.getNormalNewell(e),n=(Math.abs(t.z)>.5?new B(0,1,0):new B(0,0,1)).cross(t).normalize();return{normal:t,tangent:n,bitangent:t.clone().cross(n).normalize()}}flattenVertex(e,t,n){return new R(e.dot(t),e.dot(n))}genFace(e,t,n,r,i,a,o,s,c,l){let u;if(l>3){let e=[],r=t.baseVertexPositions||t.vertexPositions;for(let t=0;t<n.length;t+=3)e.push(new B(r[n[t]],r[n[t+1]],r[n[t+2]]));let{tangent:i,bitangent:a}=this.getNormalTangentAndBitangent(e),o=[];for(let t of e)o.push(this.flattenVertex(t,i,a));u=Yc.triangulateShape(o,[])}else u=[[0,1,2]];for(let[l,d,f]of u)e.vertex.push(t.vertexPositions[n[l*3]]),e.vertex.push(t.vertexPositions[n[l*3+1]]),e.vertex.push(t.vertexPositions[n[l*3+2]]),e.vertex.push(t.vertexPositions[n[d*3]]),e.vertex.push(t.vertexPositions[n[d*3+1]]),e.vertex.push(t.vertexPositions[n[d*3+2]]),e.vertex.push(t.vertexPositions[n[f*3]]),e.vertex.push(t.vertexPositions[n[f*3+1]]),e.vertex.push(t.vertexPositions[n[f*3+2]]),t.skeleton&&(e.vertexWeights.push(s[l*4]),e.vertexWeights.push(s[l*4+1]),e.vertexWeights.push(s[l*4+2]),e.vertexWeights.push(s[l*4+3]),e.vertexWeights.push(s[d*4]),e.vertexWeights.push(s[d*4+1]),e.vertexWeights.push(s[d*4+2]),e.vertexWeights.push(s[d*4+3]),e.vertexWeights.push(s[f*4]),e.vertexWeights.push(s[f*4+1]),e.vertexWeights.push(s[f*4+2]),e.vertexWeights.push(s[f*4+3]),e.weightsIndices.push(c[l*4]),e.weightsIndices.push(c[l*4+1]),e.weightsIndices.push(c[l*4+2]),e.weightsIndices.push(c[l*4+3]),e.weightsIndices.push(c[d*4]),e.weightsIndices.push(c[d*4+1]),e.weightsIndices.push(c[d*4+2]),e.weightsIndices.push(c[d*4+3]),e.weightsIndices.push(c[f*4]),e.weightsIndices.push(c[f*4+1]),e.weightsIndices.push(c[f*4+2]),e.weightsIndices.push(c[f*4+3])),t.color&&(e.colors.push(a[l*3]),e.colors.push(a[l*3+1]),e.colors.push(a[l*3+2]),e.colors.push(a[d*3]),e.colors.push(a[d*3+1]),e.colors.push(a[d*3+2]),e.colors.push(a[f*3]),e.colors.push(a[f*3+1]),e.colors.push(a[f*3+2])),t.material&&t.material.mappingType!==`AllSame`&&(e.materialIndex.push(r),e.materialIndex.push(r),e.materialIndex.push(r)),t.normal&&(e.normal.push(i[l*3]),e.normal.push(i[l*3+1]),e.normal.push(i[l*3+2]),e.normal.push(i[d*3]),e.normal.push(i[d*3+1]),e.normal.push(i[d*3+2]),e.normal.push(i[f*3]),e.normal.push(i[f*3+1]),e.normal.push(i[f*3+2])),t.uv&&t.uv.forEach(function(t,n){e.uvs[n]===void 0&&(e.uvs[n]=[]),e.uvs[n].push(o[n][l*2]),e.uvs[n].push(o[n][l*2+1]),e.uvs[n].push(o[n][d*2]),e.uvs[n].push(o[n][d*2+1]),e.uvs[n].push(o[n][f*2]),e.uvs[n].push(o[n][f*2+1])})}addMorphTargets(e,t,n,r){if(n.length===0)return;e.morphTargetsRelative=!0,e.morphAttributes.position=[];let i=r.clone().setPosition(0,0,0),a=this;n.forEach(function(n){n.rawTargets.forEach(function(n){let r=X.Objects.Geometry[n.geoID];r!==void 0&&a.genMorphGeometry(e,t,r,i,n.name)})})}genMorphGeometry(e,t,n,r,i){let a=t.Vertices===void 0?[]:t.Vertices.a,o=t.PolygonVertexIndex===void 0?[]:t.PolygonVertexIndex.a,s=n.Vertices===void 0?[]:n.Vertices.a,c=n.Indexes===void 0?[]:n.Indexes.a,l=e.attributes.position.count*3,u=new Float32Array(l);for(let e=0;e<c.length;e++){let t=c[e]*3;u[t]=s[e*3],u[t+1]=s[e*3+1],u[t+2]=s[e*3+2]}let d={vertexIndices:o,vertexPositions:u,baseVertexPositions:a},f=new U(this.genBuffers(d).vertex,3);f.name=i||n.attrName,f.applyMatrix4(r),e.morphAttributes.position.push(f)}parseNormals(e){let t=e.MappingInformationType,n=e.ReferenceInformationType,r=e.Normals.a,i=[];return n===`IndexToDirect`&&(`NormalIndex`in e?i=e.NormalIndex.a:`NormalsIndex`in e&&(i=e.NormalsIndex.a)),{dataSize:3,buffer:r,indices:i,mappingType:t,referenceType:n}}parseUVs(e){let t=e.MappingInformationType,n=e.ReferenceInformationType,r=e.UV.a,i=[];return n===`IndexToDirect`&&(i=e.UVIndex.a),{dataSize:2,buffer:r,indices:i,mappingType:t,referenceType:n}}parseVertexColors(e){let t=e.MappingInformationType,n=e.ReferenceInformationType,r=e.Colors.a,i=[];n===`IndexToDirect`&&(i=e.ColorIndex.a);for(let e=0,t=new H;e<r.length;e+=4)t.fromArray(r,e),Xn.colorSpaceToWorking(t,Ot),t.toArray(r,e);return{dataSize:4,buffer:r,indices:i,mappingType:t,referenceType:n}}parseMaterialIndices(e){let t=e.MappingInformationType,n=e.ReferenceInformationType;if(t===`NoMappingInformation`)return{dataSize:1,buffer:[0],indices:[0],mappingType:`AllSame`,referenceType:n};let r=e.Materials.a,i=[];for(let e=0;e<r.length;++e)i.push(e);return{dataSize:1,buffer:r,indices:i,mappingType:t,referenceType:n}}parseNurbsGeometry(e){let t=parseInt(e.Order);if(isNaN(t))return console.error(`THREE.FBXLoader: Invalid Order %s given for geometry ID: %s`,e.Order,e.id),new W;let n=t-1,r=e.KnotVector.a,i=[],a=e.Points.a;for(let e=0,t=a.length;e<t;e+=4)i.push(new sr().fromArray(a,e));let o,s;if(e.Form===`Closed`)i.push(i[0]);else if(e.Form===`Periodic`){o=n,s=r.length-1-o;for(let e=0;e<n;++e)i.push(i[e])}let c=new rh(n,r,i,o,s).getPoints(i.length*12);return new W().setFromPoints(c)}},lh=class{parse(){let e=[],t=this.parseClips();if(t!==void 0)for(let n in t){let r=t[n],i=this.addClip(r);e.push(i)}return e}parseClips(){if(X.Objects.AnimationCurve===void 0)return;let e=this.parseAnimationCurveNodes();this.parseAnimationCurves(e);let t=this.parseAnimationLayers(e);return this.parseAnimStacks(t)}parseAnimationCurveNodes(){let e=X.Objects.AnimationCurveNode,t=new Map;for(let n in e){let r=e[n];if(r.attrName.match(/S|R|T|DeformPercent/)!==null){let e={id:r.id,attr:r.attrName,curves:{}};t.set(e.id,e)}}return t}parseAnimationCurves(e){let t=X.Objects.AnimationCurve;for(let n in t){let r={id:t[n].id,times:t[n].KeyTime.a.map(_h),values:t[n].KeyValueFloat.a},i=ih.get(r.id);if(i!==void 0){let t=i.parents[0].ID,n=i.parents[0].relationship;n.match(/X/)?e.get(t).curves.x=r:n.match(/Y/)?e.get(t).curves.y=r:n.match(/Z/)?e.get(t).curves.z=r:n.match(/DeformPercent/)&&e.has(t)&&(e.get(t).curves.morph=r)}}}parseAnimationLayers(e){let t=X.Objects.AnimationLayer,n=new Map;for(let r in t){let t=[],i=ih.get(parseInt(r));i!==void 0&&(i.children.forEach(function(n,r){if(e.has(n.ID)){let i=e.get(n.ID);if(i.curves.x!==void 0||i.curves.y!==void 0||i.curves.z!==void 0){if(t[r]===void 0){let e=ih.get(n.ID).parents.filter(function(e){return e.relationship!==void 0});if(e.length===0)return;let i=e[0].ID;if(i!==void 0){let e=X.Objects.Model[i.toString()];if(e===void 0){console.warn(`THREE.FBXLoader: Encountered a unused curve.`,n);return}let a={modelName:e.attrName?Y.sanitizeNodeName(e.attrName):``,ID:e.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};ah.traverse(function(t){t.ID===e.id&&(a.transform=t.matrix,t.userData.transformData&&(a.eulerOrder=t.userData.transformData.eulerOrder,t.userData.transformData.rotation&&(a.initialRotation=t.userData.transformData.rotation)))}),a.transform||=new V,`PreRotation`in e&&(a.preRotation=e.PreRotation.value),`PostRotation`in e&&(a.postRotation=e.PostRotation.value),t[r]=a}}t[r]&&(t[r][i.attr]=i)}else if(i.curves.morph!==void 0){if(t[r]===void 0){let e=ih.get(n.ID).parents.filter(function(e){return e.relationship!==void 0});if(e.length===0)return;let i=e[0].ID,a=ih.get(i).parents[0].ID,o=ih.get(a).parents[0].ID,s=ih.get(o).parents[0].ID,c=X.Objects.Model[s],l={modelName:c.attrName?Y.sanitizeNodeName(c.attrName):``,morphName:X.Objects.Deformer[i].attrName};t[r]=l}t[r][i.attr]=i}}}),n.set(parseInt(r),t))}return n}parseAnimStacks(e){let t=X.Objects.AnimationStack,n={};for(let r in t){let i=ih.get(parseInt(r)).children;i.length>1&&console.warn(`THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.`);let a=e.get(i[0].ID);n[r]={name:t[r].attrName,layer:a}}return n}addClip(e){let t=[],n=this;return e.layer.forEach(function(e){t=t.concat(n.generateTracks(e))}),new tu(e.name,-1,t)}generateTracks(e){let t=[],n=new B,r=new B;if(e.transform&&e.transform.decompose(n,new z,r),n=n.toArray(),r=r.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){let r=this.generateVectorTrack(e.modelName,e.T.curves,n,`position`);r!==void 0&&t.push(r)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){let n=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder,e.initialRotation);n!==void 0&&t.push(n)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){let n=this.generateVectorTrack(e.modelName,e.S.curves,r,`scale`);n!==void 0&&t.push(n)}if(e.DeformPercent!==void 0){let n=this.generateMorphTrack(e);n!==void 0&&t.push(n)}return t}generateVectorTrack(e,t,n,r){let i=this.getTimesForAllAxes(t),a=this.getKeyframeTrackValues(i,t,n);return new eu(e+`.`+r,i,a)}generateRotationTrack(e,t,n,r,i,a){let o,s;if(t.x!==void 0||t.y!==void 0||t.z!==void 0){let e=this.getTimesForAllAxes(t);if(e.length>0){let n=a||[0,0,0],r=this.synchronizeCurve(t.x,e,n[0]),c=this.synchronizeCurve(t.y,e,n[1]),l=this.synchronizeCurve(t.z,e,n[2]),u=this.interpolateRotations(r,c,l,i);o=u[0],s=u[1]}}let c=Ch(0);n!==void 0&&(n=n.map(Hn.degToRad),n.push(c),n=new Cr().fromArray(n),n=new z().setFromEuler(n)),r!==void 0&&(r=r.map(Hn.degToRad),r.push(c),r=new Cr().fromArray(r),r=new z().setFromEuler(r).invert());let l=new z,u=new Cr,d=[];if(!(!s||!o)){for(let e=0;e<s.length;e+=3)u.set(s[e],s[e+1],s[e+2],i),l.setFromEuler(u),n!==void 0&&l.premultiply(n),r!==void 0&&l.multiply(r),e>2&&new z().fromArray(d,(e-3)/3*4).dot(l)<0&&l.set(-l.x,-l.y,-l.z,-l.w),l.toArray(d,e/3*4);return new Ql(e+`.quaternion`,o,d)}}generateMorphTrack(e){let t=e.DeformPercent.curves.morph,n=t.values.map(function(e){return e/100}),r=ah.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new Xl(e.modelName+`.morphTargetInfluences[`+r+`]`,t.times,n)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(e,t){return e-t}),t.length>1){let e=1,n=t[0];for(let r=1;r<t.length;r++){let i=t[r];i!==n&&(t[e]=i,n=i,e++)}t=t.slice(0,e)}return t}getKeyframeTrackValues(e,t,n){let r=n,i=[],a=-1,o=-1,s=-1;return e.forEach(function(e){if(t.x&&(a=t.x.times.indexOf(e)),t.y&&(o=t.y.times.indexOf(e)),t.z&&(s=t.z.times.indexOf(e)),a!==-1){let e=t.x.values[a];i.push(e),r[0]=e}else i.push(r[0]);if(o!==-1){let e=t.y.values[o];i.push(e),r[1]=e}else i.push(r[1]);if(s!==-1){let e=t.z.values[s];i.push(e),r[2]=e}else i.push(r[2])}),i}synchronizeCurve(e,t,n){if(e===void 0)return{times:t,values:t.map(()=>n)};if(e.times.length===t.length)return e;let r=[];for(let i=0;i<t.length;i++)r.push(this.sampleCurveValue(e,t[i],n));return{times:t,values:r}}sampleCurveValue(e,t,n){let r=e.times,i=e.values;if(t<=r[0])return i[0];if(t>=r[r.length-1])return i[i.length-1];for(let e=0;e<r.length-1;e++)if(t>=r[e]&&t<=r[e+1]){if(r[e]===t)return i[e];let n=(t-r[e])/(r[e+1]-r[e]);return i[e]*(1-n)+i[e+1]*n}return n}interpolateRotations(e,t,n,r){let i=[],a=[];i.push(e.times[0]),a.push(Hn.degToRad(e.values[0])),a.push(Hn.degToRad(t.values[0])),a.push(Hn.degToRad(n.values[0]));for(let o=1;o<e.values.length;o++){let s=[e.values[o-1],t.values[o-1],n.values[o-1]];if(isNaN(s[0])||isNaN(s[1])||isNaN(s[2]))continue;let c=s.map(Hn.degToRad),l=[e.values[o],t.values[o],n.values[o]];if(isNaN(l[0])||isNaN(l[1])||isNaN(l[2]))continue;let u=l.map(Hn.degToRad),d=[l[0]-s[0],l[1]-s[1],l[2]-s[2]],f=[Math.abs(d[0]),Math.abs(d[1]),Math.abs(d[2])];if(f[0]>=180||f[1]>=180||f[2]>=180){let t=Math.max(...f)/180,n=new Cr(...c,r),s=new Cr(...u,r),l=new z().setFromEuler(n),d=new z().setFromEuler(s);l.dot(d)<0&&d.set(-d.x,-d.y,-d.z,-d.w);let p=e.times[o-1],m=e.times[o]-p,h=new z,g=new Cr;for(let e=0;e<1;e+=1/t)h.copy(l.clone().slerp(d.clone(),e)),i.push(p+e*m),g.setFromQuaternion(h,r),a.push(g.x),a.push(g.y),a.push(g.z)}else i.push(e.times[o]),a.push(Hn.degToRad(e.values[o])),a.push(Hn.degToRad(t.values[o])),a.push(Hn.degToRad(n.values[o]))}return[i,a]}},uh=class{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),--this.currentIndent}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new ph,this.nodeStack=[],this.currentProp=[],this.currentPropName=``;let t=this,n=e.split(/[\r\n]+/);return n.forEach(function(e,r){let i=e.match(/^[\s\t]*;/),a=e.match(/^[\s\t]*$/);if(i||a)return;let o=e.match(`^\\t{`+t.currentIndent+`}(\\w+):(.*){`,``),s=e.match(`^\\t{`+t.currentIndent+`}(\\w+):[\\s\\t\\r\\n](.*)`),c=e.match(`^\\t{`+(t.currentIndent-1)+`}}`);o?t.parseNodeBegin(e,o):s?t.parseNodeProperty(e,s,n[++r]):c?t.popStack():e.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(e)}),this.allNodes}parseNodeBegin(e,t){let n=t[1].trim().replace(/^"/,``).replace(/"$/,``),r=t[2].split(`,`).map(function(e){return e.trim().replace(/^"/,``).replace(/"$/,``)}),i={name:n},a=this.parseNodeAttr(r),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(n,i):n in o?(n===`PoseNode`?o.PoseNode.push(i):o[n].id!==void 0&&(o[n]={},o[n][o[n].id]=o[n]),a.id!==``&&(o[n][a.id]=i)):typeof a.id==`number`?(o[n]={},o[n][a.id]=i):n!==`Properties70`&&(o[n]=n===`PoseNode`?[i]:i),typeof a.id==`number`&&(i.id=a.id),a.name!==``&&(i.attrName=a.name),a.type!==``&&(i.attrType=a.type),this.pushStack(i)}parseNodeAttr(e){let t=e[0];e[0]!==``&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let n=``,r=``;return e.length>1&&(n=e[1].replace(/^(\w+)::/,``),r=e[2]),{id:t,name:n,type:r}}parseNodeProperty(e,t,n){let r=t[1].replace(/^"/,``).replace(/"$/,``).trim(),i=t[2].replace(/^"/,``).replace(/"$/,``).trim();r===`Content`&&i===`,`&&(i=n.replace(/"/g,``).replace(/,$/,``).trim());let a=this.getCurrentNode();if(a.name===`Properties70`){this.parseNodeSpecialProperty(e,r,i);return}if(r===`C`){let e=i.split(`,`).slice(1),t=parseInt(e[0]),n=parseInt(e[1]),o=i.split(`,`).slice(3);o=o.map(function(e){return e.trim().replace(/^"/,``)}),r=`connections`,i=[t,n],Eh(i,o),a[r]===void 0&&(a[r]=[])}r===`Node`&&(a.id=i),r in a&&Array.isArray(a[r])?a[r].push(i):r===`a`?a.a=i:a[r]=i,this.setCurrentProp(a,r),r===`a`&&i.slice(-1)!==`,`&&(a.a=wh(i))}parseNodePropertyContinued(e){let t=this.getCurrentNode();t.a+=e,e.slice(-1)!==`,`&&(t.a=wh(t.a))}parseNodeSpecialProperty(e,t,n){let r=n.split(`",`).map(function(e){return e.trim().replace(/^\"/,``).replace(/\s/,`_`)}),i=r[0],a=r[1],o=r[2],s=r[3],c=r[4];switch(a){case`int`:case`enum`:case`bool`:case`ULongLong`:case`double`:case`Number`:case`FieldOfView`:c=parseFloat(c);break;case`Color`:case`ColorRGB`:case`Vector3D`:case`Lcl_Translation`:case`Lcl_Rotation`:case`Lcl_Scaling`:c=wh(c)}this.getPrevNode()[i]={type:a,type2:o,flag:s,value:c},this.setCurrentProp(this.getPrevNode(),i)}},dh=class{parse(e){let t=new fh(e);t.skip(23);let n=t.getUint32();if(n<6400)throw Error(`THREE.FBXLoader: FBX version not supported, FileVersion: `+n);let r=new ph;for(;!this.endOfContent(t);){let e=this.parseNode(t,n);e!==null&&r.add(e.name,e)}return r}endOfContent(e){return e.size()%16==0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){let n={},r=t>=7500?e.getUint64():e.getUint32(),i=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();let a=e.getUint8(),o=e.getString(a);if(r===0)return null;let s=[];for(let t=0;t<i;t++)s.push(this.parseProperty(e));let c=s.length>0?s[0]:``,l=s.length>1?s[1]:``,u=s.length>2?s[2]:``;for(n.singleProperty=i===1&&e.getOffset()===r;r>e.getOffset();){let r=this.parseNode(e,t);r!==null&&this.parseSubNode(o,n,r)}return n.propertyList=s,typeof c==`number`&&(n.id=c),l!==``&&(n.attrName=l),u!==``&&(n.attrType=u),o!==``&&(n.name=o),n}parseSubNode(e,t,n){if(n.singleProperty===!0){let e=n.propertyList[0];Array.isArray(e)?(t[n.name]=n,n.a=e):t[n.name]=e}else if(e===`Connections`&&n.name===`C`){let e=[];n.propertyList.forEach(function(t,n){n!==0&&e.push(t)}),t.connections===void 0&&(t.connections=[]),t.connections.push(e)}else if(n.name===`Properties70`)Object.keys(n).forEach(function(e){t[e]=n[e]});else if(e===`Properties70`&&n.name===`P`){let e=n.propertyList[0],r=n.propertyList[1],i=n.propertyList[2],a=n.propertyList[3],o;e.indexOf(`Lcl `)===0&&(e=e.replace(`Lcl `,`Lcl_`)),r.indexOf(`Lcl `)===0&&(r=r.replace(`Lcl `,`Lcl_`)),o=r===`Color`||r===`ColorRGB`||r===`Vector`||r===`Vector3D`||r.indexOf(`Lcl_`)===0?[n.propertyList[4],n.propertyList[5],n.propertyList[6]]:n.propertyList[4],t[e]={type:r,type2:i,flag:a,value:o}}else t[n.name]===void 0?typeof n.id==`number`?(t[n.name]={},t[n.name][n.id]=n):t[n.name]=n:n.name===`PoseNode`?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(n)):t[n.name][n.id]===void 0&&(t[n.name][n.id]=n)}parseProperty(e){let t=e.getString(1),n;switch(t){case`C`:return e.getBoolean();case`D`:return e.getFloat64();case`F`:return e.getFloat32();case`I`:return e.getInt32();case`L`:return e.getInt64();case`R`:return n=e.getUint32(),e.getArrayBuffer(n);case`S`:return n=e.getUint32(),e.getString(n);case`Y`:return e.getInt16();case`b`:case`c`:case`d`:case`f`:case`i`:case`l`:let r=e.getUint32(),i=e.getUint32(),a=e.getUint32();if(i===0)switch(t){case`b`:case`c`:return e.getBooleanArray(r);case`d`:return e.getFloat64Array(r);case`f`:return e.getFloat32Array(r);case`i`:return e.getInt32Array(r);case`l`:return e.getInt64Array(r)}let o=new fh(qm(new Uint8Array(e.getArrayBuffer(a))).buffer);switch(t){case`b`:case`c`:return o.getBooleanArray(r);case`d`:return o.getFloat64Array(r);case`f`:return o.getFloat32Array(r);case`i`:return o.getInt32Array(r);case`l`:return o.getInt64Array(r)}break;default:throw Error(`THREE.FBXLoader: Unknown property type `+t)}}},fh=class{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t===void 0||t,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)==1}getBooleanArray(e){let t=[];for(let n=0;n<e;n++)t.push(this.getBoolean());return t}getUint8(){let e=this.dv.getUint8(this.offset);return this.offset+=1,e}getInt16(){let e=this.dv.getInt16(this.offset,this.littleEndian);return this.offset+=2,e}getInt32(){let e=this.dv.getInt32(this.offset,this.littleEndian);return this.offset+=4,e}getInt32Array(e){let t=[];for(let n=0;n<e;n++)t.push(this.getInt32());return t}getUint32(){let e=this.dv.getUint32(this.offset,this.littleEndian);return this.offset+=4,e}getInt64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t&2147483648?(t=~t&4294967295,e=~e&4294967295,e===4294967295&&(t=t+1&4294967295),e=e+1&4294967295,-(t*4294967296+e)):t*4294967296+e}getInt64Array(e){let t=[];for(let n=0;n<e;n++)t.push(this.getInt64());return t}getUint64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t*4294967296+e}getFloat32(){let e=this.dv.getFloat32(this.offset,this.littleEndian);return this.offset+=4,e}getFloat32Array(e){let t=[];for(let n=0;n<e;n++)t.push(this.getFloat32());return t}getFloat64(){let e=this.dv.getFloat64(this.offset,this.littleEndian);return this.offset+=8,e}getFloat64Array(e){let t=[];for(let n=0;n<e;n++)t.push(this.getFloat64());return t}getArrayBuffer(e){let t=this.dv.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}getString(e){let t=this.offset,n=new Uint8Array(this.dv.buffer,t,e);this.skip(e);let r=n.indexOf(0);return r>=0&&(n=new Uint8Array(this.dv.buffer,t,r)),this._textDecoder.decode(n)}},ph=class{add(e,t){this[e]=t}};function mh(e){return e.byteLength>=21&&Th(e,0,21)===`Kaydara FBX Binary \0`}function hh(e){let t=[`K`,`a`,`y`,`d`,`a`,`r`,`a`,`\\`,`F`,`B`,`X`,`\\`,`B`,`i`,`n`,`a`,`r`,`y`,`\\`,`\\`],n=0;function r(t){let r=e[t-1];return e=e.slice(n+t),n++,r}for(let e=0;e<t.length;++e)if(r(1)===t[e])return!1;return!0}function gh(e){let t=e.match(/FBXVersion: (\d+)/);if(t)return parseInt(t[1]);throw Error(`THREE.FBXLoader: Cannot find the version number for the file given.`)}function _h(e){return e/46186158e3}var vh=[];function yh(e,t,n,r){let i;switch(r.mappingType){case`ByPolygonVertex`:i=e;break;case`ByPolygon`:i=t;break;case`ByVertice`:i=n;break;case`AllSame`:i=r.indices[0];break;default:console.warn(`THREE.FBXLoader: unknown attribute mapping type `+r.mappingType)}r.referenceType===`IndexToDirect`&&(i=r.indices[i]);let a=i*r.dataSize,o=a+r.dataSize;return Dh(vh,r.buffer,a,o)}var bh=new Cr,xh=new B;function Sh(e){let t=new V,n=new V,r=new V,i=new V,a=new V,o=new V,s=new V,c=new V,l=new V,u=new V,d=new V,f=new V,p=e.inheritType?e.inheritType:0;e.translation&&t.setPosition(xh.fromArray(e.translation));let m=Ch(0);if(e.preRotation){let t=e.preRotation.map(Hn.degToRad);t.push(m),n.makeRotationFromEuler(bh.fromArray(t))}if(e.rotation){let t=e.rotation.map(Hn.degToRad);t.push(e.eulerOrder||m),r.makeRotationFromEuler(bh.fromArray(t))}if(e.postRotation){let t=e.postRotation.map(Hn.degToRad);t.push(m),i.makeRotationFromEuler(bh.fromArray(t)),i.invert()}e.scale&&a.scale(xh.fromArray(e.scale)),e.scalingOffset&&s.setPosition(xh.fromArray(e.scalingOffset)),e.scalingPivot&&o.setPosition(xh.fromArray(e.scalingPivot)),e.rotationOffset&&c.setPosition(xh.fromArray(e.rotationOffset)),e.rotationPivot&&l.setPosition(xh.fromArray(e.rotationPivot)),e.parentMatrixWorld&&(d.copy(e.parentMatrix),u.copy(e.parentMatrixWorld));let h=n.clone().multiply(r).multiply(i),g=new V;g.extractRotation(u);let _=new V;_.copyPosition(u);let v=_.clone().invert().multiply(u),y=g.clone().invert().multiply(v),b=a,x=new V;if(p===0)x.copy(g).multiply(h).multiply(y).multiply(b);else if(p===1)x.copy(g).multiply(y).multiply(h).multiply(b);else{let e=new V().scale(new B().setFromMatrixScale(d)).clone().invert(),t=y.clone().multiply(e);x.copy(g).multiply(h).multiply(t).multiply(b)}let S=l.clone().invert(),C=o.clone().invert(),w=t.clone().multiply(c).multiply(l).multiply(n).multiply(r).multiply(i).multiply(S).multiply(s).multiply(o).multiply(a).multiply(C),T=new V().copyPosition(w),E=u.clone().multiply(T);return f.copyPosition(E),w=f.clone().multiply(x),w.premultiply(u.invert()),w}function Ch(e){e||=0;let t=[`ZYX`,`YZX`,`XZY`,`ZXY`,`YXZ`,`XYZ`];return e===6?(console.warn(`THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.`),t[0]):t[e]}function wh(e){return e.split(`,`).map(function(e){return parseFloat(e)})}function Th(e,t,n){return t===void 0&&(t=0),n===void 0&&(n=e.byteLength),new TextDecoder().decode(new Uint8Array(e,t,n))}function Eh(e,t){for(let n=0,r=e.length,i=t.length;n<i;n++,r++)e[r]=t[n]}function Dh(e,t,n,r){for(let i=n,a=0;i<r;i++,a++)e[a]=t[i];return e}var Oh=`Kaydara FBX Binary \0`,kh=65536;function Ah(e){return e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null}function jh(e){return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):null}function Mh(e){let t=Ah(e);if(!t||t.byteLength<21)return!1;for(let e=0;e<21;e++)if(t[e]!==Oh.charCodeAt(e))return!1;return!0}function Nh(e){let t=Ah(e);if(!t||!t.byteLength)return null;let n=t.subarray(0,Math.min(t.byteLength,kh)),r=new TextDecoder(`utf-8`).decode(n).match(/FBXVersion: (\d+)/);if(!r)return null;let i=Number(r[1]);return Number.isFinite(i)?i:null}function Ph(e){let t=jh(e);return!t||!t.byteLength?null:new oh().parse(t,``)}function Fh(e){try{let t=Ph(e);if(!t)return null;t.updateMatrixWorld(!0);let n=new fi().setFromObject(t),r=n.getSize(new B);return!(r.y>0)||!Number.isFinite(r.y)?null:{min:{x:n.min.x,y:n.min.y,z:n.min.z},max:{x:n.max.x,y:n.max.y,z:n.max.z}}}catch{return null}}var Ih=.05,Lh=1179937895,Rh=1313821514,zh=12,Bh=8;function Vh(e){return e instanceof ArrayBuffer?new DataView(e):ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):null}function Hh(e){let t=Vh(e);return!!(t&&t.byteLength>=4&&t.getUint32(0,!0)===Lh)}function Uh(e){let t=Vh(e);if(!t||t.byteLength<zh||t.getUint32(0,!0)!==Lh)return null;let n=zh;for(;n+Bh<=t.byteLength;){let e=t.getUint32(n,!0),r=t.getUint32(n+4,!0),i=n+Bh;if(e>t.byteLength-i)return null;if(r===Rh){let n=new Uint8Array(t.buffer,t.byteOffset+i,e);try{let e=n.length;for(;e>0&&n[e-1]===0;)--e;return JSON.parse(new TextDecoder().decode(n.subarray(0,e)))}catch{return null}}n=i+e}return null}function Wh(e){let t=Uh(e);if(!t||typeof t!=`object`)return null;let n=Array.isArray(t.accessors)?t.accessors:[],r=new Set;for(let e of Array.isArray(t.meshes)?t.meshes:[])for(let t of Array.isArray(e?.primitives)?e.primitives:[]){let e=t?.attributes?.POSITION;Number.isInteger(e)&&r.add(e)}let i=null;for(let e of r){let t=n[e],r=t?.min,a=t?.max;if(!Array.isArray(r)||!Array.isArray(a)||r.length!==3||a.length!==3)continue;let o=[Number(r[0]),Number(r[1]),Number(r[2])],s=[Number(a[0]),Number(a[1]),Number(a[2])];if(!(o.some(e=>!Number.isFinite(e))||s.some(e=>!Number.isFinite(e)))){if(!i){i={min:{x:o[0],y:o[1],z:o[2]},max:{x:s[0],y:s[1],z:s[2]}};continue}i.min.x=Math.min(i.min.x,o[0]),i.min.y=Math.min(i.min.y,o[1]),i.min.z=Math.min(i.min.z,o[2]),i.max.x=Math.max(i.max.x,s[0]),i.max.y=Math.max(i.max.y,s[1]),i.max.z=Math.max(i.max.z,s[2])}}return i}var Gh=new Set([`KHR_draco_mesh_compression`,`EXT_meshopt_compression`]),Kh=`That model is compressed — export it uncompressed (no Draco / meshopt)`;function qh(e){let t=new Set;if(!e||typeof e!=`object`)return t;for(let n of[e.extensionsUsed,e.extensionsRequired])if(Array.isArray(n))for(let e of n)typeof e==`string`&&t.add(e);for(let n of Array.isArray(e.meshes)?e.meshes:[])for(let e of Array.isArray(n?.primitives)?n.primitives:[]){let n=e?.extensions;if(!(!n||typeof n!=`object`))for(let e of Object.keys(n))t.add(e)}return t}function Jh(e){let t=Uh(e);if(!t)return null;for(let e of qh(t))if(Gh.has(e))return Kh;return null}function Yh(e){return e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null}function Xh(e){let t=Yh(e);if(!t||!t.byteLength)return``;let n=new TextDecoder(`utf-8`).decode(t);return n.charCodeAt(0)===65279&&(n=n.slice(1)),n}function Zh(e){let t=Xh(e);if(!t)return null;let n=null;for(let e of t.split(/\r?\n/)){let t=e.trim();if(!/^v(?:\s|$)/.test(t))continue;let r=t.split(/\s+/);if(r[0]!==`v`)continue;let i=Number(r[1]),a=Number(r[2]),o=Number(r[3]);if([i,a,o].every(Number.isFinite)){if(!n){n={min:{x:i,y:a,z:o},max:{x:i,y:a,z:o}};continue}n.min.x=Math.min(n.min.x,i),n.min.y=Math.min(n.min.y,a),n.min.z=Math.min(n.min.z,o),n.max.x=Math.max(n.max.x,i),n.max.y=Math.max(n.max.y,a),n.max.z=Math.max(n.max.z,o)}}return n}function Qh(e){let t=String(e?.type??``).toLowerCase();return t===`model/obj`?Zh(e?.bytes):t===`model/fbx`?Fh(e?.bytes):t===`model/gltf-binary`?Wh(e?.bytes):null}function $h({min:e,max:t}={}){let n=Number(t?.x)-Number(e?.x),r=Number(t?.y)-Number(e?.y),i=Number(t?.z)-Number(e?.z);if(!Number.isFinite(r)||!(r>0))return null;let a=r<.05||r>10?1/r:1,o=n*a,s=r*a,c=i*a;return{width:o,height:s,depth:c,fitScale:a,footprint:{width:o,depth:c}}}function eg(e){if(!e)return!1;let t=typeof e.type==`string`?e.type.toLowerCase():``;return t===`model/gltf-binary`||t===`application/gltf-binary`?!0:t===``||t===`application/octet-stream`?String(e.name??``).toLowerCase().endsWith(`.glb`):!1}function tg(e){if(!e)return!1;let t=typeof e.type==`string`?e.type.toLowerCase():``;return t===`model/obj`?!0:String(e.name??``).toLowerCase().endsWith(`.obj`)?t===``||t===`text/plain`||t===`application/octet-stream`||t===`text/x-obj`||t===`application/object`:!1}function ng(e){if(!e)return!1;let t=typeof e.type==`string`?e.type.toLowerCase():``;return t===`model/fbx`?!0:String(e.name??``).toLowerCase().endsWith(`.fbx`)?t===``||t===`text/plain`||t===`application/octet-stream`:!1}function rg(e){return Array.from(e?.files??[]).filter(e=>eg(e)||tg(e)||ng(e))}function ig(e){return e?Array.isArray(e)?e:typeof e.length==`number`&&e.files==null?Array.from(e):Array.from(e.files??[]):[]}function ag(e){let t=[],n=[],r=[];for(let i of ig(e))rg({files:[i]}).length?n.push(i):tm({files:[i]}).length?t.push(i):r.push(i);return{images:t,meshes:n,rejected:r}}async function og(e,t=globalThis.crypto?.subtle){if(!e||typeof e.arrayBuffer!=`function`)throw Error(`importMeshFile needs a File or Blob`);if(Number(e.size)>33554432)throw Error(`That model is too large to import — larger than ${Math.round(Rp/1048576)} MB`);let n=await e.arrayBuffer(),r=typeof e.name==`string`?e.name:``,i=eg(e)||r.toLowerCase().endsWith(`.glb`),a=ng(e)||r.toLowerCase().endsWith(`.fbx`),o=tg(e)||r.toLowerCase().endsWith(`.obj`);if(Hh(n)){let e=Jh(n);if(e)throw Error(e);let i=Wh(n),a=i?$h(i):null;if(!a)throw Error(`That model has no measurable geometry`);let o=em({id:await Zp(n,t),type:`model/gltf-binary`,bytes:n,name:r});if(!o)throw Error(`That model could not be prepared for the set`);return{asset:o,height:a.height,footprint:a.footprint}}if(i)throw Error(`That file is not a GLB model`);let s=Nh(n);if(Mh(n)||(s??0)>=7e3)try{let e=Fh(n),i=e?$h(e):null;if(!i)throw Error(`That model has no measurable geometry`);let a=em({id:await Zp(n,t),type:`model/fbx`,bytes:n,name:r});if(!a)throw Error(`That model could not be prepared for the set`);return{asset:a,height:i.height,footprint:i.footprint}}catch(e){throw sg(e)}if(s!=null&&s<7e3)throw Error(`That FBX file is too old to import`);if(a)throw Error(`That file is not an FBX model`);let c=Zh(n);if(!c)throw Error(o?`That file is not an OBJ model`:`That file is not a 3D model`);let l=$h(c);if(!l)throw Error(`That model has no measurable geometry`);let u=em({id:await Zp(n,t),type:`model/obj`,bytes:n,name:r});if(!u)throw Error(`That model could not be prepared for the set`);return{asset:u,height:l.height,footprint:l.footprint}}function sg(e){let t=String(e?.message??e);return/too old to import/i.test(t)||/no measurable geometry/i.test(t)||/not an FBX/i.test(t)?e instanceof Error?e:Error(t):/version not supported|FileVersion/i.test(t)?Error(`That FBX file is too old to import`):Error(`That file is not an FBX model`)}var cg=[],lg=`XYZ`,ug=Math.PI/180,dg=i(`object.position`),fg=i(`object.rotation`),pg=i(`object.scale`),mg=(e,t,n)=>Math.min(n,Math.max(t,e)),hg=e=>{let t=fg.min.y,n=fg.max.y-t;return((e-t)%n+n)%n+t},gg=(e,t)=>Number((t>0?Math.round(e/t)*t:e).toFixed(4)),_g=`#c2c6c8`,vg=[{kind:`cube`,label:`Cube`,group:`Primitives`,footprint:{width:1,depth:1},height:1,color:_g},{kind:`sphere`,label:`Sphere`,group:`Primitives`,footprint:{width:1,depth:1},height:1,color:_g},{kind:`capsule`,label:`Capsule`,group:`Primitives`,footprint:{width:.7,depth:.7},height:1.4,color:_g},{kind:`cylinder`,label:`Cylinder`,group:`Primitives`,footprint:{width:1,depth:1},height:1,color:_g},{kind:`cone`,label:`Cone`,group:`Primitives`,footprint:{width:1,depth:1},height:1,color:_g},{kind:`plane`,label:`Plane`,group:`Primitives`,footprint:{width:2,depth:2},height:0,color:_g},{kind:`chair`,label:`Chair`,group:`Set pieces`,footprint:{width:.6,depth:.6},height:1.15,supportY:.495,color:`#b9855d`},{kind:`car`,label:`Car`,group:`Set pieces`,footprint:{width:1.8,depth:4.5},height:1.4,color:`#d98770`},{kind:`small-plane`,label:`Plane (aircraft)`,group:`Set pieces`,footprint:{width:3.4,depth:3.6},height:1.4,color:`#7896a4`}],yg=[`#e2e5e6`,_g,`#9aa1a5`,`#767d81`,`#d9b18c`,`#8fae9b`,`#d94a4a`,`#4a7bd9`,`#e2c04a`,`#4fa86a`],bg=`cozyclay.objectColors.recent`,xg=/^#?([0-9a-f]{3})$/i,Sg=/^#?([0-9a-f]{6})$/i;function Cg(e){if(typeof e!=`string`)return null;let t=e.trim(),n=xg.exec(t);if(n)return`#${n[1].toLowerCase().replace(/./g,e=>e+e)}`;let r=Sg.exec(t);return r?`#${r[1].toLowerCase()}`:null}function wg(e,t){let n=Array.isArray(e)?e.map(Cg).filter((e,t,n)=>e&&n.indexOf(e)===t&&!yg.includes(e)):[],r=Cg(t),i=(r&&!yg.includes(r)?[r,...n.filter(e=>e!==r)]:n).slice(0,6);return Array.isArray(e)&&i.length===e.length&&i.every((t,n)=>t===e[n])?e:i}function Tg(e){try{let t=JSON.parse(e?.getItem(`cozyclay.objectColors.recent`)??`[]`);return wg(Array.isArray(t)?t:[],null)}catch{return[]}}function Eg(e,t){try{e?.setItem(bg,JSON.stringify(t))}catch{}}var Dg=`cutout`,Og=.02,kg=1.8,Ag=.05,jg=.02,Mg=50,Ng=`#ffffff`,Pg={kind:Dg,label:`Cutout`,group:`Images`,footprint:{width:1,depth:Og},height:kg,color:Ng},Fg=`mesh`,Ig={kind:Fg,label:`Model`,group:`Models`,footprint:{width:1,depth:1},height:1,color:`#c49a6c`};function Lg(e){return e===`cutout`?Pg:e===`mesh`?Ig:vg.find(t=>t.kind===e)??null}function Rg(e){if(!e||typeof e!=`object`)return 0;let t=Lg(e.renderer),n=Number(e.supportY??t?.supportY??e.height??t?.height);return Number.isFinite(n)?n:0}var zg=e=>Math.max(Ag,e),Bg=e=>mg(e,jg,Mg),Vg=.1,Hg=e=>{let t=Number(e);return Number.isFinite(t)?mg(t,Vg,10):1};function Ug(e,t,n=1){return{width:zg(e)*Bg(t)*Hg(n),depth:Og}}var Wg=Object.freeze([`hips`,`spine`,`chest`,`neck`,`head`,`leftShoulder`,`leftElbow`,`leftHand`,`rightShoulder`,`rightElbow`,`rightHand`,`leftKnee`,`leftFoot`,`rightKnee`,`rightFoot`]);function Gg(e){if(e===null)return null;if(!e||typeof e!=`object`||Array.isArray(e))return;let{characterId:t,bone:n}=e;if(!(typeof t!=`string`||!t)){if(n==null)return{characterId:t,bone:null};if(!(typeof n!=`string`||!Wg.includes(n)))return{characterId:t,bone:n}}}function Kg(e){return e.startsWith(`object:`)?e.slice(7):null}function qg(e,t=[],n={}){if(e===`cutout`||e===`mesh`)return null;let r=Lg(e);if(!r)return null;let i=new Set(t.map(e=>e.name)),a=r.label;for(let e=2;i.has(a);e+=1)a=`${r.label} ${e}`;let o=new Set(t.map(e=>e.id)),s=e;for(let t=2;o.has(s);t+=1)s=`${e}-${t}`;return{id:s,name:a,renderer:e,x:Qg.x(Number(n.x)||0),y:0,z:Qg.z(Number(n.z)||0),rot:Qg.rot(Number(n.rot)||0),rotX:0,rotZ:0,scaleX:1,scaleY:1,scaleZ:1,path:null,color:r.color,parent:null,attach:null,hidden:!1,footprint:{...r.footprint},height:r.height,supportY:Number.isFinite(r.supportY)?r.supportY:r.height}}function Jg({assetId:e,aspect:t=1,height:n=kg,name:r=``,sourceAssetId:i,matteAssetId:a,matteScale:o,stretch:s}={},c=[],l={}){if(typeof e!=`string`||!e)return null;let u=Bg(Number(t)),d=zg(Number(n));if(!Number.isFinite(u)||!Number.isFinite(d))return null;let f=Hg(s),p=typeof r==`string`&&r.trim()?r.trim():Pg.label,m=new Set(c.map(e=>e.name)),h=p;for(let e=2;m.has(h);e+=1)h=`${p} ${e}`;let g=new Set(c.map(e=>e.id)),_=Dg;for(let e=2;g.has(_);e+=1)_=`${Dg}-${e}`;return{id:_,name:h,renderer:Dg,x:Qg.x(Number(l.x)||0),y:0,z:Qg.z(Number(l.z)||0),rot:Qg.rot(Number(l.rot)||0),rotX:0,rotZ:0,scaleX:1,scaleY:1,scaleZ:1,path:null,color:Ng,parent:null,attach:null,hidden:!1,assetId:e,sourceAssetId:typeof i==`string`&&i?i:e,matteAssetId:typeof a==`string`?a:``,matteScale:Number.isFinite(Number(o))?Number(o):1,aspect:u,stretch:f,footprint:Ug(d,u,f),height:d}}function Yg(e){return{assetId:e.assetId,aspect:e.aspect,height:e.height,name:e.name,sourceAssetId:e.sourceAssetId,matteAssetId:e.matteAssetId,matteScale:e.matteScale,stretch:e.stretch}}function Xg({assetId:e,height:t=1,footprint:n,name:r=``,clay:i=!1}={},a=[],o={}){if(typeof e!=`string`||!e)return null;let s=Math.max(Ih,Number(t));if(!Number.isFinite(s))return null;let c=Number(n?.width),l=Number(n?.depth),u=Number.isFinite(c)&&c>0&&Number.isFinite(l)&&l>0?{width:c,depth:l}:{width:s,depth:s},d=typeof r==`string`&&r.trim()?r.trim():Ig.label,f=new Set(a.map(e=>e.name)),p=d;for(let e=2;f.has(p);e+=1)p=`${d} ${e}`;let m=new Set(a.map(e=>e.id)),h=Fg;for(let e=2;m.has(h);e+=1)h=`${Fg}-${e}`;return{id:h,name:p,renderer:Fg,x:Qg.x(Number(o.x)||0),y:0,z:Qg.z(Number(o.z)||0),rot:hg(Number(o.rot)||0),rotX:0,rotZ:0,scaleX:1,scaleY:1,scaleZ:1,path:null,color:Ig.color,parent:null,attach:null,hidden:!1,assetId:e,clay:i===!0,footprint:u,height:s}}function Zg(e){return{assetId:e.assetId,height:e.height,footprint:e.footprint,name:e.name,clay:e.clay===!0}}var Qg={x:e=>mg(e,dg.min.x,dg.max.x),y:e=>mg(e,dg.min.y,dg.max.y),z:e=>mg(e,dg.min.z,dg.max.z),rot:e=>hg(e),rotX:e=>hg(e),rotZ:e=>hg(e),scaleX:e=>mg(e,pg.min.x,pg.max.x),scaleY:e=>mg(e,pg.min.y,pg.max.y),scaleZ:e=>mg(e,pg.min.z,pg.max.z)};function $g(e,t){let n=[],r=new Set([t]),i=[t];for(;i.length;){let t=[];for(let a of e)a.parent&&i.includes(a.parent)&&!r.has(a.id)&&(r.add(a.id),n.push(a),t.push(a.id));i=t}return n}function e_(e,t=[],n=[]){if(!e||typeof e!=`object`)return!1;let r=new Map;for(let e of t)e&&typeof e.id==`string`&&r.set(e.id,e);let i=e=>n.some(t=>t&&typeof t==`object`&&t.id===e&&t.hidden===!0),a=new Set,o=e;for(;o&&typeof o==`object`;){let e=typeof o.id==`string`?o.id:null;if(e){if(a.has(e))break;a.add(e),r.has(e)&&(o=r.get(e))}if(o.hidden===!0)return!0;let t=o.attach&&typeof o.attach.characterId==`string`?o.attach.characterId:null;if(t&&i(t))return!0;let n=typeof o.parent==`string`?o.parent:null;if(!n)break;o=r.get(n)??null}return!1}function t_(e,t,n){let r=!1,i=e.find(e=>e.id===t),a=i?$g(e,t):[],o={x:0,y:0,z:0};if(i)for(let e of[`x`,`y`,`z`]){if(n[e]===void 0)continue;let t=Number(n[e]);Number.isFinite(t)&&(o[e]=Qg[e](t)-i[e])}let s=new Set(a.map(e=>e.id)),c=o.x||o.y||o.z,l=e.map(e=>{if(e.id!==t){if(!c||!s.has(e.id))return e;let t={},n={x:0,y:0,z:0};for(let r of[`x`,`y`,`z`]){if(!o[r])continue;let i=Qg[r](e[r]+o[r]);i!==e[r]&&(t[r]=i,n[r]=i-e[r])}return e.path&&(n.x||n.y||n.z)&&(t.path=Tp(e.path,n)),Object.keys(t).length?(r=!0,{...e,...t}):e}let i={};for(let[t,r]of Object.entries(Qg)){if(n[t]===void 0)continue;let a=Number(n[t]);if(!Number.isFinite(a))continue;let o=r(a);o!==e[t]&&(i[t]=o)}for(let t of[`name`,`color`])typeof n[t]!=`string`||!n[t]||n[t]===e[t]||(i[t]=n[t]);if(typeof n.hidden==`boolean`&&n.hidden!==(e.hidden===!0)&&(i.hidden=n.hidden),n.path!==void 0){let t=n.path===null?null:wp(n.path);JSON.stringify(t??null)!==JSON.stringify(e.path??null)&&(i.path=t)}else if(e.path&&c){let t=Tp(e.path,o);JSON.stringify(t??null)!==JSON.stringify(e.path??null)&&(i.path=t)}if(e.renderer===`cutout`){for(let t of[`assetId`,`sourceAssetId`,`matteAssetId`])typeof n[t]==`string`&&n[t]&&n[t]!==e[t]&&(i[t]=n[t]);if(Number.isFinite(Number(n.matteScale))){let t=mg(Number(n.matteScale),.01,1);t!==e.matteScale&&(i.matteScale=t)}let t=n.height===void 0?NaN:zg(Number(n.height)),r=n.aspect===void 0?NaN:Bg(Number(n.aspect)),a=Number.isFinite(t)?t:e.height,o=Number.isFinite(r)?r:e.aspect,s=Hg(e.stretch),c=n.width!==void 0&&Number.isFinite(Number(n.width))?Hg(Number(n.width)/(a*o)):n.stretch===void 0?s:Hg(n.stretch);(a!==e.height||o!==e.aspect||c!==s)&&(i.height=a,i.aspect=o,i.stretch=c,i.footprint=Ug(a,o,c))}if(e.renderer===`mesh`){typeof n.clay==`boolean`&&n.clay!==(e.clay===!0)&&(i.clay=n.clay),typeof n.assetId==`string`&&n.assetId&&n.assetId!==e.assetId&&(i.assetId=n.assetId);let t=n.height===void 0?NaN:Math.max(Ih,Number(n.height));if(Number.isFinite(t)&&t!==e.height){i.height=t;let n=Number(e.height);if(n>0){let r=t/n;i.footprint={width:Number(e.footprint?.width)*r,depth:Number(e.footprint?.depth)*r}}}}return Object.keys(i).length?(r=!0,{...e,...i}):e});return r?l:e}function n_(e,t,n){if(t===n||n!==null&&!e.some(e=>e.id===n)||n!==null&&$g(e,t).some(e=>e.id===n))return e;let r=!1,i=e.map(e=>{if(e.id!==t)return e;let i=n??null,a=i!==null&&(e.attach??null)!==null;return(e.parent??null)===i&&!a?e:(r=!0,a?{...e,parent:i,attach:null}:{...e,parent:i})});return r?i:e}function r_(e,t,n){let r=Gg(n);if(r===void 0||!e.some(e=>e.id===t))return e;let i=!1,a=e.map(e=>{if(e.id!==t)return e;let n=e.attach??null;if(r===null)return n===null?e:(i=!0,{...e,attach:null});let a=n!==null&&n.characterId===r.characterId&&(n.bone??null)===r.bone,o=(e.parent??null)!==null;return a&&!o?e:(i=!0,o?{...e,attach:r,parent:null}:{...e,attach:r})});return i?a:e}function i_(e,t){let n=e.filter(e=>e.id!==t);return n.length===e.length?e:n.map(e=>e.parent===t?{...e,parent:null}:e)}function a_(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=Lg(e.renderer);if(!t||typeof e.id!=`string`||!e.id)return null;let n=t.kind===Dg,r=t.kind===Fg;if(n&&(typeof e.assetId!=`string`||!e.assetId)||r&&(typeof e.assetId!=`string`||!e.assetId))return null;let i=e.scaleX===void 0&&e.scaleY===void 0&&e.scaleZ===void 0?Number(e.scale):NaN,a=Number.isFinite(i)?i:1,o=(e,t)=>{let n=e===void 0?t:Number(e);return Number.isFinite(n)?n:t},s=Number(e.footprint?.width),c=Number(e.footprint?.depth),l=Number.isFinite(s)&&s>0&&Number.isFinite(c)&&c>0?{width:s,depth:c}:{...t.footprint};return{id:e.id,name:typeof e.name==`string`&&e.name?e.name:t.label,renderer:t.kind,x:Qg.x(o(e.x,0)),y:Qg.y(o(e.y,0)),z:Qg.z(o(e.z,0)),rot:Qg.rot(o(e.rot,0)),rotX:Qg.rotX(o(e.rotX,0)),rotZ:Qg.rotZ(o(e.rotZ,0)),scaleX:Qg.scaleX(o(e.scaleX,a)),scaleY:Qg.scaleY(o(e.scaleY,a)),scaleZ:Qg.scaleZ(o(e.scaleZ,a)),path:wp(e.path),color:typeof e.color==`string`&&e.color?e.color:t.color,parent:typeof e.parent==`string`&&e.parent?e.parent:null,attach:Gg(e.attach)??null,hidden:e.hidden===!0,...n?{assetId:e.assetId,sourceAssetId:typeof e.sourceAssetId==`string`&&e.sourceAssetId?e.sourceAssetId:e.assetId,matteAssetId:typeof e.matteAssetId==`string`?e.matteAssetId:``,matteScale:mg(o(e.matteScale,1),.01,1),aspect:Bg(o(e.aspect,1)),stretch:Hg(o(e.stretch,1)),footprint:Ug(o(e.height,kg),o(e.aspect,1),o(e.stretch,1)),height:zg(o(e.height,kg))}:r?{assetId:e.assetId,clay:e.clay===!0,footprint:l,height:Math.max(Ih,o(e.height,t.height))}:{footprint:{...t.footprint},height:t.height,supportY:Number.isFinite(t.supportY)?t.supportY:t.height}}}var o_=[`x`,`y`,`z`],s_={x:`rotX`,y:`rot`,z:`rotZ`},c_={x:`scaleX`,y:`scaleY`,z:`scaleZ`},l_=.05,u_=5,d_=.05;function f_(e,t,n,r=l_){if(!o_.includes(t)||!Number.isFinite(n))return null;let i=gg((e[t]??0)+n,r);return{[t]:i}}function p_(e,t,n,r=u_){let i=s_[t];return!i||!Number.isFinite(n)?null:{[i]:hg(gg((e[i]??0)+n,r))}}function m_(e,t,n,r=d_){if(!Number.isFinite(n)||n<=0)return null;let i=t===null?o_:o_.includes(t)?[t]:[];if(!i.length)return null;let a={};for(let t of i){let i=c_[t];a[i]=Qg[i](gg((e[i]??1)*n,r))}return a}function h_(e,t,n,r=u_){if(!Number.isFinite(n)||!t)return null;let i=gg(n,r),a=new z().setFromEuler(new Cr((e.rotX??0)*ug,(e.rot??0)*ug,(e.rotZ??0)*ug,lg));a.premultiply(new z().setFromAxisAngle(t,i*ug));let o=new Cr().setFromQuaternion(a,lg);return{rotX:hg(gg(o.x/ug,0)),rot:hg(gg(o.y/ug,0)),rotZ:hg(gg(o.z/ug,0))}}function g_(e){return{width:(e.footprint?.width??1)*(e.scaleX??1),height:(e.height??1)*(e.scaleY??1),depth:(e.footprint?.depth??1)*(e.scaleZ??1)}}var __=1e-4;function v_(e){let t=g_(e),n=(e.rot??0)*ug,r=Math.abs(Math.cos(n)),i=Math.abs(Math.sin(n)),a=(t.width*r+t.depth*i)/2,o=(t.width*i+t.depth*r)/2,s=e.x??0,c=e.z??0,l=e.y??0;return{minX:s-a,maxX:s+a,minZ:c-o,maxZ:c+o,baseY:l,topY:l+t.height}}function y_(e,t,n=[]){let r=v_(e),i=0;for(let e of t){if(e_(e,t,n))continue;let a=v_(e);r.minX>=a.maxX-__||a.minX>=r.maxX-__||r.minZ>=a.maxZ-__||a.minZ>=r.maxZ-__||a.topY>r.baseY+__||a.topY>i&&(i=a.topY)}return i===r.baseY?null:{y:i}}function b_(e,t,n=2.6){let r=e.x-Math.sin(t)*n,i=e.z-Math.cos(t)*n;return{x:gg(Qg.x(r),l_),z:gg(Qg.z(i),l_)}}var x_=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),S_=t(((e,t)=>{t.exports=x_()})),C_=t((e=>{var t=g();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),w_=t(((e,t)=>{t.exports=C_()})),T_=t((e=>{var t=g(),n=w_();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),E_=t(((e,t)=>{t.exports=T_()})),Z=`Hips.Spine.Spine1.Spine2.Spine3.Neck.Head.RightShoulder.RightArm.RightForeArm.RightHand.RightHandEnd.RightHandThumb1.LeftShoulder.LeftArm.LeftForeArm.LeftHand.LeftHandEnd.LeftHandThumb1.RightUpLeg.RightLeg.RightFoot.RightToeBase.LeftUpLeg.LeftLeg.LeftFoot.LeftToeBase`.split(`.`),D_=Object.fromEntries(Z.map((e,t)=>[e,t])),O_={Hips:null,Spine:`Hips`,Spine1:`Spine`,Spine2:`Spine1`,Spine3:`Spine2`,Neck:`Spine3`,Head:`Neck`,RightShoulder:`Spine3`,RightArm:`RightShoulder`,RightForeArm:`RightArm`,RightHand:`RightForeArm`,RightHandEnd:`RightHand`,RightHandThumb1:`RightHand`,LeftShoulder:`Spine3`,LeftArm:`LeftShoulder`,LeftForeArm:`LeftArm`,LeftHand:`LeftForeArm`,LeftHandEnd:`LeftHand`,LeftHandThumb1:`LeftHand`,RightUpLeg:`Hips`,RightLeg:`RightUpLeg`,RightFoot:`RightLeg`,RightToeBase:`RightFoot`,LeftUpLeg:`Hips`,LeftLeg:`LeftUpLeg`,LeftFoot:`LeftLeg`,LeftToeBase:`LeftFoot`},k_=Z.map(e=>O_[e]===null?null:D_[O_[e]]),A_=[`Hips`,`Spine`,`Spine1`,`Neck`,`Head`,`LeftShoulder`,`RightShoulder`,`LeftArm`,`RightArm`,`LeftForeArm`,`RightForeArm`,`LeftHand`,`RightHand`,`LeftUpLeg`,`RightUpLeg`,`LeftLeg`,`RightLeg`,`LeftFoot`,`RightFoot`],j_=Object.fromEntries(A_.map(e=>[e,D_[e===`Spine`?`Spine1`:e===`Spine1`?`Spine2`:e]])),M_=1e-12;function N_(e){return typeof e==`number`&&Number.isFinite(e)}function P_(e,t){if(!Array.isArray(e)||e.length!==4||!e.every(N_))throw Error(`${t} must be a [w, x, y, z] quaternion of four finite numbers`);return e}function F_(e,t){if(!Array.isArray(e)||e.length!==3||!e.every(e=>Array.isArray(e)&&e.length===3&&e.every(N_)))throw Error(`${t} must be a row-major 3x3 matrix of finite numbers`);return e}function I_(e,t){if(!Array.isArray(e)||e.length!==3||!e.every(N_))throw Error(`${t} must be an [x, y, z] vector of three finite numbers`);return e}function L_(e,t){if(!Array.isArray(e)||e.length!==k_.length)throw Error(`${t} must hold ${k_.length} entries (one per cskel27 joint)`);return e.forEach((e,n)=>F_(e,`${t}[${n}]`)),e}function R_(e,t){if(!Array.isArray(e)||e.length!==k_.length)throw Error(`${t} must hold ${k_.length} entries (one per cskel27 joint)`);return e.forEach((e,n)=>I_(e,`${t}[${n}]`)),e}function z_(){let e=new Set,t=[];for(k_.forEach((n,r)=>{n===null&&(e.add(r),t.push(r))}),t.sort((e,t)=>e-t);t.length<k_.length;){let n=!1;for(let r=0;r<k_.length;r+=1)!e.has(r)&&e.has(k_[r])&&(t.push(r),e.add(r),n=!0);if(!n)throw Error(`cskel27 parent table is not a tree`)}return t}var B_=z_();function V_(e,t){return F_(e,`matMul(a, b): a`),F_(t,`matMul(a, b): b`),[[e[0][0]*t[0][0]+e[0][1]*t[1][0]+e[0][2]*t[2][0],e[0][0]*t[0][1]+e[0][1]*t[1][1]+e[0][2]*t[2][1],e[0][0]*t[0][2]+e[0][1]*t[1][2]+e[0][2]*t[2][2]],[e[1][0]*t[0][0]+e[1][1]*t[1][0]+e[1][2]*t[2][0],e[1][0]*t[0][1]+e[1][1]*t[1][1]+e[1][2]*t[2][1],e[1][0]*t[0][2]+e[1][1]*t[1][2]+e[1][2]*t[2][2]],[e[2][0]*t[0][0]+e[2][1]*t[1][0]+e[2][2]*t[2][0],e[2][0]*t[0][1]+e[2][1]*t[1][1]+e[2][2]*t[2][1],e[2][0]*t[0][2]+e[2][1]*t[1][2]+e[2][2]*t[2][2]]]}function H_(e){return F_(e,`matTranspose(m): m`),[[e[0][0],e[1][0],e[2][0]],[e[0][1],e[1][1],e[2][1]],[e[0][2],e[1][2],e[2][2]]]}function U_(e,t){return[e[0][0]*t[0]+e[0][1]*t[1]+e[0][2]*t[2],e[1][0]*t[0]+e[1][1]*t[1]+e[1][2]*t[2],e[2][0]*t[0]+e[2][1]*t[1]+e[2][2]*t[2]]}function W_(e){let[t,n,r,i]=P_(e,`quatToMat(q): q`),a=t*t+n*n+r*r+i*i;if(!Number.isFinite(a)||a<=M_)throw Error(`quatToMat(q): quaternion is zero-length and cannot represent a rotation`);let o=1/Math.sqrt(a),s=t*o,c=n*o,l=r*o,u=i*o;return[[1-2*(l*l+u*u),2*(c*l-s*u),2*(c*u+s*l)],[2*(c*l+s*u),1-2*(c*c+u*u),2*(l*u-s*c)],[2*(c*u-s*l),2*(l*u+s*c),1-2*(c*c+l*l)]]}function G_(e){F_(e,`matToQuat(m): m`);let t,n=e[0][0]+e[1][1]+e[2][2];if(n>0){let r=Math.sqrt(n+1)*2;t=[.25*r,(e[2][1]-e[1][2])/r,(e[0][2]-e[2][0])/r,(e[1][0]-e[0][1])/r]}else if(e[0][0]>e[1][1]&&e[0][0]>e[2][2]){let n=Math.sqrt(1+e[0][0]-e[1][1]-e[2][2])*2;t=[(e[2][1]-e[1][2])/n,.25*n,(e[0][1]+e[1][0])/n,(e[0][2]+e[2][0])/n]}else if(e[1][1]>e[2][2]){let n=Math.sqrt(1+e[1][1]-e[0][0]-e[2][2])*2;t=[(e[0][2]-e[2][0])/n,(e[0][1]+e[1][0])/n,.25*n,(e[1][2]+e[2][1])/n]}else{let n=Math.sqrt(1+e[2][2]-e[0][0]-e[1][1])*2;t=[(e[1][0]-e[0][1])/n,(e[0][2]+e[2][0])/n,(e[1][2]+e[2][1])/n,.25*n]}let r=t.reduce((e,t)=>e+t*t,0);if(!Number.isFinite(r)||r<=M_)throw Error(`matToQuat(m): matrix is degenerate and cannot represent a rotation`);let i=1/Math.sqrt(r),a=t.map(e=>e*i);if(!a.every(N_))throw Error(`matToQuat(m): matrix is degenerate and cannot represent a rotation`);return a}function K_(e){let t=L_(e,`globalRotations(localRotations)`),n=Array(k_.length);for(let e of B_){let r=k_[e];n[e]=r===null?t[e].map(e=>e.slice()):V_(n[r],t[e])}return n}function q_(e,t){let n=R_(e,`deriveBoneOffsets(jointPositions, ...)`),r=K_(t),i=Array(k_.length);for(let e=0;e<i.length;e+=1)i[e]=[0,0,0];for(let e of B_){let t=k_[e];if(t===null)continue;let a=[n[e][0]-n[t][0],n[e][1]-n[t][1],n[e][2]-n[t][2]];i[e]=U_(H_(r[t]),a)}return i}function J_(e,t,n=[0,0,0]){let r=K_(e);R_(t,`forwardKinematics(...): boneOffsets`);let i=I_(n,`forwardKinematics(...): rootPosition`),a=Array(k_.length);for(let e of B_){let n=k_[e];if(n===null){a[e]=i.slice();continue}let o=U_(r[n],t[e]);a[e]=[a[n][0]+o[0],a[n][1]+o[1],a[n][2]+o[2]]}return a}var Y_=[[0,0,0],[0,.0709891,-.0473261],[0,.1642033,-.0637623],[0,.2584953,-.0720118],[0,.3531475,-.0720119],[0,.6016096,-.0365176],[0,.7297793,-.0139179],[-.0319949,.5259196,-.0186873],[-.1909029,.5259195,-.0186873],[-.4863389,.5259194,-.0186873],[-.7189909,.5259193,-.0186873],[-.7886024,.5259193,-.0186873],[-.7468355,.5073563,.0277204],[.0319949,.5259196,-.0186873],[.1909029,.5259196,-.0186873],[.4863389,.5259196,-.0186873],[.7189909,.5259196,-.0186873],[.7886024,.5259196,-.0186873],[.7468355,.5073565,.0277204],[-.0949182,-.0277289,0],[-.0949182,-.4398469,0],[-.0949182,-.8959379,0],[-.0949182,-.9544128,.1606583],[.0949182,-.0277289,0],[.0949182,-.4398469,0],[.0949182,-.8959379,0],[.0949182,-.9544128,.1606583]],X_=[[1,0,0],[0,1,0],[0,0,1]];new Map(A_.map(e=>[Z[j_[e]],e]));var Z_=-Math.min(...Y_.map(e=>e[1]));function Q_(){return{local_rot_mats:Z.map(()=>X_.map(e=>e.slice())),posed_joints:Y_.map(([e,t,n])=>[e,t+Z_,n])}}function $_(e,t,n){let r=e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],i=r<0?-1:1;r*=i;let a,o;if(r>.9995)a=1-n,o=n;else{let e=Math.acos(Math.min(1,r)),t=Math.sin(e);a=Math.sin((1-n)*e)/t,o=Math.sin(n*e)/t}let s=[e[0]*a+t[0]*i*o,e[1]*a+t[1]*i*o,e[2]*a+t[2]*i*o,e[3]*a+t[3]*i*o],c=Math.hypot(...s);return s.map(e=>e/c)}function ev(e,t){return[[e[t],e[t+1],e[t+2]],[e[t+3],e[t+4],e[t+5]],[e[t+6],e[t+7],e[t+8]]]}function tv(e,t,n){e[t]=n[0][0],e[t+1]=n[0][1],e[t+2]=n[0][2],e[t+3]=n[1][0],e[t+4]=n[1][1],e[t+5]=n[1][2],e[t+6]=n[2][0],e[t+7]=n[2][1],e[t+8]=n[2][2]}var nv=Z.length,rv=(()=>{let e=Q_();return q_(e.posed_joints,e.local_rot_mats)})(),iv=1e-4;function av(e,t){let n=Array(nv);for(let r=0;r<nv;r+=1)n[r]=ev(e,(t*nv+r)*9);return n}function ov(e){let t=Math.max(1,Math.floor(e.frames/16));for(let n=0;n<e.frames;n+=t){let t=J_(av(e.rotMats,n),rv,[e.rootPos[n*3],e.rootPos[n*3+1],e.rootPos[n*3+2]]);for(let r=0;r<nv;r+=1){let i=(n*nv+r)*3,a=t[r][0]-e.posedJoints[i],o=t[r][1]-e.posedJoints[i+1],s=t[r][2]-e.posedJoints[i+2];if(Math.hypot(a,o,s)>iv)return!1}}return!0}function sv(e,t){if(!e||!Number.isFinite(e.fps)||e.fps<=0)throw Error(`retimeMotion: motion.fps must be a positive finite number`);if(!Number.isFinite(t)||t<=0)throw Error(`retimeMotion: targetFps must be a positive finite number`);if(e.fps===t)return e;let n=e.frames;if(!Number.isInteger(n)||n<1)throw Error(`retimeMotion: motion.frames must be a positive integer`);let r=t/e.fps,i=Math.max(1,Math.round(n*r)),a=new Float32Array(i*nv*9),o=new Float32Array(i*3),s=new Float32Array(i*nv*3),c=ov(e);for(let t=0;t<i;t+=1){let i=t/r,l=Math.min(Math.floor(i),n-1),u=Math.min(l+1,n-1),d=Math.min(Math.max(i-l,0),1),f=d===0||l===u;for(let n=0;n<nv;n+=1){let r=(l*nv+n)*9,i=(t*nv+n)*9;if(f)for(let t=0;t<9;t+=1)a[i+t]=e.rotMats[r+t];else{let t=(u*nv+n)*9;tv(a,i,W_($_(G_(ev(e.rotMats,r)),G_(ev(e.rotMats,t)),d)))}}for(let n=0;n<3;n+=1)o[t*3+n]=e.rootPos[l*3+n]*(1-d)+e.rootPos[u*3+n]*d;if(c){let e=J_(av(a,t),rv,[o[t*3],o[t*3+1],o[t*3+2]]);for(let n=0;n<nv;n+=1){let r=(t*nv+n)*3;s[r]=e[n][0],s[r+1]=e[n][1],s[r+2]=e[n][2]}}else for(let n=0;n<nv;n+=1){let r=(l*nv+n)*3,i=(u*nv+n)*3,a=(t*nv+n)*3;for(let t=0;t<3;t+=1)s[a+t]=e.posedJoints[r+t]*(1-d)+e.posedJoints[i+t]*d}}let l={...e,frames:i,fps:t,rotMats:a,rootPos:o,posedJoints:s};return Number.isFinite(e.anchorFrame)&&(l.anchorFrame=Math.min(i-1,Math.round(e.anchorFrame*r))),l}var cv=Z.map(e=>{switch(e){case`Spine`:case`RightHandEnd`:case`LeftHandEnd`:case`RightHand`:case`LeftHand`:case`RightHandThumb1`:case`LeftHandThumb1`:return null;case`Spine1`:return`Spine`;case`Spine2`:return`Spine1`;case`Spine3`:return`Spine2`;default:return e}}),lv=new Set([`RightShoulder`,`RightArm`,`RightForeArm`,`LeftShoulder`,`LeftArm`,`LeftForeArm`]),uv=-.9544128;function dv(e,t){let n=ep(t),r=null;return e.traverse(e=>{if(r||!e.isBone)return;let t=ep(e.name);(t===n||t.endsWith(n))&&(r=e)}),r}var fv=new WeakMap;function pv(e){let t=e.userData&&e.userData.poseBind;if(t)return t;let n=fv.get(e);return n||(n=new Map,e.traverse(e=>{if(e.isBone){let t=e.quaternion;n.set(e,{x:t.x,y:t.y,z:t.z,w:t.w})}}),fv.set(e,n)),n}var mv=new WeakMap;function hv(e){let t=mv.get(e);if(t)return t;let n=pv(e),r=new Map,i=e=>{let t=e.isBone?n.get(e):null;return t?.position?new B(t.position.x,t.position.y,t.position.z):e.position},a=(e,t)=>{let o=e.isBone?n.get(e):null,s=o?new z(o.x,o.y,o.z,o.w):e.quaternion,c=new V().compose(i(e),s,e.scale),l=t.clone().multiply(c);r.set(e,l);for(let t of e.children)a(t,l)};for(let t of e.children)a(t,new V);let o=Array(Z.length).fill(null),s=Array(Z.length).fill(null),c=Array(Z.length).fill(null),l=Array(Z.length).fill(null),u=Array(Z.length).fill(null),d=Array(Z.length).fill(null);for(let t=0;t<Z.length;t+=1){let n=cv[t];if(!n)continue;let a=dv(e,n);if(!a)continue;let f=r.get(a);o[t]=a,s[t]=new B().setFromMatrixPosition(f),c[t]=new z().setFromRotationMatrix(f),l[t]=a.scale.clone(),u[t]=i(a).clone(),d[t]=r.get(a.parent)??new V}let f=Z.indexOf(`Hips`),p=s[f]?s[f].y:0,m=p;for(let e=0;e<s.length;e+=1)s[e]&&s[e].y<m&&(m=s[e].y);let h=p-m,g=h>1e-6?h/.9544128:1,_=Array(Z.length).fill(null);for(let e=0;e<Z.length;e+=1){if(!o[e])continue;let t=Y_[e];_[e]=new B(s[e].x-g*t[0],s[e].y-g*(t[1]-uv),s[e].z-g*t[2])}let v=new Map;for(let e=0;e<o.length;e+=1)o[e]&&v.set(o[e],e);let y=Array(Z.length).fill(-1),b=Array(Z.length).fill(null);for(let t=0;t<o.length;t+=1){let n=o[t];if(n){for(let i=n.parent;i&&i!==e;i=i.parent)if(i.isBone&&v.has(i)){y[t]=v.get(i),b[t]=new V().copy(r.get(i)).invert().multiply(r.get(n.parent));break}}}let x=[];for(let t of[`LeftHand`,`RightHand`]){let a=dv(e,t);if(a){let e=n.get(a);x.push({bone:a,joint:Z.indexOf(t),bindLocalPos:i(a).clone(),bindWorldQuat:new z().setFromRotationMatrix(r.get(a)),parentBindQuat:new z().setFromRotationMatrix(r.get(a.parent)),bindLocalQuat:e?new z(e.x,e.y,e.z,e.w):a.quaternion.clone()})}}let S=Array(Z.length).fill(0),C=Array(Z.length).fill(0);for(let e=1;e<Z.length;e+=1){let t=k_[e],n=Y_[e],r=Y_[t];S[e]=g*Math.hypot(n[0]-r[0],n[1]-r[1],n[2]-r[2]);let a=o[e]??x.find(t=>t.joint===e)?.bone;a&&(C[e]=i(a).length())}return t={bones:o,bindPos:s,stretchedLeaves:x,canonicalBoneLength:S,rigBoneLength:C,bindQuat:c,bindScale:l,bindLocalPos:u,parentBindWorld:d,chainParent:y,chainRel:b,scale:g,offsets:_},mv.set(e,t),t}function gv(e){let t=hv(e);if(!t)throw Error(`captureArdyRoot: rig is not prepared for ARDY playback`);let n=Z.indexOf(`Hips`),r=t.bones[n];if(!r)throw Error(`captureArdyRoot: mapped Hips bone is unavailable`);e.updateMatrixWorld(!0);let i=new V().copy(e.matrixWorld).invert(),a=new V().multiplyMatrices(i,r.matrixWorld),o=new B,s=new z;a.decompose(o,s,new B);let c=s.multiply(t.bindQuat[n].clone().invert()).normalize(),l=t.offsets[n].clone().applyQuaternion(c),u=t.lastScale??t.scale;return[(o.x-l.x)/u,(o.y-l.y)/u,(o.z-l.z)/u]}var _v=new WeakMap;function vv(e,t){let n=_v.get(t);if(n&&n.prep===e)return n.offsets;let r=Array(Z.length);for(let e=0;e<Z.length;e+=1){let n=k_[e],i=Y_[e];if(n===null){r[e]=[i[0],i[1],i[2]];continue}let a=Y_[n],o=r[n];r[e]=[o[0]+t[e]*(i[0]-a[0]),o[1]+t[e]*(i[1]-a[1]),o[2]+t[e]*(i[2]-a[2])]}let i=Array(Z.length).fill(null);for(let t=0;t<Z.length;t+=1){if(!e.bones[t])continue;let n=r[t];i[t]=new B(e.bindPos[t].x-e.scale*n[0],e.bindPos[t].y-e.scale*(n[1]-uv),e.bindPos[t].z-e.scale*n[2])}return _v.set(t,{prep:e,offsets:i}),i}function yv(e,t,n){if(!t.boneScale)return 1;if(bv.has(Z[n]))return t.boneScale[n];let r=e.canonicalBoneLength[n],i=e.rigBoneLength[n];return!(r>1e-6)||!(i>1e-6)?t.boneScale[n]:t.boneScale[n]*r/i}var bv=new Set([`LeftShoulder`,`RightShoulder`,`LeftArm`,`RightArm`]),xv=Array(Z.length);for(let e=0;e<xv.length;e+=1)xv[e]=[[0,0,0],[0,0,0],[0,0,0]];var Sv=new Gn,Cv=new V,wv=new V,Tv=new V,Ev=new z,Dv=new z,Ov=new B,kv=new B,Av=new B,jv=new z,Mv=new B,Nv=Array(Z.length).fill(null);function Pv(e,t){for(let n=0;n<xv.length;n+=1){let r=(t*xv.length+n)*9,i=xv[n];for(let t=0;t<3;t+=1)for(let n=0;n<3;n+=1)i[t][n]=e.rotMats[r+t*3+n]}return K_(xv)}function Fv(e,t=new z){return Sv.set(...e[0],...e[1],...e[2]),t.setFromRotationMatrix(Cv.setFromMatrix3(Sv))}function Iv(e,{base:t,chains:n},r){let i=Pv(t,r),a=t.boneScale?vv(e,t.boneScale):e.offsets,o=Math.max(0,Math.min(t.anchorFrame||0,t.frames-1))*27*3,s=new Map,c=new Map,l=new Map,u=n=>{if(!s.has(n)){let c=Fv(i[n]),l=new B().fromArray(t.posedJoints,(r*27+n)*3);l.x-=t.posedJoints[o],l.z-=t.posedJoints[o+2],l.multiplyScalar(e.scale).add(a[n].clone().applyQuaternion(c)),s.set(n,new V().compose(l,c.multiply(e.bindQuat[n]),e.bindScale[n]))}return s.get(n)};for(let t of n){let n=t.startsWith(`left`)?`Left`:`Right`;if(t.endsWith(`Hand`)){let t=e.stretchedLeaves.find(e=>Z[e.joint]===`${n}Hand`);t&&l.set(t.bone,Fv(i[k_[t.joint]]).multiply(t.bindWorldQuat))}else for(let t of[`UpLeg`,`Leg`,`Foot`,`ToeBase`]){let r=Z.indexOf(n+t),i=e.bones[r];if(!i)continue;let a=e.chainParent[r],o=a<0?e.parentBindWorld[r].clone():u(a).clone().multiply(e.chainRel[r]);c.set(i,new B().setFromMatrixPosition(u(r)).applyMatrix4(o.invert()))}}return{positions:c,wrists:l}}function Lv(e,t,n){if(!e||!t)return;let r=Math.max(0,Math.min(Math.round(n)||0,t.frames-1)),i=hv(e),a=Z.length,o=t.trailRetarget?Iv(i,t.trailRetarget,r):null,s=Pv(t,r),c=Math.max(0,Math.min(t.anchorFrame||0,t.frames-1)),l=t.posedJoints[c*a*3],u=t.posedJoints[c*a*3+2],d=i.scale;i.lastScale=d;let f=t.boneScale?vv(i,t.boneScale):i.offsets;for(let e=0;e<a;e+=1){let n=i.bones[e];if(Nv[e]=null,!n)continue;let c=s[e];Sv.set(c[0][0],c[0][1],c[0][2],c[1][0],c[1][1],c[1][2],c[2][0],c[2][1],c[2][2]),Ev.setFromRotationMatrix(Cv.setFromMatrix3(Sv));let p=(r*a+e)*3;Ov.copy(f[e]).applyQuaternion(Ev),kv.set(d*(t.posedJoints[p]-l)+Ov.x,d*t.posedJoints[p+1]+Ov.y,d*(t.posedJoints[p+2]-u)+Ov.z),Dv.copy(Ev).multiply(i.bindQuat[e]);let m=i.chainParent[e];m>=0?Tv.copy(Nv[m]).multiply(i.chainRel[e]):Tv.copy(i.parentBindWorld[e]),o?.positions.has(n)?kv.copy(o.positions.get(n)).applyMatrix4(Tv):lv.has(Z[e])&&kv.copy(i.bindLocalPos[e]).multiplyScalar(yv(i,t,e)).applyMatrix4(Tv),Cv.compose(kv,Dv,i.bindScale[e]),Nv[e]=Cv.clone(),wv.copy(Tv).invert().multiply(Cv),wv.decompose(Av,jv,Mv),n.position.copy(Av),n.quaternion.copy(jv)}for(let e of i.stretchedLeaves){e.bone.position.copy(e.bindLocalPos).multiplyScalar(yv(i,t,e.joint));let n=o?.wrists.get(e.bone);n?(Fv(s[k_[e.joint]],Ev).multiply(e.parentBindQuat),e.bone.quaternion.copy(Ev.invert().multiply(n))):e.bone.quaternion.copy(e.bindLocalQuat)}e.updateMatrixWorld(!0)}var Rv=new WeakMap;function zv(e){let t=Rv.get(e);if(t)return t;let n=e.userData?.poseBind??fv.get(e)??new Map,r=new Map,i=e=>e.isBone||e.children.some(i),a=e=>{let t=e.isBone?new io:new Br;t.name=e.name,t.position.copy(e.position),t.quaternion.copy(e.quaternion),t.scale.copy(e.scale);let o=e.isBone?n.get(e):null,s=e.quaternion;e.isBone&&r.set(t,o??{x:s.x,y:s.y,z:s.z,w:s.w});for(let n of e.children)i(n)&&t.add(a(n));return t};t=new Br;for(let n of e.children)i(n)&&t.add(a(n));return t.userData.poseBind=r,Rv.set(e,t),t}var Bv=new WeakMap;function Vv(e,t,n,r,i){let a=zv(e),o=hv(a);o.driven||=Z.map((e,t)=>o.bones[t]??o.stretchedLeaves.find(e=>e.joint===t)?.bone??null),Lv(a,t,n);for(let e=0;e<o.driven.length;e+=1){let t=o.driven[e],n=i+e*3;if(!t){r[n]=r[n+1]=r[n+2]=NaN;continue}let a=t.matrixWorld.elements;r[n]=a[12],r[n+1]=a[13],r[n+2]=a[14]}}function Hv(e,t,n){if(!e||!t?.rotMats||!(t.frames>0))return null;let r=new Float32Array(Z.length*3);return Vv(e,t,Math.max(0,Math.min(Math.round(n)||0,t.frames-1)),r,0),r}function Uv(e,t){if(!e||!t?.rotMats||!(t.frames>0))return null;let n=Bv.get(t);n||(n=new WeakMap,Bv.set(t,n));let r=n.get(e);if(r)return r;let i=Z.length,a=new Float32Array(t.frames*i*3);for(let n=0;n<t.frames;n+=1)Vv(e,t,n,a,n*i*3);let o={positions:a};return n.set(e,o),o}function Wv(e){let t=[],n=hv(e);for(let e of[...n.bones,...n.stretchedLeaves.map(e=>e.bone)])e&&t.push([e,e.quaternion.x,e.quaternion.y,e.quaternion.z,e.quaternion.w,e.position.x,e.position.y,e.position.z]);return t}function Gv(e,t){if(!(!e||!t)){for(let e of t)e[0].quaternion.set(e[1],e[2],e[3],e[4]),e.length>5&&e[0].position.set(e[5],e[6],e[7]);e.updateMatrixWorld(!0)}}function Kv(e,t,n){if(!e||!Number.isInteger(e.frames)||e.frames<1)throw Error(`sliceMotion: motion.frames must be a positive integer`);if(!Number.isInteger(t)||!Number.isInteger(n))throw Error(`sliceMotion: startFrame and endFrame must be integers`);if(t<0||n>=e.frames||t>n)throw Error(`sliceMotion: range ${t}..${n} is outside 0..${e.frames-1}`);let r=Z.length,i=n-t+1;return{...e,frames:i,rotMats:e.rotMats.slice(t*r*9,(n+1)*r*9),rootPos:e.rootPos.slice(t*3,(n+1)*3),posedJoints:e.posedJoints.slice(t*r*3,(n+1)*r*3),anchorFrame:0}}var qv=.1,Jv=4,Yv=.1,Xv=e=>Math.round(Number(e)/Yv)*Yv,Zv=e=>e.sourceEnd-e.sourceStart+1,Qv=e=>Math.max(1,Math.round(Zv(e)/e.speed));function $v(e){if(!Number.isInteger(e)||e<1)throw Error(`createMotionEdit: frames must be a positive integer`);return[{id:`motion-0`,sourceStart:0,sourceEnd:e-1,speed:1}]}function ey(e){return!Array.isArray(e)||e.length<1?0:e.reduce((e,t)=>e+Qv(t),0)}function ty(e){let t=0;return e.map(e=>{let n=Qv(e),r={...e,timelineStart:t,timelineEnd:t+n-1,timelineFrames:n};return t+=n,r})}function ny(e,t){let n=ty(e);if(n.length<1)return Math.max(0,Math.round(t)||0);let r=Math.max(0,Math.min(Number.isFinite(t)?t:0,n.at(-1).timelineEnd)),i=n.find(e=>r<=e.timelineEnd)??n.at(-1);if(i.timelineFrames<=1)return i.sourceStart;let a=(r-i.timelineStart)/(i.timelineFrames-1);return i.sourceStart+a*(i.sourceEnd-i.sourceStart)}function ry(e,t){if(!Array.isArray(e)||e.length<1||!Number.isFinite(t))return null;let n=ty(e).find(e=>t>=e.sourceStart&&t<=e.sourceEnd);if(!n)return null;if(n.sourceEnd===n.sourceStart)return n.timelineStart;let r=(t-n.sourceStart)/(n.sourceEnd-n.sourceStart);return Math.round(n.timelineStart+r*(n.timelineFrames-1))}function iy(e,t,n){return ry(t,ny(e,n))}function ay(e,t,n){let r=new Map;for(let i of[...e.keys()].sort((e,t)=>e-t)){let a=iy(t,n,i);a===null||r.has(a)||r.set(a,e.get(i))}return r}function oy(e,t){if(!Array.isArray(e)||e.length<1)return e;let n=ty(e),r=Math.round(t);if(r<=0||r>=ey(e))return e;let i=n.findIndex(e=>r>e.timelineStart&&r<=e.timelineEnd);if(i<0)return e;let a=n[i],o=Math.max(a.sourceStart+1,Math.min(a.sourceEnd,Math.round(ny(e,r))));if(o<=a.sourceStart||o>a.sourceEnd)return e;let s=[...e];return s.splice(i,1,{id:`${a.id}-a`,sourceStart:a.sourceStart,sourceEnd:o-1,speed:a.speed},{id:`${a.id}-b`,sourceStart:o,sourceEnd:a.sourceEnd,speed:a.speed}),s}function sy(e,t,n){let r=Xv(n);if(!Number.isFinite(r)||r<qv||r>Jv)throw Error(`setMotionSegmentSpeed: speed must be between 0.1 and 4.0 in 0.1 steps`);return e.map(e=>e.id===t?{...e,speed:Number(r.toFixed(1))}:e)}function cy(e,t){if(!Array.isArray(e)||e.length<2)return e;let n=e.filter(e=>e.id!==t);return n.length===e.length?e:n}function ly(e,t){let n=Math.max(1,Math.round(Number(t)||1)),r=Zv(e)/n;return Number(Xv(Math.min(Jv,Math.max(qv,r))).toFixed(1))}function uy(e,t,n){if(!Array.isArray(e)||e.length<1)return e;let r=ey(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n>=r||t>n)throw Error(`trimMotionEdit: range ${t}..${n} is outside 0..${r-1}`);return ty(e).flatMap(r=>{let i=Math.max(t,r.timelineStart),a=Math.min(n,r.timelineEnd);if(i>a)return[];let o=Math.ceil(ny(e,i)),s=Math.floor(ny(e,a));return[{id:`${r.id}-trim-${o}`,sourceStart:Math.max(r.sourceStart,o),sourceEnd:Math.min(r.sourceEnd,s),speed:r.speed}]}).filter(e=>e.sourceStart<=e.sourceEnd)}function dy(e,t,n,r,i){let a=t*i;n.set(e.subarray(a,a+i),r*i)}function fy(e,t){if(!e||!Number.isInteger(e.frames)||e.frames<1||!Number.isFinite(e.fps)||e.fps<=0)throw Error(`renderMotionEdit: motion must have positive frames and fps`);let n=Array.isArray(t)&&t.length?t:$v(e.frames),r=n.map(t=>{let n=Kv(e,t.sourceStart,t.sourceEnd);return t.speed===1?n:sv(n,e.fps/t.speed)}),i=r.reduce((e,t)=>e+t.frames,0),a=e.rotMats.length/e.frames,o=e.rootPos.length/e.frames,s=e.posedJoints.length/e.frames,c=new Float32Array(i*a),l=new Float32Array(i*o),u=new Float32Array(i*s),d=0;for(let t=0;t<r.length;t+=1){let i=r[t],f=n[t];for(let t=0;t<i.frames;t+=1){let n=t===i.frames-1&&f.speed>1,r=n?e:i,p=n?f.sourceEnd:t;dy(r.rotMats,p,c,d+t,a),dy(r.rootPos,p,l,d+t,o),dy(r.posedJoints,p,u,d+t,s)}d+=i.frames}return{...e,frames:i,fps:e.fps,rotMats:c,rootPos:l,posedJoints:u,anchorFrame:0,editSegments:n.map(e=>({...e}))}}var py=.01,my=Z.length,hy=e=>Z.indexOf(e),gy={leftHand:[`LeftArm`,`LeftForeArm`,`LeftHand`],rightHand:[`RightArm`,`RightForeArm`,`RightHand`],leftFoot:[`LeftUpLeg`,`LeftLeg`,`LeftFoot`],rightFoot:[`RightUpLeg`,`RightLeg`,`RightFoot`]},_y=[{id:`leftHand`,joint:`LeftHand`,color:`#ff8a3d`},{id:`rightHand`,joint:`RightHand`,color:`#ff8a3d`},{id:`leftFoot`,joint:`LeftFoot`,color:`#4dd2ff`},{id:`rightFoot`,joint:`RightFoot`,color:`#4dd2ff`},{id:`head`,joint:`Head`,color:`#b98cff`},{id:`hips`,joint:`Hips`,color:`#ffd23d`}],vy={hips:`Hips`,spine:`Spine1`,chest:`Spine2`,neck:`Neck`,head:`Head`,leftShoulder:`LeftArm`,leftElbow:`LeftForeArm`,leftHand:`LeftHand`,rightShoulder:`RightArm`,rightElbow:`RightForeArm`,rightHand:`RightHand`,leftKnee:`LeftLeg`,leftFoot:`LeftFoot`,rightKnee:`RightLeg`,rightFoot:`RightFoot`};function yy(e){let t=e?.frames??0,n=Math.max(0,Math.min(e?.anchorFrame||0,Math.max(0,t-1))),r=(Number.isFinite(e?.rotationDeg)?e.rotationDeg:0)*Math.PI/180;return{anchorFrame:n,cos:Math.cos(r),sin:Math.sin(r),anchorX:Number.isFinite(e?.anchorX)?e.anchorX:0,anchorZ:Number.isFinite(e?.anchorZ)?e.anchorZ:0,rootX:e?.posedJoints?.[n*my*3]??e?.rootPos?.[n*3]??0,rootZ:e?.posedJoints?.[n*my*3+2]??e?.rootPos?.[n*3+2]??0}}function by(e,t,n){let r=t-e.rootX,i=n-e.rootZ;return[e.anchorX+r*e.cos+i*e.sin,e.anchorZ+-r*e.sin+i*e.cos]}function xy(e,t,n){if(!n)return null;let r=Uv(n,e);return r&&Number.isFinite(r.positions[t*3])?r:null}function Sy(e,t=`Hips`,{baseY:n=0,scale:r=1,rig:i=null}={}){if(!e?.posedJoints||!(e.frames>0))return null;let a=Z.indexOf(t);if(a<0)return null;let o=yy(e),s=new Float32Array(e.frames*3),c=xy(e,a,i);if(c){let t=py*r;for(let r=0;r<e.frames;r+=1){let e=(r*my+a)*3,i=c.positions[e]*t,l=c.positions[e+2]*t;s[r*3]=o.anchorX+i*o.cos+l*o.sin,s[r*3+1]=n+c.positions[e+1]*t,s[r*3+2]=o.anchorZ-i*o.sin+l*o.cos}return s}for(let t=0;t<e.frames;t+=1){let i=(t*my+a)*3,[c,l]=by(o,e.posedJoints[i],e.posedJoints[i+2]);s[t*3]=o.anchorX+(c-o.anchorX)*r,s[t*3+1]=n+e.posedJoints[i+1]*r,s[t*3+2]=o.anchorZ+(l-o.anchorZ)*r}return s}function Cy(e,t,{baseY:n=0,scale:r=1}={}){let i=yy(e),a=Number.isFinite(r)&&Math.abs(r)>1e-9?r:1,o=(t.x-i.anchorX)/a,s=(t.z-i.anchorZ)/a,c=o*i.cos-s*i.sin,l=o*i.sin+s*i.cos;return{x:i.rootX+c,y:(t.y-n)/a,z:i.rootZ+l}}function wy(e,t){let{cos:n,sin:r}=yy(e);return{x:t.x*n-t.z*r,y:t.y,z:t.x*r+t.z*n}}function Ty(e,t,{track:n=`hips`,grabFrame:r=0,radiusFrames:i=0,rig:a=null,scale:o=1}={}){let s=Number.isFinite(o)&&o>1e-9?o:1,c=wy(e,{x:t.x/s,y:t.y/s,z:t.z/s}),l=Math.hypot(t.x,t.y,t.z),u=hy(_y.find(e=>e.id===n)?.joint??``),d=a&&u>=0&&e?.rotMats&&l>1e-6?Uv(a,e):null,f=Math.max(0,Math.min((e?.frames??1)-1,Math.round(r)||0)),p=d?.positions.subarray((f*my+u)*3,(f*my+u)*3+3);if(!p||!Number.isFinite(p[0]))return c;let m=yy(e),h=py*s,g=[t.x,t.y,t.z],_=e=>({x:c.x*e,y:c.y*e,z:c.z*e}),v=t=>{let r=Hv(a,Xy(e,{track:n,grabFrame:f,radiusFrames:i,clipDelta:_(t)}),f).subarray(u*3,u*3+3),o=(r[0]-p[0])*h,s=(r[2]-p[2])*h;return[o*m.cos+s*m.sin,(r[1]-p[1])*h,-o*m.sin+s*m.cos]},y=1,b={gain:1,miss:1/0};for(let e=0;e<4;e+=1){let e=v(y),t=Ny(Oy(g,e));t<b.miss&&(b={gain:y,miss:t});let n=jy(e,e);if(!(n>1e-12)||t<1e-4)break;let r=Math.max(.1,Math.min(1.5,y*jy(g,e)/n));if(Math.abs(r-y)<1e-4)break;y=r}return _(b.gain)}function Ey(e,t){if(!(t>0))return+(e===0);let n=1-Math.min(1,Math.abs(e)/t);return n*n*(3-2*n)}function Dy(e,t,n){let r=Math.max(0,e-1),i=Math.max(0,Math.min(r,Math.round(t)||0)),a=Math.max(0,Math.round(n)||0);return{startFrame:Math.max(0,i-a),endFrame:Math.min(e,i+a+1)}}var Oy=(e,t)=>[e[0]-t[0],e[1]-t[1],e[2]-t[2]],ky=(e,t)=>[e[0]+t[0],e[1]+t[1],e[2]+t[2]],Ay=(e,t)=>[e[0]*t,e[1]*t,e[2]*t],jy=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],My=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],Ny=e=>Math.hypot(e[0],e[1],e[2]);function Py(e){let t=Ny(e);return t>1e-9?Ay(e,1/t):null}function Fy(e,t){let n=Array(9);for(let r=0;r<3;r+=1)for(let i=0;i<3;i+=1)n[r*3+i]=e[r*3]*t[i]+e[r*3+1]*t[3+i]+e[r*3+2]*t[6+i];return n}var Iy=e=>[e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]],Ly=(e,t)=>[e[0]*t[0]+e[1]*t[1]+e[2]*t[2],e[3]*t[0]+e[4]*t[1]+e[5]*t[2],e[6]*t[0]+e[7]*t[1]+e[8]*t[2]];function Ry(e,t){let n=jy(e,t);if(n<-1+1e-9){let[t,n,r]=Py(My(e,Math.abs(e[0])<.9?[1,0,0]:[0,1,0]));return[2*t*t-1,2*t*n,2*t*r,2*t*n,2*n*n-1,2*n*r,2*t*r,2*n*r,2*r*r-1]}let[r,i,a]=My(e,t),o=1/(1+n);return[1-o*(i*i+a*a),-a+o*r*i,i+o*r*a,a+o*r*i,1-o*(r*r+a*a),-r+o*i*a,-i+o*r*a,r+o*i*a,1-o*(r*r+i*i)]}function zy(e){return Z.map((e,t)=>t).filter(t=>{for(let n=t;n!==null;n=k_[n])if(n===e)return!0;return!1})}function By(e,t,n){let r=new Map,i=e=>Array.from(t.subarray((n*my+e)*9,(n*my+e)*9+9)),a=e=>{if(!r.has(e)){let t=k_[e];r.set(e,t===null?i(e):Fy(a(t),i(e)))}return r.get(e)};return{pos:t=>{let r=(n*my+t)*3;return[e[r],e[r+1],e[r+2]]},setPos:(t,r)=>e.set(r,(n*my+t)*3),global:a,setGlobal:(e,r,i=k_[e]===null?null:a(k_[e]))=>{t.set(i?Fy(Iy(i),r):r,(n*my+e)*9)}}}function Vy(e,[t,n,r],i,a,o,s){let c=[0,0,0];for(let l=i;l<a;l+=1){let i=By(e.posedJoints,null,l),a=My(Oy(i.pos(n),i.pos(t)),Oy(i.pos(r),i.pos(t)));c=ky(c,Ay(a,Ey(l-o,s)))}return Py(c)}var Hy=Math.PI/6,Uy=.25;function Wy(e,t,n){if(Math.acos(Math.max(-1,Math.min(1,jy(e,t))))<=n)return t;let r=Py(Oy(t,Ay(e,jy(e,t))));return r?ky(Ay(e,Math.cos(n)),Ay(r,Math.sin(n))):e}function Gy(e,[t,n,r],i,a,o){let s=e.pos(t),c=e.pos(n),l=e.pos(r),u=Ny(Oy(c,s)),d=Ny(Oy(l,c));if(Ny(a)<1e-9)return;let f=Oy(c,s),p=Oy(l,s),m=Py(My(f,p)),h=Oy(ky(l,a),s),g=Py(h)??Py(p);if(!g)return;let _=o??m??Py(My(g,Math.abs(g[0])<.9?[1,0,0]:[0,1,0])),v=Py(Oy(_,Ay(g,jy(_,g))))??Py(My(g,Math.abs(g[0])<.9?[1,0,0]:[0,1,0])),y=(Ny(h)-(u+d))/((u+d)*Uy),b=m?Math.acos(Math.max(-1,Math.min(1,jy(m,v)))):0;if(y>0&&b>Hy){let e=Math.min(1,y),t=Wy(m,v,b-(b-Hy)*e*e*(3-2*e)),n=Oy(h,Ay(t,jy(h,t)));Py(n)&&(v=t,h=n,g=Py(n))}let x=Math.min(u+d-1e-6,Math.max(Math.abs(u-d)+1e-6,Ny(h)));if(!(x>1e-9))return;let S=(u*u-d*d+x*x)/(2*x),C=Math.sqrt(Math.max(0,u*u-S*S)),w=Py(My(g,v)),T=ky(s,ky(Ay(g,S),Ay(w,C))),E=ky(s,Ay(g,x)),D=Oy(E,l);for(let t of i)e.setPos(t,ky(e.pos(t),D));if(e.setPos(n,T),!e.rotMats)return;let O=(e,t)=>Ry(Py(e),Py(t)),ee=Fy(O(f,Oy(T,s)),e.global(t)),k=Fy(O(Oy(l,c),Oy(E,T)),e.global(n)),te=e.global(r);e.setGlobal(t,ee),e.setGlobal(n,k,ee),e.setGlobal(r,te,k)}function Ky(e,t,n,r,i){let a=e.pos(t),o=e.pos(n),s=Py(Oy(o,a)),c=Py(Oy(ky(o,i),a));if(!s||!c)return;let l=Ry(s,c);for(let t of r)e.setPos(t,ky(a,Ly(l,Oy(e.pos(t),a))));e.rotMats&&e.setGlobal(t,Fy(l,e.global(t)))}function qy(e){if(e==null)return null;let t=()=>{throw TypeError(`Invalid motion trail edit recipe`)};(e.version!==1||!Number.isInteger(e.frames)||e.frames<1||!(e.fps>0)||!Number.isFinite(e.fps)||!Array.isArray(e.edits)||e.edits.length>4096)&&t();let n=e.edits.map(n=>((!_y.some(({id:e})=>e===n?.track)||!Number.isInteger(n.grabFrame)||n.grabFrame<0||n.grabFrame>=e.frames||!Number.isInteger(n.radiusFrames)||n.radiusFrames<0||![`x`,`y`,`z`].every(e=>Number.isFinite(n.clipDelta?.[e])))&&t(),{track:n.track,grabFrame:n.grabFrame,radiusFrames:n.radiusFrames,clipDelta:{x:n.clipDelta.x,y:n.clipDelta.y,z:n.clipDelta.z}})),r=null;return e.segments!=null&&((!Array.isArray(e.segments)||!e.segments.length||e.segments.length>4096)&&t(),r=e.segments.map(e=>((typeof e?.id!=`string`||!Number.isInteger(e.sourceStart)||e.sourceStart<0||!Number.isInteger(e.sourceEnd)||e.sourceEnd<e.sourceStart||!Number.isFinite(e.speed)||e.speed<.1||e.speed>4)&&t(),{id:e.id,sourceStart:e.sourceStart,sourceEnd:e.sourceEnd,speed:e.speed}))),{version:1,frames:e.frames,fps:e.fps,segments:r,edits:n}}function Jy(e,t,n){let r=e.trailEdits;return{...t,trailEdits:{version:1,frames:e.frames,fps:e.fps,segments:r?.segments??e.editSegments?.map(e=>({...e}))??null,edits:[...r?.edits??[],{...n,clipDelta:{...n.clipDelta}}]}}}function Yy(e,t){let n=qy(t);if(!n)return e;if(n.segments?.some(t=>t.sourceEnd>=e.frames))throw RangeError(`Motion trail source segment exceeds the take`);let r=n.segments?fy(e,n.segments):e;if(r.frames!==n.frames||r.fps!==n.fps)throw RangeError(`Motion trail recipe does not match the take clock`);for(let e of n.edits)r=Xy(r,e);return r}function Xy(e,{track:t=`hips`,grabFrame:n,radiusFrames:r,clipDelta:i}){if(!e?.posedJoints||!e?.rootPos||!(e.frames>0))return e;let{startFrame:a,endFrame:o}=Dy(e.frames,n,r),s=e.rootPos.slice(),c=e.posedJoints.slice(),l=gy[t]?.map(hy);if(l||t===`head`){let u=e.rotMats?e.rotMats.slice():null,d=hy(`Neck`),f=hy(`Head`),p=zy(l?l[2]:f).filter(e=>!l||e!==l[2]),m=l?Vy(e,l,a,o,n,r):null;for(let e=a;e<o;e+=1){let t=Ey(e-n,r);if(t<=0)continue;let a={...By(c,u,e),rotMats:u},o=[i.x*t,i.y*t,i.z*t];l?Gy(a,l,[l[2],...p],o,m):Ky(a,d,f,p,o)}let h=u?{...e,rootPos:s,posedJoints:c,rotMats:u}:{...e,rootPos:s,posedJoints:c};return l&&u&&(h.trailRetarget={base:e.trailRetarget?.base??e,chains:[...new Set([...e.trailRetarget?.chains??[],t])]}),Jy(e,h,{track:t,grabFrame:n,radiusFrames:r,clipDelta:i})}for(let e=a;e<o;e+=1){let t=Ey(e-n,r);if(t<=0)continue;let a=i.x*t,o=i.y*t,l=i.z*t;s[e*3]+=a,s[e*3+1]+=o,s[e*3+2]+=l;for(let t=0;t<my;t+=1){let n=(e*my+t)*3;c[n]+=a,c[n+1]+=o,c[n+2]+=l}}return Jy(e,{...e,rootPos:s,posedJoints:c},{track:t,grabFrame:n,radiusFrames:r,clipDelta:i})}var Zy=1.8,Qy=1.3,$y=Object.freeze({super16:Object.freeze({id:`super16`,label:`Super 16`,widthMm:12.52,heightMm:7.41}),super35:Object.freeze({id:`super35`,label:`Super 35`,widthMm:24.89,heightMm:18.66}),fullFrame:Object.freeze({id:`fullFrame`,label:`Full Frame`,widthMm:36,heightMm:24}),"65mm":Object.freeze({id:`65mm`,label:`65mm`,widthMm:52.63,heightMm:23.01})}),eb=`fullFrame`,tb=16/9,nb=Object.freeze({"16:9":16/9,"2.39:1":2.39,"9:16":9/16,"1:1":1,"4:3":4/3,"12:7":12/7,"fal 480P":832/480});function rb(e){return nb[e]??1.7777777777777777}function ib(e=eb,t=tb){let n=$y[e]??$y.fullFrame,r=Number.isFinite(t)&&t>0?t:tb;return Math.min(n.heightMm,n.widthMm/r)}function ab(e,t=eb,n=tb){return ib(t,n)/(2*Math.tan(e/2))}function ob(e,t=eb,n=tb){return 2*Math.atan(ib(t,n)/(2*e))}var sb=[14,18,24,28,35,50,85,100,135];function cb(e,t=eb,n=tb){let r=ab(e,t,n);return sb.reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)}var lb=[[2.8,`extreme close-up`,`ultra-realistic skin texture with visible pores and micro-detail, tack-sharp eyes, shallow depth of field`],[1.6,`close-up`,`ultra-realistic skin texture and fine facial detail, soft background blur, shallow depth of field`],[1.15,`medium close-up`,`natural skin and fabric texture, clear facial detail, shallow depth of field`],[.8,`medium shot`,`balanced detail on the subject and the surrounding space, moderate depth of field`],[.52,`medium-wide shot`,`the full figure with the environment clearly visible, deep focus`],[.3,`wide shot`,`full body in a richly detailed environment, deep focus`],[0,`extreme wide shot`,`a small figure within a vast, highly detailed environment, epic sense of scale, deep focus`]],ub=[[2.5,`overhead`,`a directly overhead bird's-eye view looking down at the subject`],[1.8,`high angle`,`a high angle looking down at the subject`],[1.5,`eye level`,`eye level`],[1.25,`chest level`,`chest level`],[.95,`hip level`,`a low hip-level angle`],[.45,`knee level`,`a low knee-level angle looking up at the subject`],[-1/0,`ground level`,`a dramatic ground-level angle looking up at the subject`]],db=(e,t)=>e.find(([e])=>t>=e)??e[e.length-1];function fb(e,t,n,r=Zy,i={}){let a=i.sensorId??`fullFrame`,o=i.aspectRatio??1.7777777777777777,s=e.x-t.x,c=e.z-t.z,l=e.y-Qy,u=Math.hypot(s,c),d=Math.max(Math.hypot(u,l),1e-6),f=r/(2*d*Math.tan(n/2)),[,p,m]=db(lb,f),[,h,g]=db(ub,e.y),_=Math.atan2(e.y-r*.94,Math.max(u,1e-6))*180/Math.PI,v=t.rot*Math.PI/180,y={x:Math.sin(v),z:Math.cos(v)},b={x:s/Math.max(u,1e-6),z:c/Math.max(u,1e-6)},x=y.x*b.x+y.z*b.z,S=y.x*b.z-y.z*b.x>=0?`right`:`left`,C=S===`right`?`R`:`L`,w,T;return x>.85?(w=`front`,T=`seen from the front, the face toward the camera`):x<-.85?(w=`back`,T=`seen from directly behind, the back of the head toward the camera`):x>.34?(w=`front ¾ ${C}`,T=`a three-quarter front view from the ${S}`):x<-.34?(w=`rear ¾ ${C}`,T=`a three-quarter rear view from the ${S}`):(w=`${S} profile`,T=`a ${S}-side profile view`),{sizeLabel:p,sizeContext:m,levelLabel:h,levelPhrase:g,viewShort:w,viewPhrase:T,focalMm:cb(n,a,o),exactFocalMm:ab(n,a,o),sensorId:$y[a]?.id??`fullFrame`,usedSensorHeightMm:ib(a,o),distance:d,screenFraction:f,elevationDeg:_}}function pb(e){return[e.sizeLabel,e.viewShort,e.levelLabel,`${e.focalMm}mm`].map(e=>e.toUpperCase()).join(` · `)}var mb=[{id:`nano_banana_pro`,label:`Nano Banana Pro`},{id:`nano_banana_2`,label:`Nano Banana 2`},{id:`gpt_image_2`,label:`GPT Image 2`},{id:`seedream_5`,label:`Seedream 5.0`},{id:`flux_2`,label:`Flux 2`,numericLens:!0,flavor:`fine film grain, high micro-detail`}],hb=`Custom…`,gb=[`Static / locked-off`,`Push-in (dolly in)`,`Pull-out (dolly out)`,`Pan left`,`Pan right`,`Tilt up`,`Tilt down`,`Tracking / follow`,`Orbit / arc`,`Crane up`,`Crane down`,`Handheld`,`Crash zoom in`,`Dolly-zoom (vertigo)`,`Whip pan`,`Aerial / drone`,hb];function _b({mode:e=`image`,model:t,shot:n,subject:r,subject2:i=null,posePhrase:a=``,pose2Phrase:o=``,environment:s,style:c,cameraMove:l=gb[0],customMove:u=``,hasCharSheet:d=!1,hasEnvSheet:f=!1}){let p=t?.numericLens?`${n.focalMm}mm lens at f/2.2`:`${n.focalMm}mm lens`,m=e===`video`?`Cinematic ${n.sizeLabel} at ${p}, ${n.levelPhrase}, ${n.viewPhrase}.`:`Photorealistic cinematic film still, ${n.sizeLabel} at ${p}, ${n.levelPhrase}, ${n.viewPhrase}.`,h=(e,t)=>t?`${e}, ${t}`:e,g;g=d?i?`Both subjects are the characters from the attached character sheet. Each one exactly matches their own body pose and placement shown in the blocking frame.`:`The subject is the character from the attached character sheet, exactly matching the body pose and placement shown in the blocking frame.`:i?`Two subjects. Subject 1: ${h(r,a)}. Subject 2: ${h(i,o)}. Each subject exactly matches their own body pose and placement shown in the blocking frame.`:`Subject: ${h(r,a)}, exactly matching the body pose and placement shown in the blocking frame.`;let _=f?`The setting is the location from the attached environment sheet.`:`Environment: ${s}.`,v=l===`Custom…`?u.trim()||`static, locked-off shot`:l.toLowerCase();return[m,g,_,`${c}, ${n.sizeContext}.`,e===`video`?`Camera move: ${v}.`:null,`Use the attached blocking frame ONLY as a camera and staging guide — it fixes the exact framing, this camera angle, the lens, and the subject placement. Its floor grid is a measuring aid that encodes distance and scale: read the subject's depth and size from it, but do NOT draw the grid itself. Replace the entire setting with the described environment and render real people; do NOT reproduce its grey mannequins, grey box set, measurement grid, or flat lighting.`,t?.flavor??null,e===`video`&&(t?.audio||t?.capabilities?.audio)?`Include natural ambient sound.`:null,`16:9.`].filter(Boolean).join(` `)}var vb=1;function yb(e){return Array.isArray(e)?`[${e.map(yb).join(`,`)}]`:!e||typeof e!=`object`?JSON.stringify(e):`{${Object.keys(e).filter(e=>e!==`id`).sort().map(t=>`${JSON.stringify(t)}:${yb(e[t])}`).join(`,`)}}`}function bb(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}var xb=class extends Error{constructor(e,t){super(`Unknown ${e} ID: ${t}`),this.name=`UnknownStableItemIdError`}};function Sb(e){return`${e}-${Date.now().toString(36)}-${vb++}`}function Cb(e){return typeof e==`string`&&e.trim()!==``}function wb(e,t,n=new Set){let r=n,i=new Map;return(Array.isArray(e)?e:[]).map(e=>{let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{},a=Cb(n.id)?n.id:null;if(a&&!r.has(a))return r.add(a),{...n,id:a};let o=`${t}-${bb(yb(n))}`,s=i.get(o)??0;i.set(o,s+1);let c=s===0?o:`${o}-${s+1}`;for(;r.has(c);){let e=i.get(o)??0;i.set(o,e+1),c=`${o}-${e+1}`}return r.add(c),{...n,id:c}})}function Tb(e,t,n){let r=Array.isArray(e)?e.find(e=>e.id===t):void 0;if(!r)throw new xb(n,t);return r}function Eb(e,t,n,r){return Tb(e,t,r),e.map(e=>e.id===t?n(e):e)}function Db(e,t,n){return Tb(e,t,n),e.filter(e=>e.id!==t)}var Ob=Object.freeze({minScale:.1,maxScale:10,maxOffset:100}),kb=(e,t)=>{let n=Number(e);return Number.isFinite(n)?n:t};function Ab(e){let t=((e+180)%360+360)%360-180;return Object.is(t,-0)?0:t}function jb(e,t=Ob){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{},r=Math.max(2**-52,kb(t?.minScale,Ob.minScale)),i=Math.max(r,kb(t?.maxScale,Ob.maxScale)),a=Math.max(0,kb(t?.maxOffset,Ob.maxOffset)),o=kb(n.scale,1),s=kb(n.yawDeg??n.yaw,0),c=e=>Math.max(-a,Math.min(a,kb(e,0)));return{scale:Math.max(r,Math.min(i,o>0?o:1)),yawDeg:Ab(s),offsetX:c(n.offsetX??n.offset_x),offsetY:c(n.offsetY??n.offset_y),offsetZ:c(n.offsetZ??n.offset_z)}}function Mb(e){return e==null?e:typeof e.slice==`function`?e.slice():Array.from(e)}function Nb(e,t){return e!=null&&typeof e.length==`number`&&e.length>=t}function Pb(e,t=e?.sceneCalibration,n={}){let r={status:`not-needed`,applied:!1,changedFrames:0,maxDisplacement:0,maxRootDisplacement:0,maxJointDisplacement:0,calibration:jb(null,n.limits)};if(!e||typeof e!=`object`)return{motion:e,diagnostics:{...r,status:`invalid-motion`}};let i=jb(t,n.limits),a=Number(e.frames),o=Number.isInteger(a)&&a>=0&&Nb(e.rootPos,a*3),s=Number.isInteger(a)&&a>=0&&Nb(e.posedJoints,0)&&e.posedJoints.length%(a*3||1)==0;if(!o&&!s)return{motion:e,diagnostics:{...r,status:`invalid-motion`,calibration:i}};if(i.scale===1&&i.yawDeg===0&&i.offsetX===0&&i.offsetY===0&&i.offsetZ===0)return{motion:e,diagnostics:{...r,calibration:i}};let c=i.yawDeg*Math.PI/180,l=Math.cos(c),u=Math.sin(c),d=(e,t,n)=>{let r=i.scale*e,a=i.scale*t,o=i.scale*n;return[l*r+u*o+i.offsetX,a+i.offsetY,-u*r+l*o+i.offsetZ]},f=o?Mb(e.rootPos):e.rootPos,p=s?Mb(e.posedJoints):e.posedJoints,m=0,h=0,g=0,_=(e,t)=>[...e,...t].every(Number.isFinite)?Math.hypot(t[0]-e[0],t[1]-e[1],t[2]-e[2]):0;for(let t=0;t<a;t+=1){let n=!1;if(o){let r=t*3,i=[e.rootPos[r],e.rootPos[r+1],e.rootPos[r+2]],a=d(...i);f[r]=a[0],f[r+1]=a[1],f[r+2]=a[2],m=Math.max(m,_(i,a)),n||=_(i,a)>1e-9}if(s){let r=e.posedJoints.length/(a*3);for(let i=0;i<r;i+=1){let a=(t*r+i)*3,o=[e.posedJoints[a],e.posedJoints[a+1],e.posedJoints[a+2]],s=d(...o);p[a]=s[0],p[a+1]=s[1],p[a+2]=s[2],h=Math.max(h,_(o,s)),n||=_(o,s)>1e-9}}n&&(g+=1)}let v={status:`calibrated`,applied:!0,changedFrames:g,maxDisplacement:Math.max(m,h),maxRootDisplacement:m,maxJointDisplacement:h,calibration:i};return{motion:{...e,rootPos:f,posedJoints:p},diagnostics:v}}var Fb=i(`character.position`);i(`character.rot`);var Ib=i(`character.scale`),Lb=Object.fromEntries([`x`,`y`,`z`,`intensity`,`warmth`].map(e=>[e,i(`stage.keyLight.${e}`)])),Rb=`cozyclay.scenes.v4`,zb=`cozyclay.scenes.v4.quarantine`,Bb=`cozyclay.scenes.v3`,Vb=`cozyclay.scenes.v2`,Hb=`cozyclay.scenes.v1`,Ub=`cozyclay.scene.v1`,Wb=Object.freeze([Bb,Vb,Hb]),Gb=e=>Math.round(e*24/20),Kb=Object.freeze([`y-bot-tpose`,`x-bot-tpose`]),qb=`y-bot-tpose`,Jb=`a young woman in a tan coat`,Yb=`a man in a dark coat`,Xb=Object.freeze({characters:Object.freeze([Object.freeze({id:`char-a`,model:qb,x:0,z:0,rot:0,hidden:!1,pose:null,subject:Jb})]),hasCharSheet:!1,environmentImage:null,environment:`a sunlit modern living room`,style:`moody cinematic lighting, 35mm film look`,hasEnvSheet:!1,shotAspect:`16:9`,cameraPresetId:null,sensorId:eb,keyLight:Object.freeze({x:6,y:9,z:4,intensity:1.12,warmth:.5})});function Zb(e){let t=$b(e)?e:{},n=Xb.keyLight,r=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)?Math.max(n.min,Math.min(n.max,e)):t;return{x:r(t.x,n.x,Lb.x),y:r(t.y,n.y,Lb.y),z:r(t.z,n.z,Lb.z),intensity:r(t.intensity,n.intensity,Lb.intensity),warmth:r(t.warmth,n.warmth,Lb.warmth)}}var Qb=1,$b=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function ex(e,t=new WeakMap){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e!=`object`)return null;if(t.has(e))return t.get(e);if(Array.isArray(e)){let n=[];t.set(e,n);for(let r of e)n.push(ex(r,t));return n}let n={};t.set(e,n);for(let[r,i]of Object.entries(e))Object.defineProperty(n,r,{value:ex(i,t),enumerable:!0,writable:!0,configurable:!0});return n}var tx=(e,t)=>Number.isFinite(e)?e:t;function nx(e){return typeof e==`string`&&e.startsWith(`data:image/`)?e:null}Ib.min,Ib.max;var rx=e=>Number.isFinite(e)&&e>0?Math.max(Ib.min,Math.min(Ib.max,e)):1;function ix(e,t,n){let r=tx(e?.rot,0)*Math.PI/180,i=tx(t,0),a=tx(n,0);return{x:tx(e?.x,0)+i*Math.cos(r)+a*Math.sin(r),z:tx(e?.z,0)-i*Math.sin(r)+a*Math.cos(r)}}function ax(e=null,t=0){let n=$b(e)?e:{};return{id:typeof n.id==`string`&&n.id?n.id:`char-${t+1}`,model:Kb.includes(n.model)?n.model:qb,x:Math.max(Fb.min.x,Math.min(Fb.max.x,tx(n.x,0))),y:Math.max(Fb.min.y,Math.min(Fb.max.y,tx(n.y,0))),z:Math.max(Fb.min.z,Math.min(Fb.max.z,tx(n.z,0))),rot:hg(tx(n.rot,0)),hidden:n.hidden===!0,tint:typeof n.tint==`string`&&/^#[0-9a-fA-F]{6}$/.test(n.tint)?n.tint:null,pose:$b(n.pose)?ex(n.pose):null,identityImage:nx(n.identityImage),scale:rx(n.scale),subject:typeof n.subject==`string`?n.subject:t===0?Jb:Yb,layer:cx(n.layer),motionRef:sx(n.motionRef)}}var ox=/^[0-9a-f]{64}$/i;function sx(e){if(!$b(e))return null;let t=typeof e.motionId==`string`&&ox.test(e.motionId)?e.motionId.toLowerCase():null,n=typeof e.url==`string`&&e.url?e.url:null;if(!t&&!n)return null;let r={};return t&&(r.motionId=t),n&&(r.url=n),Object.assign(r,{prompt:typeof e.prompt==`string`?e.prompt:``,rotationDeg:Number.isFinite(e.rotationDeg)?e.rotationDeg:0,anchorX:Number.isFinite(e.anchorX)?e.anchorX:0,anchorZ:Number.isFinite(e.anchorZ)?e.anchorZ:0}),$b(e.calibration)&&(r.calibration=jb(e.calibration)),e.trailEdits!=null&&(r.trailEdits=qy(e.trailEdits)),typeof e.studioTakeId==`string`&&e.studioTakeId&&(r.studioTakeId=e.studioTakeId),r}function cx(e){let t=$b(e)?e:{};return{waypoints:wb(ex(t.waypoints),`waypoint`),promptClips:wb(ex(t.promptClips),`prompt-clip`)}}function lx(e){let t=$b(e)?e:{},n=new Set;return{...t,characters:Array.isArray(t.characters)?t.characters.map(e=>({...e,layer:{waypoints:wb(ex(e.layer?.waypoints),`waypoint`,n),promptClips:wb(ex(e.layer?.promptClips),`prompt-clip`,n)}})):t.characters}}function ux(){return{waypoints:[],promptClips:[]}}function dx(e){if(!$b(e))return e;let t={...ex(e)};if(Array.isArray(e.waypoints)){let n=new Map;for(let t of e.waypoints){if(!$b(t)||!Number.isFinite(t.frame))continue;let e=Math.max(0,Gb(Math.round(t.frame)));n.set(e,{...ex(t),frame:e})}t.waypoints=[...n.values()].sort((e,t)=>e.frame-t.frame)}if(Array.isArray(e.promptClips)){let n=e.promptClips.filter(e=>$b(e)&&Number.isFinite(e.startFrame)&&Number.isFinite(e.endFrame)).sort((e,t)=>e.startFrame-t.startFrame),r=[],i=0;for(let e of n){let t=Math.max(i,Gb(Math.round(e.startFrame))),n=Math.max(t,Gb(Math.round(e.endFrame)));r.push({...ex(e),startFrame:t,endFrame:n}),i=n}t.promptClips=r}return t}function fx(e){return!$b(e)||!Array.isArray(e.characters)?e:{...e,characters:e.characters.map(e=>$b(e)&&$b(e.layer)?{...e,layer:dx(e.layer)}:e)}}function px(e){let t=[ax({...$b(e.charA)?e.charA:{},id:`char-a`,pose:e.poseA??null,subject:e.subject??`a young woman in a tan coat`},0)];return e.showB===!0&&t.push(ax({...$b(e.charB)?e.charB:{},id:`char-b`,pose:e.poseB??null,subject:e.subject2??`a man in a dark coat`},1)),t}var mx=new Set([`characters`,`hasCharSheet`,`environmentImage`,`environment`,`style`,`hasEnvSheet`,`shotAspect`,`cameraPresetId`,`sensorId`,`keyLight`,`charA`,`charB`,`showB`,`poseA`,`poseB`,`subject`,`subject2`]);function hx(e=null){let t=$b(e)?e:{},n=Array.isArray(t.characters)&&t.characters.length?t.characters.map((e,t)=>ax(e,t)):px(t),r={};for(let[e,n]of Object.entries(t))mx.has(e)||(r[e]=ex(n));return{...r,characters:n,hasCharSheet:t.hasCharSheet===!0,environmentImage:nx(t.environmentImage),environment:typeof t.environment==`string`?t.environment:Xb.environment,style:typeof t.style==`string`?t.style:Xb.style,hasEnvSheet:t.hasEnvSheet===!0,shotAspect:[`16:9`,`2.39:1`,`9:16`,`1:1`,`4:3`,`12:7`,`fal 480P`].includes(t.shotAspect)?t.shotAspect:Xb.shotAspect,cameraPresetId:typeof t.cameraPresetId==`string`&&t.cameraPresetId?t.cameraPresetId:Xb.cameraPresetId,sensorId:Object.hasOwn($y,t.sensorId??t.sensorFormat)?t.sensorId??t.sensorFormat:Xb.sensorId,keyLight:Zb(t.keyLight)}}function gx(e){let t=new Set(e.map(e=>e?.id)),n;do n=`scene-${Date.now().toString(36)}-${Qb++}`;while(t.has(n));return n}function _x(e,t){let n=e=>typeof e==`string`?e.normalize(`NFKC`).toLowerCase():``,r=new Set(t.map(e=>n(e?.name))),i=e=>r.has(n(e)),a=typeof e==`string`&&e.trim()?e.trim():`SCENE 01`;if(!i(a))return a;let o=a.match(/^(.*?)(\d+)$/);if(o){let[,e,t]=o;for(let n=Number(t)+1;;n+=1){let r=`${e}${String(n).padStart(t.length,`0`)}`;if(!i(r))return r}}for(let e=2;;e+=1){let t=`${a} ${e}`;if(!i(t))return t}}function vx(e=`SCENE 01`,t=[]){return{id:gx(t),name:_x(e,t),objects:[],shotDocument:null,stage:hx()}}function yx(e,t=`SCENE 01`){let n=Array.isArray(e)?e:[];return[...n,vx(t,n)]}function bx(e,t){if(!Array.isArray(e)||t<0||t>=e.length)return e;let n=e[t],r=vx(n.name,e);return r.objects=ex(n.objects),r.shotDocument=ex(n.shotDocument),r.stage=hx(n.stage),[...e.slice(0,t+1),r,...e.slice(t+1)]}function xx(e,t,n){if(!Array.isArray(e)||t<0||t>=e.length||typeof n!=`string`||!n.trim())return e;let r=_x(n,e.filter((e,n)=>n!==t));return r===e[t].name?e:e.map((e,n)=>n===t?{...e,name:r}:e)}function Sx(e,t){return!Array.isArray(e)||e.length<=1||t<0||t>=e.length?e:e.filter((e,n)=>n!==t)}function Cx(e,t){if(!Array.isArray(e)||!e.length)return-1;let n=e.findIndex(e=>e.id===t);return n<0?0:n}function wx(){let e=vx();return{version:4,activeSceneId:e.id,scenes:[e]}}function Tx(e,t,n,r,i=!1){if(!$b(e)||typeof e.id!=`string`||!e.id||!Array.isArray(e.objects)||t.some(t=>t.id===e.id))return null;let a=lx(hx(ex($b(e.stage)?e.stage:r)));return{id:e.id,name:_x(typeof e.name==`string`?e.name:`SCENE ${String(n).padStart(2,`0`)}`,t),objects:e.objects.filter($b).map(e=>ex(e)),shotDocument:ex(e.shotDocument??null),stage:i?fx(a):a}}function Ex(e,t=Xb,n=!1){let r=[],i=0;for(let a of e.scenes){let e=Tx(a,r,r.length+1,t,n);e?r.push(e):i+=1}return r.length||r.push(vx()),{document:{version:4,activeSceneId:r[Cx(r,e.activeSceneId)].id,scenes:r},dropped:i}}function Dx(e){try{return JSON.parse(e)}catch{return null}}function Ox(e,t=null){if(e==null||e===``){if(t!=null&&t!==``){let e=Dx(t);if(!$b(e)||e.version!==1||!Array.isArray(e.objects))return{status:`corrupt`,document:wx(),dropped:0,quarantineRaw:t};let n=wx();return n.scenes[0].objects=e.objects.filter($b).map(e=>ex(e)),{status:`migrated`,document:n,dropped:e.objects.length-n.scenes[0].objects.length}}return{status:`absent`,document:wx(),dropped:0}}let n=Dx(e);if(!$b(n)||!Number.isInteger(n.version)||n.version<1)return{status:`corrupt`,document:wx(),dropped:0,quarantineRaw:e};if(n.version>4)return{status:`future`,document:null,dropped:0};if(!Array.isArray(n.scenes))return{status:`corrupt`,document:wx(),dropped:0,quarantineRaw:e};let r=n.version<4,i=n.version<4,a=Ex(n,hx(n.stage),i);return{status:r?`migrated`:`valid`,...a}}function kx(e){return JSON.stringify({version:4,activeSceneId:e.activeSceneId,scenes:e.scenes})}function Ax(e){let t=e.getItem(Rb);for(let n of Wb){if(t)break;t=e.getItem(n)}let n=t?null:e.getItem(Ub),r=Ox(t,n);return r.status===`corrupt`&&r.quarantineRaw!==void 0&&e.setItem(zb,r.quarantineRaw),r.status===`migrated`&&e.setItem(Rb,kx(r.document)),r}var Q=e(g(),1),jx=`cozyclay.locale`;function Mx(){try{let e=localStorage.getItem(jx);return e===`ko`||e===`en`?e:null}catch{return null}}var Nx=Mx()??`en`,Px=Nx===`ko`,Fx=Mx()!==null;function Ix(e,t){return Px?t:e}function Lx(e){if(e===`ko`||e===`en`){try{localStorage.setItem(jx,e)}catch{}window.location.reload()}}var Rx=`.cclayproject`,zx=`cozyclay.workflow.v1`,Bx=`cozyclay.project-handle.v1`,Vx=`kv`,Hx=`lastProjectHandle`,Ux=201326592,Wx=268435456,Gx=/^[0-9a-f]{64}$/i;function Kx(e){if(!e||typeof e!=`object`)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qx(e,t=0){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:null;if(t>32)return null;if(Array.isArray(e))return e.map(e=>qx(e,t+1));if(!Kx(e))return null;let n={};for(let[r,i]of Object.entries(e))r!==`__proto__`&&r!==`constructor`&&r!==`prototype`&&i!==void 0&&typeof i!=`function`&&typeof i!=`symbol`&&(n[r]=qx(i,t+1));return n}function Jx(e){return{x:Number.isFinite(e?.x)?e.x:0,y:Number.isFinite(e?.y)?e.y:0}}function Yx(){return{version:1,nodes:[],edges:[]}}function Xx(e){if(!Kx(e)||e.version!==void 0&&e.version!==1)return Yx();let t=[],n=new Set;for(let r of Array.isArray(e.nodes)?e.nodes:[]){if(!Kx(r)||typeof r.id!=`string`||!r.id.trim()||n.has(r.id))continue;let e=qx(r.data);t.push({id:r.id,type:typeof r.type==`string`&&r.type.trim()?r.type:`default`,position:Jx(r.position),data:Kx(e)?e:{}}),n.add(r.id)}let r=[],i=new Set;for(let t=0;t<(Array.isArray(e.edges)?e.edges.length:0);t+=1){let a=e.edges[t];if(!Kx(a)||typeof a.source!=`string`||typeof a.target!=`string`||!n.has(a.source)||!n.has(a.target))continue;let o=typeof a.id==`string`&&a.id.trim()?a.id:`${a.source}->${a.target}:${t}`;if(i.has(o))continue;let s={id:o,source:a.source,target:a.target};typeof a.sourceHandle==`string`&&a.sourceHandle&&(s.sourceHandle=a.sourceHandle),typeof a.targetHandle==`string`&&a.targetHandle&&(s.targetHandle=a.targetHandle);let c=qx(a.data);Kx(c)&&(s.data=c),r.push(s),i.add(o)}return{version:1,nodes:t,edges:r}}function Zx(e=globalThis.localStorage){try{return Xx(JSON.parse(e?.getItem(`cozyclay.workflow.v1`)||`null`))}catch{return Yx()}}function Qx(e,t=globalThis.localStorage){let n=Xx(e);try{t?.setItem(zx,JSON.stringify(n))}catch{}try{globalThis.dispatchEvent?.(new CustomEvent(`cozyclay:workflow-change`))}catch{}return n}function $x(e){return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):null}function eS(e){let t=new Uint8Array(e),n=``;for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(n)}function tS(e,t){if(typeof e!=`string`||e.length<4||e.length%4)return{code:`bad-base64`};if(e.length>Math.ceil(t/3)*4)return{code:`too-large`};let n=e.endsWith(`==`)?2:+!!e.endsWith(`=`);for(let t=0;t<e.length-n;t+=1){let n=e.charCodeAt(t);if(!(n>=65&&n<=90||n>=97&&n<=122||n>=48&&n<=57||n===43||n===47))return{code:`bad-base64`}}let r=e.length/4*3-n;return r>t?{code:`too-large`}:{bytes:r}}function nS(e,t){let n=tS(e,t);if(n.code)return n;try{let t=atob(e),n=Uint8Array.from(t,e=>e.charCodeAt(0));return eS(n)===e?{buffer:n.buffer}:{code:`bad-base64`}}catch{return{code:`bad-base64`}}}function rS(e,t,n){let r=Error(`${n} (${e} bytes) exceeds the ${t}-byte limit.`);return r.code=`resources-too-large`,r.bytes=e,r.limit=t,r}function iS(e){let t=$x(e?.bytes),n=em({...e,bytes:t});return!n||n.bytes.byteLength>33554432?null:{record:{...n,bytes:eS(n.bytes)},bytes:n.bytes.byteLength}}function aS(e){let t=new Set,n=e=>{if(Array.isArray(e)){for(let t of e)n(t);return}if(Kx(e)){Kp(e.assetRef)&&t.add(e.assetRef);for(let t of Object.values(e))n(t)}};return n(e),t}function oS(e){return{...Number.isInteger(e.frames)&&e.frames>=0?{frames:e.frames}:{},...Number.isFinite(e.fps)&&e.fps>0?{fps:e.fps}:{},...typeof e.name==`string`&&e.name.trim()?{name:e.name}:{},...Kx(e.meta)?{meta:qx(e.meta)}:{}}}function sS(e){return typeof e==`string`&&Gx.test(e)?e.toLowerCase():null}function cS(e){if(!e||typeof e!=`object`)return null;let t=sS(e.motionId);if(!t)return null;let n=$x(e.bytes);if(n){if(!n.byteLength)return null;if(n.byteLength>201326592)throw rS(n.byteLength,Ux,`Motion ${t}`);return{motionId:t,bytes:n.byteLength,raw:n,details:oS(e)}}if(e.encoding!==`base64`)return null;let r=tS(e.data,Ux);if(r.code===`too-large`)throw rS(e.data.length/4*3,Ux,`Motion ${t}`);return r.code||e.bytes!==void 0&&e.bytes!==r.bytes?null:{motionId:t,bytes:r.bytes,data:e.data,details:oS(e)}}async function lS(e,t){let n=$x(e?.bytes);if(!n)return!1;try{return(qp(e.id)?await Zp(n,t):await Xp(n,t))===e.id}catch{return!1}}var uS={"bad-id":`its id is not a content address`,duplicate:`the same id appears earlier in the file`,"bad-encoding":`its encoding is not base64`,"bad-base64":`its payload is not valid base64`,"length-mismatch":`its payload does not match the recorded byte length`,"too-large":`its payload exceeds the size limit`,"bad-record":`its metadata is incomplete`};function dS(e,t){let n=[];if(!Array.isArray(e))return n;let r=new Set;for(let i of e){let e=typeof i?.id==`string`?i.id:null;if(!Jp(e)){t(`image`,e,`bad-id`);continue}if(r.has(e)){t(`image`,e,`duplicate`);continue}let a=nS(i.bytes,Rp);if(a.code){t(`image`,e,a.code);continue}let o=em({...i,bytes:a.buffer});if(!o){t(`image`,e,`bad-record`);continue}r.add(e),n.push(o)}return n}function fS(e,t){let n=[];if(!Array.isArray(e))return n;let r=new Set;for(let i of e){let e=sS(i?.motionId);if(!e){t(`motion`,typeof i?.motionId==`string`?i.motionId:null,`bad-id`);continue}if(r.has(e)){t(`motion`,e,`duplicate`);continue}if(i.encoding!==`base64`){t(`motion`,e,`bad-encoding`);continue}let a=tS(i.data,Ux);if(a.code){t(`motion`,e,a.code);continue}if(i.bytes!==a.bytes){t(`motion`,e,`length-mismatch`);continue}r.add(e),n.push({motionId:e,encoding:`base64`,data:i.data,bytes:a.bytes,...oS(i)})}return n}function pS({scenesDocument:e,workspaceLayout:t,customPoses:n,name:r,assets:i,motions:a,savedAt:o,workflow:s}){let c=new Map;for(let e of Array.isArray(i)?i:[]){let t=iS(e);t&&c.set(t.record.id,t)}let l=[],u=0,d=om(e?.scenes);for(let e of aS(s))d.add(e);for(let e of d){let t=c.get(e);t&&(l.push(t.record),u+=t.bytes)}let f=new Map;for(let e of Array.isArray(a)?a:[]){let t=cS(e);!t||f.has(t.motionId)||(f.set(t.motionId,t),u+=t.bytes)}if(u>268435456)throw rS(u,Wx,`Embedded resources`);let p=[...f.values()].map(({motionId:e,bytes:t,raw:n,data:r,details:i})=>({motionId:e,encoding:`base64`,data:r??eS(n),bytes:t,...i}));return{app:`cozyclay`,kind:`project`,version:4,name:typeof r==`string`&&r.trim()?r.trim():`Untitled`,...Number.isFinite(o)&&o>0?{savedAt:o}:{},scenes:e,workspace:t??null,poseLibrary:Array.isArray(n)?n:[],workflow:Xx(s),resources:{assets:l,motions:p}}}function mS(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,reason:`corrupt`}}if(!t||typeof t!=`object`)return{ok:!1,reason:`corrupt`};if(t.app!==`cozyclay`||t.kind!==`project`)return{ok:!1,reason:`not-a-project`};if(typeof t.version!=`number`)return{ok:!1,reason:`corrupt`};if(t.version>4)return{ok:!1,reason:`future`};let n=t.scenes;if(!n||typeof n!=`object`||n.version>4||!Array.isArray(n.scenes))return{ok:!1,reason:`scenes-invalid`};let r=[],i=[],a=(e,t,n)=>{let a=`Skipped embedded ${e} ${t??`(no id)`}: ${uS[n]}.`;i.push({kind:e,id:t,code:n,message:a}),r.push(a)},o=dS(t.version>=4?t.resources?.assets:t.version>=2?t.assets:void 0,a),s=t.version>=4?fS(t.resources?.motions,a):[],c=Xx(t.workflow);return{ok:!0,warnings:r,problems:i,project:{name:typeof t.name==`string`&&t.name.trim()?t.name.trim():`Untitled`,savedAt:Number.isFinite(t.savedAt)&&t.savedAt>0?t.savedAt:null,scenesDocument:{version:n.version,activeSceneId:n.activeSceneId??null,scenes:n.scenes},workspaceLayout:t.workspace&&typeof t.workspace==`object`?t.workspace:null,customPoses:Array.isArray(t.poseLibrary)?t.poseLibrary.filter(e=>e&&typeof e==`object`&&typeof e.id==`string`&&e.bones&&typeof e.bones==`object`):[],assets:o,motions:s,workflow:c}}}function hS(){return typeof window<`u`&&typeof window.showSaveFilePicker==`function`&&typeof window.showOpenFilePicker==`function`}var gS=[{description:`CozyClay Project`,accept:{"application/json":[Rx,`.json`]}}];async function _S(e){return await window.showSaveFilePicker({suggestedName:`${e||`Untitled`}${Rx}`,types:gS})}async function vS(){let[e]=await window.showOpenFilePicker({types:gS,multiple:!1});return e}async function yS(e,t){let n=await e.createWritable();await n.write(t),await n.close()}async function bS(e){let t=await e.getFile();return{name:t.name.replace(/\.cclayproject$|\.json$/i,``),text:await t.text(),savedAt:t.lastModified}}function xS(e,t){let n=new Blob([e],{type:`application/json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${t||`Untitled`}${Rx}`,i.click(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}function SS(){return new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=`${Rx},.json,application/json`,t.onchange=async()=>{let n=t.files?.[0];if(!n)return e(null);e({name:n.name.replace(/\.cclayproject$|\.json$/i,``),text:await n.text(),savedAt:n.lastModified})},t.oncancel=()=>e(null),t.click()})}function CS(){return new Promise((e,t)=>{let n=indexedDB.open(Bx,1);n.onupgradeneeded=()=>n.result.createObjectStore(Vx),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async function wS(e,t){try{let n=await CS();await new Promise((r,i)=>{let a=n.transaction(Vx,`readwrite`);a.objectStore(Vx).put({handle:e,name:t},Hx),a.oncomplete=r,a.onerror=()=>i(a.error)}),n.close()}catch{}}async function TS(){try{let e=await CS(),t=await new Promise((t,n)=>{let r=e.transaction(Vx,`readonly`).objectStore(Vx).get(Hx);r.onsuccess=()=>t(r.result??null),r.onerror=()=>n(r.error)});return e.close(),t}catch{return null}}async function ES(){try{let e=await CS();await new Promise((t,n)=>{let r=e.transaction(Vx,`readwrite`);r.objectStore(Vx).delete(Hx),r.oncomplete=t,r.onerror=()=>n(r.error)}),e.close()}catch{}}var DS=`recentProjects`,OS=`projectsDirectory`,kS=8,AS=`cozyclay.project-session.v1`;function jS(e=globalThis.localStorage){try{let t=JSON.parse(e?.getItem(`cozyclay.project-session.v1`)||`null`);if(!t||typeof t!=`object`)return null;let n=typeof t.name==`string`?t.name.trim():``;return n?{name:n,updatedAt:Number.isFinite(t.updatedAt)?t.updatedAt:0}:null}catch{return null}}function MS(e,t=globalThis.localStorage){let n=typeof e==`string`?e.trim():``;if(!n)return!1;try{return t?.setItem(AS,JSON.stringify({name:n,updatedAt:Date.now()})),!0}catch{return!1}}async function NS(e,t){try{let n=await CS();await new Promise((r,i)=>{let a=n.transaction(Vx,`readwrite`);a.objectStore(Vx).put(t,e),a.oncomplete=r,a.onerror=()=>i(a.error)}),n.close()}catch{}}async function PS(e){try{let t=await CS(),n=await new Promise((n,r)=>{let i=t.transaction(Vx,`readonly`).objectStore(Vx).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)});return t.close(),n}catch{return null}}async function FS(e,t){let n=await PS(DS)??[];await NS(DS,[{handle:e,name:t,openedAt:Date.now()},...n.filter(e=>e.name!==t)].slice(0,kS)),await wS(e,t)}async function IS(){return await PS(DS)??[]}async function LS(e){await NS(DS,(await PS(DS)??[]).filter(t=>t.name!==e))}function RS(){return typeof window<`u`&&typeof window.showDirectoryPicker==`function`}async function zS(){return window.showDirectoryPicker({mode:`readwrite`})}async function BS(e){await NS(OS,{handle:e})}async function VS(){return(await PS(OS))?.handle??null}async function HS(e){let t=[];try{for await(let[n,r]of e.entries()){if(r.kind!==`file`||!n.endsWith(`.cclayproject`))continue;let e=await r.getFile();t.push({name:n.slice(0,-13),handle:r,lastModified:e.lastModified})}}catch{return[]}return t.sort((e,t)=>t.lastModified-e.lastModified)}async function US(e){try{return await e.queryPermission({mode:`readwrite`})}catch{return`denied`}}async function WS(e){try{return await e.queryPermission({mode:`readwrite`})===`granted`?`granted`:await e.requestPermission({mode:`readwrite`})}catch{return`denied`}}Object.freeze([`idle`,`fetching`,`probing`,`ready`,`error`]);function GS(e,t=!1){if(!e)return``;if(e.status===`disabled`)return t?`낙하 보정 꺼짐`:`Descent recovery off`;if(e.status===`corrected`){let n=e.rejected?.length??0;return t?`낙하 보정 ${e.changedFrames}프레임 적용${n?` · ${n}구간 미해결`:``}`:`Descent recovery: ${e.changedFrames} frames corrected${n?` · ${n} unresolved spans`:``}`}let n=e.rejected?.[0]?.reason??e.reason??`unknown`;return`${t?`낙하 보정 미적용`:`Descent recovery not applied`}: ${{"world-endpoint-unsettled":[`3D endpoint never settles`,`3D 끝점이 안정되지 않음`],"no-confident-delayed-descent":[`no confident delayed descent detected`,`확실한 낙하 지연이 검출되지 않음`],"moving-camera-not-supported":[`moving-camera recovery unsupported`,`이동 카메라 보정 미지원`],"uncertain-keypoints":[`body tracking uncertain`,`관절 추적 불확실`],"uncertain-depth":[`depth change too large`,`깊이 변화가 큼`],"moving-landing":[`landing does not stay still`,`착지 후 이동이 계속됨`],"no-observed-landing":[`landing not observed`,`착지를 확인할 수 없음`],"landing-observation-too-short":[`not enough footage after landing`,`착지 이후 영상이 너무 짧음`],"excessive-correction":[`recovery exceeds its safety bound`,`보정량이 안전 범위를 초과함`]}[n]?.[+!!t]??n}`}function KS(e,t=!1){if(!e)return``;if(e.available===!1)return t?`색 세그멘테이션 측정 불가`:`Palette segmentation metrics unavailable`;if(e.detector!==`palette`||!Number.isFinite(e.detectionRate))return``;let n=Math.round(e.detectionRate*100),r=Number.isFinite(e.coverage?.mean)?Math.round(e.coverage.mean*100):null,i=Number.isFinite(e.coverage?.p10)&&Number.isFinite(e.coverage?.p90)?`${Math.round(e.coverage.p10*100)}–${Math.round(e.coverage.p90*100)}%`:null,a=Number.isFinite(e.parts?.mean)?Math.round(e.parts.mean):null,o=Number.isFinite(e.longestGapFrames)?e.longestGapFrames:0,s=Number.isFinite(e.hueErrorDeg?.p95)?Math.round(e.hueErrorDeg.p95):null;return t?`색 세그멘테이션: ${n}% 검출${r===null?``:` · 마스크 ${r}%${i?` (${i})`:``}`}${a===null?``:` · 색 파트 ${a}개`}${o?` · 최대 끊김 ${o}프레임`:``}${s===null?``:` · 색 오차 P95 ${s}°`}`:`Palette segmentation: ${n}% detected${r===null?``:` · ${r}% mask${i?` (${i})`:``}`}${a===null?``:` · ${a} colour parts`}${o?` · longest gap ${o} frames`:``}${s===null?``:` · hue error P95 ${s}°`}`}function qS(e){if(typeof e!=`string`)return{ok:!1,reason:`url-not-string`};let t=e.trim();if(t.length===0)return{ok:!1,reason:`url-empty`};if(t.startsWith(`//`))return{ok:!1,reason:`url-protocol-relative`};if(t.startsWith(`/`))return{ok:!0,url:t};if(/^https?:\/\//i.test(t)){let e;try{e=new URL(t)}catch{return{ok:!1,reason:`url-malformed`}}return YS(e.toString())?{ok:!1,reason:`url-platform-page`}:{ok:!0,url:e.toString()}}return{ok:!1,reason:`url-scheme-unsupported`}}var JS=/(?:^|\.)(?:youtube\.com|youtu\.be|vimeo\.com|tiktok\.com|instagram\.com|facebook\.com|twitter\.com|x\.com|bilibili\.com|naver\.com|kakao\.com)$/i;function YS(e){if(typeof e!=`string`)return!1;try{return JS.test(new URL(e).hostname)}catch{return!1}}async function XS(e,t,{fetchImpl:n,onProgress:r,defaultError:i}={}){let a=n??globalThis.fetch;if(typeof a!=`function`)throw Error(`fetch-unavailable`);let o;try{o=await a(e,t)}catch{throw Error(`bridge-unreachable`)}if(!o.ok){let e=`http-${o.status}`;try{e=(await o.json())?.reason??e}catch{}throw Error(e)}let s=o.body?.getReader?null:await o.text(),c=``,l=null,u=e=>{if(!e.trim())return;let t;try{t=JSON.parse(e)}catch{return}if(t.event===`progress`)r?.({stage:t.stage,ratio:t.ratio});else if(t.event===`error`)throw Error(t.message||i);else t.event===`done`&&(l=t)};if(s!==null)for(let e of s.split(`
|
|
13
|
+
}`,Tl=class extends aa{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Cl,this.fragmentShader=wl,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=_l(e.uniforms),this.uniformsGroups=bl(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let r=e.uniforms[n];switch(this.uniforms[n]={},r.type){case`t`:this.uniforms[n].value=t[r.value]||null;break;case`c`:this.uniforms[n].value=new H().setHex(r.value);break;case`v2`:this.uniforms[n].value=new R().fromArray(r.value);break;case`v3`:this.uniforms[n].value=new B().fromArray(r.value);break;case`v4`:this.uniforms[n].value=new sr().fromArray(r.value);break;case`m3`:this.uniforms[n].value=new Gn().fromArray(r.value);break;case`m4`:this.uniforms[n].value=new V().fromArray(r.value);break;default:this.uniforms[n].value=r.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let t in e.extensions)this.extensions[t]=e.extensions[t];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},El=class extends Tl{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},Dl=class extends aa{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type=`MeshStandardMaterial`,this.defines={STANDARD:``},this.color=new H(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new H(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Cr,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:``},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Ol=class extends Dl{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:``,PHYSICAL:``},this.type=`MeshPhysicalMaterial`,this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new R(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return I(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new H(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new H(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new H(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:``,PHYSICAL:``},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},kl=class extends aa{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type=`MeshPhongMaterial`,this.color=new H(16777215),this.specular=new H(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new H(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Cr,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Al=class extends aa{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:``},this.type=`MeshToonMaterial`,this.color=new H(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new H(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},jl=class extends aa{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type=`MeshNormalMaterial`,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}},Ml=class extends aa{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type=`MeshLambertMaterial`,this.color=new H(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new H(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Cr,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Nl=class extends aa{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=wt,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},Pl=class extends aa{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}},Fl=class extends aa{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:``},this.type=`MeshMatcapMaterial`,this.color=new H(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new R(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:``},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}},Il=class extends qo{constructor(e){super(),this.isLineDashedMaterial=!0,this.type=`LineDashedMaterial`,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}};function Ll(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function Rl(e){function t(t,n){return e[t]-e[n]}let n=e.length,r=Array(n);for(let e=0;e!==n;++e)r[e]=e;return r.sort(t),r}function zl(e,t,n){let r=e.length,i=new e.constructor(r);for(let a=0,o=0;o!==r;++a){let r=n[a]*t;for(let n=0;n!==t;++n)i[o++]=e[r+n]}return i}function Bl(e,t,n,r){let i=1,a=e[0];for(;a!==void 0&&a[r]===void 0;)a=e[i++];if(a===void 0)return;let o=a[r];if(o!==void 0)if(Array.isArray(o))do o=a[r],o!==void 0&&(t.push(a.time),n.push(...o)),a=e[i++];while(a!==void 0);else if(o.toArray!==void 0)do o=a[r],o!==void 0&&(t.push(a.time),o.toArray(n,n.length)),a=e[i++];while(a!==void 0);else do o=a[r],o!==void 0&&(t.push(a.time),n.push(o)),a=e[i++];while(a!==void 0)}function K(e,t,n,r,i=30){let a=e.clone();a.name=t;let o=[];for(let e=0;e<a.tracks.length;++e){let t=a.tracks[e],s=t.getValueSize(),c=[],l=[];for(let e=0;e<t.times.length;++e){let a=t.times[e]*i;if(!(a<n||a>=r)){c.push(t.times[e]);for(let n=0;n<s;++n)l.push(t.values[e*s+n])}}c.length!==0&&(t.times=Ll(c,t.times.constructor),t.values=Ll(l,t.values.constructor),o.push(t))}a.tracks=o;let s=1/0;for(let e=0;e<a.tracks.length;++e)s>a.tracks[e].times[0]&&(s=a.tracks[e].times[0]);for(let e=0;e<a.tracks.length;++e)a.tracks[e].shift(-1*s);return a.resetDuration(),a}function q(e,t=0,n=e,r=30){r<=0&&(r=30);let i=n.tracks.length,a=t/r;for(let t=0;t<i;++t){let r=n.tracks[t],i=r.ValueTypeName;if(i===`bool`||i===`string`)continue;let o=e.tracks.find(function(e){return e.name===r.name&&e.ValueTypeName===i});if(o===void 0)continue;let s=0,c=r.getValueSize();r.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(s=c/3);let l=0,u=o.getValueSize();o.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(l=u/3);let d=r.times.length-1,f;if(a<=r.times[0]){let e=s,t=c-s;f=r.values.slice(e,t)}else if(a>=r.times[d]){let e=d*c+s,t=e+c-s;f=r.values.slice(e,t)}else{let e=r.createInterpolant(),t=s,n=c-s;e.evaluate(a),f=e.resultBuffer.slice(t,n)}i===`quaternion`&&new z().fromArray(f).normalize().conjugate().toArray(f);let p=o.times.length;for(let e=0;e<p;++e){let t=e*u+l;if(i===`quaternion`)z.multiplyQuaternionsFlat(o.values,t,f,0,o.values,t);else{let e=u-l*2;for(let n=0;n<e;++n)o.values[t+n]-=f[n]}}}return e.blendMode=Ct,e}var Vl=class{static convertArray(e,t){return Ll(e,t)}static isTypedArray(e){return an(e)}static getKeyframeOrder(e){return Rl(e)}static sortedArray(e,t,n){return zl(e,t,n)}static flattenJSON(e,t,n,r){Bl(e,t,n,r)}static subclip(e,t,n,r,i=30){return K(e,t,n,r,i)}static makeClipAdditive(e,t=0,n=e,r=30){return q(e,t,n,r)}},Hl=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`THREE.Interpolant: Call to abstract method.`)}intervalChanged_(){}},Ul=class extends Hl{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:yt,endingEnd:yt}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case bt:i=e,o=2*t-n;break;case xt:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case bt:a=e,s=2*n-t;break;case xt:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},Wl=class extends Hl{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},Gl=class extends Hl{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},Kl=class extends Hl{interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this.inTangents,u=this.outTangents;if(!l||!u){let e=(n-t)/(r-t),l=1-e;for(let t=0;t!==o;++t)i[t]=a[c+t]*l+a[s+t]*e;return i}let d=o*2,f=e-1;for(let p=0;p!==o;++p){let o=a[c+p],m=a[s+p],h=f*d+p*2,g=u[h],_=u[h+1],v=e*d+p*2,y=l[v],b=l[v+1],x=(n-t)/(r-t),S,C,w,T,E;for(let e=0;e<8;e++){S=x*x,C=S*x,w=1-x,T=w*w,E=T*w;let e=E*t+3*T*x*g+3*w*S*y+C*r-n;if(Math.abs(e)<1e-10)break;let i=3*T*(g-t)+6*w*x*(y-g)+3*S*(r-y);if(Math.abs(i)<1e-10)break;x-=e/i,x=Math.max(0,Math.min(1,x))}i[p]=E*o+3*T*x*_+3*w*S*b+C*m}return i}},ql=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=Ll(t,this.TimeBufferType),this.values=Ll(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:Ll(e.times,Array),values:Ll(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Gl(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Wl(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Ul(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new Kl(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.inTangents=this.settings.inTangents,t.outTangents=this.settings.outTangents),t}setInterpolation(e){let t;switch(e){case ht:t=this.InterpolantFactoryMethodDiscrete;break;case gt:t=this.InterpolantFactoryMethodLinear;break;case _t:t=this.InterpolantFactoryMethodSmooth;break;case vt:t=this.InterpolantFactoryMethodBezier}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t);return P(`KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return ht;case this.InterpolantFactoryMethodLinear:return gt;case this.InterpolantFactoryMethodSmooth:return _t;case this.InterpolantFactoryMethodBezier:return vt}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(F(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(F(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){F(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){F(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&an(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){F(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===_t,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0]))if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};ql.prototype.ValueTypeName=``,ql.prototype.TimeBufferType=Float32Array,ql.prototype.ValueBufferType=Float32Array,ql.prototype.DefaultInterpolation=gt;var Jl=class extends ql{constructor(e,t,n){super(e,t,n)}};Jl.prototype.ValueTypeName=`bool`,Jl.prototype.ValueBufferType=Array,Jl.prototype.DefaultInterpolation=ht,Jl.prototype.InterpolantFactoryMethodLinear=void 0,Jl.prototype.InterpolantFactoryMethodSmooth=void 0;var Yl=class extends ql{constructor(e,t,n,r){super(e,t,n,r)}};Yl.prototype.ValueTypeName=`color`;var Xl=class extends ql{constructor(e,t,n,r){super(e,t,n,r)}};Xl.prototype.ValueTypeName=`number`;var Zl=class extends Hl{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)z.slerpFlat(i,0,a,c-o,a,c,s);return i}},Ql=class extends ql{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new Zl(this.times,this.values,this.getValueSize(),e)}};Ql.prototype.ValueTypeName=`quaternion`,Ql.prototype.InterpolantFactoryMethodSmooth=void 0;var $l=class extends ql{constructor(e,t,n){super(e,t,n)}};$l.prototype.ValueTypeName=`string`,$l.prototype.ValueBufferType=Array,$l.prototype.DefaultInterpolation=ht,$l.prototype.InterpolantFactoryMethodLinear=void 0,$l.prototype.InterpolantFactoryMethodSmooth=void 0;var eu=class extends ql{constructor(e,t,n,r){super(e,t,n,r)}};eu.prototype.ValueTypeName=`vector`;var tu=class{constructor(e=``,t=-1,n=[],r=St){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=Sn(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,r=1/(e.fps||1);for(let e=0,i=n.length;e!==i;++e)t.push(ru(n[e]).scale(r));let i=new this(e.name,e.duration,t,e.blendMode);return i.uuid=e.uuid,i.userData=JSON.parse(e.userData||`{}`),i}static toJSON(e){let t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let e=0,r=n.length;e!==r;++e)t.push(ql.toJSON(n[e]));return r}static CreateFromMorphTargetSequence(e,t,n,r){let i=t.length,a=[];for(let e=0;e<i;e++){let o=[],s=[];o.push((e+i-1)%i,e,(e+1)%i),s.push(0,1,0);let c=Rl(o);o=zl(o,1,c),s=zl(s,1,c),!r&&o[0]===0&&(o.push(i),s.push(s[0])),a.push(new Xl(`.morphTargetInfluences[`+t[e].name+`]`,o,s).scale(1/n))}return new this(e,-1,a)}static findByName(e,t){let n=e;if(!Array.isArray(e)){let t=e;n=t.geometry&&t.geometry.animations||t.animations}for(let e=0;e<n.length;e++)if(n[e].name===t)return n[e];return null}static CreateClipsFromMorphTargetSequences(e,t,n){let r={},i=/^([\w-]*?)([\d]+)$/;for(let t=0,n=e.length;t<n;t++){let n=e[t],a=n.name.match(i);if(a&&a.length>1){let e=a[1],t=r[e];t||(r[e]=t=[]),t.push(n)}}let a=[];for(let e in r)a.push(this.CreateFromMorphTargetSequence(e,r[e],t,n));return a}resetDuration(){let e=this.tracks,t=0;for(let n=0,r=e.length;n!==r;++n){let e=this.tracks[n];t=Math.max(t,e.times[e.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e&&=this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){let e=[];for(let t=0;t<this.tracks.length;t++)e.push(this.tracks[t].clone());let t=new this.constructor(this.name,this.duration,e,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}};function nu(e){switch(e.toLowerCase()){case`scalar`:case`double`:case`float`:case`number`:case`integer`:return Xl;case`vector`:case`vector2`:case`vector3`:case`vector4`:return eu;case`color`:return Yl;case`quaternion`:return Ql;case`bool`:case`boolean`:return Jl;case`string`:return $l}throw Error(`THREE.KeyframeTrack: Unsupported typeName: `+e)}function ru(e){if(e.type===void 0)throw Error(`THREE.KeyframeTrack: track type undefined, can not parse`);let t=nu(e.type);if(e.times===void 0){let t=[],n=[];Bl(e.keys,t,n,`value`),e.times=t,e.values=n}return t.parse===void 0?new t(e.name,e.times,e.values,e.interpolation):t.parse(e)}var iu={enabled:!1,files:{},add:function(e,t){this.enabled!==!1&&(au(e)||(this.files[e]=t))},get:function(e){if(this.enabled!==!1&&!au(e))return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function au(e){try{let t=e.slice(e.indexOf(`:`)+1);return new URL(t).protocol===`blob:`}catch{return!1}}var ou=class{constructor(e,t,n){let r=this,i=!1,a=0,o=0,s,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(e){o++,i===!1&&r.onStart!==void 0&&r.onStart(e,a,o),i=!0},this.itemEnd=function(e){a++,r.onProgress!==void 0&&r.onProgress(e,a,o),a===o&&(i=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(e){r.onError!==void 0&&r.onError(e)},this.resolveURL=function(e){return e=e.normalize(`NFC`),s?s(e):e},this.setURLModifier=function(e){return s=e,this},this.addHandler=function(e,t){return c.push(e,t),this},this.removeHandler=function(e){let t=c.indexOf(e);return t!==-1&&c.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=c.length;t<n;t+=2){let n=c[t],r=c[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return r}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||=new AbortController,this._abortController}},su=new ou,cu=class{constructor(e){this.manager=e===void 0?su:e,this.crossOrigin=`anonymous`,this.withCredentials=!1,this.path=``,this.resourcePath=``,this.requestHeader={},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}load(){}loadAsync(e,t){let n=this;return new Promise(function(r,i){n.load(e,r,t,i)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}};cu.DEFAULT_MATERIAL_NAME=`__DEFAULT`;var lu={},uu=class extends Error{constructor(e,t){super(e),this.response=t}},du=class extends cu{constructor(e){super(e),this.mimeType=``,this.responseType=``,this._abortController=new AbortController}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=iu.get(`file:${e}`);if(i!==void 0){this.manager.itemStart(e),setTimeout(()=>{t&&t(i),this.manager.itemEnd(e)},0);return}if(lu[e]!==void 0){lu[e].push({onLoad:t,onProgress:n,onError:r});return}lu[e]=[],lu[e].push({onLoad:t,onProgress:n,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?`include`:`same-origin`,signal:typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,s=this.responseType;fetch(a).then(t=>{if(t.status===200||t.status===0){if(t.status===0&&P(`FileLoader: HTTP Status 0 received.`),typeof ReadableStream>`u`||t.body===void 0||t.body.getReader===void 0)return t;let n=lu[e],r=t.body.getReader(),i=t.headers.get(`X-File-Size`)||t.headers.get(`Content-Length`),a=i?parseInt(i):0,o=a!==0,s=0,c=new ReadableStream({start(e){t();function t(){r.read().then(({done:r,value:i})=>{if(r)e.close();else{s+=i.byteLength;let r=new ProgressEvent(`progress`,{lengthComputable:o,loaded:s,total:a});for(let e=0,t=n.length;e<t;e++){let t=n[e];t.onProgress&&t.onProgress(r)}e.enqueue(i),t()}},t=>{e.error(t)})}}});return new Response(c)}throw new uu(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(s){case`arraybuffer`:return e.arrayBuffer();case`blob`:return e.blob();case`document`:return e.text().then(e=>new DOMParser().parseFromString(e,o));case`json`:return e.json();default:if(o===``)return e.text();{let t=/charset="?([^;"\s]*)"?/i.exec(o),n=t&&t[1]?t[1].toLowerCase():void 0,r=new TextDecoder(n);return e.arrayBuffer().then(e=>r.decode(e))}}}).then(t=>{iu.add(`file:${e}`,t);let n=lu[e];delete lu[e];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.onLoad&&r.onLoad(t)}}).catch(t=>{let n=lu[e];if(n===void 0)throw this.manager.itemError(e),t;delete lu[e];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.onError&&r.onError(t)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},fu=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new du(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(n){try{t(i.parse(JSON.parse(n)))}catch(t){r?r(t):F(t),i.manager.itemError(e)}},n,r)}parse(e){let t=[];for(let n=0;n<e.length;n++){let r=tu.parse(e[n]);t.push(r)}return t}},pu=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=[],o=new _s,s=new du(this.manager);s.setPath(this.path),s.setResponseType(`arraybuffer`),s.setRequestHeader(this.requestHeader),s.setWithCredentials(i.withCredentials);let c=0;function l(l){s.load(e[l],function(e){let n=i.parse(e,!0);a[l]={width:n.width,height:n.height,format:n.format,mipmaps:n.mipmaps},c+=1,c===6&&(n.mipmapCount===1&&(o.minFilter=A),o.image=a,o.format=n.format,o.needsUpdate=!0,t&&t(o))},n,r)}if(Array.isArray(e))for(let t=0,n=e.length;t<n;++t)l(t);else s.load(e,function(e){let n=i.parse(e,!0);if(n.isCubemap){let e=n.mipmaps.length/n.mipmapCount;for(let t=0;t<e;t++){a[t]={mipmaps:[]};for(let e=0;e<n.mipmapCount;e++)a[t].mipmaps.push(n.mipmaps[t*n.mipmapCount+e]),a[t].format=n.format,a[t].width=n.width,a[t].height=n.height}o.image=a}else o.image.width=n.width,o.image.height=n.height,o.mipmaps=n.mipmaps;n.mipmapCount===1&&(o.minFilter=A),o.format=n.format,o.needsUpdate=!0,t&&t(o)},n,r);return o}},mu=new WeakMap,hu=class extends cu{constructor(e){super(e)}load(e,t,n,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=iu.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)i.manager.itemStart(e),setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);else{let e=mu.get(a);e===void 0&&(e=[],mu.set(a,e)),e.push({onLoad:t,onError:r})}return a}let o=on(`img`);function s(){l(),t&&t(this);let n=mu.get(this)||[];for(let e=0;e<n.length;e++){let t=n[e];t.onLoad&&t.onLoad(this)}mu.delete(this),i.manager.itemEnd(e)}function c(t){l(),r&&r(t),iu.remove(`image:${e}`);let n=mu.get(this)||[];for(let e=0;e<n.length;e++){let r=n[e];r.onError&&r.onError(t)}mu.delete(this),i.manager.itemError(e),i.manager.itemEnd(e)}function l(){o.removeEventListener(`load`,s,!1),o.removeEventListener(`error`,c,!1)}return o.addEventListener(`load`,s,!1),o.addEventListener(`error`,c,!1),e.slice(0,5)!==`data:`&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),iu.add(`image:${e}`,o),i.manager.itemStart(e),o.src=e,o}},gu=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=new bs;i.colorSpace=Ot;let a=new hu(this.manager);a.setCrossOrigin(this.crossOrigin),a.setPath(this.path);let o=0;function s(n){a.load(e[n],function(e){i.images[n]=e,o++,o===6&&(i.needsUpdate=!0,t&&t(i))},void 0,r)}for(let t=0;t<e.length;++t)s(t);return i}},_u=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new ao,o=new du(this.manager);return o.setResponseType(`arraybuffer`),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(i.withCredentials),o.load(e,function(e){let n;try{n=i.parse(e)}catch(e){r===void 0?F(e):r(e);return}i._applyTexData(a,n),t&&t(a,n)},n,r),a}createDataTexture(e){let t=new ao;return this._applyTexData(t,this.parse(e)),t}_applyTexData(e,t){t.image===void 0?t.data!==void 0&&(e.image.width=t.width,e.image.height=t.height,e.image.data=t.data):e.image=t.image,e.wrapS=t.wrapS===void 0?O:t.wrapS,e.wrapT=t.wrapT===void 0?O:t.wrapT,e.magFilter=t.magFilter===void 0?A:t.magFilter,e.minFilter=t.minFilter===void 0?A:t.minFilter,e.anisotropy=t.anisotropy===void 0?1:t.anisotropy,t.colorSpace!==void 0&&(e.colorSpace=t.colorSpace),t.flipY!==void 0&&(e.flipY=t.flipY),t.format!==void 0&&(e.format=t.format),t.type!==void 0&&(e.type=t.type),t.mipmaps!==void 0&&(e.mipmaps=t.mipmaps,e.minFilter=ae),t.mipmapCount===1&&(e.minFilter=A),t.generateMipmaps!==void 0&&(e.generateMipmaps=t.generateMipmaps),e.needsUpdate=!0}},vu=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=new or,a=new hu(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(e){i.image=e,i.needsUpdate=!0,t!==void 0&&t(i)},n,r),i}},yu=class extends Br{constructor(e,t=1){super(),this.isLight=!0,this.type=`Light`,this.color=new H(e),this.intensity=t}dispose(){this.dispatchEvent({type:`dispose`})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}},bu=class extends yu{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type=`HemisphereLight`,this.position.copy(Br.DEFAULT_UP),this.updateMatrix(),this.groundColor=new H(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){let t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}},xu=new V,Su=new B,Cu=new B,wu=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new R(512,512),this.mapType=se,this.map=null,this.mapPass=null,this.matrix=new V,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new To,this._frameExtents=new R(1,1),this._viewportCount=1,this._viewports=[new sr(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;Su.setFromMatrixPosition(e.matrixWorld),t.position.copy(Su),Cu.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Cu),t.updateMatrixWorld(),xu.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(xu,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===2001||t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(xu)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},Tu=new B,Eu=new z,Du=new B,Ou=class extends Br{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new V,this.projectionMatrix=new V,this.projectionMatrixInverse=new V,this.coordinateSystem=Yt,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(Tu,Eu,Du),Du.x===1&&Du.y===1&&Du.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Tu,Eu,Du.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(Tu,Eu,Du),Du.x===1&&Du.y===1&&Du.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Tu,Eu,Du.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},ku=new B,Au=new R,ju=new R,Mu=class extends Ou{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=xn*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(bn*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return xn*2*Math.atan(Math.tan(bn*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){ku.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ku.x,ku.y).multiplyScalar(-e/ku.z),ku.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ku.x,ku.y).multiplyScalar(-e/ku.z)}getViewSize(e,t){return this.getViewBounds(e,Au,ju),t.subVectors(ju,Au)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(bn*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},Nu=class extends wu{constructor(){super(new Mu(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=xn*2*e.angle*this.focus,r=this.mapSize.width/this.mapSize.height*this.aspect,i=e.distance||t.far;(n!==t.fov||r!==t.aspect||i!==t.far)&&(t.fov=n,t.aspect=r,t.far=i,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},Pu=class extends yu{constructor(e,t,n=0,r=Math.PI/3,i=0,a=2){super(e,t),this.isSpotLight=!0,this.type=`SpotLight`,this.position.copy(Br.DEFAULT_UP),this.updateMatrix(),this.target=new Br,this.distance=n,this.angle=r,this.penumbra=i,this.decay=a,this.map=null,this.shadow=new Nu}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}},Fu=class extends wu{constructor(){super(new Mu(90,1,.5,500)),this.isPointLightShadow=!0}},Iu=class extends yu{constructor(e,t,n=0,r=2){super(e,t),this.isPointLight=!0,this.type=`PointLight`,this.distance=n,this.decay=r,this.shadow=new Fu}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}},Lu=class extends Ou{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},Ru=class extends wu{constructor(){super(new Lu(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},zu=class extends yu{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type=`DirectionalLight`,this.position.copy(Br.DEFAULT_UP),this.updateMatrix(),this.target=new Br,this.shadow=new Ru}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){let t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}},Bu=class extends yu{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type=`AmbientLight`}},Vu=class extends yu{constructor(e,t,n=10,r=10){super(e,t),this.isRectAreaLight=!0,this.type=`RectAreaLight`,this.width=n,this.height=r}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){let t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}},Hu=class{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new B)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){let n=e.x,r=e.y,i=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.282095),t.addScaledVector(a[1],.488603*r),t.addScaledVector(a[2],.488603*i),t.addScaledVector(a[3],.488603*n),t.addScaledVector(a[4],n*r*1.092548),t.addScaledVector(a[5],r*i*1.092548),t.addScaledVector(a[6],.315392*(3*i*i-1)),t.addScaledVector(a[7],n*i*1.092548),t.addScaledVector(a[8],.546274*(n*n-r*r)),t}getIrradianceAt(e,t){let n=e.x,r=e.y,i=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.886227),t.addScaledVector(a[1],1.023328*r),t.addScaledVector(a[2],1.023328*i),t.addScaledVector(a[3],1.023328*n),t.addScaledVector(a[4],.858086*n*r),t.addScaledVector(a[5],.858086*r*i),t.addScaledVector(a[6],.743125*i*i-.247708),t.addScaledVector(a[7],.858086*n*i),t.addScaledVector(a[8],.429043*(n*n-r*r)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(e.coefficients[n],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let n=0;n<9;n++)this.coefficients[n].lerp(e.coefficients[n],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){let n=this.coefficients;for(let r=0;r<9;r++)n[r].fromArray(e,t+r*3);return this}toArray(e=[],t=0){let n=this.coefficients;for(let r=0;r<9;r++)n[r].toArray(e,t+r*3);return e}static getBasisAt(e,t){let n=e.x,r=e.y,i=e.z;t[0]=.282095,t[1]=.488603*r,t[2]=.488603*i,t[3]=.488603*n,t[4]=1.092548*n*r,t[5]=1.092548*r*i,t[6]=.315392*(3*i*i-1),t[7]=1.092548*n*i,t[8]=.546274*(n*n-r*r)}},Uu=class extends yu{constructor(e=new Hu,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){let t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}},Wu={},Gu=class e extends cu{constructor(e){super(e),this.textures={}}load(e,t,n,r){let i=this,a=new du(i.manager);a.setPath(i.path),a.setRequestHeader(i.requestHeader),a.setWithCredentials(i.withCredentials),a.load(e,function(n){try{t(i.parse(JSON.parse(n)))}catch(t){r?r(t):F(t),i.manager.itemError(e)}},n,r)}parse(e){let t=this.createMaterialFromType(e.type);return t.fromJSON(e,this.textures),t}setTextures(e){return this.textures=e,this}createMaterialFromType(t){return e.createMaterialFromType(t)}static createMaterialFromType(e){let t={ShadowMaterial:gl,SpriteMaterial:oa,RawShaderMaterial:El,ShaderMaterial:Tl,PointsMaterial:ss,MeshPhysicalMaterial:Ol,MeshStandardMaterial:Dl,MeshPhongMaterial:kl,MeshToonMaterial:Al,MeshNormalMaterial:jl,MeshLambertMaterial:Ml,MeshDepthMaterial:Nl,MeshDistanceMaterial:Pl,MeshBasicMaterial:Na,MeshMatcapMaterial:Fl,LineDashedMaterial:Il,LineBasicMaterial:qo,Material:aa,...Wu}[e],n;return t===void 0?(mn(`MaterialLoader: Unknown material type "${e}". Use .registerMaterial() before starting the deserialization process.`),n=new aa):n=new t,n}static registerMaterial(e,t){Wu[e]=t}},Ku=class{static extractUrlBase(e){let t=e.lastIndexOf(`/`);return t===-1?`./`:e.slice(0,t+1)}static resolveURL(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},qu=class extends W{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type=`InstancedBufferGeometry`,this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){let e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}},Ju=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new du(i.manager);a.setPath(i.path),a.setRequestHeader(i.requestHeader),a.setWithCredentials(i.withCredentials),a.load(e,function(n){try{t(i.parse(JSON.parse(n)))}catch(t){r?r(t):F(t),i.manager.itemError(e)}},n,r)}parse(e){let t={},n={};function r(e,n){if(t[n]!==void 0)return t[n];let r=e.interleavedBuffers[n],a=i(e,r.buffer),o=new ta(rn(r.type,a),r.stride);return o.uuid=r.uuid,t[n]=o,o}function i(e,t){if(n[t]!==void 0)return n[t];let r=e.arrayBuffers[t],i=new Uint32Array(r).buffer;return n[t]=i,i}let a=e.isInstancedBufferGeometry?new qu:new W,o=e.data.index;if(o!==void 0){let e=rn(o.type,o.array);a.setIndex(new Fi(e,1))}let s=e.data.attributes;for(let t in s){let n=s[t],i;if(n.isInterleavedBufferAttribute)i=new ra(r(e.data,n.data),n.itemSize,n.offset,n.normalized);else{let e=rn(n.type,n.array);i=new(n.isInstancedBufferAttribute?co:Fi)(e,n.itemSize,n.normalized)}n.name!==void 0&&(i.name=n.name),n.usage!==void 0&&i.setUsage(n.usage),a.setAttribute(t,i)}let c=e.data.morphAttributes;if(c)for(let t in c){let n=c[t],i=[];for(let t=0,a=n.length;t<a;t++){let a=n[t],o;o=a.isInterleavedBufferAttribute?new ra(r(e.data,a.data),a.itemSize,a.offset,a.normalized):new Fi(rn(a.type,a.array),a.itemSize,a.normalized),a.name!==void 0&&(o.name=a.name),i.push(o)}a.morphAttributes[t]=i}e.data.morphTargetsRelative&&(a.morphTargetsRelative=!0);let l=e.data.groups||e.data.drawcalls||e.data.offsets;if(l!==void 0)for(let e=0,t=l.length;e!==t;++e){let t=l[e];a.addGroup(t.start,t.count,t.materialIndex)}let u=e.data.boundingSphere;return u!==void 0&&(a.boundingSphere=new qi().fromJSON(u)),e.name&&(a.name=e.name),e.userData&&(a.userData=e.userData),a}},Yu={},Xu=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=this.path===``?Ku.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||a;let o=new du(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(n){let a=null;try{a=JSON.parse(n)}catch(t){r!==void 0&&r(t),F(`ObjectLoader: Can't parse `+e+`.`,t.message);return}let o=a.metadata;if(o===void 0||o.type===void 0||o.type.toLowerCase()===`geometry`){r!==void 0&&r(Error(`THREE.ObjectLoader: Can't load `+e)),F(`ObjectLoader: Can't load `+e);return}i.parse(a,t)},n,r)}async loadAsync(e,t){let n=this,r=this.path===``?Ku.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||r;let i=new du(this.manager);i.setPath(this.path),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials);let a=await i.loadAsync(e,t),o;try{o=JSON.parse(a)}catch(t){throw Error(`THREE.ObjectLoader: Can't parse `+e+`. `+t.message)}let s=o.metadata;if(s===void 0||s.type===void 0||s.type.toLowerCase()===`geometry`)throw Error(`THREE.ObjectLoader: Can't load `+e);return await n.parseAsync(o)}parse(e,t){let n=this.parseAnimations(e.animations),r=this.parseShapes(e.shapes),i=this.parseGeometries(e.geometries,r),a=this.parseImages(e.images,function(){t!==void 0&&t(c)}),o=this.parseTextures(e.textures,a),s=this.parseMaterials(e.materials,o),c=this.parseObject(e.object,i,s,o,n),l=this.parseSkeletons(e.skeletons,c);if(this.bindSkeletons(c,l),this.bindLightTargets(c),t!==void 0){let e=!1;for(let t in a)if(a[t].data instanceof HTMLImageElement){e=!0;break}e===!1&&t(c)}return c}async parseAsync(e){let t=this.parseAnimations(e.animations),n=this.parseShapes(e.shapes),r=this.parseGeometries(e.geometries,n),i=await this.parseImagesAsync(e.images),a=this.parseTextures(e.textures,i),o=this.parseMaterials(e.materials,a),s=this.parseObject(e.object,r,o,a,t),c=this.parseSkeletons(e.skeletons,s);return this.bindSkeletons(s,c),this.bindLightTargets(s),s}static registerGeometry(e,t){Yu[e]=t}parseShapes(e){let t={};if(e!==void 0)for(let n=0,r=e.length;n<r;n++){let r=new mc().fromJSON(e[n]);t[r.uuid]=r}return t}parseSkeletons(e,t){let n={},r={};if(t.traverse(function(e){e.isBone&&(r[e.uuid]=e)}),e!==void 0)for(let t=0,i=e.length;t<i;t++){let i=new G().fromJSON(e[t],r);n[i.uuid]=i}return n}parseGeometries(e,t){let n={};if(e!==void 0){let r=new Ju;for(let i=0,a=e.length;i<a;i++){let a,o=e[i];switch(o.type){case`BufferGeometry`:case`InstancedBufferGeometry`:a=r.parse(o);break;default:o.type in hl?a=hl[o.type].fromJSON(o,t):o.type in Yu?a=Yu[o.type].fromJSON(o,t):P(`ObjectLoader: Unknown geometry type "${o.type}". Use .registerGeometry() before starting the deserialization process.`)}a.uuid=o.uuid,o.name!==void 0&&(a.name=o.name),o.userData!==void 0&&(a.userData=o.userData),n[o.uuid]=a}}return n}parseMaterials(e,t){let n={},r={};if(e!==void 0){let i=new Gu;i.setTextures(t);for(let t=0,a=e.length;t<a;t++){let a=e[t];n[a.uuid]===void 0&&(n[a.uuid]=i.parse(a)),r[a.uuid]=n[a.uuid]}}return r}parseAnimations(e){let t={};if(e!==void 0)for(let n=0;n<e.length;n++){let r=e[n],i=tu.parse(r);t[i.uuid]=i}return t}parseImages(e,t){let n=this,r={},i;function a(e){return e=n.manager.resolveURL(e),n.manager.itemStart(e),i.load(e,function(){n.manager.itemEnd(e)},void 0,function(){n.manager.itemError(e),n.manager.itemEnd(e)})}function o(e){if(typeof e==`string`){let t=e;return a(/^(\/\/)|([a-z]+:(\/\/)?)/i.test(t)?t:n.resourcePath+t)}return e.data?{data:rn(e.type,e.data),width:e.width,height:e.height}:null}if(e!==void 0&&e.length>0){i=new hu(new ou(t)),i.setCrossOrigin(this.crossOrigin);for(let t=0,n=e.length;t<n;t++){let n=e[t],i=n.url;if(Array.isArray(i)){let e=[];for(let t=0,n=i.length;t<n;t++){let n=i[t],r=o(n);r!==null&&(r instanceof HTMLImageElement?e.push(r):e.push(new ao(r.data,r.width,r.height)))}r[n.uuid]=new nr(e)}else{let e=o(n.url);r[n.uuid]=new nr(e)}}}return r}async parseImagesAsync(e){let t=this,n={},r;async function i(e){if(typeof e==`string`){let n=e,i=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(n)?n:t.resourcePath+n;return await r.loadAsync(i)}return e.data?{data:rn(e.type,e.data),width:e.width,height:e.height}:null}if(e!==void 0&&e.length>0){r=new hu(this.manager),r.setCrossOrigin(this.crossOrigin);for(let t=0,r=e.length;t<r;t++){let r=e[t],a=r.url;if(Array.isArray(a)){let e=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=await i(n);r!==null&&(r instanceof HTMLImageElement?e.push(r):e.push(new ao(r.data,r.width,r.height)))}n[r.uuid]=new nr(e)}else{let e=await i(r.url);n[r.uuid]=new nr(e)}}}return n}parseTextures(e,t){function n(e,t){return typeof e==`number`?e:(P(`ObjectLoader.parseTexture: Constant should be in numeric form.`,e),t[e])}let r={};if(e!==void 0)for(let i=0,a=e.length;i<a;i++){let a=e[i];a.image===void 0&&P(`ObjectLoader: No "image" specified for`,a.uuid),t[a.image]===void 0&&P(`ObjectLoader: Undefined image`,a.image);let o=t[a.image],s=o.data,c;Array.isArray(s)?(c=new bs,s.length===6&&(c.needsUpdate=!0)):(c=s&&s.data?new ao:new or,s&&(c.needsUpdate=!0)),c.source=o,c.uuid=a.uuid,a.name!==void 0&&(c.name=a.name),a.mapping!==void 0&&(c.mapping=n(a.mapping,Zu)),a.channel!==void 0&&(c.channel=a.channel),a.offset!==void 0&&c.offset.fromArray(a.offset),a.repeat!==void 0&&c.repeat.fromArray(a.repeat),a.center!==void 0&&c.center.fromArray(a.center),a.rotation!==void 0&&(c.rotation=a.rotation),a.wrap!==void 0&&(c.wrapS=n(a.wrap[0],Qu),c.wrapT=n(a.wrap[1],Qu)),a.format!==void 0&&(c.format=a.format),a.internalFormat!==void 0&&(c.internalFormat=a.internalFormat),a.type!==void 0&&(c.type=a.type),a.colorSpace!==void 0&&(c.colorSpace=a.colorSpace),a.minFilter!==void 0&&(c.minFilter=n(a.minFilter,$u)),a.magFilter!==void 0&&(c.magFilter=n(a.magFilter,$u)),a.anisotropy!==void 0&&(c.anisotropy=a.anisotropy),a.flipY!==void 0&&(c.flipY=a.flipY),a.generateMipmaps!==void 0&&(c.generateMipmaps=a.generateMipmaps),a.premultiplyAlpha!==void 0&&(c.premultiplyAlpha=a.premultiplyAlpha),a.unpackAlignment!==void 0&&(c.unpackAlignment=a.unpackAlignment),a.compareFunction!==void 0&&(c.compareFunction=a.compareFunction),a.normalized!==void 0&&(c.normalized=a.normalized),a.userData!==void 0&&(c.userData=a.userData),r[a.uuid]=c}return r}parseObject(e,t,n,r,i){let a;function o(e){return t[e]===void 0&&P(`ObjectLoader: Undefined geometry`,e),t[e]}function s(e){if(e!==void 0){if(Array.isArray(e)){let t=[];for(let r=0,i=e.length;r<i;r++){let i=e[r];n[i]===void 0&&P(`ObjectLoader: Undefined material`,i),t.push(n[i])}return t}return n[e]===void 0&&P(`ObjectLoader: Undefined material`,e),n[e]}}function c(e){return r[e]===void 0&&P(`ObjectLoader: Undefined texture`,e),r[e]}let l,u;switch(e.type){case`Scene`:a=new Zr,e.background!==void 0&&(Number.isInteger(e.background)?a.background=new H(e.background):a.background=c(e.background)),e.environment!==void 0&&(a.environment=c(e.environment)),e.fog!==void 0&&(e.fog.type===`Fog`?a.fog=new Xr(e.fog.color,e.fog.near,e.fog.far):e.fog.type===`FogExp2`&&(a.fog=new Yr(e.fog.color,e.fog.density)),e.fog.name!==``&&(a.fog.name=e.fog.name)),e.backgroundBlurriness!==void 0&&(a.backgroundBlurriness=e.backgroundBlurriness),e.backgroundIntensity!==void 0&&(a.backgroundIntensity=e.backgroundIntensity),e.backgroundRotation!==void 0&&a.backgroundRotation.fromArray(e.backgroundRotation),e.environmentIntensity!==void 0&&(a.environmentIntensity=e.environmentIntensity),e.environmentRotation!==void 0&&a.environmentRotation.fromArray(e.environmentRotation);break;case`PerspectiveCamera`:a=new Mu(e.fov,e.aspect,e.near,e.far),e.focus!==void 0&&(a.focus=e.focus),e.zoom!==void 0&&(a.zoom=e.zoom),e.filmGauge!==void 0&&(a.filmGauge=e.filmGauge),e.filmOffset!==void 0&&(a.filmOffset=e.filmOffset),e.view!==void 0&&(a.view=Object.assign({},e.view));break;case`OrthographicCamera`:a=new Lu(e.left,e.right,e.top,e.bottom,e.near,e.far),e.zoom!==void 0&&(a.zoom=e.zoom),e.view!==void 0&&(a.view=Object.assign({},e.view));break;case`AmbientLight`:a=new Bu(e.color,e.intensity);break;case`DirectionalLight`:a=new zu(e.color,e.intensity),a.target=e.target||``;break;case`PointLight`:a=new Iu(e.color,e.intensity,e.distance,e.decay);break;case`RectAreaLight`:a=new Vu(e.color,e.intensity,e.width,e.height);break;case`SpotLight`:a=new Pu(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay),a.target=e.target||``;break;case`HemisphereLight`:a=new bu(e.color,e.groundColor,e.intensity);break;case`LightProbe`:a=new Uu(new Hu().fromArray(e.sh),e.intensity);break;case`SkinnedMesh`:l=o(e.geometry),u=s(e.material),a=new ro(l,u),e.bindMode!==void 0&&(a.bindMode=e.bindMode),e.bindMatrix!==void 0&&a.bindMatrix.fromArray(e.bindMatrix),e.skeleton!==void 0&&(a.skeleton=e.skeleton);break;case`Mesh`:l=o(e.geometry),u=s(e.material),a=new Ga(l,u);break;case`InstancedMesh`:l=o(e.geometry),u=s(e.material);let t=e.count,n=e.instanceMatrix,r=e.instanceColor;a=new _o(l,u,t),a.instanceMatrix=new co(new Float32Array(n.array),16),r!==void 0&&(a.instanceColor=new co(new Float32Array(r.array),r.itemSize));break;case`BatchedMesh`:l=o(e.geometry),u=s(e.material),a=new Ko(e.maxInstanceCount,e.maxVertexCount,e.maxIndexCount,u),a.geometry=l,a.perObjectFrustumCulled=e.perObjectFrustumCulled,a.sortObjects=e.sortObjects,a._drawRanges=e.drawRanges,a._reservedRanges=e.reservedRanges,a._geometryInfo=e.geometryInfo.map(e=>{let t=null,n=null;return e.boundingBox!==void 0&&(t=new fi().fromJSON(e.boundingBox)),e.boundingSphere!==void 0&&(n=new qi().fromJSON(e.boundingSphere)),{...e,boundingBox:t,boundingSphere:n}}),a._instanceInfo=e.instanceInfo,a._availableInstanceIds=e._availableInstanceIds,a._availableGeometryIds=e._availableGeometryIds,a._nextIndexStart=e.nextIndexStart,a._nextVertexStart=e.nextVertexStart,a._geometryCount=e.geometryCount,a._maxInstanceCount=e.maxInstanceCount,a._maxVertexCount=e.maxVertexCount,a._maxIndexCount=e.maxIndexCount,a._geometryInitialized=e.geometryInitialized,a._matricesTexture=c(e.matricesTexture.uuid),a._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(a._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(a.boundingSphere=new qi().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(a.boundingBox=new fi().fromJSON(e.boundingBox));break;case`LOD`:a=new wa;break;case`Line`:a=new ts(o(e.geometry),s(e.material));break;case`LineLoop`:a=new os(o(e.geometry),s(e.material));break;case`LineSegments`:a=new as(o(e.geometry),s(e.material));break;case`PointCloud`:case`Points`:a=new fs(o(e.geometry),s(e.material));break;case`Sprite`:a=new ba(s(e.material));break;case`Group`:a=new Vr;break;case`Bone`:a=new io;break;default:a=new Br}if(a.uuid=e.uuid,e.name!==void 0&&(a.name=e.name),e.matrix===void 0?(e.position!==void 0&&a.position.fromArray(e.position),e.rotation!==void 0&&a.rotation.fromArray(e.rotation),e.quaternion!==void 0&&a.quaternion.fromArray(e.quaternion),e.scale!==void 0&&a.scale.fromArray(e.scale)):(a.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(a.matrixAutoUpdate=e.matrixAutoUpdate),a.matrixAutoUpdate&&a.matrix.decompose(a.position,a.quaternion,a.scale)),e.up!==void 0&&a.up.fromArray(e.up),e.pivot!==void 0&&(a.pivot=new B().fromArray(e.pivot)),e.morphTargetDictionary!==void 0&&(a.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),e.morphTargetInfluences!==void 0&&(a.morphTargetInfluences=e.morphTargetInfluences.slice()),e.castShadow!==void 0&&(a.castShadow=e.castShadow),e.receiveShadow!==void 0&&(a.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(a.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(a.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(a.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(a.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&a.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(a.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(a.visible=e.visible),e.frustumCulled!==void 0&&(a.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(a.renderOrder=e.renderOrder),e.static!==void 0&&(a.static=e.static),e.userData!==void 0&&(a.userData=e.userData),e.layers!==void 0&&(a.layers.mask=e.layers),e.children!==void 0){let o=e.children;for(let e=0;e<o.length;e++)a.add(this.parseObject(o[e],t,n,r,i))}if(e.animations!==void 0){let t=e.animations;for(let e=0;e<t.length;e++){let n=t[e];a.animations.push(i[n])}}if(e.type===`LOD`){e.autoUpdate!==void 0&&(a.autoUpdate=e.autoUpdate);let t=e.levels;for(let e=0;e<t.length;e++){let n=t[e],r=a.getObjectByProperty(`uuid`,n.object);r!==void 0&&a.addLevel(r,n.distance,n.hysteresis)}}return a}bindSkeletons(e,t){Object.keys(t).length!==0&&e.traverse(function(e){if(e.isSkinnedMesh===!0&&e.skeleton!==void 0){let n=t[e.skeleton];n===void 0?P(`ObjectLoader: No skeleton found with UUID:`,e.skeleton):e.bind(n,e.bindMatrix)}})}bindLightTargets(e){e.traverse(function(t){if(t.isDirectionalLight||t.isSpotLight){let n=t.target,r=e.getObjectByProperty(`uuid`,n);t.target=r===void 0?new Br:r}})}},Zu={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,CubeUVReflectionMapping:306},Qu={RepeatWrapping:D,ClampToEdgeWrapping:O,MirroredRepeatWrapping:ee},$u={NearestFilter:k,NearestMipmapNearestFilter:te,NearestMipmapLinearFilter:re,LinearFilter:A,LinearMipmapNearestFilter:j,LinearMipmapLinearFilter:ae},ed=new WeakMap,td=class extends cu{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>`u`&&P(`ImageBitmapLoader: createImageBitmap() not supported.`),typeof fetch>`u`&&P(`ImageBitmapLoader: fetch() not supported.`),this.options={premultiplyAlpha:`none`},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=iu.get(`image-bitmap:${e}`);if(a!==void 0){if(i.manager.itemStart(e),a.then){a.then(n=>{ed.has(a)===!0?(r&&r(ed.get(a)),i.manager.itemError(e),i.manager.itemEnd(e)):(t&&t(n),i.manager.itemEnd(e))});return}setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);return}let o={};o.credentials=this.crossOrigin===`anonymous`?`same-origin`:`include`,o.headers=this.requestHeader,o.signal=typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let s=fetch(e,o).then(function(e){return e.blob()}).then(function(e){return createImageBitmap(e,Object.assign(i.options,{colorSpaceConversion:`none`}))}).then(function(n){iu.add(`image-bitmap:${e}`,n),t&&t(n),i.manager.itemEnd(e)}).catch(function(t){r&&r(t),ed.set(s,t),iu.remove(`image-bitmap:${e}`),i.manager.itemError(e),i.manager.itemEnd(e)});iu.add(`image-bitmap:${e}`,s),i.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},nd,rd=class{static getContext(){return nd===void 0&&(nd=new(window.AudioContext||window.webkitAudioContext)),nd}static setContext(e){nd=e}},id=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new du(this.manager);a.setResponseType(`arraybuffer`),a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(n){try{let r=n.slice(0),a=rd.getContext(),s=e+`#decode`;i.manager.itemStart(s),a.decodeAudioData(r,function(e){t(e),i.manager.itemEnd(s)}).catch(function(e){o(e),i.manager.itemEnd(s)})}catch(e){o(e)}},n,r);function o(t){r?r(t):F(t),i.manager.itemError(e)}}},ad=new V,od=new V,sd=new V,cd=class{constructor(){this.type=`StereoCamera`,this.aspect=1,this.eyeSep=.064,this.cameraL=new Mu,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Mu,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){let t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,sd.copy(e.projectionMatrix);let n=t.eyeSep/2,r=n*t.near/t.focus,i=t.near*Math.tan(bn*t.fov*.5)/t.zoom,a,o;od.elements[12]=-n,ad.elements[12]=n,a=-i*t.aspect+r,o=i*t.aspect+r,sd.elements[0]=2*t.near/(o-a),sd.elements[8]=(o+a)/(o-a),this.cameraL.projectionMatrix.copy(sd),a=-i*t.aspect-r,o=i*t.aspect-r,sd.elements[0]=2*t.near/(o-a),sd.elements[8]=(o+a)/(o-a),this.cameraR.projectionMatrix.copy(sd)}this.cameraL.matrix.copy(e.matrixWorld).multiply(od),this.cameraL.matrixWorldNeedsUpdate=!0,this.cameraR.matrix.copy(e.matrixWorld).multiply(ad),this.cameraR.matrixWorldNeedsUpdate=!0}},ld=-90,ud=1,dd=class extends Br{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new Mu(ld,ud,e,t);r.layers=this.layers,this.add(r);let i=new Mu(ld,ud,e,t);i.layers=this.layers,this.add(i);let a=new Mu(ld,ud,e,t);a.layers=this.layers,this.add(a);let o=new Mu(ld,ud,e,t);o.layers=this.layers,this.add(o);let s=new Mu(ld,ud,e,t);s.layers=this.layers,this.add(s);let c=new Mu(ld,ud,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},fd=class extends Mu{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},pd=class{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=md.bind(this),e.addEventListener(`visibilitychange`,this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener(`visibilitychange`,this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e===void 0?performance.now():e)-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function md(){this._document.hidden===!1&&this.reset()}var hd=new B,gd=new z,_d=new B,vd=new B,yd=new B,bd=class extends Br{constructor(){super(),this.type=`AudioListener`,this.context=rd.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._timer=new pd}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter===null?this.gain.disconnect(this.context.destination):(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e),this._timer.update();let t=this.context.listener;if(this.timeDelta=this._timer.getDelta(),this.matrixWorld.decompose(hd,gd,_d),vd.set(0,0,-1).applyQuaternion(gd),yd.set(0,1,0).applyQuaternion(gd),t.positionX){let e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(hd.x,e),t.positionY.linearRampToValueAtTime(hd.y,e),t.positionZ.linearRampToValueAtTime(hd.z,e),t.forwardX.linearRampToValueAtTime(vd.x,e),t.forwardY.linearRampToValueAtTime(vd.y,e),t.forwardZ.linearRampToValueAtTime(vd.z,e),t.upX.linearRampToValueAtTime(yd.x,e),t.upY.linearRampToValueAtTime(yd.y,e),t.upZ.linearRampToValueAtTime(yd.z,e)}else t.setPosition(hd.x,hd.y,hd.z),t.setOrientation(vd.x,vd.y,vd.z,yd.x,yd.y,yd.z)}},xd=class extends Br{constructor(e){super(),this.type=`Audio`,this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType=`empty`,this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType=`audioNode`,this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType=`mediaNode`,this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType=`mediaStreamNode`,this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType=`buffer`,this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){P(`Audio: Audio is already playing.`);return}if(this.hasPlaybackControl===!1){P(`Audio: this Audio has no playback control.`);return}this._startedAt=this.context.currentTime+e;let t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){P(`Audio: this Audio has no playback control.`);return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress%=this.duration||this.buffer.duration),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){P(`Audio: this Audio has no playback control.`);return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].connect(this.filters[e]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this._connected=!0,this}disconnect(){if(this._connected!==!1){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].disconnect(this.filters[e]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this._connected=!1,this}}getFilters(){return this.filters}setFilters(e){return e||=[],this._connected===!0?(this.disconnect(),this.filters=e.slice(),this.connect()):this.filters=e.slice(),this}setDetune(e){return this.detune=e,this.isPlaying===!0&&this.source.detune!==void 0&&this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,.01),this}getDetune(){return this.detune}getFilter(){return this.getFilters()[0]}setFilter(e){return this.setFilters(e?[e]:[])}setPlaybackRate(e){if(this.hasPlaybackControl===!1){P(`Audio: this Audio has no playback control.`);return}return this.playbackRate=e,this.isPlaying===!0&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1,this._progress=0}getLoop(){return this.hasPlaybackControl===!1?(P(`Audio: this Audio has no playback control.`),!1):this.loop}setLoop(e){if(this.hasPlaybackControl===!1){P(`Audio: this Audio has no playback control.`);return}return this.loop=e,this.isPlaying===!0&&(this.source.loop=this.loop),this}setLoopStart(e){return this.loopStart=e,this}setLoopEnd(e){return this.loopEnd=e,this}getVolume(){return this.gain.gain.value}setVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}copy(e,t){return super.copy(e,t),e.sourceType===`buffer`?(this.autoplay=e.autoplay,this.buffer=e.buffer,this.detune=e.detune,this.loop=e.loop,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.offset=e.offset,this.duration=e.duration,this.playbackRate=e.playbackRate,this.hasPlaybackControl=e.hasPlaybackControl,this.sourceType=e.sourceType,this.filters=e.filters.slice(),this):(P(`Audio: Audio source type cannot be copied.`),this)}clone(e){return new this.constructor(this.listener).copy(this,e)}},Sd=new B,Cd=new z,J=new B,wd=new B,Td=class extends xd{constructor(e){super(e),this.panner=this.context.createPanner(),this.panner.panningModel=`HRTF`,this.panner.connect(this.gain)}connect(){return super.connect(),this.panner.connect(this.gain),this}disconnect(){return super.disconnect(),this.panner.disconnect(this.gain),this}getOutput(){return this.panner}getRefDistance(){return this.panner.refDistance}setRefDistance(e){return this.panner.refDistance=e,this}getRolloffFactor(){return this.panner.rolloffFactor}setRolloffFactor(e){return this.panner.rolloffFactor=e,this}getDistanceModel(){return this.panner.distanceModel}setDistanceModel(e){return this.panner.distanceModel=e,this}getMaxDistance(){return this.panner.maxDistance}setMaxDistance(e){return this.panner.maxDistance=e,this}setDirectionalCone(e,t,n){return this.panner.coneInnerAngle=e,this.panner.coneOuterAngle=t,this.panner.coneOuterGain=n,this}updateMatrixWorld(e){if(super.updateMatrixWorld(e),this.hasPlaybackControl===!0&&this.isPlaying===!1)return;this.matrixWorld.decompose(Sd,Cd,J),wd.set(0,0,1).applyQuaternion(Cd);let t=this.panner;if(t.positionX){let e=this.context.currentTime+this.listener.timeDelta;t.positionX.linearRampToValueAtTime(Sd.x,e),t.positionY.linearRampToValueAtTime(Sd.y,e),t.positionZ.linearRampToValueAtTime(Sd.z,e),t.orientationX.linearRampToValueAtTime(wd.x,e),t.orientationY.linearRampToValueAtTime(wd.y,e),t.orientationZ.linearRampToValueAtTime(wd.z,e)}else t.setPosition(Sd.x,Sd.y,Sd.z),t.setOrientation(wd.x,wd.y,wd.z)}},Ed=class{constructor(e,t=2048){this.analyser=e.context.createAnalyser(),this.analyser.fftSize=t,this.data=new Uint8Array(this.analyser.frequencyBinCount),e.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let e=0,t=this.getFrequencyData();for(let n=0;n<t.length;n++)e+=t[n];return e/t.length}},Dd=class{constructor(e,t,n){this.binding=e,this.valueSize=n;let r,i,a;switch(t){case`quaternion`:r=this._slerp,i=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case`string`:case`bool`:r=this._select,i=this._select,a=this._setAdditiveIdentityOther,this.buffer=Array(n*5);break;default:r=this._lerp,i=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=r,this._mixBufferRegionAdditive=i,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let n=this.buffer,r=this.valueSize,i=e*r+r,a=this.cumulativeWeight;if(a===0){for(let e=0;e!==r;++e)n[i+e]=n[e];a=t}else{a+=t;let e=t/a;this._mixBufferRegion(n,i,0,e,r)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,r=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,r,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,r=e*t+t,i=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,i<1){let e=t*this._origIndex;this._mixBufferRegion(n,r,e,1-i,t)}a>0&&this._mixBufferRegionAdditive(n,r,this._addIndex*t,1,t);for(let e=t,i=t+t;e!==i;++e)if(n[e]!==n[e+t]){o.setValue(n,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,r=n*this._origIndex;e.getValue(t,r);for(let e=n,i=r;e!==i;++e)t[e]=t[r+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n<t;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[t+n]=this.buffer[e+n]}_select(e,t,n,r,i){if(r>=.5)for(let r=0;r!==i;++r)e[t+r]=e[n+r]}_slerp(e,t,n,r){z.slerpFlat(e,t,e,t,e,n,r)}_slerpAdditive(e,t,n,r,i){let a=this._workIndex*i;z.multiplyQuaternionsFlat(e,a,e,t,e,n),z.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,n,r,i){let a=1-r;for(let o=0;o!==i;++o){let i=t+o;e[i]=e[i]*a+e[n+o]*r}}_lerpAdditive(e,t,n,r,i){for(let a=0;a!==i;++a){let i=t+a;e[i]=e[i]+e[n+a]*r}}},Od=`\\[\\]\\.:\\/`,kd=RegExp(`[\\[\\]\\.:\\/]`,`g`),Ad=`[^\\[\\]\\.:\\/]`,jd=`[^`+Od.replace(`\\.`,``)+`]`,Md=`((?:WC+[\\/:])*)`.replace(`WC`,Ad),Nd=`(WCOD+)?`.replace(`WCOD`,jd),Pd=`(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,Ad),Fd=`\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,Ad),Id=RegExp(`^`+Md+Nd+Pd+Fd+`$`),Ld=[`material`,`materials`,`bones`,`map`],Rd=class{constructor(e,t,n){let r=n||Y.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},Y=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(kd,``)}static parseTrackName(e){let t=Id.exec(e);if(t===null)throw Error(`THREE.PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);Ld.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`THREE.PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){P(`PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){F(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){F(`PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){F(`PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){F(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){F(`PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){F(`PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){F(`PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;F(`PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){F(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){F(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};Y.Composite=Rd,Y.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Y.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Y.prototype.GetterByBindingType=[Y.prototype._getValue_direct,Y.prototype._getValue_array,Y.prototype._getValue_arrayElement,Y.prototype._getValue_toArray],Y.prototype.SetterByBindingTypeAndVersioning=[[Y.prototype._setValue_direct,Y.prototype._setValue_direct_setNeedsUpdate,Y.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Y.prototype._setValue_array,Y.prototype._setValue_array_setNeedsUpdate,Y.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Y.prototype._setValue_arrayElement,Y.prototype._setValue_arrayElement_setNeedsUpdate,Y.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Y.prototype._setValue_fromArray,Y.prototype._setValue_fromArray_setNeedsUpdate,Y.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var zd=class{constructor(){this.isAnimationObjectGroup=!0,this.uuid=Sn(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;let e={};this._indicesByUUID=e;for(let t=0,n=arguments.length;t!==n;++t)e[arguments[t].uuid]=t;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};let t=this;this.stats={objects:{get total(){return t._objects.length},get inUse(){return this.total-t.nCachedObjects_}},get bindingsPerObject(){return t._bindings.length}}}add(){let e=this._objects,t=this._indicesByUUID,n=this._paths,r=this._parsedPaths,i=this._bindings,a=i.length,o,s=e.length,c=this.nCachedObjects_;for(let l=0,u=arguments.length;l!==u;++l){let u=arguments[l],d=u.uuid,f=t[d];if(f===void 0){f=s++,t[d]=f,e.push(u);for(let e=0,t=a;e!==t;++e)i[e].push(new Y(u,n[e],r[e]))}else if(f<c){o=e[f];let s=--c,l=e[s];t[l.uuid]=f,e[f]=l,t[d]=s,e[s]=u;for(let e=0,t=a;e!==t;++e){let t=i[e],a=t[s],o=t[f];t[f]=a,o===void 0&&(o=new Y(u,n[e],r[e])),t[s]=o}}else e[f]!==o&&F(`AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.`)}this.nCachedObjects_=c}remove(){let e=this._objects,t=this._indicesByUUID,n=this._bindings,r=n.length,i=this.nCachedObjects_;for(let a=0,o=arguments.length;a!==o;++a){let o=arguments[a],s=o.uuid,c=t[s];if(c!==void 0&&c>=i){let a=i++,l=e[a];t[l.uuid]=c,e[c]=l,t[s]=a,e[a]=o;for(let e=0,t=r;e!==t;++e){let t=n[e],r=t[a],i=t[c];t[c]=r,t[a]=i}}}this.nCachedObjects_=i}uncache(){let e=this._objects,t=this._indicesByUUID,n=this._bindings,r=n.length,i=this.nCachedObjects_,a=e.length;for(let o=0,s=arguments.length;o!==s;++o){let s=arguments[o].uuid,c=t[s];if(c!==void 0)if(delete t[s],c<i){let o=--i,s=e[o],l=--a,u=e[l];t[s.uuid]=c,e[c]=s,t[u.uuid]=o,e[o]=u,e.pop();for(let e=0,t=r;e!==t;++e){let t=n[e],r=t[o],i=t[l];t[c]=r,t[o]=i,t.pop()}}else{let i=--a,o=e[i];i>0&&(t[o.uuid]=c),e[c]=o,e.pop();for(let e=0,t=r;e!==t;++e){let t=n[e];t[c]=t[i],t.pop()}}}this.nCachedObjects_=i}subscribe_(e,t){let n=this._bindingsIndicesByPath,r=n[e],i=this._bindings;if(r!==void 0)return i[r];let a=this._paths,o=this._parsedPaths,s=this._objects,c=s.length,l=this.nCachedObjects_,u=Array(c);r=i.length,n[e]=r,a.push(e),o.push(t),i.push(u);for(let n=l,r=s.length;n!==r;++n){let r=s[n];u[n]=new Y(r,e,t)}return u}unsubscribe_(e){let t=this._bindingsIndicesByPath,n=t[e];if(n!==void 0){let r=this._paths,i=this._parsedPaths,a=this._bindings,o=a.length-1,s=a[o],c=e[o];t[c]=n,a[n]=s,a.pop(),i[n]=i[o],i.pop(),r[n]=r[o],r.pop()}}},Bd=class{constructor(e,t,n=null,r=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=r;let i=t.tracks,a=i.length,o=Array(a),s={endingStart:yt,endingEnd:yt};for(let e=0;e!==a;++e){let t=i[e].createInterpolant(null);o[e]=t,t.settings=s}this._interpolantSettings=s,this._interpolants=o,this._propertyBindings=Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._restoreTimeScale=null,this._weightInterpolant=null,this.loop=pt,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),n===!0){let n=this._clip.duration,r=e._clip.duration,i=r/n,a=n/r;e._restoreTimeScale=e.timeScale,this._restoreTimeScale=this.timeScale,e.warp(1,i,t),this.warp(a,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){let r=this._mixer,i=r.time,a=this.timeScale,o=this._timeScaleInterpolant;o===null&&(o=r._lendControlInterpolant(),this._timeScaleInterpolant=o);let s=o.parameterPositions,c=o.sampleValues;return s[0]=i,s[1]=i+n,c[0]=e/a,c[1]=t/a,this}stopWarping(){let e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this._restoreTimeScale=null,this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,r){if(!this.enabled){this._updateWeight(e);return}let i=this._startTime;if(i!==null){let r=(e-i)*n;r<0||n===0?t=0:(this._startTime=null,t=n*r)}t*=this._updateTimeScale(e);let a=this._updateTime(t),o=this._updateWeight(e);if(o>0){let e=this._interpolants,t=this._propertyBindings;switch(this.blendMode){case Ct:for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(a),t[n].accumulateAdditive(o);break;case St:default:for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(a),t[n].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(t===0?this.paused=!0:(this._restoreTimeScale!==null&&(t=this._restoreTimeScale),this.timeScale=t),this.stopWarping())}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,r=this.time+e,i=this._loopCount,a=n===mt;if(e===0)return i===-1?r:a&&(i&1)==1?t-r:r;if(n===2200){i===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));handle_stop:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break handle_stop}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e<0?-1:1})}}else{if(i===-1&&(e>=0?(i=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let n=Math.floor(r/t);r-=t*n,i+=Math.abs(n);let o=this.repetitions-i;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e>0?1:-1});else{if(o===1){let t=e<0;this._setEndings(t,!t,a)}else this._setEndings(!1,!1,a);this._loopCount=i,this.time=r,this._mixer.dispatchEvent({type:`loop`,action:this,loopDelta:n})}}else this._loopCount=i,this.time=r;if(a&&(i&1)==1)return t-r}return r}_setEndings(e,t,n){let r=this._interpolantSettings;n?(r.endingStart=bt,r.endingEnd=bt):(r.endingStart=e?this.zeroSlopeAtStart?bt:yt:xt,r.endingEnd=t?this.zeroSlopeAtEnd?bt:yt:xt)}_scheduleFading(e,t,n){let r=this._mixer,i=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,s=a.sampleValues;return o[0]=i,s[0]=t,o[1]=i+e,s[1]=n,this}},Vd=new Float32Array(1),Hd=class extends _n{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}_bindAction(e,t){let n=e._localRoot||this._root,r=e._clip.tracks,i=r.length,a=e._propertyBindings,o=e._interpolants,s=n.uuid,c=this._bindingsByRootAndName,l=c[s];l===void 0&&(l={},c[s]=l);for(let e=0;e!==i;++e){let i=r[e],c=i.name,u=l[c];if(u!==void 0)++u.referenceCount,a[e]=u;else{if(u=a[e],u!==void 0){u._cacheIndex===null&&(++u.referenceCount,this._addInactiveBinding(u,s,c));continue}let r=t&&t._propertyBindings[e].binding.parsedPath;u=new Dd(Y.create(n,c,r),i.ValueTypeName,i.getValueSize()),++u.referenceCount,this._addInactiveBinding(u,s,c),a[e]=u}o[e].resultBuffer=u.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let t=(e._localRoot||this._root).uuid,n=e._clip.uuid,r=this._actionsByClip[n];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,n,t)}let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];n.useCount++===0&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.useCount===0&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,n){let r=this._actions,i=this._actionsByClip,a=i[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,i[t]=a;else{let t=a.knownActions;e._byClipCacheIndex=t.length,t.push(e)}e._cacheIndex=r.length,r.push(e),a.actionByRoot[n]=e}_removeInactiveAction(e){let t=this._actions,n=t[t.length-1],r=e._cacheIndex;n._cacheIndex=r,t[r]=n,t.pop(),e._cacheIndex=null;let i=e._clip.uuid,a=this._actionsByClip,o=a[i],s=o.knownActions,c=s[s.length-1],l=e._byClipCacheIndex;c._byClipCacheIndex=l,s[l]=c,s.pop(),e._byClipCacheIndex=null;let u=o.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],s.length===0&&delete a[i],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.referenceCount===0&&this._removeInactiveBinding(n)}}_lendAction(e){let t=this._actions,n=e._cacheIndex,r=this._nActiveActions++,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_takeBackAction(e){let t=this._actions,n=e._cacheIndex,r=--this._nActiveActions,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_addInactiveBinding(e,t,n){let r=this._bindingsByRootAndName,i=this._bindings,a=r[t];a===void 0&&(a={},r[t]=a),a[n]=e,e._cacheIndex=i.length,i.push(e)}_removeInactiveBinding(e){let t=this._bindings,n=e.binding,r=n.rootNode.uuid,i=n.path,a=this._bindingsByRootAndName,o=a[r],s=t[t.length-1],c=e._cacheIndex;s._cacheIndex=c,t[c]=s,t.pop(),delete o[i],Object.keys(o).length===0&&delete a[r]}_lendBinding(e){let t=this._bindings,n=e._cacheIndex,r=this._nActiveBindings++,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_takeBackBinding(e){let t=this._bindings,n=e._cacheIndex,r=--this._nActiveBindings,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,n=e[t];return n===void 0&&(n=new Wl(new Float32Array(2),new Float32Array(2),1,Vd),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){let t=this._controlInterpolants,n=e.__cacheIndex,r=--this._nActiveControlInterpolants,i=t[r];e.__cacheIndex=r,t[r]=e,i.__cacheIndex=n,t[n]=i}clipAction(e,t,n){let r=t||this._root,i=r.uuid,a=typeof e==`string`?tu.findByName(r,e):e,o=a===null?e:a.uuid,s=this._actionsByClip[o],c=null;if(n===void 0&&(n=a===null?St:a.blendMode),s!==void 0){let e=s.actionByRoot[i];if(e!==void 0&&e.blendMode===n)return e;c=s.knownActions[0],a===null&&(a=c._clip)}if(a===null)return null;let l=new Bd(this,a,t,n);return this._bindAction(l,c),this._addInactiveAction(l,o,i),l}existingAction(e,t){let n=t||this._root,r=n.uuid,i=typeof e==`string`?tu.findByName(n,e):e,a=i?i.uuid:e,o=this._actionsByClip[a];return o===void 0?null:o.actionByRoot[r]||null}stopAllAction(){let e=this._actions,t=this._nActiveActions;for(let n=t-1;n>=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,r=this.time+=e,i=Math.sign(e),a=this._accuIndex^=1;for(let o=0;o!==n;++o)t[o]._update(r,e,i,a);let o=this._bindings,s=this._nActiveBindings;for(let e=0;e!==s;++e)o[e].apply(a);return this}setTime(e){this.time=0;for(let e=0;e<this._actions.length;e++)this._actions[e].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){let t=this._actions,n=e.uuid,r=this._actionsByClip,i=r[n];if(i!==void 0){let e=i.knownActions;for(let n=0,r=e.length;n!==r;++n){let r=e[n];this._deactivateAction(r);let i=r._cacheIndex,a=t[t.length-1];r._cacheIndex=null,r._byClipCacheIndex=null,a._cacheIndex=i,t[i]=a,t.pop(),this._removeInactiveBindingsForAction(r)}delete r[n]}}uncacheRoot(e){let t=e.uuid,n=this._actionsByClip;for(let e in n){let r=n[e].actionByRoot[t];r!==void 0&&(this._deactivateAction(r),this._removeInactiveAction(r))}let r=this._bindingsByRootAndName[t];if(r!==void 0)for(let e in r){let t=r[e];t.restoreOriginalState(),this._removeInactiveBinding(t)}}uncacheAction(e,t){let n=this.existingAction(e,t);n!==null&&(this._deactivateAction(n),this._removeInactiveAction(n))}},Ud=class extends cr{constructor(e=1,t=1,n=1,r={}){super(e,t,r),this.isRenderTarget3D=!0,this.depth=n,this.texture=new fr(null,e,t,n),this._setTextureOptions(r),this.texture.isRenderTargetTexture=!0}},Wd=class e{constructor(e){this.value=e}clone(){return new e(this.value.clone===void 0?this.value:this.value.clone())}},Gd=0,Kd=class extends _n{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:Gd++}),this.name=``,this.usage=zt,this.uniforms=[]}add(e){return this.uniforms.push(e),this}remove(e){let t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}setName(e){return this.name=e,this}setUsage(e){return this.usage=e,this}dispose(){this.dispatchEvent({type:`dispose`})}copy(e){this.name=e.name,this.usage=e.usage;let t=e.uniforms;this.uniforms.length=0;for(let e=0,n=t.length;e<n;e++){let n=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0;e<n.length;e++)this.uniforms.push(n[e].clone())}return this}clone(){return new this.constructor().copy(this)}},qd=class extends ta{constructor(e,t,n=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){let t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){let t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}},Jd=class{constructor(e,t,n,r,i,a=!1){this.isGLBufferAttribute=!0,this.name=``,this.buffer=e,this.type=t,this.itemSize=n,this.elementSize=r,this.count=i,this.normalized=a,this.version=0}set needsUpdate(e){e===!0&&this.version++}setBuffer(e){return this.buffer=e,this}setType(e,t){return this.type=e,this.elementSize=t,this}setItemSize(e){return this.itemSize=e,this}setCount(e){return this.count=e,this}},Yd=new V,Xd=class{constructor(e,t,n=0,r=1/0){this.ray=new Ma(e,t),this.near=n,this.far=r,this.camera=null,this.layers=new wr,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,t.projectionMatrix.elements[14]).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):F(`Raycaster: Unsupported camera type: `+t.type)}setFromXRController(e){return Yd.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(Yd),this}intersectObject(e,t=!0,n=[]){return Qd(e,this,n,t),n.sort(Zd),n}intersectObjects(e,t=!0,n=[]){for(let r=0,i=e.length;r<i;r++)Qd(e[r],this,n,t);return n.sort(Zd),n}};function Zd(e,t){return e.distance-t.distance}function Qd(e,t,n,r){let i=!0;if(e.layers.test(t.layers)&&e.raycast(t,n)===!1&&(i=!1),i===!0&&r===!0){let r=e.children;for(let e=0,i=r.length;e<i;e++)Qd(r[e],t,n,!0)}}var $d=class{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1,P(`Clock: This module has been deprecated. Please use THREE.Timer instead.`)}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){let t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}},ef=class{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){let e=1e-6;return this.phi=I(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(I(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}},tf=class{constructor(e=1,t=0,n=0){this.radius=e,this.theta=t,this.y=n}set(e,t,n){return this.radius=e,this.theta=t,this.y=n,this}copy(e){return this.radius=e.radius,this.theta=e.theta,this.y=e.y,this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+n*n),this.theta=Math.atan2(e,n),this.y=t,this}clone(){return new this.constructor().copy(this)}},nf=class e{static{e.prototype.isMatrix2=!0}constructor(e,t,n,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){let i=this.elements;return i[0]=e,i[2]=t,i[1]=n,i[3]=r,this}},rf=new R,af=class{constructor(e=new R(1/0,1/0),t=new R(-1/0,-1/0)){this.isBox2=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=rf.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y}getCenter(e){return this.isEmpty()?e.set(0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,rf).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}},of=new B,sf=new B,cf=new B,lf=new B,uf=new B,df=new B,ff=new B,pf=class{constructor(e=new B,t=new B){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){of.subVectors(e,this.start),sf.subVectors(this.end,this.start);let n=sf.dot(sf);if(n===0)return 0;let r=sf.dot(of)/n;return t&&(r=I(r,0,1)),r}closestPointToPoint(e,t,n){let r=this.closestPointToPointParameter(e,t);return this.delta(n).multiplyScalar(r).add(this.start)}distanceSqToLine3(e,t=df,n=ff){let r=1e-8*1e-8,i,a,o=this.start,s=e.start,c=this.end,l=e.end;cf.subVectors(c,o),lf.subVectors(l,s),uf.subVectors(o,s);let u=cf.dot(cf),d=lf.dot(lf),f=lf.dot(uf);if(u<=r&&d<=r)return t.copy(o),n.copy(s),t.sub(n),t.dot(t);if(u<=r)i=0,a=f/d,a=I(a,0,1);else{let e=cf.dot(uf);if(d<=r)a=0,i=I(-e/u,0,1);else{let t=cf.dot(lf),n=u*d-t*t;i=n===0?0:I((t*f-e*d)/n,0,1),a=(t*i+f)/d,a<0?(a=0,i=I(-e/u,0,1)):a>1&&(a=1,i=I((t-e)/u,0,1))}}return t.copy(o).addScaledVector(cf,i),n.copy(s).addScaledVector(lf,a),t.distanceToSquared(n)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}},mf=new B,hf=class extends Br{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type=`SpotLightHelper`;let n=new W,r=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let e=0,t=1;e<32;e++,t++){let n=e/32*Math.PI*2,i=t/32*Math.PI*2;r.push(Math.cos(n),Math.sin(n),1,Math.cos(i),Math.sin(i),1)}n.setAttribute(`position`,new U(r,3));let i=new qo({fog:!1,toneMapped:!1});this.cone=new as(n,i),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),this.parent?(this.parent.updateWorldMatrix(!0),this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)):this.matrix.copy(this.light.matrixWorld),this.matrixWorldNeedsUpdate=!0;let e=this.light.distance?this.light.distance:1e3,t=e*Math.tan(this.light.angle);this.cone.scale.set(t,t,e),mf.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(mf),this.color===void 0?this.cone.material.color.copy(this.light.color):this.cone.material.color.set(this.color)}},gf=new B,_f=new V,vf=new V,yf=class extends as{constructor(e){let t=bf(e),n=new W,r=[],i=[];for(let e=0;e<t.length;e++){let n=t[e];n.parent&&n.parent.isBone&&(r.push(0,0,0),r.push(0,0,0),i.push(0,0,0),i.push(0,0,0))}n.setAttribute(`position`,new U(r,3)),n.setAttribute(`color`,new U(i,3));let a=new qo({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});super(n,a),this.isSkeletonHelper=!0,this.type=`SkeletonHelper`,this.root=e,this.bones=t,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1;let o=new H(255),s=new H(65280);this.setColors(o,s)}updateMatrixWorld(e){let t=this.bones,n=this.geometry,r=n.getAttribute(`position`);vf.copy(this.root.matrixWorld).invert();for(let e=0,n=0;e<t.length;e++){let i=t[e];i.parent&&i.parent.isBone&&(_f.multiplyMatrices(vf,i.matrixWorld),gf.setFromMatrixPosition(_f),r.setXYZ(n,gf.x,gf.y,gf.z),_f.multiplyMatrices(vf,i.parent.matrixWorld),gf.setFromMatrixPosition(_f),r.setXYZ(n+1,gf.x,gf.y,gf.z),n+=2)}n.getAttribute(`position`).needsUpdate=!0,super.updateMatrixWorld(e)}setColors(e,t){let n=this.geometry.getAttribute(`color`);for(let r=0;r<n.count;r+=2)n.setXYZ(r,e.r,e.g,e.b),n.setXYZ(r+1,t.r,t.g,t.b);return n.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}};function bf(e){let t=[];e.isBone===!0&&t.push(e);for(let n=0;n<e.children.length;n++)t.push(...bf(e.children[n]));return t}var xf=class extends Ga{constructor(e,t,n){let r=new cl(t,4,2),i=new Na({wireframe:!0,fog:!1,toneMapped:!1});super(r,i),this.light=e,this.color=n,this.type=`PointLightHelper`,this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1,this.update()}dispose(){this.geometry.dispose(),this.material.dispose()}update(){this.matrixWorldNeedsUpdate=!0,this.light.updateWorldMatrix(!0,!1),this.color===void 0?this.material.color.copy(this.light.color):this.material.color.set(this.color)}},Sf=new B,Cf=new H,wf=new H,Tf=class extends Br{constructor(e,t,n){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=n,this.type=`HemisphereLightHelper`;let r=new rl(t);r.rotateY(Math.PI*.5),this.material=new Na({wireframe:!0,fog:!1,toneMapped:!1}),this.color===void 0&&(this.material.vertexColors=!0);let i=r.getAttribute(`position`),a=new Float32Array(i.count*3);r.setAttribute(`color`,new Fi(a,3)),this.add(new Ga(r,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){let e=this.children[0];if(this.color!==void 0)this.material.color.set(this.color);else{let t=e.geometry.getAttribute(`color`);Cf.copy(this.light.color),wf.copy(this.light.groundColor);for(let e=0,n=t.count;e<n;e++){let r=e<n/2?Cf:wf;t.setXYZ(e,r.r,r.g,r.b)}t.needsUpdate=!0}this.matrixWorldNeedsUpdate=!0,this.light.updateWorldMatrix(!0,!1),e.lookAt(Sf.setFromMatrixPosition(this.light.matrixWorld).negate())}},Ef=class extends as{constructor(e=10,t=10,n=4473924,r=8947848){n=new H(n),r=new H(r);let i=t/2,a=e/t,o=e/2,s=[],c=[];for(let e=0,l=0,u=-o;e<=t;e++,u+=a){s.push(-o,0,u,o,0,u),s.push(u,0,-o,u,0,o);let t=e===i?n:r;t.toArray(c,l),l+=3,t.toArray(c,l),l+=3,t.toArray(c,l),l+=3,t.toArray(c,l),l+=3}let l=new W;l.setAttribute(`position`,new U(s,3)),l.setAttribute(`color`,new U(c,3));let u=new qo({vertexColors:!0,toneMapped:!1});super(l,u),this.type=`GridHelper`}dispose(){this.geometry.dispose(),this.material.dispose()}},Df=class extends as{constructor(e=10,t=16,n=8,r=64,i=4473924,a=8947848){i=new H(i),a=new H(a);let o=[],s=[];if(t>1)for(let n=0;n<t;n++){let r=n/t*(Math.PI*2),c=Math.sin(r)*e,l=Math.cos(r)*e;o.push(0,0,0),o.push(c,0,l);let u=n&1?i:a;s.push(u.r,u.g,u.b),s.push(u.r,u.g,u.b)}for(let t=0;t<n;t++){let c=t&1?i:a,l=e-e/n*t;for(let e=0;e<r;e++){let t=e/r*(Math.PI*2),n=Math.sin(t)*l,i=Math.cos(t)*l;o.push(n,0,i),s.push(c.r,c.g,c.b),t=(e+1)/r*(Math.PI*2),n=Math.sin(t)*l,i=Math.cos(t)*l,o.push(n,0,i),s.push(c.r,c.g,c.b)}}let c=new W;c.setAttribute(`position`,new U(o,3)),c.setAttribute(`color`,new U(s,3));let l=new qo({vertexColors:!0,toneMapped:!1});super(c,l),this.type=`PolarGridHelper`}dispose(){this.geometry.dispose(),this.material.dispose()}},Of=new B,kf=new B,Af=new B,jf=class extends Br{constructor(e,t,n){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=n,this.type=`DirectionalLightHelper`,t===void 0&&(t=1);let r=new W;r.setAttribute(`position`,new U([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));let i=new qo({fog:!1,toneMapped:!1});this.lightPlane=new ts(r,i),this.add(this.lightPlane),r=new W,r.setAttribute(`position`,new U([0,0,0,0,0,1],3)),this.targetLine=new ts(r,i),this.add(this.targetLine),this.update()}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()}update(){this.matrixWorldNeedsUpdate=!0,this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),Of.setFromMatrixPosition(this.light.matrixWorld),kf.setFromMatrixPosition(this.light.target.matrixWorld),Af.subVectors(kf,Of),this.lightPlane.lookAt(kf),this.color===void 0?(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color)):(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)),this.targetLine.lookAt(kf),this.targetLine.scale.z=Af.length()}},Mf=new B,Nf=new Ou,Pf=class extends as{constructor(e){let t=new W,n=new qo({color:16777215,vertexColors:!0,toneMapped:!1}),r=[],i=[],a={};o(`n1`,`n2`),o(`n2`,`n4`),o(`n4`,`n3`),o(`n3`,`n1`),o(`f1`,`f2`),o(`f2`,`f4`),o(`f4`,`f3`),o(`f3`,`f1`),o(`n1`,`f1`),o(`n2`,`f2`),o(`n3`,`f3`),o(`n4`,`f4`),o(`p`,`n1`),o(`p`,`n2`),o(`p`,`n3`),o(`p`,`n4`),o(`u1`,`u2`),o(`u2`,`u3`),o(`u3`,`u1`),o(`c`,`t`),o(`p`,`c`),o(`cn1`,`cn2`),o(`cn3`,`cn4`),o(`cf1`,`cf2`),o(`cf3`,`cf4`);function o(e,t){s(e),s(t)}function s(e){r.push(0,0,0),i.push(0,0,0),a[e]===void 0&&(a[e]=[]),a[e].push(r.length/3-1)}t.setAttribute(`position`,new U(r,3)),t.setAttribute(`color`,new U(i,3)),super(t,n),this.type=`CameraHelper`,this.camera=e,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=a,this.update();let c=new H(16755200),l=new H(16711680),u=new H(43775),d=new H(16777215),f=new H(3355443);this.setColors(c,l,u,d,f)}setColors(e,t,n,r,i){let a=this.geometry.getAttribute(`color`);return a.setXYZ(0,e.r,e.g,e.b),a.setXYZ(1,e.r,e.g,e.b),a.setXYZ(2,e.r,e.g,e.b),a.setXYZ(3,e.r,e.g,e.b),a.setXYZ(4,e.r,e.g,e.b),a.setXYZ(5,e.r,e.g,e.b),a.setXYZ(6,e.r,e.g,e.b),a.setXYZ(7,e.r,e.g,e.b),a.setXYZ(8,e.r,e.g,e.b),a.setXYZ(9,e.r,e.g,e.b),a.setXYZ(10,e.r,e.g,e.b),a.setXYZ(11,e.r,e.g,e.b),a.setXYZ(12,e.r,e.g,e.b),a.setXYZ(13,e.r,e.g,e.b),a.setXYZ(14,e.r,e.g,e.b),a.setXYZ(15,e.r,e.g,e.b),a.setXYZ(16,e.r,e.g,e.b),a.setXYZ(17,e.r,e.g,e.b),a.setXYZ(18,e.r,e.g,e.b),a.setXYZ(19,e.r,e.g,e.b),a.setXYZ(20,e.r,e.g,e.b),a.setXYZ(21,e.r,e.g,e.b),a.setXYZ(22,e.r,e.g,e.b),a.setXYZ(23,e.r,e.g,e.b),a.setXYZ(24,t.r,t.g,t.b),a.setXYZ(25,t.r,t.g,t.b),a.setXYZ(26,t.r,t.g,t.b),a.setXYZ(27,t.r,t.g,t.b),a.setXYZ(28,t.r,t.g,t.b),a.setXYZ(29,t.r,t.g,t.b),a.setXYZ(30,t.r,t.g,t.b),a.setXYZ(31,t.r,t.g,t.b),a.setXYZ(32,n.r,n.g,n.b),a.setXYZ(33,n.r,n.g,n.b),a.setXYZ(34,n.r,n.g,n.b),a.setXYZ(35,n.r,n.g,n.b),a.setXYZ(36,n.r,n.g,n.b),a.setXYZ(37,n.r,n.g,n.b),a.setXYZ(38,r.r,r.g,r.b),a.setXYZ(39,r.r,r.g,r.b),a.setXYZ(40,i.r,i.g,i.b),a.setXYZ(41,i.r,i.g,i.b),a.setXYZ(42,i.r,i.g,i.b),a.setXYZ(43,i.r,i.g,i.b),a.setXYZ(44,i.r,i.g,i.b),a.setXYZ(45,i.r,i.g,i.b),a.setXYZ(46,i.r,i.g,i.b),a.setXYZ(47,i.r,i.g,i.b),a.setXYZ(48,i.r,i.g,i.b),a.setXYZ(49,i.r,i.g,i.b),a.needsUpdate=!0,this}update(){let e=this.geometry,t=this.pointMap,n,r;if(Nf.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),this.camera.reversedDepth===!0)n=1,r=0;else if(this.camera.coordinateSystem===2e3)n=-1,r=1;else if(this.camera.coordinateSystem===2001)n=0,r=1;else throw Error(`THREE.CameraHelper.update(): Invalid coordinate system: `+this.camera.coordinateSystem);Ff(`c`,t,e,Nf,0,0,n),Ff(`t`,t,e,Nf,0,0,r),Ff(`n1`,t,e,Nf,-1,-1,n),Ff(`n2`,t,e,Nf,1,-1,n),Ff(`n3`,t,e,Nf,-1,1,n),Ff(`n4`,t,e,Nf,1,1,n),Ff(`f1`,t,e,Nf,-1,-1,r),Ff(`f2`,t,e,Nf,1,-1,r),Ff(`f3`,t,e,Nf,-1,1,r),Ff(`f4`,t,e,Nf,1,1,r),Ff(`u1`,t,e,Nf,.7,1.1,n),Ff(`u2`,t,e,Nf,-.7,1.1,n),Ff(`u3`,t,e,Nf,0,2,n),Ff(`cf1`,t,e,Nf,-1,0,r),Ff(`cf2`,t,e,Nf,1,0,r),Ff(`cf3`,t,e,Nf,0,-1,r),Ff(`cf4`,t,e,Nf,0,1,r),Ff(`cn1`,t,e,Nf,-1,0,n),Ff(`cn2`,t,e,Nf,1,0,n),Ff(`cn3`,t,e,Nf,0,-1,n),Ff(`cn4`,t,e,Nf,0,1,n),e.getAttribute(`position`).needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}};function Ff(e,t,n,r,i,a,o){Mf.set(i,a,o).unproject(r);let s=t[e];if(s!==void 0){let e=n.getAttribute(`position`);for(let t=0,n=s.length;t<n;t++)e.setXYZ(s[t],Mf.x,Mf.y,Mf.z)}}var If=new fi,Lf=class extends as{constructor(e,t=16776960){let n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),r=new Float32Array(24),i=new W;i.setIndex(new Fi(n,1)),i.setAttribute(`position`,new Fi(r,3)),super(i,new qo({color:t,toneMapped:!1})),this.object=e,this.type=`BoxHelper`,this.matrixAutoUpdate=!1,this.update()}update(){if(this.object!==void 0&&If.setFromObject(this.object),If.isEmpty())return;let e=If.min,t=If.max,n=this.geometry.attributes.position,r=n.array;r[0]=t.x,r[1]=t.y,r[2]=t.z,r[3]=e.x,r[4]=t.y,r[5]=t.z,r[6]=e.x,r[7]=e.y,r[8]=t.z,r[9]=t.x,r[10]=e.y,r[11]=t.z,r[12]=t.x,r[13]=t.y,r[14]=e.z,r[15]=e.x,r[16]=t.y,r[17]=e.z,r[18]=e.x,r[19]=e.y,r[20]=e.z,r[21]=t.x,r[22]=e.y,r[23]=e.z,n.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(e){return this.object=e,this.update(),this}copy(e,t){return super.copy(e,t),this.object=e.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}},Rf=class extends as{constructor(e,t=16776960){let n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),r=[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],i=new W;i.setIndex(new Fi(n,1)),i.setAttribute(`position`,new U(r,3)),super(i,new qo({color:t,toneMapped:!1})),this.box=e,this.type=`Box3Helper`,this.geometry.computeBoundingSphere()}updateMatrixWorld(e){let t=this.box;t.isEmpty()||(t.getCenter(this.position),t.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(e))}dispose(){this.geometry.dispose(),this.material.dispose()}},zf=class extends ts{constructor(e,t=1,n=16776960){let r=n,i=[1,-1,0,-1,1,0,-1,-1,0,1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],a=new W;a.setAttribute(`position`,new U(i,3)),a.computeBoundingSphere(),super(a,new qo({color:r,toneMapped:!1})),this.type=`PlaneHelper`,this.plane=e,this.size=t;let o=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],s=new W;s.setAttribute(`position`,new U(o,3)),s.computeBoundingSphere(),this.add(new Ga(s,new Na({color:r,opacity:.2,transparent:!0,depthWrite:!1,toneMapped:!1})))}updateMatrixWorld(e){this.position.set(0,0,0),this.scale.set(.5*this.size,.5*this.size,1),this.lookAt(this.plane.normal),this.translateZ(-this.plane.constant),super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}},Bf=new B,Vf,Hf,Uf=class extends Br{constructor(e=new B(0,0,1),t=new B(0,0,0),n=1,r=16776960,i=n*.2,a=i*.2){super(),this.type=`ArrowHelper`,Vf===void 0&&(Vf=new W,Vf.setAttribute(`position`,new U([0,0,0,0,1,0],3)),Hf=new As(.5,1,5,1),Hf.translate(0,-.5,0)),this.position.copy(t),this.line=new ts(Vf,new qo({color:r,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new Ga(Hf,new Na({color:r,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(e),this.setLength(n,i,a)}setDirection(e){if(e.y>.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{Bf.set(e.z,0,-e.x).normalize();let t=Math.acos(e.y);this.quaternion.setFromAxisAngle(Bf,t)}}setLength(e,t=e*.2,n=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(n,t,n),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}},Wf=class extends as{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new W;r.setAttribute(`position`,new U(t,3)),r.setAttribute(`color`,new U(n,3));let i=new qo({vertexColors:!0,toneMapped:!1});super(r,i),this.type=`AxesHelper`}setColors(e,t,n){let r=new H,i=this.geometry.attributes.color.array;return r.set(e),r.toArray(i,0),r.toArray(i,3),r.set(t),r.toArray(i,6),r.toArray(i,9),r.set(n),r.toArray(i,12),r.toArray(i,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}},Gf=class{constructor(){this.type=`ShapePath`,this.color=new H,this.subPaths=[],this.currentPath=null,this.userData={}}moveTo(e,t){return this.currentPath=new pc,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,n,r){return this.currentPath.quadraticCurveTo(e,t,n,r),this}bezierCurveTo(e,t,n,r,i,a){return this.currentPath.bezierCurveTo(e,t,n,r,i,a),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(){function e(e,t){let n=!1,r=t.length;for(let i=0,a=r-1;i<r;a=i++){let r=t[i],o=t[a];r.y>e.y!=o.y>e.y&&e.x<(o.x-r.x)*(e.y-r.y)/(o.y-r.y)+r.x&&(n=!n)}return n}function t(t,n){let r=n.getCenter(new R);if(e(r,t))return r;let i=r.y,a=[],o=t.length;for(let e=0;e<o;e++){let n=t[e],r=t[(e+1)%o];if(n.y>i!=r.y>i){let e=n.x+(i-n.y)*(r.x-n.x)/(r.y-n.y);a.push(e)}}return a.length>1&&(a.sort((e,t)=>e-t),r.x=(a[0]+a[1])/2),r}let n=this.userData.style&&this.userData.style.fillRule||`nonzero`;n!==`nonzero`&&n!==`evenodd`&&(P(`Fill-rule "`+n+`" is not supported, falling back to "nonzero".`),n=`nonzero`);let r=n===`nonzero`?(e=>e!==0):(e=>!!(e&1)),i=[];for(let e of this.subPaths){let n=e.getPoints();if(n.length<3)continue;let r=Yc.area(n);if(r===0)continue;let a=new af;for(let e=0;e<n.length;e++)a.expandByPoint(n[e]);i.push({subPath:e,points:n,boundingBox:a,interiorPoint:t(n,a),absArea:Math.abs(r),winding:r<0?-1:1,container:null,exclude:!1,role:null})}i.sort((e,t)=>t.absArea-e.absArea);for(let t=0;t<i.length;t++){let n=i[t],a=0;for(let r=t-1;r>=0;r--){let t=i[r];if(t.boundingBox.containsBox(n.boundingBox)&&e(n.interiorPoint,t.points)){n.container=t.exclude?t.container:t,a=t.winding,n.winding+=a;break}}r(n.winding)===r(a)&&(n.exclude=!0)}for(let e of i)e.exclude||(e.role=e.container===null||e.container.role===`hole`?`outer`:`hole`);let a=[],o=new Map;for(let e of i){if(e.exclude||e.role!==`outer`)continue;let t=new mc;t.curves=e.subPath.curves,a.push(t),o.set(e,t)}for(let e of i){if(e.exclude||e.role!==`hole`)continue;let t=o.get(e.container);if(!t)continue;let n=new pc;n.curves=e.subPath.curves,t.holes.push(n)}return a}},Kf=class extends _n{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){P(`Controls: connect() now requires an element.`);return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}};function qf(e,t){let n=e.image&&e.image.width?e.image.width/e.image.height:1;return n>t?(e.repeat.x=1,e.repeat.y=n/t,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2):(e.repeat.x=t/n,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0),e}function Jf(e,t){let n=e.image&&e.image.width?e.image.width/e.image.height:1;return n>t?(e.repeat.x=t/n,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0):(e.repeat.x=1,e.repeat.y=n/t,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2),e}function Yf(e){return e.repeat.x=1,e.repeat.y=1,e.offset.x=0,e.offset.y=0,e}function Xf(e,t,n,r){let i=Zf(r);switch(n){case be:return e*t;case Te:return e*t/i.components*i.byteLength;case Ee:return e*t/i.components*i.byteLength;case De:return e*t*2/i.components*i.byteLength;case Oe:return e*t*2/i.components*i.byteLength;case xe:return e*t*3/i.components*i.byteLength;case Se:return e*t*4/i.components*i.byteLength;case Ae:return e*t*4/i.components*i.byteLength;case je:case Me:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Ne:case Pe:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ie:case N:return Math.max(e,16)*Math.max(t,8)/4;case Fe:case Le:return Math.max(e,8)*Math.max(t,8)/2;case Re:case ze:case Ve:case He:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Be:case Ue:case We:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ge:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ke:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case qe:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Je:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Ye:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case Xe:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Ze:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Qe:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case $e:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case et:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case tt:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case nt:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case rt:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case it:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case at:case ot:case st:return Math.ceil(e/4)*Math.ceil(t/4)*16;case ct:case lt:return Math.ceil(e/4)*Math.ceil(t/4)*8;case ut:case dt:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function Zf(e){switch(e){case se:case ce:return{byteLength:1,components:1};case ue:case le:case me:return{byteLength:2,components:1};case he:case ge:return{byteLength:2,components:4};case fe:case de:case pe:return{byteLength:4,components:1};case ve:case ye:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}var Qf=class{static contain(e,t){return qf(e,t)}static cover(e,t){return Jf(e,t)}static fill(e){return Yf(e)}static getByteLength(e,t,n,r){return Xf(e,t,n,r)}};typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`185`}})),typeof window<`u`&&(window.__THREE__?P(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`185`);var $f=[{id:`hips`,bone:`mixamorigHips`,label:`Hips`},{id:`spine`,bone:`mixamorigSpine`,label:`Spine`},{id:`chest`,bone:`mixamorigSpine1`,label:`Chest`},{id:`upperChest`,bone:`mixamorigSpine2`,label:`Upper Chest`},{id:`neck`,bone:`mixamorigNeck`,label:`Neck`},{id:`head`,bone:`mixamorigHead`,label:`Head`},{id:`lShoulder`,bone:`mixamorigLeftShoulder`,label:`L Shoulder`},{id:`rShoulder`,bone:`mixamorigRightShoulder`,label:`R Shoulder`},{id:`lArm`,bone:`mixamorigLeftArm`,label:`L Upper Arm`},{id:`rArm`,bone:`mixamorigRightArm`,label:`R Upper Arm`},{id:`lForeArm`,bone:`mixamorigLeftForeArm`,label:`L Forearm`},{id:`rForeArm`,bone:`mixamorigRightForeArm`,label:`R Forearm`},{id:`lHand`,bone:`mixamorigLeftHand`,label:`L Hand`},{id:`rHand`,bone:`mixamorigRightHand`,label:`R Hand`},{id:`lUpLeg`,bone:`mixamorigLeftUpLeg`,label:`L Thigh`},{id:`rUpLeg`,bone:`mixamorigRightUpLeg`,label:`R Thigh`},{id:`lLeg`,bone:`mixamorigLeftLeg`,label:`L Shin`},{id:`rLeg`,bone:`mixamorigRightLeg`,label:`R Shin`},{id:`lFoot`,bone:`mixamorigLeftFoot`,label:`L Foot`},{id:`rFoot`,bone:`mixamorigRightFoot`,label:`R Foot`}];function ep(e){return String(e??``).replace(/[^a-zA-Z0-9]/g,``).toLowerCase()}function tp(e,t){let n=ep(e),r=ep(t.bone);return n===r||n.endsWith(r)||r.endsWith(n)}var np={id:`default`,label:`Default`,prompt:`standing relaxed with arms hanging naturally at their sides`,bones:{lArm:[1.5632,.1164,-.2889],rArm:[1.5632,-.1164,.2889],lForeArm:[-.0076,3e-4,-.0874],rForeArm:[-.0076,-3e-4,.0874]}},rp=`cozyclay_poses`,ip=new WeakMap;function ap(e,t,n){let r=Math.cos(e/2),i=Math.cos(t/2),a=Math.cos(n/2),o=Math.sin(e/2),s=Math.sin(t/2),c=Math.sin(n/2);return{x:o*i*a+r*s*c,y:r*s*a-o*i*c,z:r*i*c+o*s*a,w:r*i*a-o*s*c}}function op(e,t){return{x:e.w*t.x+e.x*t.w+e.y*t.z-e.z*t.y,y:e.w*t.y-e.x*t.z+e.y*t.w+e.z*t.x,z:e.w*t.z+e.x*t.y-e.y*t.x+e.z*t.w,w:e.w*t.w-e.x*t.x-e.y*t.y-e.z*t.z}}function sp(e){return{x:-e.x,y:-e.y,z:-e.z,w:e.w}}function cp(e){let t=1-2*(e.y*e.y+e.z*e.z),n=2*(e.x*e.y-e.w*e.z),r=2*(e.x*e.z+e.w*e.y),i=1-2*(e.x*e.x+e.z*e.z),a=2*(e.y*e.z-e.w*e.x),o=2*(e.y*e.z+e.w*e.x),s=1-2*(e.x*e.x+e.y*e.y),c=Math.asin(Math.max(-1,Math.min(1,r)));return Math.abs(r)<.9999999?[Math.atan2(-a,s),c,Math.atan2(-n,t)]:[Math.atan2(o,i),c,0]}function lp(e){if(!e||e.userData?.poseBind)return;let t=new Map;e.traverse(e=>{if(e.isBone){let n=e.quaternion,r=e.position;t.set(e,{x:n.x,y:n.y,z:n.z,w:n.w,position:{x:r.x,y:r.y,z:r.z}})}}),e.userData.poseBind=t}function up(e){let t=e.userData&&e.userData.poseBind;if(t)return t;let n=ip.get(e);return n||(n=new Map,e.traverse(e=>{if(e.isBone){let t=e.quaternion,r=e.position;n.set(e,{x:t.x,y:t.y,z:t.z,w:t.w,position:{x:r.x,y:r.y,z:r.z}})}}),ip.set(e,n)),n}function dp(e,t){for(let n=e.parent;n;n=n.parent)if(t.includes(n))return!0;return!1}function fp(e,t){let n=$f.length,r=0;if(e&&t){let n=up(e),i=new Map;e.traverse(e=>{if(e.isBone){for(let t of $f)if(tp(e.name,t)){let n=i.get(t.id);n||i.set(t.id,n=[]),n.push(e)}}});for(let e of $f){let a=t[e.id],o=i.get(e.id);if(!o||!Array.isArray(a)||a.length<3)continue;let s=ap(a[0],a[1],a[2]),c=[];for(let e of o){if(c.length&&dp(e,c))continue;c.push(e);let t=op(s,n.get(e)??n.get(o[0])??{x:0,y:0,z:0,w:1});e.quaternion.set(t.x,t.y,t.z,t.w)}r++}e.updateMatrixWorld(!0)}return{applied:r,total:n}}function pp(e){let t={};if(e){let n=up(e),r=new Map;e.traverse(e=>{if(e.isBone){for(let t of $f)if(!r.has(t.id)&&tp(e.name,t)){r.set(t.id,e);break}}});for(let e of $f){let i=r.get(e.id);if(i){let r=i.quaternion,a=n.get(i),o=a?op({x:r.x,y:r.y,z:r.z,w:r.w},sp(a)):{x:r.x,y:r.y,z:r.z,w:r.w};t[e.id]=cp(o)}}}return t}function mp(e){let t=$f.find(e=>e.id===`hips`),n=null;return e.traverse(e=>{!n&&e.isBone&&tp(e.name,t)&&(n=e)}),n}function hp(e){if(!e)return 0;let t=mp(e);if(!t)return 0;let n=up(e).get(t);return n?.position?t.position.y-n.position.y:0}function gp(e){if(!e)return;let t=up(e);e.traverse(e=>{if(!e.isBone)return;let n=t.get(e)?.position;n&&e.position.set(n.x,n.y,n.z)}),e.updateMatrixWorld(!0)}function _p(e,t=0){if(!e)return;let n=mp(e);if(!n)return;let r=up(e).get(n);r?.position&&(n.position.y=r.position.y+(Number.isFinite(t)?t:0),n.updateMatrixWorld(!0))}function vp(){try{let e=localStorage.getItem(rp);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&typeof e.id==`string`&&e.bones&&typeof e.bones==`object`):[]}catch{return[]}}function yp(e){try{return localStorage.setItem(rp,JSON.stringify(e)),!0}catch{return!1}}var bp=240,xp=(e,t,n)=>Math.min(n,Math.max(t,e)),Sp=(e,t=0)=>typeof e==`number`&&Number.isFinite(e)?e:t;function Cp(e){let t=e&&typeof e==`object`?e:{};return{x:xp(Sp(t.x),-240,bp),y:xp(Sp(t.y),0,60),z:xp(Sp(t.z),-240,bp)}}function wp(e){if(!e||typeof e!=`object`)return null;let t=Array.isArray(e.points)?e.points:[],r=[];for(let e of t){let t=Cp(e),n=r[r.length-1];if(!(n&&Math.hypot(t.x-n.x,t.z-n.z,t.y-n.y)<1e-4)&&(r.push(t),r.length>=64))break}if(r.length<2)return null;let i=Sp(e.speed,0),a=n(e.timing);return{points:r,timing:u(a)?null:a,speed:i>0?xp(i,.01,50):0,faceTravel:e.faceTravel!==!1,loop:e.loop===!0,extend:e.extend===!0}}function Tp(e,t){let n=wp(e);if(!n)return null;let r=Sp(t?.x),i=Sp(t?.y),a=Sp(t?.z);return!r&&!i&&!a?n:wp({...n,points:n.points.map(e=>({x:e.x+r,y:e.y+i,z:e.z+a}))})}function Ep(e){let t=e?.points??[],n=[0];for(let e=1;e<t.length;e+=1){let r=t[e-1],i=t[e];n.push(n[e-1]+Math.hypot(i.x-r.x,i.y-r.y,i.z-r.z))}return{cumulative:n,length:n[n.length-1]??0}}function Dp(e,t,n){let{points:r}=e,{cumulative:i,length:a}=t;if(n<=0){let e=Op(r[0],r[1]);return{...r[0],heading:e}}if(n>=a){let t=r[r.length-1],i=Op(r[r.length-2],t);if(!e.extend)return{...t,heading:i};let o=n-a,s=r[r.length-2],c=Math.hypot(t.x-s.x,t.y-s.y,t.z-s.z)||1;return{x:t.x+(t.x-s.x)/c*o,y:Math.max(0,t.y+(t.y-s.y)/c*o),z:t.z+(t.z-s.z)/c*o,heading:i}}let o=1;for(;o<i.length-1&&i[o]<n;)o+=1;let s=r[o-1],c=r[o],l=i[o]-i[o-1],u=l>1e-9?(n-i[o-1])/l:0;return{x:s.x+(c.x-s.x)*u,y:s.y+(c.y-s.y)*u,z:s.z+(c.z-s.z)*u,heading:Op(s,c)}}function Op(e,t){if(!e||!t)return null;let n=t.x-e.x,r=t.z-e.z;return Math.abs(n)<1e-9&&Math.abs(r)<1e-9?null:Math.atan2(n,r)*180/Math.PI}function kp(e,t,n={}){let r=wp(e?.path);if(!r)return null;let i=Ep(r);if(i.length<=1e-9)return null;let a=Math.max(1,Math.round(Sp(n.frameCount,1))),s=Math.max(1,Sp(n.fps,24)),c=xp(Sp(t),0,Math.max(0,a-1))/s,l=Math.max(1e-6,(a-1)/s),u=r.speed>0?r.speed:i.length/l,d=i.length/u,f=c/Math.max(1e-6,d),p;p=r.loop&&i.length>1e-9?i.length*o(r.timing,f-Math.floor(f)):f>=1?i.length+(r.extend?u*(c-d):0):i.length*o(r.timing,f);let m=Dp(r,i,p);return{x:m.x,y:m.y,z:m.z,rot:r.faceTravel&&m.heading!==null?m.heading:null}}function Ap(e,t,{maxPoints:n=5,epsilon:r=.55}={}){if(!e||e.length<2)return[];let i=t(e,r);for(let a=0;a<12&&i.length>n;a+=1)r*=1.8,i=t(e,r);if(i.length>n){let e=[i[0]];for(let t=1;t<n-1;t+=1)e.push(i[Math.round(t*(i.length-1)/(n-1))]);e.push(i[i.length-1]),i=e}return i.map(e=>({x:e.x,y:0,z:e.z}))}var jp=`img-`,Mp=`mesh-`,Np=32,Pp=`cozyclay.assets`,Fp=`images`,Ip=Object.freeze([`image/png`,`image/webp`,`image/jpeg`,`image/gif`]),Lp=Object.freeze([`model/gltf-binary`,`model/obj`,`model/fbx`]),Rp=33554432,zp=2048;function Bp(e){return typeof e==`string`&&Ip.includes(e.toLowerCase())}function Vp(e){return typeof e==`string`&&Lp.includes(e.toLowerCase())}function Hp(e,t){if(typeof t!=`string`)return null;let n=t.trim().toLowerCase();return!/^[0-9a-f]+$/.test(n)||n.length<Np?null:`${e}${n.slice(0,Np)}`}function Up(e,t){return typeof t==`string`&&RegExp(`^${e}[0-9a-f]{${Np}}$`).test(t)}function Wp(e){return Hp(jp,e)}function Gp(e){return Hp(Mp,e)}function Kp(e){return Up(jp,e)}function qp(e){return Up(Mp,e)}function Jp(e){return Kp(e)||qp(e)}async function Yp(e,t){if(!t?.digest)throw Error(`SubtleCrypto is unavailable — a secure context is required to import images`);let n=e instanceof ArrayBuffer?e:e?.buffer?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):null;if(!n)return null;let r=await t.digest(`SHA-256`,n);return Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,`0`)).join(``)}async function Xp(e,t=globalThis.crypto?.subtle){let n=await Yp(e,t);if(!n)throw TypeError(`assetIdForBytes needs an ArrayBuffer or a typed array`);return Wp(n)}async function Zp(e,t=globalThis.crypto?.subtle){let n=await Yp(e,t);if(!n)throw TypeError(`meshIdForBytes needs an ArrayBuffer or a typed array`);return Gp(n)}function Qp(e,t,n=zp){let r=Math.max(0,Math.round(Number(e)||0)),i=Math.max(0,Math.round(Number(t)||0));if(!r||!i)return null;let a=Math.max(r,i);if(a<=n)return{width:r,height:i,scaled:!1};let o=n/a;return{width:Math.max(1,Math.round(r*o)),height:Math.max(1,Math.round(i*o)),scaled:!0}}function $p(e){let t=Number(e?.width),n=Number(e?.height);return!Number.isFinite(t)||!Number.isFinite(n)||t<=0||n<=0?null:t/n}function em(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e.bytes instanceof ArrayBuffer?e.bytes:null;if(!t||!t.byteLength)return null;if(qp(e.id))return Vp(e.type)?{id:e.id,type:e.type.toLowerCase(),bytes:t,name:typeof e.name==`string`?e.name:``,...typeof e.role==`string`?{role:e.role}:{}}:null;if(!Kp(e.id)||!Bp(e.type))return null;let n=Math.round(Number(e.width)),r=Math.round(Number(e.height));return!Number.isInteger(n)||!Number.isInteger(r)||n<=0||r<=0?null:{id:e.id,type:e.type.toLowerCase(),width:n,height:r,bytes:t,name:typeof e.name==`string`?e.name:``,...typeof e.role==`string`?{role:e.role}:{}}}function tm(e){return Array.from(e?.files??[]).filter(e=>{if(!e)return!1;if(Bp(e.type))return!0;if(e.type)return!1;let t=String(e.name??``).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];return[`png`,`webp`,`jpg`,`jpeg`,`gif`].includes(t)})}function nm(e){let t=[],n=Array.from(e?.items??[]);for(let e of n){if(e.kind!==`file`||!Bp(e.type))continue;let n=e.getAsFile?.();n&&t.push(n.name&&n.name!==`image.png`?n:new File([n],`pasted-${Date.now()}.${e.type.split(`/`)[1]||`png`}`,{type:e.type}))}return t.length?t:tm(e)}function rm(e){return e===`image/jpeg`?`image/jpeg`:`image/png`}function im(e,t){if(typeof OffscreenCanvas==`function`)return new OffscreenCanvas(e,t);throw Error(`this browser cannot resize images — OffscreenCanvas is unavailable`)}async function am(e,{subtle:t=globalThis.crypto?.subtle,createBitmap:n=globalThis.createImageBitmap,makeCanvas:r=im,maxDimension:i=zp,maxSourceBytes:a=Rp}={}){if(!e||typeof e.arrayBuffer!=`function`)throw TypeError(`importImageFile needs a File or Blob`);let o=typeof e.type==`string`?e.type.toLowerCase():``;if(!Bp(o))throw Error(`that file is not an image CozyClay can import (PNG, WebP, JPEG or GIF)`);if(Number(e.size)>a)throw Error(`that image is larger than ${Math.round(a/1048576)} MB`);if(typeof n!=`function`)throw Error(`this browser cannot decode images — createImageBitmap is unavailable`);let s=await n(e);try{let n=Qp(s.width,s.height,i);if(!n)throw Error(`that image has no usable size`);let a=o,c;if(n.scaled){let e=r(n.width,n.height),t=e.getContext(`2d`);if(!t)throw Error(`this browser cannot resize images — no 2D context`);t.drawImage(s,0,0,n.width,n.height),a=rm(o),c=await(await e.convertToBlob({type:a})).arrayBuffer()}else c=await e.arrayBuffer();let l=em({id:await Xp(c,t),type:a,width:n.width,height:n.height,bytes:c,name:typeof e.name==`string`?e.name:``});if(!l)throw Error(`that image could not be prepared for the set`);return l}finally{s?.close?.()}}function om(e){return new Set(sm(e).keys())}function sm(e){let t=new Map;for(let n of Array.isArray(e)?e:[])for(let e of Array.isArray(n?.objects)?n.objects:[]){let n=new Set;for(let t of[e?.assetId,e?.sourceAssetId,e?.matteAssetId])Jp(t)&&n.add(t);for(let e of n)t.set(e,(t.get(e)??0)+1)}return t}function cm(e){return JSON.stringify((Array.isArray(e)?e:[]).map(e=>[typeof e?.id==`string`?e.id:null,(Array.isArray(e?.objects)?e.objects:[]).map(e=>[typeof e?.id==`string`?e.id:null,...[e?.assetId,e?.sourceAssetId,e?.matteAssetId].map(e=>Jp(e)?e:null)])]))}async function lm({expectedGraphSignature:e,deleteRecord:t,restoreRecord:n,readGraphSignature:r}){return await t(),r()===e||(await n(),!1)}function um(e,t){let n=om(t);return(Array.isArray(e)?e:[]).filter(e=>Jp(e)&&!n.has(e))}var dm=e=>new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)});function fm(e=globalThis.indexedDB){return e?new Promise((t,n)=>{let r=e.open(Pp,1);r.onupgradeneeded=()=>{r.result.objectStoreNames.contains(`images`)||r.result.createObjectStore(Fp,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error),r.onblocked=()=>n(Error(`the asset database is blocked by another tab`))}):Promise.reject(Error(`IndexedDB is unavailable`))}async function pm(e,t){let n=em(t);if(!n)throw TypeError(`putAsset needs a normalizable asset record`);let r=e.transaction(Fp,`readwrite`);return r.objectStore(Fp).put(n),await new Promise((e,t)=>{r.oncomplete=e,r.onerror=()=>t(r.error),r.onabort=()=>t(r.error)}),n}async function mm(e,t){return Jp(t)?em(await dm(e.transaction(Fp,`readonly`).objectStore(Fp).get(t))):null}async function hm(e){return(await dm(e.transaction(Fp,`readonly`).objectStore(`images`).getAllKeys())??[]).filter(Jp)}async function gm(e,t){if(!Jp(t))return!1;let n=e.transaction(Fp,`readwrite`);return n.objectStore(Fp).delete(t),await new Promise((e,t)=>{n.oncomplete=e,n.onerror=()=>t(n.error),n.onabort=()=>t(n.error)}),!0}var _m=Uint8Array,vm=Uint16Array,ym=Int32Array,bm=new _m([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),xm=new _m([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Sm=new _m([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cm=function(e,t){for(var n=new vm(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new ym(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},wm=Cm(bm,2),Tm=wm.b,Em=wm.r;Tm[28]=258,Em[258]=28;var Dm=Cm(xm,0),Om=Dm.b;Dm.r;for(var km=new vm(32768),Am=0;Am<32768;++Am){var jm=(Am&43690)>>1|(Am&21845)<<1;jm=(jm&52428)>>2|(jm&13107)<<2,jm=(jm&61680)>>4|(jm&3855)<<4,km[Am]=((jm&65280)>>8|(jm&255)<<8)>>1}for(var Mm=(function(e,t,n){for(var r=e.length,i=0,a=new vm(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new vm(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new vm(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[km[d]>>c]=l}else for(s=new vm(r),i=0;i<r;++i)e[i]&&(s[i]=km[o[e[i]-1]++]>>15-e[i]);return s}),Nm=new _m(288),Am=0;Am<144;++Am)Nm[Am]=8;for(var Am=144;Am<256;++Am)Nm[Am]=9;for(var Am=256;Am<280;++Am)Nm[Am]=7;for(var Am=280;Am<288;++Am)Nm[Am]=8;for(var Pm=new _m(32),Am=0;Am<32;++Am)Pm[Am]=5;var Fm=Mm(Nm,9,1),Im=Mm(Pm,5,1),Lm=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Rm=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},zm=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Bm=function(e){return(e+7)/8|0},Vm=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new _m(e.subarray(t,n))},Hm=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],Um=function(e,t,n){var r=Error(t||Hm[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Um),!n)throw r;return r},Wm=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new _m(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new _m(i*3));var l=function(e){var t=n.length;if(e>t){var r=new _m(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=Rm(e,d,1);var v=Rm(e,d+1,3);if(d+=3,!v){var y=Bm(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&Um(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}if(v==1)p=Fm,m=Im,h=9,g=5;else if(v==2){var S=Rm(e,d,31)+257,C=Rm(e,d+10,15)+4,w=S+Rm(e,d+5,31)+1;d+=14;for(var T=new _m(w),E=new _m(19),D=0;D<C;++D)E[Sm[D]]=Rm(e,d+D*3,7);d+=C*3;for(var O=Lm(E),ee=(1<<O)-1,k=Mm(E,O,1),D=0;D<w;){var te=k[Rm(e,d,ee)];d+=te&15;var y=te>>4;if(y<16)T[D++]=y;else{var ne=0,re=0;for(y==16?(re=3+Rm(e,d,3),d+=2,ne=T[D-1]):y==17?(re=3+Rm(e,d,7),d+=3):y==18&&(re=11+Rm(e,d,127),d+=7);re--;)T[D++]=ne}}var ie=T.subarray(0,S),A=T.subarray(S);h=Lm(ie),g=Lm(A),p=Mm(ie,h,1),m=Mm(A,g,1)}else Um(1);if(d>_){c&&Um(0);break}}s&&l(f+131072);for(var j=(1<<h)-1,M=(1<<g)-1,ae=d;;ae=d){var ne=p[zm(e,d)&j],oe=ne>>4;if(d+=ne&15,d>_){c&&Um(0);break}if(ne||Um(2),oe<256)n[f++]=oe;else if(oe==256){ae=d,p=null;break}else{var se=oe-254;if(oe>264){var D=oe-257,ce=bm[D];se=Rm(e,d,(1<<ce)-1)+Tm[D],d+=ce}var le=m[zm(e,d)&M],ue=le>>4;le||Um(3),d+=le&15;var A=Om[ue];if(ue>3){var ce=xm[ue];A+=zm(e,d)&(1<<ce)-1,d+=ce}if(d>_){c&&Um(0);break}s&&l(f+131072);var de=f+se;if(f<A){var fe=a-A,pe=Math.min(A,de);for(fe+f<0&&Um(3);f<pe;++f)n[f]=r[fe+f]}for(;f<de;++f)n[f]=n[f-A]}}t.l=p,t.p=ae,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?Vm(n,0,f):n.subarray(0,f)},Gm=new _m(0),Km=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&Um(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&Um(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function qm(e,t){return Wm(e.subarray(Km(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}var Jm=typeof TextDecoder<`u`&&new TextDecoder;try{Jm.decode(Gm,{stream:!0})}catch{}function Ym(e,t,n){let r=n.length-e-1;if(t>=n[r])return r-1;if(t<=n[e])return e;let i=e,a=r,o=Math.floor((i+a)/2);for(;t<n[o]||t>=n[o+1];)t<n[o]?a=o:i=o,o=Math.floor((i+a)/2);return o}function Xm(e,t,n,r){let i=[],a=[],o=[];i[0]=1;for(let s=1;s<=n;++s){a[s]=t-r[e+1-s],o[s]=r[e+s]-t;let n=0;for(let e=0;e<s;++e){let t=o[e+1],r=a[s-e],c=i[e]/(t+r);i[e]=n+t*c,n=r*c}i[s]=n}return i}function Zm(e,t,n,r){let i=Ym(e,r,t),a=Xm(i,r,e,t),o=new sr(0,0,0,0);for(let t=0;t<=e;++t){let r=n[i-e+t],s=a[t],c=r.w*s;o.x+=r.x*c,o.y+=r.y*c,o.z+=r.z*c,o.w+=r.w*s}return o}function Qm(e,t,n,r,i){let a=[];for(let e=0;e<=n;++e)a[e]=0;let o=[];for(let e=0;e<=r;++e)o[e]=a.slice(0);let s=[];for(let e=0;e<=n;++e)s[e]=a.slice(0);s[0][0]=1;let c=a.slice(0),l=a.slice(0);for(let r=1;r<=n;++r){c[r]=t-i[e+1-r],l[r]=i[e+r]-t;let n=0;for(let e=0;e<r;++e){let t=l[e+1],i=c[r-e];s[r][e]=t+i;let a=s[e][r-1]/s[r][e];s[e][r]=n+t*a,n=i*a}s[r][r]=n}for(let e=0;e<=n;++e)o[0][e]=s[e][n];for(let e=0;e<=n;++e){let t=0,i=1,c=[];for(let e=0;e<=n;++e)c[e]=a.slice(0);c[0][0]=1;for(let a=1;a<=r;++a){let r=0,l=e-a,u=n-a;e>=a&&(c[i][0]=c[t][0]/s[u+1][l],r=c[i][0]*s[l][u]);let d=l>=-1?1:-l,f=e-1<=u?a-1:n-e;for(let e=d;e<=f;++e)c[i][e]=(c[t][e]-c[t][e-1])/s[u+1][l+e],r+=c[i][e]*s[l+e][u];e<=u&&(c[i][a]=-c[t][a-1]/s[u+1][e],r+=c[i][a]*s[e][u]),o[a][e]=r;let p=t;t=i,i=p}}let u=n;for(let e=1;e<=r;++e){for(let t=0;t<=n;++t)o[e][t]*=u;u*=n-e}return o}function $m(e,t,n,r,i){let a=i<e?i:e,o=[],s=Ym(e,r,t),c=Qm(s,r,e,a,t),l=[];for(let e=0;e<n.length;++e){let t=n[e].clone(),r=t.w;t.x*=r,t.y*=r,t.z*=r,l[e]=t}for(let t=0;t<=a;++t){let n=l[s-e].clone().multiplyScalar(c[t][0]);for(let r=1;r<=e;++r)n.add(l[s-e+r].clone().multiplyScalar(c[t][r]));o[t]=n}for(let e=a+1;e<=i+1;++e)o[e]=new sr(0,0,0);return o}function eh(e,t){let n=1;for(let t=2;t<=e;++t)n*=t;let r=1;for(let e=2;e<=t;++e)r*=e;for(let n=2;n<=e-t;++n)r*=n;return n/r}function th(e){let t=e.length,n=[],r=[];for(let i=0;i<t;++i){let t=e[i];n[i]=new B(t.x,t.y,t.z),r[i]=t.w}let i=[];for(let e=0;e<t;++e){let t=n[e].clone();for(let n=1;n<=e;++n)t.sub(i[e-n].clone().multiplyScalar(eh(e,n)*r[n]));i[e]=t.divideScalar(r[0])}return i}function nh(e,t,n,r,i){return th($m(e,t,n,r,i))}var rh=class extends Rs{constructor(e,t,n,r,i){super();let a=t?t.length-1:0,o=n?n.length:0;this.degree=e,this.knots=t,this.controlPoints=[],this.startKnot=r||0,this.endKnot=i||a;for(let e=0;e<o;++e){let t=n[e];this.controlPoints[e]=new sr(t.x,t.y,t.z,t.w)}}getPoint(e,t=new B){let n=t,r=this.knots[this.startKnot]+e*(this.knots[this.endKnot]-this.knots[this.startKnot]),i=Zm(this.degree,this.knots,this.controlPoints,r);return i.w!==1&&i.divideScalar(i.w),n.set(i.x,i.y,i.z)}getTangent(e,t=new B){let n=t,r=this.knots[0]+e*(this.knots[this.knots.length-1]-this.knots[0]),i=nh(this.degree,this.knots,this.controlPoints,r,1);return n.copy(i[1]).normalize(),n}toJSON(){let e=super.toJSON();return e.degree=this.degree,e.knots=[...this.knots],e.controlPoints=this.controlPoints.map(e=>e.toArray()),e.startKnot=this.startKnot,e.endKnot=this.endKnot,e}fromJSON(e){return super.fromJSON(e),this.degree=e.degree,this.knots=[...e.knots],this.controlPoints=e.controlPoints.map(e=>new sr(e[0],e[1],e[2],e[3])),this.startKnot=e.startKnot,this.endKnot=e.endKnot,this}},X,ih,ah,oh=class extends cu{constructor(e){super(e)}load(e,t,n,r){let i=this,a=i.path===``?Ku.extractUrlBase(e):i.path,o=new du(this.manager);o.setPath(i.path),o.setResponseType(`arraybuffer`),o.setRequestHeader(i.requestHeader),o.setWithCredentials(i.withCredentials),o.load(e,function(n){try{t(i.parse(n,a))}catch(t){r?r(t):console.error(t),i.manager.itemError(e)}},n,r)}parse(e,t){if(mh(e))X=new dh().parse(e);else{let t=Th(e);if(!hh(t))throw Error(`THREE.FBXLoader: Unknown format.`);if(gh(t)<7e3)throw Error(`THREE.FBXLoader: FBX version not supported, FileVersion: `+gh(t));X=new uh().parse(t)}return new sh(new vu(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin),this.manager).parse(X)}},sh=class{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){ih=this.parseConnections();let e=this.parseImages(),t=this.parseTextures(e),n=this.parseMaterials(t),r=this.parseDeformers(),i=new ch().parse(r);return this.parseScene(r,i,n),ah}parseConnections(){let e=new Map;return`Connections`in X&&X.Connections.connections.forEach(function(t){let n=t[0],r=t[1],i=t[2];e.has(n)||e.set(n,{parents:[],children:[]});let a={ID:r,relationship:i};e.get(n).parents.push(a),e.has(r)||e.set(r,{parents:[],children:[]});let o={ID:n,relationship:i};e.get(r).children.push(o)}),e}parseImages(){let e={},t={};if(`Video`in X.Objects){let n=X.Objects.Video;for(let r in n){let i=n[r],a=parseInt(r);if(e[a]=i.RelativeFilename||i.Filename,`Content`in i){let e=i.Content instanceof ArrayBuffer&&i.Content.byteLength>0,a=typeof i.Content==`string`&&i.Content!==``;if(e||a){let e=this.parseImage(n[r]);t[i.RelativeFilename||i.Filename]=e}}}}for(let n in e){let r=e[n];e[n]=t[r]===void 0?e[n].split(`\\`).pop():t[r]}return e}parseImage(e){let t=e.Content,n=e.RelativeFilename||e.Filename,r=n.slice(n.lastIndexOf(`.`)+1).toLowerCase(),i;switch(r){case`bmp`:i=`image/bmp`;break;case`jpg`:case`jpeg`:i=`image/jpeg`;break;case`png`:i=`image/png`;break;case`tif`:i=`image/tiff`;break;case`tga`:this.manager.getHandler(`.tga`)===null&&console.warn(`FBXLoader: TGA loader not found, skipping `,n),i=`image/tga`;break;case`webp`:i=`image/webp`;break;default:console.warn(`FBXLoader: Image type "`+r+`" is not supported.`);return}if(typeof t==`string`)return`data:`+i+`;base64,`+t;{let e=new Uint8Array(t);return window.URL.createObjectURL(new Blob([e],{type:i}))}}parseTextures(e){let t=new Map;if(`Texture`in X.Objects){let n=X.Objects.Texture;for(let r in n){let i=this.parseTexture(n[r],e);t.set(parseInt(r),i)}}return t}parseTexture(e,t){let n=this.loadTexture(e,t);n.ID=e.id,n.name=e.attrName;let r=e.WrapModeU,i=e.WrapModeV,a=r===void 0?0:r.value,o=i===void 0?0:i.value;if(n.wrapS=a===0?D:O,n.wrapT=o===0?D:O,`Scaling`in e){let t=e.Scaling.value;n.repeat.x=t[0],n.repeat.y=t[1]}if(`Translation`in e){let t=e.Translation.value;n.offset.x=t[0],n.offset.y=t[1]}return n}loadTexture(e,t){let n=e.FileName.split(`.`).pop().toLowerCase(),r=this.manager.getHandler(`.${n}`);r===null&&(r=this.textureLoader);let i=r.path;i||r.setPath(this.textureLoader.path);let a=ih.get(e.id).children,o;if(a!==void 0&&a.length>0&&t[a[0].ID]!==void 0&&(o=t[a[0].ID],(o.indexOf(`blob:`)===0||o.indexOf(`data:`)===0)&&r.setPath(void 0)),o===void 0)return console.warn(`FBXLoader: Undefined filename, creating placeholder texture.`),new or;let s=r.load(o);return r.setPath(i),s}parseMaterials(e){let t=new Map;if(`Material`in X.Objects){let n=X.Objects.Material;for(let r in n){let i=this.parseMaterial(n[r],e);i!==null&&t.set(parseInt(r),i)}}return t}parseMaterial(e,t){let n=e.id,r=e.attrName,i=e.ShadingModel;if(typeof i==`object`&&(i=i.value),!ih.has(n))return null;let a=this.parseParameters(e,t,n),o;switch(i.toLowerCase()){case`phong`:o=new kl;break;case`lambert`:o=new Ml;break;default:console.warn(`THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.`,i),o=new kl}return o.setValues(a),o.name=r,o}parseParameters(e,t,n){let r={};e.BumpFactor&&(r.bumpScale=e.BumpFactor.value),e.Diffuse?r.color=Xn.colorSpaceToWorking(new H().fromArray(e.Diffuse.value),Ot):e.DiffuseColor&&(e.DiffuseColor.type===`Color`||e.DiffuseColor.type===`ColorRGB`)&&(r.color=Xn.colorSpaceToWorking(new H().fromArray(e.DiffuseColor.value),Ot)),e.DisplacementFactor&&(r.displacementScale=e.DisplacementFactor.value),e.Emissive?r.emissive=Xn.colorSpaceToWorking(new H().fromArray(e.Emissive.value),Ot):e.EmissiveColor&&(e.EmissiveColor.type===`Color`||e.EmissiveColor.type===`ColorRGB`)&&(r.emissive=Xn.colorSpaceToWorking(new H().fromArray(e.EmissiveColor.value),Ot)),e.EmissiveFactor&&(r.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),r.opacity=1-(e.TransparencyFactor?parseFloat(e.TransparencyFactor.value):0),(r.opacity===1||r.opacity===0)&&(r.opacity=e.Opacity?parseFloat(e.Opacity.value):null,r.opacity===null&&(r.opacity=1)),r.opacity<1&&(r.transparent=!0),e.ReflectionFactor&&(r.reflectivity=e.ReflectionFactor.value),e.Shininess&&(r.shininess=e.Shininess.value),e.Specular?r.specular=Xn.colorSpaceToWorking(new H().fromArray(e.Specular.value),Ot):e.SpecularColor&&e.SpecularColor.type===`Color`&&(r.specular=Xn.colorSpaceToWorking(new H().fromArray(e.SpecularColor.value),Ot));let i=this;return ih.get(n).children.forEach(function(e){let n=e.relationship;switch(n){case`Bump`:r.bumpMap=i.getTexture(t,e.ID);break;case`Maya|TEX_ao_map`:r.aoMap=i.getTexture(t,e.ID);break;case`DiffuseColor`:case`Maya|TEX_color_map`:r.map=i.getTexture(t,e.ID),r.map!==void 0&&(r.map.colorSpace=Ot);break;case`DisplacementColor`:r.displacementMap=i.getTexture(t,e.ID);break;case`EmissiveColor`:r.emissiveMap=i.getTexture(t,e.ID),r.emissiveMap!==void 0&&(r.emissiveMap.colorSpace=Ot);break;case`NormalMap`:case`Maya|TEX_normal_map`:r.normalMap=i.getTexture(t,e.ID);break;case`ReflectionColor`:r.envMap=i.getTexture(t,e.ID),r.envMap!==void 0&&(r.envMap.mapping=303,r.envMap.colorSpace=Ot);break;case`SpecularColor`:r.specularMap=i.getTexture(t,e.ID),r.specularMap!==void 0&&(r.specularMap.colorSpace=Ot);break;case`TransparentColor`:case`TransparencyFactor`:r.alphaMap=i.getTexture(t,e.ID),r.transparent=!0;break;default:console.warn(`THREE.FBXLoader: %s map is not supported in three.js, skipping texture.`,n)}}),r}getTexture(e,t){return`LayeredTexture`in X.Objects&&t in X.Objects.LayeredTexture&&(console.warn(`THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.`),t=ih.get(t).children[0].ID),e.get(t)}parseDeformers(){let e={},t={};if(`Deformer`in X.Objects){let n=X.Objects.Deformer;for(let r in n){let i=n[r],a=ih.get(parseInt(r));if(i.attrType===`Skin`){let t=this.parseSkeleton(a,n);t.ID=r,a.parents.length>1&&console.warn(`THREE.FBXLoader: skeleton attached to more than one geometry is not supported.`),t.geometryID=a.parents[0].ID,e[r]=t}else if(i.attrType===`BlendShape`){let e={id:r};e.rawTargets=this.parseMorphTargets(a,n),e.id=r,a.parents.length>1&&console.warn(`THREE.FBXLoader: morph target attached to more than one geometry is not supported.`),t[r]=e}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){let n=[];return e.children.forEach(function(e){let r=t[e.ID];if(r.attrType!==`Cluster`)return;let i={ID:e.ID,indices:[],weights:[],transformLink:new V().fromArray(r.TransformLink.a)};`Indexes`in r&&(i.indices=r.Indexes.a,i.weights=r.Weights.a),n.push(i)}),{rawBones:n,bones:[]}}parseMorphTargets(e,t){let n=[];for(let r=0;r<e.children.length;r++){let i=e.children[r],a=t[i.ID],o={name:a.attrName,initialWeight:a.DeformPercent,id:a.id,fullWeights:a.FullWeights.a};if(a.attrType!==`BlendShapeChannel`)return;o.geoID=ih.get(parseInt(i.ID)).children.filter(function(e){return e.relationship===void 0})[0].ID,n.push(o)}return n}parseScene(e,t,n){ah=new Vr;let r=this.parseModels(e.skeletons,t,n),i=X.Objects.Model,a=this;r.forEach(function(e){let t=i[e.ID];a.setLookAtProperties(e,t),ih.get(e.ID).parents.forEach(function(t){let n=r.get(t.ID);n!==void 0&&n.add(e)}),e.parent===null&&ah.add(e)}),this.addGlobalSceneSettings(),ah.traverse(function(e){if(e.userData.transformData){e.parent&&(e.userData.transformData.parentMatrix=e.parent.matrix,e.userData.transformData.parentMatrixWorld=e.parent.matrixWorld);let t=Sh(e.userData.transformData);e.applyMatrix4(t),e.updateWorldMatrix()}});let o=this.parsePoseNodes(),s=new Set;for(let t in e.skeletons)e.skeletons[t].rawBones.forEach(function(n,r){let i=e.skeletons[t].bones[r];i&&s.add(i.ID)});let c=new V;ah.traverse(function(e){if(e.isBone&&e.ID!==void 0&&!s.has(e.ID)){let t=o[e.ID];t!==void 0&&(e.parent?(c.copy(e.parent.matrixWorld).invert(),c.multiply(t)):c.copy(t),c.decompose(e.position,e.quaternion,e.scale),e.updateMatrix(),e.matrixWorld.copy(t))}}),this.bindSkeleton(e.skeletons,t,r);let l=new lh().parse();ah.children.length===1&&ah.children[0].isGroup&&(ah.children[0].animations=l,ah=ah.children[0]),ah.animations=l,`GlobalSettings`in X&&`UpAxis`in X.GlobalSettings&&X.GlobalSettings.UpAxis.value===2&&(console.warn(`THREE.FBXLoader: You are loading an asset with a Z-UP coordinate system. The loader just rotates the asset to transform it into Y-UP. The vertex data are not converted.`),ah.rotation.set(-Math.PI/2,0,0))}parseModels(e,t,n){let r=new Map,i=X.Objects.Model;for(let a in i){let o=parseInt(a),s=i[a],c=ih.get(o),l=this.buildSkeleton(c,e,o,s.attrName);if(!l){switch(s.attrType){case`Camera`:l=this.createCamera(c);break;case`Light`:l=this.createLight(c);break;case`Mesh`:l=this.createMesh(c,t,n);break;case`NurbsCurve`:l=this.createCurve(c,t);break;case`LimbNode`:case`Root`:l=new io;break;default:l=new Vr}l.name=s.attrName?Y.sanitizeNodeName(s.attrName):``,l.userData.originalName=s.attrName,l.ID=o}this.getTransformData(l,s),r.set(o,l)}return r}buildSkeleton(e,t,n,r){let i=null;return e.parents.forEach(function(e){for(let a in t){let o=t[a];o.rawBones.forEach(function(t,a){if(t.ID===e.ID){let e=i;i=new io,i.matrixWorld.copy(t.transformLink),i.name=r?Y.sanitizeNodeName(r):``,i.userData.originalName=r,i.ID=n,o.bones[a]=i,e!==null&&i.add(e)}})}}),i}createCamera(e){let t,n;if(e.children.forEach(function(e){let t=X.Objects.NodeAttribute[e.ID];t!==void 0&&(n=t)}),n===void 0)t=new Br;else{let e=0;n.CameraProjectionType!==void 0&&n.CameraProjectionType.value===1&&(e=1);let r=1;n.NearPlane!==void 0&&(r=n.NearPlane.value/1e3);let i=1e3;n.FarPlane!==void 0&&(i=n.FarPlane.value/1e3);let a=window.innerWidth,o=window.innerHeight;n.AspectWidth!==void 0&&n.AspectHeight!==void 0&&(a=n.AspectWidth.value,o=n.AspectHeight.value);let s=a/o,c=45;n.FieldOfView!==void 0&&(c=n.FieldOfView.value);let l=n.FocalLength?n.FocalLength.value:null;switch(e){case 0:t=new Mu(c,s,r,i),l!==null&&t.setFocalLength(l);break;case 1:console.warn(`THREE.FBXLoader: Orthographic cameras not supported yet.`),t=new Br;break;default:console.warn(`THREE.FBXLoader: Unknown camera type `+e+`.`),t=new Br}}return t}createLight(e){let t,n;if(e.children.forEach(function(e){let t=X.Objects.NodeAttribute[e.ID];t!==void 0&&(n=t)}),n===void 0)t=new Br;else{let e;e=n.LightType===void 0?0:n.LightType.value;let r=16777215;n.Color!==void 0&&(r=Xn.colorSpaceToWorking(new H().fromArray(n.Color.value),Ot));let i=n.Intensity===void 0?1:n.Intensity.value/100;n.CastLightOnObject!==void 0&&n.CastLightOnObject.value===0&&(i=0);let a=0;switch(n.FarAttenuationEnd!==void 0&&(a=n.EnableFarAttenuation!==void 0&&n.EnableFarAttenuation.value===0?0:n.FarAttenuationEnd.value),e){case 0:t=new Iu(r,i,a,1);break;case 1:t=new zu(r,i);break;case 2:let e=Math.PI/3,o=0;n.OuterAngle===void 0?n.InnerAngle!==void 0&&(e=Hn.degToRad(n.InnerAngle.value)):(e=Hn.degToRad(n.OuterAngle.value),n.InnerAngle!==void 0&&(o=1-n.InnerAngle.value/n.OuterAngle.value,o=Math.max(0,o))),t=new Pu(r,i,a,e,o,1);break;default:console.warn(`THREE.FBXLoader: Unknown light type `+n.LightType.value+`, defaulting to a PointLight.`),t=new Iu(r,i)}n.CastShadows!==void 0&&n.CastShadows.value===1&&(t.castShadow=!0)}return t}createMesh(e,t,n){let r,i=null,a=null,o=[];if(e.children.forEach(function(e){t.has(e.ID)&&(i=t.get(e.ID)),n.has(e.ID)&&o.push(n.get(e.ID))}),o.length>1?a=o:o.length>0?a=o[0]:(a=new kl({name:cu.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(a)),`color`in i.attributes&&o.forEach(function(e){e.vertexColors=!0}),i.groups.length>0){let e=!1;for(let t=0,n=i.groups.length;t<n;t++){let n=i.groups[t];(n.materialIndex<0||n.materialIndex>=o.length)&&(n.materialIndex=o.length,e=!0)}if(e){let e=new kl;o.push(e)}}return i.FBX_Deformer?(r=new ro(i,a),r.normalizeSkinWeights()):r=new Ga(i,a),r}createCurve(e,t){return new ts(e.children.reduce(function(e,n){return t.has(n.ID)&&(e=t.get(n.ID)),e},null),new qo({name:cu.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1}))}getTransformData(e,t){let n={};`InheritType`in t&&(n.inheritType=parseInt(t.InheritType.value)),n.eulerOrder=`RotationOrder`in t?Ch(t.RotationOrder.value):Ch(0),`Lcl_Translation`in t&&(n.translation=t.Lcl_Translation.value),`PreRotation`in t&&(n.preRotation=t.PreRotation.value),`Lcl_Rotation`in t&&(n.rotation=t.Lcl_Rotation.value),`PostRotation`in t&&(n.postRotation=t.PostRotation.value),`Lcl_Scaling`in t&&(n.scale=t.Lcl_Scaling.value),`ScalingOffset`in t&&(n.scalingOffset=t.ScalingOffset.value),`ScalingPivot`in t&&(n.scalingPivot=t.ScalingPivot.value),`RotationOffset`in t&&(n.rotationOffset=t.RotationOffset.value),`RotationPivot`in t&&(n.rotationPivot=t.RotationPivot.value),e.userData.transformData=n}setLookAtProperties(e,t){`LookAtProperty`in t&&ih.get(e.ID).children.forEach(function(t){if(t.relationship===`LookAtProperty`){let n=X.Objects.Model[t.ID];if(`Lcl_Translation`in n){let t=n.Lcl_Translation.value;e.target===void 0?e.lookAt(new B().fromArray(t)):(e.target.position.fromArray(t),ah.add(e.target))}}})}bindSkeleton(e,t,n){for(let r in e){let i=e[r],a=[];for(let e=0,t=i.bones.length;e<t;e++){let t=new V;i.bones[e]&&i.rawBones[e]&&t.copy(i.rawBones[e].transformLink).invert(),a.push(t)}ih.get(parseInt(i.ID)).parents.forEach(function(e){if(t.has(e.ID)){let t=e.ID;ih.get(t).parents.forEach(function(e){if(n.has(e.ID)){let t=n.get(e.ID);t.updateMatrixWorld(!0),t.bind(new G(i.bones,a),t.matrixWorld)}})}})}}parsePoseNodes(){let e={};if(`Pose`in X.Objects){let t=X.Objects.Pose;for(let n in t)if(t[n].attrType===`BindPose`&&t[n].NbPoseNodes>0){let r=t[n].PoseNode;Array.isArray(r)?r.forEach(function(t){e[t.Node]=new V().fromArray(t.Matrix.a)}):e[r.Node]=new V().fromArray(r.Matrix.a)}}return e}addGlobalSceneSettings(){if(`GlobalSettings`in X){if(`AmbientColor`in X.GlobalSettings){let e=X.GlobalSettings.AmbientColor.value,t=e[0],n=e[1],r=e[2];if(t!==0||n!==0||r!==0){let e=new H().setRGB(t,n,r,Ot);ah.add(new Bu(e,1))}}`UnitScaleFactor`in X.GlobalSettings&&(ah.userData.unitScaleFactor=X.GlobalSettings.UnitScaleFactor.value)}}},ch=class{constructor(){this.negativeMaterialIndices=!1}parse(e){let t=new Map;if(`Geometry`in X.Objects){let n=X.Objects.Geometry;for(let r in n){let i=ih.get(parseInt(r)),a=this.parseGeometry(i,n[r],e);t.set(parseInt(r),a)}}return this.negativeMaterialIndices===!0&&console.warn(`THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected.`),t}parseGeometry(e,t,n){switch(t.attrType){case`Mesh`:return this.parseMeshGeometry(e,t,n);case`NurbsCurve`:return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,n){let r=n.skeletons,i=[],a=e.parents.map(function(e){return X.Objects.Model[e.ID]});if(a.length===0)return;let o=e.children.reduce(function(e,t){return r[t.ID]!==void 0&&(e=r[t.ID]),e},null);e.children.forEach(function(e){n.morphTargets[e.ID]!==void 0&&i.push(n.morphTargets[e.ID])});let s=a[0],c={};`RotationOrder`in s&&(c.eulerOrder=Ch(s.RotationOrder.value)),`InheritType`in s&&(c.inheritType=parseInt(s.InheritType.value)),`GeometricTranslation`in s&&(c.translation=s.GeometricTranslation.value),`GeometricRotation`in s&&(c.rotation=s.GeometricRotation.value),`GeometricScaling`in s&&(c.scale=s.GeometricScaling.value);let l=Sh(c);return this.genGeometry(t,o,i,l)}genGeometry(e,t,n,r){let i=new W;e.attrName&&(i.name=e.attrName);let a=this.parseGeoNode(e,t),o=this.genBuffers(a),s=new U(o.vertex,3);if(s.applyMatrix4(r),i.setAttribute(`position`,s),o.colors.length>0&&i.setAttribute(`color`,new U(o.colors,3)),t&&(i.setAttribute(`skinIndex`,new Bi(o.weightsIndices,4)),i.setAttribute(`skinWeight`,new U(o.vertexWeights,4)),i.FBX_Deformer=t),o.normal.length>0){let e=new Gn().getNormalMatrix(r),t=new U(o.normal,3);t.applyNormalMatrix(e),i.setAttribute(`normal`,t)}if(o.uvs.forEach(function(e,t){let n=t===0?`uv`:`uv${t}`;i.setAttribute(n,new U(o.uvs[t],2))}),a.material&&a.material.mappingType!==`AllSame`){let e=o.materialIndex[0],t=0;if(o.materialIndex.forEach(function(n,r){n!==e&&(i.addGroup(t,r-t,e),e=n,t=r)}),i.groups.length>0){let t=i.groups[i.groups.length-1],n=t.start+t.count;n!==o.materialIndex.length&&i.addGroup(n,o.materialIndex.length-n,e)}i.groups.length===0&&i.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(i,e,n,r),i}parseGeoNode(e,t){let n={};if(n.vertexPositions=e.Vertices===void 0?[]:e.Vertices.a,n.vertexIndices=e.PolygonVertexIndex===void 0?[]:e.PolygonVertexIndex.a,e.LayerElementColor&&e.LayerElementColor[0].Colors&&(n.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(n.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(n.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){n.uv=[];let t=0;for(;e.LayerElementUV[t];)e.LayerElementUV[t].UV&&n.uv.push(this.parseUVs(e.LayerElementUV[t])),t++}return n.weightTable={},t!==null&&(n.skeleton=t,t.rawBones.forEach(function(e,t){e.indices.forEach(function(r,i){n.weightTable[r]===void 0&&(n.weightTable[r]=[]),n.weightTable[r].push({id:t,weight:e.weights[i]})})})),n}genBuffers(e){let t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]},n=0,r=0,i=!1,a=[],o=[],s=[],c=[],l=[],u=[],d=this;return e.vertexIndices.forEach(function(f,p){let m,h=!1;f<0&&(f^=-1,h=!0);let g=[],_=[];if(a.push(f*3,f*3+1,f*3+2),e.color){let t=yh(p,n,f,e.color);s.push(t[0],t[1],t[2])}if(e.skeleton){if(e.weightTable[f]!==void 0&&e.weightTable[f].forEach(function(e){_.push(e.weight),g.push(e.id)}),_.length>4){i||=(console.warn(`THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.`),!0);let e=[0,0,0,0],t=[0,0,0,0];_.forEach(function(n,r){let i=n,a=g[r];t.forEach(function(t,n,r){if(i>t){r[n]=i,i=t;let o=e[n];e[n]=a,a=o}})}),g=e,_=t}for(;_.length<4;)_.push(0),g.push(0);for(let e=0;e<4;++e)l.push(_[e]),u.push(g[e])}if(e.normal){let t=yh(p,n,f,e.normal);o.push(t[0],t[1],t[2])}e.material&&e.material.mappingType!==`AllSame`&&(m=yh(p,n,f,e.material)[0],m<0&&(d.negativeMaterialIndices=!0,m=0)),e.uv&&e.uv.forEach(function(e,t){let r=yh(p,n,f,e);c[t]===void 0&&(c[t]=[]),c[t].push(r[0]),c[t].push(r[1])}),r++,h&&(d.genFace(t,e,a,m,o,s,c,l,u,r),n++,r=0,a=[],o=[],s=[],c=[],l=[],u=[])}),t}getNormalNewell(e){let t=new B(0,0,0);for(let n=0;n<e.length;n++){let r=e[n],i=e[(n+1)%e.length];t.x+=(r.y-i.y)*(r.z+i.z),t.y+=(r.z-i.z)*(r.x+i.x),t.z+=(r.x-i.x)*(r.y+i.y)}return t.normalize(),t}getNormalTangentAndBitangent(e){let t=this.getNormalNewell(e),n=(Math.abs(t.z)>.5?new B(0,1,0):new B(0,0,1)).cross(t).normalize();return{normal:t,tangent:n,bitangent:t.clone().cross(n).normalize()}}flattenVertex(e,t,n){return new R(e.dot(t),e.dot(n))}genFace(e,t,n,r,i,a,o,s,c,l){let u;if(l>3){let e=[],r=t.baseVertexPositions||t.vertexPositions;for(let t=0;t<n.length;t+=3)e.push(new B(r[n[t]],r[n[t+1]],r[n[t+2]]));let{tangent:i,bitangent:a}=this.getNormalTangentAndBitangent(e),o=[];for(let t of e)o.push(this.flattenVertex(t,i,a));u=Yc.triangulateShape(o,[])}else u=[[0,1,2]];for(let[l,d,f]of u)e.vertex.push(t.vertexPositions[n[l*3]]),e.vertex.push(t.vertexPositions[n[l*3+1]]),e.vertex.push(t.vertexPositions[n[l*3+2]]),e.vertex.push(t.vertexPositions[n[d*3]]),e.vertex.push(t.vertexPositions[n[d*3+1]]),e.vertex.push(t.vertexPositions[n[d*3+2]]),e.vertex.push(t.vertexPositions[n[f*3]]),e.vertex.push(t.vertexPositions[n[f*3+1]]),e.vertex.push(t.vertexPositions[n[f*3+2]]),t.skeleton&&(e.vertexWeights.push(s[l*4]),e.vertexWeights.push(s[l*4+1]),e.vertexWeights.push(s[l*4+2]),e.vertexWeights.push(s[l*4+3]),e.vertexWeights.push(s[d*4]),e.vertexWeights.push(s[d*4+1]),e.vertexWeights.push(s[d*4+2]),e.vertexWeights.push(s[d*4+3]),e.vertexWeights.push(s[f*4]),e.vertexWeights.push(s[f*4+1]),e.vertexWeights.push(s[f*4+2]),e.vertexWeights.push(s[f*4+3]),e.weightsIndices.push(c[l*4]),e.weightsIndices.push(c[l*4+1]),e.weightsIndices.push(c[l*4+2]),e.weightsIndices.push(c[l*4+3]),e.weightsIndices.push(c[d*4]),e.weightsIndices.push(c[d*4+1]),e.weightsIndices.push(c[d*4+2]),e.weightsIndices.push(c[d*4+3]),e.weightsIndices.push(c[f*4]),e.weightsIndices.push(c[f*4+1]),e.weightsIndices.push(c[f*4+2]),e.weightsIndices.push(c[f*4+3])),t.color&&(e.colors.push(a[l*3]),e.colors.push(a[l*3+1]),e.colors.push(a[l*3+2]),e.colors.push(a[d*3]),e.colors.push(a[d*3+1]),e.colors.push(a[d*3+2]),e.colors.push(a[f*3]),e.colors.push(a[f*3+1]),e.colors.push(a[f*3+2])),t.material&&t.material.mappingType!==`AllSame`&&(e.materialIndex.push(r),e.materialIndex.push(r),e.materialIndex.push(r)),t.normal&&(e.normal.push(i[l*3]),e.normal.push(i[l*3+1]),e.normal.push(i[l*3+2]),e.normal.push(i[d*3]),e.normal.push(i[d*3+1]),e.normal.push(i[d*3+2]),e.normal.push(i[f*3]),e.normal.push(i[f*3+1]),e.normal.push(i[f*3+2])),t.uv&&t.uv.forEach(function(t,n){e.uvs[n]===void 0&&(e.uvs[n]=[]),e.uvs[n].push(o[n][l*2]),e.uvs[n].push(o[n][l*2+1]),e.uvs[n].push(o[n][d*2]),e.uvs[n].push(o[n][d*2+1]),e.uvs[n].push(o[n][f*2]),e.uvs[n].push(o[n][f*2+1])})}addMorphTargets(e,t,n,r){if(n.length===0)return;e.morphTargetsRelative=!0,e.morphAttributes.position=[];let i=r.clone().setPosition(0,0,0),a=this;n.forEach(function(n){n.rawTargets.forEach(function(n){let r=X.Objects.Geometry[n.geoID];r!==void 0&&a.genMorphGeometry(e,t,r,i,n.name)})})}genMorphGeometry(e,t,n,r,i){let a=t.Vertices===void 0?[]:t.Vertices.a,o=t.PolygonVertexIndex===void 0?[]:t.PolygonVertexIndex.a,s=n.Vertices===void 0?[]:n.Vertices.a,c=n.Indexes===void 0?[]:n.Indexes.a,l=e.attributes.position.count*3,u=new Float32Array(l);for(let e=0;e<c.length;e++){let t=c[e]*3;u[t]=s[e*3],u[t+1]=s[e*3+1],u[t+2]=s[e*3+2]}let d={vertexIndices:o,vertexPositions:u,baseVertexPositions:a},f=new U(this.genBuffers(d).vertex,3);f.name=i||n.attrName,f.applyMatrix4(r),e.morphAttributes.position.push(f)}parseNormals(e){let t=e.MappingInformationType,n=e.ReferenceInformationType,r=e.Normals.a,i=[];return n===`IndexToDirect`&&(`NormalIndex`in e?i=e.NormalIndex.a:`NormalsIndex`in e&&(i=e.NormalsIndex.a)),{dataSize:3,buffer:r,indices:i,mappingType:t,referenceType:n}}parseUVs(e){let t=e.MappingInformationType,n=e.ReferenceInformationType,r=e.UV.a,i=[];return n===`IndexToDirect`&&(i=e.UVIndex.a),{dataSize:2,buffer:r,indices:i,mappingType:t,referenceType:n}}parseVertexColors(e){let t=e.MappingInformationType,n=e.ReferenceInformationType,r=e.Colors.a,i=[];n===`IndexToDirect`&&(i=e.ColorIndex.a);for(let e=0,t=new H;e<r.length;e+=4)t.fromArray(r,e),Xn.colorSpaceToWorking(t,Ot),t.toArray(r,e);return{dataSize:4,buffer:r,indices:i,mappingType:t,referenceType:n}}parseMaterialIndices(e){let t=e.MappingInformationType,n=e.ReferenceInformationType;if(t===`NoMappingInformation`)return{dataSize:1,buffer:[0],indices:[0],mappingType:`AllSame`,referenceType:n};let r=e.Materials.a,i=[];for(let e=0;e<r.length;++e)i.push(e);return{dataSize:1,buffer:r,indices:i,mappingType:t,referenceType:n}}parseNurbsGeometry(e){let t=parseInt(e.Order);if(isNaN(t))return console.error(`THREE.FBXLoader: Invalid Order %s given for geometry ID: %s`,e.Order,e.id),new W;let n=t-1,r=e.KnotVector.a,i=[],a=e.Points.a;for(let e=0,t=a.length;e<t;e+=4)i.push(new sr().fromArray(a,e));let o,s;if(e.Form===`Closed`)i.push(i[0]);else if(e.Form===`Periodic`){o=n,s=r.length-1-o;for(let e=0;e<n;++e)i.push(i[e])}let c=new rh(n,r,i,o,s).getPoints(i.length*12);return new W().setFromPoints(c)}},lh=class{parse(){let e=[],t=this.parseClips();if(t!==void 0)for(let n in t){let r=t[n],i=this.addClip(r);e.push(i)}return e}parseClips(){if(X.Objects.AnimationCurve===void 0)return;let e=this.parseAnimationCurveNodes();this.parseAnimationCurves(e);let t=this.parseAnimationLayers(e);return this.parseAnimStacks(t)}parseAnimationCurveNodes(){let e=X.Objects.AnimationCurveNode,t=new Map;for(let n in e){let r=e[n];if(r.attrName.match(/S|R|T|DeformPercent/)!==null){let e={id:r.id,attr:r.attrName,curves:{}};t.set(e.id,e)}}return t}parseAnimationCurves(e){let t=X.Objects.AnimationCurve;for(let n in t){let r={id:t[n].id,times:t[n].KeyTime.a.map(_h),values:t[n].KeyValueFloat.a},i=ih.get(r.id);if(i!==void 0){let t=i.parents[0].ID,n=i.parents[0].relationship;n.match(/X/)?e.get(t).curves.x=r:n.match(/Y/)?e.get(t).curves.y=r:n.match(/Z/)?e.get(t).curves.z=r:n.match(/DeformPercent/)&&e.has(t)&&(e.get(t).curves.morph=r)}}}parseAnimationLayers(e){let t=X.Objects.AnimationLayer,n=new Map;for(let r in t){let t=[],i=ih.get(parseInt(r));i!==void 0&&(i.children.forEach(function(n,r){if(e.has(n.ID)){let i=e.get(n.ID);if(i.curves.x!==void 0||i.curves.y!==void 0||i.curves.z!==void 0){if(t[r]===void 0){let e=ih.get(n.ID).parents.filter(function(e){return e.relationship!==void 0});if(e.length===0)return;let i=e[0].ID;if(i!==void 0){let e=X.Objects.Model[i.toString()];if(e===void 0){console.warn(`THREE.FBXLoader: Encountered a unused curve.`,n);return}let a={modelName:e.attrName?Y.sanitizeNodeName(e.attrName):``,ID:e.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};ah.traverse(function(t){t.ID===e.id&&(a.transform=t.matrix,t.userData.transformData&&(a.eulerOrder=t.userData.transformData.eulerOrder,t.userData.transformData.rotation&&(a.initialRotation=t.userData.transformData.rotation)))}),a.transform||=new V,`PreRotation`in e&&(a.preRotation=e.PreRotation.value),`PostRotation`in e&&(a.postRotation=e.PostRotation.value),t[r]=a}}t[r]&&(t[r][i.attr]=i)}else if(i.curves.morph!==void 0){if(t[r]===void 0){let e=ih.get(n.ID).parents.filter(function(e){return e.relationship!==void 0});if(e.length===0)return;let i=e[0].ID,a=ih.get(i).parents[0].ID,o=ih.get(a).parents[0].ID,s=ih.get(o).parents[0].ID,c=X.Objects.Model[s],l={modelName:c.attrName?Y.sanitizeNodeName(c.attrName):``,morphName:X.Objects.Deformer[i].attrName};t[r]=l}t[r][i.attr]=i}}}),n.set(parseInt(r),t))}return n}parseAnimStacks(e){let t=X.Objects.AnimationStack,n={};for(let r in t){let i=ih.get(parseInt(r)).children;i.length>1&&console.warn(`THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.`);let a=e.get(i[0].ID);n[r]={name:t[r].attrName,layer:a}}return n}addClip(e){let t=[],n=this;return e.layer.forEach(function(e){t=t.concat(n.generateTracks(e))}),new tu(e.name,-1,t)}generateTracks(e){let t=[],n=new B,r=new B;if(e.transform&&e.transform.decompose(n,new z,r),n=n.toArray(),r=r.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){let r=this.generateVectorTrack(e.modelName,e.T.curves,n,`position`);r!==void 0&&t.push(r)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){let n=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder,e.initialRotation);n!==void 0&&t.push(n)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){let n=this.generateVectorTrack(e.modelName,e.S.curves,r,`scale`);n!==void 0&&t.push(n)}if(e.DeformPercent!==void 0){let n=this.generateMorphTrack(e);n!==void 0&&t.push(n)}return t}generateVectorTrack(e,t,n,r){let i=this.getTimesForAllAxes(t),a=this.getKeyframeTrackValues(i,t,n);return new eu(e+`.`+r,i,a)}generateRotationTrack(e,t,n,r,i,a){let o,s;if(t.x!==void 0||t.y!==void 0||t.z!==void 0){let e=this.getTimesForAllAxes(t);if(e.length>0){let n=a||[0,0,0],r=this.synchronizeCurve(t.x,e,n[0]),c=this.synchronizeCurve(t.y,e,n[1]),l=this.synchronizeCurve(t.z,e,n[2]),u=this.interpolateRotations(r,c,l,i);o=u[0],s=u[1]}}let c=Ch(0);n!==void 0&&(n=n.map(Hn.degToRad),n.push(c),n=new Cr().fromArray(n),n=new z().setFromEuler(n)),r!==void 0&&(r=r.map(Hn.degToRad),r.push(c),r=new Cr().fromArray(r),r=new z().setFromEuler(r).invert());let l=new z,u=new Cr,d=[];if(!(!s||!o)){for(let e=0;e<s.length;e+=3)u.set(s[e],s[e+1],s[e+2],i),l.setFromEuler(u),n!==void 0&&l.premultiply(n),r!==void 0&&l.multiply(r),e>2&&new z().fromArray(d,(e-3)/3*4).dot(l)<0&&l.set(-l.x,-l.y,-l.z,-l.w),l.toArray(d,e/3*4);return new Ql(e+`.quaternion`,o,d)}}generateMorphTrack(e){let t=e.DeformPercent.curves.morph,n=t.values.map(function(e){return e/100}),r=ah.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new Xl(e.modelName+`.morphTargetInfluences[`+r+`]`,t.times,n)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(e,t){return e-t}),t.length>1){let e=1,n=t[0];for(let r=1;r<t.length;r++){let i=t[r];i!==n&&(t[e]=i,n=i,e++)}t=t.slice(0,e)}return t}getKeyframeTrackValues(e,t,n){let r=n,i=[],a=-1,o=-1,s=-1;return e.forEach(function(e){if(t.x&&(a=t.x.times.indexOf(e)),t.y&&(o=t.y.times.indexOf(e)),t.z&&(s=t.z.times.indexOf(e)),a!==-1){let e=t.x.values[a];i.push(e),r[0]=e}else i.push(r[0]);if(o!==-1){let e=t.y.values[o];i.push(e),r[1]=e}else i.push(r[1]);if(s!==-1){let e=t.z.values[s];i.push(e),r[2]=e}else i.push(r[2])}),i}synchronizeCurve(e,t,n){if(e===void 0)return{times:t,values:t.map(()=>n)};if(e.times.length===t.length)return e;let r=[];for(let i=0;i<t.length;i++)r.push(this.sampleCurveValue(e,t[i],n));return{times:t,values:r}}sampleCurveValue(e,t,n){let r=e.times,i=e.values;if(t<=r[0])return i[0];if(t>=r[r.length-1])return i[i.length-1];for(let e=0;e<r.length-1;e++)if(t>=r[e]&&t<=r[e+1]){if(r[e]===t)return i[e];let n=(t-r[e])/(r[e+1]-r[e]);return i[e]*(1-n)+i[e+1]*n}return n}interpolateRotations(e,t,n,r){let i=[],a=[];i.push(e.times[0]),a.push(Hn.degToRad(e.values[0])),a.push(Hn.degToRad(t.values[0])),a.push(Hn.degToRad(n.values[0]));for(let o=1;o<e.values.length;o++){let s=[e.values[o-1],t.values[o-1],n.values[o-1]];if(isNaN(s[0])||isNaN(s[1])||isNaN(s[2]))continue;let c=s.map(Hn.degToRad),l=[e.values[o],t.values[o],n.values[o]];if(isNaN(l[0])||isNaN(l[1])||isNaN(l[2]))continue;let u=l.map(Hn.degToRad),d=[l[0]-s[0],l[1]-s[1],l[2]-s[2]],f=[Math.abs(d[0]),Math.abs(d[1]),Math.abs(d[2])];if(f[0]>=180||f[1]>=180||f[2]>=180){let t=Math.max(...f)/180,n=new Cr(...c,r),s=new Cr(...u,r),l=new z().setFromEuler(n),d=new z().setFromEuler(s);l.dot(d)<0&&d.set(-d.x,-d.y,-d.z,-d.w);let p=e.times[o-1],m=e.times[o]-p,h=new z,g=new Cr;for(let e=0;e<1;e+=1/t)h.copy(l.clone().slerp(d.clone(),e)),i.push(p+e*m),g.setFromQuaternion(h,r),a.push(g.x),a.push(g.y),a.push(g.z)}else i.push(e.times[o]),a.push(Hn.degToRad(e.values[o])),a.push(Hn.degToRad(t.values[o])),a.push(Hn.degToRad(n.values[o]))}return[i,a]}},uh=class{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),--this.currentIndent}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new ph,this.nodeStack=[],this.currentProp=[],this.currentPropName=``;let t=this,n=e.split(/[\r\n]+/);return n.forEach(function(e,r){let i=e.match(/^[\s\t]*;/),a=e.match(/^[\s\t]*$/);if(i||a)return;let o=e.match(`^\\t{`+t.currentIndent+`}(\\w+):(.*){`,``),s=e.match(`^\\t{`+t.currentIndent+`}(\\w+):[\\s\\t\\r\\n](.*)`),c=e.match(`^\\t{`+(t.currentIndent-1)+`}}`);o?t.parseNodeBegin(e,o):s?t.parseNodeProperty(e,s,n[++r]):c?t.popStack():e.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(e)}),this.allNodes}parseNodeBegin(e,t){let n=t[1].trim().replace(/^"/,``).replace(/"$/,``),r=t[2].split(`,`).map(function(e){return e.trim().replace(/^"/,``).replace(/"$/,``)}),i={name:n},a=this.parseNodeAttr(r),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(n,i):n in o?(n===`PoseNode`?o.PoseNode.push(i):o[n].id!==void 0&&(o[n]={},o[n][o[n].id]=o[n]),a.id!==``&&(o[n][a.id]=i)):typeof a.id==`number`?(o[n]={},o[n][a.id]=i):n!==`Properties70`&&(o[n]=n===`PoseNode`?[i]:i),typeof a.id==`number`&&(i.id=a.id),a.name!==``&&(i.attrName=a.name),a.type!==``&&(i.attrType=a.type),this.pushStack(i)}parseNodeAttr(e){let t=e[0];e[0]!==``&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let n=``,r=``;return e.length>1&&(n=e[1].replace(/^(\w+)::/,``),r=e[2]),{id:t,name:n,type:r}}parseNodeProperty(e,t,n){let r=t[1].replace(/^"/,``).replace(/"$/,``).trim(),i=t[2].replace(/^"/,``).replace(/"$/,``).trim();r===`Content`&&i===`,`&&(i=n.replace(/"/g,``).replace(/,$/,``).trim());let a=this.getCurrentNode();if(a.name===`Properties70`){this.parseNodeSpecialProperty(e,r,i);return}if(r===`C`){let e=i.split(`,`).slice(1),t=parseInt(e[0]),n=parseInt(e[1]),o=i.split(`,`).slice(3);o=o.map(function(e){return e.trim().replace(/^"/,``)}),r=`connections`,i=[t,n],Eh(i,o),a[r]===void 0&&(a[r]=[])}r===`Node`&&(a.id=i),r in a&&Array.isArray(a[r])?a[r].push(i):r===`a`?a.a=i:a[r]=i,this.setCurrentProp(a,r),r===`a`&&i.slice(-1)!==`,`&&(a.a=wh(i))}parseNodePropertyContinued(e){let t=this.getCurrentNode();t.a+=e,e.slice(-1)!==`,`&&(t.a=wh(t.a))}parseNodeSpecialProperty(e,t,n){let r=n.split(`",`).map(function(e){return e.trim().replace(/^\"/,``).replace(/\s/,`_`)}),i=r[0],a=r[1],o=r[2],s=r[3],c=r[4];switch(a){case`int`:case`enum`:case`bool`:case`ULongLong`:case`double`:case`Number`:case`FieldOfView`:c=parseFloat(c);break;case`Color`:case`ColorRGB`:case`Vector3D`:case`Lcl_Translation`:case`Lcl_Rotation`:case`Lcl_Scaling`:c=wh(c)}this.getPrevNode()[i]={type:a,type2:o,flag:s,value:c},this.setCurrentProp(this.getPrevNode(),i)}},dh=class{parse(e){let t=new fh(e);t.skip(23);let n=t.getUint32();if(n<6400)throw Error(`THREE.FBXLoader: FBX version not supported, FileVersion: `+n);let r=new ph;for(;!this.endOfContent(t);){let e=this.parseNode(t,n);e!==null&&r.add(e.name,e)}return r}endOfContent(e){return e.size()%16==0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){let n={},r=t>=7500?e.getUint64():e.getUint32(),i=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();let a=e.getUint8(),o=e.getString(a);if(r===0)return null;let s=[];for(let t=0;t<i;t++)s.push(this.parseProperty(e));let c=s.length>0?s[0]:``,l=s.length>1?s[1]:``,u=s.length>2?s[2]:``;for(n.singleProperty=i===1&&e.getOffset()===r;r>e.getOffset();){let r=this.parseNode(e,t);r!==null&&this.parseSubNode(o,n,r)}return n.propertyList=s,typeof c==`number`&&(n.id=c),l!==``&&(n.attrName=l),u!==``&&(n.attrType=u),o!==``&&(n.name=o),n}parseSubNode(e,t,n){if(n.singleProperty===!0){let e=n.propertyList[0];Array.isArray(e)?(t[n.name]=n,n.a=e):t[n.name]=e}else if(e===`Connections`&&n.name===`C`){let e=[];n.propertyList.forEach(function(t,n){n!==0&&e.push(t)}),t.connections===void 0&&(t.connections=[]),t.connections.push(e)}else if(n.name===`Properties70`)Object.keys(n).forEach(function(e){t[e]=n[e]});else if(e===`Properties70`&&n.name===`P`){let e=n.propertyList[0],r=n.propertyList[1],i=n.propertyList[2],a=n.propertyList[3],o;e.indexOf(`Lcl `)===0&&(e=e.replace(`Lcl `,`Lcl_`)),r.indexOf(`Lcl `)===0&&(r=r.replace(`Lcl `,`Lcl_`)),o=r===`Color`||r===`ColorRGB`||r===`Vector`||r===`Vector3D`||r.indexOf(`Lcl_`)===0?[n.propertyList[4],n.propertyList[5],n.propertyList[6]]:n.propertyList[4],t[e]={type:r,type2:i,flag:a,value:o}}else t[n.name]===void 0?typeof n.id==`number`?(t[n.name]={},t[n.name][n.id]=n):t[n.name]=n:n.name===`PoseNode`?(Array.isArray(t[n.name])||(t[n.name]=[t[n.name]]),t[n.name].push(n)):t[n.name][n.id]===void 0&&(t[n.name][n.id]=n)}parseProperty(e){let t=e.getString(1),n;switch(t){case`C`:return e.getBoolean();case`D`:return e.getFloat64();case`F`:return e.getFloat32();case`I`:return e.getInt32();case`L`:return e.getInt64();case`R`:return n=e.getUint32(),e.getArrayBuffer(n);case`S`:return n=e.getUint32(),e.getString(n);case`Y`:return e.getInt16();case`b`:case`c`:case`d`:case`f`:case`i`:case`l`:let r=e.getUint32(),i=e.getUint32(),a=e.getUint32();if(i===0)switch(t){case`b`:case`c`:return e.getBooleanArray(r);case`d`:return e.getFloat64Array(r);case`f`:return e.getFloat32Array(r);case`i`:return e.getInt32Array(r);case`l`:return e.getInt64Array(r)}let o=new fh(qm(new Uint8Array(e.getArrayBuffer(a))).buffer);switch(t){case`b`:case`c`:return o.getBooleanArray(r);case`d`:return o.getFloat64Array(r);case`f`:return o.getFloat32Array(r);case`i`:return o.getInt32Array(r);case`l`:return o.getInt64Array(r)}break;default:throw Error(`THREE.FBXLoader: Unknown property type `+t)}}},fh=class{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t===void 0||t,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)==1}getBooleanArray(e){let t=[];for(let n=0;n<e;n++)t.push(this.getBoolean());return t}getUint8(){let e=this.dv.getUint8(this.offset);return this.offset+=1,e}getInt16(){let e=this.dv.getInt16(this.offset,this.littleEndian);return this.offset+=2,e}getInt32(){let e=this.dv.getInt32(this.offset,this.littleEndian);return this.offset+=4,e}getInt32Array(e){let t=[];for(let n=0;n<e;n++)t.push(this.getInt32());return t}getUint32(){let e=this.dv.getUint32(this.offset,this.littleEndian);return this.offset+=4,e}getInt64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t&2147483648?(t=~t&4294967295,e=~e&4294967295,e===4294967295&&(t=t+1&4294967295),e=e+1&4294967295,-(t*4294967296+e)):t*4294967296+e}getInt64Array(e){let t=[];for(let n=0;n<e;n++)t.push(this.getInt64());return t}getUint64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t*4294967296+e}getFloat32(){let e=this.dv.getFloat32(this.offset,this.littleEndian);return this.offset+=4,e}getFloat32Array(e){let t=[];for(let n=0;n<e;n++)t.push(this.getFloat32());return t}getFloat64(){let e=this.dv.getFloat64(this.offset,this.littleEndian);return this.offset+=8,e}getFloat64Array(e){let t=[];for(let n=0;n<e;n++)t.push(this.getFloat64());return t}getArrayBuffer(e){let t=this.dv.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}getString(e){let t=this.offset,n=new Uint8Array(this.dv.buffer,t,e);this.skip(e);let r=n.indexOf(0);return r>=0&&(n=new Uint8Array(this.dv.buffer,t,r)),this._textDecoder.decode(n)}},ph=class{add(e,t){this[e]=t}};function mh(e){return e.byteLength>=21&&Th(e,0,21)===`Kaydara FBX Binary \0`}function hh(e){let t=[`K`,`a`,`y`,`d`,`a`,`r`,`a`,`\\`,`F`,`B`,`X`,`\\`,`B`,`i`,`n`,`a`,`r`,`y`,`\\`,`\\`],n=0;function r(t){let r=e[t-1];return e=e.slice(n+t),n++,r}for(let e=0;e<t.length;++e)if(r(1)===t[e])return!1;return!0}function gh(e){let t=e.match(/FBXVersion: (\d+)/);if(t)return parseInt(t[1]);throw Error(`THREE.FBXLoader: Cannot find the version number for the file given.`)}function _h(e){return e/46186158e3}var vh=[];function yh(e,t,n,r){let i;switch(r.mappingType){case`ByPolygonVertex`:i=e;break;case`ByPolygon`:i=t;break;case`ByVertice`:i=n;break;case`AllSame`:i=r.indices[0];break;default:console.warn(`THREE.FBXLoader: unknown attribute mapping type `+r.mappingType)}r.referenceType===`IndexToDirect`&&(i=r.indices[i]);let a=i*r.dataSize,o=a+r.dataSize;return Dh(vh,r.buffer,a,o)}var bh=new Cr,xh=new B;function Sh(e){let t=new V,n=new V,r=new V,i=new V,a=new V,o=new V,s=new V,c=new V,l=new V,u=new V,d=new V,f=new V,p=e.inheritType?e.inheritType:0;e.translation&&t.setPosition(xh.fromArray(e.translation));let m=Ch(0);if(e.preRotation){let t=e.preRotation.map(Hn.degToRad);t.push(m),n.makeRotationFromEuler(bh.fromArray(t))}if(e.rotation){let t=e.rotation.map(Hn.degToRad);t.push(e.eulerOrder||m),r.makeRotationFromEuler(bh.fromArray(t))}if(e.postRotation){let t=e.postRotation.map(Hn.degToRad);t.push(m),i.makeRotationFromEuler(bh.fromArray(t)),i.invert()}e.scale&&a.scale(xh.fromArray(e.scale)),e.scalingOffset&&s.setPosition(xh.fromArray(e.scalingOffset)),e.scalingPivot&&o.setPosition(xh.fromArray(e.scalingPivot)),e.rotationOffset&&c.setPosition(xh.fromArray(e.rotationOffset)),e.rotationPivot&&l.setPosition(xh.fromArray(e.rotationPivot)),e.parentMatrixWorld&&(d.copy(e.parentMatrix),u.copy(e.parentMatrixWorld));let h=n.clone().multiply(r).multiply(i),g=new V;g.extractRotation(u);let _=new V;_.copyPosition(u);let v=_.clone().invert().multiply(u),y=g.clone().invert().multiply(v),b=a,x=new V;if(p===0)x.copy(g).multiply(h).multiply(y).multiply(b);else if(p===1)x.copy(g).multiply(y).multiply(h).multiply(b);else{let e=new V().scale(new B().setFromMatrixScale(d)).clone().invert(),t=y.clone().multiply(e);x.copy(g).multiply(h).multiply(t).multiply(b)}let S=l.clone().invert(),C=o.clone().invert(),w=t.clone().multiply(c).multiply(l).multiply(n).multiply(r).multiply(i).multiply(S).multiply(s).multiply(o).multiply(a).multiply(C),T=new V().copyPosition(w),E=u.clone().multiply(T);return f.copyPosition(E),w=f.clone().multiply(x),w.premultiply(u.invert()),w}function Ch(e){e||=0;let t=[`ZYX`,`YZX`,`XZY`,`ZXY`,`YXZ`,`XYZ`];return e===6?(console.warn(`THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.`),t[0]):t[e]}function wh(e){return e.split(`,`).map(function(e){return parseFloat(e)})}function Th(e,t,n){return t===void 0&&(t=0),n===void 0&&(n=e.byteLength),new TextDecoder().decode(new Uint8Array(e,t,n))}function Eh(e,t){for(let n=0,r=e.length,i=t.length;n<i;n++,r++)e[r]=t[n]}function Dh(e,t,n,r){for(let i=n,a=0;i<r;i++,a++)e[a]=t[i];return e}var Oh=`Kaydara FBX Binary \0`,kh=65536;function Ah(e){return e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null}function jh(e){return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):null}function Mh(e){let t=Ah(e);if(!t||t.byteLength<21)return!1;for(let e=0;e<21;e++)if(t[e]!==Oh.charCodeAt(e))return!1;return!0}function Nh(e){let t=Ah(e);if(!t||!t.byteLength)return null;let n=t.subarray(0,Math.min(t.byteLength,kh)),r=new TextDecoder(`utf-8`).decode(n).match(/FBXVersion: (\d+)/);if(!r)return null;let i=Number(r[1]);return Number.isFinite(i)?i:null}function Ph(e){let t=jh(e);return!t||!t.byteLength?null:new oh().parse(t,``)}function Fh(e){try{let t=Ph(e);if(!t)return null;t.updateMatrixWorld(!0);let n=new fi().setFromObject(t),r=n.getSize(new B);return!(r.y>0)||!Number.isFinite(r.y)?null:{min:{x:n.min.x,y:n.min.y,z:n.min.z},max:{x:n.max.x,y:n.max.y,z:n.max.z}}}catch{return null}}var Ih=.05,Lh=1179937895,Rh=1313821514,zh=12,Bh=8;function Vh(e){return e instanceof ArrayBuffer?new DataView(e):ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):null}function Hh(e){let t=Vh(e);return!!(t&&t.byteLength>=4&&t.getUint32(0,!0)===Lh)}function Uh(e){let t=Vh(e);if(!t||t.byteLength<zh||t.getUint32(0,!0)!==Lh)return null;let n=zh;for(;n+Bh<=t.byteLength;){let e=t.getUint32(n,!0),r=t.getUint32(n+4,!0),i=n+Bh;if(e>t.byteLength-i)return null;if(r===Rh){let n=new Uint8Array(t.buffer,t.byteOffset+i,e);try{let e=n.length;for(;e>0&&n[e-1]===0;)--e;return JSON.parse(new TextDecoder().decode(n.subarray(0,e)))}catch{return null}}n=i+e}return null}function Wh(e){let t=Uh(e);if(!t||typeof t!=`object`)return null;let n=Array.isArray(t.accessors)?t.accessors:[],r=new Set;for(let e of Array.isArray(t.meshes)?t.meshes:[])for(let t of Array.isArray(e?.primitives)?e.primitives:[]){let e=t?.attributes?.POSITION;Number.isInteger(e)&&r.add(e)}let i=null;for(let e of r){let t=n[e],r=t?.min,a=t?.max;if(!Array.isArray(r)||!Array.isArray(a)||r.length!==3||a.length!==3)continue;let o=[Number(r[0]),Number(r[1]),Number(r[2])],s=[Number(a[0]),Number(a[1]),Number(a[2])];if(!(o.some(e=>!Number.isFinite(e))||s.some(e=>!Number.isFinite(e)))){if(!i){i={min:{x:o[0],y:o[1],z:o[2]},max:{x:s[0],y:s[1],z:s[2]}};continue}i.min.x=Math.min(i.min.x,o[0]),i.min.y=Math.min(i.min.y,o[1]),i.min.z=Math.min(i.min.z,o[2]),i.max.x=Math.max(i.max.x,s[0]),i.max.y=Math.max(i.max.y,s[1]),i.max.z=Math.max(i.max.z,s[2])}}return i}var Gh=new Set([`KHR_draco_mesh_compression`,`EXT_meshopt_compression`]),Kh=`That model is compressed — export it uncompressed (no Draco / meshopt)`;function qh(e){let t=new Set;if(!e||typeof e!=`object`)return t;for(let n of[e.extensionsUsed,e.extensionsRequired])if(Array.isArray(n))for(let e of n)typeof e==`string`&&t.add(e);for(let n of Array.isArray(e.meshes)?e.meshes:[])for(let e of Array.isArray(n?.primitives)?n.primitives:[]){let n=e?.extensions;if(!(!n||typeof n!=`object`))for(let e of Object.keys(n))t.add(e)}return t}function Jh(e){let t=Uh(e);if(!t)return null;for(let e of qh(t))if(Gh.has(e))return Kh;return null}function Yh(e){return e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):null}function Xh(e){let t=Yh(e);if(!t||!t.byteLength)return``;let n=new TextDecoder(`utf-8`).decode(t);return n.charCodeAt(0)===65279&&(n=n.slice(1)),n}function Zh(e){let t=Xh(e);if(!t)return null;let n=null;for(let e of t.split(/\r?\n/)){let t=e.trim();if(!/^v(?:\s|$)/.test(t))continue;let r=t.split(/\s+/);if(r[0]!==`v`)continue;let i=Number(r[1]),a=Number(r[2]),o=Number(r[3]);if([i,a,o].every(Number.isFinite)){if(!n){n={min:{x:i,y:a,z:o},max:{x:i,y:a,z:o}};continue}n.min.x=Math.min(n.min.x,i),n.min.y=Math.min(n.min.y,a),n.min.z=Math.min(n.min.z,o),n.max.x=Math.max(n.max.x,i),n.max.y=Math.max(n.max.y,a),n.max.z=Math.max(n.max.z,o)}}return n}function Qh(e){let t=String(e?.type??``).toLowerCase();return t===`model/obj`?Zh(e?.bytes):t===`model/fbx`?Fh(e?.bytes):t===`model/gltf-binary`?Wh(e?.bytes):null}function $h({min:e,max:t}={}){let n=Number(t?.x)-Number(e?.x),r=Number(t?.y)-Number(e?.y),i=Number(t?.z)-Number(e?.z);if(!Number.isFinite(r)||!(r>0))return null;let a=r<.05||r>10?1/r:1,o=n*a,s=r*a,c=i*a;return{width:o,height:s,depth:c,fitScale:a,footprint:{width:o,depth:c}}}function eg(e){if(!e)return!1;let t=typeof e.type==`string`?e.type.toLowerCase():``;return t===`model/gltf-binary`||t===`application/gltf-binary`?!0:t===``||t===`application/octet-stream`?String(e.name??``).toLowerCase().endsWith(`.glb`):!1}function tg(e){if(!e)return!1;let t=typeof e.type==`string`?e.type.toLowerCase():``;return t===`model/obj`?!0:String(e.name??``).toLowerCase().endsWith(`.obj`)?t===``||t===`text/plain`||t===`application/octet-stream`||t===`text/x-obj`||t===`application/object`:!1}function ng(e){if(!e)return!1;let t=typeof e.type==`string`?e.type.toLowerCase():``;return t===`model/fbx`?!0:String(e.name??``).toLowerCase().endsWith(`.fbx`)?t===``||t===`text/plain`||t===`application/octet-stream`:!1}function rg(e){return Array.from(e?.files??[]).filter(e=>eg(e)||tg(e)||ng(e))}function ig(e){return e?Array.isArray(e)?e:typeof e.length==`number`&&e.files==null?Array.from(e):Array.from(e.files??[]):[]}function ag(e){let t=[],n=[],r=[];for(let i of ig(e))rg({files:[i]}).length?n.push(i):tm({files:[i]}).length?t.push(i):r.push(i);return{images:t,meshes:n,rejected:r}}async function og(e,t=globalThis.crypto?.subtle){if(!e||typeof e.arrayBuffer!=`function`)throw Error(`importMeshFile needs a File or Blob`);if(Number(e.size)>33554432)throw Error(`That model is too large to import — larger than ${Math.round(Rp/1048576)} MB`);let n=await e.arrayBuffer(),r=typeof e.name==`string`?e.name:``,i=eg(e)||r.toLowerCase().endsWith(`.glb`),a=ng(e)||r.toLowerCase().endsWith(`.fbx`),o=tg(e)||r.toLowerCase().endsWith(`.obj`);if(Hh(n)){let e=Jh(n);if(e)throw Error(e);let i=Wh(n),a=i?$h(i):null;if(!a)throw Error(`That model has no measurable geometry`);let o=em({id:await Zp(n,t),type:`model/gltf-binary`,bytes:n,name:r});if(!o)throw Error(`That model could not be prepared for the set`);return{asset:o,height:a.height,footprint:a.footprint}}if(i)throw Error(`That file is not a GLB model`);let s=Nh(n);if(Mh(n)||(s??0)>=7e3)try{let e=Fh(n),i=e?$h(e):null;if(!i)throw Error(`That model has no measurable geometry`);let a=em({id:await Zp(n,t),type:`model/fbx`,bytes:n,name:r});if(!a)throw Error(`That model could not be prepared for the set`);return{asset:a,height:i.height,footprint:i.footprint}}catch(e){throw sg(e)}if(s!=null&&s<7e3)throw Error(`That FBX file is too old to import`);if(a)throw Error(`That file is not an FBX model`);let c=Zh(n);if(!c)throw Error(o?`That file is not an OBJ model`:`That file is not a 3D model`);let l=$h(c);if(!l)throw Error(`That model has no measurable geometry`);let u=em({id:await Zp(n,t),type:`model/obj`,bytes:n,name:r});if(!u)throw Error(`That model could not be prepared for the set`);return{asset:u,height:l.height,footprint:l.footprint}}function sg(e){let t=String(e?.message??e);return/too old to import/i.test(t)||/no measurable geometry/i.test(t)||/not an FBX/i.test(t)?e instanceof Error?e:Error(t):/version not supported|FileVersion/i.test(t)?Error(`That FBX file is too old to import`):Error(`That file is not an FBX model`)}var cg=[],lg=`XYZ`,ug=Math.PI/180,dg=i(`object.position`),fg=i(`object.rotation`),pg=i(`object.scale`),mg=(e,t,n)=>Math.min(n,Math.max(t,e)),hg=e=>{let t=fg.min.y,n=fg.max.y-t;return((e-t)%n+n)%n+t},gg=(e,t)=>Number((t>0?Math.round(e/t)*t:e).toFixed(4)),_g=`#c2c6c8`,vg=[{kind:`cube`,label:`Cube`,group:`Primitives`,footprint:{width:1,depth:1},height:1,color:_g},{kind:`sphere`,label:`Sphere`,group:`Primitives`,footprint:{width:1,depth:1},height:1,color:_g},{kind:`capsule`,label:`Capsule`,group:`Primitives`,footprint:{width:.7,depth:.7},height:1.4,color:_g},{kind:`cylinder`,label:`Cylinder`,group:`Primitives`,footprint:{width:1,depth:1},height:1,color:_g},{kind:`cone`,label:`Cone`,group:`Primitives`,footprint:{width:1,depth:1},height:1,color:_g},{kind:`plane`,label:`Plane`,group:`Primitives`,footprint:{width:2,depth:2},height:0,color:_g},{kind:`chair`,label:`Chair`,group:`Set pieces`,footprint:{width:.6,depth:.6},height:1.15,supportY:.495,color:`#b9855d`},{kind:`car`,label:`Car`,group:`Set pieces`,footprint:{width:1.8,depth:4.5},height:1.4,color:`#d98770`},{kind:`small-plane`,label:`Plane (aircraft)`,group:`Set pieces`,footprint:{width:3.4,depth:3.6},height:1.4,color:`#7896a4`}],yg=[`#e2e5e6`,_g,`#9aa1a5`,`#767d81`,`#d9b18c`,`#8fae9b`,`#d94a4a`,`#4a7bd9`,`#e2c04a`,`#4fa86a`],bg=`cozyclay.objectColors.recent`,xg=/^#?([0-9a-f]{3})$/i,Sg=/^#?([0-9a-f]{6})$/i;function Cg(e){if(typeof e!=`string`)return null;let t=e.trim(),n=xg.exec(t);if(n)return`#${n[1].toLowerCase().replace(/./g,e=>e+e)}`;let r=Sg.exec(t);return r?`#${r[1].toLowerCase()}`:null}function wg(e,t){let n=Array.isArray(e)?e.map(Cg).filter((e,t,n)=>e&&n.indexOf(e)===t&&!yg.includes(e)):[],r=Cg(t),i=(r&&!yg.includes(r)?[r,...n.filter(e=>e!==r)]:n).slice(0,6);return Array.isArray(e)&&i.length===e.length&&i.every((t,n)=>t===e[n])?e:i}function Tg(e){try{let t=JSON.parse(e?.getItem(`cozyclay.objectColors.recent`)??`[]`);return wg(Array.isArray(t)?t:[],null)}catch{return[]}}function Eg(e,t){try{e?.setItem(bg,JSON.stringify(t))}catch{}}var Dg=`cutout`,Og=.02,kg=1.8,Ag=.05,jg=.02,Mg=50,Ng=`#ffffff`,Pg={kind:Dg,label:`Cutout`,group:`Images`,footprint:{width:1,depth:Og},height:kg,color:Ng},Fg=`mesh`,Ig={kind:Fg,label:`Model`,group:`Models`,footprint:{width:1,depth:1},height:1,color:`#c49a6c`};function Lg(e){return e===`cutout`?Pg:e===`mesh`?Ig:vg.find(t=>t.kind===e)??null}function Rg(e){if(!e||typeof e!=`object`)return 0;let t=Lg(e.renderer),n=Number(e.supportY??t?.supportY??e.height??t?.height);return Number.isFinite(n)?n:0}var zg=e=>Math.max(Ag,e),Bg=e=>mg(e,jg,Mg),Vg=.1,Hg=e=>{let t=Number(e);return Number.isFinite(t)?mg(t,Vg,10):1};function Ug(e,t,n=1){return{width:zg(e)*Bg(t)*Hg(n),depth:Og}}var Wg=Object.freeze([`hips`,`spine`,`chest`,`neck`,`head`,`leftShoulder`,`leftElbow`,`leftHand`,`rightShoulder`,`rightElbow`,`rightHand`,`leftKnee`,`leftFoot`,`rightKnee`,`rightFoot`]);function Gg(e){if(e===null)return null;if(!e||typeof e!=`object`||Array.isArray(e))return;let{characterId:t,bone:n}=e;if(!(typeof t!=`string`||!t)){if(n==null)return{characterId:t,bone:null};if(!(typeof n!=`string`||!Wg.includes(n)))return{characterId:t,bone:n}}}function Kg(e){return e.startsWith(`object:`)?e.slice(7):null}function qg(e,t=[],n={}){if(e===`cutout`||e===`mesh`)return null;let r=Lg(e);if(!r)return null;let i=new Set(t.map(e=>e.name)),a=r.label;for(let e=2;i.has(a);e+=1)a=`${r.label} ${e}`;let o=new Set(t.map(e=>e.id)),s=e;for(let t=2;o.has(s);t+=1)s=`${e}-${t}`;return{id:s,name:a,renderer:e,x:Qg.x(Number(n.x)||0),y:0,z:Qg.z(Number(n.z)||0),rot:Qg.rot(Number(n.rot)||0),rotX:0,rotZ:0,scaleX:1,scaleY:1,scaleZ:1,path:null,color:r.color,parent:null,attach:null,hidden:!1,footprint:{...r.footprint},height:r.height,supportY:Number.isFinite(r.supportY)?r.supportY:r.height}}function Jg({assetId:e,aspect:t=1,height:n=kg,name:r=``,sourceAssetId:i,matteAssetId:a,matteScale:o,stretch:s}={},c=[],l={}){if(typeof e!=`string`||!e)return null;let u=Bg(Number(t)),d=zg(Number(n));if(!Number.isFinite(u)||!Number.isFinite(d))return null;let f=Hg(s),p=typeof r==`string`&&r.trim()?r.trim():Pg.label,m=new Set(c.map(e=>e.name)),h=p;for(let e=2;m.has(h);e+=1)h=`${p} ${e}`;let g=new Set(c.map(e=>e.id)),_=Dg;for(let e=2;g.has(_);e+=1)_=`${Dg}-${e}`;return{id:_,name:h,renderer:Dg,x:Qg.x(Number(l.x)||0),y:0,z:Qg.z(Number(l.z)||0),rot:Qg.rot(Number(l.rot)||0),rotX:0,rotZ:0,scaleX:1,scaleY:1,scaleZ:1,path:null,color:Ng,parent:null,attach:null,hidden:!1,assetId:e,sourceAssetId:typeof i==`string`&&i?i:e,matteAssetId:typeof a==`string`?a:``,matteScale:Number.isFinite(Number(o))?Number(o):1,aspect:u,stretch:f,footprint:Ug(d,u,f),height:d}}function Yg(e){return{assetId:e.assetId,aspect:e.aspect,height:e.height,name:e.name,sourceAssetId:e.sourceAssetId,matteAssetId:e.matteAssetId,matteScale:e.matteScale,stretch:e.stretch}}function Xg({assetId:e,height:t=1,footprint:n,name:r=``,clay:i=!1}={},a=[],o={}){if(typeof e!=`string`||!e)return null;let s=Math.max(Ih,Number(t));if(!Number.isFinite(s))return null;let c=Number(n?.width),l=Number(n?.depth),u=Number.isFinite(c)&&c>0&&Number.isFinite(l)&&l>0?{width:c,depth:l}:{width:s,depth:s},d=typeof r==`string`&&r.trim()?r.trim():Ig.label,f=new Set(a.map(e=>e.name)),p=d;for(let e=2;f.has(p);e+=1)p=`${d} ${e}`;let m=new Set(a.map(e=>e.id)),h=Fg;for(let e=2;m.has(h);e+=1)h=`${Fg}-${e}`;return{id:h,name:p,renderer:Fg,x:Qg.x(Number(o.x)||0),y:0,z:Qg.z(Number(o.z)||0),rot:hg(Number(o.rot)||0),rotX:0,rotZ:0,scaleX:1,scaleY:1,scaleZ:1,path:null,color:Ig.color,parent:null,attach:null,hidden:!1,assetId:e,clay:i===!0,footprint:u,height:s}}function Zg(e){return{assetId:e.assetId,height:e.height,footprint:e.footprint,name:e.name,clay:e.clay===!0}}var Qg={x:e=>mg(e,dg.min.x,dg.max.x),y:e=>mg(e,dg.min.y,dg.max.y),z:e=>mg(e,dg.min.z,dg.max.z),rot:e=>hg(e),rotX:e=>hg(e),rotZ:e=>hg(e),scaleX:e=>mg(e,pg.min.x,pg.max.x),scaleY:e=>mg(e,pg.min.y,pg.max.y),scaleZ:e=>mg(e,pg.min.z,pg.max.z)};function $g(e,t){let n=[],r=new Set([t]),i=[t];for(;i.length;){let t=[];for(let a of e)a.parent&&i.includes(a.parent)&&!r.has(a.id)&&(r.add(a.id),n.push(a),t.push(a.id));i=t}return n}function e_(e,t=[],n=[]){if(!e||typeof e!=`object`)return!1;let r=new Map;for(let e of t)e&&typeof e.id==`string`&&r.set(e.id,e);let i=e=>n.some(t=>t&&typeof t==`object`&&t.id===e&&t.hidden===!0),a=new Set,o=e;for(;o&&typeof o==`object`;){let e=typeof o.id==`string`?o.id:null;if(e){if(a.has(e))break;a.add(e),r.has(e)&&(o=r.get(e))}if(o.hidden===!0)return!0;let t=o.attach&&typeof o.attach.characterId==`string`?o.attach.characterId:null;if(t&&i(t))return!0;let n=typeof o.parent==`string`?o.parent:null;if(!n)break;o=r.get(n)??null}return!1}function t_(e,t,n){let r=!1,i=e.find(e=>e.id===t),a=i?$g(e,t):[],o={x:0,y:0,z:0};if(i)for(let e of[`x`,`y`,`z`]){if(n[e]===void 0)continue;let t=Number(n[e]);Number.isFinite(t)&&(o[e]=Qg[e](t)-i[e])}let s=new Set(a.map(e=>e.id)),c=o.x||o.y||o.z,l=e.map(e=>{if(e.id!==t){if(!c||!s.has(e.id))return e;let t={},n={x:0,y:0,z:0};for(let r of[`x`,`y`,`z`]){if(!o[r])continue;let i=Qg[r](e[r]+o[r]);i!==e[r]&&(t[r]=i,n[r]=i-e[r])}return e.path&&(n.x||n.y||n.z)&&(t.path=Tp(e.path,n)),Object.keys(t).length?(r=!0,{...e,...t}):e}let i={};for(let[t,r]of Object.entries(Qg)){if(n[t]===void 0)continue;let a=Number(n[t]);if(!Number.isFinite(a))continue;let o=r(a);o!==e[t]&&(i[t]=o)}for(let t of[`name`,`color`])typeof n[t]!=`string`||!n[t]||n[t]===e[t]||(i[t]=n[t]);if(typeof n.hidden==`boolean`&&n.hidden!==(e.hidden===!0)&&(i.hidden=n.hidden),n.path!==void 0){let t=n.path===null?null:wp(n.path);JSON.stringify(t??null)!==JSON.stringify(e.path??null)&&(i.path=t)}else if(e.path&&c){let t=Tp(e.path,o);JSON.stringify(t??null)!==JSON.stringify(e.path??null)&&(i.path=t)}if(e.renderer===`cutout`){for(let t of[`assetId`,`sourceAssetId`,`matteAssetId`])typeof n[t]==`string`&&n[t]&&n[t]!==e[t]&&(i[t]=n[t]);if(Number.isFinite(Number(n.matteScale))){let t=mg(Number(n.matteScale),.01,1);t!==e.matteScale&&(i.matteScale=t)}let t=n.height===void 0?NaN:zg(Number(n.height)),r=n.aspect===void 0?NaN:Bg(Number(n.aspect)),a=Number.isFinite(t)?t:e.height,o=Number.isFinite(r)?r:e.aspect,s=Hg(e.stretch),c=n.width!==void 0&&Number.isFinite(Number(n.width))?Hg(Number(n.width)/(a*o)):n.stretch===void 0?s:Hg(n.stretch);(a!==e.height||o!==e.aspect||c!==s)&&(i.height=a,i.aspect=o,i.stretch=c,i.footprint=Ug(a,o,c))}if(e.renderer===`mesh`){typeof n.clay==`boolean`&&n.clay!==(e.clay===!0)&&(i.clay=n.clay),typeof n.assetId==`string`&&n.assetId&&n.assetId!==e.assetId&&(i.assetId=n.assetId);let t=n.height===void 0?NaN:Math.max(Ih,Number(n.height));if(Number.isFinite(t)&&t!==e.height){i.height=t;let n=Number(e.height);if(n>0){let r=t/n;i.footprint={width:Number(e.footprint?.width)*r,depth:Number(e.footprint?.depth)*r}}}}return Object.keys(i).length?(r=!0,{...e,...i}):e});return r?l:e}function n_(e,t,n){if(t===n||n!==null&&!e.some(e=>e.id===n)||n!==null&&$g(e,t).some(e=>e.id===n))return e;let r=!1,i=e.map(e=>{if(e.id!==t)return e;let i=n??null,a=i!==null&&(e.attach??null)!==null;return(e.parent??null)===i&&!a?e:(r=!0,a?{...e,parent:i,attach:null}:{...e,parent:i})});return r?i:e}function r_(e,t,n){let r=Gg(n);if(r===void 0||!e.some(e=>e.id===t))return e;let i=!1,a=e.map(e=>{if(e.id!==t)return e;let n=e.attach??null;if(r===null)return n===null?e:(i=!0,{...e,attach:null});let a=n!==null&&n.characterId===r.characterId&&(n.bone??null)===r.bone,o=(e.parent??null)!==null;return a&&!o?e:(i=!0,o?{...e,attach:r,parent:null}:{...e,attach:r})});return i?a:e}function i_(e,t){let n=e.filter(e=>e.id!==t);return n.length===e.length?e:n.map(e=>e.parent===t?{...e,parent:null}:e)}function a_(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=Lg(e.renderer);if(!t||typeof e.id!=`string`||!e.id)return null;let n=t.kind===Dg,r=t.kind===Fg;if(n&&(typeof e.assetId!=`string`||!e.assetId)||r&&(typeof e.assetId!=`string`||!e.assetId))return null;let i=e.scaleX===void 0&&e.scaleY===void 0&&e.scaleZ===void 0?Number(e.scale):NaN,a=Number.isFinite(i)?i:1,o=(e,t)=>{let n=e===void 0?t:Number(e);return Number.isFinite(n)?n:t},s=Number(e.footprint?.width),c=Number(e.footprint?.depth),l=Number.isFinite(s)&&s>0&&Number.isFinite(c)&&c>0?{width:s,depth:c}:{...t.footprint};return{id:e.id,name:typeof e.name==`string`&&e.name?e.name:t.label,renderer:t.kind,x:Qg.x(o(e.x,0)),y:Qg.y(o(e.y,0)),z:Qg.z(o(e.z,0)),rot:Qg.rot(o(e.rot,0)),rotX:Qg.rotX(o(e.rotX,0)),rotZ:Qg.rotZ(o(e.rotZ,0)),scaleX:Qg.scaleX(o(e.scaleX,a)),scaleY:Qg.scaleY(o(e.scaleY,a)),scaleZ:Qg.scaleZ(o(e.scaleZ,a)),path:wp(e.path),color:typeof e.color==`string`&&e.color?e.color:t.color,parent:typeof e.parent==`string`&&e.parent?e.parent:null,attach:Gg(e.attach)??null,hidden:e.hidden===!0,...n?{assetId:e.assetId,sourceAssetId:typeof e.sourceAssetId==`string`&&e.sourceAssetId?e.sourceAssetId:e.assetId,matteAssetId:typeof e.matteAssetId==`string`?e.matteAssetId:``,matteScale:mg(o(e.matteScale,1),.01,1),aspect:Bg(o(e.aspect,1)),stretch:Hg(o(e.stretch,1)),footprint:Ug(o(e.height,kg),o(e.aspect,1),o(e.stretch,1)),height:zg(o(e.height,kg))}:r?{assetId:e.assetId,clay:e.clay===!0,footprint:l,height:Math.max(Ih,o(e.height,t.height))}:{footprint:{...t.footprint},height:t.height,supportY:Number.isFinite(t.supportY)?t.supportY:t.height}}}var o_=[`x`,`y`,`z`],s_={x:`rotX`,y:`rot`,z:`rotZ`},c_={x:`scaleX`,y:`scaleY`,z:`scaleZ`},l_=.05,u_=5,d_=.05;function f_(e,t,n,r=l_){if(!o_.includes(t)||!Number.isFinite(n))return null;let i=gg((e[t]??0)+n,r);return{[t]:i}}function p_(e,t,n,r=u_){let i=s_[t];return!i||!Number.isFinite(n)?null:{[i]:hg(gg((e[i]??0)+n,r))}}function m_(e,t,n,r=d_){if(!Number.isFinite(n)||n<=0)return null;let i=t===null?o_:o_.includes(t)?[t]:[];if(!i.length)return null;let a={};for(let t of i){let i=c_[t];a[i]=Qg[i](gg((e[i]??1)*n,r))}return a}function h_(e,t,n,r=u_){if(!Number.isFinite(n)||!t)return null;let i=gg(n,r),a=new z().setFromEuler(new Cr((e.rotX??0)*ug,(e.rot??0)*ug,(e.rotZ??0)*ug,lg));a.premultiply(new z().setFromAxisAngle(t,i*ug));let o=new Cr().setFromQuaternion(a,lg);return{rotX:hg(gg(o.x/ug,0)),rot:hg(gg(o.y/ug,0)),rotZ:hg(gg(o.z/ug,0))}}function g_(e){return{width:(e.footprint?.width??1)*(e.scaleX??1),height:(e.height??1)*(e.scaleY??1),depth:(e.footprint?.depth??1)*(e.scaleZ??1)}}var __=1e-4;function v_(e){let t=g_(e),n=(e.rot??0)*ug,r=Math.abs(Math.cos(n)),i=Math.abs(Math.sin(n)),a=(t.width*r+t.depth*i)/2,o=(t.width*i+t.depth*r)/2,s=e.x??0,c=e.z??0,l=e.y??0;return{minX:s-a,maxX:s+a,minZ:c-o,maxZ:c+o,baseY:l,topY:l+t.height}}function y_(e,t,n=[]){let r=v_(e),i=0;for(let e of t){if(e_(e,t,n))continue;let a=v_(e);r.minX>=a.maxX-__||a.minX>=r.maxX-__||r.minZ>=a.maxZ-__||a.minZ>=r.maxZ-__||a.topY>r.baseY+__||a.topY>i&&(i=a.topY)}return i===r.baseY?null:{y:i}}function b_(e,t,n=2.6){let r=e.x-Math.sin(t)*n,i=e.z-Math.cos(t)*n;return{x:gg(Qg.x(r),l_),z:gg(Qg.z(i),l_)}}var x_=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),S_=t(((e,t)=>{t.exports=x_()})),C_=t((e=>{var t=g();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),w_=t(((e,t)=>{t.exports=C_()})),T_=t((e=>{var t=g(),n=w_();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),E_=t(((e,t)=>{t.exports=T_()})),Z=`Hips.Spine.Spine1.Spine2.Spine3.Neck.Head.RightShoulder.RightArm.RightForeArm.RightHand.RightHandEnd.RightHandThumb1.LeftShoulder.LeftArm.LeftForeArm.LeftHand.LeftHandEnd.LeftHandThumb1.RightUpLeg.RightLeg.RightFoot.RightToeBase.LeftUpLeg.LeftLeg.LeftFoot.LeftToeBase`.split(`.`),D_=Object.fromEntries(Z.map((e,t)=>[e,t])),O_={Hips:null,Spine:`Hips`,Spine1:`Spine`,Spine2:`Spine1`,Spine3:`Spine2`,Neck:`Spine3`,Head:`Neck`,RightShoulder:`Spine3`,RightArm:`RightShoulder`,RightForeArm:`RightArm`,RightHand:`RightForeArm`,RightHandEnd:`RightHand`,RightHandThumb1:`RightHand`,LeftShoulder:`Spine3`,LeftArm:`LeftShoulder`,LeftForeArm:`LeftArm`,LeftHand:`LeftForeArm`,LeftHandEnd:`LeftHand`,LeftHandThumb1:`LeftHand`,RightUpLeg:`Hips`,RightLeg:`RightUpLeg`,RightFoot:`RightLeg`,RightToeBase:`RightFoot`,LeftUpLeg:`Hips`,LeftLeg:`LeftUpLeg`,LeftFoot:`LeftLeg`,LeftToeBase:`LeftFoot`},k_=Z.map(e=>O_[e]===null?null:D_[O_[e]]),A_=[`Hips`,`Spine`,`Spine1`,`Neck`,`Head`,`LeftShoulder`,`RightShoulder`,`LeftArm`,`RightArm`,`LeftForeArm`,`RightForeArm`,`LeftHand`,`RightHand`,`LeftUpLeg`,`RightUpLeg`,`LeftLeg`,`RightLeg`,`LeftFoot`,`RightFoot`],j_=Object.fromEntries(A_.map(e=>[e,D_[e===`Spine`?`Spine1`:e===`Spine1`?`Spine2`:e]])),M_=1e-12;function N_(e){return typeof e==`number`&&Number.isFinite(e)}function P_(e,t){if(!Array.isArray(e)||e.length!==4||!e.every(N_))throw Error(`${t} must be a [w, x, y, z] quaternion of four finite numbers`);return e}function F_(e,t){if(!Array.isArray(e)||e.length!==3||!e.every(e=>Array.isArray(e)&&e.length===3&&e.every(N_)))throw Error(`${t} must be a row-major 3x3 matrix of finite numbers`);return e}function I_(e,t){if(!Array.isArray(e)||e.length!==3||!e.every(N_))throw Error(`${t} must be an [x, y, z] vector of three finite numbers`);return e}function L_(e,t){if(!Array.isArray(e)||e.length!==k_.length)throw Error(`${t} must hold ${k_.length} entries (one per cskel27 joint)`);return e.forEach((e,n)=>F_(e,`${t}[${n}]`)),e}function R_(e,t){if(!Array.isArray(e)||e.length!==k_.length)throw Error(`${t} must hold ${k_.length} entries (one per cskel27 joint)`);return e.forEach((e,n)=>I_(e,`${t}[${n}]`)),e}function z_(){let e=new Set,t=[];for(k_.forEach((n,r)=>{n===null&&(e.add(r),t.push(r))}),t.sort((e,t)=>e-t);t.length<k_.length;){let n=!1;for(let r=0;r<k_.length;r+=1)!e.has(r)&&e.has(k_[r])&&(t.push(r),e.add(r),n=!0);if(!n)throw Error(`cskel27 parent table is not a tree`)}return t}var B_=z_();function V_(e,t){return F_(e,`matMul(a, b): a`),F_(t,`matMul(a, b): b`),[[e[0][0]*t[0][0]+e[0][1]*t[1][0]+e[0][2]*t[2][0],e[0][0]*t[0][1]+e[0][1]*t[1][1]+e[0][2]*t[2][1],e[0][0]*t[0][2]+e[0][1]*t[1][2]+e[0][2]*t[2][2]],[e[1][0]*t[0][0]+e[1][1]*t[1][0]+e[1][2]*t[2][0],e[1][0]*t[0][1]+e[1][1]*t[1][1]+e[1][2]*t[2][1],e[1][0]*t[0][2]+e[1][1]*t[1][2]+e[1][2]*t[2][2]],[e[2][0]*t[0][0]+e[2][1]*t[1][0]+e[2][2]*t[2][0],e[2][0]*t[0][1]+e[2][1]*t[1][1]+e[2][2]*t[2][1],e[2][0]*t[0][2]+e[2][1]*t[1][2]+e[2][2]*t[2][2]]]}function H_(e){return F_(e,`matTranspose(m): m`),[[e[0][0],e[1][0],e[2][0]],[e[0][1],e[1][1],e[2][1]],[e[0][2],e[1][2],e[2][2]]]}function U_(e,t){return[e[0][0]*t[0]+e[0][1]*t[1]+e[0][2]*t[2],e[1][0]*t[0]+e[1][1]*t[1]+e[1][2]*t[2],e[2][0]*t[0]+e[2][1]*t[1]+e[2][2]*t[2]]}function W_(e){let[t,n,r,i]=P_(e,`quatToMat(q): q`),a=t*t+n*n+r*r+i*i;if(!Number.isFinite(a)||a<=M_)throw Error(`quatToMat(q): quaternion is zero-length and cannot represent a rotation`);let o=1/Math.sqrt(a),s=t*o,c=n*o,l=r*o,u=i*o;return[[1-2*(l*l+u*u),2*(c*l-s*u),2*(c*u+s*l)],[2*(c*l+s*u),1-2*(c*c+u*u),2*(l*u-s*c)],[2*(c*u-s*l),2*(l*u+s*c),1-2*(c*c+l*l)]]}function G_(e){F_(e,`matToQuat(m): m`);let t,n=e[0][0]+e[1][1]+e[2][2];if(n>0){let r=Math.sqrt(n+1)*2;t=[.25*r,(e[2][1]-e[1][2])/r,(e[0][2]-e[2][0])/r,(e[1][0]-e[0][1])/r]}else if(e[0][0]>e[1][1]&&e[0][0]>e[2][2]){let n=Math.sqrt(1+e[0][0]-e[1][1]-e[2][2])*2;t=[(e[2][1]-e[1][2])/n,.25*n,(e[0][1]+e[1][0])/n,(e[0][2]+e[2][0])/n]}else if(e[1][1]>e[2][2]){let n=Math.sqrt(1+e[1][1]-e[0][0]-e[2][2])*2;t=[(e[0][2]-e[2][0])/n,(e[0][1]+e[1][0])/n,.25*n,(e[1][2]+e[2][1])/n]}else{let n=Math.sqrt(1+e[2][2]-e[0][0]-e[1][1])*2;t=[(e[1][0]-e[0][1])/n,(e[0][2]+e[2][0])/n,(e[1][2]+e[2][1])/n,.25*n]}let r=t.reduce((e,t)=>e+t*t,0);if(!Number.isFinite(r)||r<=M_)throw Error(`matToQuat(m): matrix is degenerate and cannot represent a rotation`);let i=1/Math.sqrt(r),a=t.map(e=>e*i);if(!a.every(N_))throw Error(`matToQuat(m): matrix is degenerate and cannot represent a rotation`);return a}function K_(e){let t=L_(e,`globalRotations(localRotations)`),n=Array(k_.length);for(let e of B_){let r=k_[e];n[e]=r===null?t[e].map(e=>e.slice()):V_(n[r],t[e])}return n}function q_(e,t){let n=R_(e,`deriveBoneOffsets(jointPositions, ...)`),r=K_(t),i=Array(k_.length);for(let e=0;e<i.length;e+=1)i[e]=[0,0,0];for(let e of B_){let t=k_[e];if(t===null)continue;let a=[n[e][0]-n[t][0],n[e][1]-n[t][1],n[e][2]-n[t][2]];i[e]=U_(H_(r[t]),a)}return i}function J_(e,t,n=[0,0,0]){let r=K_(e);R_(t,`forwardKinematics(...): boneOffsets`);let i=I_(n,`forwardKinematics(...): rootPosition`),a=Array(k_.length);for(let e of B_){let n=k_[e];if(n===null){a[e]=i.slice();continue}let o=U_(r[n],t[e]);a[e]=[a[n][0]+o[0],a[n][1]+o[1],a[n][2]+o[2]]}return a}var Y_=[[0,0,0],[0,.0709891,-.0473261],[0,.1642033,-.0637623],[0,.2584953,-.0720118],[0,.3531475,-.0720119],[0,.6016096,-.0365176],[0,.7297793,-.0139179],[-.0319949,.5259196,-.0186873],[-.1909029,.5259195,-.0186873],[-.4863389,.5259194,-.0186873],[-.7189909,.5259193,-.0186873],[-.7886024,.5259193,-.0186873],[-.7468355,.5073563,.0277204],[.0319949,.5259196,-.0186873],[.1909029,.5259196,-.0186873],[.4863389,.5259196,-.0186873],[.7189909,.5259196,-.0186873],[.7886024,.5259196,-.0186873],[.7468355,.5073565,.0277204],[-.0949182,-.0277289,0],[-.0949182,-.4398469,0],[-.0949182,-.8959379,0],[-.0949182,-.9544128,.1606583],[.0949182,-.0277289,0],[.0949182,-.4398469,0],[.0949182,-.8959379,0],[.0949182,-.9544128,.1606583]],X_=[[1,0,0],[0,1,0],[0,0,1]];new Map(A_.map(e=>[Z[j_[e]],e]));var Z_=-Math.min(...Y_.map(e=>e[1]));function Q_(){return{local_rot_mats:Z.map(()=>X_.map(e=>e.slice())),posed_joints:Y_.map(([e,t,n])=>[e,t+Z_,n])}}function $_(e,t,n){let r=e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],i=r<0?-1:1;r*=i;let a,o;if(r>.9995)a=1-n,o=n;else{let e=Math.acos(Math.min(1,r)),t=Math.sin(e);a=Math.sin((1-n)*e)/t,o=Math.sin(n*e)/t}let s=[e[0]*a+t[0]*i*o,e[1]*a+t[1]*i*o,e[2]*a+t[2]*i*o,e[3]*a+t[3]*i*o],c=Math.hypot(...s);return s.map(e=>e/c)}function ev(e,t){return[[e[t],e[t+1],e[t+2]],[e[t+3],e[t+4],e[t+5]],[e[t+6],e[t+7],e[t+8]]]}function tv(e,t,n){e[t]=n[0][0],e[t+1]=n[0][1],e[t+2]=n[0][2],e[t+3]=n[1][0],e[t+4]=n[1][1],e[t+5]=n[1][2],e[t+6]=n[2][0],e[t+7]=n[2][1],e[t+8]=n[2][2]}var nv=Z.length,rv=(()=>{let e=Q_();return q_(e.posed_joints,e.local_rot_mats)})(),iv=1e-4;function av(e,t){let n=Array(nv);for(let r=0;r<nv;r+=1)n[r]=ev(e,(t*nv+r)*9);return n}function ov(e){let t=Math.max(1,Math.floor(e.frames/16));for(let n=0;n<e.frames;n+=t){let t=J_(av(e.rotMats,n),rv,[e.rootPos[n*3],e.rootPos[n*3+1],e.rootPos[n*3+2]]);for(let r=0;r<nv;r+=1){let i=(n*nv+r)*3,a=t[r][0]-e.posedJoints[i],o=t[r][1]-e.posedJoints[i+1],s=t[r][2]-e.posedJoints[i+2];if(Math.hypot(a,o,s)>iv)return!1}}return!0}function sv(e,t){if(!e||!Number.isFinite(e.fps)||e.fps<=0)throw Error(`retimeMotion: motion.fps must be a positive finite number`);if(!Number.isFinite(t)||t<=0)throw Error(`retimeMotion: targetFps must be a positive finite number`);if(e.fps===t)return e;let n=e.frames;if(!Number.isInteger(n)||n<1)throw Error(`retimeMotion: motion.frames must be a positive integer`);let r=t/e.fps,i=Math.max(1,Math.round(n*r)),a=new Float32Array(i*nv*9),o=new Float32Array(i*3),s=new Float32Array(i*nv*3),c=ov(e);for(let t=0;t<i;t+=1){let i=t/r,l=Math.min(Math.floor(i),n-1),u=Math.min(l+1,n-1),d=Math.min(Math.max(i-l,0),1),f=d===0||l===u;for(let n=0;n<nv;n+=1){let r=(l*nv+n)*9,i=(t*nv+n)*9;if(f)for(let t=0;t<9;t+=1)a[i+t]=e.rotMats[r+t];else{let t=(u*nv+n)*9;tv(a,i,W_($_(G_(ev(e.rotMats,r)),G_(ev(e.rotMats,t)),d)))}}for(let n=0;n<3;n+=1)o[t*3+n]=e.rootPos[l*3+n]*(1-d)+e.rootPos[u*3+n]*d;if(c){let e=J_(av(a,t),rv,[o[t*3],o[t*3+1],o[t*3+2]]);for(let n=0;n<nv;n+=1){let r=(t*nv+n)*3;s[r]=e[n][0],s[r+1]=e[n][1],s[r+2]=e[n][2]}}else for(let n=0;n<nv;n+=1){let r=(l*nv+n)*3,i=(u*nv+n)*3,a=(t*nv+n)*3;for(let t=0;t<3;t+=1)s[a+t]=e.posedJoints[r+t]*(1-d)+e.posedJoints[i+t]*d}}let l={...e,frames:i,fps:t,rotMats:a,rootPos:o,posedJoints:s};return Number.isFinite(e.anchorFrame)&&(l.anchorFrame=Math.min(i-1,Math.round(e.anchorFrame*r))),l}var cv=Z.map(e=>{switch(e){case`Spine`:case`RightHandEnd`:case`LeftHandEnd`:case`RightHand`:case`LeftHand`:case`RightHandThumb1`:case`LeftHandThumb1`:return null;case`Spine1`:return`Spine`;case`Spine2`:return`Spine1`;case`Spine3`:return`Spine2`;default:return e}}),lv=new Set([`RightShoulder`,`RightArm`,`RightForeArm`,`LeftShoulder`,`LeftArm`,`LeftForeArm`]),uv=-.9544128;function dv(e,t){let n=ep(t),r=null;return e.traverse(e=>{if(r||!e.isBone)return;let t=ep(e.name);(t===n||t.endsWith(n))&&(r=e)}),r}var fv=new WeakMap;function pv(e){let t=e.userData&&e.userData.poseBind;if(t)return t;let n=fv.get(e);return n||(n=new Map,e.traverse(e=>{if(e.isBone){let t=e.quaternion;n.set(e,{x:t.x,y:t.y,z:t.z,w:t.w})}}),fv.set(e,n)),n}var mv=new WeakMap;function hv(e){let t=mv.get(e);if(t)return t;let n=pv(e),r=new Map,i=e=>{let t=e.isBone?n.get(e):null;return t?.position?new B(t.position.x,t.position.y,t.position.z):e.position},a=(e,t)=>{let o=e.isBone?n.get(e):null,s=o?new z(o.x,o.y,o.z,o.w):e.quaternion,c=new V().compose(i(e),s,e.scale),l=t.clone().multiply(c);r.set(e,l);for(let t of e.children)a(t,l)};for(let t of e.children)a(t,new V);let o=Array(Z.length).fill(null),s=Array(Z.length).fill(null),c=Array(Z.length).fill(null),l=Array(Z.length).fill(null),u=Array(Z.length).fill(null),d=Array(Z.length).fill(null);for(let t=0;t<Z.length;t+=1){let n=cv[t];if(!n)continue;let a=dv(e,n);if(!a)continue;let f=r.get(a);o[t]=a,s[t]=new B().setFromMatrixPosition(f),c[t]=new z().setFromRotationMatrix(f),l[t]=a.scale.clone(),u[t]=i(a).clone(),d[t]=r.get(a.parent)??new V}let f=Z.indexOf(`Hips`),p=s[f]?s[f].y:0,m=p;for(let e=0;e<s.length;e+=1)s[e]&&s[e].y<m&&(m=s[e].y);let h=p-m,g=h>1e-6?h/.9544128:1,_=Array(Z.length).fill(null);for(let e=0;e<Z.length;e+=1){if(!o[e])continue;let t=Y_[e];_[e]=new B(s[e].x-g*t[0],s[e].y-g*(t[1]-uv),s[e].z-g*t[2])}let v=new Map;for(let e=0;e<o.length;e+=1)o[e]&&v.set(o[e],e);let y=Array(Z.length).fill(-1),b=Array(Z.length).fill(null);for(let t=0;t<o.length;t+=1){let n=o[t];if(n){for(let i=n.parent;i&&i!==e;i=i.parent)if(i.isBone&&v.has(i)){y[t]=v.get(i),b[t]=new V().copy(r.get(i)).invert().multiply(r.get(n.parent));break}}}let x=[];for(let t of[`LeftHand`,`RightHand`]){let a=dv(e,t);if(a){let e=n.get(a);x.push({bone:a,joint:Z.indexOf(t),bindLocalPos:i(a).clone(),bindWorldQuat:new z().setFromRotationMatrix(r.get(a)),parentBindQuat:new z().setFromRotationMatrix(r.get(a.parent)),bindLocalQuat:e?new z(e.x,e.y,e.z,e.w):a.quaternion.clone()})}}let S=Array(Z.length).fill(0),C=Array(Z.length).fill(0);for(let e=1;e<Z.length;e+=1){let t=k_[e],n=Y_[e],r=Y_[t];S[e]=g*Math.hypot(n[0]-r[0],n[1]-r[1],n[2]-r[2]);let a=o[e]??x.find(t=>t.joint===e)?.bone;a&&(C[e]=i(a).length())}return t={bones:o,bindPos:s,stretchedLeaves:x,canonicalBoneLength:S,rigBoneLength:C,bindQuat:c,bindScale:l,bindLocalPos:u,parentBindWorld:d,chainParent:y,chainRel:b,scale:g,offsets:_},mv.set(e,t),t}function gv(e){let t=hv(e);if(!t)throw Error(`captureArdyRoot: rig is not prepared for ARDY playback`);let n=Z.indexOf(`Hips`),r=t.bones[n];if(!r)throw Error(`captureArdyRoot: mapped Hips bone is unavailable`);e.updateMatrixWorld(!0);let i=new V().copy(e.matrixWorld).invert(),a=new V().multiplyMatrices(i,r.matrixWorld),o=new B,s=new z;a.decompose(o,s,new B);let c=s.multiply(t.bindQuat[n].clone().invert()).normalize(),l=t.offsets[n].clone().applyQuaternion(c),u=t.lastScale??t.scale;return[(o.x-l.x)/u,(o.y-l.y)/u,(o.z-l.z)/u]}var _v=new WeakMap;function vv(e,t){let n=_v.get(t);if(n&&n.prep===e)return n.offsets;let r=Array(Z.length);for(let e=0;e<Z.length;e+=1){let n=k_[e],i=Y_[e];if(n===null){r[e]=[i[0],i[1],i[2]];continue}let a=Y_[n],o=r[n];r[e]=[o[0]+t[e]*(i[0]-a[0]),o[1]+t[e]*(i[1]-a[1]),o[2]+t[e]*(i[2]-a[2])]}let i=Array(Z.length).fill(null);for(let t=0;t<Z.length;t+=1){if(!e.bones[t])continue;let n=r[t];i[t]=new B(e.bindPos[t].x-e.scale*n[0],e.bindPos[t].y-e.scale*(n[1]-uv),e.bindPos[t].z-e.scale*n[2])}return _v.set(t,{prep:e,offsets:i}),i}function yv(e,t,n){if(!t.boneScale)return 1;if(bv.has(Z[n]))return t.boneScale[n];let r=e.canonicalBoneLength[n],i=e.rigBoneLength[n];return!(r>1e-6)||!(i>1e-6)?t.boneScale[n]:t.boneScale[n]*r/i}var bv=new Set([`LeftShoulder`,`RightShoulder`,`LeftArm`,`RightArm`]),xv=Array(Z.length);for(let e=0;e<xv.length;e+=1)xv[e]=[[0,0,0],[0,0,0],[0,0,0]];var Sv=new Gn,Cv=new V,wv=new V,Tv=new V,Ev=new z,Dv=new z,Ov=new B,kv=new B,Av=new B,jv=new z,Mv=new B,Nv=Array(Z.length).fill(null);function Pv(e,t){for(let n=0;n<xv.length;n+=1){let r=(t*xv.length+n)*9,i=xv[n];for(let t=0;t<3;t+=1)for(let n=0;n<3;n+=1)i[t][n]=e.rotMats[r+t*3+n]}return K_(xv)}function Fv(e,t=new z){return Sv.set(...e[0],...e[1],...e[2]),t.setFromRotationMatrix(Cv.setFromMatrix3(Sv))}function Iv(e,{base:t,chains:n},r){let i=Pv(t,r),a=t.boneScale?vv(e,t.boneScale):e.offsets,o=Math.max(0,Math.min(t.anchorFrame||0,t.frames-1))*27*3,s=new Map,c=new Map,l=new Map,u=n=>{if(!s.has(n)){let c=Fv(i[n]),l=new B().fromArray(t.posedJoints,(r*27+n)*3);l.x-=t.posedJoints[o],l.z-=t.posedJoints[o+2],l.multiplyScalar(e.scale).add(a[n].clone().applyQuaternion(c)),s.set(n,new V().compose(l,c.multiply(e.bindQuat[n]),e.bindScale[n]))}return s.get(n)};for(let t of n){let n=t.startsWith(`left`)?`Left`:`Right`;if(t.endsWith(`Hand`)){let t=e.stretchedLeaves.find(e=>Z[e.joint]===`${n}Hand`);t&&l.set(t.bone,Fv(i[k_[t.joint]]).multiply(t.bindWorldQuat))}else for(let t of[`UpLeg`,`Leg`,`Foot`,`ToeBase`]){let r=Z.indexOf(n+t),i=e.bones[r];if(!i)continue;let a=e.chainParent[r],o=a<0?e.parentBindWorld[r].clone():u(a).clone().multiply(e.chainRel[r]);c.set(i,new B().setFromMatrixPosition(u(r)).applyMatrix4(o.invert()))}}return{positions:c,wrists:l}}function Lv(e,t,n){if(!e||!t)return;let r=Math.max(0,Math.min(Math.round(n)||0,t.frames-1)),i=hv(e),a=Z.length,o=t.trailRetarget?Iv(i,t.trailRetarget,r):null,s=Pv(t,r),c=Math.max(0,Math.min(t.anchorFrame||0,t.frames-1)),l=t.posedJoints[c*a*3],u=t.posedJoints[c*a*3+2],d=i.scale;i.lastScale=d;let f=t.boneScale?vv(i,t.boneScale):i.offsets;for(let e=0;e<a;e+=1){let n=i.bones[e];if(Nv[e]=null,!n)continue;let c=s[e];Sv.set(c[0][0],c[0][1],c[0][2],c[1][0],c[1][1],c[1][2],c[2][0],c[2][1],c[2][2]),Ev.setFromRotationMatrix(Cv.setFromMatrix3(Sv));let p=(r*a+e)*3;Ov.copy(f[e]).applyQuaternion(Ev),kv.set(d*(t.posedJoints[p]-l)+Ov.x,d*t.posedJoints[p+1]+Ov.y,d*(t.posedJoints[p+2]-u)+Ov.z),Dv.copy(Ev).multiply(i.bindQuat[e]);let m=i.chainParent[e];m>=0?Tv.copy(Nv[m]).multiply(i.chainRel[e]):Tv.copy(i.parentBindWorld[e]),o?.positions.has(n)?kv.copy(o.positions.get(n)).applyMatrix4(Tv):lv.has(Z[e])&&kv.copy(i.bindLocalPos[e]).multiplyScalar(yv(i,t,e)).applyMatrix4(Tv),Cv.compose(kv,Dv,i.bindScale[e]),Nv[e]=Cv.clone(),wv.copy(Tv).invert().multiply(Cv),wv.decompose(Av,jv,Mv),n.position.copy(Av),n.quaternion.copy(jv)}for(let e of i.stretchedLeaves){e.bone.position.copy(e.bindLocalPos).multiplyScalar(yv(i,t,e.joint));let n=o?.wrists.get(e.bone);n?(Fv(s[k_[e.joint]],Ev).multiply(e.parentBindQuat),e.bone.quaternion.copy(Ev.invert().multiply(n))):e.bone.quaternion.copy(e.bindLocalQuat)}e.updateMatrixWorld(!0)}var Rv=new WeakMap;function zv(e){let t=Rv.get(e);if(t)return t;let n=e.userData?.poseBind??fv.get(e)??new Map,r=new Map,i=e=>e.isBone||e.children.some(i),a=e=>{let t=e.isBone?new io:new Br;t.name=e.name,t.position.copy(e.position),t.quaternion.copy(e.quaternion),t.scale.copy(e.scale);let o=e.isBone?n.get(e):null,s=e.quaternion;e.isBone&&r.set(t,o??{x:s.x,y:s.y,z:s.z,w:s.w});for(let n of e.children)i(n)&&t.add(a(n));return t};t=new Br;for(let n of e.children)i(n)&&t.add(a(n));return t.userData.poseBind=r,Rv.set(e,t),t}var Bv=new WeakMap;function Vv(e,t,n,r,i){let a=zv(e),o=hv(a);o.driven||=Z.map((e,t)=>o.bones[t]??o.stretchedLeaves.find(e=>e.joint===t)?.bone??null),Lv(a,t,n);for(let e=0;e<o.driven.length;e+=1){let t=o.driven[e],n=i+e*3;if(!t){r[n]=r[n+1]=r[n+2]=NaN;continue}let a=t.matrixWorld.elements;r[n]=a[12],r[n+1]=a[13],r[n+2]=a[14]}}function Hv(e,t,n){if(!e||!t?.rotMats||!(t.frames>0))return null;let r=new Float32Array(Z.length*3);return Vv(e,t,Math.max(0,Math.min(Math.round(n)||0,t.frames-1)),r,0),r}function Uv(e,t){if(!e||!t?.rotMats||!(t.frames>0))return null;let n=Bv.get(t);n||(n=new WeakMap,Bv.set(t,n));let r=n.get(e);if(r)return r;let i=Z.length,a=new Float32Array(t.frames*i*3);for(let n=0;n<t.frames;n+=1)Vv(e,t,n,a,n*i*3);let o={positions:a};return n.set(e,o),o}function Wv(e){let t=[],n=hv(e);for(let e of[...n.bones,...n.stretchedLeaves.map(e=>e.bone)])e&&t.push([e,e.quaternion.x,e.quaternion.y,e.quaternion.z,e.quaternion.w,e.position.x,e.position.y,e.position.z]);return t}function Gv(e,t){if(!(!e||!t)){for(let e of t)e[0].quaternion.set(e[1],e[2],e[3],e[4]),e.length>5&&e[0].position.set(e[5],e[6],e[7]);e.updateMatrixWorld(!0)}}function Kv(e,t,n){if(!e||!Number.isInteger(e.frames)||e.frames<1)throw Error(`sliceMotion: motion.frames must be a positive integer`);if(!Number.isInteger(t)||!Number.isInteger(n))throw Error(`sliceMotion: startFrame and endFrame must be integers`);if(t<0||n>=e.frames||t>n)throw Error(`sliceMotion: range ${t}..${n} is outside 0..${e.frames-1}`);let r=Z.length,i=n-t+1;return{...e,frames:i,rotMats:e.rotMats.slice(t*r*9,(n+1)*r*9),rootPos:e.rootPos.slice(t*3,(n+1)*3),posedJoints:e.posedJoints.slice(t*r*3,(n+1)*r*3),anchorFrame:0}}var qv=.1,Jv=4,Yv=.1,Xv=e=>Math.round(Number(e)/Yv)*Yv,Zv=e=>e.sourceEnd-e.sourceStart+1,Qv=e=>Math.max(1,Math.round(Zv(e)/e.speed));function $v(e){if(!Number.isInteger(e)||e<1)throw Error(`createMotionEdit: frames must be a positive integer`);return[{id:`motion-0`,sourceStart:0,sourceEnd:e-1,speed:1}]}function ey(e){return!Array.isArray(e)||e.length<1?0:e.reduce((e,t)=>e+Qv(t),0)}function ty(e){let t=0;return e.map(e=>{let n=Qv(e),r={...e,timelineStart:t,timelineEnd:t+n-1,timelineFrames:n};return t+=n,r})}function ny(e,t){let n=ty(e);if(n.length<1)return Math.max(0,Math.round(t)||0);let r=Math.max(0,Math.min(Number.isFinite(t)?t:0,n.at(-1).timelineEnd)),i=n.find(e=>r<=e.timelineEnd)??n.at(-1);if(i.timelineFrames<=1)return i.sourceStart;let a=(r-i.timelineStart)/(i.timelineFrames-1);return i.sourceStart+a*(i.sourceEnd-i.sourceStart)}function ry(e,t){if(!Array.isArray(e)||e.length<1||!Number.isFinite(t))return null;let n=ty(e).find(e=>t>=e.sourceStart&&t<=e.sourceEnd);if(!n)return null;if(n.sourceEnd===n.sourceStart)return n.timelineStart;let r=(t-n.sourceStart)/(n.sourceEnd-n.sourceStart);return Math.round(n.timelineStart+r*(n.timelineFrames-1))}function iy(e,t,n){return ry(t,ny(e,n))}function ay(e,t,n){let r=new Map;for(let i of[...e.keys()].sort((e,t)=>e-t)){let a=iy(t,n,i);a===null||r.has(a)||r.set(a,e.get(i))}return r}function oy(e,t){if(!Array.isArray(e)||e.length<1)return e;let n=ty(e),r=Math.round(t);if(r<=0||r>=ey(e))return e;let i=n.findIndex(e=>r>e.timelineStart&&r<=e.timelineEnd);if(i<0)return e;let a=n[i],o=Math.max(a.sourceStart+1,Math.min(a.sourceEnd,Math.round(ny(e,r))));if(o<=a.sourceStart||o>a.sourceEnd)return e;let s=[...e];return s.splice(i,1,{id:`${a.id}-a`,sourceStart:a.sourceStart,sourceEnd:o-1,speed:a.speed},{id:`${a.id}-b`,sourceStart:o,sourceEnd:a.sourceEnd,speed:a.speed}),s}function sy(e,t,n){let r=Xv(n);if(!Number.isFinite(r)||r<qv||r>Jv)throw Error(`setMotionSegmentSpeed: speed must be between 0.1 and 4.0 in 0.1 steps`);return e.map(e=>e.id===t?{...e,speed:Number(r.toFixed(1))}:e)}function cy(e,t){if(!Array.isArray(e)||e.length<2)return e;let n=e.filter(e=>e.id!==t);return n.length===e.length?e:n}function ly(e,t){let n=Math.max(1,Math.round(Number(t)||1)),r=Zv(e)/n;return Number(Xv(Math.min(Jv,Math.max(qv,r))).toFixed(1))}function uy(e,t,n){if(!Array.isArray(e)||e.length<1)return e;let r=ey(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n>=r||t>n)throw Error(`trimMotionEdit: range ${t}..${n} is outside 0..${r-1}`);return ty(e).flatMap(r=>{let i=Math.max(t,r.timelineStart),a=Math.min(n,r.timelineEnd);if(i>a)return[];let o=Math.ceil(ny(e,i)),s=Math.floor(ny(e,a));return[{id:`${r.id}-trim-${o}`,sourceStart:Math.max(r.sourceStart,o),sourceEnd:Math.min(r.sourceEnd,s),speed:r.speed}]}).filter(e=>e.sourceStart<=e.sourceEnd)}function dy(e,t,n,r,i){let a=t*i;n.set(e.subarray(a,a+i),r*i)}function fy(e,t){if(!e||!Number.isInteger(e.frames)||e.frames<1||!Number.isFinite(e.fps)||e.fps<=0)throw Error(`renderMotionEdit: motion must have positive frames and fps`);let n=Array.isArray(t)&&t.length?t:$v(e.frames),r=n.map(t=>{let n=Kv(e,t.sourceStart,t.sourceEnd);return t.speed===1?n:sv(n,e.fps/t.speed)}),i=r.reduce((e,t)=>e+t.frames,0),a=e.rotMats.length/e.frames,o=e.rootPos.length/e.frames,s=e.posedJoints.length/e.frames,c=new Float32Array(i*a),l=new Float32Array(i*o),u=new Float32Array(i*s),d=0;for(let t=0;t<r.length;t+=1){let i=r[t],f=n[t];for(let t=0;t<i.frames;t+=1){let n=t===i.frames-1&&f.speed>1,r=n?e:i,p=n?f.sourceEnd:t;dy(r.rotMats,p,c,d+t,a),dy(r.rootPos,p,l,d+t,o),dy(r.posedJoints,p,u,d+t,s)}d+=i.frames}return{...e,frames:i,fps:e.fps,rotMats:c,rootPos:l,posedJoints:u,anchorFrame:0,editSegments:n.map(e=>({...e}))}}var py=.01,my=Z.length,hy=e=>Z.indexOf(e),gy={leftHand:[`LeftArm`,`LeftForeArm`,`LeftHand`],rightHand:[`RightArm`,`RightForeArm`,`RightHand`],leftFoot:[`LeftUpLeg`,`LeftLeg`,`LeftFoot`],rightFoot:[`RightUpLeg`,`RightLeg`,`RightFoot`]},_y=[{id:`leftHand`,joint:`LeftHand`,color:`#ff8a3d`},{id:`rightHand`,joint:`RightHand`,color:`#ff8a3d`},{id:`leftFoot`,joint:`LeftFoot`,color:`#4dd2ff`},{id:`rightFoot`,joint:`RightFoot`,color:`#4dd2ff`},{id:`head`,joint:`Head`,color:`#b98cff`},{id:`hips`,joint:`Hips`,color:`#ffd23d`}],vy={hips:`Hips`,spine:`Spine1`,chest:`Spine2`,neck:`Neck`,head:`Head`,leftShoulder:`LeftArm`,leftElbow:`LeftForeArm`,leftHand:`LeftHand`,rightShoulder:`RightArm`,rightElbow:`RightForeArm`,rightHand:`RightHand`,leftKnee:`LeftLeg`,leftFoot:`LeftFoot`,rightKnee:`RightLeg`,rightFoot:`RightFoot`};function yy(e){let t=e?.frames??0,n=Math.max(0,Math.min(e?.anchorFrame||0,Math.max(0,t-1))),r=(Number.isFinite(e?.rotationDeg)?e.rotationDeg:0)*Math.PI/180;return{anchorFrame:n,cos:Math.cos(r),sin:Math.sin(r),anchorX:Number.isFinite(e?.anchorX)?e.anchorX:0,anchorZ:Number.isFinite(e?.anchorZ)?e.anchorZ:0,rootX:e?.posedJoints?.[n*my*3]??e?.rootPos?.[n*3]??0,rootZ:e?.posedJoints?.[n*my*3+2]??e?.rootPos?.[n*3+2]??0}}function by(e,t,n){let r=t-e.rootX,i=n-e.rootZ;return[e.anchorX+r*e.cos+i*e.sin,e.anchorZ+-r*e.sin+i*e.cos]}function xy(e,t,n){if(!n)return null;let r=Uv(n,e);return r&&Number.isFinite(r.positions[t*3])?r:null}function Sy(e,t=`Hips`,{baseY:n=0,scale:r=1,rig:i=null}={}){if(!e?.posedJoints||!(e.frames>0))return null;let a=Z.indexOf(t);if(a<0)return null;let o=yy(e),s=new Float32Array(e.frames*3),c=xy(e,a,i);if(c){let t=py*r;for(let r=0;r<e.frames;r+=1){let e=(r*my+a)*3,i=c.positions[e]*t,l=c.positions[e+2]*t;s[r*3]=o.anchorX+i*o.cos+l*o.sin,s[r*3+1]=n+c.positions[e+1]*t,s[r*3+2]=o.anchorZ-i*o.sin+l*o.cos}return s}for(let t=0;t<e.frames;t+=1){let i=(t*my+a)*3,[c,l]=by(o,e.posedJoints[i],e.posedJoints[i+2]);s[t*3]=o.anchorX+(c-o.anchorX)*r,s[t*3+1]=n+e.posedJoints[i+1]*r,s[t*3+2]=o.anchorZ+(l-o.anchorZ)*r}return s}function Cy(e,t,{baseY:n=0,scale:r=1}={}){let i=yy(e),a=Number.isFinite(r)&&Math.abs(r)>1e-9?r:1,o=(t.x-i.anchorX)/a,s=(t.z-i.anchorZ)/a,c=o*i.cos-s*i.sin,l=o*i.sin+s*i.cos;return{x:i.rootX+c,y:(t.y-n)/a,z:i.rootZ+l}}function wy(e,t){let{cos:n,sin:r}=yy(e);return{x:t.x*n-t.z*r,y:t.y,z:t.x*r+t.z*n}}function Ty(e,t,{track:n=`hips`,grabFrame:r=0,radiusFrames:i=0,rig:a=null,scale:o=1}={}){let s=Number.isFinite(o)&&o>1e-9?o:1,c=wy(e,{x:t.x/s,y:t.y/s,z:t.z/s}),l=Math.hypot(t.x,t.y,t.z),u=hy(_y.find(e=>e.id===n)?.joint??``),d=a&&u>=0&&e?.rotMats&&l>1e-6?Uv(a,e):null,f=Math.max(0,Math.min((e?.frames??1)-1,Math.round(r)||0)),p=d?.positions.subarray((f*my+u)*3,(f*my+u)*3+3);if(!p||!Number.isFinite(p[0]))return c;let m=yy(e),h=py*s,g=[t.x,t.y,t.z],_=e=>({x:c.x*e,y:c.y*e,z:c.z*e}),v=t=>{let r=Hv(a,Xy(e,{track:n,grabFrame:f,radiusFrames:i,clipDelta:_(t)}),f).subarray(u*3,u*3+3),o=(r[0]-p[0])*h,s=(r[2]-p[2])*h;return[o*m.cos+s*m.sin,(r[1]-p[1])*h,-o*m.sin+s*m.cos]},y=1,b={gain:1,miss:1/0};for(let e=0;e<4;e+=1){let e=v(y),t=Ny(Oy(g,e));t<b.miss&&(b={gain:y,miss:t});let n=jy(e,e);if(!(n>1e-12)||t<1e-4)break;let r=Math.max(.1,Math.min(1.5,y*jy(g,e)/n));if(Math.abs(r-y)<1e-4)break;y=r}return _(b.gain)}function Ey(e,t){if(!(t>0))return+(e===0);let n=1-Math.min(1,Math.abs(e)/t);return n*n*(3-2*n)}function Dy(e,t,n){let r=Math.max(0,e-1),i=Math.max(0,Math.min(r,Math.round(t)||0)),a=Math.max(0,Math.round(n)||0);return{startFrame:Math.max(0,i-a),endFrame:Math.min(e,i+a+1)}}var Oy=(e,t)=>[e[0]-t[0],e[1]-t[1],e[2]-t[2]],ky=(e,t)=>[e[0]+t[0],e[1]+t[1],e[2]+t[2]],Ay=(e,t)=>[e[0]*t,e[1]*t,e[2]*t],jy=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],My=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],Ny=e=>Math.hypot(e[0],e[1],e[2]);function Py(e){let t=Ny(e);return t>1e-9?Ay(e,1/t):null}function Fy(e,t){let n=Array(9);for(let r=0;r<3;r+=1)for(let i=0;i<3;i+=1)n[r*3+i]=e[r*3]*t[i]+e[r*3+1]*t[3+i]+e[r*3+2]*t[6+i];return n}var Iy=e=>[e[0],e[3],e[6],e[1],e[4],e[7],e[2],e[5],e[8]],Ly=(e,t)=>[e[0]*t[0]+e[1]*t[1]+e[2]*t[2],e[3]*t[0]+e[4]*t[1]+e[5]*t[2],e[6]*t[0]+e[7]*t[1]+e[8]*t[2]];function Ry(e,t){let n=jy(e,t);if(n<-1+1e-9){let[t,n,r]=Py(My(e,Math.abs(e[0])<.9?[1,0,0]:[0,1,0]));return[2*t*t-1,2*t*n,2*t*r,2*t*n,2*n*n-1,2*n*r,2*t*r,2*n*r,2*r*r-1]}let[r,i,a]=My(e,t),o=1/(1+n);return[1-o*(i*i+a*a),-a+o*r*i,i+o*r*a,a+o*r*i,1-o*(r*r+a*a),-r+o*i*a,-i+o*r*a,r+o*i*a,1-o*(r*r+i*i)]}function zy(e){return Z.map((e,t)=>t).filter(t=>{for(let n=t;n!==null;n=k_[n])if(n===e)return!0;return!1})}function By(e,t,n){let r=new Map,i=e=>Array.from(t.subarray((n*my+e)*9,(n*my+e)*9+9)),a=e=>{if(!r.has(e)){let t=k_[e];r.set(e,t===null?i(e):Fy(a(t),i(e)))}return r.get(e)};return{pos:t=>{let r=(n*my+t)*3;return[e[r],e[r+1],e[r+2]]},setPos:(t,r)=>e.set(r,(n*my+t)*3),global:a,setGlobal:(e,r,i=k_[e]===null?null:a(k_[e]))=>{t.set(i?Fy(Iy(i),r):r,(n*my+e)*9)}}}function Vy(e,[t,n,r],i,a,o,s){let c=[0,0,0];for(let l=i;l<a;l+=1){let i=By(e.posedJoints,null,l),a=My(Oy(i.pos(n),i.pos(t)),Oy(i.pos(r),i.pos(t)));c=ky(c,Ay(a,Ey(l-o,s)))}return Py(c)}var Hy=Math.PI/6,Uy=.25;function Wy(e,t,n){if(Math.acos(Math.max(-1,Math.min(1,jy(e,t))))<=n)return t;let r=Py(Oy(t,Ay(e,jy(e,t))));return r?ky(Ay(e,Math.cos(n)),Ay(r,Math.sin(n))):e}function Gy(e,[t,n,r],i,a,o){let s=e.pos(t),c=e.pos(n),l=e.pos(r),u=Ny(Oy(c,s)),d=Ny(Oy(l,c));if(Ny(a)<1e-9)return;let f=Oy(c,s),p=Oy(l,s),m=Py(My(f,p)),h=Oy(ky(l,a),s),g=Py(h)??Py(p);if(!g)return;let _=o??m??Py(My(g,Math.abs(g[0])<.9?[1,0,0]:[0,1,0])),v=Py(Oy(_,Ay(g,jy(_,g))))??Py(My(g,Math.abs(g[0])<.9?[1,0,0]:[0,1,0])),y=(Ny(h)-(u+d))/((u+d)*Uy),b=m?Math.acos(Math.max(-1,Math.min(1,jy(m,v)))):0;if(y>0&&b>Hy){let e=Math.min(1,y),t=Wy(m,v,b-(b-Hy)*e*e*(3-2*e)),n=Oy(h,Ay(t,jy(h,t)));Py(n)&&(v=t,h=n,g=Py(n))}let x=Math.min(u+d-1e-6,Math.max(Math.abs(u-d)+1e-6,Ny(h)));if(!(x>1e-9))return;let S=(u*u-d*d+x*x)/(2*x),C=Math.sqrt(Math.max(0,u*u-S*S)),w=Py(My(g,v)),T=ky(s,ky(Ay(g,S),Ay(w,C))),E=ky(s,Ay(g,x)),D=Oy(E,l);for(let t of i)e.setPos(t,ky(e.pos(t),D));if(e.setPos(n,T),!e.rotMats)return;let O=(e,t)=>Ry(Py(e),Py(t)),ee=Fy(O(f,Oy(T,s)),e.global(t)),k=Fy(O(Oy(l,c),Oy(E,T)),e.global(n)),te=e.global(r);e.setGlobal(t,ee),e.setGlobal(n,k,ee),e.setGlobal(r,te,k)}function Ky(e,t,n,r,i){let a=e.pos(t),o=e.pos(n),s=Py(Oy(o,a)),c=Py(Oy(ky(o,i),a));if(!s||!c)return;let l=Ry(s,c);for(let t of r)e.setPos(t,ky(a,Ly(l,Oy(e.pos(t),a))));e.rotMats&&e.setGlobal(t,Fy(l,e.global(t)))}function qy(e){if(e==null)return null;let t=()=>{throw TypeError(`Invalid motion trail edit recipe`)};(e.version!==1||!Number.isInteger(e.frames)||e.frames<1||!(e.fps>0)||!Number.isFinite(e.fps)||!Array.isArray(e.edits)||e.edits.length>4096)&&t();let n=e.edits.map(n=>((!_y.some(({id:e})=>e===n?.track)||!Number.isInteger(n.grabFrame)||n.grabFrame<0||n.grabFrame>=e.frames||!Number.isInteger(n.radiusFrames)||n.radiusFrames<0||![`x`,`y`,`z`].every(e=>Number.isFinite(n.clipDelta?.[e])))&&t(),{track:n.track,grabFrame:n.grabFrame,radiusFrames:n.radiusFrames,clipDelta:{x:n.clipDelta.x,y:n.clipDelta.y,z:n.clipDelta.z}})),r=null;return e.segments!=null&&((!Array.isArray(e.segments)||!e.segments.length||e.segments.length>4096)&&t(),r=e.segments.map(e=>((typeof e?.id!=`string`||!Number.isInteger(e.sourceStart)||e.sourceStart<0||!Number.isInteger(e.sourceEnd)||e.sourceEnd<e.sourceStart||!Number.isFinite(e.speed)||e.speed<.1||e.speed>4)&&t(),{id:e.id,sourceStart:e.sourceStart,sourceEnd:e.sourceEnd,speed:e.speed}))),{version:1,frames:e.frames,fps:e.fps,segments:r,edits:n}}function Jy(e,t,n){let r=e.trailEdits;return{...t,trailEdits:{version:1,frames:e.frames,fps:e.fps,segments:r?.segments??e.editSegments?.map(e=>({...e}))??null,edits:[...r?.edits??[],{...n,clipDelta:{...n.clipDelta}}]}}}function Yy(e,t){let n=qy(t);if(!n)return e;if(n.segments?.some(t=>t.sourceEnd>=e.frames))throw RangeError(`Motion trail source segment exceeds the take`);let r=n.segments?fy(e,n.segments):e;if(r.frames!==n.frames||r.fps!==n.fps)throw RangeError(`Motion trail recipe does not match the take clock`);for(let e of n.edits)r=Xy(r,e);return r}function Xy(e,{track:t=`hips`,grabFrame:n,radiusFrames:r,clipDelta:i}){if(!e?.posedJoints||!e?.rootPos||!(e.frames>0))return e;let{startFrame:a,endFrame:o}=Dy(e.frames,n,r),s=e.rootPos.slice(),c=e.posedJoints.slice(),l=gy[t]?.map(hy);if(l||t===`head`){let u=e.rotMats?e.rotMats.slice():null,d=hy(`Neck`),f=hy(`Head`),p=zy(l?l[2]:f).filter(e=>!l||e!==l[2]),m=l?Vy(e,l,a,o,n,r):null;for(let e=a;e<o;e+=1){let t=Ey(e-n,r);if(t<=0)continue;let a={...By(c,u,e),rotMats:u},o=[i.x*t,i.y*t,i.z*t];l?Gy(a,l,[l[2],...p],o,m):Ky(a,d,f,p,o)}let h=u?{...e,rootPos:s,posedJoints:c,rotMats:u}:{...e,rootPos:s,posedJoints:c};return l&&u&&(h.trailRetarget={base:e.trailRetarget?.base??e,chains:[...new Set([...e.trailRetarget?.chains??[],t])]}),Jy(e,h,{track:t,grabFrame:n,radiusFrames:r,clipDelta:i})}for(let e=a;e<o;e+=1){let t=Ey(e-n,r);if(t<=0)continue;let a=i.x*t,o=i.y*t,l=i.z*t;s[e*3]+=a,s[e*3+1]+=o,s[e*3+2]+=l;for(let t=0;t<my;t+=1){let n=(e*my+t)*3;c[n]+=a,c[n+1]+=o,c[n+2]+=l}}return Jy(e,{...e,rootPos:s,posedJoints:c},{track:t,grabFrame:n,radiusFrames:r,clipDelta:i})}var Zy=1.8,Qy=1.3,$y=Object.freeze({super16:Object.freeze({id:`super16`,label:`Super 16`,widthMm:12.52,heightMm:7.41}),super35:Object.freeze({id:`super35`,label:`Super 35`,widthMm:24.89,heightMm:18.66}),fullFrame:Object.freeze({id:`fullFrame`,label:`Full Frame`,widthMm:36,heightMm:24}),"65mm":Object.freeze({id:`65mm`,label:`65mm`,widthMm:52.63,heightMm:23.01})}),eb=`fullFrame`,tb=16/9,nb=Object.freeze({"16:9":16/9,"2.39:1":2.39,"9:16":9/16,"1:1":1,"4:3":4/3,"12:7":12/7,"fal 480P":832/480});function rb(e){return nb[e]??1.7777777777777777}function ib(e=eb,t=tb){let n=$y[e]??$y.fullFrame,r=Number.isFinite(t)&&t>0?t:tb;return Math.min(n.heightMm,n.widthMm/r)}function ab(e,t=eb,n=tb){return ib(t,n)/(2*Math.tan(e/2))}function ob(e,t=eb,n=tb){return 2*Math.atan(ib(t,n)/(2*e))}var sb=[14,18,24,28,35,50,85,100,135];function cb(e,t=eb,n=tb){let r=ab(e,t,n);return sb.reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)}var lb=[[2.8,`extreme close-up`,`ultra-realistic skin texture with visible pores and micro-detail, tack-sharp eyes, shallow depth of field`],[1.6,`close-up`,`ultra-realistic skin texture and fine facial detail, soft background blur, shallow depth of field`],[1.15,`medium close-up`,`natural skin and fabric texture, clear facial detail, shallow depth of field`],[.8,`medium shot`,`balanced detail on the subject and the surrounding space, moderate depth of field`],[.52,`medium-wide shot`,`the full figure with the environment clearly visible, deep focus`],[.3,`wide shot`,`full body in a richly detailed environment, deep focus`],[0,`extreme wide shot`,`a small figure within a vast, highly detailed environment, epic sense of scale, deep focus`]],ub=[[2.5,`overhead`,`a directly overhead bird's-eye view looking down at the subject`],[1.8,`high angle`,`a high angle looking down at the subject`],[1.5,`eye level`,`eye level`],[1.25,`chest level`,`chest level`],[.95,`hip level`,`a low hip-level angle`],[.45,`knee level`,`a low knee-level angle looking up at the subject`],[-1/0,`ground level`,`a dramatic ground-level angle looking up at the subject`]],db=(e,t)=>e.find(([e])=>t>=e)??e[e.length-1];function fb(e,t,n,r=Zy,i={}){let a=i.sensorId??`fullFrame`,o=i.aspectRatio??1.7777777777777777,s=e.x-t.x,c=e.z-t.z,l=e.y-Qy,u=Math.hypot(s,c),d=Math.max(Math.hypot(u,l),1e-6),f=r/(2*d*Math.tan(n/2)),[,p,m]=db(lb,f),[,h,g]=db(ub,e.y),_=Math.atan2(e.y-r*.94,Math.max(u,1e-6))*180/Math.PI,v=t.rot*Math.PI/180,y={x:Math.sin(v),z:Math.cos(v)},b={x:s/Math.max(u,1e-6),z:c/Math.max(u,1e-6)},x=y.x*b.x+y.z*b.z,S=y.x*b.z-y.z*b.x>=0?`right`:`left`,C=S===`right`?`R`:`L`,w,T;return x>.85?(w=`front`,T=`seen from the front, the face toward the camera`):x<-.85?(w=`back`,T=`seen from directly behind, the back of the head toward the camera`):x>.34?(w=`front ¾ ${C}`,T=`a three-quarter front view from the ${S}`):x<-.34?(w=`rear ¾ ${C}`,T=`a three-quarter rear view from the ${S}`):(w=`${S} profile`,T=`a ${S}-side profile view`),{sizeLabel:p,sizeContext:m,levelLabel:h,levelPhrase:g,viewShort:w,viewPhrase:T,focalMm:cb(n,a,o),exactFocalMm:ab(n,a,o),sensorId:$y[a]?.id??`fullFrame`,usedSensorHeightMm:ib(a,o),distance:d,screenFraction:f,elevationDeg:_}}function pb(e){return[e.sizeLabel,e.viewShort,e.levelLabel,`${e.focalMm}mm`].map(e=>e.toUpperCase()).join(` · `)}var mb=[{id:`nano_banana_pro`,label:`Nano Banana Pro`},{id:`nano_banana_2`,label:`Nano Banana 2`},{id:`gpt_image_2`,label:`GPT Image 2`},{id:`seedream_5`,label:`Seedream 5.0`},{id:`flux_2`,label:`Flux 2`,numericLens:!0,flavor:`fine film grain, high micro-detail`}],hb=`Custom…`,gb=[`Static / locked-off`,`Push-in (dolly in)`,`Pull-out (dolly out)`,`Pan left`,`Pan right`,`Tilt up`,`Tilt down`,`Tracking / follow`,`Orbit / arc`,`Crane up`,`Crane down`,`Handheld`,`Crash zoom in`,`Dolly-zoom (vertigo)`,`Whip pan`,`Aerial / drone`,hb];function _b({mode:e=`image`,model:t,shot:n,subject:r,subject2:i=null,posePhrase:a=``,pose2Phrase:o=``,environment:s,style:c,cameraMove:l=gb[0],customMove:u=``,hasCharSheet:d=!1,hasEnvSheet:f=!1}){let p=t?.numericLens?`${n.focalMm}mm lens at f/2.2`:`${n.focalMm}mm lens`,m=e===`video`?`Cinematic ${n.sizeLabel} at ${p}, ${n.levelPhrase}, ${n.viewPhrase}.`:`Photorealistic cinematic film still, ${n.sizeLabel} at ${p}, ${n.levelPhrase}, ${n.viewPhrase}.`,h=(e,t)=>t?`${e}, ${t}`:e,g;g=d?i?`Both subjects are the characters from the attached character sheet. Each one exactly matches their own body pose and placement shown in the blocking frame.`:`The subject is the character from the attached character sheet, exactly matching the body pose and placement shown in the blocking frame.`:i?`Two subjects. Subject 1: ${h(r,a)}. Subject 2: ${h(i,o)}. Each subject exactly matches their own body pose and placement shown in the blocking frame.`:`Subject: ${h(r,a)}, exactly matching the body pose and placement shown in the blocking frame.`;let _=f?`The setting is the location from the attached environment sheet.`:`Environment: ${s}.`,v=l===`Custom…`?u.trim()||`static, locked-off shot`:l.toLowerCase();return[m,g,_,`${c}, ${n.sizeContext}.`,e===`video`?`Camera move: ${v}.`:null,`Use the attached blocking frame ONLY as a camera and staging guide — it fixes the exact framing, this camera angle, the lens, and the subject placement. Its floor grid is a measuring aid that encodes distance and scale: read the subject's depth and size from it, but do NOT draw the grid itself. Replace the entire setting with the described environment and render real people; do NOT reproduce its grey mannequins, grey box set, measurement grid, or flat lighting.`,t?.flavor??null,e===`video`&&(t?.audio||t?.capabilities?.audio)?`Include natural ambient sound.`:null,`16:9.`].filter(Boolean).join(` `)}var vb=1;function yb(e){return Array.isArray(e)?`[${e.map(yb).join(`,`)}]`:!e||typeof e!=`object`?JSON.stringify(e):`{${Object.keys(e).filter(e=>e!==`id`).sort().map(t=>`${JSON.stringify(t)}:${yb(e[t])}`).join(`,`)}}`}function bb(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}var xb=class extends Error{constructor(e,t){super(`Unknown ${e} ID: ${t}`),this.name=`UnknownStableItemIdError`}};function Sb(e){return`${e}-${Date.now().toString(36)}-${vb++}`}function Cb(e){return typeof e==`string`&&e.trim()!==``}function wb(e,t,n=new Set){let r=n,i=new Map;return(Array.isArray(e)?e:[]).map(e=>{let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{},a=Cb(n.id)?n.id:null;if(a&&!r.has(a))return r.add(a),{...n,id:a};let o=`${t}-${bb(yb(n))}`,s=i.get(o)??0;i.set(o,s+1);let c=s===0?o:`${o}-${s+1}`;for(;r.has(c);){let e=i.get(o)??0;i.set(o,e+1),c=`${o}-${e+1}`}return r.add(c),{...n,id:c}})}function Tb(e,t,n){let r=Array.isArray(e)?e.find(e=>e.id===t):void 0;if(!r)throw new xb(n,t);return r}function Eb(e,t,n,r){return Tb(e,t,r),e.map(e=>e.id===t?n(e):e)}function Db(e,t,n){return Tb(e,t,n),e.filter(e=>e.id!==t)}var Ob=Object.freeze({minScale:.1,maxScale:10,maxOffset:100}),kb=(e,t)=>{let n=Number(e);return Number.isFinite(n)?n:t};function Ab(e){let t=((e+180)%360+360)%360-180;return Object.is(t,-0)?0:t}function jb(e,t=Ob){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{},r=Math.max(2**-52,kb(t?.minScale,Ob.minScale)),i=Math.max(r,kb(t?.maxScale,Ob.maxScale)),a=Math.max(0,kb(t?.maxOffset,Ob.maxOffset)),o=kb(n.scale,1),s=kb(n.yawDeg??n.yaw,0),c=e=>Math.max(-a,Math.min(a,kb(e,0)));return{scale:Math.max(r,Math.min(i,o>0?o:1)),yawDeg:Ab(s),offsetX:c(n.offsetX??n.offset_x),offsetY:c(n.offsetY??n.offset_y),offsetZ:c(n.offsetZ??n.offset_z)}}function Mb(e){return e==null?e:typeof e.slice==`function`?e.slice():Array.from(e)}function Nb(e,t){return e!=null&&typeof e.length==`number`&&e.length>=t}function Pb(e,t=e?.sceneCalibration,n={}){let r={status:`not-needed`,applied:!1,changedFrames:0,maxDisplacement:0,maxRootDisplacement:0,maxJointDisplacement:0,calibration:jb(null,n.limits)};if(!e||typeof e!=`object`)return{motion:e,diagnostics:{...r,status:`invalid-motion`}};let i=jb(t,n.limits),a=Number(e.frames),o=Number.isInteger(a)&&a>=0&&Nb(e.rootPos,a*3),s=Number.isInteger(a)&&a>=0&&Nb(e.posedJoints,0)&&e.posedJoints.length%(a*3||1)==0;if(!o&&!s)return{motion:e,diagnostics:{...r,status:`invalid-motion`,calibration:i}};if(i.scale===1&&i.yawDeg===0&&i.offsetX===0&&i.offsetY===0&&i.offsetZ===0)return{motion:e,diagnostics:{...r,calibration:i}};let c=i.yawDeg*Math.PI/180,l=Math.cos(c),u=Math.sin(c),d=(e,t,n)=>{let r=i.scale*e,a=i.scale*t,o=i.scale*n;return[l*r+u*o+i.offsetX,a+i.offsetY,-u*r+l*o+i.offsetZ]},f=o?Mb(e.rootPos):e.rootPos,p=s?Mb(e.posedJoints):e.posedJoints,m=0,h=0,g=0,_=(e,t)=>[...e,...t].every(Number.isFinite)?Math.hypot(t[0]-e[0],t[1]-e[1],t[2]-e[2]):0;for(let t=0;t<a;t+=1){let n=!1;if(o){let r=t*3,i=[e.rootPos[r],e.rootPos[r+1],e.rootPos[r+2]],a=d(...i);f[r]=a[0],f[r+1]=a[1],f[r+2]=a[2],m=Math.max(m,_(i,a)),n||=_(i,a)>1e-9}if(s){let r=e.posedJoints.length/(a*3);for(let i=0;i<r;i+=1){let a=(t*r+i)*3,o=[e.posedJoints[a],e.posedJoints[a+1],e.posedJoints[a+2]],s=d(...o);p[a]=s[0],p[a+1]=s[1],p[a+2]=s[2],h=Math.max(h,_(o,s)),n||=_(o,s)>1e-9}}n&&(g+=1)}let v={status:`calibrated`,applied:!0,changedFrames:g,maxDisplacement:Math.max(m,h),maxRootDisplacement:m,maxJointDisplacement:h,calibration:i};return{motion:{...e,rootPos:f,posedJoints:p},diagnostics:v}}var Fb=e=>Math.round(e*24/20),Ib=i(`character.position`);i(`character.rot`);var Lb=i(`character.scale`),Rb=Object.fromEntries([`x`,`y`,`z`,`intensity`,`warmth`].map(e=>[e,i(`stage.keyLight.${e}`)])),zb=`cozyclay.scenes.v4`,Bb=`cozyclay.scenes.v4.quarantine`,Vb=`cozyclay.scenes.v3`,Hb=`cozyclay.scenes.v2`,Ub=`cozyclay.scenes.v1`,Wb=`cozyclay.scene.v1`,Gb=Object.freeze([Vb,Hb,Ub]),Kb=Object.freeze([`y-bot-tpose`,`x-bot-tpose`]),qb=`y-bot-tpose`,Jb=`a young woman in a tan coat`,Yb=`a man in a dark coat`,Xb=Object.freeze({characters:Object.freeze([Object.freeze({id:`char-a`,model:qb,x:0,z:0,rot:0,hidden:!1,pose:null,subject:Jb})]),hasCharSheet:!1,environmentImage:null,environment:`a sunlit modern living room`,style:`moody cinematic lighting, 35mm film look`,hasEnvSheet:!1,shotAspect:`16:9`,cameraPresetId:null,sensorId:eb,keyLight:Object.freeze({x:6,y:9,z:4,intensity:1.12,warmth:.5})});function Zb(e){let t=$b(e)?e:{},n=Xb.keyLight,r=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)?Math.max(n.min,Math.min(n.max,e)):t;return{x:r(t.x,n.x,Rb.x),y:r(t.y,n.y,Rb.y),z:r(t.z,n.z,Rb.z),intensity:r(t.intensity,n.intensity,Rb.intensity),warmth:r(t.warmth,n.warmth,Rb.warmth)}}var Qb=1,$b=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function ex(e,t=new WeakMap){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e!=`object`)return null;if(t.has(e))return t.get(e);if(Array.isArray(e)){let n=[];t.set(e,n);for(let r of e)n.push(ex(r,t));return n}let n={};t.set(e,n);for(let[r,i]of Object.entries(e))Object.defineProperty(n,r,{value:ex(i,t),enumerable:!0,writable:!0,configurable:!0});return n}var tx=(e,t)=>Number.isFinite(e)?e:t;function nx(e){return typeof e==`string`&&e.startsWith(`data:image/`)?e:null}Lb.min,Lb.max;var rx=e=>Number.isFinite(e)&&e>0?Math.max(Lb.min,Math.min(Lb.max,e)):1;function ix(e,t,n){let r=tx(e?.rot,0)*Math.PI/180,i=tx(t,0),a=tx(n,0);return{x:tx(e?.x,0)+i*Math.cos(r)+a*Math.sin(r),z:tx(e?.z,0)-i*Math.sin(r)+a*Math.cos(r)}}function ax(e=null,t=0){let n=$b(e)?e:{};return{id:typeof n.id==`string`&&n.id?n.id:`char-${t+1}`,model:Kb.includes(n.model)?n.model:qb,x:Math.max(Ib.min.x,Math.min(Ib.max.x,tx(n.x,0))),y:Math.max(Ib.min.y,Math.min(Ib.max.y,tx(n.y,0))),z:Math.max(Ib.min.z,Math.min(Ib.max.z,tx(n.z,0))),rot:hg(tx(n.rot,0)),hidden:n.hidden===!0,tint:typeof n.tint==`string`&&/^#[0-9a-fA-F]{6}$/.test(n.tint)?n.tint:null,pose:$b(n.pose)?ex(n.pose):null,identityImage:nx(n.identityImage),scale:rx(n.scale),subject:typeof n.subject==`string`?n.subject:t===0?Jb:Yb,layer:cx(n.layer),motionRef:sx(n.motionRef)}}var ox=/^[0-9a-f]{64}$/i;function sx(e){if(!$b(e))return null;let t=typeof e.motionId==`string`&&ox.test(e.motionId)?e.motionId.toLowerCase():null,n=typeof e.url==`string`&&e.url?e.url:null;if(!t&&!n)return null;let r={};return t&&(r.motionId=t),n&&(r.url=n),Object.assign(r,{prompt:typeof e.prompt==`string`?e.prompt:``,rotationDeg:Number.isFinite(e.rotationDeg)?e.rotationDeg:0,anchorX:Number.isFinite(e.anchorX)?e.anchorX:0,anchorZ:Number.isFinite(e.anchorZ)?e.anchorZ:0}),$b(e.calibration)&&(r.calibration=jb(e.calibration)),e.trailEdits!=null&&(r.trailEdits=qy(e.trailEdits)),typeof e.studioTakeId==`string`&&e.studioTakeId&&(r.studioTakeId=e.studioTakeId),r}function cx(e){let t=$b(e)?e:{};return{waypoints:wb(ex(t.waypoints),`waypoint`),promptClips:wb(ex(t.promptClips),`prompt-clip`)}}function lx(e){let t=$b(e)?e:{},n=new Set;return{...t,characters:Array.isArray(t.characters)?t.characters.map(e=>({...e,layer:{waypoints:wb(ex(e.layer?.waypoints),`waypoint`,n),promptClips:wb(ex(e.layer?.promptClips),`prompt-clip`,n)}})):t.characters}}function ux(){return{waypoints:[],promptClips:[]}}function dx(e){if(!$b(e))return e;let t={...ex(e)};if(Array.isArray(e.waypoints)){let n=new Map;for(let t of e.waypoints){if(!$b(t)||!Number.isFinite(t.frame))continue;let e=Math.max(0,Fb(Math.round(t.frame)));n.set(e,{...ex(t),frame:e})}t.waypoints=[...n.values()].sort((e,t)=>e.frame-t.frame)}if(Array.isArray(e.promptClips)){let n=e.promptClips.filter(e=>$b(e)&&Number.isFinite(e.startFrame)&&Number.isFinite(e.endFrame)).sort((e,t)=>e.startFrame-t.startFrame),r=[],i=0;for(let e of n){let t=Math.max(i,Fb(Math.round(e.startFrame))),n=Math.max(t,Fb(Math.round(e.endFrame)));r.push({...ex(e),startFrame:t,endFrame:n}),i=n}t.promptClips=r}return t}function fx(e){return!$b(e)||!Array.isArray(e.characters)?e:{...e,characters:e.characters.map(e=>$b(e)&&$b(e.layer)?{...e,layer:dx(e.layer)}:e)}}function px(e){let t=[ax({...$b(e.charA)?e.charA:{},id:`char-a`,pose:e.poseA??null,subject:e.subject??`a young woman in a tan coat`},0)];return e.showB===!0&&t.push(ax({...$b(e.charB)?e.charB:{},id:`char-b`,pose:e.poseB??null,subject:e.subject2??`a man in a dark coat`},1)),t}var mx=new Set([`characters`,`hasCharSheet`,`environmentImage`,`environment`,`style`,`hasEnvSheet`,`shotAspect`,`cameraPresetId`,`sensorId`,`keyLight`,`charA`,`charB`,`showB`,`poseA`,`poseB`,`subject`,`subject2`]);function hx(e=null){let t=$b(e)?e:{},n=Array.isArray(t.characters)&&t.characters.length?t.characters.map((e,t)=>ax(e,t)):px(t),r={};for(let[e,n]of Object.entries(t))mx.has(e)||(r[e]=ex(n));return{...r,characters:n,hasCharSheet:t.hasCharSheet===!0,environmentImage:nx(t.environmentImage),environment:typeof t.environment==`string`?t.environment:Xb.environment,style:typeof t.style==`string`?t.style:Xb.style,hasEnvSheet:t.hasEnvSheet===!0,shotAspect:[`16:9`,`2.39:1`,`9:16`,`1:1`,`4:3`,`12:7`,`fal 480P`].includes(t.shotAspect)?t.shotAspect:Xb.shotAspect,cameraPresetId:typeof t.cameraPresetId==`string`&&t.cameraPresetId?t.cameraPresetId:Xb.cameraPresetId,sensorId:Object.hasOwn($y,t.sensorId??t.sensorFormat)?t.sensorId??t.sensorFormat:Xb.sensorId,keyLight:Zb(t.keyLight)}}function gx(e){let t=new Set(e.map(e=>e?.id)),n;do n=`scene-${Date.now().toString(36)}-${Qb++}`;while(t.has(n));return n}function _x(e,t){let n=e=>typeof e==`string`?e.normalize(`NFKC`).toLowerCase():``,r=new Set(t.map(e=>n(e?.name))),i=e=>r.has(n(e)),a=typeof e==`string`&&e.trim()?e.trim():`SCENE 01`;if(!i(a))return a;let o=a.match(/^(.*?)(\d+)$/);if(o){let[,e,t]=o;for(let n=Number(t)+1;;n+=1){let r=`${e}${String(n).padStart(t.length,`0`)}`;if(!i(r))return r}}for(let e=2;;e+=1){let t=`${a} ${e}`;if(!i(t))return t}}function vx(e=`SCENE 01`,t=[]){return{id:gx(t),name:_x(e,t),objects:[],shotDocument:null,stage:hx()}}function yx(e,t=`SCENE 01`){let n=Array.isArray(e)?e:[];return[...n,vx(t,n)]}function bx(e,t){if(!Array.isArray(e)||t<0||t>=e.length)return e;let n=e[t],r=vx(n.name,e);return r.objects=ex(n.objects),r.shotDocument=ex(n.shotDocument),r.stage=hx(n.stage),[...e.slice(0,t+1),r,...e.slice(t+1)]}function xx(e,t,n){if(!Array.isArray(e)||t<0||t>=e.length||typeof n!=`string`||!n.trim())return e;let r=_x(n,e.filter((e,n)=>n!==t));return r===e[t].name?e:e.map((e,n)=>n===t?{...e,name:r}:e)}function Sx(e,t){return!Array.isArray(e)||e.length<=1||t<0||t>=e.length?e:e.filter((e,n)=>n!==t)}function Cx(e,t){if(!Array.isArray(e)||!e.length)return-1;let n=e.findIndex(e=>e.id===t);return n<0?0:n}function wx(){let e=vx();return{version:4,activeSceneId:e.id,scenes:[e]}}function Tx(e,t,n,r,i=!1){if(!$b(e)||typeof e.id!=`string`||!e.id||!Array.isArray(e.objects)||t.some(t=>t.id===e.id))return null;let a=lx(hx(ex($b(e.stage)?e.stage:r)));return{id:e.id,name:_x(typeof e.name==`string`?e.name:`SCENE ${String(n).padStart(2,`0`)}`,t),objects:e.objects.filter($b).map(e=>ex(e)),shotDocument:ex(e.shotDocument??null),stage:i?fx(a):a}}function Ex(e,t=Xb,n=!1){let r=[],i=0;for(let a of e.scenes){let e=Tx(a,r,r.length+1,t,n);e?r.push(e):i+=1}return r.length||r.push(vx()),{document:{version:4,activeSceneId:r[Cx(r,e.activeSceneId)].id,scenes:r},dropped:i}}function Dx(e){try{return JSON.parse(e)}catch{return null}}function Ox(e,t=null){if(e==null||e===``){if(t!=null&&t!==``){let e=Dx(t);if(!$b(e)||e.version!==1||!Array.isArray(e.objects))return{status:`corrupt`,document:wx(),dropped:0,quarantineRaw:t};let n=wx();return n.scenes[0].objects=e.objects.filter($b).map(e=>ex(e)),{status:`migrated`,document:n,dropped:e.objects.length-n.scenes[0].objects.length}}return{status:`absent`,document:wx(),dropped:0}}let n=Dx(e);if(!$b(n)||!Number.isInteger(n.version)||n.version<1)return{status:`corrupt`,document:wx(),dropped:0,quarantineRaw:e};if(n.version>4)return{status:`future`,document:null,dropped:0};if(!Array.isArray(n.scenes))return{status:`corrupt`,document:wx(),dropped:0,quarantineRaw:e};let r=n.version<4,i=n.version<4,a=Ex(n,hx(n.stage),i);return{status:r?`migrated`:`valid`,...a}}function kx(e){return JSON.stringify({version:4,activeSceneId:e.activeSceneId,scenes:e.scenes})}function Ax(e){let t=e.getItem(zb);for(let n of Gb){if(t)break;t=e.getItem(n)}let n=t?null:e.getItem(Wb),r=Ox(t,n);return r.status===`corrupt`&&r.quarantineRaw!==void 0&&e.setItem(Bb,r.quarantineRaw),r.status===`migrated`&&e.setItem(zb,kx(r.document)),r}var Q=e(g(),1),jx=`cozyclay.locale`;function Mx(){try{let e=localStorage.getItem(jx);return e===`ko`||e===`en`?e:null}catch{return null}}var Nx=Mx()??`en`,Px=Nx===`ko`,Fx=Mx()!==null;function Ix(e,t){return Px?t:e}function Lx(e){if(e===`ko`||e===`en`){try{localStorage.setItem(jx,e)}catch{}window.location.reload()}}var Rx=`.cclayproject`,zx=`cozyclay.workflow.v1`,Bx=`cozyclay.project-handle.v1`,Vx=`kv`,Hx=`lastProjectHandle`,Ux=201326592,Wx=268435456,Gx=/^[0-9a-f]{64}$/i;function Kx(e){if(!e||typeof e!=`object`)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qx(e,t=0){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:null;if(t>32)return null;if(Array.isArray(e))return e.map(e=>qx(e,t+1));if(!Kx(e))return null;let n={};for(let[r,i]of Object.entries(e))r!==`__proto__`&&r!==`constructor`&&r!==`prototype`&&i!==void 0&&typeof i!=`function`&&typeof i!=`symbol`&&(n[r]=qx(i,t+1));return n}function Jx(e){return{x:Number.isFinite(e?.x)?e.x:0,y:Number.isFinite(e?.y)?e.y:0}}function Yx(){return{version:1,nodes:[],edges:[]}}function Xx(e){if(!Kx(e)||e.version!==void 0&&e.version!==1)return Yx();let t=[],n=new Set;for(let r of Array.isArray(e.nodes)?e.nodes:[]){if(!Kx(r)||typeof r.id!=`string`||!r.id.trim()||n.has(r.id))continue;let e=qx(r.data);t.push({id:r.id,type:typeof r.type==`string`&&r.type.trim()?r.type:`default`,position:Jx(r.position),data:Kx(e)?e:{}}),n.add(r.id)}let r=[],i=new Set;for(let t=0;t<(Array.isArray(e.edges)?e.edges.length:0);t+=1){let a=e.edges[t];if(!Kx(a)||typeof a.source!=`string`||typeof a.target!=`string`||!n.has(a.source)||!n.has(a.target))continue;let o=typeof a.id==`string`&&a.id.trim()?a.id:`${a.source}->${a.target}:${t}`;if(i.has(o))continue;let s={id:o,source:a.source,target:a.target};typeof a.sourceHandle==`string`&&a.sourceHandle&&(s.sourceHandle=a.sourceHandle),typeof a.targetHandle==`string`&&a.targetHandle&&(s.targetHandle=a.targetHandle);let c=qx(a.data);Kx(c)&&(s.data=c),r.push(s),i.add(o)}return{version:1,nodes:t,edges:r}}function Zx(e=globalThis.localStorage){try{return Xx(JSON.parse(e?.getItem(`cozyclay.workflow.v1`)||`null`))}catch{return Yx()}}function Qx(e,t=globalThis.localStorage){let n=Xx(e);try{t?.setItem(zx,JSON.stringify(n))}catch{}try{globalThis.dispatchEvent?.(new CustomEvent(`cozyclay:workflow-change`))}catch{}return n}function $x(e){return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):null}function eS(e){let t=new Uint8Array(e),n=``;for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(n)}function tS(e,t){if(typeof e!=`string`||e.length<4||e.length%4)return{code:`bad-base64`};if(e.length>Math.ceil(t/3)*4)return{code:`too-large`};let n=e.endsWith(`==`)?2:+!!e.endsWith(`=`);for(let t=0;t<e.length-n;t+=1){let n=e.charCodeAt(t);if(!(n>=65&&n<=90||n>=97&&n<=122||n>=48&&n<=57||n===43||n===47))return{code:`bad-base64`}}let r=e.length/4*3-n;return r>t?{code:`too-large`}:{bytes:r}}function nS(e,t){let n=tS(e,t);if(n.code)return n;try{let t=atob(e),n=Uint8Array.from(t,e=>e.charCodeAt(0));return eS(n)===e?{buffer:n.buffer}:{code:`bad-base64`}}catch{return{code:`bad-base64`}}}function rS(e,t,n){let r=Error(`${n} (${e} bytes) exceeds the ${t}-byte limit.`);return r.code=`resources-too-large`,r.bytes=e,r.limit=t,r}function iS(e){let t=$x(e?.bytes),n=em({...e,bytes:t});return!n||n.bytes.byteLength>33554432?null:{record:{...n,bytes:eS(n.bytes)},bytes:n.bytes.byteLength}}function aS(e){let t=new Set,n=e=>{if(Array.isArray(e)){for(let t of e)n(t);return}if(Kx(e)){Kp(e.assetRef)&&t.add(e.assetRef);for(let t of Object.values(e))n(t)}};return n(e),t}function oS(e){return{...Number.isInteger(e.frames)&&e.frames>=0?{frames:e.frames}:{},...Number.isFinite(e.fps)&&e.fps>0?{fps:e.fps}:{},...typeof e.name==`string`&&e.name.trim()?{name:e.name}:{},...Kx(e.meta)?{meta:qx(e.meta)}:{}}}function sS(e){return typeof e==`string`&&Gx.test(e)?e.toLowerCase():null}function cS(e){if(!e||typeof e!=`object`)return null;let t=sS(e.motionId);if(!t)return null;let n=$x(e.bytes);if(n){if(!n.byteLength)return null;if(n.byteLength>201326592)throw rS(n.byteLength,Ux,`Motion ${t}`);return{motionId:t,bytes:n.byteLength,raw:n,details:oS(e)}}if(e.encoding!==`base64`)return null;let r=tS(e.data,Ux);if(r.code===`too-large`)throw rS(e.data.length/4*3,Ux,`Motion ${t}`);return r.code||e.bytes!==void 0&&e.bytes!==r.bytes?null:{motionId:t,bytes:r.bytes,data:e.data,details:oS(e)}}async function lS(e,t){let n=$x(e?.bytes);if(!n)return!1;try{return(qp(e.id)?await Zp(n,t):await Xp(n,t))===e.id}catch{return!1}}var uS={"bad-id":`its id is not a content address`,duplicate:`the same id appears earlier in the file`,"bad-encoding":`its encoding is not base64`,"bad-base64":`its payload is not valid base64`,"length-mismatch":`its payload does not match the recorded byte length`,"too-large":`its payload exceeds the size limit`,"bad-record":`its metadata is incomplete`};function dS(e,t){let n=[];if(!Array.isArray(e))return n;let r=new Set;for(let i of e){let e=typeof i?.id==`string`?i.id:null;if(!Jp(e)){t(`image`,e,`bad-id`);continue}if(r.has(e)){t(`image`,e,`duplicate`);continue}let a=nS(i.bytes,Rp);if(a.code){t(`image`,e,a.code);continue}let o=em({...i,bytes:a.buffer});if(!o){t(`image`,e,`bad-record`);continue}r.add(e),n.push(o)}return n}function fS(e,t){let n=[];if(!Array.isArray(e))return n;let r=new Set;for(let i of e){let e=sS(i?.motionId);if(!e){t(`motion`,typeof i?.motionId==`string`?i.motionId:null,`bad-id`);continue}if(r.has(e)){t(`motion`,e,`duplicate`);continue}if(i.encoding!==`base64`){t(`motion`,e,`bad-encoding`);continue}let a=tS(i.data,Ux);if(a.code){t(`motion`,e,a.code);continue}if(i.bytes!==a.bytes){t(`motion`,e,`length-mismatch`);continue}r.add(e),n.push({motionId:e,encoding:`base64`,data:i.data,bytes:a.bytes,...oS(i)})}return n}function pS({scenesDocument:e,workspaceLayout:t,customPoses:n,name:r,assets:i,motions:a,savedAt:o,workflow:s}){let c=new Map;for(let e of Array.isArray(i)?i:[]){let t=iS(e);t&&c.set(t.record.id,t)}let l=[],u=0,d=om(e?.scenes);for(let e of aS(s))d.add(e);for(let e of d){let t=c.get(e);t&&(l.push(t.record),u+=t.bytes)}let f=new Map;for(let e of Array.isArray(a)?a:[]){let t=cS(e);!t||f.has(t.motionId)||(f.set(t.motionId,t),u+=t.bytes)}if(u>268435456)throw rS(u,Wx,`Embedded resources`);let p=[...f.values()].map(({motionId:e,bytes:t,raw:n,data:r,details:i})=>({motionId:e,encoding:`base64`,data:r??eS(n),bytes:t,...i}));return{app:`cozyclay`,kind:`project`,version:4,name:typeof r==`string`&&r.trim()?r.trim():`Untitled`,...Number.isFinite(o)&&o>0?{savedAt:o}:{},scenes:e,workspace:t??null,poseLibrary:Array.isArray(n)?n:[],workflow:Xx(s),resources:{assets:l,motions:p}}}function mS(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,reason:`corrupt`}}if(!t||typeof t!=`object`)return{ok:!1,reason:`corrupt`};if(t.app!==`cozyclay`||t.kind!==`project`)return{ok:!1,reason:`not-a-project`};if(typeof t.version!=`number`)return{ok:!1,reason:`corrupt`};if(t.version>4)return{ok:!1,reason:`future`};let n=t.scenes;if(!n||typeof n!=`object`||n.version>4||!Array.isArray(n.scenes))return{ok:!1,reason:`scenes-invalid`};let r=[],i=[],a=(e,t,n)=>{let a=`Skipped embedded ${e} ${t??`(no id)`}: ${uS[n]}.`;i.push({kind:e,id:t,code:n,message:a}),r.push(a)},o=dS(t.version>=4?t.resources?.assets:t.version>=2?t.assets:void 0,a),s=t.version>=4?fS(t.resources?.motions,a):[],c=Xx(t.workflow);return{ok:!0,warnings:r,problems:i,project:{name:typeof t.name==`string`&&t.name.trim()?t.name.trim():`Untitled`,savedAt:Number.isFinite(t.savedAt)&&t.savedAt>0?t.savedAt:null,scenesDocument:{version:n.version,activeSceneId:n.activeSceneId??null,scenes:n.scenes},workspaceLayout:t.workspace&&typeof t.workspace==`object`?t.workspace:null,customPoses:Array.isArray(t.poseLibrary)?t.poseLibrary.filter(e=>e&&typeof e==`object`&&typeof e.id==`string`&&e.bones&&typeof e.bones==`object`):[],assets:o,motions:s,workflow:c}}}function hS(){return typeof window<`u`&&typeof window.showSaveFilePicker==`function`&&typeof window.showOpenFilePicker==`function`}var gS=[{description:`CozyClay Project`,accept:{"application/json":[Rx,`.json`]}}];async function _S(e){return await window.showSaveFilePicker({suggestedName:`${e||`Untitled`}${Rx}`,types:gS})}async function vS(){let[e]=await window.showOpenFilePicker({types:gS,multiple:!1});return e}async function yS(e,t){let n=await e.createWritable();await n.write(t),await n.close()}async function bS(e){let t=await e.getFile();return{name:t.name.replace(/\.cclayproject$|\.json$/i,``),text:await t.text(),savedAt:t.lastModified}}function xS(e,t){let n=new Blob([e],{type:`application/json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${t||`Untitled`}${Rx}`,i.click(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}function SS(){return new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=`${Rx},.json,application/json`,t.onchange=async()=>{let n=t.files?.[0];if(!n)return e(null);e({name:n.name.replace(/\.cclayproject$|\.json$/i,``),text:await n.text(),savedAt:n.lastModified})},t.oncancel=()=>e(null),t.click()})}function CS(){return new Promise((e,t)=>{let n=indexedDB.open(Bx,1);n.onupgradeneeded=()=>n.result.createObjectStore(Vx),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async function wS(e,t){try{let n=await CS();await new Promise((r,i)=>{let a=n.transaction(Vx,`readwrite`);a.objectStore(Vx).put({handle:e,name:t},Hx),a.oncomplete=r,a.onerror=()=>i(a.error)}),n.close()}catch{}}async function TS(){try{let e=await CS(),t=await new Promise((t,n)=>{let r=e.transaction(Vx,`readonly`).objectStore(Vx).get(Hx);r.onsuccess=()=>t(r.result??null),r.onerror=()=>n(r.error)});return e.close(),t}catch{return null}}async function ES(){try{let e=await CS();await new Promise((t,n)=>{let r=e.transaction(Vx,`readwrite`);r.objectStore(Vx).delete(Hx),r.oncomplete=t,r.onerror=()=>n(r.error)}),e.close()}catch{}}var DS=`recentProjects`,OS=`projectsDirectory`,kS=8,AS=`cozyclay.project-session.v1`;function jS(e=globalThis.localStorage){try{let t=JSON.parse(e?.getItem(`cozyclay.project-session.v1`)||`null`);if(!t||typeof t!=`object`)return null;let n=typeof t.name==`string`?t.name.trim():``;return n?{name:n,updatedAt:Number.isFinite(t.updatedAt)?t.updatedAt:0}:null}catch{return null}}function MS(e,t=globalThis.localStorage){let n=typeof e==`string`?e.trim():``;if(!n)return!1;try{return t?.setItem(AS,JSON.stringify({name:n,updatedAt:Date.now()})),!0}catch{return!1}}async function NS(e,t){try{let n=await CS();await new Promise((r,i)=>{let a=n.transaction(Vx,`readwrite`);a.objectStore(Vx).put(t,e),a.oncomplete=r,a.onerror=()=>i(a.error)}),n.close()}catch{}}async function PS(e){try{let t=await CS(),n=await new Promise((n,r)=>{let i=t.transaction(Vx,`readonly`).objectStore(Vx).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)});return t.close(),n}catch{return null}}async function FS(e,t){let n=await PS(DS)??[];await NS(DS,[{handle:e,name:t,openedAt:Date.now()},...n.filter(e=>e.name!==t)].slice(0,kS)),await wS(e,t)}async function IS(){return await PS(DS)??[]}async function LS(e){await NS(DS,(await PS(DS)??[]).filter(t=>t.name!==e))}function RS(){return typeof window<`u`&&typeof window.showDirectoryPicker==`function`}async function zS(){return window.showDirectoryPicker({mode:`readwrite`})}async function BS(e){await NS(OS,{handle:e})}async function VS(){return(await PS(OS))?.handle??null}async function HS(e){let t=[];try{for await(let[n,r]of e.entries()){if(r.kind!==`file`||!n.endsWith(`.cclayproject`))continue;let e=await r.getFile();t.push({name:n.slice(0,-13),handle:r,lastModified:e.lastModified})}}catch{return[]}return t.sort((e,t)=>t.lastModified-e.lastModified)}async function US(e){try{return await e.queryPermission({mode:`readwrite`})}catch{return`denied`}}async function WS(e){try{return await e.queryPermission({mode:`readwrite`})===`granted`?`granted`:await e.requestPermission({mode:`readwrite`})}catch{return`denied`}}Object.freeze([`idle`,`fetching`,`probing`,`ready`,`error`]);function GS(e,t=!1){if(!e)return``;if(e.status===`disabled`)return t?`낙하 보정 꺼짐`:`Descent recovery off`;if(e.status===`corrected`){let n=e.rejected?.length??0;return t?`낙하 보정 ${e.changedFrames}프레임 적용${n?` · ${n}구간 미해결`:``}`:`Descent recovery: ${e.changedFrames} frames corrected${n?` · ${n} unresolved spans`:``}`}let n=e.rejected?.[0]?.reason??e.reason??`unknown`;return`${t?`낙하 보정 미적용`:`Descent recovery not applied`}: ${{"world-endpoint-unsettled":[`3D endpoint never settles`,`3D 끝점이 안정되지 않음`],"no-confident-delayed-descent":[`no confident delayed descent detected`,`확실한 낙하 지연이 검출되지 않음`],"moving-camera-not-supported":[`moving-camera recovery unsupported`,`이동 카메라 보정 미지원`],"uncertain-keypoints":[`body tracking uncertain`,`관절 추적 불확실`],"uncertain-depth":[`depth change too large`,`깊이 변화가 큼`],"moving-landing":[`landing does not stay still`,`착지 후 이동이 계속됨`],"no-observed-landing":[`landing not observed`,`착지를 확인할 수 없음`],"landing-observation-too-short":[`not enough footage after landing`,`착지 이후 영상이 너무 짧음`],"excessive-correction":[`recovery exceeds its safety bound`,`보정량이 안전 범위를 초과함`]}[n]?.[+!!t]??n}`}function KS(e,t=!1){if(!e)return``;if(e.available===!1)return t?`색 세그멘테이션 측정 불가`:`Palette segmentation metrics unavailable`;if(e.detector!==`palette`||!Number.isFinite(e.detectionRate))return``;let n=Math.round(e.detectionRate*100),r=Number.isFinite(e.coverage?.mean)?Math.round(e.coverage.mean*100):null,i=Number.isFinite(e.coverage?.p10)&&Number.isFinite(e.coverage?.p90)?`${Math.round(e.coverage.p10*100)}–${Math.round(e.coverage.p90*100)}%`:null,a=Number.isFinite(e.parts?.mean)?Math.round(e.parts.mean):null,o=Number.isFinite(e.longestGapFrames)?e.longestGapFrames:0,s=Number.isFinite(e.hueErrorDeg?.p95)?Math.round(e.hueErrorDeg.p95):null;return t?`색 세그멘테이션: ${n}% 검출${r===null?``:` · 마스크 ${r}%${i?` (${i})`:``}`}${a===null?``:` · 색 파트 ${a}개`}${o?` · 최대 끊김 ${o}프레임`:``}${s===null?``:` · 색 오차 P95 ${s}°`}`:`Palette segmentation: ${n}% detected${r===null?``:` · ${r}% mask${i?` (${i})`:``}`}${a===null?``:` · ${a} colour parts`}${o?` · longest gap ${o} frames`:``}${s===null?``:` · hue error P95 ${s}°`}`}function qS(e){if(typeof e!=`string`)return{ok:!1,reason:`url-not-string`};let t=e.trim();if(t.length===0)return{ok:!1,reason:`url-empty`};if(t.startsWith(`//`))return{ok:!1,reason:`url-protocol-relative`};if(t.startsWith(`/`))return{ok:!0,url:t};if(/^https?:\/\//i.test(t)){let e;try{e=new URL(t)}catch{return{ok:!1,reason:`url-malformed`}}return YS(e.toString())?{ok:!1,reason:`url-platform-page`}:{ok:!0,url:e.toString()}}return{ok:!1,reason:`url-scheme-unsupported`}}var JS=/(?:^|\.)(?:youtube\.com|youtu\.be|vimeo\.com|tiktok\.com|instagram\.com|facebook\.com|twitter\.com|x\.com|bilibili\.com|naver\.com|kakao\.com)$/i;function YS(e){if(typeof e!=`string`)return!1;try{return JS.test(new URL(e).hostname)}catch{return!1}}async function XS(e,t,{fetchImpl:n,onProgress:r,defaultError:i}={}){let a=n??globalThis.fetch;if(typeof a!=`function`)throw Error(`fetch-unavailable`);let o;try{o=await a(e,t)}catch{throw Error(`bridge-unreachable`)}if(!o.ok){let e=`http-${o.status}`;try{e=(await o.json())?.reason??e}catch{}throw Error(e)}let s=o.body?.getReader?null:await o.text(),c=``,l=null,u=e=>{if(!e.trim())return;let t;try{t=JSON.parse(e)}catch{return}if(t.event===`progress`)r?.({stage:t.stage,ratio:t.ratio});else if(t.event===`error`)throw Error(t.message||i);else t.event===`done`&&(l=t)};if(s!==null)for(let e of s.split(`
|
|
14
14
|
`))u(e);else{let e=o.body.getReader(),t=new TextDecoder;for(;;){let{done:n,value:r}=await e.read();if(n)break;c+=t.decode(r,{stream:!0});let i=c.split(`
|
|
15
15
|
`);c=i.pop()??``;for(let e of i)u(e)}c&&u(c)}return l}async function ZS(e,t={}){let n=await XS(`/ardy/footage`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({url:e})},{...t,defaultError:`footage-download-failed`});if(!n||typeof n.url!=`string`)throw Error(`bridge-footage-incomplete`);return n}async function QS(e,t={}){let n=await XS(`/ardy/extract`,typeof e?.footage==`string`?{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({footage:e.footage})}:{method:`POST`,headers:{"Content-Type":`application/octet-stream`},body:e},{...t,defaultError:`extract-run-failed`});if(!n||typeof n.motionUrl!=`string`)throw Error(`bridge-extract-incomplete`);return n}async function $S(e,t=globalThis.fetch){if(typeof e!=`string`||!e)throw Error(`Generated video has no fetchable output.`);if(typeof t!=`function`)throw Error(`video-download-unavailable`);let n=await t(e);if(!n.ok)throw Error(`Generated video download failed (${n.status}).`);return n.blob()}function eC(e){if(typeof e!=`string`||e.length===0)return``;let t=e.split(/[?#]/)[0];return t.split(`/`).filter(Boolean).pop()??t}function tC(e,t){return!Number.isFinite(t)||t<=0||!Number.isFinite(e)||e<0?null:Math.min(1,e/t)}function nC(e,t){return!(e>0)||!(t>0)?1:Math.max(1,Math.floor(e*t+1e-6)+1)}function rC(e,t=30){if(!Array.isArray(e)||e.length<3)return{fps:t,measured:!1};let n=[];for(let t=1;t<e.length;t+=1){let r=e[t]-e[t-1];r>1e-4&&n.push(r)}if(n.length===0)return{fps:t,measured:!1};n.sort((e,t)=>e-t);let r=n[Math.floor(n.length/2)];return r>0?{fps:Math.round(1/r),measured:!0}:{fps:t,measured:!1}}function iC(e){return!Number.isFinite(e)||e<0?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(0)} KB`:`${(e/1048576).toFixed(1)} MB`}function aC(e){if(!e)return``;let t=[`${e.width}×${e.height}`,`${e.durationS.toFixed(2)}s`,`${e.fps} fps${e.fpsMeasured?``:`?`}`,`${e.frames} frames`];return Number.isFinite(e.bytes)&&e.bytes>0&&t.push(iC(e.bytes)),t.join(` · `)}async function oC(e,{fetchImpl:t,onProgress:n,signal:r}={}){let i=t??globalThis.fetch;if(typeof i!=`function`)throw Error(`fetch-unavailable`);let a;try{a=await i(e,{signal:r})}catch(e){throw e?.name===`AbortError`?e:Error(`fetch-failed`)}if(!a.ok)throw Error(`http-${a.status}`);let o=Number(a.headers?.get?.(`content-length`)),s=Number.isFinite(o)&&o>0?o:null,c=a.headers?.get?.(`content-type`)??``;if(/^(?:text\/html|application\/json|text\/plain)\b/i.test(c))throw Error(`not-a-video`);if(!a.body?.getReader){let e=await a.blob();return n?.({received:e.size,total:e.size,ratio:1}),{blob:e,bytes:e.size,type:c}}let l=a.body.getReader(),u=[],d=0;for(;;){let{done:e,value:t}=await l.read();if(e)break;u.push(t),d+=t.byteLength??t.length??0,n?.({received:d,total:s,ratio:tC(d,s)})}let f=new Blob(u,{type:c||`video/mp4`});return n?.({received:d,total:s??d,ratio:1}),{blob:f,bytes:d,type:c}}async function sC(e,{createVideo:t,timeoutMs:n=15e3,fallbackFps:r=30,knownFps:i=null}={}){let a=t();a.src=e,a.muted=!0,a.playsInline=!0,a.preload=`auto`,await new Promise((e,t)=>{let r=!1,i=setTimeout(()=>{r||(r=!0,t(Error(`probe-timeout`)))},n),o=n=>{r||(r=!0,clearTimeout(i),n?t(n):e())};a.addEventListener(`loadedmetadata`,()=>o(null),{once:!0}),a.addEventListener(`error`,()=>o(Error(`decode-failed`)),{once:!0}),a.load?.()});let o=Number(a.duration),s=Number(a.videoWidth),c=Number(a.videoHeight);if(!(o>0))throw Error(`duration-unreadable`);if(!(s>0)||!(c>0))throw Error(`dimensions-unreadable`);let l=Number.isFinite(i)&&i>0,u=l?[]:await cC(a),{fps:d,measured:f}=l?{fps:i,measured:!0}:rC(u,r);return{durationS:o,width:s,height:c,fps:d,fpsMeasured:f,frames:nC(o,d)}}async function cC(e,t=12){if(typeof e.requestVideoFrameCallback!=`function`)return[];let n=[];try{await e.play?.()}catch{return[]}return await new Promise(r=>{let i=Date.now()+2e3,a=(o,s)=>{if(n.push(s?.mediaTime??0),n.length>=t||Date.now()>i){r();return}e.requestVideoFrameCallback(a)};e.requestVideoFrameCallback(a)}),e.pause?.(),e.currentTime=0,n}var $=S_();function lC(e){return e?typeof e.id==`string`&&qp(e.id)?!0:Vp(e.type):!1}function uC({getRecord:e=async e=>mm(await fC(),e),putRecord:t=async e=>pm(await fC(),e),createBitmap:n=(...e)=>createImageBitmap(...e),makeTexture:r=e=>new or(e)}={}){let i=new Map;function a(e){let t=i.get(e);return t||(t={texture:null,record:null,promise:null,listeners:new Set,generation:0,evicted:!1},i.set(e,t)),t}function o(e){for(let t of e.listeners)t(e.texture)}function s(e){e?.image?.close?.(),e?.dispose?.()}async function c(e){if(lC(e))return null;let t=r(await n(new Blob([e.bytes],{type:e.type}),{imageOrientation:`flipY`}));return t.flipY=!1,t.colorSpace=Ot,t.generateMipmaps=!0,t.minFilter=ae,t.magFilter=A,t.anisotropy=4,t.needsUpdate=!0,t.userData.assetId=e.id,t}function l(t){if(typeof t!=`string`||!t||qp(t))return Promise.resolve(null);let n=a(t);if(n.evicted)return Promise.resolve(null);if(n.texture)return Promise.resolve(n.texture);if(!n.promise){let r=n.generation;n.promise=(async()=>{let i=n.record??await e(t);if(!i||n.evicted||n.generation!==r||lC(i))return null;n.record=i;let a=await c(i);return n.evicted||n.generation!==r?(s(a),null):(n.texture=a,o(n),a)})().catch(e=>(console.warn(`[cozyclay] could not load image asset ${t}`,e),n.failed=!0,null)).finally(()=>{n.generation===r&&(n.promise=null)})}return n.promise}async function u(t){if(typeof t!=`string`||!t)return null;let n=a(t);return n.evicted?null:(n.record||=await e(t),n.record)}async function d(e){let n=await t(e),r=a(n.id),i=++r.generation;if(r.evicted=!1,s(r.texture),r.texture=null,r.record=n,r.promise=null,lC(n)||qp(n.id))return n;let l=await c(n);return!l||r.generation!==i?(s(l),n):(r.texture=l,o(r),n)}function f(e){let t=i.get(e);t&&(t.generation+=1,t.evicted=!0,s(t.texture),t.texture=null,t.record=null,t.promise=null,o(t))}function p(e,t){if(typeof e!=`string`||!e)return()=>{};let n=a(e);return n.listeners.add(t),n.texture?t(n.texture):l(e),()=>n.listeners.delete(t)}function m(){for(let e of i.values())s(e.texture);i.clear()}return{loadAssetTexture:l,assetRecord:u,rememberAsset:d,evictAssetTexture:f,subscribeToAssetTexture:p,clearAssetTextures:m}}var dC=null;function fC(){return dC||=fm(),dC}var pC=uC();pC.loadAssetTexture;var mC=pC.assetRecord,hC=pC.rememberAsset,gC=pC.evictAssetTexture,_C=pC.subscribeToAssetTexture;pC.clearAssetTextures;var vC=new Set([`aborted`,`capture_failed`,`generation_failed`,`unknown`]),yC=new Set([`aborted`,`auth`,`rate_limited`,`tool_failed`,`upstream`,`unknown`]);function bC(){try{if(!globalThis.crypto?.getRandomValues)return null;let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{return null}}function xC(e,t,n){try{Promise.resolve(e(t,n)).catch(()=>{})}catch{}}function SC(e){try{return e()}catch{return NaN}}function CC(e,t,n=`unknown`){let r=t===`agent`?yC:vC;try{if(e?.name===`AbortError`)return`aborted`}catch{}return r.has(n)?n:`unknown`}function wC(e,{capture:t=s,now:n=()=>performance.now(),durationBucket:r=p}={}){let i=bC(),a=!1,o=!1,c=SC(n),u=(e,n)=>{i&&xC(t,e,n)};i&&u(`workflow:run_requested`,{surface:`workflow`,...l.node_count_bucket.has(e.node_count_bucket)?{node_count_bucket:e.node_count_bucket}:{},run_id:i});let d=(e,t,o)=>{if(a||!i)return;a=!0;let s=CC(t,`workflow`,o),d=e===`failed`&&s===`aborted`?`cancelled`:e,f=`lt1s`;try{let e=r(SC(n)-c);l.duration_bucket.has(e)&&(f=e)}catch{}u(`workflow:run_${d}`,{run_id:i,duration_bucket:f,...d===`succeeded`?{}:{failure_code:s}})};return{runId:i,succeed(){d(`succeeded`)},fail(e,t=`unknown`){d(`failed`,e,t)},apply(){o||!i||(o=!0,u(`workflow:result_applied`,{run_id:i}))}}}var TC=new Set([...new Set([`motion:generate_requested`,`motion:preflight_blocked`,`motion:preflight_passed`,`motion:job_started`,`motion:job_succeeded`,`motion:job_failed`,`motion:result_applied`]),...d.filter(e=>e.startsWith(`mcp:`))]),EC=`5184`,DC=((e=EC)=>`ws://127.0.0.1:${e}/live`)(),OC=1e3,kC=15e3,AC=.25,jC=2e4,MC=1e4,NC=`cozyclay:live-workspace-id`,PC=``;function FC(e){try{return e??globalThis.sessionStorage??null}catch{return null}}function IC(){return globalThis.crypto?.randomUUID?.()??`live-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function LC(e,t){PC=e;try{FC(t)?.setItem(NC,e)}catch{}return e}function RC(e){try{let t=FC(e)?.getItem(NC);if(typeof t==`string`&&t)return PC=t,t}catch{}return PC||LC(IC(),e)}function zC(e){return LC(IC(),e)}function BC(e,{target:t=globalThis,doc:n=globalThis.document}={}){if(typeof t?.addEventListener!=`function`)return()=>{};let r=()=>{n?.visibilityState===`visible`&&e()},i=[`online`,`focus`,`pageshow`];for(let n of i)t.addEventListener(n,e);return n?.addEventListener?.(`visibilitychange`,r),()=>{for(let n of i)t.removeEventListener(n,e);n?.removeEventListener?.(`visibilitychange`,r)}}var VC={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>globalThis.performance?.now?.()??Date.now()};function HC(e){return e?.code===1008&&typeof e.reason==`string`&&e.reason.includes(`Workspace id is already connected`)}function UC(e){return e instanceof Error&&e.message?e.message:typeof e==`string`&&e?e:`Command failed`}function WC(e,t,n){return t?{type:`result`,id:e,ok:!0,value:n??{}}:{type:`result`,id:e,ok:!1,error:n}}async function GC(e,t={}){if(typeof e!=`string`)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!n||typeof n!=`object`||Array.isArray(n)||n.type!==`cmd`||typeof n.id!=`string`)return null;if(typeof n.name!=`string`||!n.name)return WC(n.id,!1,`Invalid command name`);if(!n.args||typeof n.args!=`object`||Array.isArray(n.args))return WC(n.id,!1,`Invalid command arguments`);let r=t[n.name];if(typeof r!=`function`)return WC(n.id,!1,`Unknown command: ${n.name}`);try{return WC(n.id,!0,await r(n.args))}catch(e){return WC(n.id,!1,UC(e))}}function KC({handlers:e={},onWorkspace:t=()=>{},onEvent:n=()=>{},onDuplicate:r=()=>zC(),captureMotionTelemetry:i=s,captureTelemetry:a=s,workspaceId:o=``,meta:l=null,WebSocketImpl:u=globalThis.WebSocket,url:p=DC,timers:m=VC,random:h=Math.random,listen:g=BC}={}){let _=e,v=o,y=null,b=null,x=0,S=!1,C=null,w=0,T=0,E=!1,D=null,O=new Set,ee=e=>{if(!TC.has(e.event))return;let t=c(e.event,e.props),n=t.request_id;if(!n||d.includes(e.event)&&f[e.event]?.some(e=>!Object.hasOwn(t,e))||(e.event===`motion:generate_requested`||e.event.startsWith(`motion:preflight_`))&&t.surface!==`mcp`)return;let r=`${n}:${e.event}`;if(O.has(r))return;O.add(r);let o=e.event.startsWith(`motion:`)?i:a;try{Promise.resolve(o(e.event,t)).catch(()=>{})}catch{}},k=()=>{b!==null&&m.clearTimeout(b),b=null},te=()=>{let e=Math.min(OC*2**x,kC);return x+=1,Math.round(e*(1+(h()*2-1)*AC))},ne=()=>{S||b!==null||y||(b=m.setTimeout(()=>{b=null,se()},te()))},re=()=>{S||y||(k(),se())},ie=()=>{C!==null&&m.clearTimeout(C),C=null,E=!1,D=null},A=e=>{C!==null&&m.clearTimeout(C),w=m.now(),T=e,C=m.setTimeout(M,e)},j=e=>{ie(),!(typeof e!=`number`||!(e>0))&&(E=!0,A(jC))};function M(){if(C=null,S||!E||!y)return;let e=m.now();if(e-w>T+2e3){D=null,A(jC);return}if(D===null){oe({type:`ping`}),D=e,A(MC);return}let t=e-D;if(t>=1e4){ae();return}A(MC-t)}let ae=()=>{let e=y;y=null,ie();try{e?.close()}catch{}ne()},oe=e=>{if(!(!y||y.readyState!==(y.OPEN??1)))try{y.send(JSON.stringify(e))}catch{}},se=()=>{if(S||!u)return;k(),ie();try{y=new u(p)}catch{y=null,ne();return}let e=y;e.onopen=()=>{y!==e||S||oe({type:`hello`,role:`editor`,version:1,...v?{workspaceId:v}:{},...l?{meta:l}:{}})},e.onmessage=async r=>{if(y!==e||S)return;if(typeof r?.data==`string`)try{let e=JSON.parse(r.data);if(e?.type===`workspace`&&typeof e.handle==`string`){x=0,j(e.heartbeatMs),t(e.handle);return}if(e?.type===`pong`){E&&(D=null,A(jC));return}if(e?.type===`event`&&typeof e.name==`string`&&e.payload&&typeof e.payload==`object`){if(e.name===`motion_telemetry`||e.name===`telemetry`){ee(e.payload);return}n(e.name,e.payload);return}}catch{}let i=await GC(r?.data,_);i&&oe(i)},e.onerror=()=>{},e.onclose=t=>{if(y===e&&(y=null,ie()),HC(t)){x=0;try{let e=r();typeof e==`string`&&e&&(v=e)}catch{}}ne()}},ce=g(re)??(()=>{});return se(),{setHandlers(e){_=e&&typeof e==`object`?e:{}},close(){S=!0,k(),ie();try{ce()}catch{}let e=y;y=null;try{e?.close()}catch{}}}}var qC={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},JC=Q.createContext&&Q.createContext(qC),YC=[`attr`,`size`,`title`];function XC(e,t){if(e==null)return{};var n,r,i=ZC(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function ZC(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function QC(){return QC=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},QC.apply(null,arguments)}function $C(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function ew(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?$C(Object(n),!0).forEach(function(t){tw(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$C(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function tw(e,t,n){return(t=nw(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function nw(e){var t=rw(e,`string`);return typeof t==`symbol`?t:t+``}function rw(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function iw(e){return e&&e.map((e,t)=>Q.createElement(e.tag,ew({key:t},e.attr),iw(e.child)))}function aw(e){return t=>Q.createElement(ow,QC({attr:ew({},e.attr)},t),iw(e.child))}function ow(e){var t=t=>{var n=e.attr,r=e.size,i=e.title,a=XC(e,YC),o=r||t.size||`1em`,s;return t.className&&(s=t.className),e.className&&(s=(s?s+` `:``)+e.className),Q.createElement(`svg`,QC({stroke:`currentColor`,fill:`currentColor`,strokeWidth:`0`},t.attr,n,a,{className:s,style:ew(ew({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:`http://www.w3.org/2000/svg`}),i&&Q.createElement(`title`,null,i),e.children)};return JC===void 0?t(qC):Q.createElement(JC.Consumer,null,e=>t(e))}function sw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`line`,attr:{x1:`18`,y1:`6`,x2:`6`,y2:`18`},child:[]},{tag:`line`,attr:{x1:`6`,y1:`6`,x2:`18`,y2:`18`},child:[]}]})(e)}function cw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`polygon`,attr:{points:`23 7 16 12 23 17 23 7`},child:[]},{tag:`rect`,attr:{x:`1`,y:`5`,width:`15`,height:`14`,rx:`2`,ry:`2`},child:[]}]})(e)}function lw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`},child:[]},{tag:`polyline`,attr:{points:`17 8 12 3 7 8`},child:[]},{tag:`line`,attr:{x1:`12`,y1:`3`,x2:`12`,y2:`15`},child:[]}]})(e)}function uw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`polyline`,attr:{points:`4 7 4 4 20 4 20 7`},child:[]},{tag:`line`,attr:{x1:`9`,y1:`20`,x2:`15`,y2:`20`},child:[]},{tag:`line`,attr:{x1:`12`,y1:`4`,x2:`12`,y2:`20`},child:[]}]})(e)}function dw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`polyline`,attr:{points:`23 4 23 10 17 10`},child:[]},{tag:`path`,attr:{d:`M20.49 15a9 9 0 1 1-2.12-9.36L23 10`},child:[]}]})(e)}function fw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`line`,attr:{x1:`12`,y1:`5`,x2:`12`,y2:`19`},child:[]},{tag:`line`,attr:{x1:`5`,y1:`12`,x2:`19`,y2:`12`},child:[]}]})(e)}function pw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`polygon`,attr:{points:`5 3 19 12 5 21 5 3`},child:[]}]})(e)}function mw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48`},child:[]}]})(e)}function hw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M9 18V5l12-2v13`},child:[]},{tag:`circle`,attr:{cx:`6`,cy:`18`,r:`3`},child:[]},{tag:`circle`,attr:{cx:`18`,cy:`16`,r:`3`},child:[]}]})(e)}function gw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`circle`,attr:{cx:`12`,cy:`12`,r:`1`},child:[]},{tag:`circle`,attr:{cx:`19`,cy:`12`,r:`1`},child:[]},{tag:`circle`,attr:{cx:`5`,cy:`12`,r:`1`},child:[]}]})(e)}function _w(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71`},child:[]},{tag:`path`,attr:{d:`M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71`},child:[]}]})(e)}function vw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`rect`,attr:{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`,ry:`2`},child:[]},{tag:`circle`,attr:{cx:`8.5`,cy:`8.5`,r:`1.5`},child:[]},{tag:`polyline`,attr:{points:`21 15 16 10 5 21`},child:[]}]})(e)}function yw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`rect`,attr:{x:`2`,y:`2`,width:`20`,height:`20`,rx:`2.18`,ry:`2.18`},child:[]},{tag:`line`,attr:{x1:`7`,y1:`2`,x2:`7`,y2:`22`},child:[]},{tag:`line`,attr:{x1:`17`,y1:`2`,x2:`17`,y2:`22`},child:[]},{tag:`line`,attr:{x1:`2`,y1:`12`,x2:`22`,y2:`12`},child:[]},{tag:`line`,attr:{x1:`2`,y1:`7`,x2:`7`,y2:`7`},child:[]},{tag:`line`,attr:{x1:`2`,y1:`17`,x2:`7`,y2:`17`},child:[]},{tag:`line`,attr:{x1:`17`,y1:`17`,x2:`22`,y2:`17`},child:[]},{tag:`line`,attr:{x1:`17`,y1:`7`,x2:`22`,y2:`7`},child:[]}]})(e)}function bw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`},child:[]},{tag:`polyline`,attr:{points:`14 2 14 8 20 8`},child:[]},{tag:`line`,attr:{x1:`16`,y1:`13`,x2:`8`,y2:`13`},child:[]},{tag:`line`,attr:{x1:`16`,y1:`17`,x2:`8`,y2:`17`},child:[]},{tag:`polyline`,attr:{points:`10 9 9 9 8 9`},child:[]}]})(e)}function xw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`},child:[]},{tag:`polyline`,attr:{points:`7 10 12 15 17 10`},child:[]},{tag:`line`,attr:{x1:`12`,y1:`15`,x2:`12`,y2:`3`},child:[]}]})(e)}function Sw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`rect`,attr:{x:`9`,y:`9`,width:`13`,height:`13`,rx:`2`,ry:`2`},child:[]},{tag:`path`,attr:{d:`M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1`},child:[]}]})(e)}function Cw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`polyline`,attr:{points:`16 18 22 12 16 6`},child:[]},{tag:`polyline`,attr:{points:`8 6 2 12 8 18`},child:[]}]})(e)}function ww(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`circle`,attr:{cx:`12`,cy:`12`,r:`10`},child:[]},{tag:`polyline`,attr:{points:`12 6 12 12 16 14`},child:[]}]})(e)}function Tw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`polyline`,attr:{points:`9 18 15 12 9 6`},child:[]}]})(e)}function Ew(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`polyline`,attr:{points:`20 6 9 17 4 12`},child:[]}]})(e)}function Dw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z`},child:[]},{tag:`polyline`,attr:{points:`3.27 6.96 12 12.01 20.73 6.96`},child:[]},{tag:`line`,attr:{x1:`12`,y1:`22.08`,x2:`12`,y2:`12`},child:[]}]})(e)}function Ow(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`line`,attr:{x1:`12`,y1:`19`,x2:`12`,y2:`5`},child:[]},{tag:`polyline`,attr:{points:`5 12 12 5 19 12`},child:[]}]})(e)}function kw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z`},child:[]},{tag:`line`,attr:{x1:`12`,y1:`9`,x2:`12`,y2:`13`},child:[]},{tag:`line`,attr:{x1:`12`,y1:`17`,x2:`12.01`,y2:`17`},child:[]}]})(e)}function Aw(e){return aw({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`polyline`,attr:{points:`22 12 18 12 15 21 9 3 6 12 2 12`},child:[]}]})(e)}function jw(e){let t=Array.from(e?.files??[]).find(e=>e.type.startsWith(`image/`));if(t)return t;for(let t of Array.from(e?.items??[]))if(t.kind===`file`&&t.type.startsWith(`image/`)){let e=t.getAsFile?.();if(e)return e}return null}async function Mw(e){let t=new Uint8Array(await e.arrayBuffer()),n=``;for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode.apply(null,t.subarray(e,e+32768));return`data:${e.type||`image/png`};base64,${btoa(n)}`}function Nw(e,t){return{fileName:e.name&&e.name!==`image.png`?e.name:`pasted-${new Date().toISOString().slice(0,19).replace(/[:T]/g,`-`)}.png`,mimeType:e.type||`image/png`,fileUrl:t,image_url:t,localPreview:!0,outputs:[{value:t}]}}function Pw(e,t){return jw(t)?!e||typeof e.matches!=`function`||!(e.isContentEditable||e.matches(`[contenteditable=true]`)):!1}var Fw=1600,Iw=4194304,Lw=.85,Rw=Object.freeze([`image/png`,`image/jpeg`,`image/webp`]),zw=`Up to 4 images per message`,Bw=`Attach a PNG, JPEG or WebP image`,Vw=`That image could not be attached`,Hw={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,webp:`image/webp`};function Uw(e){let t=String(e?.type??``).toLowerCase();return Rw.includes(t)?t:t?null:Hw[String(e?.name??``).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]]??null}function Ww(e){return Array.from(e?.types??[]).includes(`Files`)}function Gw(e){let t=Array.from(e?.files??[]);if(!t.length){let n=jw(e);n&&t.push(n)}let n=[],r=0;for(let e of t)Uw(e)?n.push(e):String(e?.type??``).startsWith(`image/`)&&(r+=1);return{images:n,unsupported:r}}function Kw(e){let t=String(e??``).slice(String(e??``).indexOf(`,`)+1);if(!t)return 0;let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return Math.max(0,Math.floor(t.length*3/4)-n)}function qw(e,t,n=Fw){let r=Math.max(e,t);if(!Number.isFinite(r)||r<=0)return null;if(r<=n)return{width:Math.round(e),height:Math.round(t),scaled:!1};let i=n/r;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i)),scaled:!0}}function Jw(e=[],t=[],n=4){let r=Math.max(0,n-e.length);return{attachments:[...e,...t.slice(0,r)],rejected:Math.max(0,t.length-r)}}var Yw=32768,Xw=e=>{let t=``;for(let n=0;n<e.length;n+=Yw)t+=String.fromCharCode.apply(null,e.subarray(n,n+Yw));return btoa(t)};async function Zw(e,t){let n=new Uint8Array(await e.arrayBuffer());return`data:${t||e.type||`image/jpeg`};base64,${Xw(n)}`}function Qw(e,t){if(typeof OffscreenCanvas==`function`)return new OffscreenCanvas(e,t);throw Error(`this browser cannot resize images — OffscreenCanvas is unavailable`)}function $w(e){let t=e.indexOf(`,`),n=e.slice(5,e.indexOf(`;`)),r=atob(e.slice(t+1)),i=new Uint8Array(r.length);for(let e=0;e<r.length;e+=1)i[e]=r.charCodeAt(e);return new Blob([i],{type:n})}async function eT(e,{decode:t=globalThis.createImageBitmap,makeCanvas:n=Qw,toBlob:r=$w,maxBytes:i=Iw,maxDimension:a=Fw,quality:o=Lw}={}){if(Kw(e)<=i)return e;if(typeof t!=`function`)throw Error(`this browser cannot decode images — createImageBitmap is unavailable`);let s=await t(r(e));try{let e=qw(s.width,s.height,a);if(!e)throw Error(`that image has no usable size`);let t=n(e.width,e.height),r=t.getContext(`2d`);if(!r)throw Error(`this browser cannot resize images — no 2D context`);return r.drawImage(s,0,0,e.width,e.height),await Zw(await t.convertToBlob({type:`image/jpeg`,quality:o}),`image/jpeg`)}finally{s?.close?.()}}function tT(e){let t=String(e?.name??``).trim();return!t||t===`image.png`?`pasted-image.png`:t.slice(0,120)}async function nT(e,t={}){let{readDataUrl:n=Mw,...r}=t,i=Uw(e)??`image/png`,a=await n(e);return{dataUrl:await eT(a.startsWith(`data:${i};`)?a:`data:${i};${a.slice(a.indexOf(`;`)+1)}`,r),name:tT(e)}}var rT=`cozyclay.workflow.agentPanel.width`,iT=1100,aT=`cozyclay.agent.session.studio`,oT=[`signed-out`,`signing-in`,`no-entitlement`,`ready`,`streaming`,`rate-limited`,`error`];function sT(e=globalThis.crypto){let t=e?.randomUUID?.();if(typeof t==`string`)return t;let n=new Uint8Array(16);e.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let r=[...n].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}var cT={queued:`Queued`,generating:`Generating`,preparing:`Preparing`,verifying:`Verifying`,repairing:`Repairing`,committing:`Installing`,reconciling:`Reconciling`,installed:`Installed`,review_required:`Needs review`,failed:`Failed`,cancelled:`Stopped`,stale_target:`Target changed`,stale_environment:`Scene changed`},lT=new Set([`installed`,`failed`,`cancelled`,`stale_target`,`stale_environment`]),uT=e=>lT.has(e),dT=e=>e===`installed`?`ok`:e===`review_required`?`warn`:uT(e)?`alert`:`busy`,fT=e=>Number.isFinite(e)?`${Math.round(e*100)}%`:``;function pT(e){if(e?.status===`installed`){let{installed:t,verification:n}=e,r=n.status===`verified`?`verified over ${n.evaluatedFrames} frames`:`installed unverified`;return`Installed ${t.durationSeconds}s of motion on ${t.characterId} — ${r}`}return e?.status===`undone`?`Undid ${e.undoneReceiptId}`:e?.status===`noop`?`Nothing to change`:e?.status===`transient`?`Changed the view only`:`Applied to ${e?.affectedIds?.join(`, `)||`the scene`}`}function mT(e){let t=Array.isArray(e?.efforts)?e.efforts:[];if(!t.length)return[];let n=e.defaultEffort&&t.includes(e.defaultEffort)?e.defaultEffort:t[0];return[n,...t.filter(e=>e!==n)]}var hT=[`Block a two-shot conversation in this scene`,`Render this frame as a storyboard panel`,`Suggest a camera move for the current shot`],gT=[Ix(`Block a two-shot`,`투샷 블로킹`),Ix(`Frame the selected character`,`선택한 캐릭터 구도 잡기`),Ix(`Light the set warmer`,`세트 조명 더 따뜻하게`)],_T=`Image generation uses about 3-5x a normal turn`,vT={describe_workflow:`Read canvas`,add_workflow_node:`Add node`,update_workflow_node:`Edit node`,remove_workflow_node:`Remove node`,connect_workflow_nodes:`Connect nodes`,disconnect_workflow_nodes:`Disconnect nodes`,run_workflow:`Run workflow`,set_workflow_node_output:`Set node output`,focus_workflow_node:`Focus node`,add_reference_node:`Add reference image`},yT={inspect_studio:Ix(`Read the scene`,`장면 읽기`),operate_studio:Ix(`Selection and view`,`선택과 뷰`),arrange_objects:Ix(`Arrange objects`,`오브젝트 배치`),arrange_characters:Ix(`Arrange characters`,`캐릭터 배치`),patch_elements:Ix(`Edit properties`,`속성 편집`),frame_shot:Ix(`Frame the shot`,`샷 구도 잡기`),generate_motion:Ix(`Generate motion`,`모션 생성`),verify_result:Ix(`Verify the result`,`결과 검증`),undo_edit:Ix(`Undo an edit`,`편집 되돌리기`),run_action:Ix(`Run an editor action`,`편집기 동작 실행`)},bT=Object.freeze({workflow:Object.freeze({toolLabels:vT,toolBadge:`Canvas`,suggestions:hT,imageHint:_T,imageEntitlement:!0,steer:!0,history:!0,persistWidth:!0,emptyTitle:`Direct the scene`,emptyHint:e=>`Ask for blocking, a camera move, or a rendered frame from \u201C${e}\u201D.`,composerPlaceholder:`Ask the agent to block, frame or render…`}),studio:Object.freeze({toolLabels:yT,toolBadge:Ix(`Scene`,`장면`),suggestions:gT,imageHint:null,imageEntitlement:!1,steer:!1,history:!0,persistWidth:!1,emptyTitle:Ix(`Direct the scene`,`장면을 연출하세요`),emptyHint:e=>Ix(`Ask for blocking, a camera move, or a motion take in \u201C${e}\u201D.`,`\u201C${e}\u201D\uC5D0\uC11C \uBE14\uB85C\uD0B9, \uCE74\uBA54\uB77C \uC6C0\uC9C1\uC784, \uBAA8\uC158 \uD14C\uC774\uD06C\uB97C \uC694\uCCAD\uD558\uC138\uC694.`),composerPlaceholder:Ix(`Ask the agent to block, frame or animate…`,`블로킹·구도·모션을 요청하세요…`)})});function xT(e){return Object.hasOwn(bT,e)?bT[e]:bT.workflow}function ST(e,t=vT){return Object.hasOwn(t,e?.name)?t[e.name]:PT(e)}function CT(e){let t=Number(e);return Number.isFinite(t)?Math.min(560,Math.max(300,Math.round(t))):360}function wT(e=globalThis.localStorage){try{let t=e?.getItem(rT);return t==null||t===``?360:CT(t)}catch{return 360}}function TT(e,t=globalThis.localStorage){try{t?.setItem(rT,String(CT(e)))}catch{}}var ET=`cozyclay.agent.model`;function DT(e=globalThis.localStorage){try{let t=e?.getItem(ET);return typeof t==`string`&&t?t:null}catch{return null}}function OT(e,t=globalThis.localStorage){try{typeof e==`string`&&e&&t?.setItem(ET,e)}catch{}}function kT(e,t=DT()){let n=Array.isArray(e)?e:[];return n.some(e=>e?.id===t)?t:n[0]?.id??``}function AT(e,t){if(!e.length)return!0;let n=e.find(e=>e.models?.some(e=>e.key===t));return!n||n.signedIn}function jT(e,t,n){return n&&t.some(e=>e.id===n)&&AT(e,n)?n:kT(t.filter(t=>AT(e,t.id)))}function MT(e,t=Date.now()){if(!e)return null;let n=typeof e==`number`?e:Date.parse(e);if(!Number.isFinite(n))return null;let r=Math.max(0,n-t),i=Math.round(r/1e3),a=Math.floor(i/3600),o=Math.floor(i%3600/60),s=i%60;return a>0?`${a}h ${String(o).padStart(2,`0`)}m`:o>0?`${o}m ${String(s).padStart(2,`0`)}s`:`${s}s`}var NT={capture_blocking_frame:{verb:`Capture`,target:`blocking frame`},render_from_frame:{verb:`Render`,target:`from frame`},place_image_in_scene:{verb:`Place`,target:`image in scene`}};function PT(e){if(e?.label)return e.label;let t=NT[e?.name];if(t)return`${t.verb} ${t.target}`;let n=String(e?.name||`tool`).split(/[_\-\s]+/).filter(Boolean);if(!n.length)return`Run tool`;let r=n[0][0].toUpperCase()+n[0].slice(1);return n.length>1?`${r} ${n.slice(1).join(` `)}`:r}function FT(e){return!Number.isFinite(e)||e<0?``:e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}var IT={STEER_UNSUPPORTED:`This surface cannot steer a running turn.`,NO_ACTIVE_TURN:`That turn already ended — send it as a new message.`},LT={auth:`Your session expired. Sign in again to continue.`,entitlement:`This account cannot generate images.`,rate_limit:`You have hit the usage limit for this window.`,upstream:`The model service failed to answer.`,overloaded:`The model service is overloaded right now. Try again in a moment.`},RT=`Ready`,zT={auth:`session expired`,entitlement:`not on this plan`,rate_limit:`usage limit reached`,rate_limited:`usage limit reached`,overloaded:`service overloaded`,no_output:`no response`};function BT(e){if(!e)return`unknown error`;let t=zT[e.code];if(t)return t;let n=String(e.message??``).trim();return n?n.length>64?`${n.slice(0,63)}…`:n:String(e.code||`unknown error`)}function VT(e){let t=Number.isFinite(e)&&e>0?Math.floor(e/1e3):0;return t<60?`${t} s`:`${Math.floor(t/60)} m ${String(t%60).padStart(2,`0`)} s`}var HT=(e,t,n)=>({phase:e,kind:`live`,tone:`busy`,text:`${t} · ${VT(n)}`,ticking:!0});function UT(e,{now:t=Date.now(),toolLabel:n=PT}={}){let r=e?.items??[],i=r.find(e=>e.kind===`image`&&e.apply?.status===`applying`);if(i)return HT(`editor`,`Waiting for the editor…`,t-(i.apply.startedAt??t));if(e?.streaming){let i=t-(e.turnStartedAt??t),a=r.findLast(e=>e.kind===`job`&&!uT(e.state));if(a){let e=fT(a.progress);return HT(`job`,`${cT[a.state]||a.state} motion${e?` ${e}`:``}`,i)}let o=r.findLast(e=>e.kind===`tool`&&e.status===`running`);return o?HT(`tool`,`Running ${n(o)}…`,i):r.findLastIndex(e=>e.kind===`user`)===r.length-1?HT(`sending`,`Sending…`,i):HT(`thinking`,`Thinking…`,i)}let a=e?.lastTurn;return a&&t-a.endedAt<6e3?a.status===`stopped`?{phase:`stopped`,kind:`terminal`,tone:`warn`,text:`Stopped`,ticking:!0}:a.status===`failed`?{phase:`failed`,kind:`terminal`,tone:`alert`,text:`Failed: ${BT(a.failure)}`,ticking:!0}:{phase:`done`,kind:`terminal`,tone:`ok`,text:`Done · ${VT(a.durationMs)}`,ticking:!0}:{phase:`idle`,kind:`idle`,tone:``,text:RT,ticking:!1}}function WT(e){let t=[],n=e.split(`
|
|
16
|
-
`),r=n.pop()??``;for(let e of n){let n=e.trim();if(!n.startsWith(`data:`))continue;let r=n.slice(5).trim();if(r)try{t.push(JSON.parse(r))}catch{}}return{events:t,tail:r}}var GT=``;function KT(e){return`${GT}${e}`}var qT=e=>typeof e==`string`&&/^[a-f0-9]{32}$/.test(e),JT=new Set([`aborted`,`auth`,`rate_limited`,`tool_failed`,`upstream`,`unknown`]),YT=(e,t)=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t)),XT=(e,t)=>{try{return e()}catch{return t}},ZT=e=>XT(()=>e?.status===401||e?.code===`auth`?`auth`:e?.status===429||e?.code===`rate_limit`?`rate_limited`:`upstream`,`upstream`),QT=new Set([`auth`,`entitlement`,`rate_limit`,`overloaded`,`upstream`]);async function $T(e){let t=Number.isFinite(e?.status)?e.status:null,n=null;try{let t=await e.clone().json();n=typeof t?.error==`string`?{message:t.error}:t?.error&&typeof t.error==`object`?t.error:null}catch{}let r=typeof n?.message==`string`?n.message.trim():``,i=r?t!==null&&r.startsWith(`${t} `)?r:`${t??`Upstream`} — ${r}`:`The turn was refused with HTTP ${t??`error`}.`;return{code:QT.has(n?.code)?n.code:t===429?`rate_limit`:t===401?`auth`:`upstream`,message:i,...t===null?{}:{status:t},...n?.resetAt?{resetAt:n.resetAt}:{}}}function eE({surface:e,capture:t,now:n,correlationId:r=null}){let i=XT(()=>{let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``)},null),a=()=>XT(()=>{let e=n();return Number.isFinite(e)?e:NaN},NaN),o=r??i,s=a(),c=XT(()=>[`studio`,`workflow`].includes(e)?e:/^\/workflow(?:\/|$)/.test(globalThis.location?.pathname||``)?`workflow`:`studio`,`studio`),u=!1,d=!1,f=new Map,h=new Set,g=(e,n)=>{if(i)try{Promise.resolve(t(e,n)).catch(()=>{})}catch{}},_=(e,t)=>{if(!u){if(u=!0,e===`cancelled`)for(let[e,t]of f)h.has(e)||g(`agent:tool_executed`,{turn_id:i,tool_category:t.category,outcome:`cancelled`,duration_bucket:p(a()-t.startedAt)});f.clear(),g(`agent:turn_${e}`,{turn_id:i,duration_bucket:p(a()-s),...e===`succeeded`?{}:{failure_code:t}})}};return g(`agent:turn_requested`,{surface:c,turn_id:i}),{turnId:i,cancel:()=>_(`cancelled`,`aborted`),fail:e=>_(`failed`,JT.has(e)?e:`upstream`),frame(e){try{if(!i||u)return;if(e.type===`execution_tool_started`){if(!YT(e,[`type`,`turn_id`,`telemetry_id`,`tool_category`])||e.turn_id!==o||!qT(e.telemetry_id)||!m.includes(e.tool_category))return;!f.has(e.telemetry_id)&&!h.has(e.telemetry_id)&&f.set(e.telemetry_id,{category:e.tool_category,startedAt:a()});return}let{event:t,props:n}=e;if(n?.turn_id!==o)return;if(t===`agent:tool_executed`){if(!YT(e,[`type`,`event`,`props`,`telemetry_id`])||!qT(e.telemetry_id)||!YT(n,[`turn_id`,`tool_category`,`outcome`,`duration_bucket`])||!m.includes(n.tool_category)||![`succeeded`,`failed`,`cancelled`].includes(n.outcome)||!l.duration_bucket.has(n.duration_bucket)||h.has(e.telemetry_id))return;h.add(e.telemetry_id),f.delete(e.telemetry_id),g(t,{turn_id:i,tool_category:n.tool_category,outcome:n.outcome,duration_bucket:n.duration_bucket});return}if(!YT(e,[`type`,`event`,`props`]))return;if(t===`agent:result_applied`){!d&&YT(n,[`turn_id`])&&(d=!0,g(t,{turn_id:i}));return}if(![`agent:turn_succeeded`,`agent:turn_failed`,`agent:turn_cancelled`].includes(t))return;let r=t.slice(11),s=Object.hasOwn(n,`failure_code`);if(!YT(n,[`turn_id`,`duration_bucket`,...s?[`failure_code`]:[]])||!l.duration_bucket.has(n.duration_bucket)||s&&(r===`succeeded`||!JT.has(n.failure_code)))return;_(r,r===`cancelled`?`aborted`:n.failure_code||`unknown`)}catch{}}}}var tE=3,nE={anthropic:[`ANTHROPIC_API_KEY`],openai:[`OPENAI_API_KEY`],google:[`GEMINI_API_KEY`,`GOOGLE_API_KEY`],openrouter:[`OPENROUTER_API_KEY`],cliproxy:[`CLIPROXY_API_KEY`]};function rE(e){let t=nE[e];return t?.length?t.join(` or `):`an environment variable`}function iE({fetchImpl:e=globalThis.fetch?.bind(globalThis),surface:t,capture:n=s,now:r=()=>performance.now()}={}){let i=new Map,a=async(t,n)=>{let r=await e(KT(t),{headers:{"content-type":`application/json`},...n});if(!r.ok){let e=null;try{e=await r.clone().json()}catch{}let n=typeof e?.error==`string`?e.error:e?.error?.message,i=Error(n||`${t} responded ${r.status}`);throw i.status=r.status,e?.error&&typeof e.error==`object`&&Object.assign(i,e.error),e?.preservation&&typeof e.preservation==`object`&&(i.preservation=e.preservation),i}return r.json()};return{mock:!1,async status(){return a(`/oauth/status`)},async signIn(){let e=await a(`/oauth/start`,{method:`POST`,body:`{}`});return e?.authorizeUrl&&globalThis.open?.(e.authorizeUrl,`_blank`,`noopener,noreferrer`),e},async signOut(){return a(`/oauth/logout`,{method:`POST`,body:`{}`})},async models(){let e=await a(`/agent/models`),t=Array.isArray(e?.models)?e.models:[];return{providers:Array.isArray(e?.providers)?e.providers.filter(e=>e?.id&&Array.isArray(e.models)):[],models:t}},async steer(e,t){return a(`/agent/turn/${encodeURIComponent(e)}/steer`,{method:`POST`,body:JSON.stringify(t)})},async providers(){let e=await a(`/agent/providers`);return Array.isArray(e?.providers)?e.providers:[]},async setProviderKey(e,t){return a(`/agent/providers/${encodeURIComponent(e)}`,{method:`PUT`,body:JSON.stringify({key:t})})},async removeProviderKey(e){return a(`/agent/providers/${encodeURIComponent(e)}`,{method:`DELETE`})},async listSessions(){let e=await a(`/agent/sessions?surface=${encodeURIComponent(t||`studio`)}`);return Array.isArray(e?.sessions)?e.sessions:[]},async loadSession(e){return a(`/agent/sessions/${encodeURIComponent(e)}`)},async stop(e){let t=typeof e==`string`||!e?{sessionId:e}:{surface:`studio`,sessionId:e.sessionId,turnId:e.turnId,...e.jobId?{jobId:e.jobId}:{}};return i.get(t.sessionId)?.cancel(),a(`/agent/stop`,{method:`POST`,body:JSON.stringify(t)})},async acceptJob({jobId:e,sessionId:t,turnId:n}){return a(`/agent/jobs/${encodeURIComponent(e)}/accept`,{method:`POST`,body:JSON.stringify({surface:`studio`,sessionId:t,turnId:n,explicitUnverifiedAcceptance:!0})})},async image({prompt:e,imageDataUrl:t,referenceDataUrl:n,references:r,quality:i=`auto`},o){return a(`/agent/image`,{method:`POST`,body:JSON.stringify({prompt:e,imageDataUrl:t,...n?{referenceDataUrl:n}:{},...Array.isArray(r)&&r.length?{references:r}:{},quality:i}),signal:o})},async video(e,t){return a(`/agent/video`,{method:`POST`,body:JSON.stringify(e),signal:t})},async videoProviders(){return a(`/agent/video/providers`)},async turn(a,o,s){let{sessionId:c,text:l,attachFrame:u,model:d,effort:f,attachments:p}=a,m=Array.isArray(p)&&p.length?{attachments:p}:{},h=a.surface===`studio`,g=h?a.turnId:null,_=eE({surface:t,capture:n,now:r,correlationId:g});a.onTurnId?.(h?g:_.turnId),i.set(c,_);let v=()=>{s.reason===`agent-stop`&&_.cancel()};s?.addEventListener(`abort`,v,{once:!0}),s?.aborted&&v();let y=!1,b,x=0,S=!1,C=e=>{if(e?.type===`execution_telemetry`||e?.type===`execution_tool_started`){_.frame(e);return}if(h&&Number.isFinite(e?.eventSeq)){if(e.eventSeq<=x)return;x=e.eventSeq}e?.type===`error`&&(b=ZT(e)),e?.type===`done`&&(S=!0),o(e)},w=async e=>{let t=e.body.getReader();y=!0;try{let e=new TextDecoder,n=``;for(;;){let{value:r,done:i}=await t.read();if(i)break;n+=e.decode(r,{stream:!0});let a=WT(n);n=a.tail;for(let e of a.events)C(e)}for(let e of WT(`${n}\n`).events)e?.type!==`execution_telemetry`&&e?.type!==`execution_tool_started`&&C(e)}finally{t.releaseLock()}},T=JSON.stringify(h?{surface:`studio`,sessionId:c,turnId:g,text:l,context:a.context,...d?{model:d}:{},...f?{effort:f}:{},...u===void 0?{}:{attachFrame:!!u},...m}:{sessionId:c,text:l,attachFrame:u,model:d,...f?{effort:f}:{},...m,..._.turnId?{turn_id:_.turnId}:{}});try{let t=await e(KT(`/agent/turn`),{method:`POST`,headers:{"content-type":`application/json`,accept:`text/event-stream`},body:T,signal:s});if(!t.ok||!t.body){_.fail(ZT(t)),o({type:`error`,...await $T(t)}),o({type:`done`});return}let n=null;try{await w(t)}catch(e){n=e}for(let t=0;h&&g&&!S&&!s?.aborted&&t<tE;t+=1){let t;try{t=await e(KT(`/agent/turn/${encodeURIComponent(g)}/events?after=${x}`),{headers:{accept:`text/event-stream`},signal:s})}catch{break}if(!t?.ok||!t.body)break;n=null;try{await w(t)}catch(e){n=e}}if(n)throw n;b&&_.fail(b)}catch(e){throw!s?.aborted&&(!y||b)&&_.fail(b||ZT(e)),e}finally{s?.removeEventListener(`abort`,v),i.get(c)===_&&i.delete(c)}}}}function aE(e=globalThis.location?.search||``){let t=new URLSearchParams(e);if(t.get(`agent`)!==`mock`)return null;let n=t.get(`state`);return{state:oT.includes(n)?n:`ready`,speed:Number(t.get(`speed`))||1}}var oE={signedIn:!0,email:`director@cozyclay.org`,plan:`Plus`,accountId:`acct_mock_126`,expiresAt:null},sE=[{delay:40,event:{type:`text.delta`,text:`Framing a wide two-shot from the current blocking. `}},{delay:120,event:{type:`text.delta`,text:`Capturing the viewport first.`}},{delay:120,event:{type:`tool.start`,callId:`call-1`,name:`capture_blocking_frame`,label:`Capture blocking frame`,args:{shot:`current`}}},{delay:260,event:{type:`tool.done`,callId:`call-1`,ok:!0,elapsedMs:268,result:{width:1280,height:720}}},{delay:90,event:{type:`tool.start`,callId:`call-2`,name:`render_from_frame`,label:`Render from frame`,args:{style:`storyboard`,strength:.6}}},{delay:420,event:{type:`tool.done`,callId:`call-2`,ok:!0,elapsedMs:1412,result:{imageId:`img-1`}}},{delay:80,event:{type:`image`,imageId:`img-1`,dataUrl:`data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22512%22%20height%3D%22288%22%20viewBox%3D%220%200%20512%20288%22%3E%3Cdefs%3E%3ClinearGradient%20id%3D%22g%22%20x1%3D%220%22%20y1%3D%220%22%20x2%3D%221%22%20y2%3D%221%22%3E%3Cstop%20offset%3D%220%22%20stop-color%3D%22%232a2f52%22%2F%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%235b3550%22%2F%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Crect%20width%3D%22512%22%20height%3D%22288%22%20fill%3D%22url(%23g)%22%2F%3E%3Ccircle%20cx%3D%22150%22%20cy%3D%22150%22%20r%3D%2252%22%20fill%3D%22%23ef759d%22%20opacity%3D%220.85%22%2F%3E%3Crect%20x%3D%22250%22%20y%3D%22112%22%20width%3D%22180%22%20height%3D%22112%22%20rx%3D%2210%22%20fill%3D%22%238994ff%22%20opacity%3D%220.8%22%2F%3E%3Crect%20y%3D%22240%22%20width%3D%22512%22%20height%3D%2248%22%20fill%3D%22%23101116%22%20opacity%3D%220.55%22%2F%3E%3Ctext%20x%3D%2224%22%20y%3D%22272%22%20font-family%3D%22Inter%2Csans-serif%22%20font-size%3D%2218%22%20fill%3D%22%23edf0fb%22%3Emock%20render%20%C2%B7%20wide%20two-shot%3C%2Ftext%3E%3C%2Fsvg%3E`,width:512,height:288,prompt:`wide two-shot, storyboard ink`}},{delay:60,event:{type:`quota`,plan:`Plus`,primary:{usedPercent:46,windowMinutes:300,resetAt:null},credits:{has:!0}}},{delay:40,event:{type:`done`}}],cE={ok:!0,commandId:`cmd-mock-1`,receiptId:`receipt-mock-1`,host:{workspaceId:`tab-mock`,documentEpoch:`doc-mock`,sceneId:`scene-mock`,sceneEpoch:`scene-open-mock`},status:`applied`,authored:!0,revision:{before:41,after:42},affectedIds:[`char-a`],delta:[{id:`char-a`,after:{position:{x:-.8,y:0,z:.4}}}],checks:{coverage:`affected-targets`},undo:{historyEntryId:`history-mock-1`,entries:1,canUndoDirect:!0},warnings:[]},lE=[{delay:40,event:{type:`text.delta`,text:`Reading the scene before I move anyone. `}},{delay:120,event:{type:`tool.start`,callId:`studio-1`,name:`inspect_studio`,label:`inspect studio`,args:{scope:`selection`}}},{delay:220,event:{type:`tool.done`,callId:`studio-1`,ok:!0,elapsedMs:214,result:{entities:2}}},{delay:90,event:{type:`text.delta`,text:`Blocking the two-shot now.`}},{delay:120,event:{type:`tool.start`,callId:`studio-2`,name:`arrange_characters`,label:`arrange characters`,args:{ops:[{op:`update`,characterId:`char-a`,position:{world:{x:-.8,y:0,z:.4}}}]}}},{delay:320,event:{type:`tool.done`,callId:`studio-2`,ok:!0,elapsedMs:332,result:{ok:!0,receiptId:cE.receiptId}}},{delay:60,event:{type:`receipt`,receipt:cE}},{delay:40,event:{type:`done`}}],uE=[[`openai-codex`,`ChatGPT (OpenAI Codex)`],[`anthropic`,`Anthropic`],[`openai`,`OpenAI`],[`google`,`Google Gemini`],[`openrouter`,`OpenRouter`],[`cliproxy`,`CLIProxyAPI`]],dE=`google`,fE={"openai-codex":[{id:`gpt-6-astra`,label:`gpt-6-astra`,efforts:[`none`,`low`,`medium`,`high`,`xhigh`],defaultEffort:`medium`},{id:`gpt-5.1-codex`,label:`gpt-5.1-codex`,efforts:[`low`,`medium`,`high`],defaultEffort:`medium`}],anthropic:[{id:`claude-sonnet-4-5`,label:`Claude Sonnet 4.5`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`medium`}],openai:[{id:`gpt-5.1`,label:`GPT-5.1`,efforts:[`none`,`low`,`medium`,`high`,`xhigh`],defaultEffort:`medium`}],google:[{id:`gemini-3-pro`,label:`Gemini 3 Pro`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`medium`}],openrouter:[{id:`deepseek-v3`,label:`DeepSeek V3`,efforts:[`none`],defaultEffort:`none`}],cliproxy:[{id:`claude-sonnet-5`,label:`Claude Sonnet 5`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`medium`}]},pE={id:`gpt-6-live-preview`,label:`gpt-6 live preview`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`high`},mE=`cozyclay.mock.agent.status-calls`,hE=`cozyclay.mock.agent.model-calls`,gE=e=>{try{globalThis.localStorage?.setItem(e,String(Number(globalThis.localStorage.getItem(e)||0)+1))}catch{}};function _E(e={state:`ready`}){let t=e?.state||`ready`,n=e?.surface===`studio`,r=e?.speed>0?e.speed:1,i=e=>new Promise(t=>setTimeout(t,Math.max(0,e/r))),a=new Set,o=t===`signed-out`?`out`:t===`signing-in`?`pending`:`in`,s=()=>uE.map(([e,t])=>{let n=e===`openai-codex`?o===`in`?`chatgpt`:null:e===dE?`env`:a.has(e)?`file`:null;return{id:e,label:t,authSource:n,signedIn:!!n}}),c=null,l=0;return{mock:!0,state:t,async status(){gE(mE);let e=s().filter(e=>e.id!==`openai-codex`&&e.signedIn).length;return o===`pending`?{signedIn:!1,pending:!0,email:null,plan:null,accountId:null,expiresAt:null,providersConfigured:a.size}:o===`out`?{signedIn:!1,email:null,plan:null,accountId:null,expiresAt:null,providersConfigured:a.size}:t===`no-entitlement`?{...oE,plan:`Free`,entitlements:{image:!1},providersConfigured:e}:{...oE,entitlements:{image:!0},providersConfigured:e}},async signIn(){return o=`in`,{ok:!0,authorizeUrl:`https://auth.example.invalid/mock`}},async signOut(){return o=`out`,{ok:!0}},async models(){gE(hE);let e=s().map(e=>{let t=fE[e.id]??[],n=e.id===`openai-codex`&&o===`in`?[...t,pE]:t;return{...e,models:n.map(t=>({...t,key:`${e.id}/${t.id}`,input:[`text`,`image`]}))}});return{providers:e,models:e.flatMap(e=>e.models.map(e=>({...e,id:e.key})))}},async providers(){return s()},async setProviderKey(e,t){if(e===`openai-codex`)throw Object.assign(Error(`Use ChatGPT sign-in for OpenAI Codex.`),{status:400});if(typeof t!=`string`||t.trim().length<8)throw Object.assign(Error(`That key was refused: it is too short.`),{status:400});return a.add(e),{ok:!0}},async removeProviderKey(e){return a.delete(e),{ok:!0}},async stop(){return c=null,{ok:!0}},async steer(e,t){if(n)throw Object.assign(Error(`409 — Steering a Studio turn is not supported.`),{status:409,code:`STEER_UNSUPPORTED`});if(!c||e!==c)throw Object.assign(Error(`409 — This turn already ended.`),{status:409,code:`NO_ACTIVE_TURN`});try{globalThis.localStorage?.setItem(`cozyclay.mock.agent.last-steer`,JSON.stringify({turnId:e,text:t?.text??null,attachments:t?.attachments?.length??0}))}catch{}return{ok:!0,queued:!0}},async acceptJob(){return{ok:!0}},async listSessions(){if(!n)return[];let e=[];try{for(let t=0;t<globalThis.localStorage.length;t+=1){let n=globalThis.localStorage.key(t);if(!n?.startsWith(`cozyclay.mock.agent.session.`))continue;let r=JSON.parse(globalThis.localStorage.getItem(n));r?.meta&&e.push(r.meta)}}catch{}return e.sort((e,t)=>Date.parse(t.updatedAt||0)-Date.parse(e.updatedAt||0)).slice(0,50)},async loadSession(e){try{let t=JSON.parse(globalThis.localStorage.getItem(`cozyclay.mock.agent.session.${e}`));if(t?.transcript)return t}catch{}throw Error(`Mock session not found.`)},async applyImage({requestId:e}){return{ok:!0,receiptId:`mock-${e}`}},async turn(e,r,a){let o=`mock-turn-${++l}`;c=o,e?.onTurnId?.(o);try{globalThis.localStorage?.setItem(`cozyclay.mock.agent.last-turn`,JSON.stringify({turnId:o,model:e?.model??null,effort:e?.effort??null,text:e?.text??null}))}catch{}try{n&&e?.sessionId&&globalThis.localStorage?.setItem(`cozyclay.mock.agent.last-turn-session`,e.sessionId)}catch{}let s=[],u=n&&e?.sessionId?`cozyclay.mock.agent.session.${e.sessionId}`:null;if(u){try{s=JSON.parse(globalThis.localStorage.getItem(u))?.transcript||[]}catch{s=[]}s.push({kind:`user`,text:e.text})}let d=t=>{if(u){if(t.type===`text.delta`){let e=s.at(-1);e?.kind===`assistant`?e.text+=t.text:s.push({kind:`assistant`,text:t.text})}else if(t.type===`tool.start`)s.push({kind:`tool`,name:t.name,label:t.label,ok:!0,elapsedMs:null,callId:t.callId});else if(t.type===`tool.done`){let e=[...s].reverse().find(e=>e.kind===`tool`&&e.callId===t.callId);e&&Object.assign(e,{ok:t.ok,elapsedMs:t.elapsedMs})}else t.type===`receipt`&&s.push({kind:`receipt`,receiptId:t.receipt?.receiptId,summary:t.receipt?.status===`applied`?`Applied to the scene`:`Receipt`});try{globalThis.localStorage.setItem(u,JSON.stringify({sessionId:e.sessionId,transcript:s,meta:{sessionId:e.sessionId,surface:`studio`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),sceneName:`Mock scene`,firstText:s.find(e=>e.kind===`user`)?.text||``}}))}catch{}}r(t)};if(t===`rate-limited`){d({type:`text.delta`,text:`Framing a wide two-shot from the current blocking.`}),d({type:`quota`,plan:`Plus`,primary:{usedPercent:100,windowMinutes:300,resetAt:new Date(Date.now()+252e4).toISOString()},credits:{has:!1}}),d({type:`error`,code:`rate_limit`,message:LT.rate_limit,resetAt:new Date(Date.now()+252e4).toISOString()}),d({type:`done`}),c=null;return}if(t===`error`){d({type:`text.delta`,text:n?`Reading the scene first.`:`Capturing the viewport first.`}),d(n?{type:`tool.start`,callId:`call-1`,name:`inspect_studio`,label:`inspect studio`,args:{scope:`selection`}}:{type:`tool.start`,callId:`call-1`,name:`capture_blocking_frame`,label:`Capture blocking frame`,args:{shot:`current`}}),d({type:`tool.done`,callId:`call-1`,ok:!1,elapsedMs:812,error:n?`The scene is not ready`:`Viewport is not ready`}),d({type:`error`,code:`upstream`,message:LT.upstream}),d({type:`done`}),c=null;return}for(let e of n?lE:sE){if(a?.aborted||(await i(e.delay),a?.aborted))break;d(e.event)}c=null,await i(240),a?.aborted&&d({type:`done`})}}}function vE(e={}){let t=e.mockConfig===void 0?aE():e.mockConfig;return t?_E({surface:e.surface,...t}):iE(e)}function yE(e){let t=e?.outcome;return t?.status===`already_applied`?null:t&&t.mutated===!1?{status:`not_applied`,code:t.code??`CANCELLED`,mutated:!1}:{status:`unknown`,code:t?.code??null,mutated:`unknown`}}function bE(e){return new Promise(t=>{let n=r=>{r.detail?.requestId===e.requestId&&(globalThis.removeEventListener(`cozyclay:agent-image-result`,n),t({ok:!!r.detail.ok,error:r.detail.error,receiptId:r.detail.receiptId}))};globalThis.addEventListener?.(`cozyclay:agent-image-result`,n),!(globalThis.dispatchEvent&&!globalThis.dispatchEvent(new CustomEvent(`cozyclay:agent-image`,{cancelable:!0,detail:e})))&&(globalThis.removeEventListener?.(`cozyclay:agent-image-result`,n),t({ok:!1,error:`No editor accepted the image. Open the scene that should receive it.`}))})}function xE({transport:e,surface:t=`workflow`,buildContext:n=null,requestImageAction:i=null,onAuthLost:o=null,onReceipt:s=null,newId:c=sT,clock:l=()=>Date.now()}={}){let u=t===`studio`,d=new Set,f=new Set,p=new Set,m=null,h=null,g=null,_={sessionId:c(),turnId:null,draft:``,pendingAttachments:[],items:[],streaming:!1,quota:null,rateLimit:null,lastPrompt:``,turnStartedAt:null,lastTurn:null},v=e=>{_={..._,...e};for(let e of[...d])e(_)},y=e=>v({items:e(_.items)}),b=(e,t)=>y(n=>n.map(n=>e(n)?{...n,...t}:n)),x=e=>_.items.find(t=>t.kind===`job`&&t.jobId===e);function S(e){if(!e?.jobId||!a.jobStates.includes(e.state))return;let t=typeof e.progress==`number`&&Number.isFinite(e.progress)?Math.min(1,Math.max(0,e.progress)):null;y(n=>{let r=n.find(t=>t.kind===`job`&&t.jobId===e.jobId),i={kind:`job`,id:r?.id??`job:${e.jobId}`,jobId:e.jobId,commandId:e.commandId??r?.commandId??null,state:e.state,phase:typeof e.phase==`string`?e.phase:r?.phase??null,progress:t??r?.progress??null,verification:r?.verification??null,receiptId:r?.receiptId??null,outcome:r?.outcome??null,acceptance:e.state===`review_required`?r?.acceptance??{status:`required`}:r?.acceptance??null};return r?n.map(e=>e===r?i:e):[...n,i]})}function C(e){let t;try{t=r(e)}catch(e){y(t=>[...t,{kind:`failure`,id:c(),failure:{code:e?.code||`INVALID_RECEIPT`,message:e?.message||`The host returned an unreadable receipt.`,preserved:{authoredState:`unknown`},recovery:{action:`inspect`}}}]);return}if(t.ok===!1){let e=`failure:${t.commandId}:${t.code}`;if(f.has(e))return;f.add(e),y(n=>[...n.map(e=>e.kind===`job`&&e.commandId===t.commandId&&!uT(e.state)?{...e,state:`failed`,phase:t.phase,acceptance:null}:e),{kind:`failure`,id:e,failure:t}]);return}if(!f.has(t.receiptId)){f.add(t.receiptId),y(e=>[...e.map(e=>e.kind===`job`&&e.jobId===t.jobId?{...e,state:t.status===`installed`?`installed`:e.state,verification:t.verification??null,receiptId:t.receiptId,acceptance:t.explicitUnverifiedAcceptance?{status:`accepted`}:null}:e),{kind:`receipt`,id:`receipt:${t.receiptId}`,receiptId:t.receiptId,receipt:t,summary:pT(t)}]);try{s?.(t)}catch{}}}function w(e){if(h&&[`text.delta`,`tool.start`,`tool.done`,`image`,`job.state`,`job.progress`,`receipt`,`error`].includes(e?.type)&&(h.produced=!0),e?.type===`text.delta`){y(t=>{let n=t[t.length-1];return n?.kind===`assistant`?[...t.slice(0,-1),{...n,text:n.text+e.text}]:[...t,{kind:`assistant`,id:c(),text:e.text}]});return}if(e?.type===`tool.start`){y(t=>[...t,{kind:`tool`,id:e.callId||c(),callId:e.callId,name:e.name,label:e.label,args:e.args,status:`running`}]);return}if(e?.type===`tool.done`){b(t=>t.kind===`tool`&&t.callId===e.callId,{status:e.ok?`done`:`failed`,elapsedMs:e.elapsedMs,result:e.result,error:e.error});let t=e.result;if(e.ok&&t&&typeof t==`object`&&t.ok===!0&&typeof t.receiptId==`string`&&Array.isArray(t.affectedIds))try{s?.(t)}catch{}return}if(e?.type===`image`){y(t=>[...t,{kind:`image`,id:e.imageId||c(),imageId:e.imageId,dataUrl:e.dataUrl,width:e.width,height:e.height,prompt:e.prompt,placed:!1,apply:null}]);return}if(e?.type===`job.state`||e?.type===`job.progress`){S(e);return}if(e?.type===`receipt`){C(e.receipt);return}if(e?.type===`quota`){v({quota:{plan:e.plan,usedPercent:e.primary?.usedPercent,windowMinutes:e.primary?.windowMinutes,resetAt:e.primary?.resetAt,credits:e.credits}});return}if(e?.type!==`error`)return;let t={code:e.code||`upstream`,message:e.message||LT[e.code]||`The turn failed.`,...Number.isFinite(e.status)?{status:e.status}:{}};if(h&&(h.failure=t),e.code===`rate_limit`){v({rateLimit:{resetAt:e.resetAt||null,message:e.message||LT.rate_limit}});return}if(e.code===`auth`){o?.();return}y(e=>{let n=e.findLastIndex(e=>e.kind===`user`),r=e.findLastIndex((e,t)=>t>n&&e.kind===`tool`&&e.status===`failed`);return r===-1?[...e,{kind:`failure`,id:c(),failure:{...t,recovery:{action:`retry`,retryAllowed:!0}}}]:e.map((e,n)=>n===r?{...e,failure:t}:e)})}function T(e,t,n){if(!e||p.has(e))return;p.add(e);let r=!!t?.ok,i={apply:{requestId:e,status:r?`settled`:`failed`,error:r?null:t?.error||`The editor did not apply the image.`,receiptId:t?.receiptId??null}};r&&(i.placed=n===`place`),b(t=>t.kind===`image`&&t.apply?.requestId===e,i)}async function E(e,t){let n=_.items.find(t=>t.kind===`image`&&t.id===e);if(!n||n.apply?.status===`applying`||(t===`place`?n.placed:!n.placed))return;let r=c();b(t=>t.kind===`image`&&t.id===e,{apply:{requestId:r,status:`applying`,error:null,receiptId:null,startedAt:l()}});let a={action:t,requestId:r,imageId:n.imageId,dataUrl:n.dataUrl,width:n.width,height:n.height,prompt:n.prompt};try{T(r,await(i??bE)(a),t)}catch(e){T(r,{ok:!1,error:String(e?.message||e)},t)}}let D=()=>{f.clear(),p.clear(),v({sessionId:c(),turnId:null,items:[],pendingAttachments:[],rateLimit:null,lastPrompt:``,turnStartedAt:null,lastTurn:null})};return{getState:()=>_,subscribe(e){return d.add(e),()=>d.delete(e)},setDraft:e=>v({draft:String(e??``)}),addAttachments(e){let t=(Array.isArray(e)?e:[]).filter(e=>typeof e?.dataUrl==`string`&&e.dataUrl.startsWith(`data:image/`)).map(e=>({id:c(),dataUrl:e.dataUrl,...e.name?{name:String(e.name).slice(0,120)}:{}})),{attachments:n,rejected:r}=Jw(_.pendingAttachments,t,4),i=n.length-_.pendingAttachments.length;return v({pendingAttachments:n}),{added:i,rejected:r}},removeAttachment:e=>v({pendingAttachments:_.pendingAttachments.filter(t=>t.id!==e)}),clearAttachments:()=>v({pendingAttachments:[]}),async send(t,r={}){let i=String(t??``).trim();if(!i||_.streaming)return;let a=c(),o=u?n?.()??null:null;if(u&&!o){w({type:`error`,code:`upstream`,message:`The editor is not ready to describe the scene yet.`});return}let s=l(),d={produced:!1,failure:null};h=d;let f=(Array.isArray(r.attachments)?r.attachments:_.pendingAttachments).slice(0,4).map(({dataUrl:e,name:t})=>({dataUrl:e,...t?{name:t}:{}}));v({lastPrompt:i,rateLimit:null,turnId:a,streaming:!0,draft:``,pendingAttachments:[],turnStartedAt:s,lastTurn:null,items:[..._.items,{kind:`user`,id:c(),text:i,attachFrame:!!r.attachFrame,attachments:f}]}),m=new AbortController;let p=m.signal;try{await e.turn({onTurnId:e=>{g=e},...u?{surface:`studio`,turnId:a,context:o}:{},sessionId:_.sessionId,text:i,...f.length?{attachments:f}:{},attachFrame:!!r.attachFrame,model:r.model,effort:r.effort??void 0},w,p)}catch(e){p.aborted||w({type:`error`,code:`upstream`,message:String(e?.message||e)})}finally{if(m?.signal===p&&(m=null),h===d){g=null,!d.produced&&!d.failure&&!p.aborted&&(d.failure={code:`no_output`,message:`The turn ended without a response.`,recovery:{action:`retry`,retryAllowed:!0}},y(e=>[...e,{kind:`failure`,id:c(),failure:d.failure}]));let e=l();h=null,v({streaming:!1,turnStartedAt:null,lastTurn:{status:p.aborted?`stopped`:d.failure?`failed`:`done`,endedAt:e,durationMs:e-s,failure:d.failure}})}}},async steer(t,n={}){let r=String(t??``).trim();if(!r)return{ok:!1,code:`EMPTY`,message:``};if(!_.streaming||!g||typeof e.steer!=`function`)return{ok:!1,code:`NO_ACTIVE_TURN`,message:IT.NO_ACTIVE_TURN};let i=(Array.isArray(n.attachments)?n.attachments:_.pendingAttachments).slice(0,4).map(({dataUrl:e,name:t})=>({dataUrl:e,...t?{name:t}:{}}));try{await e.steer(g,{text:r,...i.length?{attachments:i}:{}})}catch(e){let t=typeof e?.code==`string`?e.code:`upstream`;return{ok:!1,code:t,message:IT[t]||String(e?.message||e)}}return v({draft:``,pendingAttachments:[],items:[..._.items,{kind:`user`,id:c(),text:r,steered:!0,attachments:i}]}),{ok:!0,code:null,message:``}},stop(){let t=[..._.items].reverse().find(e=>e.kind===`job`&&!uT(e.state));m?.abort(`agent-stop`),m=null;let n=u?{sessionId:_.sessionId,turnId:_.turnId,...t?{jobId:t.jobId}:{}}:_.sessionId;if(Promise.resolve(e.stop?.(n)).then(e=>{if(!t)return;let n=yE(e);n&&(b(e=>e.kind===`job`&&e.jobId===t.jobId&&!uT(e.state),{state:n.status===`not_applied`?`cancelled`:`reconciling`,phase:null,outcome:n,acceptance:null}),b(e=>e.kind===`tool`&&e.status===`running`,{status:`cancelled`,result:n,elapsedMs:null}))}).catch(()=>{}),!_.streaming){v({streaming:!1});return}let r=l();v({streaming:!1,turnStartedAt:null,lastTurn:{status:`stopped`,endedAt:r,durationMs:r-(_.turnStartedAt??r),failure:null}})},async acceptJob(t){let n=x(t);if(!(!n||n.acceptance?.status!==`required`)){b(e=>e.kind===`job`&&e.jobId===t,{acceptance:{status:`accepting`}});try{let n=await e.acceptJob?.({jobId:t,sessionId:_.sessionId,turnId:_.turnId});n?.receipt?C(n.receipt):b(e=>e.kind===`job`&&e.jobId===t,{acceptance:{status:`required`,error:`The host did not acknowledge the acceptance.`}})}catch(e){b(e=>e.kind===`job`&&e.jobId===t,{acceptance:{status:`required`,error:String(e?.message||e)}})}}},applyImage:e=>E(e,`place`),undoImage:e=>E(e,`remove`),acknowledgeImageAction:({requestId:e,ok:t,error:n,receiptId:r})=>{let i=_.items.find(t=>t.kind===`image`&&t.apply?.requestId===e);T(e,{ok:t,error:n,receiptId:r},i?.placed?`remove`:`place`)},clearRateLimit:()=>v({rateLimit:null}),clearContext:D,newSession:D,restore:(e,t=_.sessionId)=>{f.clear(),p.clear();let n=new Set,r=(Array.isArray(e)?e:[]).flatMap(e=>{if(e?.kind===`user`||e?.kind===`assistant`){let t=Array.isArray(e.attachments)?e.attachments.filter(e=>typeof e?.dataUrl==`string`):[];return[{kind:e.kind,id:c(),text:String(e.text??``),...t.length?{attachments:t}:{}}]}return e?.kind===`tool`?[{kind:`tool`,id:c(),callId:c(),name:e.name||`tool`,label:e.label,ok:e.ok,elapsedMs:e.elapsedMs,status:e.ok===!1?`failed`:`done`}]:e?.kind===`receipt`?e.receiptId&&n.has(e.receiptId)?[]:(e.receiptId&&(n.add(e.receiptId),f.add(e.receiptId)),[{kind:`receipt`,id:`receipt:${e.receiptId||c()}`,receiptId:e.receiptId,summary:e.summary||`Receipt`,receipt:{status:`applied`,warnings:[],verification:{status:`verified`}}}]):e?.kind===`failure`?[{kind:`failure`,id:c(),failure:{code:e.code||`upstream`,message:String(e.message||`The turn failed.`),recovery:{action:`retry`,retryAllowed:!0}}}]:[]}),i=[...r].reverse().find(e=>e.kind===`user`)?.text||``;return v({sessionId:t,turnId:null,items:r,rateLimit:null,lastPrompt:i,turnStartedAt:null,lastTurn:null,streaming:!1}),r}}}function SE(e,t=Date.now()){let n=Date.parse(e||``);if(!Number.isFinite(n))return`just now`;let r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i}m ago`;let a=Math.floor(i/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function CE({tone:e,title:t}){return(0,$.jsx)(`span`,{className:`agent-status-dot ${e}`,title:t,"aria-hidden":`true`})}function wE({call:e,presentation:t,onRetry:n}){let r=e.status===`running`?`busy`:[`failed`,`cancelled`].includes(e.status)?`alert`:`ok`,i=Object.hasOwn(t.toolLabels,e.name),a=e.error?`error: ${e.error}`:JSON.stringify(e.result??e.args??{},null,2);return(0,$.jsxs)(`div`,{className:`agent-card agent-tool-card${e.status===`failed`?` failed`:``}`,"data-tool-status":e.status,"data-tool-name":e.name,children:[(0,$.jsxs)(`details`,{children:[(0,$.jsxs)(`summary`,{children:[(0,$.jsx)(CE,{tone:r,title:e.status}),(0,$.jsx)(`span`,{className:`agent-tool-label`,children:ST(e,t.toolLabels)}),i&&(0,$.jsx)(`span`,{className:`agent-tool-badge`,children:t.toolBadge}),(0,$.jsx)(`span`,{className:`agent-tool-elapsed`,children:e.status===`running`?`running…`:e.status===`cancelled`?e.result?.status===`not_applied`?`not applied`:`result unknown`:FT(e.elapsedMs)}),(0,$.jsx)(Tw,{size:12,"aria-hidden":`true`})]}),(0,$.jsx)(`pre`,{className:`agent-tool-detail`,children:a})]}),e.failure&&(0,$.jsxs)(`div`,{className:`agent-error`,role:`alert`,children:[(0,$.jsx)(`span`,{children:e.failure.message||LT[e.failure.code]||`The turn failed.`}),(0,$.jsxs)(`div`,{className:`agent-error-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-ghost-button agent-error-retry`,onClick:n,children:`Retry`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-ghost-button agent-error-details`,onClick:e=>{let t=e.currentTarget.closest(`.agent-tool-card`)?.querySelector(`details`);t&&(t.open=!t.open)},children:`Details`})]})]})]})}function TE({image:e,onUse:t,onUndo:n,onRegenerate:r,onOpen:i}){let a=e.apply?.status===`applying`,o=e.apply?.status===`failed`;return(0,$.jsxs)(`div`,{className:`agent-card agent-image-card`,"data-image-id":e.imageId,"data-placed":e.placed?`true`:`false`,"data-apply-status":e.apply?.status||`idle`,children:[(0,$.jsx)(`figure`,{children:(0,$.jsx)(`img`,{src:e.dataUrl,width:e.width,height:e.height,alt:e.prompt||`Generated image`,onClick:()=>i(e)})}),e.placed?(0,$.jsxs)(`div`,{className:`agent-placed`,children:[(0,$.jsx)(CE,{tone:`ok`}),`Placed`,(0,$.jsx)(`button`,{type:`button`,className:`agent-image-undo`,disabled:a,onClick:()=>n(e),children:a?`Removing…`:`Undo`})]}):(0,$.jsxs)(`div`,{className:`agent-image-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`primary agent-image-use`,disabled:a,onClick:()=>t(e),children:[(0,$.jsx)(vw,{size:11}),` `,a?`Applying…`:`Use in scene`]}),(0,$.jsxs)(`a`,{className:`agent-image-download`,role:`button`,href:e.dataUrl,download:`${e.imageId||`agent-image`}.png`,children:[(0,$.jsx)(xw,{size:11}),` Download`]}),(0,$.jsxs)(`button`,{type:`button`,className:`agent-image-regenerate`,onClick:()=>r(e),children:[(0,$.jsx)(dw,{size:11}),` Regenerate`]})]}),o&&(0,$.jsx)(`p`,{className:`agent-image-error`,role:`alert`,children:e.apply.error})]})}function EE({resetAt:e,onRetry:t,onSwitchModel:n}){let[r,i]=(0,Q.useState)(()=>Date.now());(0,Q.useEffect)(()=>{let e=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(e)},[]);let a=MT(e,r);return(0,$.jsxs)(`div`,{className:`agent-paused`,"data-agent-card":`rate-limited`,role:`status`,children:[(0,$.jsxs)(`div`,{className:`agent-paused-head`,children:[(0,$.jsx)(ww,{size:12,"aria-hidden":`true`}),` Paused — usage limit reached`,(0,$.jsx)(`span`,{className:`agent-paused-countdown`,children:a?`resets in ${a}`:`resets soon`})]}),(0,$.jsx)(`p`,{style:{margin:0},children:LT.rate_limit}),(0,$.jsxs)(`div`,{className:`agent-paused-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-paused-wait`,onClick:t,children:`Wait & retry`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-paused-switch`,onClick:n,children:`Switch model`})]})]})}function DE({job:e,onStop:t,onAccept:n}){let r=!uT(e.state),i=r&&Number.isFinite(e.progress)?Math.round(e.progress*100):null,a=e.state===`installed`?null:e.phase,o=e.state===`review_required`||e.verification?.status===`unverified`,s=e.verification?.limitations??[],c=e.state===`installed`&&o?`Installed with warnings`:cT[e.state]||e.state;return(0,$.jsxs)(`div`,{className:`agent-card agent-job-card`,"data-job-id":e.jobId,"data-job-state":e.state,children:[(0,$.jsxs)(`div`,{className:`agent-job-head`,children:[(0,$.jsx)(CE,{tone:dT(e.state),title:e.state}),(0,$.jsx)(`span`,{className:`agent-job-label`,children:c}),o&&(0,$.jsx)(`span`,{className:`agent-job-badge`,children:`Unverified`}),i!==null&&(0,$.jsx)(`span`,{className:`agent-job-progress`,children:fT(e.progress)})]}),a&&(0,$.jsx)(`p`,{className:`agent-job-phase`,children:a}),e.outcome?.status===`not_applied`&&(0,$.jsx)(`p`,{className:`agent-job-outcome`,children:`Not applied — scene unchanged.`}),e.outcome?.status===`unknown`&&(0,$.jsx)(`p`,{className:`agent-job-outcome`,children:`Stopped, but the result is unknown — reconcile before editing this target.`}),i!==null&&(0,$.jsx)(`div`,{className:`agent-job-bar`,role:`progressbar`,"aria-label":`Generation progress`,"aria-valuenow":i,"aria-valuemin":0,"aria-valuemax":100,children:(0,$.jsx)(`span`,{className:`agent-job-bar-fill`,style:{transform:`scaleX(${e.progress})`}})}),s.length>0&&(0,$.jsx)(`ul`,{className:`agent-job-limits`,children:s.map(e=>(0,$.jsx)(`li`,{children:e},e))}),(0,$.jsxs)(`div`,{className:`agent-job-actions`,children:[r&&e.state!==`review_required`&&(0,$.jsx)(`button`,{type:`button`,className:`agent-ghost-button agent-job-stop`,onClick:()=>t(e),children:`Stop`}),e.acceptance?.status===`required`&&(0,$.jsxs)(`button`,{type:`button`,className:`agent-ghost-button agent-job-accept`,onClick:()=>n(e),children:[(0,$.jsx)(kw,{size:11}),` Apply with warnings`]}),e.acceptance?.status===`accepting`&&(0,$.jsx)(`span`,{className:`agent-job-note`,children:`Applying…`}),e.acceptance?.status===`accepted`&&(0,$.jsxs)(`span`,{className:`agent-job-note`,children:[(0,$.jsx)(Ew,{size:11}),` Applied at your request`]}),e.acceptance?.error&&(0,$.jsx)(`span`,{className:`agent-job-note alert`,role:`alert`,children:e.acceptance.error})]})]})}function OE({item:e}){let{receipt:t={},summary:n}=e,r=t.verification?.status===`unverified`,i=t.verification?.limitations??[],a=t.warnings??[],o=t.status===`installed`&&r;return(0,$.jsxs)(`div`,{className:`agent-card agent-receipt-card`,"data-receipt-id":e.receiptId,"data-receipt-status":t.status,children:[(0,$.jsxs)(`div`,{className:`agent-receipt-head`,children:[(0,$.jsx)(CE,{tone:r?`warn`:`ok`,title:t.status}),o&&(0,$.jsx)(`span`,{className:`agent-job-label`,children:`Installed with warnings`}),(0,$.jsx)(`span`,{className:`agent-receipt-summary`,children:n})]}),(a.length>0||i.length>0)&&(0,$.jsxs)(`ul`,{className:`agent-receipt-notes`,children:[a.map(e=>(0,$.jsx)(`li`,{children:e.message||e.code},e.code)),i.map(e=>(0,$.jsx)(`li`,{children:e},e))]}),o&&(0,$.jsx)(`p`,{className:`agent-job-note`,children:`Undo with Cmd+Z or ask the agent.`})]})}var kE={none:`No recovery is available for this command.`,inspect:`Ask the agent to inspect the target before trying again.`,retry:`The same command can be retried.`,new_intent:`Tell the agent what to do with the changed target.`,reconcile:`The result is unknown; reconcile before changing this target.`,sign_in:`Sign in again to continue.`};function AE({failure:e,onRetry:t}){return(0,$.jsxs)(`div`,{className:`agent-card agent-failure-card`,"data-failure-code":e.code,role:`alert`,children:[(0,$.jsxs)(`div`,{className:`agent-failure-head`,children:[(0,$.jsx)(kw,{size:12,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`agent-failure-code`,children:e.code})]}),(0,$.jsx)(`p`,{className:`agent-failure-message`,children:e.message||`The command did not complete.`}),(0,$.jsxs)(`p`,{className:`agent-failure-recovery`,children:[kE[e.recovery?.action]||kE.none,e.preserved?.authoredState===`unchanged`?` Nothing in the scene changed.`:e.preserved?.authoredState===`unknown`?` Whether the scene changed is unknown.`:``]}),e.recovery?.retryAllowed&&(0,$.jsx)(`div`,{className:`agent-error-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`agent-ghost-button agent-error-retry`,onClick:t,children:`Retry`})})]})}function jE({provider:e,onSave:t,onRemove:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(``),l=e.authSource===`env`,u=e.authSource===`file`,d=`set by ${rE(e.id)}`,f=`agent-key-${e.id}`,p=async e=>{o(!0),c(``);try{await e(),i(``)}catch(e){c(e?.message||`The sidecar refused that key.`)}finally{o(!1)}};return(0,$.jsxs)(`div`,{className:`agent-key-row`,"data-provider":e.id,"data-provider-source":e.authSource||`none`,"data-provider-signed-in":e.signedIn?`true`:`false`,children:[(0,$.jsxs)(`div`,{className:`agent-key-head`,children:[(0,$.jsx)(CE,{tone:e.signedIn?`ok`:``,title:e.signedIn?`key configured`:`no key`}),(0,$.jsx)(`label`,{className:`agent-key-label`,htmlFor:f,children:e.label}),(0,$.jsx)(`span`,{className:`agent-key-source`,children:l?`environment`:u?`saved on this machine`:`no key`})]}),(0,$.jsxs)(`div`,{className:`agent-key-controls`,children:[(0,$.jsx)(`input`,{id:f,className:`agent-key-input`,type:`password`,autoComplete:`off`,spellCheck:`false`,"aria-label":`${e.label} API key`,placeholder:l?d:e.signedIn?`Replace key`:`Paste API key`,disabled:l||a,value:r,onChange:e=>{i(e.target.value),c(``)}}),(0,$.jsx)(`button`,{type:`button`,className:`agent-key-save`,disabled:l||a||!r.trim(),onClick:()=>p(()=>t(e.id,r)),children:`Save`}),u&&(0,$.jsx)(`button`,{type:`button`,className:`agent-ghost-button agent-key-remove`,disabled:a,onClick:()=>p(()=>n(e.id)),children:`Remove`})]}),s&&(0,$.jsx)(`p`,{className:`agent-key-error`,role:`alert`,children:s})]})}function ME({transport:e=null,sceneName:t=`CozyClay Scene`,defaultCollapsed:n=!1,onCollapsedChange:r=null,embedded:i=!1,hidden:a=!1,surface:o=`workflow`,buildContext:s=null,onImageAction:c=null,onI2vAction:l=null,onReceipt:u=null}){let d=(0,Q.useMemo)(()=>xT(o),[o]),f=(0,Q.useMemo)(()=>e||vE({surface:o}),[e,o]),p=f.mock?f.state:null,[m,h]=(0,Q.useState)(n),[g,_]=(0,Q.useState)(()=>d.persistWidth?wT():360),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(null),[w,T]=(0,Q.useState)(`loading`),[E,D]=(0,Q.useState)([]),[O,ee]=(0,Q.useState)([]),[k,te]=(0,Q.useState)(``),[ne,re]=(0,Q.useState)(`loading`),[ie,A]=(0,Q.useState)(null),j=(0,Q.useMemo)(()=>mT(E.find(e=>e.id===k)),[E,k]),M=(0,Q.useCallback)(e=>{te(e),A(null),OT(e)},[]),ae=(0,Q.useCallback)(e=>{let t=Array.isArray(e?.models)?e.models:[];if(!t.length)return!1;let n=Array.isArray(e?.providers)?e.providers:[];return ee(n),D(t),te(e=>jT(n,t,e)),re(`ready`),!0},[]),[oe,se]=(0,Q.useState)(!1),[ce,le]=(0,Q.useState)(null),[ue,de]=(0,Q.useState)(!1),[fe,pe]=(0,Q.useState)(null),[me,he]=(0,Q.useState)(()=>!i&&(globalThis.innerWidth||1440)<1100),[ge,_e]=(0,Q.useState)(!1),[ve,ye]=(0,Q.useState)(!1),[be,xe]=(0,Q.useState)([]),[Se,Ce]=(0,Q.useState)(`loading`),[we,Te]=(0,Q.useState)([]),[Ee,De]=(0,Q.useState)(``),[Oe,ke]=(0,Q.useState)(``),[Ae,je]=(0,Q.useState)(o!==`studio`),Me=(0,Q.useRef)(null),Ne=(0,Q.useRef)(null),Pe=(0,Q.useRef)(s);Pe.current=s;let Fe=(0,Q.useRef)(c);Fe.current=c;let Ie=(0,Q.useRef)(l);Ie.current=l;let Le=(0,Q.useRef)(u);Le.current=u;let N=(0,Q.useMemo)(()=>xE({transport:f,surface:o,buildContext:()=>Pe.current?.()??null,requestImageAction:e=>(Fe.current??f.applyImage?.bind(f)??bE)(e),onReceipt:e=>Le.current?.(e),onAuthLost:()=>T(`signed-out`)}),[o,f]),Re=(0,Q.useSyncExternalStore)(N.subscribe,N.getState,N.getState),{draft:ze,items:Be,pendingAttachments:Ve,quota:He,rateLimit:Ue,streaming:We}=Re;(0,Q.useEffect)(()=>{if(o!==`studio`){je(!0);return}let e=!1,t=null;try{t=globalThis.localStorage?.getItem(aT)}catch{}if(!t){je(!0);return}return(async()=>{try{let n=await f.loadSession(t);if(!Array.isArray(n?.transcript))throw Error(`missing transcript`);e||N.restore(n.transcript,n.sessionId||t)}catch{e||(N.newSession(),De(`Previous conversation could not be restored`))}finally{e||je(!0)}})(),()=>{e=!0}},[o,N,f]),(0,Q.useEffect)(()=>{if(!(o!==`studio`||!Ae))try{globalThis.localStorage?.setItem(aT,Re.sessionId)}catch{}},[Re.sessionId,Ae,o]);let[Ge,Ke]=(0,Q.useState)(()=>Date.now()),qe=k?UT(Re,{now:Ge,toolLabel:e=>ST(e,d.toolLabels)}):ne===`failed`?{phase:`no-model`,kind:`terminal`,tone:`alert`,text:`No model available — the agent service did not answer with one`,ticking:!1}:{phase:`models`,kind:`live`,tone:`busy`,text:`Loading models…`,ticking:!1};(0,Q.useEffect)(()=>{if(!qe.ticking)return;let e=setInterval(()=>Ke(Date.now()),500);return()=>clearInterval(e)},[qe.ticking]);let Je=(0,Q.useCallback)(e=>e?.signedIn||e?.providersConfigured>0?d.imageEntitlement&&e?.entitlements?.image===!1?`no-entitlement`:`ready`:e?.pending?`signing-in`:`signed-out`,[d]),Ye=(0,Q.useCallback)(async()=>{try{let e=await f.status();return C(e),T(Je(e)),e}catch{return T(`signed-out`),null}},[Je,f]),Xe=(0,Q.useCallback)(async()=>{try{let e=await f.providers?.();if(!Array.isArray(e))throw Error(`no provider list`);xe(e),Ce(`ready`)}catch{xe([]),Ce(`failed`)}},[f]),Ze=(0,Q.useCallback)(async()=>{let e=Ye();await Xe(),await e;try{ae(await f.models())}catch{}},[ae,Ye,Xe,f]);(0,Q.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await f.status();if(e)return;C(t),T(Je(t))}catch{e||T(`signed-out`)}try{let t=await f.models();if(e)return;if(!ae(t)){re(`failed`);return}}catch{e||re(`failed`)}})(),()=>{e=!0}},[ae,Je,f]),(0,Q.useEffect)(()=>{if(w!==`signing-in`)return;let e=()=>{document.visibilityState!==`hidden`&&Ze()};return window.addEventListener(`focus`,e),window.addEventListener(`cozyclay:agent-auth-return`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`cozyclay:agent-auth-return`,e),document.removeEventListener(`visibilitychange`,e)}},[w,Ze]),(0,Q.useEffect)(()=>{!p||w!==`ready`||!k||[`streaming`,`rate-limited`,`error`].includes(p)&&(Be.length||N.send(`Give me a wide two-shot of this scene`,{attachFrame:!1,model:k}))},[w,Be.length,p,k,N]),(0,Q.useEffect)(()=>{if(i)return;let e=()=>he((globalThis.innerWidth||1440)<iT);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[i]),(0,Q.useEffect)(()=>{if(i)return;let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`b`&&(e.preventDefault(),h(e=>!e))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]),(0,Q.useEffect)(()=>{if(i)return;let e=()=>h(e=>!e);return window.addEventListener(`cozyclay:agent-panel-toggle`,e),()=>window.removeEventListener(`cozyclay:agent-panel-toggle`,e)},[i]),(0,Q.useEffect)(()=>{i||r?.(m)},[m,i,r]),(0,Q.useEffect)(()=>{if(a){Me.current&&Me.current===document.activeElement&&Me.current.blur();return}m||Me.current?.focus()},[w,m,a]),(0,Q.useEffect)(()=>{let e=Ne.current;e&&(e.scrollTop=e.scrollHeight)},[Be,We]);let Qe=(0,Q.useCallback)(e=>{e.preventDefault(),y(!0);let t=e.clientX,n=g,r=e=>_(CT(n+(t-e.clientX))),i=e=>{y(!1),window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i),TT(CT(n+(t-e.clientX)))};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)},[g]),$e=(0,Q.useCallback)(e=>{_(t=>{let n=CT(t+e);return TT(n),n})},[]),et=(0,Q.useCallback)(async e=>{let t=[],n=0;for(let r of e)try{t.push(await nT(r))}catch{n+=1}let r=t.length?N.addAttachments(t).rejected:0;le(r?zw:n?Vw:null)},[N]),tt=(0,Q.useCallback)(e=>{let{images:t,unsupported:n}=Gw(e);return t.length?(et(t),!0):(n&&le(Bw),n>0)},[et]),nt=(0,Q.useCallback)(e=>{tt(e.clipboardData)&&e.preventDefault()},[tt]),rt=(0,Q.useCallback)(e=>{Ww(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`,de(!0))},[]),it=(0,Q.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||de(!1)},[]),at=(0,Q.useCallback)(e=>{de(!1),tt(e.dataTransfer)&&e.preventDefault()},[tt]),ot=(0,Q.useCallback)(e=>(le(null),ke(``),N.send(e,{attachFrame:oe,model:k,effort:ie??void 0})),[oe,ie,k,N]),st=(0,Q.useCallback)(()=>N.stop(),[N]),ct=(0,Q.useCallback)(async e=>{if(!String(e??``).trim())return;le(null),ke(``);let t=await N.steer(e);t.ok||ke(t.message||`The running turn did not take that message.`)},[N]),lt=(0,Q.useCallback)(async()=>{T(`signing-in`);try{await f.signIn(),await Ze()}catch{T(`signed-out`)}},[Ze,f]),ut=(0,Q.useCallback)(async()=>{x(!1),await f.signOut().catch(()=>{}),C(null),N.newSession(),await Ze()},[Ze,N,f]),dt=(0,Q.useCallback)(()=>{if(o===`studio`)try{globalThis.localStorage?.removeItem(aT)}catch{}N.newSession(),_e(!1),x(!1),Me.current?.focus()},[N,o]),ft=(0,Q.useCallback)(async()=>{if(o!==`studio`)return;let e=!ge;if(_e(e),e)try{Te(await f.listSessions())}catch{Te([])}},[ge,o,f]),pt=(0,Q.useCallback)(async e=>{try{let t=await f.loadSession(e);if(!Array.isArray(t?.transcript))throw Error(`missing transcript`);N.restore(t.transcript,t.sessionId||e),_e(!1),De(``)}catch{De(`Previous conversation could not be restored`)}},[N,f]),mt=(0,Q.useCallback)(()=>{x(!1);let e=!ve;ye(e),e&&(Ce(`loading`),Xe())},[ve,Xe]),ht=(0,Q.useCallback)(async(e,t)=>{await f.setProviderKey(e,t),await Ze()},[Ze,f]),gt=(0,Q.useCallback)(async e=>{await f.removeProviderKey(e),await Ze()},[Ze,f]),_t=(0,Q.useCallback)(()=>{N.clearContext(),x(!1)},[N]),vt=(0,Q.useCallback)(()=>{let e=E.filter(e=>AT(O,e.id)),t=e.length?e:E,n=t[(t.findIndex(e=>e.id===k)+1)%t.length];n&&M(n.id),N.clearRateLimit()},[M,k,O,E,N]),yt=(0,Q.useCallback)(e=>{if(e.key===`Escape`&&We){e.preventDefault(),st();return}if(e.key===`Enter`&&!e.shiftKey){if(e.preventDefault(),We){d.steer&&ct(ze);return}ot(ze)}},[ze,d,ot,ct,st,We]),bt=Ue?`rate-limited`:w===`ready`?We?`streaming`:Be.some(e=>e.kind===`tool`&&e.status===`failed`||e.kind===`failure`)?`error`:`ready`:w,xt={"signed-out":``,"signing-in":`busy`,"no-entitlement":`warn`,ready:`ok`,streaming:`busy`,"rate-limited":`warn`,error:`alert`}[bt]||``,St=MT(Ue?.resetAt||He?.resetAt),Ct=w===`ready`||w===`no-entitlement`,wt=bt===`rate-limited`||!k||!AT(O,k);return m&&!i?(0,$.jsxs)(`aside`,{className:`agent-panel collapsed`,"data-agent-state":bt,"data-agent-collapsed":`true`,"aria-label":`Agent panel, collapsed`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-rail-toggle`,onClick:()=>h(!1),"aria-label":`Expand agent panel`,title:`Expand agent panel (Cmd/Ctrl+B)`,children:(0,$.jsx)(Tw,{size:13,style:{transform:`rotate(180deg)`}})}),(0,$.jsx)(CE,{tone:xt,title:bt}),(0,$.jsx)(`span`,{className:`agent-rail-label`,children:`Agent`})]}):(0,$.jsxs)(`aside`,{className:`agent-panel${v?` resizing`:``}${me&&!i?` overlay`:``}${i?` embedded`:``}`,style:i?void 0:{width:`${g}px`},hidden:i&&a,"data-agent-state":bt,"data-agent-width":i?void 0:g,"data-agent-overlay":me&&!i?`true`:`false`,"data-agent-embedded":i?`true`:`false`,"aria-label":`Agent`,children:[!i&&(0,$.jsx)(`div`,{role:`separator`,"aria-label":`Resize agent panel`,"aria-orientation":`vertical`,"aria-valuenow":g,"aria-valuemin":300,"aria-valuemax":560,tabIndex:0,className:`agent-resize`,onPointerDown:Qe,onKeyDown:e=>{e.key===`ArrowLeft`&&(e.preventDefault(),$e(16)),e.key===`ArrowRight`&&(e.preventDefault(),$e(-16))}}),(0,$.jsxs)(`header`,{className:`agent-header`,children:[(0,$.jsx)(CE,{tone:xt,title:bt}),(0,$.jsx)(`h2`,{className:`agent-title`,children:`Agent`}),(0,$.jsx)(`span`,{className:`agent-header-spacer`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-icon-button agent-new`,"aria-label":`New conversation`,title:`New conversation`,onClick:dt,children:(0,$.jsx)(fw,{size:14,"aria-hidden":`true`})}),d.history&&(0,$.jsxs)(`span`,{className:`agent-history-wrap`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-icon-button agent-history`,"aria-label":`History`,title:`History`,"aria-haspopup":`listbox`,"aria-expanded":o===`studio`?ge:void 0,onClick:o===`studio`?ft:void 0,disabled:o!==`studio`,children:(0,$.jsx)(ww,{size:13,"aria-hidden":`true`})}),o===`studio`&&ge&&(0,$.jsx)(`div`,{className:`agent-history-popover`,role:`listbox`,"aria-label":`Agent history`,children:we.length?we.map(e=>(0,$.jsxs)(`button`,{type:`button`,role:`option`,className:`agent-history-item`,onClick:()=>pt(e.sessionId),children:[(0,$.jsx)(`span`,{className:`agent-history-time`,children:SE(e.updatedAt)}),(0,$.jsx)(`span`,{className:`agent-history-text`,children:e.firstText||`Untitled conversation`})]},e.sessionId)):(0,$.jsx)(`span`,{className:`agent-history-empty`,children:`No previous conversations`})})]}),(0,$.jsxs)(`span`,{className:`agent-overflow`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-icon-button agent-overflow-toggle`,"aria-haspopup":`menu`,"aria-expanded":b,"aria-label":`More agent actions`,onClick:()=>x(e=>!e),children:(0,$.jsx)(gw,{size:13})}),b&&(0,$.jsxs)(`div`,{className:`agent-menu`,role:`menu`,children:[S?.signedIn&&(0,$.jsxs)(`div`,{className:`agent-account`,role:`presentation`,children:[(0,$.jsx)(`span`,{className:`agent-account-email`,children:S.email}),(0,$.jsx)(`span`,{className:`agent-plan-badge`,children:He?.plan||S.plan||`Free`}),St&&(0,$.jsxs)(`span`,{className:`agent-account-reset`,children:[`resets in `,St]})]}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,onClick:_t,children:`Clear context`}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:`agent-menu-keys`,"aria-expanded":ve,onClick:mt,children:`Provider keys…`}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,onClick:ut,children:`Sign out`})]})]}),!i&&(0,$.jsx)(`button`,{type:`button`,className:`agent-icon-button agent-collapse`,onClick:()=>h(!0),"aria-label":`Collapse agent panel`,title:`Collapse agent panel (Cmd/Ctrl+B)`,children:(0,$.jsx)(Tw,{size:13})})]}),Ee&&(0,$.jsx)(`div`,{className:`agent-toast`,role:`status`,children:Ee}),Oe&&(0,$.jsx)(`div`,{className:`agent-toast alert agent-steer-notice`,role:`alert`,children:Oe}),ve&&(0,$.jsxs)(`section`,{className:`agent-keys`,"aria-label":`Provider keys`,"data-agent-keys":`true`,children:[(0,$.jsxs)(`div`,{className:`agent-keys-head`,children:[(0,$.jsx)(`h3`,{className:`agent-keys-title`,children:`Provider keys`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-icon-button agent-keys-close`,"aria-label":`Close provider keys`,onClick:()=>ye(!1),children:(0,$.jsx)(sw,{size:11,"aria-hidden":`true`})})]}),(0,$.jsx)(`p`,{className:`agent-keys-hint`,children:`Keys are stored by the local CozyClay service and are never shown again.`}),Se===`loading`&&(0,$.jsx)(`p`,{className:`agent-keys-note`,children:`Loading providers…`}),Se===`failed`&&(0,$.jsx)(`p`,{className:`agent-keys-note alert`,role:`alert`,children:`The provider list is unavailable.`}),be.filter(e=>e.id!==`openai-codex`).map(e=>(0,$.jsx)(jE,{provider:e,onSave:ht,onRemove:gt},e.id))]}),(0,$.jsxs)(`div`,{className:`agent-transcript`,ref:Ne,"aria-live":`polite`,"aria-label":`Conversation`,"data-agent-transcript":`true`,children:[w===`signed-out`&&(0,$.jsxs)(`div`,{className:`agent-state-card`,"data-agent-card":`signed-out`,children:[(0,$.jsx)(`h3`,{children:`Sign in with ChatGPT`}),(0,$.jsx)(`p`,{children:`The agent runs against your ChatGPT plan. Sign-in happens in your browser — no token is ever stored in this page.`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-primary-button agent-signin`,onClick:lt,children:`Sign in with ChatGPT`})]}),w===`signing-in`&&(0,$.jsxs)(`div`,{className:`agent-state-card`,"data-agent-card":`signing-in`,children:[(0,$.jsx)(`span`,{className:`agent-spinner`,"aria-hidden":`true`}),(0,$.jsx)(`h3`,{children:`Waiting for your browser…`}),(0,$.jsx)(`p`,{children:`Finish the ChatGPT sign-in in the tab that just opened. This panel picks up the session when you come back.`})]}),w===`no-entitlement`&&(0,$.jsxs)(`div`,{className:`agent-state-card`,"data-agent-card":`no-entitlement`,children:[(0,$.jsx)(`h3`,{children:`Image generation is not on this plan`}),(0,$.jsxs)(`p`,{children:[`Signed in as `,S?.email||`your account`,`. Chat and tool calls work; image results need a plan with image generation.`]}),(0,$.jsx)(`button`,{type:`button`,className:`agent-primary-button`,onClick:()=>window.open(`https://chatgpt.com/#pricing`,`_blank`,`noopener,noreferrer`),children:`See plans`})]}),w===`ready`&&!Be.length&&!Ue&&(0,$.jsxs)(`div`,{className:`agent-state-card`,"data-agent-card":`ready`,children:[(0,$.jsx)(`h3`,{children:d.emptyTitle}),(0,$.jsx)(`p`,{children:d.emptyHint(t)}),(0,$.jsx)(`div`,{className:`agent-suggestions`,children:d.suggestions.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`agent-chip`,onClick:()=>{N.setDraft(e),Me.current?.focus()},children:e},e))})]}),Be.map(e=>e.kind===`user`?(0,$.jsxs)(`div`,{className:`agent-row user`,children:[e.attachments?.length>0&&(0,$.jsx)(`div`,{className:`agent-bubble-attachments`,children:e.attachments.map((t,n)=>(0,$.jsx)(`img`,{src:t.dataUrl,alt:t.name||`Attached image`,onClick:()=>pe({dataUrl:t.dataUrl,prompt:t.name})},`${e.id}-${n}`))}),(0,$.jsx)(`div`,{className:`agent-bubble`,children:e.text})]},e.id):e.kind===`assistant`?(0,$.jsx)(`div`,{className:`agent-row assistant`,children:(0,$.jsxs)(`div`,{className:`agent-assistant-text`,children:[e.text,We&&(0,$.jsx)(`span`,{className:`agent-caret`,children:`▌`})]})},e.id):e.kind===`tool`?(0,$.jsx)(`div`,{className:`agent-row`,children:(0,$.jsx)(wE,{call:e,presentation:d,onRetry:()=>ot(Re.lastPrompt)})},e.id):e.kind===`job`?(0,$.jsx)(`div`,{className:`agent-row`,children:(0,$.jsx)(DE,{job:e,onStop:st,onAccept:e=>N.acceptJob(e.jobId)})},e.id):e.kind===`receipt`?(0,$.jsx)(`div`,{className:`agent-row`,children:(0,$.jsx)(OE,{item:e})},e.id):e.kind===`failure`?(0,$.jsx)(`div`,{className:`agent-row`,children:(0,$.jsx)(AE,{failure:e.failure,onRetry:()=>ot(Re.lastPrompt)})},e.id):(0,$.jsx)(`div`,{className:`agent-row`,children:(0,$.jsx)(TE,{image:e,onUse:e=>N.applyImage(e.id),onUndo:e=>N.undoImage(e.id),onRegenerate:()=>ot(Re.lastPrompt),onOpen:pe})},e.id)),Ue&&(0,$.jsx)(EE,{resetAt:Ue.resetAt,onRetry:()=>{N.clearRateLimit(),ot(Re.lastPrompt)},onSwitchModel:vt})]}),Ct&&(0,$.jsxs)(`div`,{className:`agent-activity`,"data-agent-activity":qe.phase,"data-agent-activity-kind":qe.kind,role:`status`,"aria-live":`polite`,children:[(0,$.jsx)(`span`,{className:`agent-activity-indicator ${qe.tone}`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`agent-activity-text`,children:qe.text})]}),Ct&&(0,$.jsxs)(`div`,{className:`agent-composer`,"data-agent-dropping":ue?`true`:`false`,onDragOver:wt?void 0:rt,onDragLeave:wt?void 0:it,onDrop:wt?void 0:at,children:[Ve.length>0&&(0,$.jsx)(`ul`,{className:`agent-attachments`,"aria-label":`Attached images`,children:Ve.map(e=>(0,$.jsxs)(`li`,{className:`agent-attachment`,children:[(0,$.jsx)(`img`,{src:e.dataUrl,alt:e.name||`Attached image`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-attachment-remove`,"aria-label":`Remove ${e.name||`attached image`}`,onClick:()=>N.removeAttachment(e.id),children:(0,$.jsx)(sw,{size:10,"aria-hidden":`true`})})]},e.id))}),ce&&(0,$.jsx)(`p`,{className:`agent-attachment-notice`,role:`status`,children:ce}),(0,$.jsxs)(`div`,{className:`agent-field`,children:[(0,$.jsx)(`textarea`,{ref:Me,className:`agent-input`,"aria-label":`Message the agent`,placeholder:bt===`rate-limited`?`Composer is paused`:k?d.composerPlaceholder:`Waiting for the model list…`,value:ze,disabled:wt,onChange:e=>N.setDraft(e.target.value),onKeyDown:yt,onPaste:nt,onDragOver:rt,onDrop:at}),(0,$.jsxs)(`div`,{className:`agent-composer-controls`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-attach-chip`,"aria-pressed":oe,"aria-label":`Attach current frame`,title:`Attach current frame`,onClick:()=>se(e=>!e),children:oe?(0,$.jsx)(`span`,{className:`agent-attach-thumb`,"aria-hidden":`true`}):(0,$.jsx)(mw,{size:13,"aria-hidden":`true`})}),(0,$.jsx)(`select`,{className:`agent-model-select`,"aria-label":`Model`,title:`Model`,value:k,disabled:!E.length,onChange:e=>M(e.target.value),children:O.length?O.map(e=>(0,$.jsx)(`optgroup`,{label:e.label,children:e.models.length?e.models.map(t=>(0,$.jsx)(`option`,{value:t.key,disabled:!e.signedIn,children:e.signedIn?t.label:`${t.label} — add key`},t.key)):(0,$.jsx)(`option`,{value:`${e.id}/`,disabled:!0,children:e.signedIn?`No models`:`No models — add key`})},e.id)):E.length?E.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id)):(0,$.jsx)(`option`,{value:``,children:ne===`failed`?`No model available`:`Loading models…`})}),j.length>0&&(0,$.jsx)(`select`,{className:`agent-model-select agent-effort-select`,"aria-label":`Reasoning effort`,title:`Reasoning effort`,value:ie??j[0],onChange:e=>A(e.target.value),children:j.map((e,t)=>(0,$.jsx)(`option`,{value:e,title:t===0?`Default for this model`:void 0,children:e},e))}),(0,$.jsx)(`span`,{className:`agent-composer-spacer`,"aria-hidden":`true`}),o===`studio`&&Ie.current&&(0,$.jsx)(`button`,{type:`button`,className:`agent-attach-chip agent-i2v-action`,"data-testid":`i2v-agent-action`,"aria-label":`Generate motion`,title:`Generate motion from this message`,disabled:wt||!ze.trim()||We,onClick:()=>{let e=ze.trim();N.setDraft(``),Ie.current?.(e)},children:(0,$.jsx)(yw,{size:13,"aria-hidden":`true`})}),We?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-send stop agent-stop`,onClick:st,children:`Stop`}),d.steer&&(0,$.jsx)(`button`,{type:`button`,className:`agent-send agent-steer`,disabled:!ze.trim(),onClick:()=>ct(ze),children:`Steer`})]}):(0,$.jsx)(`button`,{type:`button`,className:`agent-send`,"aria-label":`Send`,title:`Send (Enter)`,disabled:wt||!ze.trim(),onClick:()=>ot(ze),children:(0,$.jsx)(Ow,{size:14,"aria-hidden":`true`})})]})]})]}),Ct&&d.imageHint&&(0,$.jsx)(`p`,{className:`agent-footer-hint`,children:d.imageHint}),fe&&(0,$.jsx)(`button`,{type:`button`,className:`agent-lightbox`,"aria-label":`Close image preview`,onClick:()=>pe(null),children:(0,$.jsx)(`img`,{src:fe.dataUrl,alt:fe.prompt||`Generated image`})})]})}var NE=`cozyclay:scene-change`,PE=`cozyclay.scene-playback.v1`,FE=`cozyclay:scene-playback`;function IE(e,t){return!e||typeof e!=`object`?!1:[e.assetId,e.sourceAssetId,e.matteAssetId].includes(t)}function LE(e,t,{height:n=kg,placement:r={},name:i=t?.name}={}){if(!t||!Kp(t.id))return{document:e,object:null,changed:!1,reason:`invalid-asset`};let a=e&&typeof e==`object`?e:wx(),o=Array.isArray(a.scenes)?a.scenes:[],s=Cx(o,a.activeSceneId);if(s<0||!o[s])return{document:a,object:null,changed:!1,reason:`no-active-scene`};let c=o[s],l=Array.isArray(c.objects)?c.objects:[];if(l.some(e=>IE(e,t.id)))return{document:a,object:null,changed:!1,reason:`already-in-scene`};let u=Jg({assetId:t.id,aspect:$p(t)??1,height:n,name:i},l,r);if(!u)return{document:a,object:null,changed:!1,reason:`cutout-failed`};let d=o.map((e,t)=>t===s?{...e,objects:[...l,u]}:e);return{document:{...a,version:Number.isInteger(a.version)?a.version:4,scenes:d},object:u,changed:!0,reason:`added`}}function RE(e,t,n={}){if(typeof t!=`string`||!t.trim()||!n||typeof n!=`object`)return{document:e,changed:!1,reason:`invalid-motion`};let r=e&&typeof e==`object`?e:wx(),i=Array.isArray(r.scenes)?r.scenes:[],a=Cx(i,r.activeSceneId);if(a<0||!i[a])return{document:r,changed:!1,reason:`no-active-scene`};let o=i[a],s=o.stage&&typeof o.stage==`object`?o.stage:{},c=Array.isArray(s.characters)?s.characters:[],l=c.find(e=>e?.id===t);if(!l)return{document:r,changed:!1,reason:`character-not-found`};let u=typeof n.url==`string`&&n.url?n.url:typeof n.objectUrl==`string`&&n.objectUrl?n.objectUrl:null;if(!u)return{document:r,changed:!1,reason:`motion-url-missing`};let d={...l.motionRef&&typeof l.motionRef==`object`?l.motionRef:{},...n.motionRef&&typeof n.motionRef==`object`?n.motionRef:{},url:u},f=c.map(e=>e?.id===t?{...e,motionRef:d}:e),p={...o,stage:{...s,characters:f}};return{document:{...r,scenes:i.map((e,t)=>t===a?p:e)},changed:!0,reason:`updated`,characterId:t,motionRef:d}}function zE(e,t,n={}){let r=RE(n.document??BE(n.storage),e,t);return r.changed&&VE(r.document,n),r}function BE(e=globalThis.localStorage){return Ox(e?.getItem?.(`cozyclay.scenes.v4`)??null).document}function VE(e,{storage:t=globalThis.localStorage,target:n=globalThis}={}){let r=e&&typeof e==`object`?e:wx(),i=kx(r);try{t?.setItem?.(Rb,i)}catch{}try{n?.dispatchEvent?.(new CustomEvent(NE,{detail:r}))}catch{}return r}function HE(e,{storage:t=globalThis.localStorage,target:n=globalThis}={}){if(typeof e!=`function`)return()=>{};let r=t=>{let n=t?.detail;n&&typeof n==`object`&&e(n,{source:`same-tab`})},i=t=>{if(t?.key!==`cozyclay.scenes.v4`||!t.newValue)return;let n=Ox(t.newValue);n.status===`corrupt`||n.status===`future`||!n.document||e(n.document,{source:`storage`})};return n?.addEventListener?.(NE,r),n?.addEventListener?.(`storage`,i),()=>{n?.removeEventListener?.(NE,r),n?.removeEventListener?.(`storage`,i)}}function UE(e,{storage:t=globalThis.localStorage,target:n=globalThis}={}){let r={activeSceneId:typeof e?.activeSceneId==`string`?e.activeSceneId:null,frame:Number.isFinite(Number(e?.frame))?Math.max(0,Math.round(Number(e.frame))):null,playing:typeof e?.playing==`boolean`&&e.playing,issuedAt:Date.now()};try{t?.setItem?.(PE,JSON.stringify(r))}catch{}try{n?.dispatchEvent?.(new CustomEvent(FE,{detail:r}))}catch{}return r}function WE(e,{storage:t=globalThis.localStorage,target:n=globalThis}={}){if(typeof e!=`function`)return()=>{};let r=t=>{try{let n=typeof t==`string`?JSON.parse(t):t;n&&typeof n==`object`&&e(n)}catch{}},i=e=>r(e?.detail),a=e=>{e?.key===`cozyclay.scene-playback.v1`&&e.newValue&&r(e.newValue)};return n?.addEventListener?.(FE,i),n?.addEventListener?.(`storage`,a),()=>{n?.removeEventListener?.(FE,i),n?.removeEventListener?.(`storage`,a)}}async function GE(e,{importer:t=am,remember:n=hC,importOptions:r}={}){return n(await t(e,{maxDimension:zp,...r||{}}))}async function KE(e,t={}){let n=await GE(e,t),r=LE(t.document??BE(t.storage),n,t);return r.changed&&VE(r.document,t),{...r,asset:n}}var qE=`follow the reference clip's framing and camera motion exactly`,JE=`clay previs, neutral look`,YE=`motion and blocking come from the reference; keep timing`;function XE(e){if(!Number.isFinite(e)||e<=0)return`normal`;let t=18/Math.tan(e*Math.PI/360);return t<=20?`wide`:t<=40?`normal`:`long`}function ZE(e){return`${Number(e.toFixed(2))}s`}function QE(e){let t=[];return e?.dolly&&t.push(`smooth dolly move`),e?.crane&&t.push(`gentle crane move`),e?.rail&&t.push(`sliding rail move`),t.length>0?t.join(`; `):`locked-off camera, no move`}var $E=[`front`,`front right`,`right`,`back right`,`back`,`back left`,`left`,`front left`];function eD(e){if(!Number.isFinite(e))return``;let t=(e%360+360)%360;return $E[Math.round(t/45)%8]}function tD(e){return Number.isFinite(e)?e>=50?`high`:e<=10?`low`:`level`:``}function nD(e){return Number.isFinite(e)?e>=.8?`strong`:e>=.35?`moderate`:`dim`:`moderate`}function rD(e){return e?`${[tD(e.elevationDeg),eD(e.azimuthDeg)].filter(Boolean).join(` `)||`even`} key light, ${nD(e.intensity)}`:`no key light, ambient fill`}function iD(e,t={}){let n=t.target===`video`?`video`:`image`,r=t.referenceOwnsCamera!==!1,i=Math.max(0,(e.frameRange?.end??0)-(e.frameRange?.start??0)+1)/(e.fps||24),a=typeof e.intent==`string`?e.intent.trim():``,o=[`SHOT: ${e.shotTitle||`untitled shot`}, ${ZE(i)}, ${e.aspect||``}`.trimEnd(),`LENS: ${e.focalMm}mm, ${XE(e.fovDeg)} shot`,r?`CAMERA: ${qE}`:`CAMERA: ${QE(e.cameraMove)}`,`LIGHT: ${rD(e.keyLight)}`,`CAST: ${(e.cast||[]).map(e=>e.name).join(`, `)||`none`}`,`LOOK: ${a||JE}`];return n===`video`&&o.push(`MOTION: ${YE}`),o.join(`
|
|
17
|
-
`)}export{RS as $,Ui as $a,Xd as $c,Pf as $i,di as $l,Jg as $n,as as $o,fm as $r,Df as $s,Db as $t,zC as A,_u as Aa,Qe as Ac,T as Ai,Hu as Al,ay as An,ra as Ao,og as Ar,Dl as As,Yb as At,yt as Au,qS as B,jf as Ba,ke as Bc,io as Bi,qt as Bl,Gv as Bn,ql as Bo,sm as Br,Br as Bs,bx as Bt,vl as Bu,pw as C,Rs as Ca,Ge as Cc,fu as Ci,G as Cl,Yy as Cn,qd as Co,t_ as Cr,Nl as Cs,Nx as Ct,dr as Cu,cw as D,fr as Da,Ye as Dc,Bs as Di,qi as Dl,$v as Dn,Ii as Do,Jh as Dr,jl as Ds,Lx as Dt,Ur as Du,lw as E,tf as Ea,Je as Ec,Vl as Ei,nr as El,Cy as En,Vi as Eo,Ih as Er,Fl as Es,Fx as Et,Xt as Eu,_C as F,Ce as Fa,Me as Fc,id as Fi,oa as Fl,oy as Fn,_t as Fo,Ip as Fr,ne as Fs,ax as Ft,F as Fu,eC as G,Ut as Ga,Ie as Gc,Es as Gi,ll as Gl,S_ as Gn,Uu as Go,nm as Gr,Mu as Gs,Sx as Gt,S as Gu,QS as H,Ms as Ha,st as Hc,af as Hi,Wt as Hl,sv as Hn,nl as Ho,lm as Hr,rl as Hs,fx as Ht,un as Hu,oC as I,we as Ia,Ne as Ic,Wf as Ii,Gt as Il,uy as In,$t as Io,Rp as Ir,re as Is,ux as It,Xf as Iu,zx as J,Cr as Ja,Dt as Jc,W as Ji,Qf as Jl,cg as Jn,qo as Jo,Kp as Jr,zf as Js,ix as Jt,g as Ju,GS as K,Ls as Ka,Fe as Kc,Lf as Ki,or as Kl,kg as Kn,ts as Ko,am as Kr,xo as Ks,xx as Kt,b as Ku,$S as L,Cs as La,Pe as Lc,wt as Li,zt as Ll,Kv as Ln,Qt as Lo,$p as Lr,te as Ls,Zb as Lt,dn as Lu,mC as M,Ft as Ma,Be as Mc,Ed as Mi,Pu as Ml,cy as Mn,vt as Mo,ag as Mr,ee as Ms,
|
|
16
|
+
`),r=n.pop()??``;for(let e of n){let n=e.trim();if(!n.startsWith(`data:`))continue;let r=n.slice(5).trim();if(r)try{t.push(JSON.parse(r))}catch{}}return{events:t,tail:r}}var GT=``;function KT(e){return`${GT}${e}`}var qT=e=>typeof e==`string`&&/^[a-f0-9]{32}$/.test(e),JT=new Set([`aborted`,`auth`,`rate_limited`,`tool_failed`,`upstream`,`unknown`]),YT=(e,t)=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t)),XT=(e,t)=>{try{return e()}catch{return t}},ZT=e=>XT(()=>e?.status===401||e?.code===`auth`?`auth`:e?.status===429||e?.code===`rate_limit`?`rate_limited`:`upstream`,`upstream`),QT=new Set([`auth`,`entitlement`,`rate_limit`,`overloaded`,`upstream`]);async function $T(e){let t=Number.isFinite(e?.status)?e.status:null,n=null;try{let t=await e.clone().json();n=typeof t?.error==`string`?{message:t.error}:t?.error&&typeof t.error==`object`?t.error:null}catch{}let r=typeof n?.message==`string`?n.message.trim():``,i=r?t!==null&&r.startsWith(`${t} `)?r:`${t??`Upstream`} — ${r}`:`The turn was refused with HTTP ${t??`error`}.`;return{code:QT.has(n?.code)?n.code:t===429?`rate_limit`:t===401?`auth`:`upstream`,message:i,...t===null?{}:{status:t},...n?.resetAt?{resetAt:n.resetAt}:{}}}function eE({surface:e,capture:t,now:n,correlationId:r=null}){let i=XT(()=>{let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``)},null),a=()=>XT(()=>{let e=n();return Number.isFinite(e)?e:NaN},NaN),o=r??i,s=a(),c=XT(()=>[`studio`,`workflow`].includes(e)?e:/^\/workflow(?:\/|$)/.test(globalThis.location?.pathname||``)?`workflow`:`studio`,`studio`),u=!1,d=!1,f=new Map,h=new Set,g=(e,n)=>{if(i)try{Promise.resolve(t(e,n)).catch(()=>{})}catch{}},_=(e,t)=>{if(!u){if(u=!0,e===`cancelled`)for(let[e,t]of f)h.has(e)||g(`agent:tool_executed`,{turn_id:i,tool_category:t.category,outcome:`cancelled`,duration_bucket:p(a()-t.startedAt)});f.clear(),g(`agent:turn_${e}`,{turn_id:i,duration_bucket:p(a()-s),...e===`succeeded`?{}:{failure_code:t}})}};return g(`agent:turn_requested`,{surface:c,turn_id:i}),{turnId:i,cancel:()=>_(`cancelled`,`aborted`),fail:e=>_(`failed`,JT.has(e)?e:`upstream`),frame(e){try{if(!i||u)return;if(e.type===`execution_tool_started`){if(!YT(e,[`type`,`turn_id`,`telemetry_id`,`tool_category`])||e.turn_id!==o||!qT(e.telemetry_id)||!m.includes(e.tool_category))return;!f.has(e.telemetry_id)&&!h.has(e.telemetry_id)&&f.set(e.telemetry_id,{category:e.tool_category,startedAt:a()});return}let{event:t,props:n}=e;if(n?.turn_id!==o)return;if(t===`agent:tool_executed`){if(!YT(e,[`type`,`event`,`props`,`telemetry_id`])||!qT(e.telemetry_id)||!YT(n,[`turn_id`,`tool_category`,`outcome`,`duration_bucket`])||!m.includes(n.tool_category)||![`succeeded`,`failed`,`cancelled`].includes(n.outcome)||!l.duration_bucket.has(n.duration_bucket)||h.has(e.telemetry_id))return;h.add(e.telemetry_id),f.delete(e.telemetry_id),g(t,{turn_id:i,tool_category:n.tool_category,outcome:n.outcome,duration_bucket:n.duration_bucket});return}if(!YT(e,[`type`,`event`,`props`]))return;if(t===`agent:result_applied`){!d&&YT(n,[`turn_id`])&&(d=!0,g(t,{turn_id:i}));return}if(![`agent:turn_succeeded`,`agent:turn_failed`,`agent:turn_cancelled`].includes(t))return;let r=t.slice(11),s=Object.hasOwn(n,`failure_code`);if(!YT(n,[`turn_id`,`duration_bucket`,...s?[`failure_code`]:[]])||!l.duration_bucket.has(n.duration_bucket)||s&&(r===`succeeded`||!JT.has(n.failure_code)))return;_(r,r===`cancelled`?`aborted`:n.failure_code||`unknown`)}catch{}}}}var tE=3,nE={anthropic:[`ANTHROPIC_API_KEY`],openai:[`OPENAI_API_KEY`],google:[`GEMINI_API_KEY`,`GOOGLE_API_KEY`],openrouter:[`OPENROUTER_API_KEY`],cliproxy:[`CLIPROXY_API_KEY`]};function rE(e){let t=nE[e];return t?.length?t.join(` or `):`an environment variable`}function iE({fetchImpl:e=globalThis.fetch?.bind(globalThis),surface:t,capture:n=s,now:r=()=>performance.now()}={}){let i=new Map,a=async(t,n)=>{let r=await e(KT(t),{headers:{"content-type":`application/json`},...n});if(!r.ok){let e=null;try{e=await r.clone().json()}catch{}let n=typeof e?.error==`string`?e.error:e?.error?.message,i=Error(n||`${t} responded ${r.status}`);throw i.status=r.status,e?.error&&typeof e.error==`object`&&Object.assign(i,e.error),e?.preservation&&typeof e.preservation==`object`&&(i.preservation=e.preservation),i}return r.json()};return{mock:!1,async status(){return a(`/oauth/status`)},async signIn(){let e=await a(`/oauth/start`,{method:`POST`,body:`{}`});return e?.authorizeUrl&&globalThis.open?.(e.authorizeUrl,`_blank`,`noopener,noreferrer`),e},async signOut(){return a(`/oauth/logout`,{method:`POST`,body:`{}`})},async models(){let e=await a(`/agent/models`),t=Array.isArray(e?.models)?e.models:[];return{providers:Array.isArray(e?.providers)?e.providers.filter(e=>e?.id&&Array.isArray(e.models)):[],models:t}},async steer(e,t){return a(`/agent/turn/${encodeURIComponent(e)}/steer`,{method:`POST`,body:JSON.stringify(t)})},async providers(){let e=await a(`/agent/providers`);return Array.isArray(e?.providers)?e.providers:[]},async setProviderKey(e,t){return a(`/agent/providers/${encodeURIComponent(e)}`,{method:`PUT`,body:JSON.stringify({key:t})})},async removeProviderKey(e){return a(`/agent/providers/${encodeURIComponent(e)}`,{method:`DELETE`})},async listSessions(){let e=await a(`/agent/sessions?surface=${encodeURIComponent(t||`studio`)}`);return Array.isArray(e?.sessions)?e.sessions:[]},async loadSession(e){return a(`/agent/sessions/${encodeURIComponent(e)}`)},async stop(e){let t=typeof e==`string`||!e?{sessionId:e}:{surface:`studio`,sessionId:e.sessionId,turnId:e.turnId,...e.jobId?{jobId:e.jobId}:{}};return i.get(t.sessionId)?.cancel(),a(`/agent/stop`,{method:`POST`,body:JSON.stringify(t)})},async acceptJob({jobId:e,sessionId:t,turnId:n}){return a(`/agent/jobs/${encodeURIComponent(e)}/accept`,{method:`POST`,body:JSON.stringify({surface:`studio`,sessionId:t,turnId:n,explicitUnverifiedAcceptance:!0})})},async image({prompt:e,imageDataUrl:t,referenceDataUrl:n,references:r,quality:i=`auto`},o){return a(`/agent/image`,{method:`POST`,body:JSON.stringify({prompt:e,imageDataUrl:t,...n?{referenceDataUrl:n}:{},...Array.isArray(r)&&r.length?{references:r}:{},quality:i}),signal:o})},async video(e,t){return a(`/agent/video`,{method:`POST`,body:JSON.stringify(e),signal:t})},async videoProviders(){return a(`/agent/video/providers`)},async turn(a,o,s){let{sessionId:c,text:l,attachFrame:u,model:d,effort:f,attachments:p}=a,m=Array.isArray(p)&&p.length?{attachments:p}:{},h=a.surface===`studio`,g=h?a.turnId:null,_=eE({surface:t,capture:n,now:r,correlationId:g});a.onTurnId?.(h?g:_.turnId),i.set(c,_);let v=()=>{s.reason===`agent-stop`&&_.cancel()};s?.addEventListener(`abort`,v,{once:!0}),s?.aborted&&v();let y=!1,b,x=0,S=!1,C=e=>{if(e?.type===`execution_telemetry`||e?.type===`execution_tool_started`){_.frame(e);return}if(h&&Number.isFinite(e?.eventSeq)){if(e.eventSeq<=x)return;x=e.eventSeq}e?.type===`error`&&(b=ZT(e)),e?.type===`done`&&(S=!0),o(e)},w=async e=>{let t=e.body.getReader();y=!0;try{let e=new TextDecoder,n=``;for(;;){let{value:r,done:i}=await t.read();if(i)break;n+=e.decode(r,{stream:!0});let a=WT(n);n=a.tail;for(let e of a.events)C(e)}for(let e of WT(`${n}\n`).events)e?.type!==`execution_telemetry`&&e?.type!==`execution_tool_started`&&C(e)}finally{t.releaseLock()}},T=JSON.stringify(h?{surface:`studio`,sessionId:c,turnId:g,text:l,context:a.context,...d?{model:d}:{},...f?{effort:f}:{},...u===void 0?{}:{attachFrame:!!u},...m}:{sessionId:c,text:l,attachFrame:u,model:d,...f?{effort:f}:{},...m,..._.turnId?{turn_id:_.turnId}:{}});try{let t=await e(KT(`/agent/turn`),{method:`POST`,headers:{"content-type":`application/json`,accept:`text/event-stream`},body:T,signal:s});if(!t.ok||!t.body){_.fail(ZT(t)),o({type:`error`,...await $T(t)}),o({type:`done`});return}let n=null;try{await w(t)}catch(e){n=e}for(let t=0;h&&g&&!S&&!s?.aborted&&t<tE;t+=1){let t;try{t=await e(KT(`/agent/turn/${encodeURIComponent(g)}/events?after=${x}`),{headers:{accept:`text/event-stream`},signal:s})}catch{break}if(!t?.ok||!t.body)break;n=null;try{await w(t)}catch(e){n=e}}if(n)throw n;b&&_.fail(b)}catch(e){throw!s?.aborted&&(!y||b)&&_.fail(b||ZT(e)),e}finally{s?.removeEventListener(`abort`,v),i.get(c)===_&&i.delete(c)}}}}function aE(e=globalThis.location?.search||``){let t=new URLSearchParams(e);if(t.get(`agent`)!==`mock`)return null;let n=t.get(`state`);return{state:oT.includes(n)?n:`ready`,speed:Number(t.get(`speed`))||1}}var oE={signedIn:!0,email:`director@cozyclay.org`,plan:`Plus`,accountId:`acct_mock_126`,expiresAt:null},sE=[{delay:40,event:{type:`text.delta`,text:`Framing a wide two-shot from the current blocking. `}},{delay:120,event:{type:`text.delta`,text:`Capturing the viewport first.`}},{delay:120,event:{type:`tool.start`,callId:`call-1`,name:`capture_blocking_frame`,label:`Capture blocking frame`,args:{shot:`current`}}},{delay:260,event:{type:`tool.done`,callId:`call-1`,ok:!0,elapsedMs:268,result:{width:1280,height:720}}},{delay:90,event:{type:`tool.start`,callId:`call-2`,name:`render_from_frame`,label:`Render from frame`,args:{style:`storyboard`,strength:.6}}},{delay:420,event:{type:`tool.done`,callId:`call-2`,ok:!0,elapsedMs:1412,result:{imageId:`img-1`}}},{delay:80,event:{type:`image`,imageId:`img-1`,dataUrl:`data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22512%22%20height%3D%22288%22%20viewBox%3D%220%200%20512%20288%22%3E%3Cdefs%3E%3ClinearGradient%20id%3D%22g%22%20x1%3D%220%22%20y1%3D%220%22%20x2%3D%221%22%20y2%3D%221%22%3E%3Cstop%20offset%3D%220%22%20stop-color%3D%22%232a2f52%22%2F%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%235b3550%22%2F%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Crect%20width%3D%22512%22%20height%3D%22288%22%20fill%3D%22url(%23g)%22%2F%3E%3Ccircle%20cx%3D%22150%22%20cy%3D%22150%22%20r%3D%2252%22%20fill%3D%22%23ef759d%22%20opacity%3D%220.85%22%2F%3E%3Crect%20x%3D%22250%22%20y%3D%22112%22%20width%3D%22180%22%20height%3D%22112%22%20rx%3D%2210%22%20fill%3D%22%238994ff%22%20opacity%3D%220.8%22%2F%3E%3Crect%20y%3D%22240%22%20width%3D%22512%22%20height%3D%2248%22%20fill%3D%22%23101116%22%20opacity%3D%220.55%22%2F%3E%3Ctext%20x%3D%2224%22%20y%3D%22272%22%20font-family%3D%22Inter%2Csans-serif%22%20font-size%3D%2218%22%20fill%3D%22%23edf0fb%22%3Emock%20render%20%C2%B7%20wide%20two-shot%3C%2Ftext%3E%3C%2Fsvg%3E`,width:512,height:288,prompt:`wide two-shot, storyboard ink`}},{delay:60,event:{type:`quota`,plan:`Plus`,primary:{usedPercent:46,windowMinutes:300,resetAt:null},credits:{has:!0}}},{delay:40,event:{type:`done`}}],cE={ok:!0,commandId:`cmd-mock-1`,receiptId:`receipt-mock-1`,host:{workspaceId:`tab-mock`,documentEpoch:`doc-mock`,sceneId:`scene-mock`,sceneEpoch:`scene-open-mock`},status:`applied`,authored:!0,revision:{before:41,after:42},affectedIds:[`char-a`],delta:[{id:`char-a`,after:{position:{x:-.8,y:0,z:.4}}}],checks:{coverage:`affected-targets`},undo:{historyEntryId:`history-mock-1`,entries:1,canUndoDirect:!0},warnings:[]},lE=[{delay:40,event:{type:`text.delta`,text:`Reading the scene before I move anyone. `}},{delay:120,event:{type:`tool.start`,callId:`studio-1`,name:`inspect_studio`,label:`inspect studio`,args:{scope:`selection`}}},{delay:220,event:{type:`tool.done`,callId:`studio-1`,ok:!0,elapsedMs:214,result:{entities:2}}},{delay:90,event:{type:`text.delta`,text:`Blocking the two-shot now.`}},{delay:120,event:{type:`tool.start`,callId:`studio-2`,name:`arrange_characters`,label:`arrange characters`,args:{ops:[{op:`update`,characterId:`char-a`,position:{world:{x:-.8,y:0,z:.4}}}]}}},{delay:320,event:{type:`tool.done`,callId:`studio-2`,ok:!0,elapsedMs:332,result:{ok:!0,receiptId:cE.receiptId}}},{delay:60,event:{type:`receipt`,receipt:cE}},{delay:40,event:{type:`done`}}],uE=[[`openai-codex`,`ChatGPT (OpenAI Codex)`],[`anthropic`,`Anthropic`],[`openai`,`OpenAI`],[`google`,`Google Gemini`],[`openrouter`,`OpenRouter`],[`cliproxy`,`CLIProxyAPI`]],dE=`google`,fE={"openai-codex":[{id:`gpt-6-astra`,label:`gpt-6-astra`,efforts:[`none`,`low`,`medium`,`high`,`xhigh`],defaultEffort:`medium`},{id:`gpt-5.1-codex`,label:`gpt-5.1-codex`,efforts:[`low`,`medium`,`high`],defaultEffort:`medium`}],anthropic:[{id:`claude-sonnet-4-5`,label:`Claude Sonnet 4.5`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`medium`}],openai:[{id:`gpt-5.1`,label:`GPT-5.1`,efforts:[`none`,`low`,`medium`,`high`,`xhigh`],defaultEffort:`medium`}],google:[{id:`gemini-3-pro`,label:`Gemini 3 Pro`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`medium`}],openrouter:[{id:`deepseek-v3`,label:`DeepSeek V3`,efforts:[`none`],defaultEffort:`none`}],cliproxy:[{id:`claude-sonnet-5`,label:`Claude Sonnet 5`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`medium`}]},pE={id:`gpt-6-live-preview`,label:`gpt-6 live preview`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`high`},mE=`cozyclay.mock.agent.status-calls`,hE=`cozyclay.mock.agent.model-calls`,gE=e=>{try{globalThis.localStorage?.setItem(e,String(Number(globalThis.localStorage.getItem(e)||0)+1))}catch{}};function _E(e={state:`ready`}){let t=e?.state||`ready`,n=e?.surface===`studio`,r=e?.speed>0?e.speed:1,i=e=>new Promise(t=>setTimeout(t,Math.max(0,e/r))),a=new Set,o=t===`signed-out`?`out`:t===`signing-in`?`pending`:`in`,s=()=>uE.map(([e,t])=>{let n=e===`openai-codex`?o===`in`?`chatgpt`:null:e===dE?`env`:a.has(e)?`file`:null;return{id:e,label:t,authSource:n,signedIn:!!n}}),c=null,l=0;return{mock:!0,state:t,async status(){gE(mE);let e=s().filter(e=>e.id!==`openai-codex`&&e.signedIn).length;return o===`pending`?{signedIn:!1,pending:!0,email:null,plan:null,accountId:null,expiresAt:null,providersConfigured:a.size}:o===`out`?{signedIn:!1,email:null,plan:null,accountId:null,expiresAt:null,providersConfigured:a.size}:t===`no-entitlement`?{...oE,plan:`Free`,entitlements:{image:!1},providersConfigured:e}:{...oE,entitlements:{image:!0},providersConfigured:e}},async signIn(){return o=`in`,{ok:!0,authorizeUrl:`https://auth.example.invalid/mock`}},async signOut(){return o=`out`,{ok:!0}},async models(){gE(hE);let e=s().map(e=>{let t=fE[e.id]??[],n=e.id===`openai-codex`&&o===`in`?[...t,pE]:t;return{...e,models:n.map(t=>({...t,key:`${e.id}/${t.id}`,input:[`text`,`image`]}))}});return{providers:e,models:e.flatMap(e=>e.models.map(e=>({...e,id:e.key})))}},async providers(){return s()},async setProviderKey(e,t){if(e===`openai-codex`)throw Object.assign(Error(`Use ChatGPT sign-in for OpenAI Codex.`),{status:400});if(typeof t!=`string`||t.trim().length<8)throw Object.assign(Error(`That key was refused: it is too short.`),{status:400});return a.add(e),{ok:!0}},async removeProviderKey(e){return a.delete(e),{ok:!0}},async stop(){return c=null,{ok:!0}},async steer(e,t){if(n)throw Object.assign(Error(`409 — Steering a Studio turn is not supported.`),{status:409,code:`STEER_UNSUPPORTED`});if(!c||e!==c)throw Object.assign(Error(`409 — This turn already ended.`),{status:409,code:`NO_ACTIVE_TURN`});try{globalThis.localStorage?.setItem(`cozyclay.mock.agent.last-steer`,JSON.stringify({turnId:e,text:t?.text??null,attachments:t?.attachments?.length??0}))}catch{}return{ok:!0,queued:!0}},async acceptJob(){return{ok:!0}},async listSessions(){if(!n)return[];let e=[];try{for(let t=0;t<globalThis.localStorage.length;t+=1){let n=globalThis.localStorage.key(t);if(!n?.startsWith(`cozyclay.mock.agent.session.`))continue;let r=JSON.parse(globalThis.localStorage.getItem(n));r?.meta&&e.push(r.meta)}}catch{}return e.sort((e,t)=>Date.parse(t.updatedAt||0)-Date.parse(e.updatedAt||0)).slice(0,50)},async loadSession(e){try{let t=JSON.parse(globalThis.localStorage.getItem(`cozyclay.mock.agent.session.${e}`));if(t?.transcript)return t}catch{}throw Error(`Mock session not found.`)},async applyImage({requestId:e}){return{ok:!0,receiptId:`mock-${e}`}},async turn(e,r,a){let o=`mock-turn-${++l}`;c=o,e?.onTurnId?.(o);try{globalThis.localStorage?.setItem(`cozyclay.mock.agent.last-turn`,JSON.stringify({turnId:o,model:e?.model??null,effort:e?.effort??null,text:e?.text??null}))}catch{}try{n&&e?.sessionId&&globalThis.localStorage?.setItem(`cozyclay.mock.agent.last-turn-session`,e.sessionId)}catch{}let s=[],u=n&&e?.sessionId?`cozyclay.mock.agent.session.${e.sessionId}`:null;if(u){try{s=JSON.parse(globalThis.localStorage.getItem(u))?.transcript||[]}catch{s=[]}s.push({kind:`user`,text:e.text})}let d=t=>{if(u){if(t.type===`text.delta`){let e=s.at(-1);e?.kind===`assistant`?e.text+=t.text:s.push({kind:`assistant`,text:t.text})}else if(t.type===`tool.start`)s.push({kind:`tool`,name:t.name,label:t.label,ok:!0,elapsedMs:null,callId:t.callId});else if(t.type===`tool.done`){let e=[...s].reverse().find(e=>e.kind===`tool`&&e.callId===t.callId);e&&Object.assign(e,{ok:t.ok,elapsedMs:t.elapsedMs})}else t.type===`receipt`&&s.push({kind:`receipt`,receiptId:t.receipt?.receiptId,summary:t.receipt?.status===`applied`?`Applied to the scene`:`Receipt`});try{globalThis.localStorage.setItem(u,JSON.stringify({sessionId:e.sessionId,transcript:s,meta:{sessionId:e.sessionId,surface:`studio`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),sceneName:`Mock scene`,firstText:s.find(e=>e.kind===`user`)?.text||``}}))}catch{}}r(t)};if(t===`rate-limited`){d({type:`text.delta`,text:`Framing a wide two-shot from the current blocking.`}),d({type:`quota`,plan:`Plus`,primary:{usedPercent:100,windowMinutes:300,resetAt:new Date(Date.now()+252e4).toISOString()},credits:{has:!1}}),d({type:`error`,code:`rate_limit`,message:LT.rate_limit,resetAt:new Date(Date.now()+252e4).toISOString()}),d({type:`done`}),c=null;return}if(t===`error`){d({type:`text.delta`,text:n?`Reading the scene first.`:`Capturing the viewport first.`}),d(n?{type:`tool.start`,callId:`call-1`,name:`inspect_studio`,label:`inspect studio`,args:{scope:`selection`}}:{type:`tool.start`,callId:`call-1`,name:`capture_blocking_frame`,label:`Capture blocking frame`,args:{shot:`current`}}),d({type:`tool.done`,callId:`call-1`,ok:!1,elapsedMs:812,error:n?`The scene is not ready`:`Viewport is not ready`}),d({type:`error`,code:`upstream`,message:LT.upstream}),d({type:`done`}),c=null;return}for(let e of n?lE:sE){if(a?.aborted||(await i(e.delay),a?.aborted))break;d(e.event)}c=null,await i(240),a?.aborted&&d({type:`done`})}}}function vE(e={}){let t=e.mockConfig===void 0?aE():e.mockConfig;return t?_E({surface:e.surface,...t}):iE(e)}function yE(e){let t=e?.outcome;return t?.status===`already_applied`?null:t&&t.mutated===!1?{status:`not_applied`,code:t.code??`CANCELLED`,mutated:!1}:{status:`unknown`,code:t?.code??null,mutated:`unknown`}}function bE(e){return new Promise(t=>{let n=r=>{r.detail?.requestId===e.requestId&&(globalThis.removeEventListener(`cozyclay:agent-image-result`,n),t({ok:!!r.detail.ok,error:r.detail.error,receiptId:r.detail.receiptId}))};globalThis.addEventListener?.(`cozyclay:agent-image-result`,n),!(globalThis.dispatchEvent&&!globalThis.dispatchEvent(new CustomEvent(`cozyclay:agent-image`,{cancelable:!0,detail:e})))&&(globalThis.removeEventListener?.(`cozyclay:agent-image-result`,n),t({ok:!1,error:`No editor accepted the image. Open the scene that should receive it.`}))})}function xE({transport:e,surface:t=`workflow`,buildContext:n=null,requestImageAction:i=null,onAuthLost:o=null,onReceipt:s=null,newId:c=sT,clock:l=()=>Date.now()}={}){let u=t===`studio`,d=new Set,f=new Set,p=new Set,m=null,h=null,g=null,_={sessionId:c(),turnId:null,draft:``,pendingAttachments:[],items:[],streaming:!1,quota:null,rateLimit:null,lastPrompt:``,turnStartedAt:null,lastTurn:null},v=e=>{_={..._,...e};for(let e of[...d])e(_)},y=e=>v({items:e(_.items)}),b=(e,t)=>y(n=>n.map(n=>e(n)?{...n,...t}:n)),x=e=>_.items.find(t=>t.kind===`job`&&t.jobId===e);function S(e){if(!e?.jobId||!a.jobStates.includes(e.state))return;let t=typeof e.progress==`number`&&Number.isFinite(e.progress)?Math.min(1,Math.max(0,e.progress)):null;y(n=>{let r=n.find(t=>t.kind===`job`&&t.jobId===e.jobId),i={kind:`job`,id:r?.id??`job:${e.jobId}`,jobId:e.jobId,commandId:e.commandId??r?.commandId??null,state:e.state,phase:typeof e.phase==`string`?e.phase:r?.phase??null,progress:t??r?.progress??null,verification:r?.verification??null,receiptId:r?.receiptId??null,outcome:r?.outcome??null,acceptance:e.state===`review_required`?r?.acceptance??{status:`required`}:r?.acceptance??null};return r?n.map(e=>e===r?i:e):[...n,i]})}function C(e){let t;try{t=r(e)}catch(e){y(t=>[...t,{kind:`failure`,id:c(),failure:{code:e?.code||`INVALID_RECEIPT`,message:e?.message||`The host returned an unreadable receipt.`,preserved:{authoredState:`unknown`},recovery:{action:`inspect`}}}]);return}if(t.ok===!1){let e=`failure:${t.commandId}:${t.code}`;if(f.has(e))return;f.add(e),y(n=>[...n.map(e=>e.kind===`job`&&e.commandId===t.commandId&&!uT(e.state)?{...e,state:`failed`,phase:t.phase,acceptance:null}:e),{kind:`failure`,id:e,failure:t}]);return}if(!f.has(t.receiptId)){f.add(t.receiptId),y(e=>[...e.map(e=>e.kind===`job`&&e.jobId===t.jobId?{...e,state:t.status===`installed`?`installed`:e.state,verification:t.verification??null,receiptId:t.receiptId,acceptance:t.explicitUnverifiedAcceptance?{status:`accepted`}:null}:e),{kind:`receipt`,id:`receipt:${t.receiptId}`,receiptId:t.receiptId,receipt:t,summary:pT(t)}]);try{s?.(t)}catch{}}}function w(e){if(h&&[`text.delta`,`tool.start`,`tool.done`,`image`,`job.state`,`job.progress`,`receipt`,`error`].includes(e?.type)&&(h.produced=!0),e?.type===`text.delta`){y(t=>{let n=t[t.length-1];return n?.kind===`assistant`?[...t.slice(0,-1),{...n,text:n.text+e.text}]:[...t,{kind:`assistant`,id:c(),text:e.text}]});return}if(e?.type===`tool.start`){y(t=>[...t,{kind:`tool`,id:e.callId||c(),callId:e.callId,name:e.name,label:e.label,args:e.args,status:`running`}]);return}if(e?.type===`tool.done`){b(t=>t.kind===`tool`&&t.callId===e.callId,{status:e.ok?`done`:`failed`,elapsedMs:e.elapsedMs,result:e.result,error:e.error});let t=e.result;if(e.ok&&t&&typeof t==`object`&&t.ok===!0&&typeof t.receiptId==`string`&&Array.isArray(t.affectedIds))try{s?.(t)}catch{}return}if(e?.type===`image`){y(t=>[...t,{kind:`image`,id:e.imageId||c(),imageId:e.imageId,dataUrl:e.dataUrl,width:e.width,height:e.height,prompt:e.prompt,placed:!1,apply:null}]);return}if(e?.type===`job.state`||e?.type===`job.progress`){S(e);return}if(e?.type===`receipt`){C(e.receipt);return}if(e?.type===`quota`){v({quota:{plan:e.plan,usedPercent:e.primary?.usedPercent,windowMinutes:e.primary?.windowMinutes,resetAt:e.primary?.resetAt,credits:e.credits}});return}if(e?.type!==`error`)return;let t={code:e.code||`upstream`,message:e.message||LT[e.code]||`The turn failed.`,...Number.isFinite(e.status)?{status:e.status}:{}};if(h&&(h.failure=t),e.code===`rate_limit`){v({rateLimit:{resetAt:e.resetAt||null,message:e.message||LT.rate_limit}});return}if(e.code===`auth`){o?.();return}y(e=>{let n=e.findLastIndex(e=>e.kind===`user`),r=e.findLastIndex((e,t)=>t>n&&e.kind===`tool`&&e.status===`failed`);return r===-1?[...e,{kind:`failure`,id:c(),failure:{...t,recovery:{action:`retry`,retryAllowed:!0}}}]:e.map((e,n)=>n===r?{...e,failure:t}:e)})}function T(e,t,n){if(!e||p.has(e))return;p.add(e);let r=!!t?.ok,i={apply:{requestId:e,status:r?`settled`:`failed`,error:r?null:t?.error||`The editor did not apply the image.`,receiptId:t?.receiptId??null}};r&&(i.placed=n===`place`),b(t=>t.kind===`image`&&t.apply?.requestId===e,i)}async function E(e,t){let n=_.items.find(t=>t.kind===`image`&&t.id===e);if(!n||n.apply?.status===`applying`||(t===`place`?n.placed:!n.placed))return;let r=c();b(t=>t.kind===`image`&&t.id===e,{apply:{requestId:r,status:`applying`,error:null,receiptId:null,startedAt:l()}});let a={action:t,requestId:r,imageId:n.imageId,dataUrl:n.dataUrl,width:n.width,height:n.height,prompt:n.prompt};try{T(r,await(i??bE)(a),t)}catch(e){T(r,{ok:!1,error:String(e?.message||e)},t)}}let D=()=>{f.clear(),p.clear(),v({sessionId:c(),turnId:null,items:[],pendingAttachments:[],rateLimit:null,lastPrompt:``,turnStartedAt:null,lastTurn:null})};return{getState:()=>_,subscribe(e){return d.add(e),()=>d.delete(e)},setDraft:e=>v({draft:String(e??``)}),addAttachments(e){let t=(Array.isArray(e)?e:[]).filter(e=>typeof e?.dataUrl==`string`&&e.dataUrl.startsWith(`data:image/`)).map(e=>({id:c(),dataUrl:e.dataUrl,...e.name?{name:String(e.name).slice(0,120)}:{}})),{attachments:n,rejected:r}=Jw(_.pendingAttachments,t,4),i=n.length-_.pendingAttachments.length;return v({pendingAttachments:n}),{added:i,rejected:r}},removeAttachment:e=>v({pendingAttachments:_.pendingAttachments.filter(t=>t.id!==e)}),clearAttachments:()=>v({pendingAttachments:[]}),async send(t,r={}){let i=String(t??``).trim();if(!i||_.streaming)return;let a=c(),o=u?n?.()??null:null;if(u&&!o){w({type:`error`,code:`upstream`,message:`The editor is not ready to describe the scene yet.`});return}let s=l(),d={produced:!1,failure:null};h=d;let f=(Array.isArray(r.attachments)?r.attachments:_.pendingAttachments).slice(0,4).map(({dataUrl:e,name:t})=>({dataUrl:e,...t?{name:t}:{}}));v({lastPrompt:i,rateLimit:null,turnId:a,streaming:!0,draft:``,pendingAttachments:[],turnStartedAt:s,lastTurn:null,items:[..._.items,{kind:`user`,id:c(),text:i,attachFrame:!!r.attachFrame,attachments:f}]}),m=new AbortController;let p=m.signal;try{await e.turn({onTurnId:e=>{g=e},...u?{surface:`studio`,turnId:a,context:o}:{},sessionId:_.sessionId,text:i,...f.length?{attachments:f}:{},attachFrame:!!r.attachFrame,model:r.model,effort:r.effort??void 0},w,p)}catch(e){p.aborted||w({type:`error`,code:`upstream`,message:String(e?.message||e)})}finally{if(m?.signal===p&&(m=null),h===d){g=null,!d.produced&&!d.failure&&!p.aborted&&(d.failure={code:`no_output`,message:`The turn ended without a response.`,recovery:{action:`retry`,retryAllowed:!0}},y(e=>[...e,{kind:`failure`,id:c(),failure:d.failure}]));let e=l();h=null,v({streaming:!1,turnStartedAt:null,lastTurn:{status:p.aborted?`stopped`:d.failure?`failed`:`done`,endedAt:e,durationMs:e-s,failure:d.failure}})}}},async steer(t,n={}){let r=String(t??``).trim();if(!r)return{ok:!1,code:`EMPTY`,message:``};if(!_.streaming||!g||typeof e.steer!=`function`)return{ok:!1,code:`NO_ACTIVE_TURN`,message:IT.NO_ACTIVE_TURN};let i=(Array.isArray(n.attachments)?n.attachments:_.pendingAttachments).slice(0,4).map(({dataUrl:e,name:t})=>({dataUrl:e,...t?{name:t}:{}}));try{await e.steer(g,{text:r,...i.length?{attachments:i}:{}})}catch(e){let t=typeof e?.code==`string`?e.code:`upstream`;return{ok:!1,code:t,message:IT[t]||String(e?.message||e)}}return v({draft:``,pendingAttachments:[],items:[..._.items,{kind:`user`,id:c(),text:r,steered:!0,attachments:i}]}),{ok:!0,code:null,message:``}},stop(){let t=[..._.items].reverse().find(e=>e.kind===`job`&&!uT(e.state));m?.abort(`agent-stop`),m=null;let n=u?{sessionId:_.sessionId,turnId:_.turnId,...t?{jobId:t.jobId}:{}}:_.sessionId;if(Promise.resolve(e.stop?.(n)).then(e=>{if(!t)return;let n=yE(e);n&&(b(e=>e.kind===`job`&&e.jobId===t.jobId&&!uT(e.state),{state:n.status===`not_applied`?`cancelled`:`reconciling`,phase:null,outcome:n,acceptance:null}),b(e=>e.kind===`tool`&&e.status===`running`,{status:`cancelled`,result:n,elapsedMs:null}))}).catch(()=>{}),!_.streaming){v({streaming:!1});return}let r=l();v({streaming:!1,turnStartedAt:null,lastTurn:{status:`stopped`,endedAt:r,durationMs:r-(_.turnStartedAt??r),failure:null}})},async acceptJob(t){let n=x(t);if(!(!n||n.acceptance?.status!==`required`)){b(e=>e.kind===`job`&&e.jobId===t,{acceptance:{status:`accepting`}});try{let n=await e.acceptJob?.({jobId:t,sessionId:_.sessionId,turnId:_.turnId});n?.receipt?C(n.receipt):b(e=>e.kind===`job`&&e.jobId===t,{acceptance:{status:`required`,error:`The host did not acknowledge the acceptance.`}})}catch(e){b(e=>e.kind===`job`&&e.jobId===t,{acceptance:{status:`required`,error:String(e?.message||e)}})}}},applyImage:e=>E(e,`place`),undoImage:e=>E(e,`remove`),acknowledgeImageAction:({requestId:e,ok:t,error:n,receiptId:r})=>{let i=_.items.find(t=>t.kind===`image`&&t.apply?.requestId===e);T(e,{ok:t,error:n,receiptId:r},i?.placed?`remove`:`place`)},clearRateLimit:()=>v({rateLimit:null}),clearContext:D,newSession:D,restore:(e,t=_.sessionId)=>{f.clear(),p.clear();let n=new Set,r=(Array.isArray(e)?e:[]).flatMap(e=>{if(e?.kind===`user`||e?.kind===`assistant`){let t=Array.isArray(e.attachments)?e.attachments.filter(e=>typeof e?.dataUrl==`string`):[];return[{kind:e.kind,id:c(),text:String(e.text??``),...t.length?{attachments:t}:{}}]}return e?.kind===`tool`?[{kind:`tool`,id:c(),callId:c(),name:e.name||`tool`,label:e.label,ok:e.ok,elapsedMs:e.elapsedMs,status:e.ok===!1?`failed`:`done`}]:e?.kind===`receipt`?e.receiptId&&n.has(e.receiptId)?[]:(e.receiptId&&(n.add(e.receiptId),f.add(e.receiptId)),[{kind:`receipt`,id:`receipt:${e.receiptId||c()}`,receiptId:e.receiptId,summary:e.summary||`Receipt`,receipt:{status:`applied`,warnings:[],verification:{status:`verified`}}}]):e?.kind===`failure`?[{kind:`failure`,id:c(),failure:{code:e.code||`upstream`,message:String(e.message||`The turn failed.`),recovery:{action:`retry`,retryAllowed:!0}}}]:[]}),i=[...r].reverse().find(e=>e.kind===`user`)?.text||``;return v({sessionId:t,turnId:null,items:r,rateLimit:null,lastPrompt:i,turnStartedAt:null,lastTurn:null,streaming:!1}),r}}}function SE(e,t=Date.now()){let n=Date.parse(e||``);if(!Number.isFinite(n))return`just now`;let r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i}m ago`;let a=Math.floor(i/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function CE({tone:e,title:t}){return(0,$.jsx)(`span`,{className:`agent-status-dot ${e}`,title:t,"aria-hidden":`true`})}function wE({call:e,presentation:t,onRetry:n}){let r=e.status===`running`?`busy`:[`failed`,`cancelled`].includes(e.status)?`alert`:`ok`,i=Object.hasOwn(t.toolLabels,e.name),a=e.error?`error: ${e.error}`:JSON.stringify(e.result??e.args??{},null,2);return(0,$.jsxs)(`div`,{className:`agent-card agent-tool-card${e.status===`failed`?` failed`:``}`,"data-tool-status":e.status,"data-tool-name":e.name,children:[(0,$.jsxs)(`details`,{children:[(0,$.jsxs)(`summary`,{children:[(0,$.jsx)(CE,{tone:r,title:e.status}),(0,$.jsx)(`span`,{className:`agent-tool-label`,children:ST(e,t.toolLabels)}),i&&(0,$.jsx)(`span`,{className:`agent-tool-badge`,children:t.toolBadge}),(0,$.jsx)(`span`,{className:`agent-tool-elapsed`,children:e.status===`running`?`running…`:e.status===`cancelled`?e.result?.status===`not_applied`?`not applied`:`result unknown`:FT(e.elapsedMs)}),(0,$.jsx)(Tw,{size:12,"aria-hidden":`true`})]}),(0,$.jsx)(`pre`,{className:`agent-tool-detail`,children:a})]}),e.failure&&(0,$.jsxs)(`div`,{className:`agent-error`,role:`alert`,children:[(0,$.jsx)(`span`,{children:e.failure.message||LT[e.failure.code]||`The turn failed.`}),(0,$.jsxs)(`div`,{className:`agent-error-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-ghost-button agent-error-retry`,onClick:n,children:`Retry`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-ghost-button agent-error-details`,onClick:e=>{let t=e.currentTarget.closest(`.agent-tool-card`)?.querySelector(`details`);t&&(t.open=!t.open)},children:`Details`})]})]})]})}function TE({image:e,onUse:t,onUndo:n,onRegenerate:r,onOpen:i}){let a=e.apply?.status===`applying`,o=e.apply?.status===`failed`;return(0,$.jsxs)(`div`,{className:`agent-card agent-image-card`,"data-image-id":e.imageId,"data-placed":e.placed?`true`:`false`,"data-apply-status":e.apply?.status||`idle`,children:[(0,$.jsx)(`figure`,{children:(0,$.jsx)(`img`,{src:e.dataUrl,width:e.width,height:e.height,alt:e.prompt||`Generated image`,onClick:()=>i(e)})}),e.placed?(0,$.jsxs)(`div`,{className:`agent-placed`,children:[(0,$.jsx)(CE,{tone:`ok`}),`Placed`,(0,$.jsx)(`button`,{type:`button`,className:`agent-image-undo`,disabled:a,onClick:()=>n(e),children:a?`Removing…`:`Undo`})]}):(0,$.jsxs)(`div`,{className:`agent-image-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`primary agent-image-use`,disabled:a,onClick:()=>t(e),children:[(0,$.jsx)(vw,{size:11}),` `,a?`Applying…`:`Use in scene`]}),(0,$.jsxs)(`a`,{className:`agent-image-download`,role:`button`,href:e.dataUrl,download:`${e.imageId||`agent-image`}.png`,children:[(0,$.jsx)(xw,{size:11}),` Download`]}),(0,$.jsxs)(`button`,{type:`button`,className:`agent-image-regenerate`,onClick:()=>r(e),children:[(0,$.jsx)(dw,{size:11}),` Regenerate`]})]}),o&&(0,$.jsx)(`p`,{className:`agent-image-error`,role:`alert`,children:e.apply.error})]})}function EE({resetAt:e,onRetry:t,onSwitchModel:n}){let[r,i]=(0,Q.useState)(()=>Date.now());(0,Q.useEffect)(()=>{let e=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(e)},[]);let a=MT(e,r);return(0,$.jsxs)(`div`,{className:`agent-paused`,"data-agent-card":`rate-limited`,role:`status`,children:[(0,$.jsxs)(`div`,{className:`agent-paused-head`,children:[(0,$.jsx)(ww,{size:12,"aria-hidden":`true`}),` Paused — usage limit reached`,(0,$.jsx)(`span`,{className:`agent-paused-countdown`,children:a?`resets in ${a}`:`resets soon`})]}),(0,$.jsx)(`p`,{style:{margin:0},children:LT.rate_limit}),(0,$.jsxs)(`div`,{className:`agent-paused-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-paused-wait`,onClick:t,children:`Wait & retry`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-paused-switch`,onClick:n,children:`Switch model`})]})]})}function DE({job:e,onStop:t,onAccept:n}){let r=!uT(e.state),i=r&&Number.isFinite(e.progress)?Math.round(e.progress*100):null,a=e.state===`installed`?null:e.phase,o=e.state===`review_required`||e.verification?.status===`unverified`,s=e.verification?.limitations??[],c=e.state===`installed`&&o?`Installed with warnings`:cT[e.state]||e.state;return(0,$.jsxs)(`div`,{className:`agent-card agent-job-card`,"data-job-id":e.jobId,"data-job-state":e.state,children:[(0,$.jsxs)(`div`,{className:`agent-job-head`,children:[(0,$.jsx)(CE,{tone:dT(e.state),title:e.state}),(0,$.jsx)(`span`,{className:`agent-job-label`,children:c}),o&&(0,$.jsx)(`span`,{className:`agent-job-badge`,children:`Unverified`}),i!==null&&(0,$.jsx)(`span`,{className:`agent-job-progress`,children:fT(e.progress)})]}),a&&(0,$.jsx)(`p`,{className:`agent-job-phase`,children:a}),e.outcome?.status===`not_applied`&&(0,$.jsx)(`p`,{className:`agent-job-outcome`,children:`Not applied — scene unchanged.`}),e.outcome?.status===`unknown`&&(0,$.jsx)(`p`,{className:`agent-job-outcome`,children:`Stopped, but the result is unknown — reconcile before editing this target.`}),i!==null&&(0,$.jsx)(`div`,{className:`agent-job-bar`,role:`progressbar`,"aria-label":`Generation progress`,"aria-valuenow":i,"aria-valuemin":0,"aria-valuemax":100,children:(0,$.jsx)(`span`,{className:`agent-job-bar-fill`,style:{transform:`scaleX(${e.progress})`}})}),s.length>0&&(0,$.jsx)(`ul`,{className:`agent-job-limits`,children:s.map(e=>(0,$.jsx)(`li`,{children:e},e))}),(0,$.jsxs)(`div`,{className:`agent-job-actions`,children:[r&&e.state!==`review_required`&&(0,$.jsx)(`button`,{type:`button`,className:`agent-ghost-button agent-job-stop`,onClick:()=>t(e),children:`Stop`}),e.acceptance?.status===`required`&&(0,$.jsxs)(`button`,{type:`button`,className:`agent-ghost-button agent-job-accept`,onClick:()=>n(e),children:[(0,$.jsx)(kw,{size:11}),` Apply with warnings`]}),e.acceptance?.status===`accepting`&&(0,$.jsx)(`span`,{className:`agent-job-note`,children:`Applying…`}),e.acceptance?.status===`accepted`&&(0,$.jsxs)(`span`,{className:`agent-job-note`,children:[(0,$.jsx)(Ew,{size:11}),` Applied at your request`]}),e.acceptance?.error&&(0,$.jsx)(`span`,{className:`agent-job-note alert`,role:`alert`,children:e.acceptance.error})]})]})}function OE({item:e}){let{receipt:t={},summary:n}=e,r=t.verification?.status===`unverified`,i=t.verification?.limitations??[],a=t.warnings??[],o=t.status===`installed`&&r;return(0,$.jsxs)(`div`,{className:`agent-card agent-receipt-card`,"data-receipt-id":e.receiptId,"data-receipt-status":t.status,children:[(0,$.jsxs)(`div`,{className:`agent-receipt-head`,children:[(0,$.jsx)(CE,{tone:r?`warn`:`ok`,title:t.status}),o&&(0,$.jsx)(`span`,{className:`agent-job-label`,children:`Installed with warnings`}),(0,$.jsx)(`span`,{className:`agent-receipt-summary`,children:n})]}),(a.length>0||i.length>0)&&(0,$.jsxs)(`ul`,{className:`agent-receipt-notes`,children:[a.map(e=>(0,$.jsx)(`li`,{children:e.message||e.code},e.code)),i.map(e=>(0,$.jsx)(`li`,{children:e},e))]}),o&&(0,$.jsx)(`p`,{className:`agent-job-note`,children:`Undo with Cmd+Z or ask the agent.`})]})}var kE={none:`No recovery is available for this command.`,inspect:`Ask the agent to inspect the target before trying again.`,retry:`The same command can be retried.`,new_intent:`Tell the agent what to do with the changed target.`,reconcile:`The result is unknown; reconcile before changing this target.`,sign_in:`Sign in again to continue.`};function AE({failure:e,onRetry:t}){return(0,$.jsxs)(`div`,{className:`agent-card agent-failure-card`,"data-failure-code":e.code,role:`alert`,children:[(0,$.jsxs)(`div`,{className:`agent-failure-head`,children:[(0,$.jsx)(kw,{size:12,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`agent-failure-code`,children:e.code})]}),(0,$.jsx)(`p`,{className:`agent-failure-message`,children:e.message||`The command did not complete.`}),(0,$.jsxs)(`p`,{className:`agent-failure-recovery`,children:[kE[e.recovery?.action]||kE.none,e.preserved?.authoredState===`unchanged`?` Nothing in the scene changed.`:e.preserved?.authoredState===`unknown`?` Whether the scene changed is unknown.`:``]}),e.recovery?.retryAllowed&&(0,$.jsx)(`div`,{className:`agent-error-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`agent-ghost-button agent-error-retry`,onClick:t,children:`Retry`})})]})}function jE({provider:e,onSave:t,onRemove:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(``),l=e.authSource===`env`,u=e.authSource===`file`,d=`set by ${rE(e.id)}`,f=`agent-key-${e.id}`,p=async e=>{o(!0),c(``);try{await e(),i(``)}catch(e){c(e?.message||`The sidecar refused that key.`)}finally{o(!1)}};return(0,$.jsxs)(`div`,{className:`agent-key-row`,"data-provider":e.id,"data-provider-source":e.authSource||`none`,"data-provider-signed-in":e.signedIn?`true`:`false`,children:[(0,$.jsxs)(`div`,{className:`agent-key-head`,children:[(0,$.jsx)(CE,{tone:e.signedIn?`ok`:``,title:e.signedIn?`key configured`:`no key`}),(0,$.jsx)(`label`,{className:`agent-key-label`,htmlFor:f,children:e.label}),(0,$.jsx)(`span`,{className:`agent-key-source`,children:l?`environment`:u?`saved on this machine`:`no key`})]}),(0,$.jsxs)(`div`,{className:`agent-key-controls`,children:[(0,$.jsx)(`input`,{id:f,className:`agent-key-input`,type:`password`,autoComplete:`off`,spellCheck:`false`,"aria-label":`${e.label} API key`,placeholder:l?d:e.signedIn?`Replace key`:`Paste API key`,disabled:l||a,value:r,onChange:e=>{i(e.target.value),c(``)}}),(0,$.jsx)(`button`,{type:`button`,className:`agent-key-save`,disabled:l||a||!r.trim(),onClick:()=>p(()=>t(e.id,r)),children:`Save`}),u&&(0,$.jsx)(`button`,{type:`button`,className:`agent-ghost-button agent-key-remove`,disabled:a,onClick:()=>p(()=>n(e.id)),children:`Remove`})]}),s&&(0,$.jsx)(`p`,{className:`agent-key-error`,role:`alert`,children:s})]})}function ME({transport:e=null,sceneName:t=`CozyClay Scene`,defaultCollapsed:n=!1,onCollapsedChange:r=null,embedded:i=!1,hidden:a=!1,surface:o=`workflow`,buildContext:s=null,onImageAction:c=null,onI2vAction:l=null,onReceipt:u=null}){let d=(0,Q.useMemo)(()=>xT(o),[o]),f=(0,Q.useMemo)(()=>e||vE({surface:o}),[e,o]),p=f.mock?f.state:null,[m,h]=(0,Q.useState)(n),[g,_]=(0,Q.useState)(()=>d.persistWidth?wT():360),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(null),[w,T]=(0,Q.useState)(`loading`),[E,D]=(0,Q.useState)([]),[O,ee]=(0,Q.useState)([]),[k,te]=(0,Q.useState)(``),[ne,re]=(0,Q.useState)(`loading`),[ie,A]=(0,Q.useState)(null),j=(0,Q.useMemo)(()=>mT(E.find(e=>e.id===k)),[E,k]),M=(0,Q.useCallback)(e=>{te(e),A(null),OT(e)},[]),ae=(0,Q.useCallback)(e=>{let t=Array.isArray(e?.models)?e.models:[];if(!t.length)return!1;let n=Array.isArray(e?.providers)?e.providers:[];return ee(n),D(t),te(e=>jT(n,t,e)),re(`ready`),!0},[]),[oe,se]=(0,Q.useState)(!1),[ce,le]=(0,Q.useState)(null),[ue,de]=(0,Q.useState)(!1),[fe,pe]=(0,Q.useState)(null),[me,he]=(0,Q.useState)(()=>!i&&(globalThis.innerWidth||1440)<1100),[ge,_e]=(0,Q.useState)(!1),[ve,ye]=(0,Q.useState)(!1),[be,xe]=(0,Q.useState)([]),[Se,Ce]=(0,Q.useState)(`loading`),[we,Te]=(0,Q.useState)([]),[Ee,De]=(0,Q.useState)(``),[Oe,ke]=(0,Q.useState)(``),[Ae,je]=(0,Q.useState)(o!==`studio`),Me=(0,Q.useRef)(null),Ne=(0,Q.useRef)(null),Pe=(0,Q.useRef)(s);Pe.current=s;let Fe=(0,Q.useRef)(c);Fe.current=c;let Ie=(0,Q.useRef)(l);Ie.current=l;let Le=(0,Q.useRef)(u);Le.current=u;let N=(0,Q.useMemo)(()=>xE({transport:f,surface:o,buildContext:()=>Pe.current?.()??null,requestImageAction:e=>(Fe.current??f.applyImage?.bind(f)??bE)(e),onReceipt:e=>Le.current?.(e),onAuthLost:()=>T(`signed-out`)}),[o,f]),Re=(0,Q.useSyncExternalStore)(N.subscribe,N.getState,N.getState),{draft:ze,items:Be,pendingAttachments:Ve,quota:He,rateLimit:Ue,streaming:We}=Re;(0,Q.useEffect)(()=>{if(o!==`studio`){je(!0);return}let e=!1,t=null;try{t=globalThis.localStorage?.getItem(aT)}catch{}if(!t){je(!0);return}return(async()=>{try{let n=await f.loadSession(t);if(!Array.isArray(n?.transcript))throw Error(`missing transcript`);e||N.restore(n.transcript,n.sessionId||t)}catch(t){e||(N.newSession(),t?.status!==404&&De(`Previous conversation could not be restored`))}finally{e||je(!0)}})(),()=>{e=!0}},[o,N,f]),(0,Q.useEffect)(()=>{if(!(o!==`studio`||!Ae))try{globalThis.localStorage?.setItem(aT,Re.sessionId)}catch{}},[Re.sessionId,Ae,o]);let[Ge,Ke]=(0,Q.useState)(()=>Date.now()),qe=k?UT(Re,{now:Ge,toolLabel:e=>ST(e,d.toolLabels)}):ne===`failed`?{phase:`no-model`,kind:`terminal`,tone:`alert`,text:`No model available — the agent service did not answer with one`,ticking:!1}:{phase:`models`,kind:`live`,tone:`busy`,text:`Loading models…`,ticking:!1};(0,Q.useEffect)(()=>{if(!qe.ticking)return;let e=setInterval(()=>Ke(Date.now()),500);return()=>clearInterval(e)},[qe.ticking]);let Je=(0,Q.useCallback)(e=>e?.signedIn||e?.providersConfigured>0?d.imageEntitlement&&e?.entitlements?.image===!1?`no-entitlement`:`ready`:e?.pending?`signing-in`:`signed-out`,[d]),Ye=(0,Q.useCallback)(async()=>{try{let e=await f.status();return C(e),T(Je(e)),e}catch{return T(`signed-out`),null}},[Je,f]),Xe=(0,Q.useCallback)(async()=>{try{let e=await f.providers?.();if(!Array.isArray(e))throw Error(`no provider list`);xe(e),Ce(`ready`)}catch{xe([]),Ce(`failed`)}},[f]),Ze=(0,Q.useCallback)(async()=>{let e=Ye();await Xe(),await e;try{ae(await f.models())}catch{}},[ae,Ye,Xe,f]);(0,Q.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await f.status();if(e)return;C(t),T(Je(t))}catch{e||T(`signed-out`)}try{let t=await f.models();if(e)return;if(!ae(t)){re(`failed`);return}}catch{e||re(`failed`)}})(),()=>{e=!0}},[ae,Je,f]),(0,Q.useEffect)(()=>{if(w!==`signing-in`)return;let e=()=>{document.visibilityState!==`hidden`&&Ze()};return window.addEventListener(`focus`,e),window.addEventListener(`cozyclay:agent-auth-return`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),window.removeEventListener(`cozyclay:agent-auth-return`,e),document.removeEventListener(`visibilitychange`,e)}},[w,Ze]),(0,Q.useEffect)(()=>{!p||w!==`ready`||!k||[`streaming`,`rate-limited`,`error`].includes(p)&&(Be.length||N.send(`Give me a wide two-shot of this scene`,{attachFrame:!1,model:k}))},[w,Be.length,p,k,N]),(0,Q.useEffect)(()=>{if(i)return;let e=()=>he((globalThis.innerWidth||1440)<iT);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[i]),(0,Q.useEffect)(()=>{if(i)return;let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`b`&&(e.preventDefault(),h(e=>!e))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]),(0,Q.useEffect)(()=>{if(i)return;let e=()=>h(e=>!e);return window.addEventListener(`cozyclay:agent-panel-toggle`,e),()=>window.removeEventListener(`cozyclay:agent-panel-toggle`,e)},[i]),(0,Q.useEffect)(()=>{i||r?.(m)},[m,i,r]),(0,Q.useEffect)(()=>{if(a){Me.current&&Me.current===document.activeElement&&Me.current.blur();return}m||Me.current?.focus()},[w,m,a]),(0,Q.useEffect)(()=>{let e=Ne.current;e&&(e.scrollTop=e.scrollHeight)},[Be,We]);let Qe=(0,Q.useCallback)(e=>{e.preventDefault(),y(!0);let t=e.clientX,n=g,r=e=>_(CT(n+(t-e.clientX))),i=e=>{y(!1),window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i),TT(CT(n+(t-e.clientX)))};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)},[g]),$e=(0,Q.useCallback)(e=>{_(t=>{let n=CT(t+e);return TT(n),n})},[]),et=(0,Q.useCallback)(async e=>{let t=[],n=0;for(let r of e)try{t.push(await nT(r))}catch{n+=1}let r=t.length?N.addAttachments(t).rejected:0;le(r?zw:n?Vw:null)},[N]),tt=(0,Q.useCallback)(e=>{let{images:t,unsupported:n}=Gw(e);return t.length?(et(t),!0):(n&&le(Bw),n>0)},[et]),nt=(0,Q.useCallback)(e=>{tt(e.clipboardData)&&e.preventDefault()},[tt]),rt=(0,Q.useCallback)(e=>{Ww(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`,de(!0))},[]),it=(0,Q.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||de(!1)},[]),at=(0,Q.useCallback)(e=>{de(!1),tt(e.dataTransfer)&&e.preventDefault()},[tt]),ot=(0,Q.useCallback)(e=>(le(null),ke(``),N.send(e,{attachFrame:oe,model:k,effort:ie??void 0})),[oe,ie,k,N]),st=(0,Q.useCallback)(()=>N.stop(),[N]),ct=(0,Q.useCallback)(async e=>{if(!String(e??``).trim())return;le(null),ke(``);let t=await N.steer(e);t.ok||ke(t.message||`The running turn did not take that message.`)},[N]),lt=(0,Q.useCallback)(async()=>{T(`signing-in`);try{await f.signIn(),await Ze()}catch{T(`signed-out`)}},[Ze,f]),ut=(0,Q.useCallback)(async()=>{x(!1),await f.signOut().catch(()=>{}),C(null),N.newSession(),await Ze()},[Ze,N,f]),dt=(0,Q.useCallback)(()=>{if(o===`studio`)try{globalThis.localStorage?.removeItem(aT)}catch{}N.newSession(),_e(!1),x(!1),Me.current?.focus()},[N,o]),ft=(0,Q.useCallback)(async()=>{if(o!==`studio`)return;let e=!ge;if(_e(e),e)try{Te(await f.listSessions())}catch{Te([])}},[ge,o,f]),pt=(0,Q.useCallback)(async e=>{try{let t=await f.loadSession(e);if(!Array.isArray(t?.transcript))throw Error(`missing transcript`);N.restore(t.transcript,t.sessionId||e),_e(!1),De(``)}catch{De(`Previous conversation could not be restored`)}},[N,f]),mt=(0,Q.useCallback)(()=>{x(!1);let e=!ve;ye(e),e&&(Ce(`loading`),Xe())},[ve,Xe]),ht=(0,Q.useCallback)(async(e,t)=>{await f.setProviderKey(e,t),await Ze()},[Ze,f]),gt=(0,Q.useCallback)(async e=>{await f.removeProviderKey(e),await Ze()},[Ze,f]),_t=(0,Q.useCallback)(()=>{N.clearContext(),x(!1)},[N]),vt=(0,Q.useCallback)(()=>{let e=E.filter(e=>AT(O,e.id)),t=e.length?e:E,n=t[(t.findIndex(e=>e.id===k)+1)%t.length];n&&M(n.id),N.clearRateLimit()},[M,k,O,E,N]),yt=(0,Q.useCallback)(e=>{if(e.key===`Escape`&&We){e.preventDefault(),st();return}if(e.key===`Enter`&&!e.shiftKey){if(e.preventDefault(),We){d.steer&&ct(ze);return}ot(ze)}},[ze,d,ot,ct,st,We]),bt=Ue?`rate-limited`:w===`ready`?We?`streaming`:Be.some(e=>e.kind===`tool`&&e.status===`failed`||e.kind===`failure`)?`error`:`ready`:w,xt={"signed-out":``,"signing-in":`busy`,"no-entitlement":`warn`,ready:`ok`,streaming:`busy`,"rate-limited":`warn`,error:`alert`}[bt]||``,St=MT(Ue?.resetAt||He?.resetAt),Ct=w===`ready`||w===`no-entitlement`,wt=bt===`rate-limited`||!k||!AT(O,k);return m&&!i?(0,$.jsxs)(`aside`,{className:`agent-panel collapsed`,"data-agent-state":bt,"data-agent-collapsed":`true`,"aria-label":`Agent panel, collapsed`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-rail-toggle`,onClick:()=>h(!1),"aria-label":`Expand agent panel`,title:`Expand agent panel (Cmd/Ctrl+B)`,children:(0,$.jsx)(Tw,{size:13,style:{transform:`rotate(180deg)`}})}),(0,$.jsx)(CE,{tone:xt,title:bt}),(0,$.jsx)(`span`,{className:`agent-rail-label`,children:`Agent`})]}):(0,$.jsxs)(`aside`,{className:`agent-panel${v?` resizing`:``}${me&&!i?` overlay`:``}${i?` embedded`:``}`,style:i?void 0:{width:`${g}px`},hidden:i&&a,"data-agent-state":bt,"data-agent-width":i?void 0:g,"data-agent-overlay":me&&!i?`true`:`false`,"data-agent-embedded":i?`true`:`false`,"aria-label":`Agent`,children:[!i&&(0,$.jsx)(`div`,{role:`separator`,"aria-label":`Resize agent panel`,"aria-orientation":`vertical`,"aria-valuenow":g,"aria-valuemin":300,"aria-valuemax":560,tabIndex:0,className:`agent-resize`,onPointerDown:Qe,onKeyDown:e=>{e.key===`ArrowLeft`&&(e.preventDefault(),$e(16)),e.key===`ArrowRight`&&(e.preventDefault(),$e(-16))}}),(0,$.jsxs)(`header`,{className:`agent-header`,children:[(0,$.jsx)(CE,{tone:xt,title:bt}),(0,$.jsx)(`h2`,{className:`agent-title`,children:`Agent`}),(0,$.jsx)(`span`,{className:`agent-header-spacer`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-icon-button agent-new`,"aria-label":`New conversation`,title:`New conversation`,onClick:dt,children:(0,$.jsx)(fw,{size:14,"aria-hidden":`true`})}),d.history&&(0,$.jsxs)(`span`,{className:`agent-history-wrap`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-icon-button agent-history`,"aria-label":`History`,title:`History`,"aria-haspopup":`listbox`,"aria-expanded":o===`studio`?ge:void 0,onClick:o===`studio`?ft:void 0,disabled:o!==`studio`,children:(0,$.jsx)(ww,{size:13,"aria-hidden":`true`})}),o===`studio`&&ge&&(0,$.jsx)(`div`,{className:`agent-history-popover`,role:`listbox`,"aria-label":`Agent history`,children:we.length?we.map(e=>(0,$.jsxs)(`button`,{type:`button`,role:`option`,className:`agent-history-item`,onClick:()=>pt(e.sessionId),children:[(0,$.jsx)(`span`,{className:`agent-history-time`,children:SE(e.updatedAt)}),(0,$.jsx)(`span`,{className:`agent-history-text`,children:e.firstText||`Untitled conversation`})]},e.sessionId)):(0,$.jsx)(`span`,{className:`agent-history-empty`,children:`No previous conversations`})})]}),(0,$.jsxs)(`span`,{className:`agent-overflow`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-icon-button agent-overflow-toggle`,"aria-haspopup":`menu`,"aria-expanded":b,"aria-label":`More agent actions`,onClick:()=>x(e=>!e),children:(0,$.jsx)(gw,{size:13})}),b&&(0,$.jsxs)(`div`,{className:`agent-menu`,role:`menu`,children:[S?.signedIn&&(0,$.jsxs)(`div`,{className:`agent-account`,role:`presentation`,children:[(0,$.jsx)(`span`,{className:`agent-account-email`,children:S.email}),(0,$.jsx)(`span`,{className:`agent-plan-badge`,children:He?.plan||S.plan||`Free`}),St&&(0,$.jsxs)(`span`,{className:`agent-account-reset`,children:[`resets in `,St]})]}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,onClick:_t,children:`Clear context`}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:`agent-menu-keys`,"aria-expanded":ve,onClick:mt,children:`Provider keys…`}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,onClick:ut,children:`Sign out`})]})]}),!i&&(0,$.jsx)(`button`,{type:`button`,className:`agent-icon-button agent-collapse`,onClick:()=>h(!0),"aria-label":`Collapse agent panel`,title:`Collapse agent panel (Cmd/Ctrl+B)`,children:(0,$.jsx)(Tw,{size:13})})]}),Ee&&(0,$.jsx)(`div`,{className:`agent-toast`,role:`status`,children:Ee}),Oe&&(0,$.jsx)(`div`,{className:`agent-toast alert agent-steer-notice`,role:`alert`,children:Oe}),ve&&(0,$.jsxs)(`section`,{className:`agent-keys`,"aria-label":`Provider keys`,"data-agent-keys":`true`,children:[(0,$.jsxs)(`div`,{className:`agent-keys-head`,children:[(0,$.jsx)(`h3`,{className:`agent-keys-title`,children:`Provider keys`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-icon-button agent-keys-close`,"aria-label":`Close provider keys`,onClick:()=>ye(!1),children:(0,$.jsx)(sw,{size:11,"aria-hidden":`true`})})]}),(0,$.jsx)(`p`,{className:`agent-keys-hint`,children:`Keys are stored by the local CozyClay service and are never shown again.`}),Se===`loading`&&(0,$.jsx)(`p`,{className:`agent-keys-note`,children:`Loading providers…`}),Se===`failed`&&(0,$.jsx)(`p`,{className:`agent-keys-note alert`,role:`alert`,children:`The provider list is unavailable.`}),be.filter(e=>e.id!==`openai-codex`).map(e=>(0,$.jsx)(jE,{provider:e,onSave:ht,onRemove:gt},e.id))]}),(0,$.jsxs)(`div`,{className:`agent-transcript`,ref:Ne,"aria-live":`polite`,"aria-label":`Conversation`,"data-agent-transcript":`true`,children:[w===`signed-out`&&(0,$.jsxs)(`div`,{className:`agent-state-card`,"data-agent-card":`signed-out`,children:[(0,$.jsx)(`h3`,{children:`Sign in with ChatGPT`}),(0,$.jsx)(`p`,{children:`The agent runs against your ChatGPT plan. Sign-in happens in your browser — no token is ever stored in this page.`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-primary-button agent-signin`,onClick:lt,children:`Sign in with ChatGPT`})]}),w===`signing-in`&&(0,$.jsxs)(`div`,{className:`agent-state-card`,"data-agent-card":`signing-in`,children:[(0,$.jsx)(`span`,{className:`agent-spinner`,"aria-hidden":`true`}),(0,$.jsx)(`h3`,{children:`Waiting for your browser…`}),(0,$.jsx)(`p`,{children:`Finish the ChatGPT sign-in in the tab that just opened. This panel picks up the session when you come back.`})]}),w===`no-entitlement`&&(0,$.jsxs)(`div`,{className:`agent-state-card`,"data-agent-card":`no-entitlement`,children:[(0,$.jsx)(`h3`,{children:`Image generation is not on this plan`}),(0,$.jsxs)(`p`,{children:[`Signed in as `,S?.email||`your account`,`. Chat and tool calls work; image results need a plan with image generation.`]}),(0,$.jsx)(`button`,{type:`button`,className:`agent-primary-button`,onClick:()=>window.open(`https://chatgpt.com/#pricing`,`_blank`,`noopener,noreferrer`),children:`See plans`})]}),w===`ready`&&!Be.length&&!Ue&&(0,$.jsxs)(`div`,{className:`agent-state-card`,"data-agent-card":`ready`,children:[(0,$.jsx)(`h3`,{children:d.emptyTitle}),(0,$.jsx)(`p`,{children:d.emptyHint(t)}),(0,$.jsx)(`div`,{className:`agent-suggestions`,children:d.suggestions.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`agent-chip`,onClick:()=>{N.setDraft(e),Me.current?.focus()},children:e},e))})]}),Be.map(e=>e.kind===`user`?(0,$.jsxs)(`div`,{className:`agent-row user`,children:[e.attachments?.length>0&&(0,$.jsx)(`div`,{className:`agent-bubble-attachments`,children:e.attachments.map((t,n)=>(0,$.jsx)(`img`,{src:t.dataUrl,alt:t.name||`Attached image`,onClick:()=>pe({dataUrl:t.dataUrl,prompt:t.name})},`${e.id}-${n}`))}),(0,$.jsx)(`div`,{className:`agent-bubble`,children:e.text})]},e.id):e.kind===`assistant`?(0,$.jsx)(`div`,{className:`agent-row assistant`,children:(0,$.jsxs)(`div`,{className:`agent-assistant-text`,children:[e.text,We&&(0,$.jsx)(`span`,{className:`agent-caret`,children:`▌`})]})},e.id):e.kind===`tool`?(0,$.jsx)(`div`,{className:`agent-row`,children:(0,$.jsx)(wE,{call:e,presentation:d,onRetry:()=>ot(Re.lastPrompt)})},e.id):e.kind===`job`?(0,$.jsx)(`div`,{className:`agent-row`,children:(0,$.jsx)(DE,{job:e,onStop:st,onAccept:e=>N.acceptJob(e.jobId)})},e.id):e.kind===`receipt`?(0,$.jsx)(`div`,{className:`agent-row`,children:(0,$.jsx)(OE,{item:e})},e.id):e.kind===`failure`?(0,$.jsx)(`div`,{className:`agent-row`,children:(0,$.jsx)(AE,{failure:e.failure,onRetry:()=>ot(Re.lastPrompt)})},e.id):(0,$.jsx)(`div`,{className:`agent-row`,children:(0,$.jsx)(TE,{image:e,onUse:e=>N.applyImage(e.id),onUndo:e=>N.undoImage(e.id),onRegenerate:()=>ot(Re.lastPrompt),onOpen:pe})},e.id)),Ue&&(0,$.jsx)(EE,{resetAt:Ue.resetAt,onRetry:()=>{N.clearRateLimit(),ot(Re.lastPrompt)},onSwitchModel:vt})]}),Ct&&(0,$.jsxs)(`div`,{className:`agent-activity`,"data-agent-activity":qe.phase,"data-agent-activity-kind":qe.kind,role:`status`,"aria-live":`polite`,children:[(0,$.jsx)(`span`,{className:`agent-activity-indicator ${qe.tone}`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`agent-activity-text`,children:qe.text})]}),Ct&&(0,$.jsxs)(`div`,{className:`agent-composer`,"data-agent-dropping":ue?`true`:`false`,onDragOver:wt?void 0:rt,onDragLeave:wt?void 0:it,onDrop:wt?void 0:at,children:[Ve.length>0&&(0,$.jsx)(`ul`,{className:`agent-attachments`,"aria-label":`Attached images`,children:Ve.map(e=>(0,$.jsxs)(`li`,{className:`agent-attachment`,children:[(0,$.jsx)(`img`,{src:e.dataUrl,alt:e.name||`Attached image`}),(0,$.jsx)(`button`,{type:`button`,className:`agent-attachment-remove`,"aria-label":`Remove ${e.name||`attached image`}`,onClick:()=>N.removeAttachment(e.id),children:(0,$.jsx)(sw,{size:10,"aria-hidden":`true`})})]},e.id))}),ce&&(0,$.jsx)(`p`,{className:`agent-attachment-notice`,role:`status`,children:ce}),(0,$.jsxs)(`div`,{className:`agent-field`,children:[(0,$.jsx)(`textarea`,{ref:Me,className:`agent-input`,"aria-label":`Message the agent`,placeholder:bt===`rate-limited`?`Composer is paused`:k?d.composerPlaceholder:`Waiting for the model list…`,value:ze,disabled:wt,onChange:e=>N.setDraft(e.target.value),onKeyDown:yt,onPaste:nt,onDragOver:rt,onDrop:at}),(0,$.jsxs)(`div`,{className:`agent-composer-controls`,children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-attach-chip`,"aria-pressed":oe,"aria-label":`Attach current frame`,title:`Attach current frame`,onClick:()=>se(e=>!e),children:oe?(0,$.jsx)(`span`,{className:`agent-attach-thumb`,"aria-hidden":`true`}):(0,$.jsx)(mw,{size:13,"aria-hidden":`true`})}),(0,$.jsx)(`select`,{className:`agent-model-select`,"aria-label":`Model`,title:`Model`,value:k,disabled:!E.length,onChange:e=>M(e.target.value),children:O.length?O.map(e=>(0,$.jsx)(`optgroup`,{label:e.label,children:e.models.length?e.models.map(t=>(0,$.jsx)(`option`,{value:t.key,disabled:!e.signedIn,children:e.signedIn?t.label:`${t.label} — add key`},t.key)):(0,$.jsx)(`option`,{value:`${e.id}/`,disabled:!0,children:e.signedIn?`No models`:`No models — add key`})},e.id)):E.length?E.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id)):(0,$.jsx)(`option`,{value:``,children:ne===`failed`?`No model available`:`Loading models…`})}),j.length>0&&(0,$.jsx)(`select`,{className:`agent-model-select agent-effort-select`,"aria-label":`Reasoning effort`,title:`Reasoning effort`,value:ie??j[0],onChange:e=>A(e.target.value),children:j.map((e,t)=>(0,$.jsx)(`option`,{value:e,title:t===0?`Default for this model`:void 0,children:e},e))}),(0,$.jsx)(`span`,{className:`agent-composer-spacer`,"aria-hidden":`true`}),o===`studio`&&Ie.current&&(0,$.jsx)(`button`,{type:`button`,className:`agent-attach-chip agent-i2v-action`,"data-testid":`i2v-agent-action`,"aria-label":`Generate motion`,title:`Generate motion from this message`,disabled:wt||!ze.trim()||We,onClick:()=>{let e=ze.trim();N.setDraft(``),Ie.current?.(e)},children:(0,$.jsx)(yw,{size:13,"aria-hidden":`true`})}),We?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`agent-send stop agent-stop`,onClick:st,children:`Stop`}),d.steer&&(0,$.jsx)(`button`,{type:`button`,className:`agent-send agent-steer`,disabled:!ze.trim(),onClick:()=>ct(ze),children:`Steer`})]}):(0,$.jsx)(`button`,{type:`button`,className:`agent-send`,"aria-label":`Send`,title:`Send (Enter)`,disabled:wt||!ze.trim(),onClick:()=>ot(ze),children:(0,$.jsx)(Ow,{size:14,"aria-hidden":`true`})})]})]})]}),Ct&&d.imageHint&&(0,$.jsx)(`p`,{className:`agent-footer-hint`,children:d.imageHint}),fe&&(0,$.jsx)(`button`,{type:`button`,className:`agent-lightbox`,"aria-label":`Close image preview`,onClick:()=>pe(null),children:(0,$.jsx)(`img`,{src:fe.dataUrl,alt:fe.prompt||`Generated image`})})]})}var NE=`cozyclay:scene-change`,PE=`cozyclay.scene-playback.v1`,FE=`cozyclay:scene-playback`;function IE(e,t){return!e||typeof e!=`object`?!1:[e.assetId,e.sourceAssetId,e.matteAssetId].includes(t)}function LE(e,t,{height:n=kg,placement:r={},name:i=t?.name}={}){if(!t||!Kp(t.id))return{document:e,object:null,changed:!1,reason:`invalid-asset`};let a=e&&typeof e==`object`?e:wx(),o=Array.isArray(a.scenes)?a.scenes:[],s=Cx(o,a.activeSceneId);if(s<0||!o[s])return{document:a,object:null,changed:!1,reason:`no-active-scene`};let c=o[s],l=Array.isArray(c.objects)?c.objects:[];if(l.some(e=>IE(e,t.id)))return{document:a,object:null,changed:!1,reason:`already-in-scene`};let u=Jg({assetId:t.id,aspect:$p(t)??1,height:n,name:i},l,r);if(!u)return{document:a,object:null,changed:!1,reason:`cutout-failed`};let d=o.map((e,t)=>t===s?{...e,objects:[...l,u]}:e);return{document:{...a,version:Number.isInteger(a.version)?a.version:4,scenes:d},object:u,changed:!0,reason:`added`}}function RE(e,t,n={}){if(typeof t!=`string`||!t.trim()||!n||typeof n!=`object`)return{document:e,changed:!1,reason:`invalid-motion`};let r=e&&typeof e==`object`?e:wx(),i=Array.isArray(r.scenes)?r.scenes:[],a=Cx(i,r.activeSceneId);if(a<0||!i[a])return{document:r,changed:!1,reason:`no-active-scene`};let o=i[a],s=o.stage&&typeof o.stage==`object`?o.stage:{},c=Array.isArray(s.characters)?s.characters:[],l=c.find(e=>e?.id===t);if(!l)return{document:r,changed:!1,reason:`character-not-found`};let u=typeof n.url==`string`&&n.url?n.url:typeof n.objectUrl==`string`&&n.objectUrl?n.objectUrl:null;if(!u)return{document:r,changed:!1,reason:`motion-url-missing`};let d={...l.motionRef&&typeof l.motionRef==`object`?l.motionRef:{},...n.motionRef&&typeof n.motionRef==`object`?n.motionRef:{},url:u},f=c.map(e=>e?.id===t?{...e,motionRef:d}:e),p={...o,stage:{...s,characters:f}};return{document:{...r,scenes:i.map((e,t)=>t===a?p:e)},changed:!0,reason:`updated`,characterId:t,motionRef:d}}function zE(e,t,n={}){let r=RE(n.document??BE(n.storage),e,t);return r.changed&&VE(r.document,n),r}function BE(e=globalThis.localStorage){return Ox(e?.getItem?.(`cozyclay.scenes.v4`)??null).document}function VE(e,{storage:t=globalThis.localStorage,target:n=globalThis}={}){let r=e&&typeof e==`object`?e:wx(),i=kx(r);try{t?.setItem?.(zb,i)}catch{}try{n?.dispatchEvent?.(new CustomEvent(NE,{detail:r}))}catch{}return r}function HE(e,{storage:t=globalThis.localStorage,target:n=globalThis}={}){if(typeof e!=`function`)return()=>{};let r=t=>{let n=t?.detail;n&&typeof n==`object`&&e(n,{source:`same-tab`})},i=t=>{if(t?.key!==`cozyclay.scenes.v4`||!t.newValue)return;let n=Ox(t.newValue);n.status===`corrupt`||n.status===`future`||!n.document||e(n.document,{source:`storage`})};return n?.addEventListener?.(NE,r),n?.addEventListener?.(`storage`,i),()=>{n?.removeEventListener?.(NE,r),n?.removeEventListener?.(`storage`,i)}}function UE(e,{storage:t=globalThis.localStorage,target:n=globalThis}={}){let r={activeSceneId:typeof e?.activeSceneId==`string`?e.activeSceneId:null,frame:Number.isFinite(Number(e?.frame))?Math.max(0,Math.round(Number(e.frame))):null,playing:typeof e?.playing==`boolean`&&e.playing,issuedAt:Date.now()};try{t?.setItem?.(PE,JSON.stringify(r))}catch{}try{n?.dispatchEvent?.(new CustomEvent(FE,{detail:r}))}catch{}return r}function WE(e,{storage:t=globalThis.localStorage,target:n=globalThis}={}){if(typeof e!=`function`)return()=>{};let r=t=>{try{let n=typeof t==`string`?JSON.parse(t):t;n&&typeof n==`object`&&e(n)}catch{}},i=e=>r(e?.detail),a=e=>{e?.key===`cozyclay.scene-playback.v1`&&e.newValue&&r(e.newValue)};return n?.addEventListener?.(FE,i),n?.addEventListener?.(`storage`,a),()=>{n?.removeEventListener?.(FE,i),n?.removeEventListener?.(`storage`,a)}}async function GE(e,{importer:t=am,remember:n=hC,importOptions:r}={}){return n(await t(e,{maxDimension:zp,...r||{}}))}async function KE(e,t={}){let n=await GE(e,t),r=LE(t.document??BE(t.storage),n,t);return r.changed&&VE(r.document,t),{...r,asset:n}}var qE=`follow the reference clip's framing and camera motion exactly`,JE=`clay previs, neutral look`,YE=`motion and blocking come from the reference; keep timing`;function XE(e){if(!Number.isFinite(e)||e<=0)return`normal`;let t=18/Math.tan(e*Math.PI/360);return t<=20?`wide`:t<=40?`normal`:`long`}function ZE(e){return`${Number(e.toFixed(2))}s`}function QE(e){let t=[];return e?.dolly&&t.push(`smooth dolly move`),e?.crane&&t.push(`gentle crane move`),e?.rail&&t.push(`sliding rail move`),t.length>0?t.join(`; `):`locked-off camera, no move`}var $E=[`front`,`front right`,`right`,`back right`,`back`,`back left`,`left`,`front left`];function eD(e){if(!Number.isFinite(e))return``;let t=(e%360+360)%360;return $E[Math.round(t/45)%8]}function tD(e){return Number.isFinite(e)?e>=50?`high`:e<=10?`low`:`level`:``}function nD(e){return Number.isFinite(e)?e>=.8?`strong`:e>=.35?`moderate`:`dim`:`moderate`}function rD(e){return e?`${[tD(e.elevationDeg),eD(e.azimuthDeg)].filter(Boolean).join(` `)||`even`} key light, ${nD(e.intensity)}`:`no key light, ambient fill`}function iD(e,t={}){let n=t.target===`video`?`video`:`image`,r=t.referenceOwnsCamera!==!1,i=Math.max(0,(e.frameRange?.end??0)-(e.frameRange?.start??0)+1)/(e.fps||24),a=typeof e.intent==`string`?e.intent.trim():``,o=[`SHOT: ${e.shotTitle||`untitled shot`}, ${ZE(i)}, ${e.aspect||``}`.trimEnd(),`LENS: ${e.focalMm}mm, ${XE(e.fovDeg)} shot`,r?`CAMERA: ${qE}`:`CAMERA: ${QE(e.cameraMove)}`,`LIGHT: ${rD(e.keyLight)}`,`CAST: ${(e.cast||[]).map(e=>e.name).join(`, `)||`none`}`,`LOOK: ${a||JE}`];return n===`video`&&o.push(`MOTION: ${YE}`),o.join(`
|
|
17
|
+
`)}export{RS as $,Ui as $a,Xd as $c,Pf as $i,di as $l,Jg as $n,as as $o,fm as $r,Df as $s,Db as $t,zC as A,_u as Aa,Qe as Ac,T as Ai,Hu as Al,ay as An,ra as Ao,og as Ar,Dl as As,Yb as At,yt as Au,qS as B,jf as Ba,ke as Bc,io as Bi,qt as Bl,Gv as Bn,ql as Bo,sm as Br,Br as Bs,bx as Bt,vl as Bu,pw as C,Rs as Ca,Ge as Cc,fu as Ci,G as Cl,Yy as Cn,qd as Co,t_ as Cr,Nl as Cs,Nx as Ct,dr as Cu,cw as D,fr as Da,Ye as Dc,Bs as Di,qi as Dl,$v as Dn,Ii as Do,Jh as Dr,jl as Ds,Lx as Dt,Ur as Du,lw as E,tf as Ea,Je as Ec,Vl as Ei,nr as El,Cy as En,Vi as Eo,Ih as Er,Fl as Es,Fx as Et,Xt as Eu,_C as F,Ce as Fa,Me as Fc,id as Fi,oa as Fl,oy as Fn,_t as Fo,Ip as Fr,ne as Fs,ax as Ft,F as Fu,eC as G,Ut as Ga,Ie as Gc,Es as Gi,ll as Gl,S_ as Gn,Uu as Go,nm as Gr,Mu as Gs,Sx as Gt,S as Gu,QS as H,Ms as Ha,st as Hc,af as Hi,Wt as Hl,sv as Hn,nl as Ho,lm as Hr,rl as Hs,fx as Ht,un as Hu,oC as I,we as Ia,Ne as Ic,Wf as Ii,Gt as Il,uy as In,$t as Io,Rp as Ir,re as Is,ux as It,Xf as Iu,zx as J,Cr as Ja,Dt as Jc,W as Ji,Qf as Jl,cg as Jn,qo as Jo,Kp as Jr,zf as Js,ix as Jt,g as Ju,GS as K,Ls as Ka,Fe as Kc,Lf as Ki,or as Kl,kg as Kn,ts as Ko,am as Kr,xo as Ks,xx as Kt,b as Ku,$S as L,Cs as La,Pe as Lc,wt as Li,zt as Ll,Kv as Ln,Qt as Lo,$p as Lr,te as Ls,Zb as Lt,dn as Lu,mC as M,Ft as Ma,Be as Mc,Ed as Mi,Pu as Ml,cy as Mn,vt as Mo,ag as Mr,ee as Ms,zb as Mt,_l as Mu,gC as N,Lt as Na,N as Nc,rd as Ni,hf as Nl,fy as Nn,ht as No,jh as Nr,k as Ns,Cx as Nt,sn as Nu,KC as O,ur as Oa,Xe as Oc,fd as Oi,cl as Ol,ty as On,de as Oo,Xh as Or,kl as Os,Kb as Ot,pl as Ou,hC as P,su as Pa,Le as Pc,bd as Pi,ba as Pl,sy as Pn,gt as Po,oh as Pr,ie as Ps,yx as Pt,on as Pu,xS as Q,du as Qa,Ma as Qc,Ou as Qi,dl as Ql,Wg as Qn,os as Qo,em as Qr,ss as Qs,wb as Qt,aC as R,E as Ra,Et as Rc,Ko as Ri,Ht as Rl,Lv as Rn,Rt as Ro,cm as Rr,St as Rs,wx as Rt,xl as Ru,hw as S,Ul as Sa,it as Sc,tu as Si,le as Sl,Sy as Sn,qu as So,f_ as Sr,Na as Ss,yS as St,pr as Su,uw as T,ks as Ta,qe as Tc,zd as Ti,ro as Tl,Ty as Tn,zi as To,Eg as Tr,Ml as Ts,Ix as Tt,lr as Tu,ZS as U,Kt as Ua,Re as Uc,fi as Ui,$l as Ul,Z as Un,wr as Uo,Qp as Ur,Lu as Us,nx as Ut,P as Uu,sC as V,Gl as Va,ot as Vc,Jl as Vi,Vt as Vl,Wv as Vn,wa as Vo,gm as Vr,Xu as Vs,Ax as Vt,hn as Vu,KS as W,Bt as Wa,ze as Wc,Rf as Wi,w as Wl,E_ as Wn,yu as Wo,mm as Wr,pc as Ws,Ox as Wt,mn as Wu,pS as X,Ts as Xa,Oe as Xc,ce as Xi,Zt as Xl,yg as Xn,sc as Xo,Vp as Xr,xf as Xs,jb as Xt,ES as Y,_n as Ya,De as Yc,Ju as Yi,pd as Yl,Fg as Yn,oc as Yo,qp as Yr,Iu as Ys,Pb as Yt,Yx as Z,Qc as Za,El as Zc,iu as Zi,ul as Zl,vg as Zn,Il as Zo,hm as Zr,fs as Zs,Sb as Zt,Sw as _,ws as _a,nt as _c,yp as _i,gl as _l,ib as _n,hu as _o,Kg as _r,Hn as _s,WS as _t,B as _u,BE as a,$d as aa,lc as ac,Ep as ai,D as al,Qy as an,To as ao,Zg as ar,j as as,TS as at,Wd as au,vw as b,ic as ba,tt as bc,Bu as bi,Gf as bl,Xy as bn,It as bo,n_ as br,V as bs,Qx as bt,hs as bu,ME as c,Xn as ca,Zl as cc,$f as ci,al as cl,$y as cn,Jt as co,a_ as cr,cu as cs,SS as ct,se as cu,Mw as d,ys as da,ut as dc,hp as di,lt as dl,_b as dn,Ss as do,b_ as dr,ft as ds,zS as dt,ve as du,xs as ea,js as ec,pm as ei,Vu as el,Tb as en,U as eo,Xg as er,A as es,hS as et,fl as eu,jw as f,_s as fa,ct as fc,pp as fi,We as fl,fb as fn,me as fo,Tg as fr,mt as fs,US as ft,fe as fu,Cw as g,dd as ga,Ae as gc,gp as gi,Tl as gl,pb as gn,td as go,m_ as gr,Gu as gs,LS as gt,R as gu,Dw as h,Kf as ha,Se as hc,lp as hi,Zr as hl,rb as hn,tl as ho,p_ as hr,aa as hs,FS as ht,ue as hu,UE as i,O as ia,cc as ic,kp as ii,Ud as il,eb as in,gs as io,Yg as ir,ae as is,IS as it,Ri as iu,wC as j,ji as ja,at as jc,xd as ji,uc as jl,iy as jn,Hl as jo,Qh as jr,Al as js,Bb as jt,bt as ju,RC as k,ao as ka,Ze as kc,Uf as ki,ef as kl,ly as kn,ta as ko,$h as kr,Ol as ks,Jb as kt,xt as ku,iE as l,en as la,Ve as lc,_p as li,He as ll,nb as ln,Ef as lo,v_ as lr,Ku as ls,vS as lt,ye as lu,Aw as m,As as ma,Tt as mc,ep as mi,jt as ml,ab as mn,Tf as mo,i_ as mr,C as ms,bS as mt,ge as mu,zE as n,qs as na,Y as nc,um as ni,Ee as nl,gb as nn,Xr as no,$g as nr,oe as ns,jS as nt,Hi as nu,HE as o,H as oa,z as oc,Ap as oi,Nt as ol,mb as on,Do as oo,e_ as or,kt as os,Zx as ot,Kd as ou,Nw as p,pu as pa,Ue as pc,vp as pi,Ot as pl,ob as pn,bu as po,wg as pr,pt as ps,mS as pt,he as pu,Rx as q,zs as qa,je as qc,Fi as qi,vu as ql,Dg as qn,pf as qo,Jp as qr,il as qs,kx as qt,v as qu,KE as r,Os as ra,Dd as rc,wp as ri,cr as rl,hb as rn,Yr as ro,y_ as rr,M as rs,VS as rt,Li as ru,WE as s,Yl as sa,Ql as sc,np as si,gn as sl,sb as sn,Jd as so,Cg as sr,At as ss,Xx as st,Sl as su,iD as t,Ds as ta,Td as tc,om as ti,Te as tl,Eb as tn,pe as to,qg as tr,Wl as ts,HS as tt,Bi as tu,Pw as u,vs as ua,xn as uc,fp as ui,dt as ul,Zy as un,Vr as uo,g_ as ur,ou as us,_S as ut,_e as uu,bw as v,bs as va,$e as vc,Ct as vi,mc as vl,vy as vn,er as vo,h_ as vr,nf as vs,MS as vt,sr as vu,fw as w,fc as wa,Ke as wc,Hd as wi,yf as wl,Dy as wn,_o as wo,hg as wr,Pl as ws,Px as wt,Yt as wu,_w as x,ac as xa,rt as xc,Bd as xi,Yc as xl,Ey as xn,co as xo,Rg as xr,Ga as xs,lS as xt,ms as xu,yw as y,gu as ya,et as yc,be as yi,ol as yl,_y as yn,Pt as yo,r_ as yr,Gn as ys,BS as yt,eu as yu,YS as z,zu as za,xe as zc,Kl as zi,cd as zl,gv as zn,Mt as zo,Xp as zr,Xl as zs,hx as zt,fn as zu};
|