mjswan 0.5.0 → 0.5.1
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.
|
@@ -12822,7 +12822,7 @@ void main() {
|
|
|
12822
12822
|
center = quatVec(quat, center) + translate;
|
|
12823
12823
|
quaternion = quatQuat(quat, quaternion);
|
|
12824
12824
|
}
|
|
12825
|
-
`);new ys(new ue(-1,-1,-1),new ue(1,1,1)),new ue(-1,-3,1).normalize(),new xt(1,1,1),new xt(.5,.5,1),new ue(1,1,1);new ys(new ue(-2,-1,-2),new ue(2,5,2)),new ue(0,-1,0),new xt(1,1,1),new xt(.25,.25,.5),new ue(.1,1,.1);const sP=class _w{static createButton(e,t={}){const r=navigator.xr;if(!r)return null;const i=r,s=document.createElement("button");e.xr.enabled=!0,e.xr.setReferenceSpaceType("local");function a(){let h=null;async function p(m){console.log("onSessionStarted"),m.addEventListener("end",A),await e.xr.setSession(m),s.textContent="EXIT VR",h=m}function A(){console.log("onSessionEnded"),h?.removeEventListener("end",A),s.textContent="ENTER VR",h=null}s.style.display="",s.style.cursor="pointer",s.style.left="calc(50% - 100px)",s.style.width="200px",s.style.height="100px",s.textContent="ENTER VR";const y={...t,optionalFeatures:[...t.optionalFeatures||[]]};s.onmouseenter=()=>{s.style.opacity="1.0"},s.onmouseleave=()=>{s.style.opacity="0.5"},s.onclick=()=>{h===null?(console.log("requesting session"),i.requestSession("immersive-vr",y).then(p)):(console.log("ending session"),h.end())}}function o(){s.style.display="none",s.style.cursor="auto",s.style.left="calc(50% - 75px)",s.style.width="150px",s.onmouseenter=null,s.onmouseleave=null,s.onclick=null}function l(){o(),s.textContent="VR NOT SUPPORTED"}function c(h){o(),console.warn("Exception when trying to call xr.isSessionSupported",h),s.textContent="VR NOT ALLOWED"}function d(h){h.style.position="absolute",h.style.bottom="20px",h.style.padding="12px 6px",h.style.border="1px solid #fff",h.style.borderRadius="4px",h.style.background="rgba(0,0,0,0.1)",h.style.color="#fff",h.style.font="normal 13px sans-serif",h.style.textAlign="center",h.style.opacity="0.5",h.style.outline="none",h.style.zIndex="999"}return s.id="VRButton",s.style.display="none",d(s),i.isSessionSupported("immersive-vr").then(h=>{h?a():l(),h&&_w.xrSessionIsGranted&&s.click()}).catch(c),s}static registerSessionGrantedListener(){const e=navigator.xr;if(!e)return null;const t=e;/WebXRViewer\//i.test(navigator.userAgent)||t.addEventListener("sessiongranted",()=>{_w.xrSessionIsGranted=!0})}};sP.xrSessionIsGranted=!1;let nZ=sP;nZ.registerSessionGrantedListener();var aP=(n=>(n.w="wrist",n.t0="thumb-metacarpal",n.t1="thumb-phalanx-proximal",n.t2="thumb-phalanx-distal",n.t3="thumb-tip",n.i0="index-finger-metacarpal",n.i1="index-finger-phalanx-proximal",n.i2="index-finger-phalanx-intermediate",n.i3="index-finger-phalanx-distal",n.i4="index-finger-tip",n.m0="middle-finger-metacarpal",n.m1="middle-finger-phalanx-proximal",n.m2="middle-finger-phalanx-intermediate",n.m3="middle-finger-phalanx-distal",n.m4="middle-finger-tip",n.r0="ring-finger-metacarpal",n.r1="ring-finger-phalanx-proximal",n.r2="ring-finger-phalanx-intermediate",n.r3="ring-finger-phalanx-distal",n.r4="ring-finger-tip",n.p0="pinky-finger-metacarpal",n.p1="pinky-finger-phalanx-proximal",n.p2="pinky-finger-phalanx-intermediate",n.p3="pinky-finger-phalanx-distal",n.p4="pinky-finger-tip",n))(aP||{});const rZ=Object.keys(aP);rZ.length;new ue(0,0,-1),new ue(0,0,1),new ue(-1,0,0),new ue(1,0,0),new ue(0,1,0),new ue(0,-1,0);new ue(0,0,-1),new ue(0,0,1),new ue(-1,0,0),new ue(1,0,0),new ue(0,1,0),new ue(0,-1,0);new ue(0,0,1),new ue(0,0,-1);new ue(0,-1,0),new ue(0,1,0),new ue(-1,0,0),new ue(1,0,0);const jv=Math.PI/180,iZ=new Cn().setFromEuler(new ji(Math.PI,0,0));function oP(n,e){const t=e.scale??1,r=e.xOffset??0,i=e.yOffset??0,s=e.zOffset??0,a=(e.roll??0)*jv,o=(e.pitch??0)*jv,l=(e.yaw??0)*jv;n.scale.setScalar(t);const c=new Cn().setFromEuler(new ji(o,l,a));n.quaternion.copy(iZ.clone().multiply(c)),n.position.set(r*t,s*t,i*t)}function tB(n,e){const t=n.url;if(!t)throw new Error("SplatConfig.url must be resolved before calling loadSplat. Use App.tsx resolvedSplatConfig.");const r=new LC({url:t});return oP(r,n),e.add(r),r}function nB(n,e){e.remove(n),n.dispose?.()}function rB(n,e){if(e===cV)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===rw||e===VN){let t=n.getIndex();if(t===null){const a=[],o=n.getAttribute("position");if(o!==void 0){for(let l=0;l<o.count;l++)a.push(l);n.setIndex(a),t=n.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),n}const r=t.count-2,i=[];if(e===rw)for(let a=1;a<=r;a++)i.push(t.getX(0)),i.push(t.getX(a)),i.push(t.getX(a+1));else for(let a=0;a<r;a++)a%2===0?(i.push(t.getX(a)),i.push(t.getX(a+1)),i.push(t.getX(a+2))):(i.push(t.getX(a+2)),i.push(t.getX(a+1)),i.push(t.getX(a)));i.length/3!==r&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const s=n.clone();return s.setIndex(i),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),n}class sZ extends lu{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new uZ(t)}),this.register(function(t){return new dZ(t)}),this.register(function(t){return new vZ(t)}),this.register(function(t){return new _Z(t)}),this.register(function(t){return new bZ(t)}),this.register(function(t){return new fZ(t)}),this.register(function(t){return new pZ(t)}),this.register(function(t){return new AZ(t)}),this.register(function(t){return new mZ(t)}),this.register(function(t){return new cZ(t)}),this.register(function(t){return new gZ(t)}),this.register(function(t){return new hZ(t)}),this.register(function(t){return new xZ(t)}),this.register(function(t){return new yZ(t)}),this.register(function(t){return new oZ(t)}),this.register(function(t){return new wZ(t)}),this.register(function(t){return new EZ(t)})}load(e,t,r,i){const s=this;let a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){const c=fp.extractUrlBase(e);a=fp.resolveURL(c,this.path)}else a=fp.extractUrlBase(e);this.manager.itemStart(e);const o=function(c){i?i(c):console.error(c),s.manager.itemError(e),s.manager.itemEnd(e)},l=new IC(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{s.parse(c,a,function(d){t(d),s.manager.itemEnd(e)},o)}catch(d){o(d)}},r,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,r,i){let s;const a={},o={},l=new TextDecoder;if(typeof e=="string")s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===lP){try{a[cn.KHR_BINARY_GLTF]=new CZ(e)}catch(h){i&&i(h);return}s=JSON.parse(a[cn.KHR_BINARY_GLTF].content)}else s=JSON.parse(l.decode(e));else s=e;if(s.asset===void 0||s.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const c=new FZ(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](c);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),o[h.name]=h,a[h.name]=!0}if(s.extensionsUsed)for(let d=0;d<s.extensionsUsed.length;++d){const h=s.extensionsUsed[d],p=s.extensionsRequired||[];switch(h){case cn.KHR_MATERIALS_UNLIT:a[h]=new lZ;break;case cn.KHR_DRACO_MESH_COMPRESSION:a[h]=new IZ(s,this.dracoLoader);break;case cn.KHR_TEXTURE_TRANSFORM:a[h]=new SZ;break;case cn.KHR_MESH_QUANTIZATION:a[h]=new BZ;break;default:p.indexOf(h)>=0&&o[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}c.setExtensions(a),c.setPlugins(o),c.parse(r,i)}parseAsync(e,t){const r=this;return new Promise(function(i,s){r.parse(e,t,i,s)})}}function aZ(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const cn={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class oZ{constructor(e){this.parser=e,this.name=cn.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let r=0,i=t.length;r<i;r++){const s=t[r];s.extensions&&s.extensions[this.name]&&s.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,s.extensions[this.name].light)}}_loadLight(e){const t=this.parser,r="light:"+e;let i=t.cache.get(r);if(i)return i;const s=t.json,l=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e];let c;const d=new xt(16777215);l.color!==void 0&&d.setRGB(l.color[0],l.color[1],l.color[2],ii);const h=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new lw(d),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new hQ(d),c.distance=h;break;case"spot":c=new dQ(d),c.distance=h,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),ba(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),i=Promise.resolve(c),t.cache.add(r,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,r=this.parser,s=r.json.nodes[e],o=(s.extensions&&s.extensions[this.name]||{}).light;return o===void 0?null:this._loadLight(o).then(function(l){return r._getNodeRef(t.cache,o,l)})}}class lZ{constructor(){this.name=cn.KHR_MATERIALS_UNLIT}getMaterialType(){return zc}extendParams(e,t,r){const i=[];e.color=new xt(1,1,1),e.opacity=1;const s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){const a=s.baseColorFactor;e.color.setRGB(a[0],a[1],a[2],ii),e.opacity=a[3]}s.baseColorTexture!==void 0&&i.push(r.assignTexture(e,"map",s.baseColorTexture,gr))}return Promise.all(i)}}class cZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name].emissiveStrength;return s!==void 0&&(t.emissiveIntensity=s),Promise.resolve()}}class uZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&s.push(r.assignTexture(t,"clearcoatMap",a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&s.push(r.assignTexture(t,"clearcoatRoughnessMap",a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(s.push(r.assignTexture(t,"clearcoatNormalMap",a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){const o=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Dt(o,o)}return Promise.all(s)}}class dZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_DISPERSION}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name];return t.dispersion=s.dispersion!==void 0?s.dispersion:0,Promise.resolve()}}class hZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&s.push(r.assignTexture(t,"iridescenceMap",a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&s.push(r.assignTexture(t,"iridescenceThicknessMap",a.iridescenceThicknessTexture)),Promise.all(s)}}class fZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_SHEEN}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[];t.sheenColor=new xt(0,0,0),t.sheenRoughness=0,t.sheen=1;const a=i.extensions[this.name];if(a.sheenColorFactor!==void 0){const o=a.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],ii)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&s.push(r.assignTexture(t,"sheenColorMap",a.sheenColorTexture,gr)),a.sheenRoughnessTexture!==void 0&&s.push(r.assignTexture(t,"sheenRoughnessMap",a.sheenRoughnessTexture)),Promise.all(s)}}class pZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&s.push(r.assignTexture(t,"transmissionMap",a.transmissionTexture)),Promise.all(s)}}class AZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_VOLUME}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];t.thickness=a.thicknessFactor!==void 0?a.thicknessFactor:0,a.thicknessTexture!==void 0&&s.push(r.assignTexture(t,"thicknessMap",a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;const o=a.attenuationColor||[1,1,1];return t.attenuationColor=new xt().setRGB(o[0],o[1],o[2],ii),Promise.all(s)}}class mZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_IOR}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name];return t.ior=s.ior!==void 0?s.ior:1.5,Promise.resolve()}}class gZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_SPECULAR}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];t.specularIntensity=a.specularFactor!==void 0?a.specularFactor:1,a.specularTexture!==void 0&&s.push(r.assignTexture(t,"specularIntensityMap",a.specularTexture));const o=a.specularColorFactor||[1,1,1];return t.specularColor=new xt().setRGB(o[0],o[1],o[2],ii),a.specularColorTexture!==void 0&&s.push(r.assignTexture(t,"specularColorMap",a.specularColorTexture,gr)),Promise.all(s)}}class yZ{constructor(e){this.parser=e,this.name=cn.EXT_MATERIALS_BUMP}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];return t.bumpScale=a.bumpFactor!==void 0?a.bumpFactor:1,a.bumpTexture!==void 0&&s.push(r.assignTexture(t,"bumpMap",a.bumpTexture)),Promise.all(s)}}class xZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&s.push(r.assignTexture(t,"anisotropyMap",a.anisotropyTexture)),Promise.all(s)}}class vZ{constructor(e){this.parser=e,this.name=cn.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,r=t.json,i=r.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const s=i.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(r.extensionsRequired&&r.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,a)}}class _Z{constructor(e){this.parser=e,this.name=cn.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,r=this.parser,i=r.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const a=s.extensions[t],o=i.images[a.source];let l=r.textureLoader;if(o.uri){const c=r.options.manager.getHandler(o.uri);c!==null&&(l=c)}return r.loadTextureImage(e,a.source,l)}}class bZ{constructor(e){this.parser=e,this.name=cn.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,r=this.parser,i=r.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const a=s.extensions[t],o=i.images[a.source];let l=r.textureLoader;if(o.uri){const c=r.options.manager.getHandler(o.uri);c!==null&&(l=c)}return r.loadTextureImage(e,a.source,l)}}class wZ{constructor(e){this.name=cn.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,r=t.bufferViews[e];if(r.extensions&&r.extensions[this.name]){const i=r.extensions[this.name],s=this.parser.getDependency("buffer",i.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(o){const l=i.byteOffset||0,c=i.byteLength||0,d=i.count,h=i.byteStride,p=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(d,h,p,i.mode,i.filter).then(function(A){return A.buffer}):a.ready.then(function(){const A=new ArrayBuffer(d*h);return a.decodeGltfBuffer(new Uint8Array(A),d,h,p,i.mode,i.filter),A})})}else return null}}class EZ{constructor(e){this.name=cn.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,r=t.nodes[e];if(!r.extensions||!r.extensions[this.name]||r.mesh===void 0)return null;const i=t.meshes[r.mesh];for(const c of i.primitives)if(c.mode!==rs.TRIANGLES&&c.mode!==rs.TRIANGLE_STRIP&&c.mode!==rs.TRIANGLE_FAN&&c.mode!==void 0)return null;const a=r.extensions[this.name].attributes,o=[],l={};for(const c in a)o.push(this.parser.getDependency("accessor",a[c]).then(d=>(l[c]=d,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const d=c.pop(),h=d.isGroup?d.children:[d],p=c[0].count,A=[];for(const y of h){const m=new Ft,x=new ue,g=new Cn,_=new ue(1,1,1),b=new aw(y.geometry,y.material,p);for(let w=0;w<p;w++)l.TRANSLATION&&x.fromBufferAttribute(l.TRANSLATION,w),l.ROTATION&&g.fromBufferAttribute(l.ROTATION,w),l.SCALE&&_.fromBufferAttribute(l.SCALE,w),b.setMatrixAt(w,m.compose(x,g,_));for(const w in l)if(w==="_COLOR_0"){const C=l[w];b.instanceColor=new $g(C.array,C.itemSize,C.normalized)}else w!=="TRANSLATION"&&w!=="ROTATION"&&w!=="SCALE"&&y.geometry.setAttribute(w,l[w]);zn.prototype.copy.call(b,y),this.parser.assignFinalMaterial(b),A.push(b)}return d.isGroup?(d.clear(),d.add(...A),d):A[0]}))}}const lP="glTF",Lf=12,iB={JSON:1313821514,BIN:5130562};class CZ{constructor(e){this.name=cn.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Lf),r=new TextDecoder;if(this.header={magic:r.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==lP)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-Lf,s=new DataView(e,Lf);let a=0;for(;a<i;){const o=s.getUint32(a,!0);a+=4;const l=s.getUint32(a,!0);if(a+=4,l===iB.JSON){const c=new Uint8Array(e,Lf+a,o);this.content=r.decode(c)}else if(l===iB.BIN){const c=Lf+a;this.body=e.slice(c,c+o)}a+=o}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class IZ{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=cn.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const r=this.json,i=this.dracoLoader,s=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(const d in a){const h=bw[d]||d.toLowerCase();o[h]=a[d]}for(const d in e.attributes){const h=bw[d]||d.toLowerCase();if(a[d]!==void 0){const p=r.accessors[e.attributes[d]],A=Ld[p.componentType];c[h]=A.name,l[h]=p.normalized===!0}}return t.getDependency("bufferView",s).then(function(d){return new Promise(function(h,p){i.decodeDracoFile(d,function(A){for(const y in A.attributes){const m=A.attributes[y],x=l[y];x!==void 0&&(m.normalized=x)}h(A)},o,c,ii,p)})})}}class SZ{constructor(){this.name=cn.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class BZ{constructor(){this.name=cn.KHR_MESH_QUANTIZATION}}class cP extends Gp{constructor(e,t,r,i){super(e,t,r,i)}copySampleValue_(e){const t=this.resultBuffer,r=this.sampleValues,i=this.valueSize,s=e*i*3+i;for(let a=0;a!==i;a++)t[a]=r[s+a];return t}interpolate_(e,t,r,i){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=o*2,c=o*3,d=i-t,h=(r-t)/d,p=h*h,A=p*h,y=e*c,m=y-c,x=-2*A+3*p,g=A-p,_=1-x,b=g-p+h;for(let w=0;w!==o;w++){const C=a[m+w+o],S=a[m+w+l]*d,M=a[y+w+o],T=a[y+w]*d;s[w]=_*C+b*S+x*M+g*T}return s}}const MZ=new Cn;class TZ extends cP{interpolate_(e,t,r,i){const s=super.interpolate_(e,t,r,i);return MZ.fromArray(s).normalize().toArray(s),s}}const rs={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Ld={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},sB={9728:yr,9729:ar,9984:FN,9985:Ag,9986:Zf,9987:Sa},aB={33071:ls,33648:Lg,10497:Fl},Wv={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},bw={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},El={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},RZ={CUBICSPLINE:void 0,LINEAR:Tp,STEP:Mp},qv={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function DZ(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new qd({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Co})),n.DefaultMaterial}function bc(n,e,t){for(const r in t.extensions)n[r]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[r]=t.extensions[r])}function ba(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function kZ(n,e,t){let r=!1,i=!1,s=!1;for(let c=0,d=e.length;c<d;c++){const h=e[c];if(h.POSITION!==void 0&&(r=!0),h.NORMAL!==void 0&&(i=!0),h.COLOR_0!==void 0&&(s=!0),r&&i&&s)break}if(!r&&!i&&!s)return Promise.resolve(n);const a=[],o=[],l=[];for(let c=0,d=e.length;c<d;c++){const h=e[c];if(r){const p=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):n.attributes.position;a.push(p)}if(i){const p=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):n.attributes.normal;o.push(p)}if(s){const p=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):n.attributes.color;l.push(p)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then(function(c){const d=c[0],h=c[1],p=c[2];return r&&(n.morphAttributes.position=d),i&&(n.morphAttributes.normal=h),s&&(n.morphAttributes.color=p),n.morphTargetsRelative=!0,n})}function NZ(n,e){if(n.updateMorphTargets(),e.weights!==void 0)for(let t=0,r=e.weights.length;t<r;t++)n.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(n.morphTargetInfluences.length===t.length){n.morphTargetDictionary={};for(let r=0,i=t.length;r<i;r++)n.morphTargetDictionary[t[r]]=r}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function QZ(n){let e;const t=n.extensions&&n.extensions[cn.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Yv(t.attributes):e=n.indices+":"+Yv(n.attributes)+":"+n.mode,n.targets!==void 0)for(let r=0,i=n.targets.length;r<i;r++)e+=":"+Yv(n.targets[r]);return e}function Yv(n){let e="";const t=Object.keys(n).sort();for(let r=0,i=t.length;r<i;r++)e+=t[r]+":"+n[t[r]]+";";return e}function ww(n){switch(n){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function PZ(n){return n.search(/\.jpe?g($|\?)/i)>0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const LZ=new Ft;class FZ{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new aZ,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let r=!1,i=-1,s=!1,a=-1;if(typeof navigator<"u"){const o=navigator.userAgent;r=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);i=r&&l?parseInt(l[1],10):-1,s=o.indexOf("Firefox")>-1,a=s?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||r&&i<17||s&&a<98?this.textureLoader=new N9(this.options.manager):this.textureLoader=new U9(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new IC(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const r=this,i=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([r.getDependencies("scene"),r.getDependencies("animation"),r.getDependencies("camera")])}).then(function(a){const o={scene:a[0][i.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:i.asset,parser:r,userData:{}};return bc(s,o,i),ba(o,i),Promise.all(r._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],r=this.json.meshes||[];for(let i=0,s=t.length;i<s;i++){const a=t[i].joints;for(let o=0,l=a.length;o<l;o++)e[a[o]].isBone=!0}for(let i=0,s=e.length;i<s;i++){const a=e[i];a.mesh!==void 0&&(this._addNodeRef(this.meshCache,a.mesh),a.skin!==void 0&&(r[a.mesh].isSkinnedMesh=!0)),a.camera!==void 0&&this._addNodeRef(this.cameraCache,a.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,r){if(e.refs[t]<=1)return r;const i=r.clone(),s=(a,o)=>{const l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(const[c,d]of a.children.entries())s(d,o.children[c])};return s(r,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let r=0;r<t.length;r++){const i=e(t[r]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const r=[];for(let i=0;i<t.length;i++){const s=e(t[i]);s&&r.push(s)}return r}getDependency(e,t){const r=e+":"+t;let i=this.cache.get(r);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(s){return s.loadNode&&s.loadNode(t)});break;case"mesh":i=this._invokeOne(function(s){return s.loadMesh&&s.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(s){return s.loadBufferView&&s.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(s){return s.loadMaterial&&s.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(s){return s.loadTexture&&s.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(s){return s.loadAnimation&&s.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(s){return s!=this&&s.getDependency&&s.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(r,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const r=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(s,a){return r.getDependency(e,a)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],r=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[cn.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(s,a){r.load(fp.resolveURL(t.uri,i.path),s,void 0,function(){a(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(r){const i=t.byteLength||0,s=t.byteOffset||0;return r.slice(s,s+i)})}loadAccessor(e){const t=this,r=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const a=Wv[i.type],o=Ld[i.componentType],l=i.normalized===!0,c=new o(i.count*a);return Promise.resolve(new cr(c,a,l))}const s=[];return i.bufferView!==void 0?s.push(this.getDependency("bufferView",i.bufferView)):s.push(null),i.sparse!==void 0&&(s.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(s).then(function(a){const o=a[0],l=Wv[i.type],c=Ld[i.componentType],d=c.BYTES_PER_ELEMENT,h=d*l,p=i.byteOffset||0,A=i.bufferView!==void 0?r.bufferViews[i.bufferView].byteStride:void 0,y=i.normalized===!0;let m,x;if(A&&A!==h){const g=Math.floor(p/A),_="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+g+":"+i.count;let b=t.cache.get(_);b||(m=new c(o,g*A,i.count*A/d),b=new a9(m,A/d),t.cache.add(_,b)),x=new xC(b,l,p%A/d,y)}else o===null?m=new c(i.count*l):m=new c(o,p,i.count*l),x=new cr(m,l,y);if(i.sparse!==void 0){const g=Wv.SCALAR,_=Ld[i.sparse.indices.componentType],b=i.sparse.indices.byteOffset||0,w=i.sparse.values.byteOffset||0,C=new _(a[1],b,i.sparse.count*g),S=new c(a[2],w,i.sparse.count*l);o!==null&&(x=new cr(x.array.slice(),x.itemSize,x.normalized)),x.normalized=!1;for(let M=0,T=C.length;M<T;M++){const R=C[M];if(x.setX(R,S[M*l]),l>=2&&x.setY(R,S[M*l+1]),l>=3&&x.setZ(R,S[M*l+2]),l>=4&&x.setW(R,S[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}x.normalized=y}return x})}loadTexture(e){const t=this.json,r=this.options,s=t.textures[e].source,a=t.images[s];let o=this.textureLoader;if(a.uri){const l=r.manager.getHandler(a.uri);l!==null&&(o=l)}return this.loadTextureImage(e,s,o)}loadTextureImage(e,t,r){const i=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,r).then(function(d){d.flipY=!1,d.name=a.name||o.name||"",d.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(d.name=o.uri);const p=(s.samplers||{})[a.sampler]||{};return d.magFilter=sB[p.magFilter]||ar,d.minFilter=sB[p.minFilter]||Sa,d.wrapS=aB[p.wrapS]||Fl,d.wrapT=aB[p.wrapT]||Fl,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==yr&&d.minFilter!==ar,i.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const r=this,i=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const a=i.images[e],o=self.URL||self.webkitURL;let l=a.uri||"",c=!1;if(a.bufferView!==void 0)l=r.getDependency("bufferView",a.bufferView).then(function(h){c=!0;const p=new Blob([h],{type:a.mimeType});return l=o.createObjectURL(p),l});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(l).then(function(h){return new Promise(function(p,A){let y=p;t.isImageBitmapLoader===!0&&(y=function(m){const x=new lr(m);x.needsUpdate=!0,p(x)}),t.load(fp.resolveURL(h,s.path),y,void 0,A)})}).then(function(h){return c===!0&&o.revokeObjectURL(l),ba(h,a),h.userData.mimeType=a.mimeType||PZ(a.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),h});return this.sourceCache[e]=d,d}assignTexture(e,t,r,i){const s=this;return this.getDependency("texture",r.index).then(function(a){if(!a)return null;if(r.texCoord!==void 0&&r.texCoord>0&&(a=a.clone(),a.channel=r.texCoord),s.extensions[cn.KHR_TEXTURE_TRANSFORM]){const o=r.extensions!==void 0?r.extensions[cn.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=s.associations.get(a);a=s.extensions[cn.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),s.associations.set(a,l)}}return i!==void 0&&(a.colorSpace=i),e[t]=a,a})}assignFinalMaterial(e){const t=e.geometry;let r=e.material;const i=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+r.uuid;let l=this.cache.get(o);l||(l=new aQ,Ks.prototype.copy.call(l,r),l.color.copy(r.color),l.map=r.map,l.sizeAttenuation=!1,this.cache.add(o,l)),r=l}else if(e.isLine){const o="LineBasicMaterial:"+r.uuid;let l=this.cache.get(o);l||(l=new sQ,Ks.prototype.copy.call(l,r),l.color.copy(r.color),l.map=r.map,this.cache.add(o,l)),r=l}if(i||s||a){let o="ClonedMaterial:"+r.uuid+":";i&&(o+="derivative-tangents:"),s&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=r.clone(),s&&(l.vertexColors=!0),a&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(r))),r=l}e.material=r}getMaterialType(){return qd}loadMaterial(e){const t=this,r=this.json,i=this.extensions,s=r.materials[e];let a;const o={},l=s.extensions||{},c=[];if(l[cn.KHR_MATERIALS_UNLIT]){const h=i[cn.KHR_MATERIALS_UNLIT];a=h.getMaterialType(),c.push(h.extendParams(o,s,t))}else{const h=s.pbrMetallicRoughness||{};if(o.color=new xt(1,1,1),o.opacity=1,Array.isArray(h.baseColorFactor)){const p=h.baseColorFactor;o.color.setRGB(p[0],p[1],p[2],ii),o.opacity=p[3]}h.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",h.baseColorTexture,gr)),o.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,o.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",h.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",h.metallicRoughnessTexture))),a=this._invokeOne(function(p){return p.getMaterialType&&p.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(p){return p.extendMaterialParams&&p.extendMaterialParams(e,o)})))}s.doubleSided===!0&&(o.side=is);const d=s.alphaMode||qv.OPAQUE;if(d===qv.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,d===qv.MASK&&(o.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&a!==zc&&(c.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new Dt(1,1),s.normalTexture.scale!==void 0)){const h=s.normalTexture.scale;o.normalScale.set(h,h)}if(s.occlusionTexture!==void 0&&a!==zc&&(c.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&a!==zc){const h=s.emissiveFactor;o.emissive=new xt().setRGB(h[0],h[1],h[2],ii)}return s.emissiveTexture!==void 0&&a!==zc&&c.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,gr)),Promise.all(c).then(function(){const h=new a(o);return s.name&&(h.name=s.name),ba(h,s),t.associations.set(h,{materials:e}),s.extensions&&bc(i,h,s),h})}createUniqueName(e){const t=Bn.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,r=this.extensions,i=this.primitiveCache;function s(o){return r[cn.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return oB(l,o,t)})}const a=[];for(let o=0,l=e.length;o<l;o++){const c=e[o],d=QZ(c),h=i[d];if(h)a.push(h.promise);else{let p;c.extensions&&c.extensions[cn.KHR_DRACO_MESH_COMPRESSION]?p=s(c):p=oB(new wr,c,t),i[d]={primitive:c,promise:p},a.push(p)}}return Promise.all(a)}loadMesh(e){const t=this,r=this.json,i=this.extensions,s=r.meshes[e],a=s.primitives,o=[];for(let l=0,c=a.length;l<c;l++){const d=a[l].material===void 0?DZ(this.cache):this.getDependency("material",a[l].material);o.push(d)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(l){const c=l.slice(0,l.length-1),d=l[l.length-1],h=[];for(let A=0,y=d.length;A<y;A++){const m=d[A],x=a[A];let g;const _=c[A];if(x.mode===rs.TRIANGLES||x.mode===rs.TRIANGLE_STRIP||x.mode===rs.TRIANGLE_FAN||x.mode===void 0)g=s.isSkinnedMesh===!0?new l9(m,_):new Kn(m,_),g.isSkinnedMesh===!0&&g.normalizeSkinWeights(),x.mode===rs.TRIANGLE_STRIP?g.geometry=rB(g.geometry,VN):x.mode===rs.TRIANGLE_FAN&&(g.geometry=rB(g.geometry,rw));else if(x.mode===rs.LINES)g=new p9(m,_);else if(x.mode===rs.LINE_STRIP)g=new bC(m,_);else if(x.mode===rs.LINE_LOOP)g=new A9(m,_);else if(x.mode===rs.POINTS)g=new m9(m,_);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+x.mode);Object.keys(g.geometry.morphAttributes).length>0&&NZ(g,s),g.name=t.createUniqueName(s.name||"mesh_"+e),ba(g,s),x.extensions&&bc(i,g,x),t.assignFinalMaterial(g),h.push(g)}for(let A=0,y=h.length;A<y;A++)t.associations.set(h[A],{meshes:e,primitives:A});if(h.length===1)return s.extensions&&bc(i,h[0],s),h[0];const p=new cs;s.extensions&&bc(i,p,s),t.associations.set(p,{meshes:e});for(let A=0,y=h.length;A<y;A++)p.add(h[A]);return p})}loadCamera(e){let t;const r=this.json.cameras[e],i=r[r.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return r.type==="perspective"?t=new zr(qN.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):r.type==="orthographic"&&(t=new U0(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),r.name&&(t.name=this.createUniqueName(r.name)),ba(t,r),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],r=[];for(let i=0,s=t.joints.length;i<s;i++)r.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?r.push(this.getDependency("accessor",t.inverseBindMatrices)):r.push(null),Promise.all(r).then(function(i){const s=i.pop(),a=i,o=[],l=[];for(let c=0,d=a.length;c<d;c++){const h=a[c];if(h){o.push(h);const p=new Ft;s!==null&&p.fromArray(s.array,c*16),l.push(p)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new vC(o,l)})}loadAnimation(e){const t=this.json,r=this,i=t.animations[e],s=i.name?i.name:"animation_"+e,a=[],o=[],l=[],c=[],d=[];for(let h=0,p=i.channels.length;h<p;h++){const A=i.channels[h],y=i.samplers[A.sampler],m=A.target,x=m.node,g=i.parameters!==void 0?i.parameters[y.input]:y.input,_=i.parameters!==void 0?i.parameters[y.output]:y.output;m.node!==void 0&&(a.push(this.getDependency("node",x)),o.push(this.getDependency("accessor",g)),l.push(this.getDependency("accessor",_)),c.push(y),d.push(m))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(d)]).then(function(h){const p=h[0],A=h[1],y=h[2],m=h[3],x=h[4],g=[];for(let b=0,w=p.length;b<w;b++){const C=p[b],S=A[b],M=y[b],T=m[b],R=x[b];if(C===void 0)continue;C.updateMatrix&&C.updateMatrix();const k=r._createAnimationTracks(C,S,M,T,R);if(k)for(let G=0;G<k.length;G++)g.push(k[G])}const _=new S9(s,void 0,g);return ba(_,i),_})}createNodeMesh(e){const t=this.json,r=this,i=t.nodes[e];return i.mesh===void 0?null:r.getDependency("mesh",i.mesh).then(function(s){const a=r._getNodeRef(r.meshCache,i.mesh,s);return i.weights!==void 0&&a.traverse(function(o){if(o.isMesh)for(let l=0,c=i.weights.length;l<c;l++)o.morphTargetInfluences[l]=i.weights[l]}),a})}loadNode(e){const t=this.json,r=this,i=t.nodes[e],s=r._loadNodeShallow(e),a=[],o=i.children||[];for(let c=0,d=o.length;c<d;c++)a.push(r.getDependency("node",o[c]));const l=i.skin===void 0?Promise.resolve(null):r.getDependency("skin",i.skin);return Promise.all([s,Promise.all(a),l]).then(function(c){const d=c[0],h=c[1],p=c[2];p!==null&&d.traverse(function(A){A.isSkinnedMesh&&A.bind(p,LZ)});for(let A=0,y=h.length;A<y;A++)d.add(h[A]);return d})}_loadNodeShallow(e){const t=this.json,r=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const s=t.nodes[e],a=s.name?i.createUniqueName(s.name):"",o=[],l=i._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&o.push(l),s.camera!==void 0&&o.push(i.getDependency("camera",s.camera).then(function(c){return i._getNodeRef(i.cameraCache,s.camera,c)})),i._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){o.push(c)}),this.nodeCache[e]=Promise.all(o).then(function(c){let d;if(s.isBone===!0?d=new iQ:c.length>1?d=new cs:c.length===1?d=c[0]:d=new zn,d!==c[0])for(let h=0,p=c.length;h<p;h++)d.add(c[h]);if(s.name&&(d.userData.name=s.name,d.name=a),ba(d,s),s.extensions&&bc(r,d,s),s.matrix!==void 0){const h=new Ft;h.fromArray(s.matrix),d.applyMatrix4(h)}else s.translation!==void 0&&d.position.fromArray(s.translation),s.rotation!==void 0&&d.quaternion.fromArray(s.rotation),s.scale!==void 0&&d.scale.fromArray(s.scale);if(!i.associations.has(d))i.associations.set(d,{});else if(s.mesh!==void 0&&i.meshCache.refs[s.mesh]>1){const h=i.associations.get(d);i.associations.set(d,{...h})}return i.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,r=this.json.scenes[e],i=this,s=new cs;r.name&&(s.name=i.createUniqueName(r.name)),ba(s,r),r.extensions&&bc(t,s,r);const a=r.nodes||[],o=[];for(let l=0,c=a.length;l<c;l++)o.push(i.getDependency("node",a[l]));return Promise.all(o).then(function(l){for(let d=0,h=l.length;d<h;d++)s.add(l[d]);const c=d=>{const h=new Map;for(const[p,A]of i.associations)(p instanceof Ks||p instanceof lr)&&h.set(p,A);return d.traverse(p=>{const A=i.associations.get(p);A!=null&&h.set(p,A)}),h};return i.associations=c(s),s})}_createAnimationTracks(e,t,r,i,s){const a=[],o=e.name?e.name:e.uuid,l=[];El[s.path]===El.weights?e.traverse(function(p){p.morphTargetInfluences&&l.push(p.name?p.name:p.uuid)}):l.push(o);let c;switch(El[s.path]){case El.weights:c=Yd;break;case El.rotation:c=Jd;break;case El.translation:case El.scale:c=Xd;break;default:r.itemSize===1?c=Yd:c=Xd;break}const d=i.interpolation!==void 0?RZ[i.interpolation]:Tp,h=this._getArrayFromAccessor(r);for(let p=0,A=l.length;p<A;p++){const y=new c(l[p]+"."+El[s.path],t.array,h,d);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(y),a.push(y)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const r=ww(t.constructor),i=new Float32Array(t.length);for(let s=0,a=t.length;s<a;s++)i[s]=t[s]*r;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(r){const i=this instanceof Jd?TZ:cP;return new i(this.times,this.values,this.getValueSize()/3,r)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function zZ(n,e,t){const r=e.attributes,i=new ys;if(r.POSITION!==void 0){const o=t.json.accessors[r.POSITION],l=o.min,c=o.max;if(l!==void 0&&c!==void 0){if(i.set(new ue(l[0],l[1],l[2]),new ue(c[0],c[1],c[2])),o.normalized){const d=ww(Ld[o.componentType]);i.min.multiplyScalar(d),i.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const s=e.targets;if(s!==void 0){const o=new ue,l=new ue;for(let c=0,d=s.length;c<d;c++){const h=s[c];if(h.POSITION!==void 0){const p=t.json.accessors[h.POSITION],A=p.min,y=p.max;if(A!==void 0&&y!==void 0){if(l.setX(Math.max(Math.abs(A[0]),Math.abs(y[0]))),l.setY(Math.max(Math.abs(A[1]),Math.abs(y[1]))),l.setZ(Math.max(Math.abs(A[2]),Math.abs(y[2]))),p.normalized){const m=ww(Ld[p.componentType]);l.multiplyScalar(m)}o.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(o)}n.boundingBox=i;const a=new Ua;i.getCenter(a.center),a.radius=i.min.distanceTo(i.max)/2,n.boundingSphere=a}function oB(n,e,t){const r=e.attributes,i=[];function s(a,o){return t.getDependency("accessor",a).then(function(l){n.setAttribute(o,l)})}for(const a in r){const o=bw[a]||a.toLowerCase();o in n.attributes||i.push(s(r[a],o))}if(e.indices!==void 0&&!n.index){const a=t.getDependency("accessor",e.indices).then(function(o){n.setIndex(o)});i.push(a)}return pn.workingColorSpace!==ii&&"COLOR_0"in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${pn.workingColorSpace}" not supported.`),ba(n,e),zZ(n,e,t),Promise.all(i).then(function(){return e.targets!==void 0?kZ(n,e.targets,t):n})}async function lB(n,e){const i=(await new sZ().loadAsync(n)).scene;return i.traverse(s=>{s.visible=!1}),e.add(i),i}function cB(n,e){e.remove(n),n.traverse(t=>{const r=t;r.geometry?.dispose(),Array.isArray(r.material)?r.material.forEach(i=>i.dispose()):r.material?.dispose()})}class uB{constructor(e){this.onPointer=s=>{s.type==="pointerdown"?(this.start(s.clientX,s.clientY),this.mouseDown=!0):s.type==="pointermove"&&this.mouseDown?this.move(s.clientX,s.clientY):s.type==="pointerup"&&this.end()},this.scene=e.scene,this.renderer=e.renderer,this.camera=e.camera,this.container=e.container,this.controls=e.controls,this.draggableBodyIds=e.draggableBodyIds??null,this.mousePos=new Dt,this.raycaster=new X9,this.raycaster.params.Line.threshold=.1,this.grabDistance=0,this.active=!1,this.mouseDown=!1,this.physicsObject=null,this.localHit=new ue,this.worldHit=new ue,this.currentWorld=new ue,this.offset=new ue,this.arrow=new cs;const t=new Ah(.008,.008,1),r=new qd({color:16737095,transparent:!0,opacity:.5,metalness:0,roughness:.2});this.arrowShaft=new Kn(t,r),this.arrowShaft.position.y=.5;const i=new EC(.03,.1);this.arrowHead=new Kn(i,r),this.arrowHead.position.y=1,this.arrow.add(this.arrowShaft),this.arrow.add(this.arrowHead),this.arrow.visible=!1,this.scene.add(this.arrow),this.container.addEventListener("pointerdown",this.onPointer,!0),document.addEventListener("pointermove",this.onPointer,!0),document.addEventListener("pointerup",this.onPointer,!0)}updateRaycaster(e,t){const r=this.renderer.domElement.getBoundingClientRect();this.mousePos.x=(e-r.left)/r.width*2-1,this.mousePos.y=-((t-r.top)/r.height)*2+1,this.raycaster.setFromCamera(this.mousePos,this.camera)}start(e,t){this.physicsObject=null,this.updateRaycaster(e,t);const r=this.raycaster.intersectObjects(this.scene.children,!0);for(const i of r){const s=i.object;if(!this.shouldIgnoreForDrag(s)&&this.isDraggableObject(s)){this.physicsObject=s,this.grabDistance=i.distance;const a=this.raycaster.ray.origin.clone().addScaledVector(this.raycaster.ray.direction,this.grabDistance);this.localHit.copy(s.worldToLocal(a.clone())),this.worldHit.copy(a),this.currentWorld.copy(a),this.offset.set(0,0,0),this.arrow.position.copy(a),this.arrow.visible=!1,this.active=!0,this.controls.enabled=!1;break}}}setDraggableBodyIds(e){this.draggableBodyIds=e}isDraggableObject(e){if(!("bodyID"in e)||typeof e.bodyID!="number")return!1;const t=e.bodyID;return!(t<=0||this.draggableBodyIds&&!this.draggableBodyIds.has(t))}shouldIgnoreForDrag(e){let t=e;for(;t;){if(t.userData?.ignoreDragForce===!0)return!0;t=t.parent}return!1}move(e,t){this.active&&this.updateRaycaster(e,t)}update(){if(!this.physicsObject||!this.active)return;this.raycaster.setFromCamera(this.mousePos,this.camera),this.currentWorld.copy(this.raycaster.ray.origin.clone().addScaledVector(this.raycaster.ray.direction,this.grabDistance)),this.worldHit.copy(this.localHit),this.physicsObject.localToWorld(this.worldHit),this.offset.copy(this.currentWorld).sub(this.worldHit),this.arrow.position.copy(this.worldHit);const e=this.offset.length();if(e>.001){this.arrow.visible=!0;const t=this.offset.clone().normalize();this.arrow.quaternion.setFromUnitVectors(new ue(0,1,0),t);const r=.1,i=Math.max(.01,e-r);this.arrowShaft.scale.y=i,this.arrowShaft.position.y=i/2,this.arrowHead.position.y=i+r/2}else this.arrow.visible=!1}end(){this.physicsObject=null,this.active=!1,this.controls.enabled=!0,this.arrow.visible=!1,this.mouseDown=!1}dispose(){this.container.removeEventListener("pointerdown",this.onPointer,!0),document.removeEventListener("pointermove",this.onPointer,!0),document.removeEventListener("pointerup",this.onPointer,!0),this.arrow.parent&&this.scene.remove(this.arrow),this.arrowShaft.geometry.dispose(),this.arrowHead.geometry.dispose(),this.arrowShaft.material&&this.arrowShaft.material.dispose()}}const Ff={lookat:[0,0,0],distance:4,elevation:-30,azimuth:45,fovy:45};function UZ(n,e,t,r){const i=t*Math.PI/180,s=r*Math.PI/180,a=n[0]+e*Math.cos(i)*Math.cos(s),o=n[1]+e*Math.cos(i)*Math.sin(s),l=n[2]-e*Math.sin(i);return zl([a,o,l])}function OZ(n,e,t,r,i){const s={trackBodyId:null,prevBodyPos:null};t.enabled=!0;const a=n?.lookat??Ff.lookat,o=n?.distance??Ff.distance,l=n?.elevation??Ff.elevation,c=n?.azimuth??Ff.azimuth;if(e.fov=n?.fovy??Ff.fovy,e.updateProjectionMatrix(),e.position.copy(UZ(a,o,l,c)),t.target.copy(zl(a)),t.update(),!n)return s;const d=n.originType??"AUTO";if(d==="ASSET_BODY"&&n.bodyName&&r){const h=n.bodyName,p=n.entityName,A=p?`${p}/${h}`:null;for(let y=0;y<r.nbody;y++){const m=r.body(y).name;if(m===h||m===A||m.endsWith(`/${h}`)){s.trackBodyId=y;break}}s.trackBodyId===null&&console.warn(`[Camera] bodyName: body "${n.bodyName}" not found.`)}else(d==="AUTO"||d==="ASSET_ROOT")&&r&&r.nbody>1&&(s.trackBodyId=1);if(s.trackBodyId!==null&&i){const h=zl(i.xpos.slice(s.trackBodyId*3,s.trackBodyId*3+3));e.position.add(h),t.target.add(h),s.prevBodyPos=h,t.update()}return s}function $Z(n,e,t,r){if(r.trackBodyId!==null){const i=r.trackBodyId,s=zl(n.xpos.slice(i*3,i*3+3));if(r.prevBodyPos!==null){const a=s.clone().sub(r.prevBodyPos);e.position.add(a),t.target.add(a)}r.prevBodyPos=s}}const Rl=class Rl{constructor(e){this.MAX_CACHE_SIZE=5,this.mujoco=e,this.cache=new Map,this.metrics={totalScenes:0,totalMemoryBytes:0,oldestAccessTime:Date.now(),newestAccessTime:Date.now(),cacheHits:0,cacheMisses:0,evictions:0}}static getInstance(e){return Rl.instance||(Rl.instance=new Rl(e),console.log("[SceneCache] Created new cache manager singleton")),Rl.instance}static resetInstance(){Rl.instance=null}normalizeScenePath(e){return e?DC(e):""}has(e){const t=this.normalizeScenePath(e);return this.cache.has(t)}get(e){const t=this.normalizeScenePath(e),r=this.cache.get(t);return r?(r.lastAccessed=Date.now(),this.metrics.cacheHits++,this.updateMetricsTimestamps(),r):(this.metrics.cacheMisses++,null)}async set(e,t){const r=this.normalizeScenePath(e);!this.cache.has(r)&&this.cache.size>=this.MAX_CACHE_SIZE&&await this.maybeEvict(),t.scenePath=r,t.lastAccessed=Date.now(),this.cache.set(r,t),this.updateMetrics()}async evict(e){const t=this.normalizeScenePath(e),r=this.cache.get(t);r&&(await this.disposeSceneResources(r),this.cache.delete(t),this.metrics.evictions++,this.updateMetrics())}async clear(){const e=Array.from(this.cache.keys());for(const t of e)await this.evict(t)}getMetrics(){return{...this.metrics}}async prepareForNewScene(){this.cache.size>=this.MAX_CACHE_SIZE&&await this.maybeEvict()}findLRUScene(){let e=null,t=1/0;for(const[r,i]of this.cache.entries())i.lastAccessed<t&&(t=i.lastAccessed,e=r);return e}async maybeEvict(){const e=this.findLRUScene();e&&(console.log(`[SceneCache] Evicting LRU scene: ${e}`),await this.evict(e))}async disposeSceneResources(e){const t=performance.now();if(e.skybox&&e.skybox.dispose(),e.mujocoRoot&&this.disposeThreeJSObject(e.mujocoRoot),e.mjData)try{e.mjData.delete()}catch(s){console.warn("[SceneCache] Failed to delete mjData:",s)}if(e.mjModel)try{e.mjModel.delete()}catch(s){console.warn("[SceneCache] Failed to delete mjModel:",s)}for(const s of e.fsFiles)try{const a=`/working/${s}`;this.mujoco.FS.analyzePath(a,!1).exists&&this.mujoco.FS.unlink(a)}catch{}mJ(e.scenePath);const r=performance.now()-t,i=(e.estimatedMemoryBytes/1048576).toFixed(1);console.log(`[SceneCache] Evicted: ${e.scenePath} (${i} MB) in ${r.toFixed(0)}ms`)}disposeThreeJSObject(e){e.traverse(t=>{"geometry"in t&&t.geometry&&t.geometry.dispose(),"material"in t&&t.material&&(Array.isArray(t.material)?t.material.forEach(r=>this.disposeMaterial(r)):this.disposeMaterial(t.material))}),e.parent&&e.parent.remove(e)}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),t.envMap&&t.envMap.dispose(),t.alphaMap&&t.alphaMap.dispose(),t.lightMap&&t.lightMap.dispose(),t.displacementMap&&t.displacementMap.dispose(),t.bumpMap&&t.bumpMap.dispose(),e.dispose()}updateMetrics(){this.metrics.totalScenes=this.cache.size,this.metrics.totalMemoryBytes=0;for(const e of this.cache.values())this.metrics.totalMemoryBytes+=e.estimatedMemoryBytes;this.updateMetricsTimestamps()}updateMetricsTimestamps(){let e=Date.now(),t=0;for(const r of this.cache.values())r.lastAccessed<e&&(e=r.lastAccessed),r.lastAccessed>t&&(t=r.lastAccessed);this.metrics.oldestAccessTime=e,this.metrics.newestAccessTime=t}};Rl.instance=null;let Ew=Rl;class GZ{constructor(){this.fsWriteLog=[],this.isTracking=!1}startTracking(e){if(this.isTracking){console.warn("[ResourceTracker] Already tracking FS writes");return}this.fsWriteLog=[],this.isTracking=!0,this.originalWriteFile=e.FS.writeFile;const t=this.fsWriteLog,r=this.originalWriteFile;e.FS.writeFile=function(i,s,a){if(i.startsWith("/working/")){const o=i.replace(/^\/working\//,"");t.includes(o)||t.push(o)}if(r)return r.call(e.FS,i,s,a)}}stopTracking(e){return this.isTracking?(this.originalWriteFile&&(e.FS.writeFile=this.originalWriteFile,this.originalWriteFile=void 0),this.isTracking=!1,[...this.fsWriteLog]):[]}estimateSceneMemory(e){let t=0;t+=this.estimateMuJoCoMemory(e.mjModel),t+=this.estimateMjDataMemory(e.mjData);const r=new Set,i=new Set,s=new Set;for(const a of Object.values(e.meshes))r.has(a)||(t+=this.estimateGeometryMemory(a),r.add(a));return e.mujocoRoot.traverse(a=>{if("geometry"in a&&a.geometry){const o=a.geometry;r.has(o)||(t+=this.estimateGeometryMemory(o),r.add(o))}if("material"in a&&a.material){const o=Array.isArray(a.material)?a.material:[a.material];for(const l of o)i.has(l)||(t+=1024,i.add(l),this.collectMaterialTextures(l).forEach(c=>{s.has(c)||(t+=this.estimateTextureMemory(c),s.add(c))}))}}),t}collectMaterialTextures(e){const t=[],r=e;return r.map&&t.push(r.map),r.aoMap&&t.push(r.aoMap),r.emissiveMap&&t.push(r.emissiveMap),r.metalnessMap&&t.push(r.metalnessMap),r.normalMap&&t.push(r.normalMap),r.roughnessMap&&t.push(r.roughnessMap),r.envMap&&t.push(r.envMap),r.alphaMap&&t.push(r.alphaMap),r.lightMap&&t.push(r.lightMap),r.displacementMap&&t.push(r.displacementMap),r.bumpMap&&t.push(r.bumpMap),t}estimateMuJoCoMemory(e){let t=0;return e.nq&&(t+=e.nq*8),e.nv&&(t+=e.nv*8),e.nbody&&(t+=e.nbody*256),e.mesh_vert&&(t+=e.mesh_vert.length*4),e.mesh_normal&&(t+=e.mesh_normal.length*4),e.mesh_texcoord&&(t+=e.mesh_texcoord.length*4),e.mesh_face&&(t+=e.mesh_face.length*4),e.tex_data&&(t+=e.tex_data.length),t}estimateMjDataMemory(e){let t=0;return e.qpos&&(t+=e.qpos.length*8),e.qvel&&(t+=e.qvel.length*8),e.qacc&&(t+=e.qacc.length*8),e.qacc_warmstart&&(t+=e.qacc_warmstart.length*8),e.ctrl&&(t+=e.ctrl.length*8),e.qfrc_applied&&(t+=e.qfrc_applied.length*8),e.xfrc_applied&&(t+=e.xfrc_applied.length*8),e.xpos&&(t+=e.xpos.length*8),e.xquat&&(t+=e.xquat.length*8),e.xmat&&(t+=e.xmat.length*8),e.xipos&&(t+=e.xipos.length*8),e.ximat&&(t+=e.ximat.length*8),e.ncon&&(t+=e.ncon*256),e.efc_force&&(t+=e.efc_force.length*8),e.sensordata&&(t+=e.sensordata.length*8),t}estimateGeometryMemory(e){let t=0;const r=e.attributes;for(const i in r){const s=r[i];s&&"array"in s&&(t+=s.array.byteLength)}return e.index&&(t+=e.index.array.byteLength),t}estimateTextureMemory(e){if(!e.image)return 1024;if(e instanceof ph&&Array.isArray(e.image)&&e.image.length===6){let r=0;for(const i of e.image){const s=i;s&&typeof s=="object"&&"width"in s&&"height"in s&&(r+=s.width*s.height*4)}return r}const t=e.image;return t&&typeof t=="object"&&"width"in t&&"height"in t?t.width*t.height*4:1024}}class HZ{getStats(e,t){const r=this.getJSHeapStats(),i={jsHeapUsedMB:r.used,jsHeapTotalMB:r.total,jsHeapLimitMB:r.limit,cachedScenesCount:e.totalScenes,estimatedCacheMemoryMB:e.totalMemoryBytes/1048576,estimatedGPUMemoryMB:0,sceneBreakdown:[]};if(t)for(const[s,a]of t.entries())i.sceneBreakdown.push({scenePath:s,memoryMB:a.memoryBytes/1048576,lastAccessed:new Date(a.lastAccessed)});return i}logCacheOperation(e,t,r){const i="[SceneCache]";switch(e){case"load":{const s=r?.memoryMB?` (${r.memoryMB.toFixed(1)} MB)`:"",a=r?.totalScenes!==void 0&&r?.totalMemoryMB!==void 0?` - Cache: ${r.totalScenes}/5 scenes, ${r.totalMemoryMB.toFixed(1)} MB total`:"";console.log(`${i} Loaded: ${t}${s}${a}`);break}case"hit":{const s=r?.elapsedMs!==void 0?` (~${r.elapsedMs.toFixed(0)}ms)`:"";console.log(`${i} Cache HIT: ${t}${s}`);break}case"miss":{console.log(`${i} Cache MISS: ${t}`);break}case"evict":{const s=r?.memoryMB?` (${r.memoryMB.toFixed(1)} MB)`:"";console.log(`${i} Evicted LRU: ${t}${s}`);break}}}logStats(e){if(console.log("[SceneCache] Memory Statistics:"),console.log(` JS Heap: ${e.jsHeapUsedMB.toFixed(1)} MB / ${e.jsHeapTotalMB.toFixed(1)} MB (Limit: ${e.jsHeapLimitMB.toFixed(1)} MB)`),console.log(` Cached Scenes: ${e.cachedScenesCount}/5`),console.log(` Estimated Cache Memory: ${e.estimatedCacheMemoryMB.toFixed(1)} MB`),e.sceneBreakdown.length>0){console.log(" Scene Breakdown:");for(const t of e.sceneBreakdown)console.log(` - ${t.scenePath}: ${t.memoryMB.toFixed(1)} MB (accessed: ${t.lastAccessed.toLocaleTimeString()})`)}}getJSHeapStats(){const e=performance;return e.memory?{used:e.memory.usedJSHeapSize/1048576,total:e.memory.totalJSHeapSize/1048576,limit:e.memory.jsHeapSizeLimit/1048576}:{used:0,total:0,limit:0}}estimateGPUMemory(e){const t=e.info,r=t.memory.geometries,i=t.memory.textures;return r*1+i*2}}class Vn{constructor(e,t){this.runner=e,this.config=t}}const VZ={};function us(n){const e=n[0]??1,t=n[1]??0,r=n[2]??0,i=n[3]??0,s=Math.hypot(e,t,r,i);if(s<1e-9)return[1,0,0,0];const a=1/s;return[e*a,t*a,r*a,i*a]}function OC(n,e){const t=n[0]??1,r=n[1]??0,i=n[2]??0,s=n[3]??0,a=e[0]??1,o=e[1]??0,l=e[2]??0,c=e[3]??0;return[t*a-r*o-i*l-s*c,t*o+r*a+i*c-s*l,t*l-r*c+i*a+s*o,t*c+r*l-i*o+s*a]}function $C(n){const e=n[0]??1,t=n[1]??0,r=n[2]??0,i=n[3]??0,s=e*e+t*t+r*r+i*i;if(s<1e-9)return[1,0,0,0];const a=1/s;return[e*a,-t*a,-r*a,-i*a]}function jp(n,e){const t=n[0]??1,r=n[1]??0,i=n[2]??0,s=n[3]??0,a=e[0]??0,o=e[1]??0,l=e[2]??0,c=2*(i*l-s*o),d=2*(s*a-r*l),h=2*(r*o-i*a),p=i*h-s*d,A=s*c-r*h,y=r*d-i*c;return[a-t*c+p,o-t*d+A,l-t*h+y]}function GC(n){const[e,t,r,i]=us(n),s=t*t,a=r*r,o=i*i,l=t*r,c=t*i,d=r*i,h=e*t,p=e*r,A=e*i,y=1-2*(a+o),m=2*(l-A),x=2*(l+A),g=1-2*(s+o),_=2*(c-p),b=2*(d+h);return[y,m,x,g,_,b]}function K0(n,e,t){return e.map(r=>{const i=n+r;return i<0?0:i>=t?Math.max(0,t-1):i})}const jZ={};async function WZ(n){const e=new DecompressionStream("deflate-raw"),t=e.writable.getWriter(),r=e.readable.getReader();t.write(n),t.close();const i=[];let s=0;for(;;){const{done:l,value:c}=await r.read();if(l)break;i.push(c),s+=c.byteLength}const a=new Uint8Array(s);let o=0;for(const l of i)a.set(l,o),o+=l.byteLength;return a}function qZ(n){const e=[147,78,85,77,80,89];for(let w=0;w<e.length;w++)if(n[w]!==e[w])throw new Error("Invalid .npy magic number");const t=n[6];let r,i;t===1?(r=n[8]|n[9]<<8,i=10):(r=n[8]|n[9]<<8|n[10]<<16|n[11]<<24,i=12);const s=n.slice(i,i+r),a=new TextDecoder().decode(s),o=a.match(/'descr'\s*:\s*'([^']+)'/),l=a.match(/'shape'\s*:\s*\(([^)]*)\)/),c=a.match(/'fortran_order'\s*:\s*(True|False)/);if(!o||!l)throw new Error(`Cannot parse .npy header: ${a}`);const d=o[1];if(c?c[1]==="True":!1)throw new Error("Fortran-ordered arrays not supported");const A=l[1].split(",").map(w=>w.trim()).filter(w=>w.length>0).map(w=>parseInt(w,10)),y=i+r,m=n.slice(y),x=d[0],g=d.slice(1),_=x===">"||x==="="&&!YZ();let b;if(g==="f4")b=new Float32Array(m.buffer,m.byteOffset,m.byteLength/4),_&&(b=JZ(b));else if(g==="f8"){let w=new Float64Array(m.buffer,m.byteOffset,m.byteLength/8);_&&(w=XZ(w)),b=new Float32Array(w.length);for(let C=0;C<w.length;C++)b[C]=w[C]}else if(g==="i4"){let w=new Int32Array(m.buffer,m.byteOffset,m.byteLength/4);_&&(w=KZ(w)),b=new Float32Array(w.length);for(let C=0;C<w.length;C++)b[C]=w[C]}else{const w=d.match(/^S(\d+)$/);if(w){const C=parseInt(w[1],10),S=m.length/C,M=A.reduce((k,G)=>k*G,1);if(S!==M)throw new Error(`npz: byte-string array size mismatch (shape ${A} expects ${M} elements, got ${S})`);const T=new TextDecoder("utf-8"),R=[];for(let k=0;k<S;k++){const G=m.slice(k*C,(k+1)*C),P=G.indexOf(0);R.push(T.decode(P>=0?G.slice(0,P):G))}return{shape:A,data:new Float32Array(0),strings:R}}throw new Error(`Unsupported numpy dtype: ${d}`)}return{shape:A,data:b}}function YZ(){const n=new ArrayBuffer(2);return new DataView(n).setInt16(0,1,!0),new Int16Array(n)[0]===1}function JZ(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=e.getFloat32(r*4,!0);return t}function XZ(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=new Float64Array(n.length);for(let r=0;r<n.length;r++)t[r]=e.getFloat64(r*8,!0);return t}function KZ(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=new Int32Array(n.length);for(let r=0;r<n.length;r++)t[r]=e.getInt32(r*4,!0);return t}async function ZZ(n){const e=await fetch(n);if(!e.ok)throw new Error(`Failed to fetch NPZ: ${e.status} ${n}`);const t=await e.arrayBuffer(),r=new Uint8Array(t),i={};let s=0;for(;s+30<=r.length&&!(r[s]!==80||r[s+1]!==75||r[s+2]!==3||r[s+3]!==4);){const a=r[s+8]|r[s+9]<<8,o=(r[s+22]|r[s+23]<<8|r[s+24]<<16|r[s+25]<<24)>>>0;let l=(r[s+18]|r[s+19]<<8|r[s+20]<<16|r[s+21]<<24)>>>0;const c=r[s+26]|r[s+27]<<8,d=r[s+28]|r[s+29]<<8,h=r.slice(s+30,s+30+c);let p=new TextDecoder().decode(h);if(l===4294967295||o===4294967295){const x=s+30+c;let g=x;for(;g+4<=x+d;){const _=r[g]|r[g+1]<<8,b=r[g+2]|r[g+3]<<8;if(_===1){let w=g+4;if(o===4294967295&&w+8<=g+4+b&&(w+=8),l===4294967295&&w+8<=g+4+b){const C=(r[w]|r[w+1]<<8|r[w+2]<<16|r[w+3]<<24)>>>0;l=((r[w+4]|r[w+5]<<8|r[w+6]<<16|r[w+7]<<24)>>>0)*4294967296+C}break}g+=4+b}}const A=s+30+c+d,y=r.slice(A,A+l);if(s=A+l,p.endsWith("/"))continue;p.endsWith(".npy")&&(p=p.slice(0,-4));let m;if(a===0)m=y;else if(a===8)m=await WZ(y);else{console.warn(`[NPZ] Unsupported compression method ${a} for ${p}`);continue}try{i[p]=qZ(m)}catch(x){console.warn(`[NPZ] Failed to parse ${p}:`,x)}}return i}function Jv(n){const e=Math.hypot(n[0]??1,n[1]??0,n[2]??0,n[3]??0)||1;return new Float32Array([(n[0]??1)/e,(n[1]??0)/e,(n[2]??0)/e,(n[3]??0)/e])}function wd(n){const e=n.shape[0]??0,t=n.shape.length<=1?1:n.shape.slice(1).reduce((i,s)=>i*s,1),r=[];for(let i=0;i<e;i++){const s=new Float32Array(t),a=i*t;for(let o=0;o<t;o++)s[o]=n.data[a+o]??0;r.push(s)}return r}function uP(n,e){if(!Array.isArray(n)||n.length<2)return e;const t=Number(n[0]),r=Number(n[1]);return!Number.isFinite(t)||!Number.isFinite(r)?e:[t,r]}function dB(n){if(n===null||typeof n!="object"||Array.isArray(n))return{};const e={};for(const t of["x","y","z","roll","pitch","yaw"]){const r=uP(n[t],[0,0]);(r[0]!==0||r[1]!==0)&&(e[t]=r)}return e}function $i(n){return n?n[0]+Math.random()*(n[1]-n[0]):0}function eee(n,e){const t=n[0]??1,r=n[1]??0,i=n[2]??0,s=n[3]??0,a=e[0]??1,o=e[1]??0,l=e[2]??0,c=e[3]??0;return new Float32Array([t*a-r*o-i*l-s*c,t*o+r*a+i*c-s*l,t*l-r*c+i*a+s*o,t*c+r*l-i*o+s*a])}function tee(n,e,t){const r=Math.cos(n*.5),i=Math.sin(n*.5),s=Math.cos(e*.5),a=Math.sin(e*.5),o=Math.cos(t*.5),l=Math.sin(t*.5);return new Float32Array([r*s*o+i*a*l,i*s*o-r*a*l,r*a*o+i*s*l,r*s*l-i*a*o])}function hB(n){const e=n.clone();return"transparent"in e&&(e.transparent=!0),"opacity"in e&&(e.opacity=.35),"depthWrite"in e&&(e.depthWrite=!1),"color"in e&&e.color instanceof xt&&(e.color=new xt("#7bd88f")),e}function nee(n){let e=!1;return n.traverse(t=>{t instanceof Kn&&(e=!0)}),e}class xp{constructor(e,t,r){this.context=r,this.motions=Array.isArray(t.motions)?t.motions:[],this.loadedMotions=new Map,this.sampleHz=50,this.selectedMotionName=this.motions.find(i=>i.default)?.name??this.motions[0]?.name??null,this.selectedMotion=null,this.selectedAnchorBodyIndex=0,this.selectedRootBodyIndex=0,this.datasetQposAdr=[],this.frameAccumulator=0,this.justReset=!0,this.referenceVisible=!0,this.samplingMode=typeof t.sampling_mode=="string"?t.sampling_mode:"start",this.poseRange=dB(t.pose_range),this.velocityRange=dB(t.velocity_range),this.jointPositionRange=uP(t.joint_position_range,[0,0]),this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.nJoints=this.motions.find(i=>i.name===this.selectedMotionName)?.dataset_joint_names?.length??0,this.ghostBodies=new Map,this.ghostData=r.mjModel?new r.mujoco.MjData(r.mjModel):null,this.ghostRoot=this.createGhostRoot(),this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[]}getCommand(){if(!this.selectedMotion||this.refLen===0)return new Float32Array(this.nJoints*2);const e=this.refJointPos[this.refIdx]??new Float32Array(this.nJoints),t=this.selectedMotion.jointVel[this.refIdx]??new Float32Array(this.nJoints),r=new Float32Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}getUiConfig(){return null}async setSelectedMotion(e){const t=e??this.selectedMotionName;if(!t)return this.selectedMotionName=null,this.selectedMotion=null,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[],this.refLen=0,this.nJoints=0,this.updateGhostPose(),!1;const r=this.motions.find(s=>s.name===t);if(!r)return!1;const i=this.loadedMotions.get(t)??await this.loadMotion(r);return this.loadedMotions.set(t,i),this.selectedMotionName=t,this.selectedMotion=i,this.selectedAnchorBodyIndex=Math.max(0,i.body_names.indexOf(i.anchor_body_name)),this.selectedRootBodyIndex=0,this.datasetQposAdr=this.resolveQposAdr(i.dataset_joint_names??[]),this.refLen=i.frameCount,this.refJointPos=i.jointPos,this.refIdx=this.sampleInitialFrame(this.refLen),this.nJoints=i.jointPos[0]?.length??0,this.frameAccumulator=0,this.justReset=!0,this.updateReferenceState(),this.applyReferenceStateToSim(),this.updateGhostPose(),!0}setReferenceVisible(e){this.referenceVisible=e,this.ghostRoot&&(this.ghostRoot.visible=e&&this.selectedMotion!==null)}reset(){this.refIdx=this.sampleInitialFrame(this.refLen),this.frameAccumulator=0,this.justReset=!0,this.updateReferenceState(),this.applyReferenceStateToSim(),this.updateGhostPose()}update(e){if(!(!this.selectedMotion||this.refLen<=1)){if(this.justReset){this.justReset=!1,this.updateGhostPose();return}for(this.frameAccumulator+=e*this.sampleHz;this.frameAccumulator>=1&&this.refIdx<this.refLen-1;)this.refIdx+=1,this.frameAccumulator-=1;this.updateGhostPose()}}updateDebugVisuals(){this.ghostRoot&&(this.ghostRoot.visible=this.referenceVisible&&this.selectedMotion!==null)}dispose(){this.ghostRoot&&(this.ghostRoot.parent?.remove(this.ghostRoot),this.ghostRoot.traverse(e=>{if(e instanceof Kn)if(Array.isArray(e.material))for(const t of e.material)t.dispose?.();else e.material?.dispose?.()})),this.ghostData?.delete?.()}isReady(){return this.selectedMotion!==null&&this.refLen>0}getSelectedMotion(){return this.selectedMotion}getSelectedMotionName(){return this.selectedMotionName}getAnchorBodyName(){return this.selectedMotion?.anchor_body_name??this.motions.find(e=>e.name===this.selectedMotionName)?.anchor_body_name??null}getBodyNames(){return this.selectedMotion?.body_names??this.motions.find(e=>e.name===this.selectedMotionName)?.body_names??[]}getAnchorBodyIndex(){return this.selectedAnchorBodyIndex}getAnchorPos(e=this.refIdx){if(!this.selectedMotion)return null;const r=this.refBodyPosW[e];if(!r)return null;const i=this.selectedAnchorBodyIndex*3;return r.slice(i,i+3)}getAnchorQuat(e=this.refIdx){if(!this.selectedMotion)return null;const r=this.refBodyQuatW[e];if(!r)return null;const i=this.selectedAnchorBodyIndex*4;return Jv(r.slice(i,i+4))}getBodyPosW(e=this.refIdx){if(!this.selectedMotion)return null;const r=this.refBodyPosW[e];return r?r.slice():null}createGhostRoot(){const e=this.context.bodies??null,t=this.context.mjModel;if(!e||!t)return null;const r=new cs;r.name="Tracking Ghost",r.visible=!1;for(const[i,s]of Object.entries(e)){const a=Number(i);if(!this.isDynamicBody(a))continue;const o=s.clone(!0);o.traverse(l=>{l instanceof Kn&&(Array.isArray(l.material)?l.material=l.material.map(hB):l.material=hB(l.material))}),nee(o)&&(this.ghostBodies.set(a,o),r.add(o))}return(this.context.mujocoRoot??this.context.scene).add(r),r}isDynamicBody(e){const t=this.context.mjModel;if(!t||e<=0||e>=t.nbody)return!1;let r=e;for(;r>0;){if(t.body_jntnum[r]>0)return!0;r=t.body_parentid[r]}return!1}async loadMotion(e){this.sampleHz=e.fps;const t=await ZZ(e.path),r=["joint_pos","joint_vel","body_pos_w","body_quat_w","body_lin_vel_w","body_ang_vel_w"];for(const h of r)if(!t[h])throw new Error(`Motion asset is missing '${h}'`);const i=wd(t.joint_pos),s=wd(t.joint_vel),a=t.body_names?.strings??null,o=this.selectMotionBodyFrames(wd(t.body_pos_w),e.body_names,3,a),l=this.selectMotionBodyFrames(wd(t.body_quat_w),e.body_names,4,a),c=this.selectMotionBodyFrames(wd(t.body_lin_vel_w),e.body_names,3,a),d=this.selectMotionBodyFrames(wd(t.body_ang_vel_w),e.body_names,3,a);return{...e,jointPos:i,jointVel:s,bodyPosW:o,bodyQuatW:l,bodyLinVelW:c,bodyAngVelW:d,frameCount:i.length}}selectMotionBodyFrames(e,t,r,i=null){const s=this.context.mjModel,a=e[0];if(!s||!a||t.length===0)return e;const o=Math.floor(a.length/r);if(o===t.length)return e;let l;if(i!==null)l=t.map(c=>i.indexOf(c));else{const c=this.findBodyIdByName(t[0]);l=t.map(h=>this.findBodyIdByName(h)).map(h=>h-c)}return l.some(c=>c<0||c>=o)?(console.warn("[TrackingCommand] Could not map all motion body names to source body indices; using raw body frames."),e):e.map(c=>{const d=new Float32Array(t.length*r);for(let h=0;h<l.length;h++){const p=l[h]*r,A=h*r;for(let y=0;y<r;y++)d[A+y]=c[p+y]??0}return d})}updateReferenceState(){const e=this.selectedMotion;if(!e||e.frameCount===0){this.refRootPos=[],this.refRootQuat=[],this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[];return}this.refBodyPosW=e.bodyPosW.map(t=>t.slice()),this.refBodyQuatW=e.bodyQuatW.map(t=>t.slice()),this.refBodyLinVelW=e.bodyLinVelW.map(t=>t.slice()),this.refBodyAngVelW=e.bodyAngVelW.map(t=>t.slice()),this.refRootPos=this.refBodyPosW.map(t=>t.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3)),this.refRootQuat=this.refBodyQuatW.map(t=>Jv(t.slice(this.selectedRootBodyIndex*4,this.selectedRootBodyIndex*4+4)))}applyReferenceStateToSim(){const e=this.context.mjModel,t=this.context.mjData,r=this.selectedMotion;if(!e||!t||!r||this.refLen===0)return;const i=this.sampleRootPos(this.refIdx),s=this.sampleRootQuat(this.refIdx),a=this.findFreeJointIndex();if(i&&s&&a>=0){const c=e.jnt_qposadr[a],d=e.jnt_dofadr[a];t.qpos[c+0]=i[0]??0,t.qpos[c+1]=i[1]??0,t.qpos[c+2]=i[2]??0,t.qpos[c+3]=s[0]??1,t.qpos[c+4]=s[1]??0,t.qpos[c+5]=s[2]??0,t.qpos[c+6]=s[3]??0;const h=this.sampleRootVelocity(this.refIdx,this.refBodyLinVelW),p=this.sampleRootAngularVelocity(this.refIdx);h&&p&&(t.qvel[d+0]=h[0]??0,t.qvel[d+1]=h[1]??0,t.qvel[d+2]=h[2]??0,t.qvel[d+3]=p[0]??0,t.qvel[d+4]=p[1]??0,t.qvel[d+5]=p[2]??0)}const o=this.sampleJointPos(this.refIdx),l=r.jointVel[this.refIdx]??new Float32Array(0);for(let c=0;c<this.datasetQposAdr.length&&c<o.length;c++)t.qpos[this.datasetQposAdr[c]]=o[c]??0;for(let c=0;c<this.datasetQposAdr.length&&c<l.length;c++){const d=this.resolveQvelAdrForQposAdr(this.datasetQposAdr[c]);d>=0&&(t.qvel[d]=l[c]??0)}this.context.mujoco.mj_forward(e,t)}sampleRootPos(e){const t=this.refRootPos[e];if(!t)return null;const r=t.slice();return r[0]+=$i(this.poseRange.x),r[1]+=$i(this.poseRange.y),r[2]+=$i(this.poseRange.z),r}sampleRootQuat(e){const t=this.refRootQuat[e];if(!t)return null;const r=$i(this.poseRange.roll),i=$i(this.poseRange.pitch),s=$i(this.poseRange.yaw);return r===0&&i===0&&s===0?t:Jv(eee(tee(r,i,s),t))}sampleRootVelocity(e,t){const r=t[e]?.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3);return r?(r[0]+=$i(this.velocityRange.x),r[1]+=$i(this.velocityRange.y),r[2]+=$i(this.velocityRange.z),r):null}sampleRootAngularVelocity(e){const t=this.refBodyAngVelW[e]?.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3);return t?(t[0]+=$i(this.velocityRange.roll),t[1]+=$i(this.velocityRange.pitch),t[2]+=$i(this.velocityRange.yaw),t):null}sampleInitialFrame(e){return e<=1||this.samplingMode==="start"?0:this.samplingMode==="uniform"?Math.floor(Math.random()*e):0}sampleJointPos(e){const t=this.refJointPos[e]??new Float32Array(0);if(this.jointPositionRange[0]===0&&this.jointPositionRange[1]===0)return t;const r=t.slice();for(let i=0;i<r.length;i++)r[i]+=$i(this.jointPositionRange);return r}resolveQposAdr(e){const t=this.context.mjModel;if(!t||e.length===0)return[];const r=[];for(const i of e){let s=-1;for(let a=0;a<t.njnt;a++){const o=t.jnt(a).name;if(o===i||o.endsWith(`/${i}`)){s=t.jnt_qposadr[a];break}}s>=0&&r.push(s)}return r}resolveQvelAdrForQposAdr(e){const t=this.context.mjModel;if(!t)return-1;for(let r=0;r<t.njnt;r++)if(t.jnt_qposadr[r]===e)return t.jnt_dofadr[r];return-1}findBodyIdByName(e){const t=this.context.mjModel;if(!t)return-1;for(let r=0;r<t.nbody;r++){const i=t.body(r).name;if(i===e||i.endsWith(`/${e}`))return r}return-1}updateGhostPose(){if(!this.ghostRoot||!this.ghostData||!this.context.mjModel||!this.selectedMotion||!this.refLen){this.ghostRoot&&(this.ghostRoot.visible=!1);return}const e=this.ghostData.qpos;e.set(this.context.mjModel.qpos0);const t=this.refRootPos[this.refIdx],r=this.refRootQuat[this.refIdx],i=this.findFreeJointIndex();if(i>=0&&t&&r){const a=this.context.mjModel.jnt_qposadr[i];e[a+0]=t[0]??0,e[a+1]=t[1]??0,e[a+2]=t[2]??0,e[a+3]=r[0]??1,e[a+4]=r[1]??0,e[a+5]=r[2]??0,e[a+6]=r[3]??0}const s=this.refJointPos[this.refIdx]??new Float32Array(0);for(let a=0;a<this.datasetQposAdr.length&&a<s.length;a++)e[this.datasetQposAdr[a]]=s[a]??0;this.context.mujoco.mj_forward(this.context.mjModel,this.ghostData);for(const[a,o]of this.ghostBodies)Vc(this.ghostData.xpos,a,o.position),pp(this.ghostData.xquat,a,o.quaternion);this.ghostRoot.visible=this.referenceVisible}findFreeJointIndex(){const e=this.context.mjModel;if(!e)return-1;for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}}class ree{constructor(e,t){this.inputs=Array.isArray(t.ui?.inputs)?t.ui.inputs:[],this.values=new Map;for(const r of this.inputs)r.type==="slider"&&this.values.set(r.name,r.default)}getCommand(){const e=this.inputs.filter(r=>r.type==="slider"),t=new Float32Array(e.length);for(let r=0;r<e.length;r++)t[r]=this.values.get(e[r].name)??e[r].default??0;return t}getUiConfig(){return{inputs:this.inputs}}reset(){for(const e of this.inputs)e.type==="slider"&&this.values.set(e.name,e.default)}setValue(e,t){const r=this.inputs.find(s=>s.type==="slider"&&s.name===e);if(!r)return 0;const i=Math.max(r.min,Math.min(r.max,t));return this.values.set(r.name,i),i}}const iee={UiCommand:ree,TrackingCommand:xp};class see{constructor(){this.terms=new Map,this.commands=new Map,this.commandGroups=new Map,this.values=new Map,this.listeners=new Set,this.resetCallback=null,this.context=null,this.registerSystemReset()}initialize(e,t){this.clear(),this.context=t;const r={...iee,...jZ};for(const[i,s]of Object.entries(e)){const a=r[s.name];if(!a)throw new Error(`Unknown command term: ${s.name}`);const o=new a(i,s,t);this.terms.set(i,o),this.registerUi(i,o)}}update(e){for(const t of this.terms.values())t.update?.(e)}updateDebugVisuals(){for(const e of this.terms.values())e.updateDebugVisuals?.()}resetTerms(){for(const e of this.terms.values())e.reset?.();this.syncValuesFromTerms(),this.emit({type:"reset",commandId:"*"})}getCommandGroups(){return Array.from(this.commandGroups.keys()).filter(e=>e!=="_system")}getCommandsInGroup(e){return(this.commandGroups.get(e)??[]).map(r=>this.commands.get(r)).filter(Boolean)}getCommands(){return Array.from(this.commands.values()).filter(e=>e.groupName!=="_system")}getAllCommands(){return Array.from(this.commands.values())}getResetCommand(){return this.commands.get("_system:reset")}getCommandById(e){return this.commands.get(e)}getValue(e){return this.values.get(e)??0}getValues(){const e={};for(const[t,r]of this.values)e[t]=r;return e}getCommand(e){const t=this.terms.get(e);return t?t.getCommand():new Float32Array(0)}getTerm(e){return this.terms.get(e)}getContext(){return this.context}getVelocityCommand(){return this.terms.has("velocity")?this.getCommand("velocity"):this.terms.has("twist")?this.getCommand("twist"):new Float32Array([.5,0,0])}setValue(e,t){const r=this.commands.get(e);if(!r||r.config.type!=="slider")return;const i=this.terms.get(r.groupName),s=r.config.name,a=i?.setValue?i.setValue(s,t):void 0,o=typeof a=="number"?a:t;this.values.set(e,o),this.emit({type:"change",commandId:e,groupName:r.groupName,value:o})}triggerButton(e){const t=this.commands.get(e);!t||t.config.type!=="button"||(e==="_system:reset"&&this.resetCallback?this.resetCallback():this.terms.get(t.groupName)?.triggerButton?.(t.config.name),this.emit({type:"button",commandId:e,groupName:t.groupName}))}resetToDefaults(){this.resetTerms()}setResetCallback(e){this.resetCallback=e}addEventListener(e){this.listeners.add(e)}removeEventListener(e){this.listeners.delete(e)}clear(){for(const e of this.terms.values())e.dispose?.();this.terms.clear(),this.commands.clear(),this.commandGroups.clear(),this.values.clear(),this.context=null,this.registerSystemReset(),this.emit({type:"clear",commandId:""})}hasCommands(){return this.commands.size>1}dispose(){for(const e of this.terms.values())e.dispose?.();this.terms.clear(),this.commands.clear(),this.commandGroups.clear(),this.values.clear(),this.listeners.clear(),this.resetCallback=null,this.context=null}registerSystemReset(){this.commands.set("_system:reset",{id:"_system:reset",groupName:"_system",config:{type:"button",name:"reset",label:"Reset Simulation"}}),this.commandGroups.set("_system",["_system:reset"])}registerUi(e,t){const r=t.getUiConfig?.(),i=Array.isArray(r?.inputs)?r.inputs:[];if(i.length!==0){this.commandGroups.set(e,[]);for(const s of i){const a=`${e}:${s.name}`;if(this.commands.set(a,{id:a,groupName:e,config:s}),this.commandGroups.get(e).push(a),s.type==="slider"){const o=t.getCommand(),l=i.filter(c=>c.type==="slider").findIndex(c=>c.name===s.name);this.values.set(a,o[l]??s.default)}}this.emit({type:"group_registered",commandId:e,groupName:e})}}syncValuesFromTerms(){for(const[e,t]of this.commands){if(t.config.type!=="slider")continue;const r=this.terms.get(t.groupName);if(!r)continue;const a=(r.getUiConfig?.()?.inputs??[]).filter(o=>o.type==="slider").findIndex(o=>o.name===t.config.name);if(a>=0){const o=r.getCommand();this.values.set(e,o[a]??this.values.get(e)??0)}}}emit(e){for(const t of this.listeners)try{t(e)}catch(r){console.warn("[CommandManager] Listener error:",r)}}}let Xv=null;function tr(){return Xv||(Xv=new see),Xv}function HC(n,e,t=1){if(typeof n=="number"){const r=new Float32Array(e);return r.fill(n),r}if(Array.isArray(n)){const r=new Float32Array(e);for(let i=0;i<e;i++){const s=n[i];r[i]=typeof s=="number"?s:t}return r}return null}class aee extends Vn{constructor(e,t){super(e,t),this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(3)),this.scale=HC(t.scale,3,1)}get size(){return 3*this.historySteps}reset(){const e=this.computeCurrent();for(const t of this.history)t.set(e)}update(){for(let e=this.history.length-1;e>0;e--)this.history[e].set(this.history[e-1]);this.history[0].set(this.computeCurrent())}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(){const t=tr().getVelocityCommand(),r=new Float32Array(t);if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}}class oee extends Vn{constructor(e,t){super(e,t),this.scale=HC(t.scale,3,1)}get size(){return 16}compute(){const e=new Float32Array(16),r=tr().getVelocityCommand();if(this.scale)for(let i=0;i<3;i++)r[i]*=this.scale[i]??1;return e[0]=r[0],e[1]=r[1],e[2]=r[2],e}}class fB extends Vn{constructor(e,t){super(e,t),this.commandName=t.command_name??"velocity",this.historySteps=Math.max(1,Math.floor(t.history_steps??1));const i=tr().getCommand(this.commandName);this.commandSize=i.length||3,this.history=Array.from({length:this.historySteps},()=>new Float32Array(this.commandSize)),this.scale=HC(t.scale,this.commandSize,1)}get size(){return this.commandSize*this.historySteps}reset(){const e=this.computeCurrent();for(const t of this.history)t.set(e)}update(){for(let e=this.history.length-1;e>0;e--)this.history[e].set(this.history[e-1]);this.history[0].set(this.computeCurrent())}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(){const t=tr().getCommand(this.commandName),r=new Float32Array(this.commandSize);for(let i=0;i<this.commandSize&&i<t.length;i++)r[i]=t[i];if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}}function ia(n){const e=tr().getTerm("motion");return e instanceof xp?e:null}function Kd(n,e){if(!n)return-1;for(let t=0;t<n.nbody;t++){const r=n.body(t).name;if(r===e||r.endsWith(`/${e}`))return t}return-1}function xh(n,e,t=1){if(typeof n=="number"){const r=new Float32Array(e);return r.fill(n),r}if(Array.isArray(n)){const r=new Float32Array(e);for(let i=0;i<e;i++){const s=n[i];r[i]=typeof s=="number"?s:t}return r}return null}function pB(n,e,t=0){if(!Array.isArray(n))return null;const r=new Float32Array(e);for(let i=0;i<e;i++)r[i]=typeof n[i]=="number"?n[i]:t;return r}class lee extends Vn{get size(){return 1}compute(){return new Float32Array([0])}}class cee extends Vn{get size(){return 3}compute(e){const t=e.rootAngVel??new Float32Array(3);return new Float32Array(t)}}class dP extends Vn{constructor(e,t){super(e,t);const r=Array.isArray(t.gravity)?t.gravity:[0,0,-1];this.gravity=new ue(r[0]??0,r[1]??0,r[2]??-1),this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(3))}get size(){return 3*this.historySteps}reset(e){const t=this.computeCurrent(e);for(const r of this.history)r.set(t)}update(e){for(let t=this.history.length-1;t>0;t--)this.history[t].set(this.history[t-1]);this.history[0].set(this.computeCurrent(e))}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(e){const t=e?.rootQuat??new Float32Array([1,0,0,0]),r=new Cn(t[1],t[2],t[3],t[0]),i=this.gravity.clone().applyQuaternion(r.clone().invert());return new Float32Array([i.x,i.y,i.z])}}class hP extends Vn{constructor(e,t){super(e,t);let r;if(Array.isArray(t.pos_steps))r=t.pos_steps.map(s=>Math.max(0,Math.floor(s)));else if(typeof t.history_steps=="number"){const s=Math.max(1,Math.floor(t.history_steps));r=Array.from({length:s},(a,o)=>o)}else r=[0,1,2,3,4,8];this.posSteps=r;const i=this.getJointNames(t);this.qposAdr=i?this.resolveQposAdr(i):null,this.numJoints=i?.length??(typeof t.num_joints=="number"?Math.max(1,Math.floor(t.num_joints)):e.getNumActions()),this.maxStep=Math.max(...this.posSteps),this.history=Array.from({length:this.maxStep+1},()=>new Float32Array(this.numJoints)),this.subtractDefault=!!t.subtract_default,this.biased=!!t.biased,this.defaultJointPos=this.normalizeDefaultJointPos(t.default_joint_pos),this.encoderBias=this.normalizeEncoderBias(t.encoder_bias),this.scale=this.normalizeScale(t.scale)}get size(){return this.posSteps.length*this.numJoints}reset(e){this.history[0].set(this.computeCurrent(e));for(let t=1;t<this.history.length;t++)this.history[t].set(this.history[0])}update(e){for(let t=this.history.length-1;t>0;t--)this.history[t].set(this.history[t-1]);this.history[0].set(this.computeCurrent(e))}compute(){const e=new Float32Array(this.posSteps.length*this.numJoints);let t=0;for(const r of this.posSteps){const i=Math.min(r,this.history.length-1),s=this.history[i];for(let a=0;a<this.numJoints;a++){let o=s[a];this.subtractDefault&&this.defaultJointPos.length>a&&(o-=this.defaultJointPos[a]),this.scale&&this.scale.length>a&&(o*=this.scale[a]),e[t+a]=o}t+=this.numJoints}return e}computeCurrent(e){if(this.qposAdr!==null){const i=this.runner.getContext()?.mjData?.qpos,s=new Float32Array(this.numJoints);for(let a=0;a<this.numJoints;a++){const o=this.qposAdr[a];s[a]=i!==void 0?i[o]:0,this.biased&&this.encoderBias.length>a&&(s[a]+=this.encoderBias[a])}return s}const t=e?.jointPos??new Float32Array(this.numJoints);if(!this.biased)return t;const r=new Float32Array(this.numJoints);for(let i=0;i<this.numJoints;i++)r[i]=(t[i]??0)+(this.encoderBias[i]??0);return r}getJointNames(e){if(!Array.isArray(e.joint_names))return null;const t=e.joint_names.filter(r=>typeof r=="string");return t.length>0?t:null}normalizeDefaultJointPos(e){const t=pB(e,this.numJoints,0);if(t)return t;const r=this.runner.getDefaultJointPos(),i=new Float32Array(this.numJoints);for(let s=0;s<this.numJoints;s++)i[s]=r[s]??0;return i}normalizeEncoderBias(e){const t=pB(e,this.numJoints,0);if(t)return t;const r=this.runner.getEncoderBias(),i=new Float32Array(this.numJoints);for(let s=0;s<this.numJoints;s++)i[s]=r[s]??0;return i}resolveQposAdr(e){const t=this.runner.getContext()?.mjModel??null;if(t===null)return Array.from({length:e.length},()=>0);const r=this.getModelJointNames(t);return e.map(i=>{const s=r.indexOf(i);if(s<0)throw new Error(`JointPos: joint "${i}" not found in model`);return t.jnt_qposadr[s]})}getModelJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;i.push(r.decode(t.subarray(a,o)))}return i}normalizeScale(e){if(typeof e=="number"){const t=new Float32Array(this.numJoints);return t.fill(e),t}if(Array.isArray(e)){const t=new Float32Array(this.numJoints);for(let r=0;r<this.numJoints;r++){const i=e[r];t[r]=typeof i=="number"?i:1}return t}return null}}class uee extends Vn{constructor(e,t){super(e,t),this.futureSteps=Array.isArray(t.future_steps)?t.future_steps.map(i=>Math.max(0,Math.floor(i))):[0,2,4,8,16];const r=this.futureSteps.length;this.outputLength=(r-1)*3+r*6}get size(){return this.outputLength}compute(e){const t=ia(this.runner);if(!t||!t.isReady())return new Float32Array(this.outputLength);const r=t.refIdx,i=t.refLen,s=K0(r,this.futureSteps,i),a=t.refRootPos[s[0]],o=us(t.refRootQuat[s[0]]),l=[];for(let p=1;p<s.length;p++){const A=t.refRootPos[s[p]],y=[A[0]-a[0],A[1]-a[1],A[2]-a[2]],m=jp(o,y);l.push(m[0],m[1],m[2])}const c=us(e.rootQuat??[1,0,0,0]),d=$C(c),h=[];for(let p=0;p<s.length;p++){const A=us(t.refRootQuat[s[p]]),y=OC(d,A),m=GC(y);h.push(m[0],m[1],m[2],m[3],m[4],m[5])}return Float32Array.from([...l,...h])}}class dee extends Vn{constructor(e,t){super(e,t),this.futureSteps=Array.isArray(t.future_steps)?t.future_steps.map(r=>Math.max(0,Math.floor(r))):[0,2,4,8,16]}get size(){return this.futureSteps.length}compute(){const e=ia(this.runner);if(!e||!e.isReady())return new Float32Array(this.size);const t=K0(e.refIdx,this.futureSteps,e.refLen),r=new Float32Array(t.length);for(let i=0;i<t.length;i++)r[i]=e.refRootPos[t[i]][2];return r}}class hee extends Vn{constructor(e,t){super(e,t),this.futureSteps=Array.isArray(t.future_steps)?t.future_steps.map(r=>Math.max(0,Math.floor(r))):[0,2,4,8,16]}get size(){const t=ia(this.runner)?.nJoints??0;return this.futureSteps.length*t}compute(){const e=ia(this.runner);if(!e||!e.isReady())return new Float32Array(this.size);const t=K0(e.refIdx,this.futureSteps,e.refLen),r=new Float32Array(t.length*e.nJoints);let i=0;for(const s of t)r.set(e.refJointPos[s],i),i+=e.nJoints;return r}}class fee extends Vn{constructor(e,t){super(e,t),this.futureSteps=Array.isArray(t.future_steps)?t.future_steps.map(r=>Math.max(0,Math.floor(r))):[0,2,4,8,16]}get size(){return this.futureSteps.length*3}compute(){const e=ia(this.runner);if(!e||!e.isReady())return new Float32Array(this.size);const t=K0(e.refIdx,this.futureSteps,e.refLen),r=new Float32Array(t.length*3),i=[0,0,-1];let s=0;for(const a of t){const o=us(e.refRootQuat[a]),l=jp(o,i);r[s++]=l[0],r[s++]=l[1],r[s++]=l[2]}return r}}class pee extends Vn{get size(){return 3}compute(e){const t=ia(this.runner),r=this.runner.getContext(),i=r?.mjModel??null,s=r?.mjData??null;if(!t||!t.isReady())return new Float32Array(3);const a=t.getAnchorPos(),o=t.getAnchorQuat(),l=t.getAnchorBodyName();if(!a||!o)return new Float32Array(3);if(!l||!i||!s)return new Float32Array(3);const c=Kd(i,l);if(c<0)return new Float32Array(3);const d=s.xpos.slice(c*3,c*3+3),h=us(s.xquat.slice(c*4,c*4+4)),p=[a[0]-d[0],a[1]-d[1],a[2]-d[2]],A=jp(h,p);return Float32Array.from(A)}}class Aee extends Vn{get size(){return 6}compute(e){const t=ia(this.runner),r=this.runner.getContext(),i=r?.mjModel??null,s=r?.mjData??null;if(!t||!t.isReady())return new Float32Array(6);const a=t.getAnchorQuat(),o=t.getAnchorBodyName();if(!a)return new Float32Array(6);if(!o||!i||!s)return new Float32Array(6);const l=Kd(i,o);if(l<0)return new Float32Array(6);const c=us(s.xquat.slice(l*4,l*4+4)),d=OC($C(c),us(a));return Float32Array.from(GC(d))}}class mee extends Vn{get size(){const e=ia(this.runner);return e?e.getBodyNames().length*3:0}compute(){const e=ia(this.runner),t=this.runner.getContext(),r=t?.mjModel??null,i=t?.mjData??null;if(!e||!e.isReady()||!r||!i)return new Float32Array(this.size);const s=e.getBodyNames(),a=e.getAnchorBodyName();if(!a)return new Float32Array(this.size);const o=Kd(r,a);if(o<0)return new Float32Array(this.size);const l=i.xpos.slice(o*3,o*3+3),c=us(i.xquat.slice(o*4,o*4+4)),d=new Float32Array(s.length*3);let h=0;for(const p of s){const A=Kd(r,p);if(A<0){h+=3;continue}const y=i.xpos.slice(A*3,A*3+3),m=[y[0]-l[0],y[1]-l[1],y[2]-l[2]],x=jp(c,m);d.set(x,h),h+=3}return d}}class gee extends Vn{get size(){const e=ia(this.runner);return e?e.getBodyNames().length*6:0}compute(){const e=ia(this.runner),t=this.runner.getContext(),r=t?.mjModel??null,i=t?.mjData??null;if(!e||!e.isReady()||!r||!i)return new Float32Array(this.size);const s=e.getBodyNames(),a=e.getAnchorBodyName();if(!a)return new Float32Array(this.size);const o=Kd(r,a);if(o<0)return new Float32Array(this.size);const l=us(i.xquat.slice(o*4,o*4+4)),c=$C(l),d=new Float32Array(s.length*6);let h=0;for(const p of s){const A=Kd(r,p);if(A<0){h+=6;continue}const y=us(i.xquat.slice(A*4,A*4+4)),m=OC(c,y);d.set(GC(m),h),h+=6}return d}}class fP extends Vn{constructor(e,t){super(e,t);const r=typeof t.history_steps=="number"?t.history_steps:4;this.steps=Math.max(1,Math.floor(r)),this.numActions=e.getNumActions(),this.actionBuffer=Array.from({length:this.steps},()=>new Float32Array(this.numActions)),this.transpose=!!t.transpose}get size(){return this.steps*this.numActions}reset(){for(const e of this.actionBuffer)e.fill(0)}update(){for(let t=this.actionBuffer.length-1;t>0;t--)this.actionBuffer[t].set(this.actionBuffer[t-1]);const e=this.runner.getLastActions();this.actionBuffer[0].set(e)}compute(){const e=new Float32Array(this.steps*this.numActions);if(this.transpose)for(let t=0;t<this.numActions;t++)for(let r=0;r<this.steps;r++)e[t*this.steps+r]=this.actionBuffer[r][t];else for(let t=0;t<this.steps;t++)for(let r=0;r<this.numActions;r++)e[t*this.numActions+r]=this.actionBuffer[t][r];return e}}class yee extends Vn{constructor(e,t){super(e,t),this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(3)),this.scale=xh(t.scale,3,1),this.worldFrame=t.world_frame??!0}get size(){return 3*this.historySteps}reset(e){const t=this.computeCurrent(e);for(const r of this.history)r.set(t)}update(e){for(let t=this.history.length-1;t>0;t--)this.history[t].set(this.history[t-1]);this.history[0].set(this.computeCurrent(e))}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(e){const t=e?.rootLinVel??new Float32Array(3);let r=new Float32Array(t);if(!this.worldFrame){const i=us(e?.rootQuat??[1,0,0,0]),s=jp(i,r);r=new Float32Array(s)}if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}}class xee extends Vn{constructor(e,t){super(e,t),this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(3)),this.scale=xh(t.scale,3,1)}get size(){return 3*this.historySteps}reset(e){const t=this.computeCurrent(e);for(const r of this.history)r.set(t)}update(e){for(let t=this.history.length-1;t>0;t--)this.history[t].set(this.history[t-1]);this.history[0].set(this.computeCurrent(e))}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(e){const t=e?.rootAngVel??new Float32Array(3),r=new Float32Array(t);if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}}class vee extends Vn{constructor(e,t){super(e,t);const r=Array.isArray(t.joint_names)?t.joint_names.filter(s=>typeof s=="string"):null,i=t.joint_name;if(r&&r.length>0)this.qvelAdr=null,this.qvelAdrList=this.resolveQvelAdrList(e.getContext()?.mjModel??null,r),this.numJoints=r.length;else if(i!==void 0){const s=e.getContext()?.mjModel??null;this.qvelAdr=s!==null?this.resolveQvelAdr(s,i):0,this.qvelAdrList=null,this.numJoints=1}else this.qvelAdr=null,this.qvelAdrList=null,this.numJoints=e.getNumActions();this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(this.numJoints)),this.scale=xh(t.scale,this.numJoints,1)}get size(){return this.numJoints*this.historySteps}reset(e){const t=this.computeCurrent(e);for(const r of this.history)r.set(t)}update(e){for(let t=this.history.length-1;t>0;t--)this.history[t].set(this.history[t-1]);this.history[0].set(this.computeCurrent(e))}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(e){if(this.qvelAdrList!==null){const i=this.runner.getContext()?.mjData?.qvel,s=new Float32Array(this.numJoints);for(let a=0;a<this.numJoints;a++)s[a]=i!==void 0?i[this.qvelAdrList[a]]:0;if(this.scale)for(let a=0;a<s.length;a++)s[a]*=this.scale[a]??1;return s}if(this.qvelAdr!==null){const i=this.runner.getContext()?.mjData?.qvel,s=i!==void 0?i[this.qvelAdr]:0,a=new Float32Array([s]);return this.scale&&(a[0]*=this.scale[0]??1),a}const t=e?.jointVel??new Float32Array(this.numJoints),r=new Float32Array(t);if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}resolveQvelAdr(e,t){const i=this.getModelJointNames(e).indexOf(t);if(i<0)throw new Error(`JointVelocities: joint "${t}" not found in model`);return e.jnt_dofadr[i]}resolveQvelAdrList(e,t){if(e===null)return Array.from({length:t.length},()=>0);const r=this.getModelJointNames(e);return t.map(i=>{const s=r.indexOf(i);if(s<0)throw new Error(`JointVelocities: joint "${i}" not found in model`);return e.jnt_dofadr[s]})}getModelJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;i.push(r.decode(t.subarray(a,o)))}return i}}class _ee extends Vn{constructor(e,t){super(e,t),this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(3)),this.scale=xh(t.scale,3,1)}get size(){return 3*this.historySteps}reset(){const e=this.computeCurrent();for(const t of this.history)t.set(e)}update(){for(let e=this.history.length-1;e>0;e--)this.history[e].set(this.history[e-1]);this.history[0].set(this.computeCurrent())}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(){const t=tr().getVelocityCommand(),r=new Float32Array(t);if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}}class bee extends Vn{constructor(e,t){super(e,t),this.scale=xh(t.scale,3,1)}get size(){return 16}compute(){const e=new Float32Array(16),r=tr().getVelocityCommand(),i=new Float32Array(r);if(this.scale)for(let s=0;s<3;s++)i[s]*=this.scale[s]??1;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e}}class wee extends Vn{get size(){return 27}compute(){return new Float32Array(27)}}class Eee extends Vn{constructor(e,t){super(e,t);const r=e.getContext()?.mjModel??null;this.qposAdr=r!==null?this.resolveQposAdr(r):0}get size(){return 2}compute(){const e=this.runner.getContext()?.mjData?.qpos,t=e!==void 0?e[this.qposAdr]:0;return new Float32Array([Math.cos(t),Math.sin(t)])}resolveQposAdr(e){const t=this.config.joint_name;if(t!==void 0){const s=this.getJointNames(e).indexOf(t);if(s<0)throw new Error(`JointPosCosSin: joint "${t}" not found in model`);return e.jnt_qposadr[s]}const r=this.config.joint_index??0;return e.jnt_qposadr[r]}getJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;i.push(r.decode(t.subarray(a,o)))}return i}}class Cee extends Vn{constructor(e,t){super(e,t),this.sensorName=t.sensor_name??"";const r=e.getContext()?.mjModel??null,i=this.resolveSensor(r,this.sensorName);this.sensorAdr=i.adr,this.sensorDim=i.dim,this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(this.sensorDim)),this.scale=xh(t.scale,this.sensorDim,1),this.clipRange=this.normalizeClipRange(t.clip)}get size(){return this.sensorDim*this.historySteps}reset(){const e=this.computeCurrent();for(const t of this.history)t.set(e)}update(){for(let e=this.history.length-1;e>0;e--)this.history[e].set(this.history[e-1]);this.history[0].set(this.computeCurrent())}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(){const e=this.runner.getContext()?.mjData?.sensordata,t=new Float32Array(this.sensorDim);if(e===void 0)return t;for(let r=0;r<this.sensorDim;r++)t[r]=e[this.sensorAdr+r]??0;if(this.scale)for(let r=0;r<t.length;r++)t[r]*=this.scale[r]??1;if(this.clipRange){const[r,i]=this.clipRange;for(let s=0;s<t.length;s++)t[s]=Math.min(i,Math.max(r,t[s]))}return t}resolveSensor(e,t){if(e===null)return{adr:0,dim:1};const i=this.getModelSensorNames(e).indexOf(t);if(i<0)throw new Error(`BuiltinSensor: sensor "${t}" not found in model`);return{adr:e.sensor_adr[i],dim:e.sensor_dim[i]}}getModelSensorNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.nsensor;s++){let a=e.name_sensoradr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;i.push(r.decode(t.subarray(a,o)))}return i}normalizeClipRange(e){if(!Array.isArray(e)||e.length<2)return null;const t=typeof e[0]=="number"?e[0]:-1/0,r=typeof e[1]=="number"?e[1]:1/0;return[t,r]}}class Iee extends dP{}class See extends hP{}class Bee extends fP{}const Mee={...VZ,PrevActions:fP,PreviousActions:Bee,BootIndicator:lee,RootAngVelB:cee,ProjectedGravityB:dP,ProjectedGravity:Iee,JointPos:hP,JointPositions:See,TrackingCommandObsRaw:uee,TargetRootZObs:dee,TargetJointPosObs:hee,TargetProjectedGravityBObs:fee,MotionAnchorPosB:pee,MotionAnchorOriB:Aee,RobotBodyPosB:mee,RobotBodyOriB:gee,BaseLinearVelocity:yee,BaseAngularVelocity:xee,JointVelocities:vee,SimpleVelocityCommand:_ee,VelocityCommandWithOscillators:bee,VelocityCommandObservation:aee,VelocityCommandWithOscillatorsObservation:oee,GeneratedCommands:fB,GeneratedCommandsObservation:fB,ImpedanceCommand:wee,JointPosCosSin:Eee,BuiltinSensor:Cee};class Tee{constructor(e,t){this.terms=[];for(const[r,i]of Object.entries(e)){const s=t[i.name];if(!s){console.warn(`[TerminationManager] Unknown termination type: ${i.name}`);continue}const a={name:i.name,params:i.params,time_out:i.time_out};this.terms.push({name:r,term:new s(a),isTimeOut:i.time_out??!1})}}evaluate(e){let t=!1,r=!1;const i=[];for(const{name:s,term:a,isTimeOut:o}of this.terms)a.evaluate(e)&&(i.push(s),o?r=!0:t=!0);return{done:t||r,terminated:t,truncated:r,reasons:i}}reset(){for(const{term:e}of this.terms)e.reset?.()}get size(){return this.terms.length}}class VC{constructor(e){this.config=e}}const Ree={};class Dee extends VC{constructor(e){super(e),this.stepCount=0;const t=e.params??{};this.maxSteps=t.max_episode_length??1e3}evaluate(){return this.stepCount++,this.stepCount>=this.maxSteps}reset(){this.stepCount=0}}class kee extends VC{constructor(e){super(e);const t=e.params??{};this.limitAngle=t.limit_angle??1}evaluate(e){const t=e.rootQuat;if(!t||t.length<4)return!1;const r=t[1],i=t[2],s=1-2*(r*r+i*i),a=Math.acos(Math.max(-1,Math.min(1,s)));return Math.abs(a)>this.limitAngle}}class Nee extends VC{constructor(e){super(e);const t=e.params??{};this.minimumHeight=t.minimum_height??0}evaluate(e){const t=e.rootPos;return!t||t.length<3?!1:t[2]<this.minimumHeight}}const Qee={TimeOut:Dee,BadOrientation:kee,RootHeightBelowMinimum:Nee},Pee={...Qee,...Ree};var jC=Object.defineProperty,Lee=Object.getOwnPropertyDescriptor,Fee=Object.getOwnPropertyNames,zee=Object.prototype.hasOwnProperty,Uee=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),et=(n,e)=>()=>(n&&(e=n(n=0)),e),vh=(n,e)=>{for(var t in e)jC(n,t,{get:e[t],enumerable:!0})},Oee=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fee(e))!zee.call(n,i)&&i!==t&&jC(n,i,{get:()=>e[i],enumerable:!(r=Lee(e,i))||r.enumerable});return n},Lp=n=>Oee(jC({},"__esModule",{value:!0}),n),zf,Cl,Bd,AB,pP,AP=et(()=>{zf=new Map,Cl=[],Bd=(n,e,t)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let r=zf.get(n);if(r===void 0)zf.set(n,{backend:e,priority:t});else{if(r.priority>t)return;if(r.priority===t&&r.backend!==e)throw new Error(`cannot register backend "${n}" using priority ${t}`)}if(t>=0){let i=Cl.indexOf(n);i!==-1&&Cl.splice(i,1);for(let s=0;s<Cl.length;s++)if(zf.get(Cl[s]).priority<=t){Cl.splice(s,0,n);return}Cl.push(n)}return}throw new TypeError("not a valid backend")},AB=async n=>{let e=zf.get(n);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let t=!!e.initPromise;try{return t||(e.initPromise=e.backend.init(n)),await e.initPromise,e.initialized=!0,e.backend}catch(r){return t||(e.error=`${r}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},pP=async n=>{let e=n.executionProviders||[],t=e.map(l=>typeof l=="string"?l:l.name),r=t.length===0?Cl:t,i,s=[],a=new Set;for(let l of r){let c=await AB(l);typeof c=="string"?s.push({name:l,err:c}):(i||(i=c),i===c&&a.add(l))}if(!i)throw new Error(`no available backend found. ERR: ${s.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of s)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let o=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[i,new Proxy(n,{get:(l,c)=>c==="executionProviders"?o:Reflect.get(l,c)})]}}),$ee=et(()=>{AP()}),mP,Gee=et(()=>{mP="1.24.3"}),Kv,Tr,gP=et(()=>{Gee(),Kv="warning",Tr={wasm:{},webgl:{},webgpu:{},versions:{common:mP},set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);Kv=n}},get logLevel(){return Kv}},Object.defineProperty(Tr,"logLevel",{enumerable:!0})}),Dn,Hee=et(()=>{gP(),Dn=Tr}),yP,xP,Vee=et(()=>{yP=(n,e)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=n.dims[3],t.height=n.dims[2];let r=t.getContext("2d");if(r!=null){let i,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(i=n.dims[2],s=n.dims[3]):(i=n.dims[3],s=n.dims[2]);let a=e?.format!==void 0?e.format:"RGB",o=e?.norm,l,c;o===void 0||o.mean===void 0?l=[255,255,255,255]:typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:(l=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(l[3]=o.mean[3])),o===void 0||o.bias===void 0?c=[0,0,0,0]:typeof o.bias=="number"?c=[o.bias,o.bias,o.bias,o.bias]:(c=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(c[3]=o.bias[3]));let d=s*i,h=0,p=d,A=d*2,y=-1;a==="RGBA"?(h=0,p=d,A=d*2,y=d*3):a==="RGB"?(h=0,p=d,A=d*2):a==="RBG"&&(h=0,A=d,p=d*2);for(let m=0;m<s;m++)for(let x=0;x<i;x++){let g=(n.data[h++]-c[0])*l[0],_=(n.data[p++]-c[1])*l[1],b=(n.data[A++]-c[2])*l[2],w=y===-1?255:(n.data[y++]-c[3])*l[3];r.fillStyle="rgba("+g+","+_+","+b+","+w+")",r.fillRect(x,m,1,1)}if("toDataURL"in t)return t.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},xP=(n,e)=>{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),r;if(t!=null){let i,s,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(i=n.dims[2],s=n.dims[1],a=n.dims[3]):(i=n.dims[3],s=n.dims[2],a=n.dims[1]);let o=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let h=s*i;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let p=4,A=0,y=1,m=2,x=3,g=0,_=h,b=h*2,w=-1;o==="RGBA"?(g=0,_=h,b=h*2,w=h*3):o==="RGB"?(g=0,_=h,b=h*2):o==="RBG"&&(g=0,b=h,_=h*2),r=t.createImageData(i,s);for(let C=0;C<s*i;A+=p,y+=p,m+=p,x+=p,C++)r.data[A]=(n.data[g++]-d[0])*c[0],r.data[y]=(n.data[_++]-d[1])*c[1],r.data[m]=(n.data[b++]-d[2])*c[2],r.data[x]=w===-1?255:(n.data[w++]-d[3])*c[3]}else throw new Error("Can not access image data");return r}}),Wm,vP,_P,bP,wP,EP,jee=et(()=>{WC(),Wm=(n,e)=>{if(n===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:r}=e,i=e.norm??{mean:255,bias:0},s,a;typeof i.mean=="number"?s=[i.mean,i.mean,i.mean,i.mean]:s=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?a=[i.bias,i.bias,i.bias,i.bias]:a=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let o=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=t*r,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),h=4,p=0,A=1,y=2,m=3,x=0,g=c,_=c*2,b=-1;o==="RGB"&&(h=3,p=0,A=1,y=2,m=-1),l==="RGBA"?b=c*3:l==="RBG"?(x=0,_=c,g=c*2):l==="BGR"&&(_=0,g=c,x=c*2);for(let w=0;w<c;w++,p+=h,y+=h,A+=h,m+=h)d[x++]=(n[p]+a[0])/s[0],d[g++]=(n[A]+a[1])/s[1],d[_++]=(n[y]+a[2])/s[2],b!==-1&&m!==-1&&(d[b++]=(n[m]+a[3])/s[3]);return l==="RGBA"?new Hi("float32",d,[1,4,t,r]):new Hi("float32",d,[1,3,t,r])},vP=async(n,e)=>{let t=typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement,r=typeof ImageData<"u"&&n instanceof ImageData,i=typeof ImageBitmap<"u"&&n instanceof ImageBitmap,s=typeof n=="string",a,o=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(t){let d=l();d.width=n.width,d.height=n.height;let h=c(d);if(h!=null){let p=n.height,A=n.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(p=e.resizedHeight,A=e.resizedWidth),e!==void 0){if(o=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=p,o.width=A}else o.tensorFormat="RGBA",o.height=p,o.width=A;h.drawImage(n,0,0),a=h.getImageData(0,0,A,p).data}else throw new Error("Can not access image data")}else if(r){let d,h;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(d=e.resizedHeight,h=e.resizedWidth):(d=n.height,h=n.width),e!==void 0&&(o=e),o.format="RGBA",o.height=d,o.width=h,e!==void 0){let p=l();p.width=h,p.height=d;let A=c(p);if(A!=null)A.putImageData(n,0,0),a=A.getImageData(0,0,h,d).data;else throw new Error("Can not access image data")}else a=n.data}else if(i){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=l();d.width=n.width,d.height=n.height;let h=c(d);if(h!=null){let p=n.height,A=n.width;return h.drawImage(n,0,0,A,p),a=h.getImageData(0,0,A,p).data,o.height=p,o.width=A,Wm(a,o)}else throw new Error("Can not access image data")}else{if(s)return new Promise((d,h)=>{let p=l(),A=c(p);if(!n||!A)return h();let y=new Image;y.crossOrigin="Anonymous",y.src=n,y.onload=()=>{p.width=y.width,p.height=y.height,A.drawImage(y,0,0,p.width,p.height);let m=A.getImageData(0,0,p.width,p.height);o.height=p.height,o.width=p.width,d(Wm(m.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Wm(a,o);throw new Error("Input data provided is not supported - aborted tensor creation")},_P=(n,e)=>{let{width:t,height:r,download:i,dispose:s}=e,a=[1,r,t,4];return new Hi({location:"texture",type:"float32",texture:n,dims:a,download:i,dispose:s})},bP=(n,e)=>{let{dataType:t,dims:r,download:i,dispose:s}=e;return new Hi({location:"gpu-buffer",type:t??"float32",gpuBuffer:n,dims:r,download:i,dispose:s})},wP=(n,e)=>{let{dataType:t,dims:r,download:i,dispose:s}=e;return new Hi({location:"ml-tensor",type:t??"float32",mlTensor:n,dims:r,download:i,dispose:s})},EP=(n,e,t)=>new Hi({location:"cpu-pinned",type:n,data:e,dims:t??[e.length]})}),kc,sp,Zv,CP,Wee=et(()=>{kc=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),sp=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Zv=!1,CP=()=>{if(!Zv){Zv=!0;let n=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,r=typeof t<"u"&&t.from;n&&(kc.set("int64",BigInt64Array),sp.set(BigInt64Array,"int64")),e&&(kc.set("uint64",BigUint64Array),sp.set(BigUint64Array,"uint64")),r?(kc.set("float16",t),sp.set(t,"float16")):kc.set("float16",Uint16Array)}}}),IP,SP,qee=et(()=>{WC(),IP=n=>{let e=1;for(let t=0;t<n.length;t++){let r=n[t];if(typeof r!="number"||!Number.isSafeInteger(r))throw new TypeError(`dims[${t}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${t}] must be a non-negative integer, got: ${r}`);e*=r}return e},SP=(n,e)=>{switch(n.location){case"cpu":return new Hi(n.type,n.data,e);case"cpu-pinned":return new Hi({location:"cpu-pinned",data:n.data,type:n.type,dims:e});case"texture":return new Hi({location:"texture",texture:n.texture,type:n.type,dims:e});case"gpu-buffer":return new Hi({location:"gpu-buffer",gpuBuffer:n.gpuBuffer,type:n.type,dims:e});case"ml-tensor":return new Hi({location:"ml-tensor",mlTensor:n.mlTensor,type:n.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${n.location} is not supported`)}}}),Hi,WC=et(()=>{Vee(),jee(),Wee(),qee(),Hi=class{constructor(n,e,t){CP();let r,i;if(typeof n=="object"&&"location"in n)switch(this.dataLocation=n.location,r=n.type,i=n.dims,n.location){case"cpu-pinned":{let a=kc.get(r);if(!a)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(n.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=n.data;break}case"texture":{if(r!=="float32")throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=n.texture,this.downloader=n.download,this.disposer=n.dispose;break}case"gpu-buffer":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=n.gpuBuffer,this.downloader=n.download,this.disposer=n.dispose;break}case"ml-tensor":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint64"&&r!=="int8"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=n.mlTensor,this.downloader=n.download,this.disposer=n.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof n=="string")if(r=n,o=t,n==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=kc.get(n);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${n}.`);if(Array.isArray(e)){if(n==="float16"&&l===Uint16Array||n==="uint4"||n==="int4")throw new TypeError(`Creating a ${n} tensor from number array is not supported. Please use ${l.name} as data.`);n==="uint64"||n==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(n==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(n==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${r} tensor's data must be type of ${l}`)}else if(o=e,Array.isArray(n)){if(n.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof n[0];if(l==="string")r="string",a=n;else if(l==="boolean")r="bool",a=Uint8Array.from(n);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(n instanceof Uint8ClampedArray)r="uint8",a=Uint8Array.from(n);else{let l=sp.get(n.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${n.constructor}.`);r=l,a=n}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");i=o,this.cpuData=a,this.dataLocation="cpu"}let s=IP(i);if(this.cpuData&&s!==this.cpuData.length&&!((r==="uint4"||r==="int4")&&Math.ceil(s/2)===this.cpuData.length))throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=s}static async fromImage(n,e){return vP(n,e)}static fromTexture(n,e){return _P(n,e)}static fromGpuBuffer(n,e){return bP(n,e)}static fromMLTensor(n,e){return wP(n,e)}static fromPinnedBuffer(n,e,t){return EP(n,e,t)}toDataURL(n){return yP(this,n)}toImageData(n){return xP(this,n)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(n){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,n&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(n){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return SP(this,n)}}}),ti,BP=et(()=>{WC(),ti=Hi}),qg,e_,Fa,Zs,jc,Wc,MP=et(()=>{gP(),qg=(n,e)=>{(typeof Tr.trace>"u"?!Tr.wasm.trace:!Tr.trace)||console.timeStamp(`${n}::ORT::${e}`)},e_=(n,e)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<t.length;i++){if(r&&!t[i].includes("TRACE_FUNC")){let s=`FUNC_${n}::${t[i].trim().split(" ")[1]}`;e&&(s+=`::${e}`),qg("CPU",s);return}t[i].includes("TRACE_FUNC")&&(r=!0)}},Fa=n=>{(typeof Tr.trace>"u"?!Tr.wasm.trace:!Tr.trace)||e_("BEGIN",n)},Zs=n=>{(typeof Tr.trace>"u"?!Tr.wasm.trace:!Tr.trace)||e_("END",n)},jc=n=>{(typeof Tr.trace>"u"?!Tr.wasm.trace:!Tr.trace)||console.time(`ORT::${n}`)},Wc=n=>{(typeof Tr.trace>"u"?!Tr.wasm.trace:!Tr.trace)||console.timeEnd(`ORT::${n}`)}}),TP,Yee=et(()=>{AP(),BP(),MP(),TP=class RP{constructor(e){this.handler=e}async run(e,t,r){Fa(),jc("InferenceSession.run");let i={},s={};if(typeof e!="object"||e===null||e instanceof ti||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof ti)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);i[c]=null}if(typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,d=Object.getOwnPropertyNames(t);for(let h of this.outputNames)if(d.indexOf(h)!==-1){let p=t[h];(p===null||p instanceof ti)&&(c=!0,a=!1,i[h]=p)}if(c){if(typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else s=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)i[c]=null;let o=await this.handler.run(e,i,s),l={};for(let c in o)if(Object.hasOwnProperty.call(o,c)){let d=o[c];d instanceof ti?l[c]=d:l[c]=new ti(d.type,d.data,d.dims)}return Wc("InferenceSession.run"),Zs(),l}async release(){return this.handler.dispose()}static async create(e,t,r,i){Fa(),jc("InferenceSession.create");let s,a={};if(typeof e=="string"){if(s=e,typeof t=="object"&&t!==null)a=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(s=e,typeof t=="object"&&t!==null)a=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let d=e,h=0,p=e.byteLength;if(typeof t=="object"&&t!==null)a=t;else if(typeof t=="number"){if(h=t,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(p=e.byteLength-h,typeof r=="number"){if(p=r,!Number.isSafeInteger(p))throw new RangeError("'byteLength' must be an integer.");if(p<=0||h+p>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-h}].`);if(typeof i=="object"&&i!==null)a=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");s=new Uint8Array(d,h,p)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,l]=await pP(a),c=await o.createInferenceSessionHandler(s,l);return Wc("InferenceSession.create"),Zs(),new RP(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),qC,Jee=et(()=>{Yee(),qC=TP}),Xee=et(()=>{}),Kee=et(()=>{}),Zee=et(()=>{}),ete=et(()=>{}),tte={};vh(tte,{InferenceSession:()=>qC,TRACE:()=>qg,TRACE_EVENT_BEGIN:()=>jc,TRACE_EVENT_END:()=>Wc,TRACE_FUNC_BEGIN:()=>Fa,TRACE_FUNC_END:()=>Zs,Tensor:()=>ti,env:()=>Dn,registerBackend:()=>Bd});var xs=et(()=>{$ee(),Hee(),Jee(),BP(),Xee(),Kee(),MP(),Zee(),ete()}),YC=et(()=>{}),DP={};vh(DP,{default:()=>kP});var t_,n_,kP,nte=et(()=>{Fz(),cu(),JC(),t_="ort-wasm-proxy-worker",n_=globalThis.self?.name===t_,n_&&(self.onmessage=n=>{let{type:e,in:t}=n.data;try{switch(e){case"init-wasm":XC(t.wasm).then(()=>{pI(t).then(()=>{postMessage({type:e})},r=>{postMessage({type:e,err:r})})},r=>{postMessage({type:e,err:r})});break;case"init-ep":{let{epName:r,env:i}=t;AI(i,r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})});break}case"copy-from":{let{buffer:r}=t,i=t0(r);postMessage({type:e,out:i});break}case"create":{let{model:r,options:i}=t;mI(r,i).then(s=>{postMessage({type:e,out:s})},s=>{postMessage({type:e,err:s})});break}case"release":gI(t),postMessage({type:e});break;case"run":{let{sessionId:r,inputIndices:i,inputs:s,outputIndices:a,options:o}=t;yI(r,i,s,a,new Array(a.length).fill(null),o).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},vI([...s,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":xI(t),postMessage({type:e});break;default:}}catch(r){postMessage({type:e,err:r})}}),kP=n_?null:n=>new Worker(n??Gi,{type:"module",name:t_})}),NP={};vh(NP,{default:()=>QP});async function mB(n={}){var e=n,t=!!globalThis.window,r=!!globalThis.WorkerGlobalScope,i=r&&self.name?.startsWith("em-pthread");e.mountExternalData=(I,N)=>{I.startsWith("./")&&(I=I.substring(2)),(e.Zc||(e.Zc=new Map)).set(I,N)},e.unmountExternalData=()=>{delete e.Zc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,ae:!0}).buffer.constructor;let s=I=>async(...N)=>{try{if(e.$c)throw Error("Session already started");let O=e.$c={Nd:N[0],errors:[]},z=await I(...N);if(e.$c!==O)throw Error("Session mismatch");e.gd?.flush();let se=O.errors;if(0<se.length){let ce=await Promise.all(se);if(ce=ce.filter(Se=>Se),0<ce.length)throw Error(ce.join(`
|
|
12825
|
+
`);new ys(new ue(-1,-1,-1),new ue(1,1,1)),new ue(-1,-3,1).normalize(),new xt(1,1,1),new xt(.5,.5,1),new ue(1,1,1);new ys(new ue(-2,-1,-2),new ue(2,5,2)),new ue(0,-1,0),new xt(1,1,1),new xt(.25,.25,.5),new ue(.1,1,.1);const sP=class _w{static createButton(e,t={}){const r=navigator.xr;if(!r)return null;const i=r,s=document.createElement("button");e.xr.enabled=!0,e.xr.setReferenceSpaceType("local");function a(){let h=null;async function p(m){console.log("onSessionStarted"),m.addEventListener("end",A),await e.xr.setSession(m),s.textContent="EXIT VR",h=m}function A(){console.log("onSessionEnded"),h?.removeEventListener("end",A),s.textContent="ENTER VR",h=null}s.style.display="",s.style.cursor="pointer",s.style.left="calc(50% - 100px)",s.style.width="200px",s.style.height="100px",s.textContent="ENTER VR";const y={...t,optionalFeatures:[...t.optionalFeatures||[]]};s.onmouseenter=()=>{s.style.opacity="1.0"},s.onmouseleave=()=>{s.style.opacity="0.5"},s.onclick=()=>{h===null?(console.log("requesting session"),i.requestSession("immersive-vr",y).then(p)):(console.log("ending session"),h.end())}}function o(){s.style.display="none",s.style.cursor="auto",s.style.left="calc(50% - 75px)",s.style.width="150px",s.onmouseenter=null,s.onmouseleave=null,s.onclick=null}function l(){o(),s.textContent="VR NOT SUPPORTED"}function c(h){o(),console.warn("Exception when trying to call xr.isSessionSupported",h),s.textContent="VR NOT ALLOWED"}function d(h){h.style.position="absolute",h.style.bottom="20px",h.style.padding="12px 6px",h.style.border="1px solid #fff",h.style.borderRadius="4px",h.style.background="rgba(0,0,0,0.1)",h.style.color="#fff",h.style.font="normal 13px sans-serif",h.style.textAlign="center",h.style.opacity="0.5",h.style.outline="none",h.style.zIndex="999"}return s.id="VRButton",s.style.display="none",d(s),i.isSessionSupported("immersive-vr").then(h=>{h?a():l(),h&&_w.xrSessionIsGranted&&s.click()}).catch(c),s}static registerSessionGrantedListener(){const e=navigator.xr;if(!e)return null;const t=e;/WebXRViewer\//i.test(navigator.userAgent)||t.addEventListener("sessiongranted",()=>{_w.xrSessionIsGranted=!0})}};sP.xrSessionIsGranted=!1;let nZ=sP;nZ.registerSessionGrantedListener();var aP=(n=>(n.w="wrist",n.t0="thumb-metacarpal",n.t1="thumb-phalanx-proximal",n.t2="thumb-phalanx-distal",n.t3="thumb-tip",n.i0="index-finger-metacarpal",n.i1="index-finger-phalanx-proximal",n.i2="index-finger-phalanx-intermediate",n.i3="index-finger-phalanx-distal",n.i4="index-finger-tip",n.m0="middle-finger-metacarpal",n.m1="middle-finger-phalanx-proximal",n.m2="middle-finger-phalanx-intermediate",n.m3="middle-finger-phalanx-distal",n.m4="middle-finger-tip",n.r0="ring-finger-metacarpal",n.r1="ring-finger-phalanx-proximal",n.r2="ring-finger-phalanx-intermediate",n.r3="ring-finger-phalanx-distal",n.r4="ring-finger-tip",n.p0="pinky-finger-metacarpal",n.p1="pinky-finger-phalanx-proximal",n.p2="pinky-finger-phalanx-intermediate",n.p3="pinky-finger-phalanx-distal",n.p4="pinky-finger-tip",n))(aP||{});const rZ=Object.keys(aP);rZ.length;new ue(0,0,-1),new ue(0,0,1),new ue(-1,0,0),new ue(1,0,0),new ue(0,1,0),new ue(0,-1,0);new ue(0,0,-1),new ue(0,0,1),new ue(-1,0,0),new ue(1,0,0),new ue(0,1,0),new ue(0,-1,0);new ue(0,0,1),new ue(0,0,-1);new ue(0,-1,0),new ue(0,1,0),new ue(-1,0,0),new ue(1,0,0);const jv=Math.PI/180,iZ=new Cn().setFromEuler(new ji(Math.PI,0,0));function oP(n,e){const t=e.scale??1,r=e.xOffset??0,i=e.yOffset??0,s=e.zOffset??0,a=(e.roll??0)*jv,o=(e.pitch??0)*jv,l=(e.yaw??0)*jv;n.scale.setScalar(t);const c=new Cn().setFromEuler(new ji(o,l,a));n.quaternion.copy(iZ.clone().multiply(c)),n.position.set(r*t,s*t,i*t)}function tB(n,e){const t=n.url;if(!t)throw new Error("SplatConfig.url must be resolved before calling loadSplat. Use App.tsx resolvedSplatConfig.");const r=new LC({url:t});return oP(r,n),e.add(r),r}function nB(n,e){e.remove(n),n.dispose?.()}function rB(n,e){if(e===cV)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===rw||e===VN){let t=n.getIndex();if(t===null){const a=[],o=n.getAttribute("position");if(o!==void 0){for(let l=0;l<o.count;l++)a.push(l);n.setIndex(a),t=n.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),n}const r=t.count-2,i=[];if(e===rw)for(let a=1;a<=r;a++)i.push(t.getX(0)),i.push(t.getX(a)),i.push(t.getX(a+1));else for(let a=0;a<r;a++)a%2===0?(i.push(t.getX(a)),i.push(t.getX(a+1)),i.push(t.getX(a+2))):(i.push(t.getX(a+2)),i.push(t.getX(a+1)),i.push(t.getX(a)));i.length/3!==r&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const s=n.clone();return s.setIndex(i),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),n}class sZ extends lu{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new uZ(t)}),this.register(function(t){return new dZ(t)}),this.register(function(t){return new vZ(t)}),this.register(function(t){return new _Z(t)}),this.register(function(t){return new bZ(t)}),this.register(function(t){return new fZ(t)}),this.register(function(t){return new pZ(t)}),this.register(function(t){return new AZ(t)}),this.register(function(t){return new mZ(t)}),this.register(function(t){return new cZ(t)}),this.register(function(t){return new gZ(t)}),this.register(function(t){return new hZ(t)}),this.register(function(t){return new xZ(t)}),this.register(function(t){return new yZ(t)}),this.register(function(t){return new oZ(t)}),this.register(function(t){return new wZ(t)}),this.register(function(t){return new EZ(t)})}load(e,t,r,i){const s=this;let a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){const c=fp.extractUrlBase(e);a=fp.resolveURL(c,this.path)}else a=fp.extractUrlBase(e);this.manager.itemStart(e);const o=function(c){i?i(c):console.error(c),s.manager.itemError(e),s.manager.itemEnd(e)},l=new IC(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{s.parse(c,a,function(d){t(d),s.manager.itemEnd(e)},o)}catch(d){o(d)}},r,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,r,i){let s;const a={},o={},l=new TextDecoder;if(typeof e=="string")s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===lP){try{a[cn.KHR_BINARY_GLTF]=new CZ(e)}catch(h){i&&i(h);return}s=JSON.parse(a[cn.KHR_BINARY_GLTF].content)}else s=JSON.parse(l.decode(e));else s=e;if(s.asset===void 0||s.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const c=new FZ(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let d=0;d<this.pluginCallbacks.length;d++){const h=this.pluginCallbacks[d](c);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),o[h.name]=h,a[h.name]=!0}if(s.extensionsUsed)for(let d=0;d<s.extensionsUsed.length;++d){const h=s.extensionsUsed[d],p=s.extensionsRequired||[];switch(h){case cn.KHR_MATERIALS_UNLIT:a[h]=new lZ;break;case cn.KHR_DRACO_MESH_COMPRESSION:a[h]=new IZ(s,this.dracoLoader);break;case cn.KHR_TEXTURE_TRANSFORM:a[h]=new SZ;break;case cn.KHR_MESH_QUANTIZATION:a[h]=new BZ;break;default:p.indexOf(h)>=0&&o[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}c.setExtensions(a),c.setPlugins(o),c.parse(r,i)}parseAsync(e,t){const r=this;return new Promise(function(i,s){r.parse(e,t,i,s)})}}function aZ(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}const cn={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class oZ{constructor(e){this.parser=e,this.name=cn.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let r=0,i=t.length;r<i;r++){const s=t[r];s.extensions&&s.extensions[this.name]&&s.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,s.extensions[this.name].light)}}_loadLight(e){const t=this.parser,r="light:"+e;let i=t.cache.get(r);if(i)return i;const s=t.json,l=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e];let c;const d=new xt(16777215);l.color!==void 0&&d.setRGB(l.color[0],l.color[1],l.color[2],ii);const h=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new lw(d),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new hQ(d),c.distance=h;break;case"spot":c=new dQ(d),c.distance=h,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),ba(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),i=Promise.resolve(c),t.cache.add(r,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,r=this.parser,s=r.json.nodes[e],o=(s.extensions&&s.extensions[this.name]||{}).light;return o===void 0?null:this._loadLight(o).then(function(l){return r._getNodeRef(t.cache,o,l)})}}class lZ{constructor(){this.name=cn.KHR_MATERIALS_UNLIT}getMaterialType(){return zc}extendParams(e,t,r){const i=[];e.color=new xt(1,1,1),e.opacity=1;const s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){const a=s.baseColorFactor;e.color.setRGB(a[0],a[1],a[2],ii),e.opacity=a[3]}s.baseColorTexture!==void 0&&i.push(r.assignTexture(e,"map",s.baseColorTexture,gr))}return Promise.all(i)}}class cZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name].emissiveStrength;return s!==void 0&&(t.emissiveIntensity=s),Promise.resolve()}}class uZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&s.push(r.assignTexture(t,"clearcoatMap",a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&s.push(r.assignTexture(t,"clearcoatRoughnessMap",a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(s.push(r.assignTexture(t,"clearcoatNormalMap",a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){const o=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Dt(o,o)}return Promise.all(s)}}class dZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_DISPERSION}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name];return t.dispersion=s.dispersion!==void 0?s.dispersion:0,Promise.resolve()}}class hZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&s.push(r.assignTexture(t,"iridescenceMap",a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&s.push(r.assignTexture(t,"iridescenceThicknessMap",a.iridescenceThicknessTexture)),Promise.all(s)}}class fZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_SHEEN}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[];t.sheenColor=new xt(0,0,0),t.sheenRoughness=0,t.sheen=1;const a=i.extensions[this.name];if(a.sheenColorFactor!==void 0){const o=a.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],ii)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&s.push(r.assignTexture(t,"sheenColorMap",a.sheenColorTexture,gr)),a.sheenRoughnessTexture!==void 0&&s.push(r.assignTexture(t,"sheenRoughnessMap",a.sheenRoughnessTexture)),Promise.all(s)}}class pZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&s.push(r.assignTexture(t,"transmissionMap",a.transmissionTexture)),Promise.all(s)}}class AZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_VOLUME}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];t.thickness=a.thicknessFactor!==void 0?a.thicknessFactor:0,a.thicknessTexture!==void 0&&s.push(r.assignTexture(t,"thicknessMap",a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;const o=a.attenuationColor||[1,1,1];return t.attenuationColor=new xt().setRGB(o[0],o[1],o[2],ii),Promise.all(s)}}class mZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_IOR}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=i.extensions[this.name];return t.ior=s.ior!==void 0?s.ior:1.5,Promise.resolve()}}class gZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_SPECULAR}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];t.specularIntensity=a.specularFactor!==void 0?a.specularFactor:1,a.specularTexture!==void 0&&s.push(r.assignTexture(t,"specularIntensityMap",a.specularTexture));const o=a.specularColorFactor||[1,1,1];return t.specularColor=new xt().setRGB(o[0],o[1],o[2],ii),a.specularColorTexture!==void 0&&s.push(r.assignTexture(t,"specularColorMap",a.specularColorTexture,gr)),Promise.all(s)}}class yZ{constructor(e){this.parser=e,this.name=cn.EXT_MATERIALS_BUMP}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];return t.bumpScale=a.bumpFactor!==void 0?a.bumpFactor:1,a.bumpTexture!==void 0&&s.push(r.assignTexture(t,"bumpMap",a.bumpTexture)),Promise.all(s)}}class xZ{constructor(e){this.parser=e,this.name=cn.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const r=this.parser.json.materials[e];return!r.extensions||!r.extensions[this.name]?null:fs}extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const s=[],a=i.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&s.push(r.assignTexture(t,"anisotropyMap",a.anisotropyTexture)),Promise.all(s)}}class vZ{constructor(e){this.parser=e,this.name=cn.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,r=t.json,i=r.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const s=i.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(r.extensionsRequired&&r.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,a)}}class _Z{constructor(e){this.parser=e,this.name=cn.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,r=this.parser,i=r.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const a=s.extensions[t],o=i.images[a.source];let l=r.textureLoader;if(o.uri){const c=r.options.manager.getHandler(o.uri);c!==null&&(l=c)}return r.loadTextureImage(e,a.source,l)}}class bZ{constructor(e){this.parser=e,this.name=cn.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,r=this.parser,i=r.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;const a=s.extensions[t],o=i.images[a.source];let l=r.textureLoader;if(o.uri){const c=r.options.manager.getHandler(o.uri);c!==null&&(l=c)}return r.loadTextureImage(e,a.source,l)}}class wZ{constructor(e){this.name=cn.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,r=t.bufferViews[e];if(r.extensions&&r.extensions[this.name]){const i=r.extensions[this.name],s=this.parser.getDependency("buffer",i.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(o){const l=i.byteOffset||0,c=i.byteLength||0,d=i.count,h=i.byteStride,p=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(d,h,p,i.mode,i.filter).then(function(A){return A.buffer}):a.ready.then(function(){const A=new ArrayBuffer(d*h);return a.decodeGltfBuffer(new Uint8Array(A),d,h,p,i.mode,i.filter),A})})}else return null}}class EZ{constructor(e){this.name=cn.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,r=t.nodes[e];if(!r.extensions||!r.extensions[this.name]||r.mesh===void 0)return null;const i=t.meshes[r.mesh];for(const c of i.primitives)if(c.mode!==rs.TRIANGLES&&c.mode!==rs.TRIANGLE_STRIP&&c.mode!==rs.TRIANGLE_FAN&&c.mode!==void 0)return null;const a=r.extensions[this.name].attributes,o=[],l={};for(const c in a)o.push(this.parser.getDependency("accessor",a[c]).then(d=>(l[c]=d,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const d=c.pop(),h=d.isGroup?d.children:[d],p=c[0].count,A=[];for(const y of h){const m=new Ft,x=new ue,g=new Cn,_=new ue(1,1,1),b=new aw(y.geometry,y.material,p);for(let w=0;w<p;w++)l.TRANSLATION&&x.fromBufferAttribute(l.TRANSLATION,w),l.ROTATION&&g.fromBufferAttribute(l.ROTATION,w),l.SCALE&&_.fromBufferAttribute(l.SCALE,w),b.setMatrixAt(w,m.compose(x,g,_));for(const w in l)if(w==="_COLOR_0"){const C=l[w];b.instanceColor=new $g(C.array,C.itemSize,C.normalized)}else w!=="TRANSLATION"&&w!=="ROTATION"&&w!=="SCALE"&&y.geometry.setAttribute(w,l[w]);zn.prototype.copy.call(b,y),this.parser.assignFinalMaterial(b),A.push(b)}return d.isGroup?(d.clear(),d.add(...A),d):A[0]}))}}const lP="glTF",Lf=12,iB={JSON:1313821514,BIN:5130562};class CZ{constructor(e){this.name=cn.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Lf),r=new TextDecoder;if(this.header={magic:r.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==lP)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-Lf,s=new DataView(e,Lf);let a=0;for(;a<i;){const o=s.getUint32(a,!0);a+=4;const l=s.getUint32(a,!0);if(a+=4,l===iB.JSON){const c=new Uint8Array(e,Lf+a,o);this.content=r.decode(c)}else if(l===iB.BIN){const c=Lf+a;this.body=e.slice(c,c+o)}a+=o}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class IZ{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=cn.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const r=this.json,i=this.dracoLoader,s=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(const d in a){const h=bw[d]||d.toLowerCase();o[h]=a[d]}for(const d in e.attributes){const h=bw[d]||d.toLowerCase();if(a[d]!==void 0){const p=r.accessors[e.attributes[d]],A=Ld[p.componentType];c[h]=A.name,l[h]=p.normalized===!0}}return t.getDependency("bufferView",s).then(function(d){return new Promise(function(h,p){i.decodeDracoFile(d,function(A){for(const y in A.attributes){const m=A.attributes[y],x=l[y];x!==void 0&&(m.normalized=x)}h(A)},o,c,ii,p)})})}}class SZ{constructor(){this.name=cn.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class BZ{constructor(){this.name=cn.KHR_MESH_QUANTIZATION}}class cP extends Gp{constructor(e,t,r,i){super(e,t,r,i)}copySampleValue_(e){const t=this.resultBuffer,r=this.sampleValues,i=this.valueSize,s=e*i*3+i;for(let a=0;a!==i;a++)t[a]=r[s+a];return t}interpolate_(e,t,r,i){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=o*2,c=o*3,d=i-t,h=(r-t)/d,p=h*h,A=p*h,y=e*c,m=y-c,x=-2*A+3*p,g=A-p,_=1-x,b=g-p+h;for(let w=0;w!==o;w++){const C=a[m+w+o],S=a[m+w+l]*d,M=a[y+w+o],T=a[y+w]*d;s[w]=_*C+b*S+x*M+g*T}return s}}const MZ=new Cn;class TZ extends cP{interpolate_(e,t,r,i){const s=super.interpolate_(e,t,r,i);return MZ.fromArray(s).normalize().toArray(s),s}}const rs={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},Ld={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},sB={9728:yr,9729:ar,9984:FN,9985:Ag,9986:Zf,9987:Sa},aB={33071:ls,33648:Lg,10497:Fl},Wv={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},bw={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},El={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},RZ={CUBICSPLINE:void 0,LINEAR:Tp,STEP:Mp},qv={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function DZ(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new qd({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Co})),n.DefaultMaterial}function bc(n,e,t){for(const r in t.extensions)n[r]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[r]=t.extensions[r])}function ba(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function kZ(n,e,t){let r=!1,i=!1,s=!1;for(let c=0,d=e.length;c<d;c++){const h=e[c];if(h.POSITION!==void 0&&(r=!0),h.NORMAL!==void 0&&(i=!0),h.COLOR_0!==void 0&&(s=!0),r&&i&&s)break}if(!r&&!i&&!s)return Promise.resolve(n);const a=[],o=[],l=[];for(let c=0,d=e.length;c<d;c++){const h=e[c];if(r){const p=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):n.attributes.position;a.push(p)}if(i){const p=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):n.attributes.normal;o.push(p)}if(s){const p=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):n.attributes.color;l.push(p)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then(function(c){const d=c[0],h=c[1],p=c[2];return r&&(n.morphAttributes.position=d),i&&(n.morphAttributes.normal=h),s&&(n.morphAttributes.color=p),n.morphTargetsRelative=!0,n})}function NZ(n,e){if(n.updateMorphTargets(),e.weights!==void 0)for(let t=0,r=e.weights.length;t<r;t++)n.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(n.morphTargetInfluences.length===t.length){n.morphTargetDictionary={};for(let r=0,i=t.length;r<i;r++)n.morphTargetDictionary[t[r]]=r}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function QZ(n){let e;const t=n.extensions&&n.extensions[cn.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Yv(t.attributes):e=n.indices+":"+Yv(n.attributes)+":"+n.mode,n.targets!==void 0)for(let r=0,i=n.targets.length;r<i;r++)e+=":"+Yv(n.targets[r]);return e}function Yv(n){let e="";const t=Object.keys(n).sort();for(let r=0,i=t.length;r<i;r++)e+=t[r]+":"+n[t[r]]+";";return e}function ww(n){switch(n){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function PZ(n){return n.search(/\.jpe?g($|\?)/i)>0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const LZ=new Ft;class FZ{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new aZ,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let r=!1,i=-1,s=!1,a=-1;if(typeof navigator<"u"){const o=navigator.userAgent;r=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);i=r&&l?parseInt(l[1],10):-1,s=o.indexOf("Firefox")>-1,a=s?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||r&&i<17||s&&a<98?this.textureLoader=new N9(this.options.manager):this.textureLoader=new U9(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new IC(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const r=this,i=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([r.getDependencies("scene"),r.getDependencies("animation"),r.getDependencies("camera")])}).then(function(a){const o={scene:a[0][i.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:i.asset,parser:r,userData:{}};return bc(s,o,i),ba(o,i),Promise.all(r._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],r=this.json.meshes||[];for(let i=0,s=t.length;i<s;i++){const a=t[i].joints;for(let o=0,l=a.length;o<l;o++)e[a[o]].isBone=!0}for(let i=0,s=e.length;i<s;i++){const a=e[i];a.mesh!==void 0&&(this._addNodeRef(this.meshCache,a.mesh),a.skin!==void 0&&(r[a.mesh].isSkinnedMesh=!0)),a.camera!==void 0&&this._addNodeRef(this.cameraCache,a.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,r){if(e.refs[t]<=1)return r;const i=r.clone(),s=(a,o)=>{const l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(const[c,d]of a.children.entries())s(d,o.children[c])};return s(r,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let r=0;r<t.length;r++){const i=e(t[r]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const r=[];for(let i=0;i<t.length;i++){const s=e(t[i]);s&&r.push(s)}return r}getDependency(e,t){const r=e+":"+t;let i=this.cache.get(r);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(s){return s.loadNode&&s.loadNode(t)});break;case"mesh":i=this._invokeOne(function(s){return s.loadMesh&&s.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(s){return s.loadBufferView&&s.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(s){return s.loadMaterial&&s.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(s){return s.loadTexture&&s.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(s){return s.loadAnimation&&s.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(s){return s!=this&&s.getDependency&&s.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(r,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const r=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(s,a){return r.getDependency(e,a)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],r=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[cn.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(s,a){r.load(fp.resolveURL(t.uri,i.path),s,void 0,function(){a(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(r){const i=t.byteLength||0,s=t.byteOffset||0;return r.slice(s,s+i)})}loadAccessor(e){const t=this,r=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const a=Wv[i.type],o=Ld[i.componentType],l=i.normalized===!0,c=new o(i.count*a);return Promise.resolve(new cr(c,a,l))}const s=[];return i.bufferView!==void 0?s.push(this.getDependency("bufferView",i.bufferView)):s.push(null),i.sparse!==void 0&&(s.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(s).then(function(a){const o=a[0],l=Wv[i.type],c=Ld[i.componentType],d=c.BYTES_PER_ELEMENT,h=d*l,p=i.byteOffset||0,A=i.bufferView!==void 0?r.bufferViews[i.bufferView].byteStride:void 0,y=i.normalized===!0;let m,x;if(A&&A!==h){const g=Math.floor(p/A),_="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+g+":"+i.count;let b=t.cache.get(_);b||(m=new c(o,g*A,i.count*A/d),b=new a9(m,A/d),t.cache.add(_,b)),x=new xC(b,l,p%A/d,y)}else o===null?m=new c(i.count*l):m=new c(o,p,i.count*l),x=new cr(m,l,y);if(i.sparse!==void 0){const g=Wv.SCALAR,_=Ld[i.sparse.indices.componentType],b=i.sparse.indices.byteOffset||0,w=i.sparse.values.byteOffset||0,C=new _(a[1],b,i.sparse.count*g),S=new c(a[2],w,i.sparse.count*l);o!==null&&(x=new cr(x.array.slice(),x.itemSize,x.normalized)),x.normalized=!1;for(let M=0,T=C.length;M<T;M++){const R=C[M];if(x.setX(R,S[M*l]),l>=2&&x.setY(R,S[M*l+1]),l>=3&&x.setZ(R,S[M*l+2]),l>=4&&x.setW(R,S[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}x.normalized=y}return x})}loadTexture(e){const t=this.json,r=this.options,s=t.textures[e].source,a=t.images[s];let o=this.textureLoader;if(a.uri){const l=r.manager.getHandler(a.uri);l!==null&&(o=l)}return this.loadTextureImage(e,s,o)}loadTextureImage(e,t,r){const i=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,r).then(function(d){d.flipY=!1,d.name=a.name||o.name||"",d.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(d.name=o.uri);const p=(s.samplers||{})[a.sampler]||{};return d.magFilter=sB[p.magFilter]||ar,d.minFilter=sB[p.minFilter]||Sa,d.wrapS=aB[p.wrapS]||Fl,d.wrapT=aB[p.wrapT]||Fl,d.generateMipmaps=!d.isCompressedTexture&&d.minFilter!==yr&&d.minFilter!==ar,i.associations.set(d,{textures:e}),d}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){const r=this,i=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());const a=i.images[e],o=self.URL||self.webkitURL;let l=a.uri||"",c=!1;if(a.bufferView!==void 0)l=r.getDependency("bufferView",a.bufferView).then(function(h){c=!0;const p=new Blob([h],{type:a.mimeType});return l=o.createObjectURL(p),l});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const d=Promise.resolve(l).then(function(h){return new Promise(function(p,A){let y=p;t.isImageBitmapLoader===!0&&(y=function(m){const x=new lr(m);x.needsUpdate=!0,p(x)}),t.load(fp.resolveURL(h,s.path),y,void 0,A)})}).then(function(h){return c===!0&&o.revokeObjectURL(l),ba(h,a),h.userData.mimeType=a.mimeType||PZ(a.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),h});return this.sourceCache[e]=d,d}assignTexture(e,t,r,i){const s=this;return this.getDependency("texture",r.index).then(function(a){if(!a)return null;if(r.texCoord!==void 0&&r.texCoord>0&&(a=a.clone(),a.channel=r.texCoord),s.extensions[cn.KHR_TEXTURE_TRANSFORM]){const o=r.extensions!==void 0?r.extensions[cn.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=s.associations.get(a);a=s.extensions[cn.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),s.associations.set(a,l)}}return i!==void 0&&(a.colorSpace=i),e[t]=a,a})}assignFinalMaterial(e){const t=e.geometry;let r=e.material;const i=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){const o="PointsMaterial:"+r.uuid;let l=this.cache.get(o);l||(l=new aQ,Ks.prototype.copy.call(l,r),l.color.copy(r.color),l.map=r.map,l.sizeAttenuation=!1,this.cache.add(o,l)),r=l}else if(e.isLine){const o="LineBasicMaterial:"+r.uuid;let l=this.cache.get(o);l||(l=new sQ,Ks.prototype.copy.call(l,r),l.color.copy(r.color),l.map=r.map,this.cache.add(o,l)),r=l}if(i||s||a){let o="ClonedMaterial:"+r.uuid+":";i&&(o+="derivative-tangents:"),s&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=r.clone(),s&&(l.vertexColors=!0),a&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(o,l),this.associations.set(l,this.associations.get(r))),r=l}e.material=r}getMaterialType(){return qd}loadMaterial(e){const t=this,r=this.json,i=this.extensions,s=r.materials[e];let a;const o={},l=s.extensions||{},c=[];if(l[cn.KHR_MATERIALS_UNLIT]){const h=i[cn.KHR_MATERIALS_UNLIT];a=h.getMaterialType(),c.push(h.extendParams(o,s,t))}else{const h=s.pbrMetallicRoughness||{};if(o.color=new xt(1,1,1),o.opacity=1,Array.isArray(h.baseColorFactor)){const p=h.baseColorFactor;o.color.setRGB(p[0],p[1],p[2],ii),o.opacity=p[3]}h.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",h.baseColorTexture,gr)),o.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,o.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",h.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",h.metallicRoughnessTexture))),a=this._invokeOne(function(p){return p.getMaterialType&&p.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(p){return p.extendMaterialParams&&p.extendMaterialParams(e,o)})))}s.doubleSided===!0&&(o.side=is);const d=s.alphaMode||qv.OPAQUE;if(d===qv.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,d===qv.MASK&&(o.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&a!==zc&&(c.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new Dt(1,1),s.normalTexture.scale!==void 0)){const h=s.normalTexture.scale;o.normalScale.set(h,h)}if(s.occlusionTexture!==void 0&&a!==zc&&(c.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&a!==zc){const h=s.emissiveFactor;o.emissive=new xt().setRGB(h[0],h[1],h[2],ii)}return s.emissiveTexture!==void 0&&a!==zc&&c.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,gr)),Promise.all(c).then(function(){const h=new a(o);return s.name&&(h.name=s.name),ba(h,s),t.associations.set(h,{materials:e}),s.extensions&&bc(i,h,s),h})}createUniqueName(e){const t=Bn.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,r=this.extensions,i=this.primitiveCache;function s(o){return r[cn.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return oB(l,o,t)})}const a=[];for(let o=0,l=e.length;o<l;o++){const c=e[o],d=QZ(c),h=i[d];if(h)a.push(h.promise);else{let p;c.extensions&&c.extensions[cn.KHR_DRACO_MESH_COMPRESSION]?p=s(c):p=oB(new wr,c,t),i[d]={primitive:c,promise:p},a.push(p)}}return Promise.all(a)}loadMesh(e){const t=this,r=this.json,i=this.extensions,s=r.meshes[e],a=s.primitives,o=[];for(let l=0,c=a.length;l<c;l++){const d=a[l].material===void 0?DZ(this.cache):this.getDependency("material",a[l].material);o.push(d)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(l){const c=l.slice(0,l.length-1),d=l[l.length-1],h=[];for(let A=0,y=d.length;A<y;A++){const m=d[A],x=a[A];let g;const _=c[A];if(x.mode===rs.TRIANGLES||x.mode===rs.TRIANGLE_STRIP||x.mode===rs.TRIANGLE_FAN||x.mode===void 0)g=s.isSkinnedMesh===!0?new l9(m,_):new Kn(m,_),g.isSkinnedMesh===!0&&g.normalizeSkinWeights(),x.mode===rs.TRIANGLE_STRIP?g.geometry=rB(g.geometry,VN):x.mode===rs.TRIANGLE_FAN&&(g.geometry=rB(g.geometry,rw));else if(x.mode===rs.LINES)g=new p9(m,_);else if(x.mode===rs.LINE_STRIP)g=new bC(m,_);else if(x.mode===rs.LINE_LOOP)g=new A9(m,_);else if(x.mode===rs.POINTS)g=new m9(m,_);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+x.mode);Object.keys(g.geometry.morphAttributes).length>0&&NZ(g,s),g.name=t.createUniqueName(s.name||"mesh_"+e),ba(g,s),x.extensions&&bc(i,g,x),t.assignFinalMaterial(g),h.push(g)}for(let A=0,y=h.length;A<y;A++)t.associations.set(h[A],{meshes:e,primitives:A});if(h.length===1)return s.extensions&&bc(i,h[0],s),h[0];const p=new cs;s.extensions&&bc(i,p,s),t.associations.set(p,{meshes:e});for(let A=0,y=h.length;A<y;A++)p.add(h[A]);return p})}loadCamera(e){let t;const r=this.json.cameras[e],i=r[r.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return r.type==="perspective"?t=new zr(qN.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):r.type==="orthographic"&&(t=new U0(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),r.name&&(t.name=this.createUniqueName(r.name)),ba(t,r),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],r=[];for(let i=0,s=t.joints.length;i<s;i++)r.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?r.push(this.getDependency("accessor",t.inverseBindMatrices)):r.push(null),Promise.all(r).then(function(i){const s=i.pop(),a=i,o=[],l=[];for(let c=0,d=a.length;c<d;c++){const h=a[c];if(h){o.push(h);const p=new Ft;s!==null&&p.fromArray(s.array,c*16),l.push(p)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new vC(o,l)})}loadAnimation(e){const t=this.json,r=this,i=t.animations[e],s=i.name?i.name:"animation_"+e,a=[],o=[],l=[],c=[],d=[];for(let h=0,p=i.channels.length;h<p;h++){const A=i.channels[h],y=i.samplers[A.sampler],m=A.target,x=m.node,g=i.parameters!==void 0?i.parameters[y.input]:y.input,_=i.parameters!==void 0?i.parameters[y.output]:y.output;m.node!==void 0&&(a.push(this.getDependency("node",x)),o.push(this.getDependency("accessor",g)),l.push(this.getDependency("accessor",_)),c.push(y),d.push(m))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(d)]).then(function(h){const p=h[0],A=h[1],y=h[2],m=h[3],x=h[4],g=[];for(let b=0,w=p.length;b<w;b++){const C=p[b],S=A[b],M=y[b],T=m[b],R=x[b];if(C===void 0)continue;C.updateMatrix&&C.updateMatrix();const k=r._createAnimationTracks(C,S,M,T,R);if(k)for(let G=0;G<k.length;G++)g.push(k[G])}const _=new S9(s,void 0,g);return ba(_,i),_})}createNodeMesh(e){const t=this.json,r=this,i=t.nodes[e];return i.mesh===void 0?null:r.getDependency("mesh",i.mesh).then(function(s){const a=r._getNodeRef(r.meshCache,i.mesh,s);return i.weights!==void 0&&a.traverse(function(o){if(o.isMesh)for(let l=0,c=i.weights.length;l<c;l++)o.morphTargetInfluences[l]=i.weights[l]}),a})}loadNode(e){const t=this.json,r=this,i=t.nodes[e],s=r._loadNodeShallow(e),a=[],o=i.children||[];for(let c=0,d=o.length;c<d;c++)a.push(r.getDependency("node",o[c]));const l=i.skin===void 0?Promise.resolve(null):r.getDependency("skin",i.skin);return Promise.all([s,Promise.all(a),l]).then(function(c){const d=c[0],h=c[1],p=c[2];p!==null&&d.traverse(function(A){A.isSkinnedMesh&&A.bind(p,LZ)});for(let A=0,y=h.length;A<y;A++)d.add(h[A]);return d})}_loadNodeShallow(e){const t=this.json,r=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const s=t.nodes[e],a=s.name?i.createUniqueName(s.name):"",o=[],l=i._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&o.push(l),s.camera!==void 0&&o.push(i.getDependency("camera",s.camera).then(function(c){return i._getNodeRef(i.cameraCache,s.camera,c)})),i._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){o.push(c)}),this.nodeCache[e]=Promise.all(o).then(function(c){let d;if(s.isBone===!0?d=new iQ:c.length>1?d=new cs:c.length===1?d=c[0]:d=new zn,d!==c[0])for(let h=0,p=c.length;h<p;h++)d.add(c[h]);if(s.name&&(d.userData.name=s.name,d.name=a),ba(d,s),s.extensions&&bc(r,d,s),s.matrix!==void 0){const h=new Ft;h.fromArray(s.matrix),d.applyMatrix4(h)}else s.translation!==void 0&&d.position.fromArray(s.translation),s.rotation!==void 0&&d.quaternion.fromArray(s.rotation),s.scale!==void 0&&d.scale.fromArray(s.scale);if(!i.associations.has(d))i.associations.set(d,{});else if(s.mesh!==void 0&&i.meshCache.refs[s.mesh]>1){const h=i.associations.get(d);i.associations.set(d,{...h})}return i.associations.get(d).nodes=e,d}),this.nodeCache[e]}loadScene(e){const t=this.extensions,r=this.json.scenes[e],i=this,s=new cs;r.name&&(s.name=i.createUniqueName(r.name)),ba(s,r),r.extensions&&bc(t,s,r);const a=r.nodes||[],o=[];for(let l=0,c=a.length;l<c;l++)o.push(i.getDependency("node",a[l]));return Promise.all(o).then(function(l){for(let d=0,h=l.length;d<h;d++)s.add(l[d]);const c=d=>{const h=new Map;for(const[p,A]of i.associations)(p instanceof Ks||p instanceof lr)&&h.set(p,A);return d.traverse(p=>{const A=i.associations.get(p);A!=null&&h.set(p,A)}),h};return i.associations=c(s),s})}_createAnimationTracks(e,t,r,i,s){const a=[],o=e.name?e.name:e.uuid,l=[];El[s.path]===El.weights?e.traverse(function(p){p.morphTargetInfluences&&l.push(p.name?p.name:p.uuid)}):l.push(o);let c;switch(El[s.path]){case El.weights:c=Yd;break;case El.rotation:c=Jd;break;case El.translation:case El.scale:c=Xd;break;default:r.itemSize===1?c=Yd:c=Xd;break}const d=i.interpolation!==void 0?RZ[i.interpolation]:Tp,h=this._getArrayFromAccessor(r);for(let p=0,A=l.length;p<A;p++){const y=new c(l[p]+"."+El[s.path],t.array,h,d);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(y),a.push(y)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const r=ww(t.constructor),i=new Float32Array(t.length);for(let s=0,a=t.length;s<a;s++)i[s]=t[s]*r;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(r){const i=this instanceof Jd?TZ:cP;return new i(this.times,this.values,this.getValueSize()/3,r)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function zZ(n,e,t){const r=e.attributes,i=new ys;if(r.POSITION!==void 0){const o=t.json.accessors[r.POSITION],l=o.min,c=o.max;if(l!==void 0&&c!==void 0){if(i.set(new ue(l[0],l[1],l[2]),new ue(c[0],c[1],c[2])),o.normalized){const d=ww(Ld[o.componentType]);i.min.multiplyScalar(d),i.max.multiplyScalar(d)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const s=e.targets;if(s!==void 0){const o=new ue,l=new ue;for(let c=0,d=s.length;c<d;c++){const h=s[c];if(h.POSITION!==void 0){const p=t.json.accessors[h.POSITION],A=p.min,y=p.max;if(A!==void 0&&y!==void 0){if(l.setX(Math.max(Math.abs(A[0]),Math.abs(y[0]))),l.setY(Math.max(Math.abs(A[1]),Math.abs(y[1]))),l.setZ(Math.max(Math.abs(A[2]),Math.abs(y[2]))),p.normalized){const m=ww(Ld[p.componentType]);l.multiplyScalar(m)}o.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(o)}n.boundingBox=i;const a=new Ua;i.getCenter(a.center),a.radius=i.min.distanceTo(i.max)/2,n.boundingSphere=a}function oB(n,e,t){const r=e.attributes,i=[];function s(a,o){return t.getDependency("accessor",a).then(function(l){n.setAttribute(o,l)})}for(const a in r){const o=bw[a]||a.toLowerCase();o in n.attributes||i.push(s(r[a],o))}if(e.indices!==void 0&&!n.index){const a=t.getDependency("accessor",e.indices).then(function(o){n.setIndex(o)});i.push(a)}return pn.workingColorSpace!==ii&&"COLOR_0"in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${pn.workingColorSpace}" not supported.`),ba(n,e),zZ(n,e,t),Promise.all(i).then(function(){return e.targets!==void 0?kZ(n,e.targets,t):n})}async function lB(n,e){const i=(await new sZ().loadAsync(n)).scene;return i.traverse(s=>{s.visible=!1}),e.add(i),i}function cB(n,e){e.remove(n),n.traverse(t=>{const r=t;r.geometry?.dispose(),Array.isArray(r.material)?r.material.forEach(i=>i.dispose()):r.material?.dispose()})}class uB{constructor(e){this.onPointer=s=>{s.type==="pointerdown"?(this.start(s.clientX,s.clientY),this.mouseDown=!0):s.type==="pointermove"&&this.mouseDown?this.move(s.clientX,s.clientY):s.type==="pointerup"&&this.end()},this.scene=e.scene,this.renderer=e.renderer,this.camera=e.camera,this.container=e.container,this.controls=e.controls,this.draggableBodyIds=e.draggableBodyIds??null,this.mousePos=new Dt,this.raycaster=new X9,this.raycaster.params.Line.threshold=.1,this.grabDistance=0,this.active=!1,this.mouseDown=!1,this.physicsObject=null,this.localHit=new ue,this.worldHit=new ue,this.currentWorld=new ue,this.offset=new ue,this.arrow=new cs;const t=new Ah(.008,.008,1),r=new qd({color:16737095,transparent:!0,opacity:.5,metalness:0,roughness:.2});this.arrowShaft=new Kn(t,r),this.arrowShaft.position.y=.5;const i=new EC(.03,.1);this.arrowHead=new Kn(i,r),this.arrowHead.position.y=1,this.arrow.add(this.arrowShaft),this.arrow.add(this.arrowHead),this.arrow.visible=!1,this.scene.add(this.arrow),this.container.addEventListener("pointerdown",this.onPointer,!0),document.addEventListener("pointermove",this.onPointer,!0),document.addEventListener("pointerup",this.onPointer,!0)}updateRaycaster(e,t){const r=this.renderer.domElement.getBoundingClientRect();this.mousePos.x=(e-r.left)/r.width*2-1,this.mousePos.y=-((t-r.top)/r.height)*2+1,this.raycaster.setFromCamera(this.mousePos,this.camera)}start(e,t){this.physicsObject=null,this.updateRaycaster(e,t);const r=this.raycaster.intersectObjects(this.scene.children,!0);for(const i of r){const s=i.object;if(!this.shouldIgnoreForDrag(s)&&this.isDraggableObject(s)){this.physicsObject=s,this.grabDistance=i.distance;const a=this.raycaster.ray.origin.clone().addScaledVector(this.raycaster.ray.direction,this.grabDistance);this.localHit.copy(s.worldToLocal(a.clone())),this.worldHit.copy(a),this.currentWorld.copy(a),this.offset.set(0,0,0),this.arrow.position.copy(a),this.arrow.visible=!1,this.active=!0,this.controls.enabled=!1;break}}}setDraggableBodyIds(e){this.draggableBodyIds=e}isDraggableObject(e){if(!("bodyID"in e)||typeof e.bodyID!="number")return!1;const t=e.bodyID;return!(t<=0||this.draggableBodyIds&&!this.draggableBodyIds.has(t))}shouldIgnoreForDrag(e){let t=e;for(;t;){if(t.userData?.ignoreDragForce===!0)return!0;t=t.parent}return!1}move(e,t){this.active&&this.updateRaycaster(e,t)}update(){if(!this.physicsObject||!this.active)return;this.raycaster.setFromCamera(this.mousePos,this.camera),this.currentWorld.copy(this.raycaster.ray.origin.clone().addScaledVector(this.raycaster.ray.direction,this.grabDistance)),this.worldHit.copy(this.localHit),this.physicsObject.localToWorld(this.worldHit),this.offset.copy(this.currentWorld).sub(this.worldHit),this.arrow.position.copy(this.worldHit);const e=this.offset.length();if(e>.001){this.arrow.visible=!0;const t=this.offset.clone().normalize();this.arrow.quaternion.setFromUnitVectors(new ue(0,1,0),t);const r=.1,i=Math.max(.01,e-r);this.arrowShaft.scale.y=i,this.arrowShaft.position.y=i/2,this.arrowHead.position.y=i+r/2}else this.arrow.visible=!1}end(){this.physicsObject=null,this.active=!1,this.controls.enabled=!0,this.arrow.visible=!1,this.mouseDown=!1}dispose(){this.container.removeEventListener("pointerdown",this.onPointer,!0),document.removeEventListener("pointermove",this.onPointer,!0),document.removeEventListener("pointerup",this.onPointer,!0),this.arrow.parent&&this.scene.remove(this.arrow),this.arrowShaft.geometry.dispose(),this.arrowHead.geometry.dispose(),this.arrowShaft.material&&this.arrowShaft.material.dispose()}}const Ff={lookat:[0,0,0],distance:4,elevation:-30,azimuth:45,fovy:45};function UZ(n,e,t,r){const i=t*Math.PI/180,s=r*Math.PI/180,a=n[0]+e*Math.cos(i)*Math.cos(s),o=n[1]+e*Math.cos(i)*Math.sin(s),l=n[2]-e*Math.sin(i);return zl([a,o,l])}function OZ(n,e,t,r,i){const s={trackBodyId:null,prevBodyPos:null};t.enabled=!0;const a=n?.lookat??Ff.lookat,o=n?.distance??Ff.distance,l=n?.elevation??Ff.elevation,c=n?.azimuth??Ff.azimuth;if(e.fov=n?.fovy??Ff.fovy,e.updateProjectionMatrix(),e.position.copy(UZ(a,o,l,c)),t.target.copy(zl(a)),t.update(),!n)return s;const d=n.originType??"AUTO";if(d==="ASSET_BODY"&&n.bodyName&&r){const h=n.bodyName,p=n.entityName,A=p?`${p}/${h}`:null;for(let y=0;y<r.nbody;y++){const m=r.body(y).name;if(m===h||m===A||m.endsWith(`/${h}`)){s.trackBodyId=y;break}}s.trackBodyId===null&&console.warn(`[Camera] bodyName: body "${n.bodyName}" not found.`)}else(d==="AUTO"||d==="ASSET_ROOT")&&r&&r.nbody>1&&(s.trackBodyId=1);if(s.trackBodyId!==null&&i){const h=zl(i.xpos.slice(s.trackBodyId*3,s.trackBodyId*3+3));e.position.add(h),t.target.add(h),s.prevBodyPos=h,t.update()}return s}function $Z(n,e,t,r){if(r.trackBodyId!==null){const i=r.trackBodyId,s=zl(n.xpos.slice(i*3,i*3+3));if(r.prevBodyPos!==null){const a=s.clone().sub(r.prevBodyPos);e.position.add(a),t.target.add(a)}r.prevBodyPos=s}}const Rl=class Rl{constructor(e){this.MAX_CACHE_SIZE=5,this.mujoco=e,this.cache=new Map,this.metrics={totalScenes:0,totalMemoryBytes:0,oldestAccessTime:Date.now(),newestAccessTime:Date.now(),cacheHits:0,cacheMisses:0,evictions:0}}static getInstance(e){return Rl.instance||(Rl.instance=new Rl(e),console.log("[SceneCache] Created new cache manager singleton")),Rl.instance}static resetInstance(){Rl.instance=null}normalizeScenePath(e){return e?DC(e):""}has(e){const t=this.normalizeScenePath(e);return this.cache.has(t)}get(e){const t=this.normalizeScenePath(e),r=this.cache.get(t);return r?(r.lastAccessed=Date.now(),this.metrics.cacheHits++,this.updateMetricsTimestamps(),r):(this.metrics.cacheMisses++,null)}async set(e,t){const r=this.normalizeScenePath(e);!this.cache.has(r)&&this.cache.size>=this.MAX_CACHE_SIZE&&await this.maybeEvict(),t.scenePath=r,t.lastAccessed=Date.now(),this.cache.set(r,t),this.updateMetrics()}async evict(e){const t=this.normalizeScenePath(e),r=this.cache.get(t);r&&(await this.disposeSceneResources(r),this.cache.delete(t),this.metrics.evictions++,this.updateMetrics())}async clear(){const e=Array.from(this.cache.keys());for(const t of e)await this.evict(t)}getMetrics(){return{...this.metrics}}async prepareForNewScene(){this.cache.size>=this.MAX_CACHE_SIZE&&await this.maybeEvict()}findLRUScene(){let e=null,t=1/0;for(const[r,i]of this.cache.entries())i.lastAccessed<t&&(t=i.lastAccessed,e=r);return e}async maybeEvict(){const e=this.findLRUScene();e&&(console.log(`[SceneCache] Evicting LRU scene: ${e}`),await this.evict(e))}async disposeSceneResources(e){const t=performance.now();if(e.skybox&&e.skybox.dispose(),e.mujocoRoot&&this.disposeThreeJSObject(e.mujocoRoot),e.mjData)try{e.mjData.delete()}catch(s){console.warn("[SceneCache] Failed to delete mjData:",s)}if(e.mjModel)try{e.mjModel.delete()}catch(s){console.warn("[SceneCache] Failed to delete mjModel:",s)}for(const s of e.fsFiles)try{const a=`/working/${s}`;this.mujoco.FS.analyzePath(a,!1).exists&&this.mujoco.FS.unlink(a)}catch{}mJ(e.scenePath);const r=performance.now()-t,i=(e.estimatedMemoryBytes/1048576).toFixed(1);console.log(`[SceneCache] Evicted: ${e.scenePath} (${i} MB) in ${r.toFixed(0)}ms`)}disposeThreeJSObject(e){e.traverse(t=>{"geometry"in t&&t.geometry&&t.geometry.dispose(),"material"in t&&t.material&&(Array.isArray(t.material)?t.material.forEach(r=>this.disposeMaterial(r)):this.disposeMaterial(t.material))}),e.parent&&e.parent.remove(e)}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),t.envMap&&t.envMap.dispose(),t.alphaMap&&t.alphaMap.dispose(),t.lightMap&&t.lightMap.dispose(),t.displacementMap&&t.displacementMap.dispose(),t.bumpMap&&t.bumpMap.dispose(),e.dispose()}updateMetrics(){this.metrics.totalScenes=this.cache.size,this.metrics.totalMemoryBytes=0;for(const e of this.cache.values())this.metrics.totalMemoryBytes+=e.estimatedMemoryBytes;this.updateMetricsTimestamps()}updateMetricsTimestamps(){let e=Date.now(),t=0;for(const r of this.cache.values())r.lastAccessed<e&&(e=r.lastAccessed),r.lastAccessed>t&&(t=r.lastAccessed);this.metrics.oldestAccessTime=e,this.metrics.newestAccessTime=t}};Rl.instance=null;let Ew=Rl;class GZ{constructor(){this.fsWriteLog=[],this.isTracking=!1}startTracking(e){if(this.isTracking){console.warn("[ResourceTracker] Already tracking FS writes");return}this.fsWriteLog=[],this.isTracking=!0,this.originalWriteFile=e.FS.writeFile;const t=this.fsWriteLog,r=this.originalWriteFile;e.FS.writeFile=function(i,s,a){if(i.startsWith("/working/")){const o=i.replace(/^\/working\//,"");t.includes(o)||t.push(o)}if(r)return r.call(e.FS,i,s,a)}}stopTracking(e){return this.isTracking?(this.originalWriteFile&&(e.FS.writeFile=this.originalWriteFile,this.originalWriteFile=void 0),this.isTracking=!1,[...this.fsWriteLog]):[]}estimateSceneMemory(e){let t=0;t+=this.estimateMuJoCoMemory(e.mjModel),t+=this.estimateMjDataMemory(e.mjData);const r=new Set,i=new Set,s=new Set;for(const a of Object.values(e.meshes))r.has(a)||(t+=this.estimateGeometryMemory(a),r.add(a));return e.mujocoRoot.traverse(a=>{if("geometry"in a&&a.geometry){const o=a.geometry;r.has(o)||(t+=this.estimateGeometryMemory(o),r.add(o))}if("material"in a&&a.material){const o=Array.isArray(a.material)?a.material:[a.material];for(const l of o)i.has(l)||(t+=1024,i.add(l),this.collectMaterialTextures(l).forEach(c=>{s.has(c)||(t+=this.estimateTextureMemory(c),s.add(c))}))}}),t}collectMaterialTextures(e){const t=[],r=e;return r.map&&t.push(r.map),r.aoMap&&t.push(r.aoMap),r.emissiveMap&&t.push(r.emissiveMap),r.metalnessMap&&t.push(r.metalnessMap),r.normalMap&&t.push(r.normalMap),r.roughnessMap&&t.push(r.roughnessMap),r.envMap&&t.push(r.envMap),r.alphaMap&&t.push(r.alphaMap),r.lightMap&&t.push(r.lightMap),r.displacementMap&&t.push(r.displacementMap),r.bumpMap&&t.push(r.bumpMap),t}estimateMuJoCoMemory(e){let t=0;return e.nq&&(t+=e.nq*8),e.nv&&(t+=e.nv*8),e.nbody&&(t+=e.nbody*256),e.mesh_vert&&(t+=e.mesh_vert.length*4),e.mesh_normal&&(t+=e.mesh_normal.length*4),e.mesh_texcoord&&(t+=e.mesh_texcoord.length*4),e.mesh_face&&(t+=e.mesh_face.length*4),e.tex_data&&(t+=e.tex_data.length),t}estimateMjDataMemory(e){let t=0;return e.qpos&&(t+=e.qpos.length*8),e.qvel&&(t+=e.qvel.length*8),e.qacc&&(t+=e.qacc.length*8),e.qacc_warmstart&&(t+=e.qacc_warmstart.length*8),e.ctrl&&(t+=e.ctrl.length*8),e.qfrc_applied&&(t+=e.qfrc_applied.length*8),e.xfrc_applied&&(t+=e.xfrc_applied.length*8),e.xpos&&(t+=e.xpos.length*8),e.xquat&&(t+=e.xquat.length*8),e.xmat&&(t+=e.xmat.length*8),e.xipos&&(t+=e.xipos.length*8),e.ximat&&(t+=e.ximat.length*8),e.ncon&&(t+=e.ncon*256),e.efc_force&&(t+=e.efc_force.length*8),e.sensordata&&(t+=e.sensordata.length*8),t}estimateGeometryMemory(e){let t=0;const r=e.attributes;for(const i in r){const s=r[i];s&&"array"in s&&(t+=s.array.byteLength)}return e.index&&(t+=e.index.array.byteLength),t}estimateTextureMemory(e){if(!e.image)return 1024;if(e instanceof ph&&Array.isArray(e.image)&&e.image.length===6){let r=0;for(const i of e.image){const s=i;s&&typeof s=="object"&&"width"in s&&"height"in s&&(r+=s.width*s.height*4)}return r}const t=e.image;return t&&typeof t=="object"&&"width"in t&&"height"in t?t.width*t.height*4:1024}}class HZ{getStats(e,t){const r=this.getJSHeapStats(),i={jsHeapUsedMB:r.used,jsHeapTotalMB:r.total,jsHeapLimitMB:r.limit,cachedScenesCount:e.totalScenes,estimatedCacheMemoryMB:e.totalMemoryBytes/1048576,estimatedGPUMemoryMB:0,sceneBreakdown:[]};if(t)for(const[s,a]of t.entries())i.sceneBreakdown.push({scenePath:s,memoryMB:a.memoryBytes/1048576,lastAccessed:new Date(a.lastAccessed)});return i}logCacheOperation(e,t,r){const i="[SceneCache]";switch(e){case"load":{const s=r?.memoryMB?` (${r.memoryMB.toFixed(1)} MB)`:"",a=r?.totalScenes!==void 0&&r?.totalMemoryMB!==void 0?` - Cache: ${r.totalScenes}/5 scenes, ${r.totalMemoryMB.toFixed(1)} MB total`:"";console.log(`${i} Loaded: ${t}${s}${a}`);break}case"hit":{const s=r?.elapsedMs!==void 0?` (~${r.elapsedMs.toFixed(0)}ms)`:"";console.log(`${i} Cache HIT: ${t}${s}`);break}case"miss":{console.log(`${i} Cache MISS: ${t}`);break}case"evict":{const s=r?.memoryMB?` (${r.memoryMB.toFixed(1)} MB)`:"";console.log(`${i} Evicted LRU: ${t}${s}`);break}}}logStats(e){if(console.log("[SceneCache] Memory Statistics:"),console.log(` JS Heap: ${e.jsHeapUsedMB.toFixed(1)} MB / ${e.jsHeapTotalMB.toFixed(1)} MB (Limit: ${e.jsHeapLimitMB.toFixed(1)} MB)`),console.log(` Cached Scenes: ${e.cachedScenesCount}/5`),console.log(` Estimated Cache Memory: ${e.estimatedCacheMemoryMB.toFixed(1)} MB`),e.sceneBreakdown.length>0){console.log(" Scene Breakdown:");for(const t of e.sceneBreakdown)console.log(` - ${t.scenePath}: ${t.memoryMB.toFixed(1)} MB (accessed: ${t.lastAccessed.toLocaleTimeString()})`)}}getJSHeapStats(){const e=performance;return e.memory?{used:e.memory.usedJSHeapSize/1048576,total:e.memory.totalJSHeapSize/1048576,limit:e.memory.jsHeapSizeLimit/1048576}:{used:0,total:0,limit:0}}estimateGPUMemory(e){const t=e.info,r=t.memory.geometries,i=t.memory.textures;return r*1+i*2}}class Vn{constructor(e,t){this.runner=e,this.config=t}}const VZ={};function us(n){const e=n[0]??1,t=n[1]??0,r=n[2]??0,i=n[3]??0,s=Math.hypot(e,t,r,i);if(s<1e-9)return[1,0,0,0];const a=1/s;return[e*a,t*a,r*a,i*a]}function OC(n,e){const t=n[0]??1,r=n[1]??0,i=n[2]??0,s=n[3]??0,a=e[0]??1,o=e[1]??0,l=e[2]??0,c=e[3]??0;return[t*a-r*o-i*l-s*c,t*o+r*a+i*c-s*l,t*l-r*c+i*a+s*o,t*c+r*l-i*o+s*a]}function $C(n){const e=n[0]??1,t=n[1]??0,r=n[2]??0,i=n[3]??0,s=e*e+t*t+r*r+i*i;if(s<1e-9)return[1,0,0,0];const a=1/s;return[e*a,-t*a,-r*a,-i*a]}function jp(n,e){const t=n[0]??1,r=n[1]??0,i=n[2]??0,s=n[3]??0,a=e[0]??0,o=e[1]??0,l=e[2]??0,c=2*(i*l-s*o),d=2*(s*a-r*l),h=2*(r*o-i*a),p=i*h-s*d,A=s*c-r*h,y=r*d-i*c;return[a-t*c+p,o-t*d+A,l-t*h+y]}function GC(n){const[e,t,r,i]=us(n),s=t*t,a=r*r,o=i*i,l=t*r,c=t*i,d=r*i,h=e*t,p=e*r,A=e*i,y=1-2*(a+o),m=2*(l-A),x=2*(l+A),g=1-2*(s+o),_=2*(c-p),b=2*(d+h);return[y,m,x,g,_,b]}function K0(n,e,t){return e.map(r=>{const i=n+r;return i<0?0:i>=t?Math.max(0,t-1):i})}const jZ={};async function WZ(n){const e=new DecompressionStream("deflate-raw"),t=e.writable.getWriter(),r=e.readable.getReader();t.write(n),t.close();const i=[];let s=0;for(;;){const{done:l,value:c}=await r.read();if(l)break;i.push(c),s+=c.byteLength}const a=new Uint8Array(s);let o=0;for(const l of i)a.set(l,o),o+=l.byteLength;return a}function qZ(n){const e=[147,78,85,77,80,89];for(let w=0;w<e.length;w++)if(n[w]!==e[w])throw new Error("Invalid .npy magic number");const t=n[6];let r,i;t===1?(r=n[8]|n[9]<<8,i=10):(r=n[8]|n[9]<<8|n[10]<<16|n[11]<<24,i=12);const s=n.slice(i,i+r),a=new TextDecoder().decode(s),o=a.match(/'descr'\s*:\s*'([^']+)'/),l=a.match(/'shape'\s*:\s*\(([^)]*)\)/),c=a.match(/'fortran_order'\s*:\s*(True|False)/);if(!o||!l)throw new Error(`Cannot parse .npy header: ${a}`);const d=o[1];if(c?c[1]==="True":!1)throw new Error("Fortran-ordered arrays not supported");const A=l[1].split(",").map(w=>w.trim()).filter(w=>w.length>0).map(w=>parseInt(w,10)),y=i+r,m=n.slice(y),x=d[0],g=d.slice(1),_=x===">"||x==="="&&!YZ();let b;if(g==="f4")b=new Float32Array(m.buffer,m.byteOffset,m.byteLength/4),_&&(b=JZ(b));else if(g==="f8"){let w=new Float64Array(m.buffer,m.byteOffset,m.byteLength/8);_&&(w=XZ(w)),b=new Float32Array(w.length);for(let C=0;C<w.length;C++)b[C]=w[C]}else if(g==="i4"){let w=new Int32Array(m.buffer,m.byteOffset,m.byteLength/4);_&&(w=KZ(w)),b=new Float32Array(w.length);for(let C=0;C<w.length;C++)b[C]=w[C]}else{const w=d.match(/^S(\d+)$/);if(w){const C=parseInt(w[1],10),S=m.length/C,M=A.reduce((k,G)=>k*G,1);if(S!==M)throw new Error(`npz: byte-string array size mismatch (shape ${A} expects ${M} elements, got ${S})`);const T=new TextDecoder("utf-8"),R=[];for(let k=0;k<S;k++){const G=m.slice(k*C,(k+1)*C),P=G.indexOf(0);R.push(T.decode(P>=0?G.slice(0,P):G))}return{shape:A,data:new Float32Array(0),strings:R}}throw new Error(`Unsupported numpy dtype: ${d}`)}return{shape:A,data:b}}function YZ(){const n=new ArrayBuffer(2);return new DataView(n).setInt16(0,1,!0),new Int16Array(n)[0]===1}function JZ(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=e.getFloat32(r*4,!0);return t}function XZ(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=new Float64Array(n.length);for(let r=0;r<n.length;r++)t[r]=e.getFloat64(r*8,!0);return t}function KZ(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=new Int32Array(n.length);for(let r=0;r<n.length;r++)t[r]=e.getInt32(r*4,!0);return t}async function ZZ(n){const e=await fetch(n);if(!e.ok)throw new Error(`Failed to fetch NPZ: ${e.status} ${n}`);const t=await e.arrayBuffer(),r=new Uint8Array(t),i={};let s=0;for(;s+30<=r.length&&!(r[s]!==80||r[s+1]!==75||r[s+2]!==3||r[s+3]!==4);){const a=r[s+8]|r[s+9]<<8,o=(r[s+22]|r[s+23]<<8|r[s+24]<<16|r[s+25]<<24)>>>0;let l=(r[s+18]|r[s+19]<<8|r[s+20]<<16|r[s+21]<<24)>>>0;const c=r[s+26]|r[s+27]<<8,d=r[s+28]|r[s+29]<<8,h=r.slice(s+30,s+30+c);let p=new TextDecoder().decode(h);if(l===4294967295||o===4294967295){const x=s+30+c;let g=x;for(;g+4<=x+d;){const _=r[g]|r[g+1]<<8,b=r[g+2]|r[g+3]<<8;if(_===1){let w=g+4;if(o===4294967295&&w+8<=g+4+b&&(w+=8),l===4294967295&&w+8<=g+4+b){const C=(r[w]|r[w+1]<<8|r[w+2]<<16|r[w+3]<<24)>>>0;l=((r[w+4]|r[w+5]<<8|r[w+6]<<16|r[w+7]<<24)>>>0)*4294967296+C}break}g+=4+b}}const A=s+30+c+d,y=r.slice(A,A+l);if(s=A+l,p.endsWith("/"))continue;p.endsWith(".npy")&&(p=p.slice(0,-4));let m;if(a===0)m=y;else if(a===8)m=await WZ(y);else{console.warn(`[NPZ] Unsupported compression method ${a} for ${p}`);continue}try{i[p]=qZ(m)}catch(x){console.warn(`[NPZ] Failed to parse ${p}:`,x)}}return i}function Jv(n){const e=Math.hypot(n[0]??1,n[1]??0,n[2]??0,n[3]??0)||1;return new Float32Array([(n[0]??1)/e,(n[1]??0)/e,(n[2]??0)/e,(n[3]??0)/e])}function wd(n){const e=n.shape[0]??0,t=n.shape.length<=1?1:n.shape.slice(1).reduce((i,s)=>i*s,1),r=[];for(let i=0;i<e;i++){const s=new Float32Array(t),a=i*t;for(let o=0;o<t;o++)s[o]=n.data[a+o]??0;r.push(s)}return r}function uP(n,e){if(!Array.isArray(n)||n.length<2)return e;const t=Number(n[0]),r=Number(n[1]);return!Number.isFinite(t)||!Number.isFinite(r)?e:[t,r]}function dB(n){if(n===null||typeof n!="object"||Array.isArray(n))return{};const e={};for(const t of["x","y","z","roll","pitch","yaw"]){const r=uP(n[t],[0,0]);(r[0]!==0||r[1]!==0)&&(e[t]=r)}return e}function $i(n){return n?n[0]+Math.random()*(n[1]-n[0]):0}function eee(n,e){const t=n[0]??1,r=n[1]??0,i=n[2]??0,s=n[3]??0,a=e[0]??1,o=e[1]??0,l=e[2]??0,c=e[3]??0;return new Float32Array([t*a-r*o-i*l-s*c,t*o+r*a+i*c-s*l,t*l-r*c+i*a+s*o,t*c+r*l-i*o+s*a])}function tee(n,e,t){const r=Math.cos(n*.5),i=Math.sin(n*.5),s=Math.cos(e*.5),a=Math.sin(e*.5),o=Math.cos(t*.5),l=Math.sin(t*.5);return new Float32Array([r*s*o+i*a*l,i*s*o-r*a*l,r*a*o+i*s*l,r*s*l-i*a*o])}function hB(n){const e=n.clone();return"transparent"in e&&(e.transparent=!0),"opacity"in e&&(e.opacity=.5),"depthWrite"in e&&(e.depthWrite=!1),"color"in e&&e.color instanceof xt&&(e.color=new xt(.5,.7,.5)),e}function nee(n){let e=!1;return n.traverse(t=>{t instanceof Kn&&(e=!0)}),e}class xp{constructor(e,t,r){this.context=r,this.motions=Array.isArray(t.motions)?t.motions:[],this.loadedMotions=new Map,this.sampleHz=50,this.selectedMotionName=this.motions.find(i=>i.default)?.name??this.motions[0]?.name??null,this.selectedMotion=null,this.selectedAnchorBodyIndex=0,this.selectedRootBodyIndex=0,this.datasetQposAdr=[],this.frameAccumulator=0,this.justReset=!0,this.referenceVisible=!0,this.samplingMode=typeof t.sampling_mode=="string"?t.sampling_mode:"start",this.poseRange=dB(t.pose_range),this.velocityRange=dB(t.velocity_range),this.jointPositionRange=uP(t.joint_position_range,[0,0]),this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.nJoints=this.motions.find(i=>i.name===this.selectedMotionName)?.dataset_joint_names?.length??0,this.ghostBodies=new Map,this.ghostData=r.mjModel?new r.mujoco.MjData(r.mjModel):null,this.ghostRoot=this.createGhostRoot(),this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[]}getCommand(){if(!this.selectedMotion||this.refLen===0)return new Float32Array(this.nJoints*2);const e=this.refJointPos[this.refIdx]??new Float32Array(this.nJoints),t=this.selectedMotion.jointVel[this.refIdx]??new Float32Array(this.nJoints),r=new Float32Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}getUiConfig(){return null}async setSelectedMotion(e){const t=e??this.selectedMotionName;if(!t)return this.selectedMotionName=null,this.selectedMotion=null,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[],this.refLen=0,this.nJoints=0,this.updateGhostPose(),!1;const r=this.motions.find(s=>s.name===t);if(!r)return!1;const i=this.loadedMotions.get(t)??await this.loadMotion(r);return this.loadedMotions.set(t,i),this.selectedMotionName=t,this.selectedMotion=i,this.selectedAnchorBodyIndex=Math.max(0,i.body_names.indexOf(i.anchor_body_name)),this.selectedRootBodyIndex=0,this.datasetQposAdr=this.resolveQposAdr(i.dataset_joint_names??[]),this.refLen=i.frameCount,this.refJointPos=i.jointPos,this.refIdx=this.sampleInitialFrame(this.refLen),this.nJoints=i.jointPos[0]?.length??0,this.frameAccumulator=0,this.justReset=!0,this.updateReferenceState(),this.applyReferenceStateToSim(),this.updateGhostPose(),!0}setReferenceVisible(e){this.referenceVisible=e,this.ghostRoot&&(this.ghostRoot.visible=e&&this.selectedMotion!==null)}reset(){this.refIdx=this.sampleInitialFrame(this.refLen),this.frameAccumulator=0,this.justReset=!0,this.updateReferenceState(),this.applyReferenceStateToSim(),this.updateGhostPose()}update(e){if(!this.selectedMotion||this.refLen<=1)return;if(this.justReset){this.justReset=!1,this.updateGhostPose();return}const t=this.selectedMotion?.loop!==!1;this.frameAccumulator+=e*this.sampleHz;let r=!1;for(;this.frameAccumulator>=1;){if(this.refIdx+=1,this.refIdx>=this.refLen){if(!t){this.refIdx=this.refLen-1,this.frameAccumulator=0;break}this.refIdx=0,r=!0}this.frameAccumulator-=1}r&&this.context.requestReset?.(),this.updateGhostPose()}updateDebugVisuals(){this.ghostRoot&&(this.ghostRoot.visible=this.referenceVisible&&this.selectedMotion!==null)}dispose(){this.ghostRoot&&(this.ghostRoot.parent?.remove(this.ghostRoot),this.ghostRoot.traverse(e=>{if(e instanceof Kn)if(Array.isArray(e.material))for(const t of e.material)t.dispose?.();else e.material?.dispose?.()})),this.ghostData?.delete?.()}isReady(){return this.selectedMotion!==null&&this.refLen>0}getSelectedMotion(){return this.selectedMotion}getSelectedMotionName(){return this.selectedMotionName}getAnchorBodyName(){return this.selectedMotion?.anchor_body_name??this.motions.find(e=>e.name===this.selectedMotionName)?.anchor_body_name??null}getBodyNames(){return this.selectedMotion?.body_names??this.motions.find(e=>e.name===this.selectedMotionName)?.body_names??[]}getAnchorBodyIndex(){return this.selectedAnchorBodyIndex}getAnchorPos(e=this.refIdx){if(!this.selectedMotion)return null;const r=this.refBodyPosW[e];if(!r)return null;const i=this.selectedAnchorBodyIndex*3;return r.slice(i,i+3)}getAnchorQuat(e=this.refIdx){if(!this.selectedMotion)return null;const r=this.refBodyQuatW[e];if(!r)return null;const i=this.selectedAnchorBodyIndex*4;return Jv(r.slice(i,i+4))}getBodyPosW(e=this.refIdx){if(!this.selectedMotion)return null;const r=this.refBodyPosW[e];return r?r.slice():null}createGhostRoot(){const e=this.context.bodies??null,t=this.context.mjModel;if(!e||!t)return null;const r=new cs;r.name="Tracking Ghost",r.visible=!1;for(const[i,s]of Object.entries(e)){const a=Number(i);if(!this.isDynamicBody(a))continue;const o=s.clone(!0);o.traverse(l=>{l instanceof Kn&&(Array.isArray(l.material)?l.material=l.material.map(hB):l.material=hB(l.material),l.renderOrder=2)}),nee(o)&&(this.ghostBodies.set(a,o),r.add(o))}return(this.context.mujocoRoot??this.context.scene).add(r),r}isDynamicBody(e){const t=this.context.mjModel;if(!t||e<=0||e>=t.nbody)return!1;let r=e;for(;r>0;){if(t.body_jntnum[r]>0)return!0;r=t.body_parentid[r]}return!1}async loadMotion(e){this.sampleHz=e.fps;const t=await ZZ(e.path),r=["joint_pos","joint_vel","body_pos_w","body_quat_w","body_lin_vel_w","body_ang_vel_w"];for(const h of r)if(!t[h])throw new Error(`Motion asset is missing '${h}'`);const i=wd(t.joint_pos),s=wd(t.joint_vel),a=t.body_names?.strings??null,o=this.selectMotionBodyFrames(wd(t.body_pos_w),e.body_names,3,a),l=this.selectMotionBodyFrames(wd(t.body_quat_w),e.body_names,4,a),c=this.selectMotionBodyFrames(wd(t.body_lin_vel_w),e.body_names,3,a),d=this.selectMotionBodyFrames(wd(t.body_ang_vel_w),e.body_names,3,a);return{...e,jointPos:i,jointVel:s,bodyPosW:o,bodyQuatW:l,bodyLinVelW:c,bodyAngVelW:d,frameCount:i.length}}selectMotionBodyFrames(e,t,r,i=null){const s=this.context.mjModel,a=e[0];if(!s||!a||t.length===0)return e;const o=Math.floor(a.length/r);if(o===t.length)return e;let l;if(i!==null)l=t.map(c=>i.indexOf(c));else{const c=this.findBodyIdByName(t[0]);l=t.map(h=>this.findBodyIdByName(h)).map(h=>h-c)}return l.some(c=>c<0||c>=o)?(console.warn("[TrackingCommand] Could not map all motion body names to source body indices; using raw body frames."),e):e.map(c=>{const d=new Float32Array(t.length*r);for(let h=0;h<l.length;h++){const p=l[h]*r,A=h*r;for(let y=0;y<r;y++)d[A+y]=c[p+y]??0}return d})}updateReferenceState(){const e=this.selectedMotion;if(!e||e.frameCount===0){this.refRootPos=[],this.refRootQuat=[],this.refBodyPosW=[],this.refBodyQuatW=[],this.refBodyLinVelW=[],this.refBodyAngVelW=[];return}this.refBodyPosW=e.bodyPosW.map(t=>t.slice()),this.refBodyQuatW=e.bodyQuatW.map(t=>t.slice()),this.refBodyLinVelW=e.bodyLinVelW.map(t=>t.slice()),this.refBodyAngVelW=e.bodyAngVelW.map(t=>t.slice()),this.refRootPos=this.refBodyPosW.map(t=>t.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3)),this.refRootQuat=this.refBodyQuatW.map(t=>Jv(t.slice(this.selectedRootBodyIndex*4,this.selectedRootBodyIndex*4+4)))}applyReferenceStateToSim(){const e=this.context.mjModel,t=this.context.mjData,r=this.selectedMotion;if(!e||!t||!r||this.refLen===0)return;const i=this.sampleRootPos(this.refIdx),s=this.sampleRootQuat(this.refIdx),a=this.findFreeJointIndex();if(i&&s&&a>=0){const c=e.jnt_qposadr[a],d=e.jnt_dofadr[a];t.qpos[c+0]=i[0]??0,t.qpos[c+1]=i[1]??0,t.qpos[c+2]=i[2]??0,t.qpos[c+3]=s[0]??1,t.qpos[c+4]=s[1]??0,t.qpos[c+5]=s[2]??0,t.qpos[c+6]=s[3]??0;const h=this.sampleRootVelocity(this.refIdx,this.refBodyLinVelW),p=this.sampleRootAngularVelocity(this.refIdx);h&&p&&(t.qvel[d+0]=h[0]??0,t.qvel[d+1]=h[1]??0,t.qvel[d+2]=h[2]??0,t.qvel[d+3]=p[0]??0,t.qvel[d+4]=p[1]??0,t.qvel[d+5]=p[2]??0)}const o=this.sampleJointPos(this.refIdx),l=r.jointVel[this.refIdx]??new Float32Array(0);for(let c=0;c<this.datasetQposAdr.length&&c<o.length;c++)t.qpos[this.datasetQposAdr[c]]=o[c]??0;for(let c=0;c<this.datasetQposAdr.length&&c<l.length;c++){const d=this.resolveQvelAdrForQposAdr(this.datasetQposAdr[c]);d>=0&&(t.qvel[d]=l[c]??0)}this.context.mujoco.mj_forward(e,t)}sampleRootPos(e){const t=this.refRootPos[e];if(!t)return null;const r=t.slice();return r[0]+=$i(this.poseRange.x),r[1]+=$i(this.poseRange.y),r[2]+=$i(this.poseRange.z),r}sampleRootQuat(e){const t=this.refRootQuat[e];if(!t)return null;const r=$i(this.poseRange.roll),i=$i(this.poseRange.pitch),s=$i(this.poseRange.yaw);return r===0&&i===0&&s===0?t:Jv(eee(tee(r,i,s),t))}sampleRootVelocity(e,t){const r=t[e]?.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3);return r?(r[0]+=$i(this.velocityRange.x),r[1]+=$i(this.velocityRange.y),r[2]+=$i(this.velocityRange.z),r):null}sampleRootAngularVelocity(e){const t=this.refBodyAngVelW[e]?.slice(this.selectedRootBodyIndex*3,this.selectedRootBodyIndex*3+3);return t?(t[0]+=$i(this.velocityRange.roll),t[1]+=$i(this.velocityRange.pitch),t[2]+=$i(this.velocityRange.yaw),t):null}sampleInitialFrame(e){return e<=1||this.samplingMode==="start"?0:this.samplingMode==="uniform"?Math.floor(Math.random()*e):0}sampleJointPos(e){const t=this.refJointPos[e]??new Float32Array(0);if(this.jointPositionRange[0]===0&&this.jointPositionRange[1]===0)return t;const r=t.slice();for(let i=0;i<r.length;i++)r[i]+=$i(this.jointPositionRange);return r}resolveQposAdr(e){const t=this.context.mjModel;if(!t||e.length===0)return[];const r=[];for(const i of e){let s=-1;for(let a=0;a<t.njnt;a++){const o=t.jnt(a).name;if(o===i||o.endsWith(`/${i}`)){s=t.jnt_qposadr[a];break}}s>=0&&r.push(s)}return r}resolveQvelAdrForQposAdr(e){const t=this.context.mjModel;if(!t)return-1;for(let r=0;r<t.njnt;r++)if(t.jnt_qposadr[r]===e)return t.jnt_dofadr[r];return-1}findBodyIdByName(e){const t=this.context.mjModel;if(!t)return-1;for(let r=0;r<t.nbody;r++){const i=t.body(r).name;if(i===e||i.endsWith(`/${e}`))return r}return-1}updateGhostPose(){if(!this.ghostRoot||!this.ghostData||!this.context.mjModel||!this.selectedMotion||!this.refLen){this.ghostRoot&&(this.ghostRoot.visible=!1);return}const e=this.ghostData.qpos;e.set(this.context.mjModel.qpos0);const t=this.refRootPos[this.refIdx],r=this.refRootQuat[this.refIdx],i=this.findFreeJointIndex();if(i>=0&&t&&r){const a=this.context.mjModel.jnt_qposadr[i];e[a+0]=t[0]??0,e[a+1]=t[1]??0,e[a+2]=t[2]??0,e[a+3]=r[0]??1,e[a+4]=r[1]??0,e[a+5]=r[2]??0,e[a+6]=r[3]??0}const s=this.refJointPos[this.refIdx]??new Float32Array(0);for(let a=0;a<this.datasetQposAdr.length&&a<s.length;a++)e[this.datasetQposAdr[a]]=s[a]??0;this.context.mujoco.mj_forward(this.context.mjModel,this.ghostData);for(const[a,o]of this.ghostBodies)Vc(this.ghostData.xpos,a,o.position),pp(this.ghostData.xquat,a,o.quaternion);this.ghostRoot.visible=this.referenceVisible}findFreeJointIndex(){const e=this.context.mjModel;if(!e)return-1;for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}}class ree{constructor(e,t){this.inputs=Array.isArray(t.ui?.inputs)?t.ui.inputs:[],this.values=new Map;for(const r of this.inputs)r.type==="slider"&&this.values.set(r.name,r.default)}getCommand(){const e=this.inputs.filter(r=>r.type==="slider"),t=new Float32Array(e.length);for(let r=0;r<e.length;r++)t[r]=this.values.get(e[r].name)??e[r].default??0;return t}getUiConfig(){return{inputs:this.inputs}}reset(){for(const e of this.inputs)e.type==="slider"&&this.values.set(e.name,e.default)}setValue(e,t){const r=this.inputs.find(s=>s.type==="slider"&&s.name===e);if(!r)return 0;const i=Math.max(r.min,Math.min(r.max,t));return this.values.set(r.name,i),i}}const iee={UiCommand:ree,TrackingCommand:xp};class see{constructor(){this.terms=new Map,this.commands=new Map,this.commandGroups=new Map,this.values=new Map,this.listeners=new Set,this.resetCallback=null,this.context=null,this.registerSystemReset()}initialize(e,t){this.clear(),this.context=t;const r={...iee,...jZ};for(const[i,s]of Object.entries(e)){const a=r[s.name];if(!a)throw new Error(`Unknown command term: ${s.name}`);const o=new a(i,s,t);this.terms.set(i,o),this.registerUi(i,o)}}update(e){for(const t of this.terms.values())t.update?.(e)}updateDebugVisuals(){for(const e of this.terms.values())e.updateDebugVisuals?.()}resetTerms(){for(const e of this.terms.values())e.reset?.();this.syncValuesFromTerms(),this.emit({type:"reset",commandId:"*"})}getCommandGroups(){return Array.from(this.commandGroups.keys()).filter(e=>e!=="_system")}getCommandsInGroup(e){return(this.commandGroups.get(e)??[]).map(r=>this.commands.get(r)).filter(Boolean)}getCommands(){return Array.from(this.commands.values()).filter(e=>e.groupName!=="_system")}getAllCommands(){return Array.from(this.commands.values())}getResetCommand(){return this.commands.get("_system:reset")}getCommandById(e){return this.commands.get(e)}getValue(e){return this.values.get(e)??0}getValues(){const e={};for(const[t,r]of this.values)e[t]=r;return e}getCommand(e){const t=this.terms.get(e);return t?t.getCommand():new Float32Array(0)}getTerm(e){return this.terms.get(e)}getContext(){return this.context}getVelocityCommand(){return this.terms.has("velocity")?this.getCommand("velocity"):this.terms.has("twist")?this.getCommand("twist"):new Float32Array([.5,0,0])}setValue(e,t){const r=this.commands.get(e);if(!r||r.config.type!=="slider")return;const i=this.terms.get(r.groupName),s=r.config.name,a=i?.setValue?i.setValue(s,t):void 0,o=typeof a=="number"?a:t;this.values.set(e,o),this.emit({type:"change",commandId:e,groupName:r.groupName,value:o})}triggerButton(e){const t=this.commands.get(e);!t||t.config.type!=="button"||(e==="_system:reset"&&this.resetCallback?this.resetCallback():this.terms.get(t.groupName)?.triggerButton?.(t.config.name),this.emit({type:"button",commandId:e,groupName:t.groupName}))}resetToDefaults(){this.resetTerms()}setResetCallback(e){this.resetCallback=e}addEventListener(e){this.listeners.add(e)}removeEventListener(e){this.listeners.delete(e)}clear(){for(const e of this.terms.values())e.dispose?.();this.terms.clear(),this.commands.clear(),this.commandGroups.clear(),this.values.clear(),this.context=null,this.registerSystemReset(),this.emit({type:"clear",commandId:""})}hasCommands(){return this.commands.size>1}dispose(){for(const e of this.terms.values())e.dispose?.();this.terms.clear(),this.commands.clear(),this.commandGroups.clear(),this.values.clear(),this.listeners.clear(),this.resetCallback=null,this.context=null}registerSystemReset(){this.commands.set("_system:reset",{id:"_system:reset",groupName:"_system",config:{type:"button",name:"reset",label:"Reset Simulation"}}),this.commandGroups.set("_system",["_system:reset"])}registerUi(e,t){const r=t.getUiConfig?.(),i=Array.isArray(r?.inputs)?r.inputs:[];if(i.length!==0){this.commandGroups.set(e,[]);for(const s of i){const a=`${e}:${s.name}`;if(this.commands.set(a,{id:a,groupName:e,config:s}),this.commandGroups.get(e).push(a),s.type==="slider"){const o=t.getCommand(),l=i.filter(c=>c.type==="slider").findIndex(c=>c.name===s.name);this.values.set(a,o[l]??s.default)}}this.emit({type:"group_registered",commandId:e,groupName:e})}}syncValuesFromTerms(){for(const[e,t]of this.commands){if(t.config.type!=="slider")continue;const r=this.terms.get(t.groupName);if(!r)continue;const a=(r.getUiConfig?.()?.inputs??[]).filter(o=>o.type==="slider").findIndex(o=>o.name===t.config.name);if(a>=0){const o=r.getCommand();this.values.set(e,o[a]??this.values.get(e)??0)}}}emit(e){for(const t of this.listeners)try{t(e)}catch(r){console.warn("[CommandManager] Listener error:",r)}}}let Xv=null;function tr(){return Xv||(Xv=new see),Xv}function HC(n,e,t=1){if(typeof n=="number"){const r=new Float32Array(e);return r.fill(n),r}if(Array.isArray(n)){const r=new Float32Array(e);for(let i=0;i<e;i++){const s=n[i];r[i]=typeof s=="number"?s:t}return r}return null}class aee extends Vn{constructor(e,t){super(e,t),this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(3)),this.scale=HC(t.scale,3,1)}get size(){return 3*this.historySteps}reset(){const e=this.computeCurrent();for(const t of this.history)t.set(e)}update(){for(let e=this.history.length-1;e>0;e--)this.history[e].set(this.history[e-1]);this.history[0].set(this.computeCurrent())}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(){const t=tr().getVelocityCommand(),r=new Float32Array(t);if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}}class oee extends Vn{constructor(e,t){super(e,t),this.scale=HC(t.scale,3,1)}get size(){return 16}compute(){const e=new Float32Array(16),r=tr().getVelocityCommand();if(this.scale)for(let i=0;i<3;i++)r[i]*=this.scale[i]??1;return e[0]=r[0],e[1]=r[1],e[2]=r[2],e}}class fB extends Vn{constructor(e,t){super(e,t),this.commandName=t.command_name??"velocity",this.historySteps=Math.max(1,Math.floor(t.history_steps??1));const i=tr().getCommand(this.commandName);this.commandSize=i.length||3,this.history=Array.from({length:this.historySteps},()=>new Float32Array(this.commandSize)),this.scale=HC(t.scale,this.commandSize,1)}get size(){return this.commandSize*this.historySteps}reset(){const e=this.computeCurrent();for(const t of this.history)t.set(e)}update(){for(let e=this.history.length-1;e>0;e--)this.history[e].set(this.history[e-1]);this.history[0].set(this.computeCurrent())}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(){const t=tr().getCommand(this.commandName),r=new Float32Array(this.commandSize);for(let i=0;i<this.commandSize&&i<t.length;i++)r[i]=t[i];if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}}function ia(n){const e=tr().getTerm("motion");return e instanceof xp?e:null}function Kd(n,e){if(!n)return-1;for(let t=0;t<n.nbody;t++){const r=n.body(t).name;if(r===e||r.endsWith(`/${e}`))return t}return-1}function xh(n,e,t=1){if(typeof n=="number"){const r=new Float32Array(e);return r.fill(n),r}if(Array.isArray(n)){const r=new Float32Array(e);for(let i=0;i<e;i++){const s=n[i];r[i]=typeof s=="number"?s:t}return r}return null}function pB(n,e,t=0){if(!Array.isArray(n))return null;const r=new Float32Array(e);for(let i=0;i<e;i++)r[i]=typeof n[i]=="number"?n[i]:t;return r}class lee extends Vn{get size(){return 1}compute(){return new Float32Array([0])}}class cee extends Vn{get size(){return 3}compute(e){const t=e.rootAngVel??new Float32Array(3);return new Float32Array(t)}}class dP extends Vn{constructor(e,t){super(e,t);const r=Array.isArray(t.gravity)?t.gravity:[0,0,-1];this.gravity=new ue(r[0]??0,r[1]??0,r[2]??-1),this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(3))}get size(){return 3*this.historySteps}reset(e){const t=this.computeCurrent(e);for(const r of this.history)r.set(t)}update(e){for(let t=this.history.length-1;t>0;t--)this.history[t].set(this.history[t-1]);this.history[0].set(this.computeCurrent(e))}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(e){const t=e?.rootQuat??new Float32Array([1,0,0,0]),r=new Cn(t[1],t[2],t[3],t[0]),i=this.gravity.clone().applyQuaternion(r.clone().invert());return new Float32Array([i.x,i.y,i.z])}}class hP extends Vn{constructor(e,t){super(e,t);let r;if(Array.isArray(t.pos_steps))r=t.pos_steps.map(s=>Math.max(0,Math.floor(s)));else if(typeof t.history_steps=="number"){const s=Math.max(1,Math.floor(t.history_steps));r=Array.from({length:s},(a,o)=>o)}else r=[0,1,2,3,4,8];this.posSteps=r;const i=this.getJointNames(t);this.qposAdr=i?this.resolveQposAdr(i):null,this.numJoints=i?.length??(typeof t.num_joints=="number"?Math.max(1,Math.floor(t.num_joints)):e.getNumActions()),this.maxStep=Math.max(...this.posSteps),this.history=Array.from({length:this.maxStep+1},()=>new Float32Array(this.numJoints)),this.subtractDefault=!!t.subtract_default,this.biased=!!t.biased,this.defaultJointPos=this.normalizeDefaultJointPos(t.default_joint_pos),this.encoderBias=this.normalizeEncoderBias(t.encoder_bias),this.scale=this.normalizeScale(t.scale)}get size(){return this.posSteps.length*this.numJoints}reset(e){this.history[0].set(this.computeCurrent(e));for(let t=1;t<this.history.length;t++)this.history[t].set(this.history[0])}update(e){for(let t=this.history.length-1;t>0;t--)this.history[t].set(this.history[t-1]);this.history[0].set(this.computeCurrent(e))}compute(){const e=new Float32Array(this.posSteps.length*this.numJoints);let t=0;for(const r of this.posSteps){const i=Math.min(r,this.history.length-1),s=this.history[i];for(let a=0;a<this.numJoints;a++){let o=s[a];this.subtractDefault&&this.defaultJointPos.length>a&&(o-=this.defaultJointPos[a]),this.scale&&this.scale.length>a&&(o*=this.scale[a]),e[t+a]=o}t+=this.numJoints}return e}computeCurrent(e){if(this.qposAdr!==null){const i=this.runner.getContext()?.mjData?.qpos,s=new Float32Array(this.numJoints);for(let a=0;a<this.numJoints;a++){const o=this.qposAdr[a];s[a]=i!==void 0?i[o]:0,this.biased&&this.encoderBias.length>a&&(s[a]+=this.encoderBias[a])}return s}const t=e?.jointPos??new Float32Array(this.numJoints);if(!this.biased)return t;const r=new Float32Array(this.numJoints);for(let i=0;i<this.numJoints;i++)r[i]=(t[i]??0)+(this.encoderBias[i]??0);return r}getJointNames(e){if(!Array.isArray(e.joint_names))return null;const t=e.joint_names.filter(r=>typeof r=="string");return t.length>0?t:null}normalizeDefaultJointPos(e){const t=pB(e,this.numJoints,0);if(t)return t;const r=this.runner.getDefaultJointPos(),i=new Float32Array(this.numJoints);for(let s=0;s<this.numJoints;s++)i[s]=r[s]??0;return i}normalizeEncoderBias(e){const t=pB(e,this.numJoints,0);if(t)return t;const r=this.runner.getEncoderBias(),i=new Float32Array(this.numJoints);for(let s=0;s<this.numJoints;s++)i[s]=r[s]??0;return i}resolveQposAdr(e){const t=this.runner.getContext()?.mjModel??null;if(t===null)return Array.from({length:e.length},()=>0);const r=this.getModelJointNames(t);return e.map(i=>{const s=r.indexOf(i);if(s<0)throw new Error(`JointPos: joint "${i}" not found in model`);return t.jnt_qposadr[s]})}getModelJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;i.push(r.decode(t.subarray(a,o)))}return i}normalizeScale(e){if(typeof e=="number"){const t=new Float32Array(this.numJoints);return t.fill(e),t}if(Array.isArray(e)){const t=new Float32Array(this.numJoints);for(let r=0;r<this.numJoints;r++){const i=e[r];t[r]=typeof i=="number"?i:1}return t}return null}}class uee extends Vn{constructor(e,t){super(e,t),this.futureSteps=Array.isArray(t.future_steps)?t.future_steps.map(i=>Math.max(0,Math.floor(i))):[0,2,4,8,16];const r=this.futureSteps.length;this.outputLength=(r-1)*3+r*6}get size(){return this.outputLength}compute(e){const t=ia(this.runner);if(!t||!t.isReady())return new Float32Array(this.outputLength);const r=t.refIdx,i=t.refLen,s=K0(r,this.futureSteps,i),a=t.refRootPos[s[0]],o=us(t.refRootQuat[s[0]]),l=[];for(let p=1;p<s.length;p++){const A=t.refRootPos[s[p]],y=[A[0]-a[0],A[1]-a[1],A[2]-a[2]],m=jp(o,y);l.push(m[0],m[1],m[2])}const c=us(e.rootQuat??[1,0,0,0]),d=$C(c),h=[];for(let p=0;p<s.length;p++){const A=us(t.refRootQuat[s[p]]),y=OC(d,A),m=GC(y);h.push(m[0],m[1],m[2],m[3],m[4],m[5])}return Float32Array.from([...l,...h])}}class dee extends Vn{constructor(e,t){super(e,t),this.futureSteps=Array.isArray(t.future_steps)?t.future_steps.map(r=>Math.max(0,Math.floor(r))):[0,2,4,8,16]}get size(){return this.futureSteps.length}compute(){const e=ia(this.runner);if(!e||!e.isReady())return new Float32Array(this.size);const t=K0(e.refIdx,this.futureSteps,e.refLen),r=new Float32Array(t.length);for(let i=0;i<t.length;i++)r[i]=e.refRootPos[t[i]][2];return r}}class hee extends Vn{constructor(e,t){super(e,t),this.futureSteps=Array.isArray(t.future_steps)?t.future_steps.map(r=>Math.max(0,Math.floor(r))):[0,2,4,8,16]}get size(){const t=ia(this.runner)?.nJoints??0;return this.futureSteps.length*t}compute(){const e=ia(this.runner);if(!e||!e.isReady())return new Float32Array(this.size);const t=K0(e.refIdx,this.futureSteps,e.refLen),r=new Float32Array(t.length*e.nJoints);let i=0;for(const s of t)r.set(e.refJointPos[s],i),i+=e.nJoints;return r}}class fee extends Vn{constructor(e,t){super(e,t),this.futureSteps=Array.isArray(t.future_steps)?t.future_steps.map(r=>Math.max(0,Math.floor(r))):[0,2,4,8,16]}get size(){return this.futureSteps.length*3}compute(){const e=ia(this.runner);if(!e||!e.isReady())return new Float32Array(this.size);const t=K0(e.refIdx,this.futureSteps,e.refLen),r=new Float32Array(t.length*3),i=[0,0,-1];let s=0;for(const a of t){const o=us(e.refRootQuat[a]),l=jp(o,i);r[s++]=l[0],r[s++]=l[1],r[s++]=l[2]}return r}}class pee extends Vn{get size(){return 3}compute(e){const t=ia(this.runner),r=this.runner.getContext(),i=r?.mjModel??null,s=r?.mjData??null;if(!t||!t.isReady())return new Float32Array(3);const a=t.getAnchorPos(),o=t.getAnchorQuat(),l=t.getAnchorBodyName();if(!a||!o)return new Float32Array(3);if(!l||!i||!s)return new Float32Array(3);const c=Kd(i,l);if(c<0)return new Float32Array(3);const d=s.xpos.slice(c*3,c*3+3),h=us(s.xquat.slice(c*4,c*4+4)),p=[a[0]-d[0],a[1]-d[1],a[2]-d[2]],A=jp(h,p);return Float32Array.from(A)}}class Aee extends Vn{get size(){return 6}compute(e){const t=ia(this.runner),r=this.runner.getContext(),i=r?.mjModel??null,s=r?.mjData??null;if(!t||!t.isReady())return new Float32Array(6);const a=t.getAnchorQuat(),o=t.getAnchorBodyName();if(!a)return new Float32Array(6);if(!o||!i||!s)return new Float32Array(6);const l=Kd(i,o);if(l<0)return new Float32Array(6);const c=us(s.xquat.slice(l*4,l*4+4)),d=OC($C(c),us(a));return Float32Array.from(GC(d))}}class mee extends Vn{get size(){const e=ia(this.runner);return e?e.getBodyNames().length*3:0}compute(){const e=ia(this.runner),t=this.runner.getContext(),r=t?.mjModel??null,i=t?.mjData??null;if(!e||!e.isReady()||!r||!i)return new Float32Array(this.size);const s=e.getBodyNames(),a=e.getAnchorBodyName();if(!a)return new Float32Array(this.size);const o=Kd(r,a);if(o<0)return new Float32Array(this.size);const l=i.xpos.slice(o*3,o*3+3),c=us(i.xquat.slice(o*4,o*4+4)),d=new Float32Array(s.length*3);let h=0;for(const p of s){const A=Kd(r,p);if(A<0){h+=3;continue}const y=i.xpos.slice(A*3,A*3+3),m=[y[0]-l[0],y[1]-l[1],y[2]-l[2]],x=jp(c,m);d.set(x,h),h+=3}return d}}class gee extends Vn{get size(){const e=ia(this.runner);return e?e.getBodyNames().length*6:0}compute(){const e=ia(this.runner),t=this.runner.getContext(),r=t?.mjModel??null,i=t?.mjData??null;if(!e||!e.isReady()||!r||!i)return new Float32Array(this.size);const s=e.getBodyNames(),a=e.getAnchorBodyName();if(!a)return new Float32Array(this.size);const o=Kd(r,a);if(o<0)return new Float32Array(this.size);const l=us(i.xquat.slice(o*4,o*4+4)),c=$C(l),d=new Float32Array(s.length*6);let h=0;for(const p of s){const A=Kd(r,p);if(A<0){h+=6;continue}const y=us(i.xquat.slice(A*4,A*4+4)),m=OC(c,y);d.set(GC(m),h),h+=6}return d}}class fP extends Vn{constructor(e,t){super(e,t);const r=typeof t.history_steps=="number"?t.history_steps:4;this.steps=Math.max(1,Math.floor(r)),this.numActions=e.getNumActions(),this.actionBuffer=Array.from({length:this.steps},()=>new Float32Array(this.numActions)),this.transpose=!!t.transpose}get size(){return this.steps*this.numActions}reset(){for(const e of this.actionBuffer)e.fill(0)}update(){for(let t=this.actionBuffer.length-1;t>0;t--)this.actionBuffer[t].set(this.actionBuffer[t-1]);const e=this.runner.getLastActions();this.actionBuffer[0].set(e)}compute(){const e=new Float32Array(this.steps*this.numActions);if(this.transpose)for(let t=0;t<this.numActions;t++)for(let r=0;r<this.steps;r++)e[t*this.steps+r]=this.actionBuffer[r][t];else for(let t=0;t<this.steps;t++)for(let r=0;r<this.numActions;r++)e[t*this.numActions+r]=this.actionBuffer[t][r];return e}}class yee extends Vn{constructor(e,t){super(e,t),this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(3)),this.scale=xh(t.scale,3,1),this.worldFrame=t.world_frame??!0}get size(){return 3*this.historySteps}reset(e){const t=this.computeCurrent(e);for(const r of this.history)r.set(t)}update(e){for(let t=this.history.length-1;t>0;t--)this.history[t].set(this.history[t-1]);this.history[0].set(this.computeCurrent(e))}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(e){const t=e?.rootLinVel??new Float32Array(3);let r=new Float32Array(t);if(!this.worldFrame){const i=us(e?.rootQuat??[1,0,0,0]),s=jp(i,r);r=new Float32Array(s)}if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}}class xee extends Vn{constructor(e,t){super(e,t),this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(3)),this.scale=xh(t.scale,3,1)}get size(){return 3*this.historySteps}reset(e){const t=this.computeCurrent(e);for(const r of this.history)r.set(t)}update(e){for(let t=this.history.length-1;t>0;t--)this.history[t].set(this.history[t-1]);this.history[0].set(this.computeCurrent(e))}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(e){const t=e?.rootAngVel??new Float32Array(3),r=new Float32Array(t);if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}}class vee extends Vn{constructor(e,t){super(e,t);const r=Array.isArray(t.joint_names)?t.joint_names.filter(s=>typeof s=="string"):null,i=t.joint_name;if(r&&r.length>0)this.qvelAdr=null,this.qvelAdrList=this.resolveQvelAdrList(e.getContext()?.mjModel??null,r),this.numJoints=r.length;else if(i!==void 0){const s=e.getContext()?.mjModel??null;this.qvelAdr=s!==null?this.resolveQvelAdr(s,i):0,this.qvelAdrList=null,this.numJoints=1}else this.qvelAdr=null,this.qvelAdrList=null,this.numJoints=e.getNumActions();this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(this.numJoints)),this.scale=xh(t.scale,this.numJoints,1)}get size(){return this.numJoints*this.historySteps}reset(e){const t=this.computeCurrent(e);for(const r of this.history)r.set(t)}update(e){for(let t=this.history.length-1;t>0;t--)this.history[t].set(this.history[t-1]);this.history[0].set(this.computeCurrent(e))}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(e){if(this.qvelAdrList!==null){const i=this.runner.getContext()?.mjData?.qvel,s=new Float32Array(this.numJoints);for(let a=0;a<this.numJoints;a++)s[a]=i!==void 0?i[this.qvelAdrList[a]]:0;if(this.scale)for(let a=0;a<s.length;a++)s[a]*=this.scale[a]??1;return s}if(this.qvelAdr!==null){const i=this.runner.getContext()?.mjData?.qvel,s=i!==void 0?i[this.qvelAdr]:0,a=new Float32Array([s]);return this.scale&&(a[0]*=this.scale[0]??1),a}const t=e?.jointVel??new Float32Array(this.numJoints),r=new Float32Array(t);if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}resolveQvelAdr(e,t){const i=this.getModelJointNames(e).indexOf(t);if(i<0)throw new Error(`JointVelocities: joint "${t}" not found in model`);return e.jnt_dofadr[i]}resolveQvelAdrList(e,t){if(e===null)return Array.from({length:t.length},()=>0);const r=this.getModelJointNames(e);return t.map(i=>{const s=r.indexOf(i);if(s<0)throw new Error(`JointVelocities: joint "${i}" not found in model`);return e.jnt_dofadr[s]})}getModelJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;i.push(r.decode(t.subarray(a,o)))}return i}}class _ee extends Vn{constructor(e,t){super(e,t),this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(3)),this.scale=xh(t.scale,3,1)}get size(){return 3*this.historySteps}reset(){const e=this.computeCurrent();for(const t of this.history)t.set(e)}update(){for(let e=this.history.length-1;e>0;e--)this.history[e].set(this.history[e-1]);this.history[0].set(this.computeCurrent())}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(){const t=tr().getVelocityCommand(),r=new Float32Array(t);if(this.scale)for(let i=0;i<r.length;i++)r[i]*=this.scale[i]??1;return r}}class bee extends Vn{constructor(e,t){super(e,t),this.scale=xh(t.scale,3,1)}get size(){return 16}compute(){const e=new Float32Array(16),r=tr().getVelocityCommand(),i=new Float32Array(r);if(this.scale)for(let s=0;s<3;s++)i[s]*=this.scale[s]??1;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e}}class wee extends Vn{get size(){return 27}compute(){return new Float32Array(27)}}class Eee extends Vn{constructor(e,t){super(e,t);const r=e.getContext()?.mjModel??null;this.qposAdr=r!==null?this.resolveQposAdr(r):0}get size(){return 2}compute(){const e=this.runner.getContext()?.mjData?.qpos,t=e!==void 0?e[this.qposAdr]:0;return new Float32Array([Math.cos(t),Math.sin(t)])}resolveQposAdr(e){const t=this.config.joint_name;if(t!==void 0){const s=this.getJointNames(e).indexOf(t);if(s<0)throw new Error(`JointPosCosSin: joint "${t}" not found in model`);return e.jnt_qposadr[s]}const r=this.config.joint_index??0;return e.jnt_qposadr[r]}getJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;i.push(r.decode(t.subarray(a,o)))}return i}}class Cee extends Vn{constructor(e,t){super(e,t),this.sensorName=t.sensor_name??"";const r=e.getContext()?.mjModel??null,i=this.resolveSensor(r,this.sensorName);this.sensorAdr=i.adr,this.sensorDim=i.dim,this.historySteps=Math.max(1,Math.floor(t.history_steps??1)),this.history=Array.from({length:this.historySteps},()=>new Float32Array(this.sensorDim)),this.scale=xh(t.scale,this.sensorDim,1),this.clipRange=this.normalizeClipRange(t.clip)}get size(){return this.sensorDim*this.historySteps}reset(){const e=this.computeCurrent();for(const t of this.history)t.set(e)}update(){for(let e=this.history.length-1;e>0;e--)this.history[e].set(this.history[e-1]);this.history[0].set(this.computeCurrent())}compute(){if(this.historySteps===1)return new Float32Array(this.history[0]);const e=new Float32Array(this.size);let t=0;for(const r of this.history)e.set(r,t),t+=r.length;return e}computeCurrent(){const e=this.runner.getContext()?.mjData?.sensordata,t=new Float32Array(this.sensorDim);if(e===void 0)return t;for(let r=0;r<this.sensorDim;r++)t[r]=e[this.sensorAdr+r]??0;if(this.scale)for(let r=0;r<t.length;r++)t[r]*=this.scale[r]??1;if(this.clipRange){const[r,i]=this.clipRange;for(let s=0;s<t.length;s++)t[s]=Math.min(i,Math.max(r,t[s]))}return t}resolveSensor(e,t){if(e===null)return{adr:0,dim:1};const i=this.getModelSensorNames(e).indexOf(t);if(i<0)throw new Error(`BuiltinSensor: sensor "${t}" not found in model`);return{adr:e.sensor_adr[i],dim:e.sensor_dim[i]}}getModelSensorNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.nsensor;s++){let a=e.name_sensoradr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;i.push(r.decode(t.subarray(a,o)))}return i}normalizeClipRange(e){if(!Array.isArray(e)||e.length<2)return null;const t=typeof e[0]=="number"?e[0]:-1/0,r=typeof e[1]=="number"?e[1]:1/0;return[t,r]}}class Iee extends dP{}class See extends hP{}class Bee extends fP{}const Mee={...VZ,PrevActions:fP,PreviousActions:Bee,BootIndicator:lee,RootAngVelB:cee,ProjectedGravityB:dP,ProjectedGravity:Iee,JointPos:hP,JointPositions:See,TrackingCommandObsRaw:uee,TargetRootZObs:dee,TargetJointPosObs:hee,TargetProjectedGravityBObs:fee,MotionAnchorPosB:pee,MotionAnchorOriB:Aee,RobotBodyPosB:mee,RobotBodyOriB:gee,BaseLinearVelocity:yee,BaseAngularVelocity:xee,JointVelocities:vee,SimpleVelocityCommand:_ee,VelocityCommandWithOscillators:bee,VelocityCommandObservation:aee,VelocityCommandWithOscillatorsObservation:oee,GeneratedCommands:fB,GeneratedCommandsObservation:fB,ImpedanceCommand:wee,JointPosCosSin:Eee,BuiltinSensor:Cee};class Tee{constructor(e,t){this.terms=[];for(const[r,i]of Object.entries(e)){const s=t[i.name];if(!s){console.warn(`[TerminationManager] Unknown termination type: ${i.name}`);continue}const a={name:i.name,params:i.params,time_out:i.time_out};this.terms.push({name:r,term:new s(a),isTimeOut:i.time_out??!1})}}evaluate(e){let t=!1,r=!1;const i=[];for(const{name:s,term:a,isTimeOut:o}of this.terms)a.evaluate(e)&&(i.push(s),o?r=!0:t=!0);return{done:t||r,terminated:t,truncated:r,reasons:i}}reset(){for(const{term:e}of this.terms)e.reset?.()}get size(){return this.terms.length}}class VC{constructor(e){this.config=e}}const Ree={};class Dee extends VC{constructor(e){super(e),this.stepCount=0;const t=e.params??{};this.maxSteps=t.max_episode_length??1e3}evaluate(){return this.stepCount++,this.stepCount>=this.maxSteps}reset(){this.stepCount=0}}class kee extends VC{constructor(e){super(e);const t=e.params??{};this.limitAngle=t.limit_angle??1}evaluate(e){const t=e.rootQuat;if(!t||t.length<4)return!1;const r=t[1],i=t[2],s=1-2*(r*r+i*i),a=Math.acos(Math.max(-1,Math.min(1,s)));return Math.abs(a)>this.limitAngle}}class Nee extends VC{constructor(e){super(e);const t=e.params??{};this.minimumHeight=t.minimum_height??0}evaluate(e){const t=e.rootPos;return!t||t.length<3?!1:t[2]<this.minimumHeight}}const Qee={TimeOut:Dee,BadOrientation:kee,RootHeightBelowMinimum:Nee},Pee={...Qee,...Ree};var jC=Object.defineProperty,Lee=Object.getOwnPropertyDescriptor,Fee=Object.getOwnPropertyNames,zee=Object.prototype.hasOwnProperty,Uee=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),et=(n,e)=>()=>(n&&(e=n(n=0)),e),vh=(n,e)=>{for(var t in e)jC(n,t,{get:e[t],enumerable:!0})},Oee=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Fee(e))!zee.call(n,i)&&i!==t&&jC(n,i,{get:()=>e[i],enumerable:!(r=Lee(e,i))||r.enumerable});return n},Lp=n=>Oee(jC({},"__esModule",{value:!0}),n),zf,Cl,Bd,AB,pP,AP=et(()=>{zf=new Map,Cl=[],Bd=(n,e,t)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let r=zf.get(n);if(r===void 0)zf.set(n,{backend:e,priority:t});else{if(r.priority>t)return;if(r.priority===t&&r.backend!==e)throw new Error(`cannot register backend "${n}" using priority ${t}`)}if(t>=0){let i=Cl.indexOf(n);i!==-1&&Cl.splice(i,1);for(let s=0;s<Cl.length;s++)if(zf.get(Cl[s]).priority<=t){Cl.splice(s,0,n);return}Cl.push(n)}return}throw new TypeError("not a valid backend")},AB=async n=>{let e=zf.get(n);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let t=!!e.initPromise;try{return t||(e.initPromise=e.backend.init(n)),await e.initPromise,e.initialized=!0,e.backend}catch(r){return t||(e.error=`${r}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},pP=async n=>{let e=n.executionProviders||[],t=e.map(l=>typeof l=="string"?l:l.name),r=t.length===0?Cl:t,i,s=[],a=new Set;for(let l of r){let c=await AB(l);typeof c=="string"?s.push({name:l,err:c}):(i||(i=c),i===c&&a.add(l))}if(!i)throw new Error(`no available backend found. ERR: ${s.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of s)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let o=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[i,new Proxy(n,{get:(l,c)=>c==="executionProviders"?o:Reflect.get(l,c)})]}}),$ee=et(()=>{AP()}),mP,Gee=et(()=>{mP="1.24.3"}),Kv,Tr,gP=et(()=>{Gee(),Kv="warning",Tr={wasm:{},webgl:{},webgpu:{},versions:{common:mP},set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);Kv=n}},get logLevel(){return Kv}},Object.defineProperty(Tr,"logLevel",{enumerable:!0})}),Dn,Hee=et(()=>{gP(),Dn=Tr}),yP,xP,Vee=et(()=>{yP=(n,e)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=n.dims[3],t.height=n.dims[2];let r=t.getContext("2d");if(r!=null){let i,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(i=n.dims[2],s=n.dims[3]):(i=n.dims[3],s=n.dims[2]);let a=e?.format!==void 0?e.format:"RGB",o=e?.norm,l,c;o===void 0||o.mean===void 0?l=[255,255,255,255]:typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:(l=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(l[3]=o.mean[3])),o===void 0||o.bias===void 0?c=[0,0,0,0]:typeof o.bias=="number"?c=[o.bias,o.bias,o.bias,o.bias]:(c=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(c[3]=o.bias[3]));let d=s*i,h=0,p=d,A=d*2,y=-1;a==="RGBA"?(h=0,p=d,A=d*2,y=d*3):a==="RGB"?(h=0,p=d,A=d*2):a==="RBG"&&(h=0,A=d,p=d*2);for(let m=0;m<s;m++)for(let x=0;x<i;x++){let g=(n.data[h++]-c[0])*l[0],_=(n.data[p++]-c[1])*l[1],b=(n.data[A++]-c[2])*l[2],w=y===-1?255:(n.data[y++]-c[3])*l[3];r.fillStyle="rgba("+g+","+_+","+b+","+w+")",r.fillRect(x,m,1,1)}if("toDataURL"in t)return t.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},xP=(n,e)=>{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),r;if(t!=null){let i,s,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(i=n.dims[2],s=n.dims[1],a=n.dims[3]):(i=n.dims[3],s=n.dims[2],a=n.dims[1]);let o=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let h=s*i;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let p=4,A=0,y=1,m=2,x=3,g=0,_=h,b=h*2,w=-1;o==="RGBA"?(g=0,_=h,b=h*2,w=h*3):o==="RGB"?(g=0,_=h,b=h*2):o==="RBG"&&(g=0,b=h,_=h*2),r=t.createImageData(i,s);for(let C=0;C<s*i;A+=p,y+=p,m+=p,x+=p,C++)r.data[A]=(n.data[g++]-d[0])*c[0],r.data[y]=(n.data[_++]-d[1])*c[1],r.data[m]=(n.data[b++]-d[2])*c[2],r.data[x]=w===-1?255:(n.data[w++]-d[3])*c[3]}else throw new Error("Can not access image data");return r}}),Wm,vP,_P,bP,wP,EP,jee=et(()=>{WC(),Wm=(n,e)=>{if(n===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:r}=e,i=e.norm??{mean:255,bias:0},s,a;typeof i.mean=="number"?s=[i.mean,i.mean,i.mean,i.mean]:s=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?a=[i.bias,i.bias,i.bias,i.bias]:a=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let o=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=t*r,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),h=4,p=0,A=1,y=2,m=3,x=0,g=c,_=c*2,b=-1;o==="RGB"&&(h=3,p=0,A=1,y=2,m=-1),l==="RGBA"?b=c*3:l==="RBG"?(x=0,_=c,g=c*2):l==="BGR"&&(_=0,g=c,x=c*2);for(let w=0;w<c;w++,p+=h,y+=h,A+=h,m+=h)d[x++]=(n[p]+a[0])/s[0],d[g++]=(n[A]+a[1])/s[1],d[_++]=(n[y]+a[2])/s[2],b!==-1&&m!==-1&&(d[b++]=(n[m]+a[3])/s[3]);return l==="RGBA"?new Hi("float32",d,[1,4,t,r]):new Hi("float32",d,[1,3,t,r])},vP=async(n,e)=>{let t=typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement,r=typeof ImageData<"u"&&n instanceof ImageData,i=typeof ImageBitmap<"u"&&n instanceof ImageBitmap,s=typeof n=="string",a,o=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(t){let d=l();d.width=n.width,d.height=n.height;let h=c(d);if(h!=null){let p=n.height,A=n.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(p=e.resizedHeight,A=e.resizedWidth),e!==void 0){if(o=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=p,o.width=A}else o.tensorFormat="RGBA",o.height=p,o.width=A;h.drawImage(n,0,0),a=h.getImageData(0,0,A,p).data}else throw new Error("Can not access image data")}else if(r){let d,h;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(d=e.resizedHeight,h=e.resizedWidth):(d=n.height,h=n.width),e!==void 0&&(o=e),o.format="RGBA",o.height=d,o.width=h,e!==void 0){let p=l();p.width=h,p.height=d;let A=c(p);if(A!=null)A.putImageData(n,0,0),a=A.getImageData(0,0,h,d).data;else throw new Error("Can not access image data")}else a=n.data}else if(i){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=l();d.width=n.width,d.height=n.height;let h=c(d);if(h!=null){let p=n.height,A=n.width;return h.drawImage(n,0,0,A,p),a=h.getImageData(0,0,A,p).data,o.height=p,o.width=A,Wm(a,o)}else throw new Error("Can not access image data")}else{if(s)return new Promise((d,h)=>{let p=l(),A=c(p);if(!n||!A)return h();let y=new Image;y.crossOrigin="Anonymous",y.src=n,y.onload=()=>{p.width=y.width,p.height=y.height,A.drawImage(y,0,0,p.width,p.height);let m=A.getImageData(0,0,p.width,p.height);o.height=p.height,o.width=p.width,d(Wm(m.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Wm(a,o);throw new Error("Input data provided is not supported - aborted tensor creation")},_P=(n,e)=>{let{width:t,height:r,download:i,dispose:s}=e,a=[1,r,t,4];return new Hi({location:"texture",type:"float32",texture:n,dims:a,download:i,dispose:s})},bP=(n,e)=>{let{dataType:t,dims:r,download:i,dispose:s}=e;return new Hi({location:"gpu-buffer",type:t??"float32",gpuBuffer:n,dims:r,download:i,dispose:s})},wP=(n,e)=>{let{dataType:t,dims:r,download:i,dispose:s}=e;return new Hi({location:"ml-tensor",type:t??"float32",mlTensor:n,dims:r,download:i,dispose:s})},EP=(n,e,t)=>new Hi({location:"cpu-pinned",type:n,data:e,dims:t??[e.length]})}),kc,sp,Zv,CP,Wee=et(()=>{kc=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),sp=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Zv=!1,CP=()=>{if(!Zv){Zv=!0;let n=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,r=typeof t<"u"&&t.from;n&&(kc.set("int64",BigInt64Array),sp.set(BigInt64Array,"int64")),e&&(kc.set("uint64",BigUint64Array),sp.set(BigUint64Array,"uint64")),r?(kc.set("float16",t),sp.set(t,"float16")):kc.set("float16",Uint16Array)}}}),IP,SP,qee=et(()=>{WC(),IP=n=>{let e=1;for(let t=0;t<n.length;t++){let r=n[t];if(typeof r!="number"||!Number.isSafeInteger(r))throw new TypeError(`dims[${t}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${t}] must be a non-negative integer, got: ${r}`);e*=r}return e},SP=(n,e)=>{switch(n.location){case"cpu":return new Hi(n.type,n.data,e);case"cpu-pinned":return new Hi({location:"cpu-pinned",data:n.data,type:n.type,dims:e});case"texture":return new Hi({location:"texture",texture:n.texture,type:n.type,dims:e});case"gpu-buffer":return new Hi({location:"gpu-buffer",gpuBuffer:n.gpuBuffer,type:n.type,dims:e});case"ml-tensor":return new Hi({location:"ml-tensor",mlTensor:n.mlTensor,type:n.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${n.location} is not supported`)}}}),Hi,WC=et(()=>{Vee(),jee(),Wee(),qee(),Hi=class{constructor(n,e,t){CP();let r,i;if(typeof n=="object"&&"location"in n)switch(this.dataLocation=n.location,r=n.type,i=n.dims,n.location){case"cpu-pinned":{let a=kc.get(r);if(!a)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(n.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=n.data;break}case"texture":{if(r!=="float32")throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=n.texture,this.downloader=n.download,this.disposer=n.dispose;break}case"gpu-buffer":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=n.gpuBuffer,this.downloader=n.download,this.disposer=n.dispose;break}case"ml-tensor":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint64"&&r!=="int8"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=n.mlTensor,this.downloader=n.download,this.disposer=n.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof n=="string")if(r=n,o=t,n==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=kc.get(n);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${n}.`);if(Array.isArray(e)){if(n==="float16"&&l===Uint16Array||n==="uint4"||n==="int4")throw new TypeError(`Creating a ${n} tensor from number array is not supported. Please use ${l.name} as data.`);n==="uint64"||n==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(n==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(n==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${r} tensor's data must be type of ${l}`)}else if(o=e,Array.isArray(n)){if(n.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof n[0];if(l==="string")r="string",a=n;else if(l==="boolean")r="bool",a=Uint8Array.from(n);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(n instanceof Uint8ClampedArray)r="uint8",a=Uint8Array.from(n);else{let l=sp.get(n.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${n.constructor}.`);r=l,a=n}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");i=o,this.cpuData=a,this.dataLocation="cpu"}let s=IP(i);if(this.cpuData&&s!==this.cpuData.length&&!((r==="uint4"||r==="int4")&&Math.ceil(s/2)===this.cpuData.length))throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=s}static async fromImage(n,e){return vP(n,e)}static fromTexture(n,e){return _P(n,e)}static fromGpuBuffer(n,e){return bP(n,e)}static fromMLTensor(n,e){return wP(n,e)}static fromPinnedBuffer(n,e,t){return EP(n,e,t)}toDataURL(n){return yP(this,n)}toImageData(n){return xP(this,n)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(n){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,n&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(n){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return SP(this,n)}}}),ti,BP=et(()=>{WC(),ti=Hi}),qg,e_,Fa,Zs,jc,Wc,MP=et(()=>{gP(),qg=(n,e)=>{(typeof Tr.trace>"u"?!Tr.wasm.trace:!Tr.trace)||console.timeStamp(`${n}::ORT::${e}`)},e_=(n,e)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<t.length;i++){if(r&&!t[i].includes("TRACE_FUNC")){let s=`FUNC_${n}::${t[i].trim().split(" ")[1]}`;e&&(s+=`::${e}`),qg("CPU",s);return}t[i].includes("TRACE_FUNC")&&(r=!0)}},Fa=n=>{(typeof Tr.trace>"u"?!Tr.wasm.trace:!Tr.trace)||e_("BEGIN",n)},Zs=n=>{(typeof Tr.trace>"u"?!Tr.wasm.trace:!Tr.trace)||e_("END",n)},jc=n=>{(typeof Tr.trace>"u"?!Tr.wasm.trace:!Tr.trace)||console.time(`ORT::${n}`)},Wc=n=>{(typeof Tr.trace>"u"?!Tr.wasm.trace:!Tr.trace)||console.timeEnd(`ORT::${n}`)}}),TP,Yee=et(()=>{AP(),BP(),MP(),TP=class RP{constructor(e){this.handler=e}async run(e,t,r){Fa(),jc("InferenceSession.run");let i={},s={};if(typeof e!="object"||e===null||e instanceof ti||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof ti)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);i[c]=null}if(typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,d=Object.getOwnPropertyNames(t);for(let h of this.outputNames)if(d.indexOf(h)!==-1){let p=t[h];(p===null||p instanceof ti)&&(c=!0,a=!1,i[h]=p)}if(c){if(typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else s=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)i[c]=null;let o=await this.handler.run(e,i,s),l={};for(let c in o)if(Object.hasOwnProperty.call(o,c)){let d=o[c];d instanceof ti?l[c]=d:l[c]=new ti(d.type,d.data,d.dims)}return Wc("InferenceSession.run"),Zs(),l}async release(){return this.handler.dispose()}static async create(e,t,r,i){Fa(),jc("InferenceSession.create");let s,a={};if(typeof e=="string"){if(s=e,typeof t=="object"&&t!==null)a=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(s=e,typeof t=="object"&&t!==null)a=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let d=e,h=0,p=e.byteLength;if(typeof t=="object"&&t!==null)a=t;else if(typeof t=="number"){if(h=t,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(p=e.byteLength-h,typeof r=="number"){if(p=r,!Number.isSafeInteger(p))throw new RangeError("'byteLength' must be an integer.");if(p<=0||h+p>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-h}].`);if(typeof i=="object"&&i!==null)a=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");s=new Uint8Array(d,h,p)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[o,l]=await pP(a),c=await o.createInferenceSessionHandler(s,l);return Wc("InferenceSession.create"),Zs(),new RP(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),qC,Jee=et(()=>{Yee(),qC=TP}),Xee=et(()=>{}),Kee=et(()=>{}),Zee=et(()=>{}),ete=et(()=>{}),tte={};vh(tte,{InferenceSession:()=>qC,TRACE:()=>qg,TRACE_EVENT_BEGIN:()=>jc,TRACE_EVENT_END:()=>Wc,TRACE_FUNC_BEGIN:()=>Fa,TRACE_FUNC_END:()=>Zs,Tensor:()=>ti,env:()=>Dn,registerBackend:()=>Bd});var xs=et(()=>{$ee(),Hee(),Jee(),BP(),Xee(),Kee(),MP(),Zee(),ete()}),YC=et(()=>{}),DP={};vh(DP,{default:()=>kP});var t_,n_,kP,nte=et(()=>{Fz(),cu(),JC(),t_="ort-wasm-proxy-worker",n_=globalThis.self?.name===t_,n_&&(self.onmessage=n=>{let{type:e,in:t}=n.data;try{switch(e){case"init-wasm":XC(t.wasm).then(()=>{pI(t).then(()=>{postMessage({type:e})},r=>{postMessage({type:e,err:r})})},r=>{postMessage({type:e,err:r})});break;case"init-ep":{let{epName:r,env:i}=t;AI(i,r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})});break}case"copy-from":{let{buffer:r}=t,i=t0(r);postMessage({type:e,out:i});break}case"create":{let{model:r,options:i}=t;mI(r,i).then(s=>{postMessage({type:e,out:s})},s=>{postMessage({type:e,err:s})});break}case"release":gI(t),postMessage({type:e});break;case"run":{let{sessionId:r,inputIndices:i,inputs:s,outputIndices:a,options:o}=t;yI(r,i,s,a,new Array(a.length).fill(null),o).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},vI([...s,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":xI(t),postMessage({type:e});break;default:}}catch(r){postMessage({type:e,err:r})}}),kP=n_?null:n=>new Worker(n??Gi,{type:"module",name:t_})}),NP={};vh(NP,{default:()=>QP});async function mB(n={}){var e=n,t=!!globalThis.window,r=!!globalThis.WorkerGlobalScope,i=r&&self.name?.startsWith("em-pthread");e.mountExternalData=(I,N)=>{I.startsWith("./")&&(I=I.substring(2)),(e.Zc||(e.Zc=new Map)).set(I,N)},e.unmountExternalData=()=>{delete e.Zc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,ae:!0}).buffer.constructor;let s=I=>async(...N)=>{try{if(e.$c)throw Error("Session already started");let O=e.$c={Nd:N[0],errors:[]},z=await I(...N);if(e.$c!==O)throw Error("Session mismatch");e.gd?.flush();let se=O.errors;if(0<se.length){let ce=await Promise.all(se);if(ce=ce.filter(Se=>Se),0<ce.length)throw Error(ce.join(`
|
|
12826
12826
|
`))}return z}finally{e.$c=null}};e.jsepInit=(I,N)=>{if(I==="webgpu"){[e.gd,e.Dd,e.Hd,e.jd,e.Gd,e.ac,e.Id,e.Kd,e.Ed,e.Fd,e.Jd]=N;let O=e.gd;e.jsepRegisterBuffer=(z,se,ce,Se)=>O.registerBuffer(z,se,ce,Se),e.jsepGetBuffer=z=>O.getBuffer(z),e.jsepCreateDownloader=(z,se,ce)=>O.createDownloader(z,se,ce),e.jsepOnCreateSession=z=>{O.onCreateSession(z)},e.jsepOnReleaseSession=z=>{O.onReleaseSession(z)},e.jsepOnRunStart=z=>O.onRunStart(z),e.Ld=(z,se)=>{O.upload(z,se)}}else if(I==="webnn"){let O=N[0];[e.Zd,e.vd,e.webnnEnsureTensor,e.xd,e.webnnDownloadTensor,e.Yd,e.webnnEnableTraceEvent]=N.slice(1),e.webnnReleaseTensorId=e.vd,e.webnnUploadTensor=e.xd,e.webnnRegisterMLContext=e.Yd,e.webnnOnRunStart=z=>O.onRunStart(z),e.webnnOnRunEnd=O.onRunEnd.bind(O),e.webnnOnReleaseSession=z=>{O.onReleaseSession(z)},e.webnnCreateMLTensorDownloader=(z,se)=>O.createMLTensorDownloader(z,se),e.webnnRegisterMLTensor=(z,se,ce,Se)=>O.registerMLTensor(z,se,ce,Se),e.webnnCreateMLContext=z=>O.createMLContext(z),e.webnnRegisterMLConstant=(z,se,ce,Se,Ue,rt)=>O.registerMLConstant(z,se,ce,Se,Ue,e.Zc,rt),e.webnnRegisterGraphInput=O.registerGraphInput.bind(O),e.webnnIsGraphInput=O.isGraphInput.bind(O),e.webnnRegisterGraphOutput=O.registerGraphOutput.bind(O),e.webnnIsGraphOutput=O.isGraphOutput.bind(O),e.webnnCreateTemporaryTensor=O.createTemporaryTensor.bind(O),e.webnnIsGraphInputOutputTypeSupported=O.isGraphInputOutputTypeSupported.bind(O)}};let a=()=>{let I=N=>(...O)=>{let z=Gr;return O=N(...O),Gr!=z?new Promise((se,ce)=>{$o={resolve:se,reject:ce}}):O};(()=>{for(let N of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[N]=I(e[N])})(),s!==void 0&&(e._OrtRun=s(e._OrtRun),e._OrtRunWithBinding=s(e._OrtRunWithBinding)),a=void 0};e.asyncInit=()=>{a?.()};var o,l,c=(I,N)=>{throw N},d=import.meta.url,h="";if(t||r){try{h=new URL(".",d).href}catch{}r&&(l=I=>{var N=new XMLHttpRequest;return N.open("GET",I,!1),N.responseType="arraybuffer",N.send(null),new Uint8Array(N.response)}),o=async I=>{if(M(I))return new Promise((O,z)=>{var se=new XMLHttpRequest;se.open("GET",I,!0),se.responseType="arraybuffer",se.onload=()=>{se.status==200||se.status==0&&se.response?O(se.response):z(se.status)},se.onerror=z,se.send(null)});var N=await fetch(I,{credentials:"same-origin"});if(N.ok)return N.arrayBuffer();throw Error(N.status+" : "+N.url)}}var p,A,y,m,x,g,_=console.log.bind(console),b=console.error.bind(console),w=_,C=b,S=!1,M=I=>I.startsWith("file://");function T(){Ie.buffer!=k.buffer&&H()}if(i){let I=function(N){try{var O=N.data,z=O.Uc;if(z==="load"){let se=[];self.onmessage=ce=>se.push(ce),g=()=>{postMessage({Uc:"loaded"});for(let ce of se)I(ce);self.onmessage=I};for(let ce of O.Ad)e[ce]&&!e[ce].proxy||(e[ce]=(...Se)=>{postMessage({Uc:"callHandler",zd:ce,args:Se})},ce=="print"&&(w=e[ce]),ce=="printErr"&&(C=e[ce]));Ie=O.Vd,H(),A=O.Wd,he(),sc()}else if(z==="run"){(function(se){var ce=(T(),W)[se+52>>>2>>>0];se=(T(),W)[se+56>>>2>>>0],Fh(ce,ce-se),qt(ce)})(O.Tc),qa(O.Tc,0,0,1,0,0),Z(),xi(O.Tc),R||(uA(),R=!0);try{me(O.Pd,O.dd)}catch(se){if(se!="unwind")throw se}}else O.target!=="setimmediate"&&(z==="checkMailbox"?R&&Uo():z&&(C(`worker: received unknown command ${z}`),C(O)))}catch(se){throw Jo(),se}};var R=!1;self.onunhandledrejection=N=>{throw N.reason||N},self.onmessage=I}var k,G,P,V,B,W,K,Y,$,J,re,L=!1;function H(){var I=Ie.buffer;e.HEAP8=k=new Int8Array(I),P=new Int16Array(I),e.HEAPU8=G=new Uint8Array(I),V=new Uint16Array(I),e.HEAP32=B=new Int32Array(I),e.HEAPU32=W=new Uint32Array(I),K=new Float32Array(I),Y=new Float64Array(I),$=new BigInt64Array(I),J=new BigUint64Array(I)}function oe(){L=!0,i?g():qi.tb()}function Ae(I){throw C(I="Aborted("+I+")"),S=!0,I=new WebAssembly.RuntimeError(I+". Build with -sASSERTIONS for more info."),x?.(I),I}function ye(){return{a:{ma:Lu,hb:xA,g:Ve,J:tt,f:dt,o:Mt,h:_e,ha:ut,b:je,T:Ye,Ia:He,n:_t,_:rr,Ya:Qo,Ea:vs,Ga:jl,Za:Or,Wa:_s,Pa:la,Va:Ga,ka:Ha,Fa:Wl,Ca:Va,Xa:Ni,Da:Po,cb:du,ea:Te,xa:De,va:St,da:$t,O:xn,H:Fn,wa:Rt,Z:Jn,ya:$r,Sa:Zn,Aa:qp,Ja:Yp,ta:_h,fa:fu,Ra:xi,$a:da,R:ql,s:gu,c:st,ib:bh,y:eA,M:fa,D:wh,m:yu,t:Eh,jb:xu,I:vu,S:tA,j:si,v:Vo,r:Ch,l:Yl,Ma:ry,Na:wu,Oa:nA,Ka:rA,La:iA,ua:sA,eb:iy,bb:ay,u:oy,aa:ly,ga:cy,ab:sy,V:uy,_a:Mh,Ba:dy,F:Ih,U:hy,la:Eu,za:py,gb:fy,fb:Ay,Ta:Wo,Ua:oA,Ha:te,$:Dh,ja:kh,Qa:Nh,ia:Qh,lb:wA,na:Er,mb:bA,oa:ma,G:Ka,d:sf,q:nf,w:Fu,B:Yi,pb:Aa,K:lf,x:gy,pa:Pn,X:Hr,ba:sl,nb:Uu,ob:Vr,ra:ic,qa:cf,qb:il,N:vy,Y:Tn,e:af,A:vA,k:rf,kb:Ou,p:xy,z:of,C:yy,E:pa,L:rc,rb:_y,Q:Za,ca:Cs,W:al,sb:rl,sa:_A,P:zu,i:qo,a:Ie,db:X}}}async function he(){function I(z,se){var ce=qi=z.exports;z={};for(let[Se,Ue]of Object.entries(ce))typeof Ue=="function"?(ce=ha(Ue),z[Se]=ce):z[Se]=Ue;return qi=z,qi=(function(){var Se=qi,Ue=ht=>Nt=>ht(Nt)>>>0,rt=ht=>()=>ht()>>>0;return(Se=Object.assign({},Se)).ub=Ue(Se.ub),Se.Yb=rt(Se.Yb),Se._b=Ue(Se._b),Se.mc=Ue(Se.mc),Se.nc=rt(Se.nc),Se.rc=Ue(Se.rc),Se})(),Ce.push(qi.$b),cA=(z=qi).ub,uA=z.vb,e._OrtInit=z.wb,e._OrtGetLastError=z.xb,e._OrtCreateSessionOptions=z.yb,e._OrtAppendExecutionProvider=z.zb,e._OrtAddFreeDimensionOverride=z.Ab,e._OrtAddSessionConfigEntry=z.Bb,e._OrtReleaseSessionOptions=z.Cb,e._OrtCreateSession=z.Db,e._OrtReleaseSession=z.Eb,e._OrtGetInputOutputCount=z.Fb,e._OrtGetInputOutputMetadata=z.Gb,e._OrtFree=z.Hb,e._OrtCreateTensor=z.Ib,e._OrtGetTensorData=z.Jb,e._OrtReleaseTensor=z.Kb,e._OrtCreateRunOptions=z.Lb,e._OrtAddRunConfigEntry=z.Mb,e._OrtReleaseRunOptions=z.Nb,e._OrtCreateBinding=z.Ob,e._OrtBindInput=z.Pb,e._OrtBindOutput=z.Qb,e._OrtClearBoundOutputs=z.Rb,e._OrtReleaseBinding=z.Sb,e._OrtRunWithBinding=z.Tb,e._OrtRun=z.Ub,e._OrtEndProfiling=z.Vb,e._JsepOutput=z.Wb,e._JsepGetNodeName=z.Xb,Iu=z.Yb,Pi=e._free=z.Zb,Yo=e._malloc=z._b,qa=z.bc,Jo=z.cc,dA=z.dc,Kl=z.ec,Ph=z.fc,Lh=z.gc,Su=z.hc,Yt=z.ic,Xo=z.jc,Fh=z.kc,qt=z.lc,zh=z.mc,Jt=z.nc,hA=z.oc,Uh=z.pc,fA=z.qc,_i=z.rc,Ko=z.sc,Bu=z.tc,Oh=z.uc,$h=z.vc,Gh=z.wc,Mu=z.xc,pA=z.yc,AA=z.zc,Ya=z.Ac,Tu=z.Bc,Zo=z.Cc,Ru=z.Dc,Hh=z.Ec,Zl=z.Fc,Ja=z.Gc,Du=z.Hc,Vh=z.Ic,ec=z.Jc,jh=z.Kc,Wh=z.Lc,qh=z.Mc,Yh=z.Nc,Jh=z.Oc,Xh=z.Pc,Es=z.Rc,ku=z.Sc,Nu=z.bd,mA=z.cd,gA=z.hd,el=z.kd,yA=z.ld,Kh=z.md,Zh=z.nd,Mn=z.od,Qu=z.pd,tc=z.qd,tl=z.rd,ef=z.wd,Pu=z.Rd,nl=z.Sd,nc=z.Td,Xa=z.Ud,A=se,qi}var N,O=ye();return e.instantiateWasm?new Promise(z=>{e.instantiateWasm(O,(se,ce)=>{z(I(se,ce))})}):i?I(new WebAssembly.Instance(A,ye()),A):(re??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.jsep.wasm",h):h+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href,N=await(async function(z){var se=re;if(!p&&!M(se))try{var ce=fetch(se,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ce,z)}catch(Se){C(`wasm streaming compile failed: ${Se}`),C("falling back to ArrayBuffer instantiation")}return(async function(Se,Ue){try{var rt=await(async function(ht){if(!p)try{var Nt=await o(ht);return new Uint8Array(Nt)}catch{}if(ht==re&&p)ht=new Uint8Array(p);else{if(!l)throw"both async and sync fetching of the wasm failed";ht=l(ht)}return ht})(Se);return await WebAssembly.instantiate(rt,Ue)}catch(ht){C(`failed to asynchronously prepare wasm: ${ht}`),Ae(ht)}})(se,z)})(O),I(N.instance,N.module))}class fe{name="ExitStatus";constructor(N){this.message=`Program terminated with exit(${N})`,this.status=N}}var Ee=I=>{I.terminate(),I.onmessage=()=>{}},Re=[],ve=0,Ne=null,ct=I=>{ee.length==0&&(le(),q(ee[0]));var N=ee.pop();if(!N)return 6;ie.push(N),be[I.Tc]=N,N.Tc=I.Tc;var O={Uc:"run",Pd:I.Od,dd:I.dd,Tc:I.Tc};return N.postMessage(O,I.ud),0},Ge=0,F=(I,N,...O)=>{var z,se=16*O.length,ce=Jt(),Se=zh(se),Ue=Se>>>3;for(z of O)typeof z=="bigint"?((T(),$)[Ue++>>>0]=1n,(T(),$)[Ue++>>>0]=z):((T(),$)[Ue++>>>0]=0n,(T(),Y)[Ue++>>>0]=z);return I=dA(I,0,se,Se,N),qt(ce),I};function X(I){if(i)return F(0,1,I);if(y=I,!(0<Ge)){for(var N of ie)Ee(N);for(N of ee)Ee(N);ee=[],ie=[],be={},S=!0}c(0,new fe(I))}function ge(I){if(i)return F(1,0,I);te(I)}var te=I=>{if(y=I,i)throw ge(I),"unwind";X(I)},ee=[],ie=[],Ce=[],be={},de=I=>{var N=I.Tc;delete be[N],ee.push(I),ie.splice(ie.indexOf(I),1),I.Tc=0,Kl(N)};function Z(){Ce.forEach(I=>I())}var q=I=>new Promise(N=>{I.onmessage=se=>{var ce=se.data;if(se=ce.Uc,ce.ad&&ce.ad!=Iu()){var Se=be[ce.ad];Se?Se.postMessage(ce,ce.ud):C(`Internal error! Worker sent a message "${se}" to target pthread ${ce.ad}, but that thread no longer exists!`)}else se==="checkMailbox"?Uo():se==="spawnThread"?ct(ce):se==="cleanupThread"?Gt(()=>{de(be[ce.Qd])}):se==="loaded"?(I.loaded=!0,N(I)):ce.target==="setimmediate"?I.postMessage(ce):se==="uncaughtException"?I.onerror(ce.error):se==="callHandler"?e[ce.zd](...ce.args):se&&C(`worker sent an unknown command ${se}`)},I.onerror=se=>{throw C(`worker sent an error! ${se.filename}:${se.lineno}: ${se.message}`),se};var O,z=[];for(O of[])e.propertyIsEnumerable(O)&&z.push(O);I.postMessage({Uc:"load",Ad:z,Vd:Ie,Wd:A})});function le(){var I=new Worker((()=>{let N=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new N("ort.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});ee.push(I)}var Ie,me=(I,N)=>{Ge=0,I=Bu(I,N),0<Ge?y=I:Ph(I)},xe=[],it=0;function Ve(I){var N=new pt(I>>>=0);return(T(),k)[N.Vc+12>>>0]==0&&(ze(N,!0),it--),Ze(N,!1),xe.push(N),_i(I)}var Ke=0,tt=()=>{Yt(0,0);var I=xe.pop();hA(I.ed),Ke=0};function ze(I,N){N=N?1:0,(T(),k)[I.Vc+12>>>0]=N}function Ze(I,N){N=N?1:0,(T(),k)[I.Vc+13>>>0]=N}class pt{constructor(N){this.ed=N,this.Vc=N-24}}var ft=I=>{var N=Ke;if(!N)return Xo(0),0;var O=new pt(N);(T(),W)[O.Vc+16>>>2>>>0]=N;var z=(T(),W)[O.Vc+4>>>2>>>0];if(!z)return Xo(0),N;for(var se of I){if(se===0||se===z)break;if(fA(se,z,O.Vc+16))return Xo(se),N}return Xo(z),N};function dt(){return ft([])}function Mt(I){return ft([I>>>0])}function _e(I,N,O,z){return ft([I>>>0,N>>>0,O>>>0,z>>>0])}var ut=()=>{var I=xe.pop();I||Ae("no exception to throw");var N=I.ed;throw(T(),k)[I.Vc+13>>>0]==0&&(xe.push(I),Ze(I,!0),ze(I,!1),it++),Uh(N),Ke=N};function je(I,N,O){var z=new pt(I>>>=0);throw N>>>=0,O>>>=0,(T(),W)[z.Vc+16>>>2>>>0]=0,(T(),W)[z.Vc+4>>>2>>>0]=N,(T(),W)[z.Vc+8>>>2>>>0]=O,Uh(I),it++,Ke=I}var Ye=()=>it;function We(I,N,O,z){return i?F(2,1,I,N,O,z):He(I,N,O,z)}function He(I,N,O,z){if(I>>>=0,N>>>=0,O>>>=0,z>>>=0,!globalThis.SharedArrayBuffer)return 6;var se=[];return i&&se.length===0?We(I,N,O,z):(I={Od:O,Tc:I,dd:z,ud:se},i?(I.Uc="spawnThread",postMessage(I,se),0):ct(I))}function _t(I){throw Ke||=I>>>0,Ke}var Ot=globalThis.TextDecoder&&new TextDecoder,En=(I,N,O,z)=>{if(O=N+O,z)return O;for(;I[N]&&!(N>=O);)++N;return N},dn=(I,N=0,O,z)=>{if(16<(O=En(I,N>>>=0,O,z))-N&&I.buffer&&Ot)return Ot.decode(I.buffer instanceof ArrayBuffer?I.subarray(N,O):I.slice(N,O));for(z="";N<O;){var se=I[N++];if(128&se){var ce=63&I[N++];if((224&se)==192)z+=String.fromCharCode((31&se)<<6|ce);else{var Se=63&I[N++];65536>(se=(240&se)==224?(15&se)<<12|ce<<6|Se:(7&se)<<18|ce<<12|Se<<6|63&I[N++])?z+=String.fromCharCode(se):(se-=65536,z+=String.fromCharCode(55296|se>>10,56320|1023&se))}}else z+=String.fromCharCode(se)}return z},hn=(I,N,O)=>(I>>>=0)?dn((T(),G),I,N,O):"";function rr(I,N,O){return i?F(3,1,I,N,O):0}function Qo(I,N){if(i)return F(4,1,I,N)}function vs(I,N){if(i)return F(5,1,I,N)}function jl(I,N,O){if(i)return F(6,1,I,N,O)}function Or(I,N,O){return i?F(7,1,I,N,O):0}function _s(I,N){if(i)return F(8,1,I,N)}function la(I,N,O){if(i)return F(9,1,I,N,O)}function Ga(I,N,O,z){if(i)return F(10,1,I,N,O,z)}function Ha(I,N,O,z){if(i)return F(11,1,I,N,O,z)}function Wl(I,N,O,z){if(i)return F(12,1,I,N,O,z)}function Va(I){if(i)return F(13,1,I)}function Ni(I,N){if(i)return F(14,1,I,N)}function Po(I,N,O){if(i)return F(15,1,I,N,O)}var du=()=>Ae(""),gi=I=>{I>>>=0;for(var N="";;){var O=(T(),G)[I++>>>0];if(!O)return N;N+=String.fromCharCode(O)}},Lo={},Fo={},bs=class extends Error{constructor(I){super(I),this.name="BindingError"}};function yi(I,N,O={}){return(function(z,se,ce={}){var Se=se.name;if(!z)throw new bs(`type "${Se}" must have a positive integer typeid pointer`);if(Fo.hasOwnProperty(z)){if(ce.Bd)return;throw new bs(`Cannot register type '${Se}' twice`)}Fo[z]=se,Lo.hasOwnProperty(z)&&(se=Lo[z],delete Lo[z],se.forEach(Ue=>Ue()))})(I,N,O)}var ae=(I,N,O)=>{switch(N){case 1:return O?z=>(T(),k)[z>>>0]:z=>(T(),G)[z>>>0];case 2:return O?z=>(T(),P)[z>>>1>>>0]:z=>(T(),V)[z>>>1>>>0];case 4:return O?z=>(T(),B)[z>>>2>>>0]:z=>(T(),W)[z>>>2>>>0];case 8:return O?z=>(T(),$)[z>>>3>>>0]:z=>(T(),J)[z>>>3>>>0];default:throw new TypeError(`invalid integer width (${N}): ${I}`)}};function Te(I,N,O,z,se){I>>>=0,O>>>=0,N=gi(N>>>0);let ce=Se=>Se;if(z=z===0n){let Se=8*O;ce=Ue=>BigInt.asUintN(Se,Ue),se=ce(se)}yi(I,{name:N,Qc:ce,Xc:(Se,Ue)=>(typeof Ue=="number"&&(Ue=BigInt(Ue)),Ue),Wc:ae(N,O,!z),Yc:null})}function De(I,N,O,z){yi(I>>>=0,{name:N=gi(N>>>0),Qc:function(se){return!!se},Xc:function(se,ce){return ce?O:z},Wc:function(se){return this.Qc((T(),G)[se>>>0])},Yc:null})}var Fe=[],Me=[0,1,,1,null,1,!0,1,!1,1];function st(I){9<(I>>>=0)&&--Me[I+1]==0&&(Me[I]=void 0,Fe.push(I))}var ot=I=>{if(!I)throw new bs(`Cannot use deleted val. handle = ${I}`);return Me[I]},At=I=>{switch(I){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let N=Fe.pop()||Me.length;return Me[N]=I,Me[N+1]=1,N}};function gt(I){return this.Qc((T(),W)[I>>>2>>>0])}var Qt={name:"emscripten::val",Qc:I=>{var N=ot(I);return st(I),N},Xc:(I,N)=>At(N),Wc:gt,Yc:null};function St(I){return yi(I>>>0,Qt)}var kt=(I,N)=>{switch(N){case 4:return function(O){return this.Qc((T(),K)[O>>>2>>>0])};case 8:return function(O){return this.Qc((T(),Y)[O>>>3>>>0])};default:throw new TypeError(`invalid float width (${N}): ${I}`)}};function $t(I,N,O){O>>>=0,yi(I>>>=0,{name:N=gi(N>>>0),Qc:z=>z,Xc:(z,se)=>se,Wc:kt(N,O),Yc:null})}function xn(I,N,O,z,se){I>>>=0,O>>>=0,N=gi(N>>>0);let ce=Ue=>Ue;if(z===0){var Se=32-8*O;ce=Ue=>Ue<<Se>>>Se,se=ce(se)}yi(I,{name:N,Qc:ce,Xc:(Ue,rt)=>rt,Wc:ae(N,O,z!==0),Yc:null})}function Fn(I,N,O){function z(ce){var Se=(T(),W)[ce>>>2>>>0];return ce=(T(),W)[ce+4>>>2>>>0],new se((T(),k).buffer,ce,Se)}var se=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][N];yi(I>>>=0,{name:O=gi(O>>>0),Qc:z,Wc:z},{Bd:!0})}var An=(I,N,O)=>{var z=(T(),G);if(N>>>=0,0<O){var se=N;O=N+O-1;for(var ce=0;ce<I.length;++ce){var Se=I.codePointAt(ce);if(127>=Se){if(N>=O)break;z[N++>>>0]=Se}else if(2047>=Se){if(N+1>=O)break;z[N++>>>0]=192|Se>>6,z[N++>>>0]=128|63&Se}else if(65535>=Se){if(N+2>=O)break;z[N++>>>0]=224|Se>>12,z[N++>>>0]=128|Se>>6&63,z[N++>>>0]=128|63&Se}else{if(N+3>=O)break;z[N++>>>0]=240|Se>>18,z[N++>>>0]=128|Se>>12&63,z[N++>>>0]=128|Se>>6&63,z[N++>>>0]=128|63&Se,ce++}}z[N>>>0]=0,I=N-se}else I=0;return I},an=I=>{for(var N=0,O=0;O<I.length;++O){var z=I.charCodeAt(O);127>=z?N++:2047>=z?N+=2:55296<=z&&57343>=z?(N+=4,++O):N+=3}return N};function Rt(I,N){yi(I>>>=0,{name:N=gi(N>>>0),Qc(O){var z=(T(),W)[O>>>2>>>0];return z=hn(O+4,z,!0),Pi(O),z},Xc(O,z){z instanceof ArrayBuffer&&(z=new Uint8Array(z));var se=typeof z=="string";if(!(se||ArrayBuffer.isView(z)&&z.BYTES_PER_ELEMENT==1))throw new bs("Cannot pass non-string to std::string");var ce=se?an(z):z.length,Se=Yo(4+ce+1),Ue=Se+4;return(T(),W)[Se>>>2>>>0]=ce,se?An(z,Ue,ce+1):(T(),G).set(z,Ue>>>0),O!==null&&O.push(Pi,Se),Se},Wc:gt,Yc(O){Pi(O)}})}var vn=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,tn=(I,N,O)=>{if(I>>>=1,16<(N=En((T(),V),I,N/2,O))-I&&vn)return vn.decode((T(),V).slice(I,N));for(O="";I<N;++I){var z=(T(),V)[I>>>0];O+=String.fromCharCode(z)}return O},Pr=(I,N,O)=>{if(O??=2147483647,2>O)return 0;var z=N;O=(O-=2)<2*I.length?O/2:I.length;for(var se=0;se<O;++se){var ce=I.charCodeAt(se);(T(),P)[N>>>1>>>0]=ce,N+=2}return(T(),P)[N>>>1>>>0]=0,N-z},ca=I=>2*I.length,dr=(I,N,O)=>{var z="";I>>>=2;for(var se=0;!(se>=N/4);se++){var ce=(T(),W)[I+se>>>0];if(!ce&&!O)break;z+=String.fromCodePoint(ce)}return z},ua=(I,N,O)=>{if(N>>>=0,O??=2147483647,4>O)return 0;var z=N;O=z+O-4;for(var se=0;se<I.length;++se){var ce=I.codePointAt(se);if(65535<ce&&se++,(T(),B)[N>>>2>>>0]=ce,(N+=4)+4>O)break}return(T(),B)[N>>>2>>>0]=0,N-z},In=I=>{for(var N=0,O=0;O<I.length;++O)65535<I.codePointAt(O)&&O++,N+=4;return N};function Jn(I,N,O){if(I>>>=0,N>>>=0,O=gi(O>>>=0),N===2)var z=tn,se=Pr,ce=ca;else z=dr,se=ua,ce=In;yi(I,{name:O,Qc:Se=>{var Ue=(T(),W)[Se>>>2>>>0];return Ue=z(Se+4,Ue*N,!0),Pi(Se),Ue},Xc:(Se,Ue)=>{if(typeof Ue!="string")throw new bs(`Cannot pass non-string to C++ string type ${O}`);var rt=ce(Ue),ht=Yo(4+rt+N);return(T(),W)[ht>>>2>>>0]=rt/N,se(Ue,ht+4,rt+N),Se!==null&&Se.push(Pi,ht),ht},Wc:gt,Yc(Se){Pi(Se)}})}function $r(I,N){yi(I>>>=0,{Cd:!0,name:N=gi(N>>>0),Qc:()=>{},Xc:()=>{}})}function Zn(I){qa(I>>>0,!r,1,!t,131072,!1),Z()}var Gt=I=>{if(!S)try{if(I(),!(0<Ge))try{i?Iu()&&Ph(y):te(y)}catch(N){N instanceof fe||N=="unwind"||c(0,N)}}catch(N){N instanceof fe||N=="unwind"||c(0,N)}},zo=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function xi(I){I>>>=0,zo||(Atomics.waitAsync((T(),B),I>>>2,I).value.then(Uo),I+=128,Atomics.store((T(),B),I>>>2,1))}var Uo=()=>Gt(()=>{var I=Iu();I&&(xi(I),Su())});function qp(I,N){(I>>>=0)==N>>>0?setTimeout(Uo):i?postMessage({ad:I,Uc:"checkMailbox"}):(I=be[I])&&I.postMessage({Uc:"checkMailbox"})}var hu=[];function Yp(I,N,O,z,se){for(N>>>=0,se>>>=0,hu.length=0,O=se>>>3,z=se+z>>>3;O<z;){var ce;ce=(T(),$)[O++>>>0]?(T(),$)[O++>>>0]:(T(),Y)[O++>>>0],hu.push(ce)}return(N?tf[N]:my[I])(...hu)}var _h=()=>{Ge=0};function fu(I){I>>>=0,i?postMessage({Uc:"cleanupThread",Qd:I}):de(be[I])}function da(I){}var Qi=I=>{try{I()}catch(N){Ae(N)}};function ha(I){var N=(...O)=>{pu.push(I);try{return I(...O)}finally{S||(pu.pop(),Gr&&vi===1&&pu.length===0&&(vi=0,Ge+=1,Qi(nl),typeof Fibers<"u"&&Fibers.ce()))}};return Jp.set(I,N),N}var vi=0,Gr=null,ws=0,pu=[],Au=new Map,Oo=new Map,Jp=new Map,Xp=0,$o=null,Kp=[],Zp=I=>(function(N){if(!S){if(vi===0){var O=!1,z=!1;N((se=0)=>{if(!S&&(ws=se,O=!0,z)){vi=2,Qi(()=>nc(Gr)),typeof MainLoop<"u"&&MainLoop.yd&&MainLoop.resume(),se=!1;try{var ce=(function(){var rt=(T(),B)[Gr+8>>>2>>>0];return rt=Oo.get(rt),rt=Jp.get(rt),--Ge,rt()})()}catch(rt){ce=rt,se=!0}var Se=!1;if(!Gr){var Ue=$o;Ue&&($o=null,(se?Ue.reject:Ue.resolve)(ce),Se=!0)}if(se&&!Se)throw ce}}),z=!0,O||(vi=1,Gr=(function(){var se=Yo(65548),ce=se+12;if((T(),W)[se>>>2>>>0]=ce,(T(),W)[se+4>>>2>>>0]=ce+65536,ce=pu[0],!Au.has(ce)){var Se=Xp++;Au.set(ce,Se),Oo.set(Se,ce)}return ce=Au.get(ce),(T(),B)[se+8>>>2>>>0]=ce,se})(),typeof MainLoop<"u"&&MainLoop.yd&&MainLoop.pause(),Qi(()=>Pu(Gr)))}else vi===2?(vi=0,Qi(Xa),Pi(Gr),Gr=null,Kp.forEach(Gt)):Ae(`invalid state: ${vi}`);return ws}})(N=>{I().then(N)});function ql(I){return I>>>=0,Zp(async()=>{var N=await ot(I);return At(N)})}var ja=[],Go=I=>{var N=ja.length;return ja.push(I),N},mu=(I,N)=>{for(var O=Array(I),z=0;z<I;++z){var se=z,ce=(T(),W)[N+4*z>>>2>>>0],Se=Fo[ce];if(Se===void 0)throw I=`parameter ${z}`,ce=cA(ce),N=gi(ce),Pi(ce),new bs(`${I} has unknown type ${N}`);O[se]=Se}return O},ty=(I,N,O)=>{var z=[];return I=I(z,O),z.length&&((T(),W)[N>>>2>>>0]=At(z)),I},ny={},Ho=I=>{var N=ny[I];return N===void 0?gi(I):N};function gu(I,N,O){var[z,...se]=mu(I,N>>>0);N=z.Xc.bind(z);var ce=se.map(rt=>rt.Wc.bind(rt));I--;var Se={toValue:ot};switch(I=ce.map((rt,ht)=>{var Nt=`argFromPtr${ht}`;return Se[Nt]=rt,`${Nt}(args${ht?"+"+8*ht:""})`}),O){case 0:var Ue="toValue(handle)";break;case 2:Ue="new (toValue(handle))";break;case 3:Ue="";break;case 1:Se.getStringOrSymbol=Ho,Ue="toValue(handle)[getStringOrSymbol(methodName)]"}return Ue+=`(${I})`,z.Cd||(Se.toReturnWire=N,Se.emval_returnValue=ty,Ue=`return emval_returnValue(toReturnWire, destructorsRef, ${Ue})`),Ue=`return function (handle, methodName, destructorsRef, args) {
|
|
12827
12827
|
${Ue}
|
|
12828
12828
|
}`,O=new Function(Object.keys(Se),Ue)(...Object.values(Se)),Ue=`methodCaller<(${se.map(rt=>rt.name)}) => ${z.name}>`,Go(Object.defineProperty(O,"name",{value:Ue}))}function bh(I,N){return N>>>=0,(I=ot(I>>>0))==ot(N)}function eA(I){return(I>>>=0)?(I=Ho(I),At(globalThis[I])):At(globalThis)}function fa(I){return I=Ho(I>>>0),At(e[I])}function wh(I,N){return N>>>=0,I=ot(I>>>0),N=ot(N),At(I[N])}function yu(I){9<(I>>>=0)&&(Me[I+1]+=1)}function Eh(I,N,O,z,se){return ja[I>>>0](N>>>0,O>>>0,z>>>0,se>>>0)}function xu(I,N,O,z,se){return Eh(I>>>0,N>>>0,O>>>0,z>>>0,se>>>0)}function vu(){return At([])}function tA(I){I=ot(I>>>0);for(var N=Array(I.length),O=0;O<I.length;O++)N[O]=I[O];return At(N)}function si(I){return At(Ho(I>>>0))}function Vo(){return At({})}function Ch(I){for(var N=ot(I>>>=0);N.length;){var O=N.pop();N.pop()(O)}st(I)}function Yl(I,N,O){N>>>=0,O>>>=0,I=ot(I>>>0),N=ot(N),O=ot(O),I[N]=O}function ry(I,N){I=-9007199254740992>I||9007199254740992<I?NaN:Number(I),N>>>=0,I=new Date(1e3*I),(T(),B)[N>>>2>>>0]=I.getUTCSeconds(),(T(),B)[N+4>>>2>>>0]=I.getUTCMinutes(),(T(),B)[N+8>>>2>>>0]=I.getUTCHours(),(T(),B)[N+12>>>2>>>0]=I.getUTCDate(),(T(),B)[N+16>>>2>>>0]=I.getUTCMonth(),(T(),B)[N+20>>>2>>>0]=I.getUTCFullYear()-1900,(T(),B)[N+24>>>2>>>0]=I.getUTCDay(),I=(I.getTime()-Date.UTC(I.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(T(),B)[N+28>>>2>>>0]=I}var _u=I=>I%4==0&&(I%100!=0||I%400==0),bu=[0,31,60,91,121,152,182,213,244,274,305,335],jo=[0,31,59,90,120,151,181,212,243,273,304,334];function wu(I,N){I=-9007199254740992>I||9007199254740992<I?NaN:Number(I),N>>>=0,I=new Date(1e3*I),(T(),B)[N>>>2>>>0]=I.getSeconds(),(T(),B)[N+4>>>2>>>0]=I.getMinutes(),(T(),B)[N+8>>>2>>>0]=I.getHours(),(T(),B)[N+12>>>2>>>0]=I.getDate(),(T(),B)[N+16>>>2>>>0]=I.getMonth(),(T(),B)[N+20>>>2>>>0]=I.getFullYear()-1900,(T(),B)[N+24>>>2>>>0]=I.getDay();var O=(_u(I.getFullYear())?bu:jo)[I.getMonth()]+I.getDate()-1|0;(T(),B)[N+28>>>2>>>0]=O,(T(),B)[N+36>>>2>>>0]=-60*I.getTimezoneOffset(),O=new Date(I.getFullYear(),6,1).getTimezoneOffset();var z=new Date(I.getFullYear(),0,1).getTimezoneOffset();I=0|(O!=z&&I.getTimezoneOffset()==Math.min(z,O)),(T(),B)[N+32>>>2>>>0]=I}function nA(I){I>>>=0;var N=new Date((T(),B)[I+20>>>2>>>0]+1900,(T(),B)[I+16>>>2>>>0],(T(),B)[I+12>>>2>>>0],(T(),B)[I+8>>>2>>>0],(T(),B)[I+4>>>2>>>0],(T(),B)[I>>>2>>>0],0),O=(T(),B)[I+32>>>2>>>0],z=N.getTimezoneOffset(),se=new Date(N.getFullYear(),6,1).getTimezoneOffset(),ce=new Date(N.getFullYear(),0,1).getTimezoneOffset(),Se=Math.min(ce,se);return 0>O?(T(),B)[I+32>>>2>>>0]=+(se!=ce&&Se==z):0<O!=(Se==z)&&(se=Math.max(ce,se),N.setTime(N.getTime()+6e4*((0<O?Se:se)-z))),(T(),B)[I+24>>>2>>>0]=N.getDay(),O=(_u(N.getFullYear())?bu:jo)[N.getMonth()]+N.getDate()-1|0,(T(),B)[I+28>>>2>>>0]=O,(T(),B)[I>>>2>>>0]=N.getSeconds(),(T(),B)[I+4>>>2>>>0]=N.getMinutes(),(T(),B)[I+8>>>2>>>0]=N.getHours(),(T(),B)[I+12>>>2>>>0]=N.getDate(),(T(),B)[I+16>>>2>>>0]=N.getMonth(),(T(),B)[I+20>>>2>>>0]=N.getYear(),I=N.getTime(),BigInt(isNaN(I)?-1:I/1e3)}function rA(I,N,O,z,se,ce,Se){return i?F(16,1,I,N,O,z,se,ce,Se):-52}function iA(I,N,O,z,se,ce){if(i)return F(17,1,I,N,O,z,se,ce)}var Jl={},Ih=()=>performance.timeOrigin+performance.now();function sA(I,N){if(i)return F(18,1,I,N);if(Jl[I]&&(clearTimeout(Jl[I].id),delete Jl[I]),!N)return 0;var O=setTimeout(()=>{delete Jl[I],Gt(()=>Lh(I,performance.timeOrigin+performance.now()))},N);return Jl[I]={id:O,be:N},0}function iy(I,N,O,z){I>>>=0,N>>>=0,O>>>=0,z>>>=0;var se=new Date().getFullYear(),ce=new Date(se,0,1).getTimezoneOffset();se=new Date(se,6,1).getTimezoneOffset();var Se=Math.max(ce,se);(T(),W)[I>>>2>>>0]=60*Se,(T(),B)[N>>>2>>>0]=+(ce!=se),I=(N=Ue=>{var rt=Math.abs(Ue);return`UTC${0<=Ue?"-":"+"}${String(Math.floor(rt/60)).padStart(2,"0")}${String(rt%60).padStart(2,"0")}`})(ce),N=N(se),se<ce?(An(I,O,17),An(N,z,17)):(An(I,z,17),An(N,O,17))}var sy=()=>Date.now();function ay(I,N,O){return O>>>=0,0<=I&&3>=I?(I===0?I=Date.now():I=performance.timeOrigin+performance.now(),I=Math.round(1e6*I),(T(),$)[O>>>3>>>0]=BigInt(I),0):28}var Sh=[],Bh=(I,N)=>{Sh.length=0;for(var O;O=(T(),G)[I++>>>0];){var z=O!=105;N+=(z&=O!=112)&&N%8?4:0,Sh.push(O==112?(T(),W)[N>>>2>>>0]:O==106?(T(),$)[N>>>3>>>0]:O==105?(T(),B)[N>>>2>>>0]:(T(),Y)[N>>>3>>>0]),N+=z?8:4}return Sh};function oy(I,N,O){return I>>>=0,N=Bh(N>>>0,O>>>0),tf[I](...N)}function ly(I,N,O){return I>>>=0,N=Bh(N>>>0,O>>>0),tf[I](...N)}var cy=()=>{};function uy(I,N){return C(hn(I>>>0,N>>>0))}var Mh=()=>{throw Ge+=1,"unwind"};function dy(){return 4294901760}var hy=()=>navigator.hardwareConcurrency,Wa={},Xl=I=>{var N;return(N=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(I))?+N[1]:(N=/:(\d+):\d+(?:\)|$)/.exec(I))?2147483648|+N[1]:0},aA=I=>{for(var N of I)(I=Xl(N))&&(Wa[I]=N)};function fy(){var I=Error().stack.toString().split(`
|
|
@@ -15610,4 +15610,4 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
15610
15610
|
}`},zR=n=>{let e=n[1].dims,t=n[2].dims,r=n[0].dims,i=n[1].dataType,s=!(Le.areEqual(e,t)&&Le.areEqual(t,r)),a=e,o=Le.size(e);if(s){let c=Zd.calcShape(Zd.calcShape(e,t,!1),r,!1);if(!c)throw new Error("Can't perform where op on the given tensors");a=c,o=Le.size(a)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>FR(c,n,a,s,i),getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...Ct(r,e,t,a)]})}},Tz=n=>{n.compute(zR(n.inputs))}}),Rz,Jte=et(()=>{ute(),oI(),dte(),hte(),fte(),pte(),Ate(),vte(),bte(),wte(),Ete(),Cte(),Ite(),Ste(),Bte(),Mte(),Tte(),Rte(),Dte(),kte(),Nte(),Qte(),Pte(),Lte(),Fte(),JF(),zte(),Ute(),Ote(),$te(),Gte(),aI(),Hte(),tz(),Vte(),jte(),Wte(),ZF(),qte(),Vl(),lI(),Yte(),Rz=new Map([["Abs",[EL]],["Acos",[CL]],["Acosh",[IL]],["Add",[aF]],["ArgMax",[vL,Rw]],["ArgMin",[xL,Rw]],["Asin",[SL]],["Asinh",[BL]],["Atan",[ML]],["Atanh",[TL]],["Attention",[_L]],["AveragePool",[uz,cz]],["BatchNormalization",[bL]],["BiasAdd",[wL]],["BiasSplitGelu",[sF]],["Cast",[DL,RL]],["Ceil",[NL]],["Clip",[kL]],["Concat",[mF,gF]],["Conv",[Lw,Pw]],["ConvTranspose",[SF,IF]],["Cos",[QL]],["Cosh",[PL]],["CumSum",[BF,MF]],["DepthToSpace",[TF,RF]],["DequantizeLinear",[gz,yz]],["Div",[oF]],["Einsum",[DF,kF]],["Elu",[LL,op]],["Equal",[lF]],["Erf",[FL]],["Exp",[zL]],["Expand",[NF]],["FastGelu",[QF]],["Floor",[UL]],["FusedConv",[Lw,Pw]],["Gather",[LF,PF]],["GatherElements",[GF,$F]],["GatherBlockQuantized",[UF,OF]],["GatherND",[FF,zF]],["Gelu",[OL]],["Gemm",[VF,HF]],["GlobalAveragePool",[hz,dz]],["GlobalMaxPool",[mz,Az]],["Greater",[hF]],["GreaterOrEqual",[pF]],["GridSample",[jF,WF]],["GroupQueryAttention",[nz]],["HardSigmoid",[YL,qL]],["InstanceNormalization",[rz]],["LayerNormalization",[iz]],["LeakyRelu",[$L,op]],["Less",[fF]],["LessOrEqual",[AF]],["Log",[rF]],["MatMul",[sz]],["MatMulNBits",[az,oz]],["MaxPool",[fz,pz]],["Mul",[cF]],["MultiHeadAttention",[YF,qF]],["Neg",[HL]],["Not",[GL]],["Pad",[lz]],["Pow",[uF]],["QuickGelu",[iF,op]],["Range",[xz]],["Reciprocal",[VL]],["ReduceMin",[pL]],["ReduceMean",[cL]],["ReduceMax",[fL]],["ReduceSum",[mL]],["ReduceProd",[AL]],["ReduceL1",[uL]],["ReduceL2",[dL]],["ReduceLogSum",[yL]],["ReduceLogSumExp",[hL]],["ReduceSumSquare",[gL]],["Relu",[jL]],["Resize",[bz,wz]],["RotaryEmbedding",[ez]],["ScatterND",[_z,vz]],["Sigmoid",[WL]],["Sin",[JL]],["Sinh",[XL]],["Slice",[Cz,Iz]],["SkipLayerNormalization",[Ez]],["Split",[XF,KF]],["Sqrt",[KL]],["Softmax",[Sz,Bz]],["Sub",[dF]],["Tan",[ZL]],["Tanh",[eF]],["ThresholdedRelu",[nF,op]],["Tile",[Mz]],["Transpose",[XP,KP]],["Where",[Tz]]])}),Dz,Xte=et(()=>{xs(),No(),Wt(),Dz=class{constructor(n){this.backend=n,this.repo=new Map,this.attributesBound=!1}getArtifact(n){return this.repo.get(n)}setArtifact(n,e){this.repo.set(n,e)}run(n,e,t,r,i){Fa(n.programInfo.name);let s=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let o=[];for(let c of e)o.push({binding:o.length,resource:{buffer:c.buffer}});for(let c of t)o.push({binding:o.length,resource:{buffer:c.buffer}});i&&o.push({binding:o.length,resource:i});let l=s.createBindGroup({layout:n.computePipeline.getBindGroupLayout(0),entries:o,label:n.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:n.computePipeline,bindGroup:l,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}a.setPipeline(n.computePipeline),a.setBindGroup(0,l),a.dispatchWorkgroups(...r),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Zs(n.programInfo.name)}dispose(){}build(n,e){Fa(n.name);let t=this.backend.device,r=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&r.push(`enable ${c.extension};`)});let i=JP(e,this.backend.device.limits),s=n.getShaderSource(i),a=`${r.join(`
|
|
15611
15611
|
`)}
|
|
15612
15612
|
${i.additionalImplementations}
|
|
15613
|
-
${s}`,o=t.createShaderModule({code:a,label:n.name});un("verbose",()=>`[WebGPU] ${n.name} shader code: ${a}`);let l=t.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:n.name});return Zs(n.name),{programInfo:n,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(n){let e=typeof n=="number"?n:n.x,t=typeof n=="number"?1:n.y||1,r=typeof n=="number"?1:n.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&t<=i&&r<=i)return[e,t,r];let s=e*t*r,a=Math.ceil(Math.sqrt(s));if(a>i){if(a=Math.ceil(Math.cbrt(s)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),kz={};vh(kz,{WebGpuBackend:()=>Nz});var UR,OR,$R,Nz,Kte=et(()=>{xs(),Lt(),No(),VP(),lte(),Jte(),Xte(),UR=(n,e)=>{if(e.length!==n.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${n.length}.`);let t=[];for(let r=0;r<n.length;++r){let i=n[r].dataType;switch(e[r]){case"none":{t.push("");break}case"type":{t.push(`${i}`);break}case"rank":{let s=n[r].dims.length;t.push(`${i};${s}`);break}case"dims":{let s=n[r].dims.join(",");t.push(`${i};${s}`);break}default:throw new Error(`unsupported input dependency: ${e[r]}`)}}return t.join("|")},OR=(n,e,t)=>{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${UR(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},$R=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},Nz=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let n=this.kernelCustomData.get(this.currentKernelId);return n||(n={},this.kernelCustomData.set(this.currentKernelId,n)),n}async initialize(n,e){this.env=n;let t=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},i=s=>e.features.has(s)&&t.push(s)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await e.requestDevice(r),this.adapterInfo=new $R(e.info||await e.requestAdapterInfo()),this.gpuDataManager=qP(this),this.programManager=new Dz(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,nI(n.logLevel,!!n.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let n=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Fa(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(n.getMappedRange()),t=this.pendingQueries.get(n);for(let r=0;r<e.length/2;r++){let i=t[r],s=i.kernelId,a=this.kernels.get(s),o=a.kernelType,l=a.kernelName,c=i.programName,d=i.inputTensorViews,h=i.outputTensorViews,p=e[r*2],A=e[r*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=p);let y=Number(p-this.queryTimeBase),m=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(y)||!Number.isSafeInteger(m))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(x=>({dims:x.dims,dataType:po(x.dataType)})),outputsMetadata:h.map(x=>({dims:x.dims,dataType:po(x.dataType)})),kernelId:s,kernelType:o,kernelName:l,programName:c,startTime:y,endTime:m});else{let x="";d.forEach((_,b)=>{x+=`input[${b}]: [${_.dims}] | ${po(_.dataType)}, `});let g="";h.forEach((_,b)=>{g+=`output[${b}]: [${_.dims}] | ${po(_.dataType)}, `}),console.log(`[profiling] kernel "${s}|${o}|${l}|${c}" ${x}${g}start time: ${y} ns, execution time: ${m-y} ns`)}qg("GPU",`${c}::${p}::${A}`)}n.unmap(),this.pendingQueries.delete(n)}),Zs()}run(n,e,t,r,i,s){Fa(n.name);let a=[];for(let _=0;_<e.length;++_){let b=e[_].data;if(b===0)continue;let w=this.gpuDataManager.get(b);if(!w)throw new Error(`no GPU data for input: ${b}`);a.push(w)}let{outputs:o,dispatchGroup:l,programUniforms:c}=n.getRunData(e),d=t.length===0?o.map((_,b)=>b):t;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let h=[],p=[];for(let _=0;_<o.length;++_){if(!Number.isInteger(d[_])||d[_]<-3||d[_]>=s)throw new Error(`Invalid output index: ${d[_]}`);if(d[_]===-3)continue;let b=d[_]===-1,w=d[_]===-2,C=b||w?i(o[_].dataType,o[_].dims):r(d[_],o[_].dataType,o[_].dims);if(h.push(C),C.data===0)continue;let S=this.gpuDataManager.get(C.data);if(!S)throw new Error(`no GPU data for output: ${C.data}`);if(b&&this.temporaryData.push(S),w){let M=this.kernelPersistentData.get(this.currentKernelId);M||(M=[],this.kernelPersistentData.set(this.currentKernelId,M)),M.push(S)}p.push(S)}if(a.length!==e.length||p.length!==h.length){if(p.length===0)return Zs(n.name),h;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let A;if(c){let _=0,b=[];c.forEach(M=>{let T=typeof M.data=="number"?[M.data]:M.data;if(T.length===0)return;let R=M.type===10?2:4,k,G;M.type===10?(G=T.length>4?16:T.length>2?8:T.length*R,k=T.length>4?16:R*T.length):(G=T.length<=2?T.length*R:16,k=16),_=Math.ceil(_/G)*G,b.push(_);let P=M.type===10?8:4;_+=T.length>4?Math.ceil(T.length/P)*k:T.length*R});let w=16;_=Math.ceil(_/w)*w;let C=new ArrayBuffer(_);c.forEach((M,T)=>{let R=b[T],k=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(C,R,k.length).set(k);else if(M.type===12)new Uint32Array(C,R,k.length).set(k);else if(M.type===10)new Uint16Array(C,R,k.length).set(k);else if(M.type===1)new Float32Array(C,R,k.length).set(k);else throw new Error(`Unsupported uniform type: ${po(M.type)}`)});let S=this.gpuDataManager.create(_,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(S.buffer,0,C,0,_),this.gpuDataManager.release(S.id),A={offset:0,size:_,buffer:S.buffer}}let y=this.programManager.normalizeDispatchGroupSize(l),m=y[1]===1&&y[2]===1,x=OR(n,e,m),g=this.programManager.getArtifact(x);if(g||(g=this.programManager.build(n,y),this.programManager.setArtifact(x,g),un("info",()=>`[artifact] key: ${x}, programName: ${n.name}`)),c&&g.uniformVariablesInfo){if(c.length!==g.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${g.uniformVariablesInfo.length}, got ${c.length} in program "${g.programInfo.name}".`);for(let _=0;_<c.length;_++){let b=c[_],w=b.type,C=typeof b.data=="number"?1:b.data.length,[S,M]=g.uniformVariablesInfo[_];if(w!==S||C!==M)throw new Error(`Uniform variable ${_} mismatch: expect type ${S} with size ${M}, got type ${w} with size ${C} in program "${g.programInfo.name}".`)}}if(un("info",()=>`[ProgramManager] run "${n.name}" (key=${x}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let _={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(_),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(_)}return this.programManager.run(g,a,p,y,A),Zs(n.name),h}upload(n,e){this.gpuDataManager.upload(n,e)}memcpy(n,e){this.gpuDataManager.memcpy(n,e)}async download(n,e){await this.gpuDataManager.download(n,e)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,e,t,r){let i=Rz.get(n);if(!i)throw new Error(`kernel not implemented: ${n}`);let s={kernelType:n,kernelName:r,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(e,s)}releaseKernel(n){let e=this.kernelPersistentData.get(n);if(e){for(let t of e)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,e,t){let r=this.kernels.get(n);if(!r)throw new Error(`kernel not created: ${n}`);let i=r.kernelType,s=r.kernelName,a=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${s}" is not allowed to be called recursively`);this.currentKernelId=n,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),un("info",()=>`[WebGPU] Start to run kernel "[${i}] ${s}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(e,o[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${s}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${s}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,e,t,r){let i=this.sessionExternalDataMapping.get(n);i||(i=new Map,this.sessionExternalDataMapping.set(n,i));let s=i.get(e),a=this.gpuDataManager.registerExternalBuffer(t,r,s);return i.set(e,[a,t]),a}unregisterBuffers(n){let e=this.sessionExternalDataMapping.get(n);e&&(e.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let e=this.gpuDataManager.get(n);if(!e)throw new Error(`no GPU data for buffer: ${n}`);return e.buffer}createDownloader(n,e,t){return async()=>{let r=await Bw(this,n,e);return rI(r.buffer,t)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){un("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){un("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){un("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),t=n.length;this.pendingKernels=[];for(let r=0;r<t;r++){let i=this.getComputePassEncoder(),s=n[r];this.writeTimestamp(this.pendingDispatchNumber*2),i.setPipeline(s.computePipeline),i.setBindGroup(0,s.bindGroup),i.dispatchWorkgroups(...s.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(e[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),Qz={};vh(Qz,{init:()=>Pz});var rg,GR,Pz,Zte=et(()=>{Lt(),No(),jt(),ote(),rg=class Lz{constructor(e,t,r,i){this.module=e,this.dataType=t,this.data=r,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Le.size(e)!==Le.size(this.dims))throw new Error("Invalid new shape");return new Lz(this.module,this.dataType,this.data,e)}},GR=class{constructor(n,e,t){this.module=n,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let r=n.PTR_SIZE,i=t/n.PTR_SIZE,s=r===4?"i32":"i64";this.opKernelContext=Number(n.getValue(r*i++,s));let a=Number(n.getValue(r*i++,s));this.outputCount=Number(n.getValue(r*i++,s)),this.customDataOffset=Number(n.getValue(r*i++,"*")),this.customDataSize=Number(n.getValue(r*i++,s));let o=[];for(let l=0;l<a;l++){let c=Number(n.getValue(r*i++,s)),d=Number(n.getValue(r*i++,"*")),h=Number(n.getValue(r*i++,s)),p=[];for(let A=0;A<h;A++)p.push(Number(n.getValue(r*i++,s)));o.push(new rg(n,c,d,p))}this.inputs=o}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(n,e){let t=e?.inputs?.map(a=>typeof a=="number"?this.inputs[a]:a)??this.inputs,r=e?.outputs??[],i=(a,o,l)=>new rg(this.module,o,this.output(a,l),l),s=(a,o)=>{let l=Qc(a,o);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new rg(this.module,a,c,o)};return this.backend.run(n,t,r,i,s,this.outputCount)}output(n,e){let t=this.module.stackSave();try{let r=this.module.PTR_SIZE,i=r===4?"i32":"i64",s=this.module.stackAlloc((1+e.length)*r);this.module.setValue(s,e.length,i);for(let a=0;a<e.length;a++)this.module.setValue(s+r*(a+1),e[a],i);return this.module._JsepOutput(this.opKernelContext,n,s)}catch(r){throw new Error(`Failed to generate kernel's output[${n}] with dims [${e}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${r}`)}finally{this.module.stackRestore(t)}}},Pz=async(n,e,t,r)=>{let i=e.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(n==="webgpu"){let s=(Kte(),Lp(kz)).WebGpuBackend,a=new s;await a.initialize(t,r),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,l,c,d=!1)=>{if(d)un("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(l)}, size=${Number(c)}`),a.memcpy(Number(o),Number(l));else{un("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let h=e.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(c));a.upload(Number(l),h)}},async(o,l,c)=>{un("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${l}, size=${c}`),await a.download(Number(o),()=>e.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(o,l,c)=>a.createKernel(o,Number(l),c,e.UTF8ToString(e._JsepGetNodeName(Number(l)))),o=>a.releaseKernel(o),(o,l,c,d)=>{un("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${o}, contextDataOffset=${l}`);let h=new GR(e,a,Number(l));return a.computeKernel(Number(o),h,d)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let s=new WP(t);i("webnn",[s,()=>s.reserveTensorId(),a=>s.releaseTensorId(a),async(a,o,l,c,d)=>s.ensureTensor(a,o,l,c,d),(a,o)=>{s.uploadTensor(a,o)},async(a,o)=>s.downloadTensor(a,o),(a,o)=>s.registerMLContext(a,o),!!t.trace])}}}),HR,pI,AI,Il,VR,H_,t0,mI,gI,V_,yI,xI,vI,Fz=et(()=>{xs(),ite(),ste(),Lt(),cu(),KC(),OP(),HR=(n,e)=>{kn()._OrtInit(n,e)!==0&&wn("Can't initialize onnxruntime.")},pI=async n=>{HR(n.wasm.numThreads,Jg(n.logLevel))},AI=async(n,e)=>{kn().asyncInit?.();let t=n.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(t){if(typeof t.limits!="object"||typeof t.features!="object"||typeof t.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=n.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let i=n.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:i}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let r=(Zte(),Lp(Qz)).init;e==="webgpu"&&await r("webgpu",kn(),n,t),e==="webnn"&&await r("webnn",kn(),n)}},Il=new Map,VR=n=>{let e=kn(),t=e.stackSave();try{let r=e.PTR_SIZE,i=e.stackAlloc(2*r);e._OrtGetInputOutputCount(n,i,i+r)!==0&&wn("Can't get session input/output count.");let s=r===4?"i32":"i64";return[Number(e.getValue(i,s)),Number(e.getValue(i+r,s))]}finally{e.stackRestore(t)}},H_=(n,e)=>{let t=kn(),r=t.stackSave(),i=0;try{let s=t.PTR_SIZE,a=t.stackAlloc(2*s);t._OrtGetInputOutputMetadata(n,e,a,a+s)!==0&&wn("Can't get session input/output metadata.");let o=Number(t.getValue(a,"*"));i=Number(t.getValue(a+s,"*"));let l=t.HEAP32[i/4];if(l===0)return[o,0];let c=t.HEAPU32[i/4+1],d=[];for(let h=0;h<c;h++){let p=Number(t.getValue(i+8+h*s,"*"));d.push(p!==0?t.UTF8ToString(p):Number(t.getValue(i+8+(h+c)*s,"*")))}return[o,l,d]}finally{t.stackRestore(r),i!==0&&t._OrtFree(i)}},t0=n=>{let e=kn(),t=e._malloc(n.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,t),[t,n.byteLength]},mI=async(n,e)=>{let t,r,i=kn();Array.isArray(n)?[t,r]=n:n.buffer===i.HEAPU8.buffer?[t,r]=[n.byteOffset,n.byteLength]:[t,r]=t0(n);let s=0,a=0,o=0,l=[],c=[],d=[];try{if([a,l]=await UP(e),e?.externalData&&i.mountExternalData){let w=[];for(let C of e.externalData){let S=typeof C=="string"?C:C.path;w.push(tI(typeof C=="string"?C:C.data).then(M=>{i.mountExternalData(S,M)}))}await Promise.all(w)}for(let w of e?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof w!="string"){let C=w,S=C?.context,M=C?.gpuDevice,T=C?.deviceType,R=C?.powerPreference;S?i.currentContext=S:M?i.currentContext=await i.webnnCreateMLContext(M):i.currentContext=await i.webnnCreateMLContext({deviceType:T,powerPreference:R})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(t,r,a),i.webgpuOnCreateSession?.(s),s===0&&wn("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=VR(s),A=!!e?.enableGraphCapture,y=[],m=[],x=[],g=[],_=[];for(let w=0;w<h;w++){let[C,S,M]=H_(s,w);C===0&&wn("Can't get an input name."),c.push(C);let T=i.UTF8ToString(C);y.push(T),x.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M})}for(let w=0;w<p;w++){let[C,S,M]=H_(s,w+h);C===0&&wn("Can't get an output name."),d.push(C);let T=i.UTF8ToString(C);m.push(T),g.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M});{if(A&&e?.preferredOutputLocation===void 0){_.push("gpu-buffer");continue}let R=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[T]??"cpu",k=i.webnnIsGraphOutput;if(R==="cpu"&&k&&k(s,T)){_.push("ml-tensor-cpu-output");continue}if(R!=="cpu"&&R!=="cpu-pinned"&&R!=="gpu-buffer"&&R!=="ml-tensor")throw new Error(`Not supported preferred output location: ${R}.`);if(A&&R!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${R}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(R)}}let b=null;return _.some(w=>w==="gpu-buffer"||w==="ml-tensor"||w==="ml-tensor-cpu-output")&&(o=i._OrtCreateBinding(s),o===0&&wn("Can't create IO binding."),b={handle:o,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(w=>w==="ml-tensor-cpu-output"?"ml-tensor":w).map(w=>Iw(w))}),Il.set(s,[s,c,d,b,A,!1]),[s,y,m,x,g]}catch(h){throw c.forEach(p=>i._OrtFree(p)),d.forEach(p=>i._OrtFree(p)),o!==0&&i._OrtReleaseBinding(o)!==0&&wn("Can't release IO binding."),s!==0&&i._OrtReleaseSession(s)!==0&&wn("Can't release session."),h}finally{i._free(t),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&wn("Can't release session options."),l.forEach(h=>i._free(h)),i.unmountExternalData?.()}},gI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error(`cannot release session. invalid session id: ${n}`);let[r,i,s,a,o]=t;a&&(o&&e._OrtClearBoundOutputs(a.handle)!==0&&wn("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&wn("Can't release IO binding.")),e.jsepOnReleaseSession?.(n),e.webnnOnReleaseSession?.(n),e.webgpuOnReleaseSession?.(n),i.forEach(l=>e._OrtFree(l)),s.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(r)!==0&&wn("Can't release session."),Il.delete(n)},V_=async(n,e,t,r,i,s,a=!1)=>{if(!n){e.push(0);return}let o=kn(),l=o.PTR_SIZE,c=n[0],d=n[1],h=n[3],p=h,A,y;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let g=n[2].gpuBuffer;y=Qc(Nc(c),d);{let _=o.jsepRegisterBuffer;if(!_)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=_(r,s,g,y)}}else if(h==="ml-tensor"){let g=n[2].mlTensor;y=Qc(Nc(c),d);let _=o.webnnRegisterMLTensor;if(!_)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=_(r,g,Nc(c),d)}else{let g=n[2];if(Array.isArray(g)){y=l*g.length,A=o._malloc(y),t.push(A);for(let _=0;_<g.length;_++){if(typeof g[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);o.setValue(A+_*l,Gs(g[_],t),"*")}}else{let _=o.webnnIsGraphInput,b=o.webnnIsGraphOutput;if(c!=="string"&&_&&b){let w=o.UTF8ToString(i);if(_(r,w)||b(r,w)){let C=Nc(c);y=Qc(C,d),p="ml-tensor";let S=o.webnnCreateTemporaryTensor,M=o.webnnUploadTensor;if(!S||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let T=await S(r,C,d);M(T,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),A=T}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}}let m=o.stackSave(),x=o.stackAlloc(4*d.length);try{d.forEach((_,b)=>o.setValue(x+b*l,_,l===4?"i32":"i64"));let g=o._OrtCreateTensor(Nc(c),A,y,x,d.length,Iw(p));g===0&&wn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(g)}finally{o.stackRestore(m)}},yI=async(n,e,t,r,i,s)=>{let a=kn(),o=a.PTR_SIZE,l=Il.get(n);if(!l)throw new Error(`cannot run inference. invalid session id: ${n}`);let c=l[0],d=l[1],h=l[2],p=l[3],A=l[4],y=l[5],m=e.length,x=r.length,g=0,_=[],b=[],w=[],C=[],S=[],M=a.stackSave(),T=a.stackAlloc(m*o),R=a.stackAlloc(m*o),k=a.stackAlloc(x*o),G=a.stackAlloc(x*o);try{[g,_]=zP(s),jc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)await V_(t[W],b,C,n,d[e[W]],e[W],A);for(let W=0;W<x;W++)await V_(i[W],w,C,n,h[r[W]],m+r[W],A);Wc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)a.setValue(T+W*o,b[W],"*"),a.setValue(R+W*o,d[e[W]],"*");for(let W=0;W<x;W++)a.setValue(k+W*o,w[W],"*"),a.setValue(G+W*o,h[r[W]],"*");if(p&&!y){let{handle:W,outputPreferredLocations:K,outputPreferredLocationsEncoded:Y}=p;if(d.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${d.length}).`);jc("wasm bindInputsOutputs");for(let $=0;$<m;$++){let J=e[$];await a._OrtBindInput(W,d[J],b[$])!==0&&wn(`Can't bind input[${$}] for session=${n}.`)}for(let $=0;$<x;$++){let J=r[$];i[$]?.[3]?(S.push(w[$]),a._OrtBindOutput(W,h[J],w[$],0)!==0&&wn(`Can't bind pre-allocated output[${$}] for session=${n}.`)):a._OrtBindOutput(W,h[J],0,Y[J])!==0&&wn(`Can't bind output[${$}] to ${K[$]} for session=${n}.`)}Wc("wasm bindInputsOutputs"),Il.set(n,[c,d,h,p,A,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let P;p?P=await a._OrtRunWithBinding(c,p.handle,x,k,g):P=await a._OrtRun(c,R,T,m,G,x,k,g),P!==0&&wn("failed to call OrtRun().");let V=[],B=[];jc("wasm ProcessOutputTensor");for(let W=0;W<x;W++){let K=Number(a.getValue(k+W*o,"*"));if(K===w[W]||S.includes(w[W])){V.push(i[W]),K!==w[W]&&a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.");continue}let Y=a.stackSave(),$=a.stackAlloc(4*o),J=!1,re,L=0;try{a._OrtGetTensorData(K,$,$+o,$+2*o,$+3*o)!==0&&wn(`Can't access output tensor data on index ${W}.`);let H=o===4?"i32":"i64",oe=Number(a.getValue($,H));L=a.getValue($+o,"*");let Ae=a.getValue($+o*2,"*"),ye=Number(a.getValue($+o*3,H)),he=[];for(let Re=0;Re<ye;Re++)he.push(Number(a.getValue(Ae+Re*o,H)));a._OrtFree(Ae)!==0&&wn("Can't free memory for tensor dims.");let fe=he.reduce((Re,ve)=>Re*ve,1);re=po(oe);let Ee=p?.outputPreferredLocations[r[W]];if(re==="string"){if(Ee==="gpu-buffer"||Ee==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Re=[];for(let ve=0;ve<fe;ve++){let Ne=a.getValue(L+ve*o,"*"),ct=a.getValue(L+(ve+1)*o,"*"),Ge=ve===fe-1?void 0:ct-Ne;Re.push(a.UTF8ToString(Ne,Ge))}V.push([re,he,Re,"cpu"])}else if(Ee==="gpu-buffer"&&fe>0){let Re=a.jsepGetBuffer;if(!Re)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ve=Re(L),Ne=Qc(oe,fe);if(Ne===void 0||!ZC(re))throw new Error(`Unsupported data type: ${re}`);J=!0,V.push([re,he,{gpuBuffer:ve,download:a.jsepCreateDownloader(ve,Ne,re),dispose:()=>{a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.")}},"gpu-buffer"])}else if(Ee==="ml-tensor"&&fe>0){let Re=a.webnnEnsureTensor,ve=a.webnnIsGraphInputOutputTypeSupported;if(!Re||!ve)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Qc(oe,fe)===void 0||!eI(re))throw new Error(`Unsupported data type: ${re}`);if(!ve(n,re,!1))throw new Error(`preferredLocation "ml-tensor" for ${re} output is not supported by current WebNN Context.`);let Ne=await Re(n,L,oe,he,!1);J=!0,V.push([re,he,{mlTensor:Ne,download:a.webnnCreateMLTensorDownloader(L,re),dispose:()=>{a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K)}},"ml-tensor"])}else if(Ee==="ml-tensor-cpu-output"&&fe>0){let Re=a.webnnCreateMLTensorDownloader(L,re)(),ve=V.length;J=!0,B.push((async()=>{let Ne=[ve,await Re];return a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K),Ne})()),V.push([re,he,[],"cpu"])}else{let Re=Z0(re),ve=new Re(fe);new Uint8Array(ve.buffer,ve.byteOffset,ve.byteLength).set(a.HEAPU8.subarray(L,L+ve.byteLength)),V.push([re,he,ve,"cpu"])}}finally{a.stackRestore(Y),re==="string"&&L&&a._free(L),J||a._OrtReleaseTensor(K)}}p&&!A&&(a._OrtClearBoundOutputs(p.handle)!==0&&wn("Can't clear bound outputs."),Il.set(n,[c,d,h,p,A,!1]));for(let[W,K]of await Promise.all(B))V[W][2]=K;return Wc("wasm ProcessOutputTensor"),V}finally{a.webnnOnRunEnd?.(c),a.stackRestore(M),b.forEach(P=>a._OrtReleaseTensor(P)),w.forEach(P=>a._OrtReleaseTensor(P)),C.forEach(P=>a._free(P)),g!==0&&a._OrtReleaseRunOptions(g),_.forEach(P=>a._free(P))}},xI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error("invalid session id");let r=t[0],i=e._OrtEndProfiling(r);i===0&&wn("Can't get an profile file name."),e._OrtFree(i)},vI=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),Sl,ts,Ed,qf,Yf,ig,j_,sg,Cc,Ic,jR,zz,Uz,Oz,$z,Gz,Hz,Vz,jz=et(()=>{xs(),Fz(),cu(),JC(),Sl=()=>!!Dn.wasm.proxy&&typeof document<"u",Ed=!1,qf=!1,Yf=!1,sg=new Map,Cc=(n,e)=>{let t=sg.get(n);t?t.push(e):sg.set(n,[e])},Ic=()=>{if(Ed||!qf||Yf||!ts)throw new Error("worker not ready")},jR=n=>{switch(n.data.type){case"init-wasm":Ed=!1,n.data.err?(Yf=!0,j_[1](n.data.err)):(qf=!0,j_[0]()),ig&&(URL.revokeObjectURL(ig),ig=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=sg.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},zz=async()=>{if(!qf){if(Ed)throw new Error("multiple calls to 'initWasm()' detected.");if(Yf)throw new Error("previous call to 'initWasm()' failed.");if(Ed=!0,Sl())return new Promise((n,e)=>{ts?.terminate(),LP().then(([t,r])=>{try{ts=r,ts.onerror=s=>e(s),ts.onmessage=jR,j_=[n,e];let i={type:"init-wasm",in:Dn};!i.in.wasm.wasmPaths&&(t||Cw)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href}),ts.postMessage(i),ig=t}catch(i){e(i)}},e)});try{await XC(Dn.wasm),await pI(Dn),qf=!0}catch(n){throw Yf=!0,n}finally{Ed=!1}}},Uz=async n=>{if(Sl())return Ic(),new Promise((e,t)=>{Cc("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Dn}};ts.postMessage(r)});await AI(Dn,n)},Oz=async n=>Sl()?(Ic(),new Promise((e,t)=>{Cc("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};ts.postMessage(r,[n.buffer])})):t0(n),$z=async(n,e)=>{if(Sl()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ic(),new Promise((t,r)=>{Cc("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},s=[];n instanceof Uint8Array&&s.push(n.buffer),ts.postMessage(i,s)})}else return mI(n,e)},Gz=async n=>{if(Sl())return Ic(),new Promise((e,t)=>{Cc("release",[e,t]);let r={type:"release",in:n};ts.postMessage(r)});gI(n)},Hz=async(n,e,t,r,i,s)=>{if(Sl()){if(t.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ic(),new Promise((a,o)=>{Cc("run",[a,o]);let l=t,c={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:s}};ts.postMessage(c,vI(l))})}else return yI(n,e,t,r,i,s)},Vz=async n=>{if(Sl())return Ic(),new Promise((e,t)=>{Cc("end-profiling",[e,t]);let r={type:"end-profiling",in:n};ts.postMessage(r)});xI(n)}}),W_,WR,Wz,ene=et(()=>{xs(),jz(),Lt(),YC(),OP(),W_=(n,e)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[n.type,n.dims,{mlTensor:n.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${n.location} for ${e()}`)}},WR=n=>{switch(n[3]){case"cpu":return new ti(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!ZC(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:r,dispose:i}=n[2];return ti.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}case"ml-tensor":{let e=n[0];if(!eI(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:r,dispose:i}=n[2];return ti.fromMLTensor(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},Wz=class{async fetchModelAndCopyToWasmMemory(n){return Oz(await tI(n))}async loadModel(n,e){Fa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await $z(t,e),Zs()}async dispose(){return Gz(this.sessionId)}async run(n,e,t){Fa();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],A=h[1],y=this.inputNames.indexOf(p);if(y===-1)throw new Error(`invalid input '${p}'`);r.push(A),i.push(y)});let s=[],a=[];Object.entries(e).forEach(h=>{let p=h[0],A=h[1],y=this.outputNames.indexOf(p);if(y===-1)throw new Error(`invalid output '${p}'`);s.push(A),a.push(y)});let o=r.map((h,p)=>W_(h,()=>`input "${this.inputNames[i[p]]}"`)),l=s.map((h,p)=>h?W_(h,()=>`output "${this.outputNames[a[p]]}"`):null),c=await Hz(this.sessionId,i,o,a,l,t),d={};for(let h=0;h<c.length;h++)d[this.outputNames[a[h]]]=s[h]??WR(c[h]);return Zs(),d}startProfiling(){}endProfiling(){Vz(this.sessionId)}}}),qz={};vh(qz,{OnnxruntimeWebAssemblyBackend:()=>Uw,initializeFlags:()=>zw,wasmBackend:()=>Yz});var zw,Uw,Yz,tne=et(()=>{xs(),jz(),ene(),zw=()=>{(typeof Dn.wasm.initTimeout!="number"||Dn.wasm.initTimeout<0)&&(Dn.wasm.initTimeout=0);let n=Dn.wasm.simd;if(typeof n!="boolean"&&n!==void 0&&n!=="fixed"&&n!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${n}". Reset it to \`false\` and ignore SIMD feature checking.`),Dn.wasm.simd=!1),typeof Dn.wasm.proxy!="boolean"&&(Dn.wasm.proxy=!1),typeof Dn.wasm.trace!="boolean"&&(Dn.wasm.trace=!1),typeof Dn.wasm.numThreads!="number"||!Number.isInteger(Dn.wasm.numThreads)||Dn.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Dn.wasm.numThreads=1;else{let e=typeof navigator>"u"?Uee("node:os").cpus().length:navigator.hardwareConcurrency;Dn.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Uw=class{async init(n){zw(),await zz(),await Uz(n)}async createInferenceSessionHandler(n,e){let t=new Wz;return await t.loadModel(n,e),t}},Yz=new Uw});xs();xs();xs();var nne="1.24.3";{let n=(tne(),Lp(qz)).wasmBackend;Bd("webgpu",n,5),Bd("webnn",n,5),Bd("cpu",n,10),Bd("wasm",n,10)}Object.defineProperty(Dn.versions,"web",{value:nne,enumerable:!0});class rne{constructor(e,t={}){this.config=e,this.options=t,this.policyModule=null,this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null,this.context=null,this.policyJointNames=(e.policy_joint_names??[]).slice(),this.numActions=this.policyJointNames.length,this.lastActions=new Float32Array(this.numActions),this.defaultJointPos=this.normalizeArray(e.default_joint_pos??[],this.numActions,0),this.encoderBias=this.normalizeArray(e.encoder_bias??[],this.numActions,0)}async init(e){this.context=e,this.policyModule=await this.buildPolicyModule(e),this.buildObservationGroups()}reset(e){this.lastActions.fill(0),this.policyModule?.reset();for(const t of Object.values(this.obsGroups))for(const r of t)r.reset&&r.reset(e);if(e){for(const[t,r]of Object.entries(this.historyConfig))if(r.steps>1){const i=this.buildFrame(this.obsGroups[t]??[],e),s=this.historyBuffers[t];for(let a=0;a<r.steps;a++)s.set(i,a*i.length)}}}update(e){this.policyModule?.update();for(const t of Object.values(this.obsGroups))for(const r of t)r.update&&r.update(e)}collectObservationsByKey(e){this.update(e);const t={};for(const[r,i]of Object.entries(this.obsGroups)){const s=this.historyConfig[r];if(s&&s.steps>1){const a=this.buildFrame(i,e),o=this.historyBuffers[r];for(let l=o.length-1;l>=a.length;l--)o[l]=o[l-a.length];o.set(a,0),t[r]=new Float32Array(o)}else t[r]=this.buildFrame(i,e)}return t}collectObservations(e){const t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];const r=Object.keys(t)[0];return r?t[r]:new Float32Array(0)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];const e=Object.keys(this.obsSizes)[0];return e?this.obsSizes[e]:0}getObservationLayout(){if(this.defaultObsKey&&this.obsLayouts[this.defaultObsKey])return this.obsLayouts[this.defaultObsKey].map(t=>({...t}));const e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(t=>({...t})):[]}getPolicyModuleContext(){return this.policyModule?.getContext()??{}}getPolicyModule(){return this.policyModule}getContext(){return this.context}getPolicyJointNames(){return this.policyJointNames.slice()}getNumActions(){return this.numActions}getDefaultJointPos(){return new Float32Array(this.defaultJointPos)}getEncoderBias(){return new Float32Array(this.encoderBias)}getLastActions(){return new Float32Array(this.lastActions)}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){const t=this.options.policyModules??{},r=this.config.policy_module,i=r?t[r]:t.default;if(r&&!i)throw new Error(`Unknown policy module: ${r}`);if(!i)return null;const s=new i(this.config);return await s.init(e),s}buildObservationGroups(){const e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;for(const[r,i]of Object.entries(t)){if(Array.isArray(i)){const s=i.map(a=>{const o=e[a.name];if(!o)throw new Error(`Unknown observation type: ${a.name}`);return new o(this,a)});this.registerGroup(r,s,i);continue}if(i&&typeof i=="object"){const s=i;if(Array.isArray(s.components)){const a=s.components.map(c=>{const d=e[c.name];if(!d)throw new Error(`Unknown observation type: ${c.name}`);const h={...c,history_steps:1};return new d(this,h)}),o=Math.max(1,Math.floor(s.history_steps??1)),l=!!s.interleaved;this.registerGroup(r,a,s.components,{steps:o,interleaved:l})}}}this.obsGroups.policy?this.defaultObsKey="policy":this.obsGroups.observation?this.defaultObsKey="observation":this.obsGroups.obs_history?this.defaultObsKey="obs_history":this.defaultObsKey=Object.keys(this.obsGroups)[0]??null}registerGroup(e,t,r,i){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((a,o)=>({name:r[o]?.name??`obs_${o}`,size:a.size}));const s=this.obsLayouts[e].reduce((a,o)=>a+o.size,0);i&&i.steps>1?(this.historyConfig[e]=i,this.historyBuffers[e]=new Float32Array(s*i.steps),this.obsSizes[e]=s*i.steps):this.obsSizes[e]=s}buildFrame(e,t){const r=e.reduce((a,o)=>a+o.size,0),i=new Float32Array(r);let s=0;for(const a of e){const o=a.compute(t),l=o instanceof Float32Array?o:Float32Array.from(o);if(l.length!==a.size)throw new Error(`Observation size mismatch: expected ${a.size}, got ${l.length}`);i.set(l,s),s+=l.length}return i}normalizeArray(e,t,r){const i=new Float32Array(t);for(let s=0;s<t;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}}Dn.wasm.proxy=!1;Dn.wasm.numThreads=1;class ine{constructor(e){if(!e?.path)throw new Error("OnnxModule requires a path.");this.config=e,this.session=null;const t=e.meta?.in_keys??["policy"],r=e.meta?.out_keys??["action"];this.configuredInKeys=t.map(i=>Array.isArray(i)?i.join(","):i),this.inKeys=[...this.configuredInKeys],this.outKeys=r.map(i=>Array.isArray(i)?i.join(","):i),this.isRecurrent=this.inKeys.includes("adapt_hx")}async init(){const e=await fetch(this.config.path);if(!e.ok)throw new Error(`Failed to fetch ONNX model: ${e.status}`);const t=await e.arrayBuffer();this.session=await qC.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"}),this.inferInputKeys(),this.isRecurrent=this.inKeys.includes("adapt_hx")}initInput(){const e={};return this.isRecurrent&&(e.is_init=new ti("bool",[!0],[1]),e.adapt_hx=new ti("float32",new Float32Array(128),[1,128])),this.inKeys.includes("time_step")&&(e.time_step=new ti("float32",new Float32Array([0]),[1,1])),e}async runInference(e){if(!this.session)throw new Error("OnnxModule not initialized.");const t={};for(let a=0;a<this.inKeys.length;a++){const o=this.inKeys[a],l=this.session.inputNames[a];if(!l||!e[o])throw new Error(`Missing ONNX input for key: ${o}`);t[l]=e[o]}const r=await this.session.run(t),i={};for(let a=0;a<this.outKeys.length;a++){const o=this.outKeys[a],l=this.session.outputNames[a];l&&r[l]&&(i[o]=r[l])}const s={};return this.isRecurrent&&i["next,adapt_hx"]&&(s.is_init=new ti("bool",[!1],[1]),s.adapt_hx=i["next,adapt_hx"]),[i,s]}inferInputKeys(){if(!this.session)return;const e=this.session.inputNames;if(e.length<=1){this.inKeys=[...this.configuredInKeys];return}if(this.configuredInKeys.length===e.length){this.inKeys=[...this.configuredInKeys];return}this.inKeys=e.map(t=>this.configuredInKeys.includes(t)?t:t==="obs"&&this.configuredInKeys.includes("policy")?"policy":t)}}class sne{constructor(e,t,r,i){this.mujoco=e,this.mjModel=t,this.mjData=r;const s=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(const a of i){const o=s.indexOf(a);if(o<0)throw new Error(`Joint "${a}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[o]),this.qvelAdr.push(t.jnt_dofadr[o]),this.jointIndices.push(o)}this.numActions=i.length,this.ctrlAdr=this.buildCtrlAdr()}build(){const e=this.mjData.qpos,t=this.mjData.qvel,r=new Float32Array(this.numActions),i=new Float32Array(this.numActions);for(let c=0;c<this.numActions;c++)r[c]=e[this.qposAdr[c]],i[c]=t[this.qvelAdr[c]];const s=new Float32Array([e[0],e[1],e[2]]),a=new Float32Array([e[3],e[4],e[5],e[6]]),o=new Float32Array([t[0],t[1],t[2]]),l=new Float32Array([t[3],t[4],t[5]]);return{jointPos:r,jointVel:i,rootPos:s,rootQuat:a,rootLinVel:o,rootAngVel:l}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}getControlMappingFor(e,t){if(!this.ctrlAdr)return null;const r=e.map(c=>new RegExp(`^(?:${c})$`)),i=c=>r.some(d=>d.test(c)),s=[],a=[],o=[],l=[];for(let c=0;c<t.length;c++)i(t[c])&&(s.push(this.ctrlAdr[c]),a.push(this.qposAdr[c]),o.push(this.qvelAdr[c]),l.push(c));return s.length===0?null:{ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l}}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;const e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let i=0;i<this.mjModel.nu;i++){const s=this.mjModel.actuator_trntype[i];e===void 0||s===e?t.push(this.mjModel.actuator_trnid[2*i]):t.push(-1)}const r=[];for(const i of this.jointIndices){const s=t.findIndex(a=>a===i);if(s<0)return null;r.push(s)}return r}getJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;let l=r.decode(t.subarray(a,o));!l&&s===0&&(l="floating_base_joint"),i.push(l)}return i}}class Jz{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class ane{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName="default",this.currentDone=!0}reset(e){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName="default"}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}}class one extends Jz{constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.tracking=new ane(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class lne{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName="default",this.currentDone=!0}reset(e){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName="default"}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}}class cne extends Jz{constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.locomotion=new lne(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class une{constructor(e,t){this.terms=[];for(const r of e){const i=t[r.name];if(!i){console.warn(`[EventManager] Unknown event type: ${r.name}`);continue}this.terms.push(new i(r))}}onReset(e){for(const t of this.terms)t.onReset(e)}get size(){return this.terms.length}}class Xz{constructor(e){this.config=e}}const dne={};class Kz extends Xz{constructor(e){super(e),this.poseRange=e.params?.pose_range??{}}onReset(e){const{mjModel:t,mjData:r}=e;if(!t||!r)return;const i=this._findFreeJoint(t);if(i===-1)return;const s=t.jnt_qposadr[i],a=l=>{const c=this.poseRange[l];return c?c[0]+Math.random()*(c[1]-c[0]):0};r.qpos[s+0]+=a("x"),r.qpos[s+1]+=a("y"),r.qpos[s+2]+=a("z");const o=a("yaw");o!==0&&this._applyYawRotation(r.qpos,s+3,o)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}class hne extends Xz{constructor(e){super(e),this.patchName=e.params?.patch_name??"spawn",this.fallback=new Kz(e)}onReset(e){const{mjModel:t,mjData:r,terrainData:i}=e;if(!t||!r)return;const s=i?.flat_patches?.[this.patchName];if(!s||s.length===0){this.fallback.onReset(e);return}const a=this._findFreeJoint(t);if(a===-1)return;const o=t.jnt_qposadr[a],l=s[Math.floor(Math.random()*s.length)],c=r.qpos[o+2];r.qpos[o+0]=l[0],r.qpos[o+1]=l[1],r.qpos[o+2]=l[2]+c;const h=(this.config.params?.pose_range??{}).yaw??[-Math.PI,Math.PI],p=h[0]+Math.random()*(h[1]-h[0]);this._applyYawRotation(r.qpos,o+3,p)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}const fne={ResetRootStateUniform:Kz,ResetRootStateFromFlatPatches:hne},pne={...fne,...dne};class Zz extends Error{constructor(){super("This scene cannot be loaded because it exceeds the browser's WebAssembly 2 GB memory limit. Try closing other browser tabs or reloading the page to free memory."),this.name="WasmMemoryLimitError"}}function qR(n){const e=n instanceof Error?n.message:String(n);return e.includes("MjModel loading returned null")||e.includes("Could not allocate memory")||e.includes("memory allocation failed")||e.includes("bad_alloc")}class Ane{constructor(e,t,r={}){this.render=()=>{if(tr().updateDebugVisuals(),this.mjData&&$Z(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){F3(this.camera,this.lights);for(const[o,l]of this.lastSimState.bodies){const c=this.bodies[o];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion))}L3(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&hJ({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{const{width:o,height:l}=this.getSize();this.camera.aspect=o/l,this.camera.updateProjectionMatrix(),this.renderer.setSize(o,l)},this.mujoco=e,this.container=t,this.baseUrl=r.baseUrl||"/";const i="/working";try{this.mujoco.FS.mkdir(i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&console.warn("Failed to create /working directory:",o)}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:"."},i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&o.code!=="EBUSY"&&console.warn("Failed to mount MEMFS at /working:",o)}const{width:s,height:a}=this.getSize();this.scene=new s9,this.scene.name="scene",this.camera=new zr(45,s/a,.001,1e3),this.camera.name="PerspectiveCamera",this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new z7({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(s,a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=QN,this.renderer.outputColorSpace=ii,this.renderer.toneMapping=PN,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported("immersive-vr").then(o=>{o&&(this.vrButton=RC.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new O7(this.camera,this.renderer.domElement),this.controls.target.set(0,.2,0),this.controls.panSpeed=2,this.controls.zoomSpeed=1,this.controls.enableDamping=!0,this.controls.dampingFactor=.1,this.controls.screenSpacePanning=!0,this.controls.update(),this.renderer.setAnimationLoop(this.render),window.addEventListener("resize",this.onWindowResize),"ResizeObserver"in window?(this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),this.resizeObserver.observe(this.container)):this.resizeObserver=null,this.lastSimState={bodies:new Map,tendons:fJ()},this.dynamicBodyIds=null,this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.loopPromise=null,this.running=!1,this.timestep=.001,this.decimation=1,this.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null,this.eventManager=null,this.terrainData=null,this.splatMesh=null,this.colliderMesh=null,this.cameraState={trackBodyId:null,prevBodyPos:null},this.sceneCacheManager=Ew.getInstance(this.mujoco),this.resourceTracker=new GZ,this.memoryMonitor=new HZ}async loadEnvironment(e,t=null,r=null,i=null,s=null,a=null){this.terrainData=a,s&&s.length>0?(this.eventManager=new une(s,pne),console.log(`[EventManager] ${this.eventManager.size} reset event(s) loaded`)):this.eventManager=null,await this.stop(),this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null);const o=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const l=performance.now()-o;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:l})}else this.memoryMonitor.logCacheOperation("miss",e),await this.sceneCacheManager.prepareForNewScene(),this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.resourceTracker.startTracking(this.mujoco),await bJ(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);r&&(this.splatMesh=tB(r,this.scene),r.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(r.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.applyViewerConfig(i),this.running=!0,this.startLoop()}initializeCommands(){const e=tr();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e,t){tr().initialize(e,t),console.log("[mjswanRuntime] Commands loaded from policy config:",Object.keys(e))}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){const e=this.policyStateBuilder.build();this.policyRunner.reset(e)}console.log("[mjswanRuntime] Simulation reset")}async setSelectedMotion(e){const t=tr().getTerm("motion");t instanceof xp&&(await t.setSelectedMotion(e),this.resetSimulation())}setReferenceVisible(e){const t=tr().getTerm("motion");t instanceof xp&&t.setReferenceVisible(e)}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{const t=this.scene.getObjectByName("MuJoCo Root");t&&this.scene.remove(t);const r={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await vJ(this.mujoco,e,r),!this.mjModel||!this.mjData)throw new Error("Failed to load MuJoCo model.");this.mujocoRoot=this.scene.getObjectByName("MuJoCo Root"),this.mujoco.mj_forward(this.mjModel,this.mjData),L3(this.mujoco,this.mjData,this.lights),F3(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds}),this.loadingScene=null})(),await this.loadingScene}async loadSceneWithOomRetry(e){try{await this.loadScene(e)}catch(t){if(!qR(t))throw t;console.warn("[mjswanRuntime] OOM — clearing cache and retrying..."),this.loadingScene=null,await this.sceneCacheManager.clear();try{await this.loadScene(e)}catch(r){throw this.loadingScene=null,qR(r)?new Zz:r}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null),e&&(this.splatMesh=tB(e,this.scene),e.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&oP(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}async stop(){this.running=!1;const e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){const e=performance.now(),t=this.timestep*this.decimation;if(this.mjModel&&this.mjData){if(this.mujoco.mj_forward(this.mjModel,this.mjData),this.policyRunner&&this.policyStateBuilder){const s=this.policyStateBuilder.build(),a=this.policyRunner.collectObservationsByKey(s);if(await this.runOnnxInference(a),this.policyDebugCounter%60===0){const o="policy"in a?"policy":"observation"in a?"observation":Object.keys(a)[0],l=o?a[o]:null,c=l?Array.from(l.slice(0,8)):[];console.log("[PolicyRunner] obs",{key:o,size:l?l.length:0,sample:c})}this.policyDebugCounter+=1}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){const s=this.policyStateBuilder.build();if(this.terminationManager.evaluate(s).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){const o=this.policyStateBuilder.build();this.policyRunner.reset(o)}}tr().update(t),tr().updateDebugVisuals()}const r=(performance.now()-e)/1e3,i=Math.max(0,t-r);i>0&&await new Promise(s=>setTimeout(s,i*1e3))}this.loopPromise=null}async loadPolicyConfig(e){const t=this.policyConfigPath;this.policyConfigPath=e,this.policyRunner=null,this.policyStateBuilder=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null;const r=tr();if(r.clear(),r.setResetCallback(()=>this.resetSimulation()),!!e){if(!this.mjModel||!this.mjData){console.warn("Policy config loaded before MuJoCo model is ready.");return}e!==t&&this.resetSimulationState();try{const{config:i}=await this.fetchPolicyConfig(e);if(Array.isArray(i.motions)&&(i.motions=i.motions.map(o=>({...o,path:this.resolveAssetUrl(this.resolvePolicyAssetPath(e,o.path))}))),i.commands?.motion?.name==="TrackingCommand"&&Array.isArray(i.motions)&&(i.commands.motion={...i.commands.motion,motions:i.motions}),this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),i.commands&&typeof i.commands=="object"){this.initializeCommandsFromConfig(i.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,bodies:this.bodies,mujocoRoot:this.mujocoRoot}),tr().resetTerms();const o=tr().getTerm("motion");o instanceof xp&&(await o.setSelectedMotion(i.motions?.find(l=>l.default)?.name??i.motions?.[0]?.name??null),o.setReferenceVisible(!0)),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()}if(!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new rne(i,{policyModules:{tracking:one,locomotion:cne},observations:Mee});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),this.policyRunner=s,this.policyStateBuilder=new sne(this.mujoco,this.mjModel,this.mjData,s.getPolicyJointNames());const a=this.policyStateBuilder.build();if(this.policyRunner.reset(a),this.policyControl=this.buildPolicyControl(i,s,this.policyStateBuilder),i.terminations&&Object.keys(i.terminations).length>0&&(this.terminationManager=new Tee(i.terminations,Pee),console.log(`[TerminationManager] ${this.terminationManager.size} termination term(s) loaded`)),i.onnx?.path){const o=this.resolvePolicyAssetPath(e,i.onnx.path),l=this.resolveAssetUrl(o),c={...i.onnx,path:l},d=new ine(c);await d.init(),this.onnxModule=d,this.onnxInputDict=d.initInput()}console.log("[PolicyRunner] config loaded",{obsSize:s.getObservationSize(),obsLayout:s.getObservationLayout(),pdEnabled:this.policyControl!==null})}catch(i){console.warn("Failed to load policy config:",i)}}}async fetchPolicyConfig(e){const t=this.resolveAssetUrl(e),r=await fetch(t,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch policy config: ${r.status}`);return{config:await r.json(),resolvedUrl:t}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;const t=(this.baseUrl||"/").replace(/\/+$/,"/"),r=new URL(t,window.location.origin+"/").toString();return new URL(e.replace(/^\/+/,""),r).toString()}resolvePolicyAssetPath(e,t){const r=e.replace(/\\/g,"/"),i=r.lastIndexOf("/");return i>=0?`${r.slice(0,i+1)}${t}`.replace(/\/+/g,"/"):t}buildPolicyControl(e,t,r){const i=t.getPolicyJointNames(),s=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(c,d,h,p,A,y,m,x)=>{const g=h.qposAdr.length,_=h.actionIndices.map(B=>i[B]),b=this.normalizeControlArray(p,g,1,_),w=this.normalizeControlArray(A,g,0,_),C=x?t.getDefaultJointPos():new Float32Array(i.length),S=new Float32Array(g);for(let B=0;B<g;B++)S[B]=C[h.actionIndices[B]];const M=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(i.length),T=new Float32Array(g);for(let B=0;B<g;B++)T[B]=M[h.actionIndices[B]]??0;const R=this.normalizeControlArray(y,g,0,_),k=this.normalizeControlArray(m,g,0,_),G=h.ctrlAdr.map(B=>B<0||!this.mjModel?!1:this.mjModel.actuator_biastype[B]===s),P=G.some(Boolean),V=G.some(B=>!B);return P&&V&&console.warn(`[PolicyRunner] Action term "${c}": mixed actuator types detected.`),console.log(`[PolicyRunner] Action term "${c}" (${d}): ${g} joint(s), mode: ${P?"position (ctrl=target_pos)":"motor (ctrl=torque, external PD)"}`),{controlType:d,ctrlAdr:h.ctrlAdr,qposAdr:h.qposAdr,qvelAdr:h.qvelAdr,actionIndices:h.actionIndices,actionScale:b,actionOffset:w,defaultJointPos:S,encoderBias:T,positionActuator:G,kp:R,kd:k}},o=e.actions;if(!o||Object.keys(o).length===0){const c=e.control_type??"joint_position";if(c!=="joint_position"&&c!=="torque")return console.warn(`[PolicyRunner] Unsupported control_type: ${c}`),null;const d=r.getControlMapping();if(!d)return console.warn("[PolicyRunner] Failed to build control mapping."),null;const h={...d,actionIndices:Array.from({length:d.qposAdr.length},(p,A)=>A)};return[a("legacy",c,h,e.action_scale,void 0,e.stiffness,e.damping,!0)]}const l=[];for(const[c,d]of Object.entries(o)){const h=d.type??"joint_position";if(h!=="joint_position"&&h!=="torque"){console.warn(`[PolicyRunner] Action term "${c}": unsupported type "${h}", skipping.`);continue}const p=d.actuator_names??[".*"],A=p.length===1&&p[0]===".*";let y;if(A){const x=r.getControlMapping();if(!x){console.warn(`[PolicyRunner] Action term "${c}": failed to build control mapping, skipping.`);continue}y={...x,actionIndices:Array.from({length:x.qposAdr.length},(g,_)=>_)}}else if(y=r.getControlMappingFor(p,i),!y){console.warn(`[PolicyRunner] Action term "${c}": no joints matched patterns [${p.join(", ")}], skipping.`);continue}const m=d.use_default_offset!==void 0?d.use_default_offset:h==="joint_position";l.push(a(c,h,y,d.scale,d.offset,d.stiffness,d.damping,m))}return l.length===0?(console.warn("[PolicyRunner] No valid action terms found in config.actions."),null):l}normalizeControlArray(e,t,r,i){const s=new Float32Array(t);if(s.fill(r),typeof e=="number")return s.fill(e),s;if(Array.isArray(e)){for(let a=0;a<t;a++)s[a]=typeof e[a]=="number"?e[a]:r;return s}if(e!==null&&typeof e=="object"&&i){for(const[a,o]of Object.entries(e)){const l=i.indexOf(a);l>=0&&l<t?s[l]=o:console.warn(`[PolicyRunner] Joint name "${a}" not found in policy_joint_names; skipping.`)}return s}return s}resetSimulationState(){!this.mjModel||!this.mjData||(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),tr().resetTerms(),this.onnxModule&&(this.onnxInputDict=this.onnxModule.initInput()),this.onnxTimeStep=0,this.mujoco.mj_forward(this.mjModel,this.mjData),this.lastSimState.bodies.clear(),this.updateCachedState())}executeSimulationSteps(){if(!(!this.mjModel||!this.mjData)){this.applyDragForces();for(let e=0;e<this.decimation;e++)this.applyPolicyControl(),this.mujoco.mj_step(this.mjModel,this.mjData)}}applyPolicyControl(){if(!this.policyControl||!this.mjData)return;const e=this.mjData.ctrl;e.fill(0);const t=this.policyRunner?.getLastActions()??new Float32Array(0);for(const r of this.policyControl){const{controlType:i,ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l,actionScale:c,actionOffset:d,defaultJointPos:h,encoderBias:p,positionActuator:A,kp:y,kd:m}=r,x=s.length;if(i==="joint_position")for(let g=0;g<x;g++){const _=s[g];if(_<0)continue;const b=t[l[g]]??0,w=h[g]+d[g]+c[g]*b-p[g];if(A[g])e[_]=w;else{const C=this.mjData.qpos[a[g]],S=this.mjData.qvel[o[g]];e[_]=y[g]*(w-C)+m[g]*(0-S)}}else if(i==="torque")for(let g=0;g<x;g++){const _=s[g];_>=0&&(e[_]=c[g]*(t[l[g]]??0))}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||(this.onnxInputDict=this.onnxModule.initInput());const t={...this.onnxInputDict};this.onnxModule.inKeys.includes("time_step")&&(t.time_step=new ti("float32",new Float32Array([this.onnxTimeStep]),[1,1]));for(const[d,h]of Object.entries(e))t[d]=new ti("float32",h,[1,h.length]);for(const d of this.onnxModule.inKeys)if(!t[d]){console.warn("[PolicyRunner] Missing ONNX input:",{key:d,available:Object.keys(t)});return}const[r,i]=await this.onnxModule.runInference(t);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i}),this.onnxModule.inKeys.includes("time_step")&&(this.onnxTimeStep+=1);const s=this.onnxModule.outKeys[0],a=r.action??(s?r[s]:null)??r.policy??null;if(!a)return;const o=a.data,l=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&l.length!==c){console.warn("[PolicyRunner] Action size mismatch:",{expected:c,got:l.length});return}this.policyRunner.setLastActions(l)}catch(t){console.warn("[PolicyRunner] ONNX inference failed:",t)}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let p=0;p<this.mjData.xfrc_applied.length;p++)this.mjData.xfrc_applied[p]=0;const e=this.dragStateManager.physicsObject;if(!e||!("bodyID"in e)||typeof e.bodyID!="number"||e.bodyID<=0)return;const t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(Vc(this.mjData.xpos,p,this.bodies[p].position),pp(this.mjData.xquat,p,this.bodies[p].quaternion),this.bodies[p].updateWorldMatrix(!0,!1));this.dragStateManager.update();const r=this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale),i=P3(r),s=this.dragStateManager.worldHit.clone(),a=P3(s),o=new ue(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),l=new ue(a.x-o.x,a.y-o.y,a.z-o.z),c=new ue(i.x,i.y,i.z),d=new ue().crossVectors(l,c),h=t*6;this.mjData.xfrc_applied[h+0]=i.x,this.mjData.xfrc_applied[h+1]=i.y,this.mjData.xfrc_applied[h+2]=i.z,this.mjData.xfrc_applied[h+3]=d.x,this.mjData.xfrc_applied[h+4]=d.y,this.mjData.xfrc_applied[h+5]=d.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++)if(!(e&&!e.has(t))&&this.bodies[t]){this.lastSimState.bodies.has(t)||this.lastSimState.bodies.set(t,{position:new ue,quaternion:new Cn});const r=this.lastSimState.bodies.get(t);Vc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&dJ(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=OZ(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){const t=new Set;for(let r=1;r<e.nbody;r++){let i=r;for(;i>0;){if(e.body_jntnum[i]>0){t.add(r);break}i=e.body_parentid[i]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;const r=this.bodies[t];r&&(Vc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion))}}dispose(){this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.dragStateManager&&(this.dragStateManager.dispose(),this.dragStateManager=null),this.mjData=null,this.mjModel=null,window.removeEventListener("resize",this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.controls.dispose(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.vrButton?.parentElement&&(this.vrButton.parentElement.removeChild(this.vrButton),this.vrButton=null),this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.lastSimState.bodies.clear()}disposeThreeJSResources(){if(this.scene)for(this.scene.traverse(e=>{"geometry"in e&&e.geometry&&e.geometry.dispose(),"material"in e&&e.material&&(Array.isArray(e.material)?e.material.forEach(t=>this.disposeMaterial(t)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),e.dispose()}getSize(){const e=this.container.clientWidth||window.innerWidth,t=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,t)}}async restoreFromCache(e){const t=this.sceneCacheManager.get(e);if(!t)throw new Error(`Scene ${e} not found in cache`);const r=this.scene.getObjectByName("MuJoCo Root");r&&this.scene.remove(r),this.mjModel=t.mjModel,this.mjData=t.mjData,this.bodies=t.bodies,this.lights=t.lights,this.mujocoRoot=t.mujocoRoot,this.scene.add(this.mujocoRoot),this.scene.background=t.skybox,this.mujoco.mj_forward(this.mjModel,this.mjData),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds})}async captureAndCacheResources(e){const t=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot){console.warn("[SceneCache] Cannot cache scene: missing resources");return}const r=this.resourceTracker.estimateSceneMemory({mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,meshes:{},mujocoRoot:this.mujocoRoot});await this.sceneCacheManager.set(e,{scenePath:e,lastAccessed:Date.now(),loadedAt:Date.now(),mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,lights:this.lights,meshes:{},mujocoRoot:this.mujocoRoot,skybox:this.scene.background instanceof ph?this.scene.background:null,fsFiles:t,estimatedMemoryBytes:r});const i=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation("load",e,{memoryMB:r/1048576,totalScenes:i.totalScenes,totalMemoryMB:i.totalMemoryBytes/1048576})}}const ag="mjswan_oom_reload_scene",mne=({scenePath:n,baseUrl:e,policyConfigPath:t,splatConfig:r,cameraConfig:i,eventsConfig:s,terrainData:a,selectedMotion:o,showReferenceMotion:l=!0,onStatusChange:c,onError:d,onReady:h,onRuntimeReady:p})=>{const A=U.useRef(null),y=U.useRef(null),m=U.useRef(null),x=U.useRef(r);x.current=r;const g=U.useRef(o);g.current=o;const _=U.useRef(l);return _.current=l,U.useEffect(()=>{let b=!1;const w=S=>{c?.(S)};return(async()=>{if(w("Loading MuJoCo..."),!m.current){const T=await RH(()=>import("./mujoco-D2QHsN8V.js"),[]);m.current=await T.default()}if(b)return;const S=A.current;if(!S)throw new Error("Failed to find viewer container.");const M=m.current;if(!M)throw new Error("MuJoCo not loaded.");y.current||(y.current=new Ane(M,S,{baseUrl:e}),p?.(y.current)),w("Loading scene assets..."),await y.current.loadEnvironment(n,t??null,x.current??null,i??null,s??null,a??null),await y.current.setSelectedMotion(g.current??null),y.current.setReferenceVisible(_.current),!b&&(sessionStorage.removeItem(ag),w("Running simulation"),h?.())})().catch(S=>{if(!b){if(S instanceof Zz){if(sessionStorage.getItem(ag)!==n){console.warn("[MjswanViewer] OOM — reloading page to free memory..."),sessionStorage.setItem(ag,n),window.location.reload();return}sessionStorage.removeItem(ag)}console.error("Failed to initialize MuJoCo viewer:",S),d?.(S instanceof Error?S:new Error(String(S))),w("Failed to load scene")}}),()=>{b=!0,y.current?.dispose(),y.current=null}},[n,e,t,i,s,a,c,d,h]),U.useEffect(()=>{y.current&&y.current.setSelectedMotion(o??null)},[o]),U.useEffect(()=>{y.current?.setReferenceVisible(l)},[l]),j.jsx("div",{ref:A,className:"viewer"})};var gne={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};const ey=(n,e,t,r)=>{const i=U.forwardRef(({color:s="currentColor",size:a=24,stroke:o=2,title:l,className:c,children:d,...h},p)=>U.createElement("svg",{ref:p,...gne[n],width:a,height:a,className:["tabler-icon",`tabler-icon-${e}`,c].join(" "),strokeWidth:o,stroke:s,...h},[l&&U.createElement("title",{key:"svg-title"},l),...r.map(([A,y])=>U.createElement(A,y)),...Array.isArray(d)?d:[d]]));return i.displayName=`${t}`,i};const yne=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],e4=ey("outline","chevron-down","ChevronDown",yne);const xne=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],vne=ey("outline","chevron-up","ChevronUp",xne);const _ne=[["path",{d:"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4",key:"svg-0"}],["path",{d:"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4",key:"svg-1"}]],bne=ey("outline","refresh","Refresh",_ne);const wne=[["path",{d:"M18 6l-12 12",key:"svg-0"}],["path",{d:"M6 6l12 12",key:"svg-1"}]],Ene=ey("outline","x","X",wne),YR="0.5.0",JR=[{login:"ttktjmt",html_url:"https://github.com/ttktjmt"},{login:"claude",html_url:"https://github.com/claude"},{login:"julien-blanchon",html_url:"https://github.com/julien-blanchon"},{login:"unmoyai",html_url:"https://github.com/unmoyai"},{login:"brentyi",html_url:"https://github.com/brentyi"},{login:"Axellwppr",html_url:"https://github.com/Axellwppr"},{login:"CharlieLeee",html_url:"https://github.com/CharlieLeee"}],Cne={move:"touchmove",end:"touchend"},Ine={move:"mousemove",end:"mouseup"};function Sne(n){return n.type==="touchmove"}function Bne(n){return n.type==="mousemove"}const Wp=On.createContext(null);function Ao({children:n,width:e,visible:t=!0,onVisibleChange:r,hiddenButtonTooltip:i}){const s=On.useRef(null),[a,{toggle:o}]=s0(!0),[l,c]=On.useState(800),d=On.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),h=On.useRef({}),p=(x,g,_)=>Math.abs(x+g/2)<Math.abs(x-_+g/2)?x:x-_,A=15;function y(x,g){const _=s.current;if(_===null)return[x,g];const b=_.parentElement;if(b===null)return[x,g];let w=x,C=g;return w=Math.min(w,b.clientWidth-_.clientWidth-A),w=Math.max(w,A),C=Math.min(C,b.clientHeight-_.clientHeight-A),C=Math.max(C,A),_.style.top=`${C.toString()}px`,_.style.left=`${w.toString()}px`,[p(w,_.clientWidth,b.clientWidth),p(C,_.clientHeight,b.clientHeight)]}On.useEffect(()=>{const x=s.current;if(x===null)return;const g=x.parentElement;if(g===null)return;const _=new ResizeObserver(()=>{h.current.x===void 0&&(h.current.x=p(x.offsetLeft,x.clientWidth,g.clientWidth)),h.current.y===void 0&&(h.current.y=p(x.offsetTop,x.clientHeight,g.clientHeight));const b=g.clientHeight-A*2;l!==b&&c(b);let w=h.current.x,C=h.current.y;for(;w<0;)w+=g.clientWidth;for(;C<0;)C+=g.clientHeight;y(w,C)});return _.observe(x),_.observe(g),()=>{_.disconnect()}});const m=x=>{const g=d.current,_=s.current;if(!_)return;x.type=="touchstart"?(x=x,g.startClientX=x.touches[0].clientX,g.startClientY=x.touches[0].clientY):(x=x,g.startClientX=x.clientX,g.startClientY=x.clientY),g.startPosX=_.offsetLeft,g.startPosY=_.offsetTop;const b=x.type=="touchstart"?Cne:Ine;function w(C){let S=0,M=0;if(Sne(C)?(C=C,S=C.touches[0].clientX-g.startClientX,M=C.touches[0].clientY-g.startClientY):Bne(C)&&(C=C,S=C.clientX-g.startClientX,M=C.clientY-g.startClientY),Math.abs(S)<=3&&Math.abs(M)<=3)return;g.dragging=!0;const T=g.startPosX+S,R=g.startPosY+M;[h.current.x,h.current.y]=y(T,R)}window.addEventListener(b.move,w),window.addEventListener(b.end,()=>{x.type=="touchstart"&&(g.dragging=!1),window.removeEventListener(b.move,w)},{once:!0})};if(!t){const x=j.jsx(Xe,{component:"button","aria-label":i??"Show controls",onClick:()=>r?.(!0),style:{width:"0.85rem",height:"0.85rem",minWidth:"0.85rem",minHeight:"0.85rem",display:"block",padding:0,border:"none",borderRadius:"9999px",background:"rgba(255, 255, 255, 0.82)",boxShadow:"0 0 0 1px rgba(0, 0, 0, 0.14), 0 2px 8px rgba(0, 0, 0, 0.18)",cursor:"pointer"}});return j.jsx(Xe,{style:{zIndex:10,position:"absolute",top:"1em",right:"1em"},children:i?j.jsx(Pl,{label:i,children:j.jsx(Xe,{children:x})}):x})}return j.jsx(Wp.Provider,{value:{wrapperRef:s,expanded:a,width:e,maxHeight:l,toggleExpanded:o,dragHandler:m,dragInfo:d},children:j.jsx(Yc,{radius:"xs",shadow:"0.1em 0 1em 0 rgba(0,0,0,0.1)",style:{boxSizing:"border-box",width:e,zIndex:10,position:"absolute",top:"1em",right:"1em",margin:0,"& .expandIcon":{transform:"rotate(0)"},overflow:"hidden"},ref:s,children:n})})}Ao.Handle=function({children:e}){const t=On.useContext(Wp);return j.jsx(j.Fragment,{children:j.jsx(Xe,{style:{borderRadius:"0.2em 0.2em 0 0",lineHeight:"1.5em",cursor:"pointer",position:"relative",fontWeight:400,userSelect:"none",display:"flex",alignItems:"center",padding:"0 0.75em",height:"2.75em"},onClick:()=>{const r=t.dragInfo.current;if(r.dragging){r.dragging=!1;return}t.toggleExpanded()},onTouchStart:r=>{t.dragHandler(r)},onMouseDown:r=>{t.dragHandler(r)},children:e})})};Ao.Contents=function({children:e}){const t=On.useContext(Wp);return j.jsxs(Mg,{in:t.expanded,children:[j.jsx(Dd,{mx:"xs"}),j.jsx(iu.Autosize,{mah:t.maxHeight,children:j.jsx(Xe,{style:{width:t.width},children:e})})]})};Ao.HideWhenCollapsed=function({children:e}){return On.useContext(Wp)?.expanded??!0?e:null};Ao.HideWhenExpanded=function({children:e}){return On.useContext(Wp)?.expanded??!0?null:e};function og({id:n,label:e,children:t}){return j.jsx(Xe,{pb:"0.5em",px:"xs",children:j.jsxs(EE,{align:"center",children:[j.jsx(Xe,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:j.jsx(Js,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:j.jsx("label",{htmlFor:n,children:e})})}),j.jsx(Xe,{style:{flexGrow:1},children:t})]})})}function t4({label:n,expandByDefault:e=!0,children:t}){const[r,{toggle:i}]=s0(e),s=r?vne:e4;return j.jsxs(Yc,{withBorder:!0,style:{borderWidth:"1px",position:"relative",marginLeft:"var(--mantine-spacing-xs)",marginRight:"var(--mantine-spacing-xs)",marginTop:"var(--mantine-spacing-xs)",marginBottom:"var(--mantine-spacing-xs)",paddingBottom:"calc(var(--mantine-spacing-xs) - 0.5em)"},children:[j.jsxs(Yc,{onClick:i,style:{fontSize:"0.875em",position:"absolute",padding:"0 0.375em",top:0,left:"0.375em",transform:"translateY(-50%)",userSelect:"none",fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center"},children:[n,j.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),j.jsx(Mg,{in:r,children:j.jsx(Xe,{pt:"1em",children:t})}),j.jsx(Mg,{in:!r,children:j.jsx(Xe,{p:"xs"})})]})}const n4={fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"4.5em",flexShrink:0},Mne={root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}},Tne={flex:1,minWidth:0,height:"1.75em",fontSize:"0.8em",fontFamily:"inherit",border:"1px solid var(--mantine-color-default-border)",borderRadius:"var(--mantine-radius-sm)",background:"var(--mantine-color-default)",color:"var(--mantine-color-text)",textAlign:"right",padding:"0 0.4em",outline:"none",cursor:"ns-resize",touchAction:"none"};function q_({axis:n,value:e,min:t=-1/0,max:r=1/0,step:i,onChange:s}){const a=U.useRef(null),o=U.useRef(null);U.useEffect(()=>{const y=a.current;y&&document.activeElement!==y&&(y.value=e.toFixed(2))},[e]);const l=y=>Math.max(t,Math.min(r,parseFloat((Math.round(y/i)*i).toFixed(10)))),c=y=>{y.preventDefault(),y.currentTarget.setPointerCapture(y.pointerId),o.current={startY:y.clientY,startValue:e,moved:!1}},d=y=>{if(!o.current||!(y.buttons&1))return;const m=o.current.startY-y.clientY;if(Math.abs(m)>3&&(o.current.moved=!0),!o.current.moved)return;const x=l(o.current.startValue+m*i);s(x),a.current&&(a.current.value=x.toFixed(2))},h=()=>{if(o.current&&!o.current.moved){const y=a.current;y&&(y.focus(),y.select())}o.current=null},p=y=>{const m=parseFloat(y.target.value);isNaN(m)||s(l(m)),y.target.value=e.toFixed(2)},A=y=>{y.key==="Enter"&&y.currentTarget.blur(),y.key==="Escape"&&(a.current&&(a.current.value=e.toFixed(2)),a.current?.blur())};return j.jsxs(Xe,{style:{display:"flex",alignItems:"center",gap:"0.25em",flex:1},children:[j.jsx(Js,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,letterSpacing:"-0.75px",flexShrink:0},children:n}),j.jsx("input",{ref:a,size:1,defaultValue:e.toFixed(2),onPointerDown:c,onPointerMove:d,onPointerUp:h,onBlur:p,onKeyDown:A,onFocus:y=>y.currentTarget.style.outline="2px solid var(--mantine-color-blue-5)",onBlurCapture:y=>y.currentTarget.style.outline="none",style:Tne})]})}function XR({label:n,x:e,y:t,z:r,step:i,xLabel:s="X",yLabel:a="Y",zLabel:o="Z",onX:l,onY:c,onZ:d}){return j.jsxs(Xe,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Js,{c:"dimmed",style:n4,children:n}),j.jsx(q_,{axis:s,value:e,step:i,onChange:l}),j.jsx(q_,{axis:a,value:t,step:i,onChange:c}),j.jsx(q_,{axis:o,value:r,step:i,onChange:d})]})}function Rne({scale:n,xOffset:e,yOffset:t,zOffset:r,roll:i,pitch:s,yaw:a,onCalibrate:o}){const[l,c]=U.useState(n),[d,h]=U.useState(e),[p,A]=U.useState(t),[y,m]=U.useState(r),[x,g]=U.useState(i),[_,b]=U.useState(s),[w,C]=U.useState(a);U.useEffect(()=>{c(n)},[n]),U.useEffect(()=>{h(e)},[e]),U.useEffect(()=>{A(t)},[t]),U.useEffect(()=>{m(r)},[r]),U.useEffect(()=>{g(i)},[i]),U.useEffect(()=>{b(s)},[s]),U.useEffect(()=>{C(a)},[a]);const S=(M,T,R,k,G,P,V)=>o(M,T,R,k,G,P,V);return j.jsxs(t4,{label:"Control",expandByDefault:!0,children:[j.jsxs(Xe,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Js,{c:"dimmed",style:n4,children:"Scale"}),j.jsx(Xe,{style:{flex:1},children:j.jsx(P0,{value:l,onChange:M=>{c(M),S(M,d,p,y,x,_,w)},min:.1,max:5,step:.05,size:"xs",label:M=>M.toFixed(2),styles:Mne})})]}),j.jsx(XR,{label:"Position",x:d,y:p,z:y,step:.05,onX:M=>{h(M),S(l,M,p,y,x,_,w)},onY:M=>{A(M),S(l,d,M,y,x,_,w)},onZ:M=>{m(M),S(l,d,p,M,x,_,w)}}),j.jsx(XR,{label:"Rotation",x,y:_,z:w,step:.5,xLabel:"R",yLabel:"P",zLabel:"Y",onX:M=>{g(M),S(l,d,p,y,M,_,w)},onY:M=>{b(M),S(l,d,p,y,x,M,w)},onZ:M=>{C(M),S(l,d,p,y,x,_,M)}})]})}function Dne(n){return n instanceof HTMLElement?n.isContentEditable?!0:n.closest('input, textarea, select, [contenteditable], [role="textbox"], [role="searchbox"], [role="combobox"]')!==null:!1}function kne(n){return n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Nne({command:n,value:e,onChange:t,disabled:r}){const i=n.config;return j.jsxs(Xe,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[j.jsx(Js,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:i.label}),j.jsx(Xe,{style:{width:"50%"},children:j.jsx(P0,{value:e,onChange:s=>t(n.id,s),min:i.min,max:i.max,step:i.step,size:"xs",disabled:r,styles:{root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}}})})]})}function Qne(n){const{visible:e,onVisibleChange:t,projects:r,projectValue:i,projectLabel:s,onProjectChange:a,scenes:o,sceneValue:l,onSceneChange:c,splats:d,splatSection:h=!1,splatValue:p,onSplatChange:A,splatConfig:y,onCalibrateSplat:m,onSplatUrlLoad:x,policies:g,policyValue:_,onPolicyChange:b,motions:w,motionValue:C,onMotionChange:S,showReferenceMotion:M,onShowReferenceMotionChange:T,commandsEnabled:R=!1,onReset:k}=n,[G,{open:P,close:V}]=s0(!1),[B,W]=U.useState(""),[K,Y]=U.useState(null),[$,J]=U.useState(!1),re=U.useCallback(async ve=>{if(ve.key!=="Enter"||!x)return;const Ne=B.trim();if(d.some(Ge=>Ge.label===Ne||Ge.value===Ne))return;if(!Ne.toLowerCase().endsWith(".spz")){Y("URL must end with .spz");return}await x(Ne)?(Y(null),J(!0)):Y("File not found at the specified URL")},[x,B,d]),[L,H]=U.useState([]),[oe,Ae]=U.useState([]),[ye,he]=U.useState({});U.useEffect(()=>{const ve=tr(),Ne=()=>{H(ve.getCommands()),Ae(ve.getCommandGroups()),he(ve.getValues())};return Ne(),ve.addEventListener(Ne),()=>{ve.removeEventListener(Ne)}},[]),U.useEffect(()=>{const ve=Ne=>{if(Ne.defaultPrevented||Ne.repeat||Ne.altKey||Ne.ctrlKey||Ne.metaKey||Ne.key.toLowerCase()!=="c")return;const ct=Ne.target instanceof Element?Ne.target:document.activeElement;Dne(ct)||(Ne.preventDefault(),t(!e))};return window.addEventListener("keydown",ve),()=>{window.removeEventListener("keydown",ve)}},[e,t]);const fe=U.useCallback((ve,Ne)=>{tr().setValue(ve,Ne),he(Ge=>({...Ge,[ve]:Ne}))},[]),Ee=U.useCallback(()=>{tr().triggerButton("_system:reset"),k&&k()},[k]),Re=ve=>L.filter(Ne=>Ne.groupName===ve&&Ne.config.type==="slider");return!r.length&&!o.length&&!g.length?null:j.jsxs(j.Fragment,{children:[j.jsx(aa,{opened:G,onClose:V,size:"lg",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:j.jsxs(sC,{gap:"md",align:"center",children:[j.jsx(Pg,{src:"./logo-color.svg",style:{width:"8em",height:"auto"}}),j.jsx(Js,{size:"xl",fw:700,children:"powered by mjswan"}),j.jsxs(Js,{size:"sm",c:"dimmed",children:["version ",YR]}),j.jsx(Js,{size:"sm",c:"dimmed",children:"MuJoco Simulation on Web Assembly with Neural netwroks"}),j.jsx(Dd,{w:"100%"}),j.jsxs(Xe,{children:[j.jsx(up,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"})," • ",j.jsx(up,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]}),j.jsx(Dd,{w:"100%"}),j.jsxs(Xe,{style:{textAlign:"left",maxHeight:"120px",overflowY:"auto",lineHeight:"1",fontSize:"0.8rem",opacity:"0.75"},px:"md",children:["Thanks to our contributors! ",j.jsx("br",{}),JR.map((ve,Ne)=>j.jsxs("span",{children:[j.jsx(up,{href:ve.html_url,target:"_blank",style:{textDecoration:"none",fontSize:"0.75rem"},children:ve.login}),Ne<JR.length-1&&", "]},ve.login))]})]})}),j.jsxs(Ao,{width:"20em",visible:e,onVisibleChange:t,hiddenButtonTooltip:"Show controls (C)",children:[j.jsxs(Ao.Handle,{children:[j.jsx(Pl,{label:`mjswan ${YR}`,children:j.jsx(Xe,{component:"a",onClick:ve=>{ve.stopPropagation(),P()},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{position:"absolute",cursor:"pointer",display:"flex",top:"0.8em",left:"0.9em"},children:j.jsx(Pg,{src:"./logo.svg",style:{width:"1.2em",height:"auto"}})})}),j.jsx("div",{style:{width:"1.1em"}}),j.jsx(Ao.HideWhenCollapsed,{children:j.jsxs(Xe,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[j.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),r.length>1&&j.jsxs(pi,{position:"bottom-start",offset:5,children:[j.jsx(pi.Target,{children:j.jsx(Xe,{onClick:ve=>ve.stopPropagation(),onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center",flexShrink:0},children:j.jsx(e4,{size:16})})}),j.jsx(pi.Dropdown,{onClick:ve=>ve.stopPropagation(),children:r.map(ve=>j.jsx(pi.Item,{onClick:Ne=>{Ne.stopPropagation(),a(ve.value)},style:{fontWeight:ve.value===i?600:400,backgroundColor:ve.value===i?"rgba(34, 139, 230, 0.1)":void 0},children:ve.label},ve.value))})]})]})}),j.jsx(Ao.HideWhenExpanded,{children:j.jsx(Xe,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:s})}),j.jsx(Pl,{label:"Hide controls (C)",children:j.jsx(su,{variant:"subtle",color:"gray",size:"sm","aria-label":"Hide controls",onClick:ve=>{ve.stopPropagation(),t(!1)},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),children:j.jsx(Ene,{size:14})})})]}),j.jsx(Ao.Contents,{children:j.jsxs(Xe,{pt:"0.375em",children:[o.length>0&&j.jsx(og,{id:"scene-select",label:"Scene",children:j.jsx(Fc,{id:"scene-select",placeholder:"Select scene",data:o,value:l,onChange:c,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),(d.length>0||h)&&j.jsx(og,{id:"splat-select",label:"Splat",children:j.jsx(Pl,{label:K??"",color:"red",position:"bottom",opened:K!==null,withArrow:!0,children:j.jsx(Fc,{id:"splat-select",placeholder:x!==void 0?"Select splat or paste .spz URL":"Select splat",data:d,value:p,onChange:ve=>{A(ve),Y(null),J(!1)},searchable:x!==void 0,searchValue:B,onSearchChange:ve=>{W(ve),ve&&Y(null)},onKeyDown:re,size:"xs",radius:"xs",clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})})}),(y?.control&&p!==null||$)&&m&&j.jsx(Rne,{scale:y?.scale??1,xOffset:y?.xOffset??0,yOffset:y?.yOffset??0,zOffset:y?.zOffset??0,roll:y?.roll??0,pitch:y?.pitch??0,yaw:y?.yaw??0,onCalibrate:m}),g.length>0&&j.jsx(og,{id:"policy-select",label:"Policy",children:j.jsx(Fc,{id:"policy-select",placeholder:"Select policy",data:g,value:_,onChange:b,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),w.length>0&&j.jsxs(j.Fragment,{children:[j.jsx(og,{id:"motion-select",label:"Motion",children:j.jsx(Fc,{id:"motion-select",placeholder:"Select motion",data:w,value:C,onChange:S,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),j.jsx(Xe,{pb:"0.5em",px:"xs",children:j.jsx(au,{label:"Show reference",checked:M,onChange:ve=>T(ve.currentTarget.checked),size:"xs"})})]}),oe.length>0&&L.filter(ve=>ve.config.type==="slider").length>0&&j.jsx(j.Fragment,{children:oe.map(ve=>{const Ne=Re(ve);return Ne.length===0?null:j.jsx(t4,{label:kne(ve),expandByDefault:!0,children:Ne.map(ct=>j.jsx(Nne,{command:ct,value:ye[ct.id]??0,onChange:fe,disabled:!R},ct.id))},ve)})}),j.jsx(Dd,{mb:"xs",mx:"xs"}),j.jsx(Xe,{px:"xs",pb:"xs",children:j.jsx(lh,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:j.jsx(bne,{size:14}),onClick:Ee,children:"Reset"})})]})})]})]})}function Jf(n,e,t){return Object.keys(n[e]).reduce((r,i)=>(r[i]=`var(--mantine-${t}-${i})`,r),{})}function KR(n,e){return n in e.breakpoints?e.breakpoints[n]:X_(n)}function Pne(n){const e=wD(c0,n),t=Jf(e,"fontSizes","font-size"),r=Jf(e,"lineHeights","line-height"),i=Jf(e,"shadows","shadow"),s=Jf(e,"radius","radius"),a=Jf(e,"spacing","spacing"),o=Object.keys(e.headings.sizes).reduce((c,d)=>(c[d]={fontSize:`var(--mantine-${d}-font-size)`,lineHeight:`var(--mantine-${d}-line-height)`,fontWeight:`var(--mantine-${d}-font-weight)`},c),{}),l=Object.keys(e.colors).reduce((c,d)=>(c[d]={0:`var(--mantine-color-${d}-0)`,1:`var(--mantine-color-${d}-1)`,2:`var(--mantine-color-${d}-2)`,3:`var(--mantine-color-${d}-3)`,4:`var(--mantine-color-${d}-4)`,5:`var(--mantine-color-${d}-5)`,6:`var(--mantine-color-${d}-6)`,7:`var(--mantine-color-${d}-7)`,8:`var(--mantine-color-${d}-8)`,9:`var(--mantine-color-${d}-9)`,filled:`var(--mantine-color-${d}-filled)`,filledHover:`var(--mantine-color-${d}-filled-hover)`,light:`var(--mantine-color-${d}-light)`,lightHover:`var(--mantine-color-${d}-light-hover)`,lightColor:`var(--mantine-color-${d}-light-color)`,outline:`var(--mantine-color-${d}-outline)`,outlineHover:`var(--mantine-color-${d}-outline-hover)`},c),{primary:"var(--mantine-primary-color-filled)",primaryColors:{0:"var(--mantine-primary-color-0)",1:"var(--mantine-primary-color-1)",2:"var(--mantine-primary-color-2)",3:"var(--mantine-primary-color-3)",4:"var(--mantine-primary-color-4)",5:"var(--mantine-primary-color-5)",6:"var(--mantine-primary-color-6)",7:"var(--mantine-primary-color-7)",8:"var(--mantine-primary-color-8)",9:"var(--mantine-primary-color-9)",filled:"var(--mantine-primary-color-filled)",filledHover:"var(--mantine-primary-color-filled-hover)",light:"var(--mantine-primary-color-light)",lightHover:"var(--mantine-primary-color-light-hover)",lightColor:"var(--mantine-primary-color-light-color)",outline:"var(--mantine-primary-color-outline)",outlineHover:"var(--mantine-primary-color-outline-hover)"},white:"var(--mantine-color-white)",black:"var(--mantine-color-black)",text:"var(--mantine-color-text)",body:"var(--mantine-color-body)",error:"var(--mantine-color-error)",placeholder:"var(--mantine-color-placeholder)",anchor:"var(--mantine-color-anchor)",default:"var(--mantine-color-default)",defaultHover:"var(--mantine-color-default-hover)",defaultColor:"var(--mantine-color-default-color)",defaultBorder:"var(--mantine-color-default-border)",dimmed:"var(--mantine-color-dimmed)",disabledBody:"var(--mantine-color-disabled)",disabledText:"var(--mantine-color-disabled-color)",disabledBorder:"var(--mantine-color-disabled-border)"});return{scale:"var(--mantine-scale)",cursorType:"var(--mantine-cursor-type)",webkitFontSmoothing:"var(--mantine-webkit-font-smoothing)",mozFontSmoothing:"var(--mantine-moz-font-smoothing)",lineHeight:"var(--mantine-line-height)",fontFamily:"var(--mantine-font-family)",fontFamilyMonospace:"var(--mantine-font-family-monospace)",fontFamilyHeadings:"var(--mantine-font-family-headings)",headingFontWeight:"var(--mantine-heading-font-weight)",radiusDefault:"var(--mantine-radius-default)",breakpoints:e.breakpoints,fontSizes:t,lineHeights:r,shadows:i,radius:s,headings:o,spacing:a,colors:l,rtlSelector:'[dir="rtl"] &',darkSelector:'[data-mantine-color-scheme="dark"] &',lightSelector:'[data-mantine-color-scheme="light"] &',smallerThan:c=>`(max-width: ${KR(c,e)})`,largerThan:c=>`(min-width: ${KR(c,e)})`}}const Ow={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:au.extend({defaultProps:{radius:"xs"}}),ColorInput:jE.extend({defaultProps:{radius:"xs"}}),Select:Fc.extend({defaultProps:{radius:"sm"}}),Textarea:qE.extend({defaultProps:{radius:"xs"}}),TextInput:aC.extend({defaultProps:{radius:"xs"}}),NumberInput:nC.extend({defaultProps:{radius:"xs"}}),Paper:Yc.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:su.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:lh.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};Pne(Ow);const r4=U.createContext(void 0),i4=()=>{const n=U.useContext(r4);if(!n)throw new Error("useLoading must be used within a LoadingProvider");return n},Lne=({children:n})=>{const[e,t]=U.useState(!1),r=U.useRef(0),i=U.useCallback(()=>{r.current+=1,r.current>0&&t(!0)},[]),s=U.useCallback(()=>{r.current=Math.max(0,r.current-1),r.current===0&&t(!1)},[]);return j.jsx(r4.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:n})},Fne=()=>{const{isLoading:n}=i4();return n?j.jsx("div",{className:"loader-overlay",children:j.jsx("div",{className:"loader-content",children:j.jsx(sh,{size:64,type:"bars"})})}):null},$w="panel",Gw="ref";function zne(){const n="/".replace(/\/+$/,"/");let t=window.location.pathname.replace(/^\/+|\/+$/g,"");const r=n.replace(/^\/+|\/+$/g,"");if(r&&(t===r?t="":t.startsWith(`${r}/`)&&(t=t.slice(r.length+1))),!t)return null;const i=t.split("/")[0];return i==="main"||i.includes(".")||i==="assets"?null:i}function _I(n){return n.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function Une(n,e){const t=n.replace(/\/+$/,"/"),r=new Set,i=(h,p)=>{if(h)try{const A=new URL(h,p||window.location.href).toString();r.add(A)}catch{r.add(h.replace(/\/+/g,"/"))}},s=`${window.location.origin}/`,a=new URL(t,s).toString();i("assets/config.json",a);const l=window.location.pathname.split("/").filter(Boolean);l.length>0&&l[l.length-1]==="index.html"&&l.pop(),l.length>0&&l[l.length-1]===(e??"main")&&l.pop();const c=`/${l.join("/")}${l.length?"/":""}`,d=`${window.location.origin}${c}`;return i("assets/config.json",d),i("assets/config.json"),i("../assets/config.json"),i("../../assets/config.json"),Array.from(r)}async function One(n,e){const r=new URLSearchParams(window.location.search).get("config"),i=Une(n,e);if(r)try{i.unshift(new URL(r,window.location.href).toString())}catch{i.unshift(r)}let s=null;for(const a of i)try{const o=await fetch(a,{cache:"no-store"});if(!o.ok)throw new Error(`Failed to fetch ${a}: ${o.status}`);const l=await o.text(),c=l.trim();if((o.headers.get("content-type")||"").includes("text/html")||c.startsWith("<!doctype")||c.startsWith("<html"))throw new Error(`Received HTML from ${a}`);try{return JSON.parse(l)}catch(h){throw new Error(`Invalid JSON from ${a}: ${h instanceof Error?h.message:String(h)}`)}}catch(o){s=o instanceof Error?o:new Error(String(o))}throw s??new Error("Failed to load config.json.")}function ZR(n,e){if(!n.scenes.length)return null;if(!e)return n.scenes[0];const t=e.trim().toLowerCase();return n.scenes.find(r=>r.name.toLowerCase()===t)||n.scenes.find(r=>_I(r.name)===t)||n.scenes[0]}function Y_(n,e){if(!n.policies.length)return null;const t=n.policies.find(s=>s.default)??n.policies[0];if(!e)return t.name;const r=e.trim().toLowerCase();return(n.policies.find(s=>s.name.toLowerCase()===r)||n.policies.find(s=>_I(s.name)===r))?.name??t.name}function Xf(n,e){return n?.motions?.length?(n.motions.find(r=>r.default)??n.motions[0]).name:null}function $ne(n){return new URLSearchParams(n).get($w)!=="0"}function Gne(n){return new URLSearchParams(n).get(Gw)!=="0"}function Hne(n){const t="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let r=t?`/${t}/`:"/";return n&&n!=="main"&&(r+=`${n}/`),r}function Vne({projectId:n,sceneName:e,policyName:t,panelVisible:r,showReference:i}){const s=Hne(n),a=new URLSearchParams(window.location.search);e?a.set("scene",e):a.delete("scene"),t?a.set("policy",t):a.delete("policy"),r?a.delete($w):a.set($w,"0"),i?a.delete(Gw):a.set(Gw,"0");const o=a.toString(),l=s+(o?`?${o}`:"")+window.location.hash;window.history.replaceState({},"",l)}function jne(){const[n,e]=U.useState(null),[t,r]=U.useState(null),[i,s]=U.useState(null),[a,o]=U.useState(null),[l,c]=U.useState(null),[d,h]=U.useState(()=>Gne(window.location.search)),[p,A]=U.useState(null),[y,m]=U.useState(null),[x,g]=U.useState(null),[_,b]=U.useState(()=>$ne(window.location.search)),w=U.useRef(null),{showLoading:C,hideLoading:S}=i4(),M=U.useMemo(()=>zne(),[]),T=U.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),R=U.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);U.useEffect(()=>{C(),One("/",M).then(X=>{e(X);const ge=X.projects.find(Ce=>M===null?Ce.id===null:Ce.id===M);if(!ge)throw new Error(`Project "${M??"(main)"}" not found in config.json.`);r(ge);const te=ZR(ge,T);s(te);const ee=te?Y_(te,R):null;o(ee);const ie=te?.policies.find(Ce=>Ce.name===ee)??null;c(Xf(ie))}).catch(X=>{console.error("Failed to load config:",X),A(X.message||"Failed to load config."),S()})},[M,T,R,C,S]);const k=U.useMemo(()=>{if(!t||!i)return null;const X=t.id?t.id:"main",ge=i.path?i.path:`scene/${_I(i.name)}/scene.xml`;return`${X}/assets/${ge}`.replace(/\/+/g,"/")},[t,i]),G=U.useMemo(()=>!i||!a?null:i.policies.find(X=>X.name===a)??null,[i,a]),P=U.useMemo(()=>!t||!G?.config?null:`${t.id?t.id:"main"}/assets/${G.config}`.replace(/\/+/g,"/"),[t,G]),V=U.useMemo(()=>G?.motions?.length?G.motions.map(X=>({value:X.name,label:X.name})):[],[G]),B=U.useMemo(()=>{if(!t||!i?.splats?.length)return[];const X=t.id?t.id:"main";return i.splats.map(ge=>{if(ge.path){const te=`${X}/assets/${ge.path}`.replace(/\/+/g,"/");return{...ge,url:te}}return ge})},[t,i?.splats]),W=U.useMemo(()=>y?B.find(X=>X.name===y)??null:x?{name:"Custom",url:x}:null,[B,y,x]),K=U.useMemo(()=>n?n.projects.map(X=>({value:X.id??"main",label:X.name||(X.id??"Main")})):[],[n]),Y=U.useMemo(()=>t?t.scenes.map(X=>({value:X.name,label:X.name})):[],[t]),$=U.useMemo(()=>!i||!i.policies?[]:i.policies.map(X=>({value:X.name,label:X.name})),[i]),J=t?t.id??"main":null,re=i?.name??null,L=U.useCallback(X=>{A(X.message),S()},[S]),H=U.useCallback(()=>{S()},[S]);U.useEffect(()=>{const X=i?.splats?.[0];m(X?X.name:null),g(null)},[i]);const oe=U.useCallback(X=>{w.current=X},[]);U.useEffect(()=>{c(Xf(G)),h(!!G?.motions?.length)},[G]);const Ae=U.useMemo(()=>i?.splats?.length?i.splats.map(X=>({value:X.name,label:X.name})):[],[i?.splats]),ye=U.useCallback(X=>{if(X===null)w.current?.setSplat(null);else{const ge=B.find(te=>te.name===X);ge&&w.current?.setSplat(ge)}m(X),g(null)},[B]),he=U.useCallback(async X=>{try{if(!(await fetch(X,{method:"HEAD"})).ok)return!1}catch{return!1}return w.current?.setSplat({name:"Custom",url:X}),g(X),!0},[]),fe=U.useCallback((X,ge,te,ee,ie,Ce,be)=>{const de=W??(x?{name:"Custom",url:x}:null);de&&w.current?.calibrateSplat({...de,scale:X,xOffset:ge,yOffset:te,zOffset:ee,roll:ie,pitch:Ce,yaw:be})},[W,x]),Ee=U.useCallback(X=>{Vne({projectId:X.projectId??t?.id??null,sceneName:X.sceneName??i?.name??null,policyName:X.policyName??a,panelVisible:X.panelVisible??_,showReference:X.showReference??d})},[t?.id,i?.name,a,_,d]),Re=U.useCallback(X=>{if(!n||!X)return;const ge=X==="main"?null:X,te=n.projects.find(be=>(be.id??"main")===(ge??"main"));if(!te)return;C(),r(te);const ee=ZR(te,null);s(ee);const ie=ee?Y_(ee,null):null;o(ie);const Ce=ee?.policies.find(be=>be.name===ie)??null;c(Xf(Ce)),Ee({projectId:te.id,sceneName:ee?.name??null,policyName:ie})},[n,C,Ee]),ve=U.useCallback(X=>{if(!t||!X)return;const ge=t.scenes.find(ie=>ie.name===X);if(!ge)return;C(),s(ge);const te=Y_(ge,null);o(te);const ee=ge.policies.find(ie=>ie.name===te)??null;c(Xf(ee)),Ee({projectId:t.id,sceneName:X,policyName:te})},[t,C,Ee]),Ne=U.useCallback(X=>{X!==a&&C(),o(X);const ge=i?.policies.find(te=>te.name===X)??null;c(Xf(ge)),Ee({policyName:X})},[a,C,Ee]),ct=U.useCallback(X=>{b(X),Ee({panelVisible:X})},[Ee]),Ge=U.useCallback(X=>{c(X),w.current?.setSelectedMotion(X)},[]),F=U.useCallback(X=>{h(X),w.current?.setReferenceVisible(X),Ee({showReference:X})},[Ee]);return p?j.jsx(tb,{theme:Ow,defaultColorScheme:"auto",children:j.jsx("div",{className:"app",children:j.jsxs("div",{className:"hud hud-error",children:[j.jsx("h1",{className:"hud-title",children:"mjswan"}),j.jsx("p",{className:"hud-message",children:p})]})})}):!t||!i||!k?null:j.jsx(tb,{theme:Ow,defaultColorScheme:"auto",children:j.jsxs("div",{className:"app",children:[j.jsx(Fne,{}),j.jsx(Qne,{visible:_,onVisibleChange:ct,projects:K,projectValue:J,projectLabel:t?.name??"mjswan",onProjectChange:Re,scenes:Y,sceneValue:re,onSceneChange:ve,splats:Ae,splatSection:i?.splatSection??!1,splatValue:y,onSplatChange:ye,splatConfig:W,onCalibrateSplat:fe,onSplatUrlLoad:he,policies:$,policyValue:a,onPolicyChange:Ne,motions:V,motionValue:l,onMotionChange:Ge,showReferenceMotion:d,onShowReferenceMotionChange:F,commandsEnabled:!!P}),j.jsx(mne,{scenePath:k,baseUrl:"/",policyConfigPath:P,splatConfig:W,cameraConfig:i?.camera,eventsConfig:i?.events,terrainData:i?.terrainData,selectedMotion:l,showReferenceMotion:d,onError:L,onReady:H,onRuntimeReady:oe})]})})}function Wne(){return j.jsx(Lne,{children:j.jsx(jne,{})})}const eD=document.getElementById("root");eD&&W4.createRoot(eD).render(j.jsx(On.StrictMode,{children:j.jsx(Wne,{})}));export{RH as _};
|
|
15613
|
+
${s}`,o=t.createShaderModule({code:a,label:n.name});un("verbose",()=>`[WebGPU] ${n.name} shader code: ${a}`);let l=t.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:n.name});return Zs(n.name),{programInfo:n,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(n){let e=typeof n=="number"?n:n.x,t=typeof n=="number"?1:n.y||1,r=typeof n=="number"?1:n.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&t<=i&&r<=i)return[e,t,r];let s=e*t*r,a=Math.ceil(Math.sqrt(s));if(a>i){if(a=Math.ceil(Math.cbrt(s)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),kz={};vh(kz,{WebGpuBackend:()=>Nz});var UR,OR,$R,Nz,Kte=et(()=>{xs(),Lt(),No(),VP(),lte(),Jte(),Xte(),UR=(n,e)=>{if(e.length!==n.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${n.length}.`);let t=[];for(let r=0;r<n.length;++r){let i=n[r].dataType;switch(e[r]){case"none":{t.push("");break}case"type":{t.push(`${i}`);break}case"rank":{let s=n[r].dims.length;t.push(`${i};${s}`);break}case"dims":{let s=n[r].dims.join(",");t.push(`${i};${s}`);break}default:throw new Error(`unsupported input dependency: ${e[r]}`)}}return t.join("|")},OR=(n,e,t)=>{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${UR(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},$R=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},Nz=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let n=this.kernelCustomData.get(this.currentKernelId);return n||(n={},this.kernelCustomData.set(this.currentKernelId,n)),n}async initialize(n,e){this.env=n;let t=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},i=s=>e.features.has(s)&&t.push(s)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await e.requestDevice(r),this.adapterInfo=new $R(e.info||await e.requestAdapterInfo()),this.gpuDataManager=qP(this),this.programManager=new Dz(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,nI(n.logLevel,!!n.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let n=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Fa(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(n.getMappedRange()),t=this.pendingQueries.get(n);for(let r=0;r<e.length/2;r++){let i=t[r],s=i.kernelId,a=this.kernels.get(s),o=a.kernelType,l=a.kernelName,c=i.programName,d=i.inputTensorViews,h=i.outputTensorViews,p=e[r*2],A=e[r*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=p);let y=Number(p-this.queryTimeBase),m=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(y)||!Number.isSafeInteger(m))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(x=>({dims:x.dims,dataType:po(x.dataType)})),outputsMetadata:h.map(x=>({dims:x.dims,dataType:po(x.dataType)})),kernelId:s,kernelType:o,kernelName:l,programName:c,startTime:y,endTime:m});else{let x="";d.forEach((_,b)=>{x+=`input[${b}]: [${_.dims}] | ${po(_.dataType)}, `});let g="";h.forEach((_,b)=>{g+=`output[${b}]: [${_.dims}] | ${po(_.dataType)}, `}),console.log(`[profiling] kernel "${s}|${o}|${l}|${c}" ${x}${g}start time: ${y} ns, execution time: ${m-y} ns`)}qg("GPU",`${c}::${p}::${A}`)}n.unmap(),this.pendingQueries.delete(n)}),Zs()}run(n,e,t,r,i,s){Fa(n.name);let a=[];for(let _=0;_<e.length;++_){let b=e[_].data;if(b===0)continue;let w=this.gpuDataManager.get(b);if(!w)throw new Error(`no GPU data for input: ${b}`);a.push(w)}let{outputs:o,dispatchGroup:l,programUniforms:c}=n.getRunData(e),d=t.length===0?o.map((_,b)=>b):t;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let h=[],p=[];for(let _=0;_<o.length;++_){if(!Number.isInteger(d[_])||d[_]<-3||d[_]>=s)throw new Error(`Invalid output index: ${d[_]}`);if(d[_]===-3)continue;let b=d[_]===-1,w=d[_]===-2,C=b||w?i(o[_].dataType,o[_].dims):r(d[_],o[_].dataType,o[_].dims);if(h.push(C),C.data===0)continue;let S=this.gpuDataManager.get(C.data);if(!S)throw new Error(`no GPU data for output: ${C.data}`);if(b&&this.temporaryData.push(S),w){let M=this.kernelPersistentData.get(this.currentKernelId);M||(M=[],this.kernelPersistentData.set(this.currentKernelId,M)),M.push(S)}p.push(S)}if(a.length!==e.length||p.length!==h.length){if(p.length===0)return Zs(n.name),h;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let A;if(c){let _=0,b=[];c.forEach(M=>{let T=typeof M.data=="number"?[M.data]:M.data;if(T.length===0)return;let R=M.type===10?2:4,k,G;M.type===10?(G=T.length>4?16:T.length>2?8:T.length*R,k=T.length>4?16:R*T.length):(G=T.length<=2?T.length*R:16,k=16),_=Math.ceil(_/G)*G,b.push(_);let P=M.type===10?8:4;_+=T.length>4?Math.ceil(T.length/P)*k:T.length*R});let w=16;_=Math.ceil(_/w)*w;let C=new ArrayBuffer(_);c.forEach((M,T)=>{let R=b[T],k=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(C,R,k.length).set(k);else if(M.type===12)new Uint32Array(C,R,k.length).set(k);else if(M.type===10)new Uint16Array(C,R,k.length).set(k);else if(M.type===1)new Float32Array(C,R,k.length).set(k);else throw new Error(`Unsupported uniform type: ${po(M.type)}`)});let S=this.gpuDataManager.create(_,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(S.buffer,0,C,0,_),this.gpuDataManager.release(S.id),A={offset:0,size:_,buffer:S.buffer}}let y=this.programManager.normalizeDispatchGroupSize(l),m=y[1]===1&&y[2]===1,x=OR(n,e,m),g=this.programManager.getArtifact(x);if(g||(g=this.programManager.build(n,y),this.programManager.setArtifact(x,g),un("info",()=>`[artifact] key: ${x}, programName: ${n.name}`)),c&&g.uniformVariablesInfo){if(c.length!==g.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${g.uniformVariablesInfo.length}, got ${c.length} in program "${g.programInfo.name}".`);for(let _=0;_<c.length;_++){let b=c[_],w=b.type,C=typeof b.data=="number"?1:b.data.length,[S,M]=g.uniformVariablesInfo[_];if(w!==S||C!==M)throw new Error(`Uniform variable ${_} mismatch: expect type ${S} with size ${M}, got type ${w} with size ${C} in program "${g.programInfo.name}".`)}}if(un("info",()=>`[ProgramManager] run "${n.name}" (key=${x}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let _={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(_),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(_)}return this.programManager.run(g,a,p,y,A),Zs(n.name),h}upload(n,e){this.gpuDataManager.upload(n,e)}memcpy(n,e){this.gpuDataManager.memcpy(n,e)}async download(n,e){await this.gpuDataManager.download(n,e)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,e,t,r){let i=Rz.get(n);if(!i)throw new Error(`kernel not implemented: ${n}`);let s={kernelType:n,kernelName:r,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(e,s)}releaseKernel(n){let e=this.kernelPersistentData.get(n);if(e){for(let t of e)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,e,t){let r=this.kernels.get(n);if(!r)throw new Error(`kernel not created: ${n}`);let i=r.kernelType,s=r.kernelName,a=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${s}" is not allowed to be called recursively`);this.currentKernelId=n,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),un("info",()=>`[WebGPU] Start to run kernel "[${i}] ${s}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(e,o[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${s}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${s}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,e,t,r){let i=this.sessionExternalDataMapping.get(n);i||(i=new Map,this.sessionExternalDataMapping.set(n,i));let s=i.get(e),a=this.gpuDataManager.registerExternalBuffer(t,r,s);return i.set(e,[a,t]),a}unregisterBuffers(n){let e=this.sessionExternalDataMapping.get(n);e&&(e.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let e=this.gpuDataManager.get(n);if(!e)throw new Error(`no GPU data for buffer: ${n}`);return e.buffer}createDownloader(n,e,t){return async()=>{let r=await Bw(this,n,e);return rI(r.buffer,t)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){un("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){un("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){un("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),t=n.length;this.pendingKernels=[];for(let r=0;r<t;r++){let i=this.getComputePassEncoder(),s=n[r];this.writeTimestamp(this.pendingDispatchNumber*2),i.setPipeline(s.computePipeline),i.setBindGroup(0,s.bindGroup),i.dispatchWorkgroups(...s.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(e[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),Qz={};vh(Qz,{init:()=>Pz});var rg,GR,Pz,Zte=et(()=>{Lt(),No(),jt(),ote(),rg=class Lz{constructor(e,t,r,i){this.module=e,this.dataType=t,this.data=r,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Le.size(e)!==Le.size(this.dims))throw new Error("Invalid new shape");return new Lz(this.module,this.dataType,this.data,e)}},GR=class{constructor(n,e,t){this.module=n,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let r=n.PTR_SIZE,i=t/n.PTR_SIZE,s=r===4?"i32":"i64";this.opKernelContext=Number(n.getValue(r*i++,s));let a=Number(n.getValue(r*i++,s));this.outputCount=Number(n.getValue(r*i++,s)),this.customDataOffset=Number(n.getValue(r*i++,"*")),this.customDataSize=Number(n.getValue(r*i++,s));let o=[];for(let l=0;l<a;l++){let c=Number(n.getValue(r*i++,s)),d=Number(n.getValue(r*i++,"*")),h=Number(n.getValue(r*i++,s)),p=[];for(let A=0;A<h;A++)p.push(Number(n.getValue(r*i++,s)));o.push(new rg(n,c,d,p))}this.inputs=o}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(n,e){let t=e?.inputs?.map(a=>typeof a=="number"?this.inputs[a]:a)??this.inputs,r=e?.outputs??[],i=(a,o,l)=>new rg(this.module,o,this.output(a,l),l),s=(a,o)=>{let l=Qc(a,o);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new rg(this.module,a,c,o)};return this.backend.run(n,t,r,i,s,this.outputCount)}output(n,e){let t=this.module.stackSave();try{let r=this.module.PTR_SIZE,i=r===4?"i32":"i64",s=this.module.stackAlloc((1+e.length)*r);this.module.setValue(s,e.length,i);for(let a=0;a<e.length;a++)this.module.setValue(s+r*(a+1),e[a],i);return this.module._JsepOutput(this.opKernelContext,n,s)}catch(r){throw new Error(`Failed to generate kernel's output[${n}] with dims [${e}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${r}`)}finally{this.module.stackRestore(t)}}},Pz=async(n,e,t,r)=>{let i=e.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(n==="webgpu"){let s=(Kte(),Lp(kz)).WebGpuBackend,a=new s;await a.initialize(t,r),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,l,c,d=!1)=>{if(d)un("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(l)}, size=${Number(c)}`),a.memcpy(Number(o),Number(l));else{un("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let h=e.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(c));a.upload(Number(l),h)}},async(o,l,c)=>{un("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${l}, size=${c}`),await a.download(Number(o),()=>e.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(o,l,c)=>a.createKernel(o,Number(l),c,e.UTF8ToString(e._JsepGetNodeName(Number(l)))),o=>a.releaseKernel(o),(o,l,c,d)=>{un("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${o}, contextDataOffset=${l}`);let h=new GR(e,a,Number(l));return a.computeKernel(Number(o),h,d)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let s=new WP(t);i("webnn",[s,()=>s.reserveTensorId(),a=>s.releaseTensorId(a),async(a,o,l,c,d)=>s.ensureTensor(a,o,l,c,d),(a,o)=>{s.uploadTensor(a,o)},async(a,o)=>s.downloadTensor(a,o),(a,o)=>s.registerMLContext(a,o),!!t.trace])}}}),HR,pI,AI,Il,VR,H_,t0,mI,gI,V_,yI,xI,vI,Fz=et(()=>{xs(),ite(),ste(),Lt(),cu(),KC(),OP(),HR=(n,e)=>{kn()._OrtInit(n,e)!==0&&wn("Can't initialize onnxruntime.")},pI=async n=>{HR(n.wasm.numThreads,Jg(n.logLevel))},AI=async(n,e)=>{kn().asyncInit?.();let t=n.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(t){if(typeof t.limits!="object"||typeof t.features!="object"||typeof t.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=n.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let i=n.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:i}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let r=(Zte(),Lp(Qz)).init;e==="webgpu"&&await r("webgpu",kn(),n,t),e==="webnn"&&await r("webnn",kn(),n)}},Il=new Map,VR=n=>{let e=kn(),t=e.stackSave();try{let r=e.PTR_SIZE,i=e.stackAlloc(2*r);e._OrtGetInputOutputCount(n,i,i+r)!==0&&wn("Can't get session input/output count.");let s=r===4?"i32":"i64";return[Number(e.getValue(i,s)),Number(e.getValue(i+r,s))]}finally{e.stackRestore(t)}},H_=(n,e)=>{let t=kn(),r=t.stackSave(),i=0;try{let s=t.PTR_SIZE,a=t.stackAlloc(2*s);t._OrtGetInputOutputMetadata(n,e,a,a+s)!==0&&wn("Can't get session input/output metadata.");let o=Number(t.getValue(a,"*"));i=Number(t.getValue(a+s,"*"));let l=t.HEAP32[i/4];if(l===0)return[o,0];let c=t.HEAPU32[i/4+1],d=[];for(let h=0;h<c;h++){let p=Number(t.getValue(i+8+h*s,"*"));d.push(p!==0?t.UTF8ToString(p):Number(t.getValue(i+8+(h+c)*s,"*")))}return[o,l,d]}finally{t.stackRestore(r),i!==0&&t._OrtFree(i)}},t0=n=>{let e=kn(),t=e._malloc(n.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,t),[t,n.byteLength]},mI=async(n,e)=>{let t,r,i=kn();Array.isArray(n)?[t,r]=n:n.buffer===i.HEAPU8.buffer?[t,r]=[n.byteOffset,n.byteLength]:[t,r]=t0(n);let s=0,a=0,o=0,l=[],c=[],d=[];try{if([a,l]=await UP(e),e?.externalData&&i.mountExternalData){let w=[];for(let C of e.externalData){let S=typeof C=="string"?C:C.path;w.push(tI(typeof C=="string"?C:C.data).then(M=>{i.mountExternalData(S,M)}))}await Promise.all(w)}for(let w of e?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof w!="string"){let C=w,S=C?.context,M=C?.gpuDevice,T=C?.deviceType,R=C?.powerPreference;S?i.currentContext=S:M?i.currentContext=await i.webnnCreateMLContext(M):i.currentContext=await i.webnnCreateMLContext({deviceType:T,powerPreference:R})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(t,r,a),i.webgpuOnCreateSession?.(s),s===0&&wn("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=VR(s),A=!!e?.enableGraphCapture,y=[],m=[],x=[],g=[],_=[];for(let w=0;w<h;w++){let[C,S,M]=H_(s,w);C===0&&wn("Can't get an input name."),c.push(C);let T=i.UTF8ToString(C);y.push(T),x.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M})}for(let w=0;w<p;w++){let[C,S,M]=H_(s,w+h);C===0&&wn("Can't get an output name."),d.push(C);let T=i.UTF8ToString(C);m.push(T),g.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M});{if(A&&e?.preferredOutputLocation===void 0){_.push("gpu-buffer");continue}let R=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[T]??"cpu",k=i.webnnIsGraphOutput;if(R==="cpu"&&k&&k(s,T)){_.push("ml-tensor-cpu-output");continue}if(R!=="cpu"&&R!=="cpu-pinned"&&R!=="gpu-buffer"&&R!=="ml-tensor")throw new Error(`Not supported preferred output location: ${R}.`);if(A&&R!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${R}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(R)}}let b=null;return _.some(w=>w==="gpu-buffer"||w==="ml-tensor"||w==="ml-tensor-cpu-output")&&(o=i._OrtCreateBinding(s),o===0&&wn("Can't create IO binding."),b={handle:o,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(w=>w==="ml-tensor-cpu-output"?"ml-tensor":w).map(w=>Iw(w))}),Il.set(s,[s,c,d,b,A,!1]),[s,y,m,x,g]}catch(h){throw c.forEach(p=>i._OrtFree(p)),d.forEach(p=>i._OrtFree(p)),o!==0&&i._OrtReleaseBinding(o)!==0&&wn("Can't release IO binding."),s!==0&&i._OrtReleaseSession(s)!==0&&wn("Can't release session."),h}finally{i._free(t),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&wn("Can't release session options."),l.forEach(h=>i._free(h)),i.unmountExternalData?.()}},gI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error(`cannot release session. invalid session id: ${n}`);let[r,i,s,a,o]=t;a&&(o&&e._OrtClearBoundOutputs(a.handle)!==0&&wn("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&wn("Can't release IO binding.")),e.jsepOnReleaseSession?.(n),e.webnnOnReleaseSession?.(n),e.webgpuOnReleaseSession?.(n),i.forEach(l=>e._OrtFree(l)),s.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(r)!==0&&wn("Can't release session."),Il.delete(n)},V_=async(n,e,t,r,i,s,a=!1)=>{if(!n){e.push(0);return}let o=kn(),l=o.PTR_SIZE,c=n[0],d=n[1],h=n[3],p=h,A,y;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let g=n[2].gpuBuffer;y=Qc(Nc(c),d);{let _=o.jsepRegisterBuffer;if(!_)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=_(r,s,g,y)}}else if(h==="ml-tensor"){let g=n[2].mlTensor;y=Qc(Nc(c),d);let _=o.webnnRegisterMLTensor;if(!_)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=_(r,g,Nc(c),d)}else{let g=n[2];if(Array.isArray(g)){y=l*g.length,A=o._malloc(y),t.push(A);for(let _=0;_<g.length;_++){if(typeof g[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);o.setValue(A+_*l,Gs(g[_],t),"*")}}else{let _=o.webnnIsGraphInput,b=o.webnnIsGraphOutput;if(c!=="string"&&_&&b){let w=o.UTF8ToString(i);if(_(r,w)||b(r,w)){let C=Nc(c);y=Qc(C,d),p="ml-tensor";let S=o.webnnCreateTemporaryTensor,M=o.webnnUploadTensor;if(!S||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let T=await S(r,C,d);M(T,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),A=T}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}}let m=o.stackSave(),x=o.stackAlloc(4*d.length);try{d.forEach((_,b)=>o.setValue(x+b*l,_,l===4?"i32":"i64"));let g=o._OrtCreateTensor(Nc(c),A,y,x,d.length,Iw(p));g===0&&wn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(g)}finally{o.stackRestore(m)}},yI=async(n,e,t,r,i,s)=>{let a=kn(),o=a.PTR_SIZE,l=Il.get(n);if(!l)throw new Error(`cannot run inference. invalid session id: ${n}`);let c=l[0],d=l[1],h=l[2],p=l[3],A=l[4],y=l[5],m=e.length,x=r.length,g=0,_=[],b=[],w=[],C=[],S=[],M=a.stackSave(),T=a.stackAlloc(m*o),R=a.stackAlloc(m*o),k=a.stackAlloc(x*o),G=a.stackAlloc(x*o);try{[g,_]=zP(s),jc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)await V_(t[W],b,C,n,d[e[W]],e[W],A);for(let W=0;W<x;W++)await V_(i[W],w,C,n,h[r[W]],m+r[W],A);Wc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)a.setValue(T+W*o,b[W],"*"),a.setValue(R+W*o,d[e[W]],"*");for(let W=0;W<x;W++)a.setValue(k+W*o,w[W],"*"),a.setValue(G+W*o,h[r[W]],"*");if(p&&!y){let{handle:W,outputPreferredLocations:K,outputPreferredLocationsEncoded:Y}=p;if(d.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${d.length}).`);jc("wasm bindInputsOutputs");for(let $=0;$<m;$++){let J=e[$];await a._OrtBindInput(W,d[J],b[$])!==0&&wn(`Can't bind input[${$}] for session=${n}.`)}for(let $=0;$<x;$++){let J=r[$];i[$]?.[3]?(S.push(w[$]),a._OrtBindOutput(W,h[J],w[$],0)!==0&&wn(`Can't bind pre-allocated output[${$}] for session=${n}.`)):a._OrtBindOutput(W,h[J],0,Y[J])!==0&&wn(`Can't bind output[${$}] to ${K[$]} for session=${n}.`)}Wc("wasm bindInputsOutputs"),Il.set(n,[c,d,h,p,A,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let P;p?P=await a._OrtRunWithBinding(c,p.handle,x,k,g):P=await a._OrtRun(c,R,T,m,G,x,k,g),P!==0&&wn("failed to call OrtRun().");let V=[],B=[];jc("wasm ProcessOutputTensor");for(let W=0;W<x;W++){let K=Number(a.getValue(k+W*o,"*"));if(K===w[W]||S.includes(w[W])){V.push(i[W]),K!==w[W]&&a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.");continue}let Y=a.stackSave(),$=a.stackAlloc(4*o),J=!1,re,L=0;try{a._OrtGetTensorData(K,$,$+o,$+2*o,$+3*o)!==0&&wn(`Can't access output tensor data on index ${W}.`);let H=o===4?"i32":"i64",oe=Number(a.getValue($,H));L=a.getValue($+o,"*");let Ae=a.getValue($+o*2,"*"),ye=Number(a.getValue($+o*3,H)),he=[];for(let Re=0;Re<ye;Re++)he.push(Number(a.getValue(Ae+Re*o,H)));a._OrtFree(Ae)!==0&&wn("Can't free memory for tensor dims.");let fe=he.reduce((Re,ve)=>Re*ve,1);re=po(oe);let Ee=p?.outputPreferredLocations[r[W]];if(re==="string"){if(Ee==="gpu-buffer"||Ee==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Re=[];for(let ve=0;ve<fe;ve++){let Ne=a.getValue(L+ve*o,"*"),ct=a.getValue(L+(ve+1)*o,"*"),Ge=ve===fe-1?void 0:ct-Ne;Re.push(a.UTF8ToString(Ne,Ge))}V.push([re,he,Re,"cpu"])}else if(Ee==="gpu-buffer"&&fe>0){let Re=a.jsepGetBuffer;if(!Re)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ve=Re(L),Ne=Qc(oe,fe);if(Ne===void 0||!ZC(re))throw new Error(`Unsupported data type: ${re}`);J=!0,V.push([re,he,{gpuBuffer:ve,download:a.jsepCreateDownloader(ve,Ne,re),dispose:()=>{a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.")}},"gpu-buffer"])}else if(Ee==="ml-tensor"&&fe>0){let Re=a.webnnEnsureTensor,ve=a.webnnIsGraphInputOutputTypeSupported;if(!Re||!ve)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Qc(oe,fe)===void 0||!eI(re))throw new Error(`Unsupported data type: ${re}`);if(!ve(n,re,!1))throw new Error(`preferredLocation "ml-tensor" for ${re} output is not supported by current WebNN Context.`);let Ne=await Re(n,L,oe,he,!1);J=!0,V.push([re,he,{mlTensor:Ne,download:a.webnnCreateMLTensorDownloader(L,re),dispose:()=>{a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K)}},"ml-tensor"])}else if(Ee==="ml-tensor-cpu-output"&&fe>0){let Re=a.webnnCreateMLTensorDownloader(L,re)(),ve=V.length;J=!0,B.push((async()=>{let Ne=[ve,await Re];return a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K),Ne})()),V.push([re,he,[],"cpu"])}else{let Re=Z0(re),ve=new Re(fe);new Uint8Array(ve.buffer,ve.byteOffset,ve.byteLength).set(a.HEAPU8.subarray(L,L+ve.byteLength)),V.push([re,he,ve,"cpu"])}}finally{a.stackRestore(Y),re==="string"&&L&&a._free(L),J||a._OrtReleaseTensor(K)}}p&&!A&&(a._OrtClearBoundOutputs(p.handle)!==0&&wn("Can't clear bound outputs."),Il.set(n,[c,d,h,p,A,!1]));for(let[W,K]of await Promise.all(B))V[W][2]=K;return Wc("wasm ProcessOutputTensor"),V}finally{a.webnnOnRunEnd?.(c),a.stackRestore(M),b.forEach(P=>a._OrtReleaseTensor(P)),w.forEach(P=>a._OrtReleaseTensor(P)),C.forEach(P=>a._free(P)),g!==0&&a._OrtReleaseRunOptions(g),_.forEach(P=>a._free(P))}},xI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error("invalid session id");let r=t[0],i=e._OrtEndProfiling(r);i===0&&wn("Can't get an profile file name."),e._OrtFree(i)},vI=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),Sl,ts,Ed,qf,Yf,ig,j_,sg,Cc,Ic,jR,zz,Uz,Oz,$z,Gz,Hz,Vz,jz=et(()=>{xs(),Fz(),cu(),JC(),Sl=()=>!!Dn.wasm.proxy&&typeof document<"u",Ed=!1,qf=!1,Yf=!1,sg=new Map,Cc=(n,e)=>{let t=sg.get(n);t?t.push(e):sg.set(n,[e])},Ic=()=>{if(Ed||!qf||Yf||!ts)throw new Error("worker not ready")},jR=n=>{switch(n.data.type){case"init-wasm":Ed=!1,n.data.err?(Yf=!0,j_[1](n.data.err)):(qf=!0,j_[0]()),ig&&(URL.revokeObjectURL(ig),ig=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=sg.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},zz=async()=>{if(!qf){if(Ed)throw new Error("multiple calls to 'initWasm()' detected.");if(Yf)throw new Error("previous call to 'initWasm()' failed.");if(Ed=!0,Sl())return new Promise((n,e)=>{ts?.terminate(),LP().then(([t,r])=>{try{ts=r,ts.onerror=s=>e(s),ts.onmessage=jR,j_=[n,e];let i={type:"init-wasm",in:Dn};!i.in.wasm.wasmPaths&&(t||Cw)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href}),ts.postMessage(i),ig=t}catch(i){e(i)}},e)});try{await XC(Dn.wasm),await pI(Dn),qf=!0}catch(n){throw Yf=!0,n}finally{Ed=!1}}},Uz=async n=>{if(Sl())return Ic(),new Promise((e,t)=>{Cc("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Dn}};ts.postMessage(r)});await AI(Dn,n)},Oz=async n=>Sl()?(Ic(),new Promise((e,t)=>{Cc("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};ts.postMessage(r,[n.buffer])})):t0(n),$z=async(n,e)=>{if(Sl()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ic(),new Promise((t,r)=>{Cc("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},s=[];n instanceof Uint8Array&&s.push(n.buffer),ts.postMessage(i,s)})}else return mI(n,e)},Gz=async n=>{if(Sl())return Ic(),new Promise((e,t)=>{Cc("release",[e,t]);let r={type:"release",in:n};ts.postMessage(r)});gI(n)},Hz=async(n,e,t,r,i,s)=>{if(Sl()){if(t.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ic(),new Promise((a,o)=>{Cc("run",[a,o]);let l=t,c={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:s}};ts.postMessage(c,vI(l))})}else return yI(n,e,t,r,i,s)},Vz=async n=>{if(Sl())return Ic(),new Promise((e,t)=>{Cc("end-profiling",[e,t]);let r={type:"end-profiling",in:n};ts.postMessage(r)});xI(n)}}),W_,WR,Wz,ene=et(()=>{xs(),jz(),Lt(),YC(),OP(),W_=(n,e)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[n.type,n.dims,{mlTensor:n.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${n.location} for ${e()}`)}},WR=n=>{switch(n[3]){case"cpu":return new ti(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!ZC(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:r,dispose:i}=n[2];return ti.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}case"ml-tensor":{let e=n[0];if(!eI(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:r,dispose:i}=n[2];return ti.fromMLTensor(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},Wz=class{async fetchModelAndCopyToWasmMemory(n){return Oz(await tI(n))}async loadModel(n,e){Fa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await $z(t,e),Zs()}async dispose(){return Gz(this.sessionId)}async run(n,e,t){Fa();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],A=h[1],y=this.inputNames.indexOf(p);if(y===-1)throw new Error(`invalid input '${p}'`);r.push(A),i.push(y)});let s=[],a=[];Object.entries(e).forEach(h=>{let p=h[0],A=h[1],y=this.outputNames.indexOf(p);if(y===-1)throw new Error(`invalid output '${p}'`);s.push(A),a.push(y)});let o=r.map((h,p)=>W_(h,()=>`input "${this.inputNames[i[p]]}"`)),l=s.map((h,p)=>h?W_(h,()=>`output "${this.outputNames[a[p]]}"`):null),c=await Hz(this.sessionId,i,o,a,l,t),d={};for(let h=0;h<c.length;h++)d[this.outputNames[a[h]]]=s[h]??WR(c[h]);return Zs(),d}startProfiling(){}endProfiling(){Vz(this.sessionId)}}}),qz={};vh(qz,{OnnxruntimeWebAssemblyBackend:()=>Uw,initializeFlags:()=>zw,wasmBackend:()=>Yz});var zw,Uw,Yz,tne=et(()=>{xs(),jz(),ene(),zw=()=>{(typeof Dn.wasm.initTimeout!="number"||Dn.wasm.initTimeout<0)&&(Dn.wasm.initTimeout=0);let n=Dn.wasm.simd;if(typeof n!="boolean"&&n!==void 0&&n!=="fixed"&&n!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${n}". Reset it to \`false\` and ignore SIMD feature checking.`),Dn.wasm.simd=!1),typeof Dn.wasm.proxy!="boolean"&&(Dn.wasm.proxy=!1),typeof Dn.wasm.trace!="boolean"&&(Dn.wasm.trace=!1),typeof Dn.wasm.numThreads!="number"||!Number.isInteger(Dn.wasm.numThreads)||Dn.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Dn.wasm.numThreads=1;else{let e=typeof navigator>"u"?Uee("node:os").cpus().length:navigator.hardwareConcurrency;Dn.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Uw=class{async init(n){zw(),await zz(),await Uz(n)}async createInferenceSessionHandler(n,e){let t=new Wz;return await t.loadModel(n,e),t}},Yz=new Uw});xs();xs();xs();var nne="1.24.3";{let n=(tne(),Lp(qz)).wasmBackend;Bd("webgpu",n,5),Bd("webnn",n,5),Bd("cpu",n,10),Bd("wasm",n,10)}Object.defineProperty(Dn.versions,"web",{value:nne,enumerable:!0});class rne{constructor(e,t={}){this.config=e,this.options=t,this.policyModule=null,this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null,this.context=null,this.policyJointNames=(e.policy_joint_names??[]).slice(),this.numActions=this.policyJointNames.length,this.lastActions=new Float32Array(this.numActions),this.defaultJointPos=this.normalizeArray(e.default_joint_pos??[],this.numActions,0),this.encoderBias=this.normalizeArray(e.encoder_bias??[],this.numActions,0)}async init(e){this.context=e,this.policyModule=await this.buildPolicyModule(e),this.buildObservationGroups()}reset(e){this.lastActions.fill(0),this.policyModule?.reset();for(const t of Object.values(this.obsGroups))for(const r of t)r.reset&&r.reset(e);if(e){for(const[t,r]of Object.entries(this.historyConfig))if(r.steps>1){const i=this.buildFrame(this.obsGroups[t]??[],e),s=this.historyBuffers[t];for(let a=0;a<r.steps;a++)s.set(i,a*i.length)}}}update(e){this.policyModule?.update();for(const t of Object.values(this.obsGroups))for(const r of t)r.update&&r.update(e)}collectObservationsByKey(e){this.update(e);const t={};for(const[r,i]of Object.entries(this.obsGroups)){const s=this.historyConfig[r];if(s&&s.steps>1){const a=this.buildFrame(i,e),o=this.historyBuffers[r];for(let l=o.length-1;l>=a.length;l--)o[l]=o[l-a.length];o.set(a,0),t[r]=new Float32Array(o)}else t[r]=this.buildFrame(i,e)}return t}collectObservations(e){const t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];const r=Object.keys(t)[0];return r?t[r]:new Float32Array(0)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];const e=Object.keys(this.obsSizes)[0];return e?this.obsSizes[e]:0}getObservationLayout(){if(this.defaultObsKey&&this.obsLayouts[this.defaultObsKey])return this.obsLayouts[this.defaultObsKey].map(t=>({...t}));const e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(t=>({...t})):[]}getPolicyModuleContext(){return this.policyModule?.getContext()??{}}getPolicyModule(){return this.policyModule}getContext(){return this.context}getPolicyJointNames(){return this.policyJointNames.slice()}getNumActions(){return this.numActions}getDefaultJointPos(){return new Float32Array(this.defaultJointPos)}getEncoderBias(){return new Float32Array(this.encoderBias)}getLastActions(){return new Float32Array(this.lastActions)}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){const t=this.options.policyModules??{},r=this.config.policy_module,i=r?t[r]:t.default;if(r&&!i)throw new Error(`Unknown policy module: ${r}`);if(!i)return null;const s=new i(this.config);return await s.init(e),s}buildObservationGroups(){const e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;for(const[r,i]of Object.entries(t)){if(Array.isArray(i)){const s=i.map(a=>{const o=e[a.name];if(!o)throw new Error(`Unknown observation type: ${a.name}`);return new o(this,a)});this.registerGroup(r,s,i);continue}if(i&&typeof i=="object"){const s=i;if(Array.isArray(s.components)){const a=s.components.map(c=>{const d=e[c.name];if(!d)throw new Error(`Unknown observation type: ${c.name}`);const h={...c,history_steps:1};return new d(this,h)}),o=Math.max(1,Math.floor(s.history_steps??1)),l=!!s.interleaved;this.registerGroup(r,a,s.components,{steps:o,interleaved:l})}}}this.obsGroups.policy?this.defaultObsKey="policy":this.obsGroups.observation?this.defaultObsKey="observation":this.obsGroups.obs_history?this.defaultObsKey="obs_history":this.defaultObsKey=Object.keys(this.obsGroups)[0]??null}registerGroup(e,t,r,i){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((a,o)=>({name:r[o]?.name??`obs_${o}`,size:a.size}));const s=this.obsLayouts[e].reduce((a,o)=>a+o.size,0);i&&i.steps>1?(this.historyConfig[e]=i,this.historyBuffers[e]=new Float32Array(s*i.steps),this.obsSizes[e]=s*i.steps):this.obsSizes[e]=s}buildFrame(e,t){const r=e.reduce((a,o)=>a+o.size,0),i=new Float32Array(r);let s=0;for(const a of e){const o=a.compute(t),l=o instanceof Float32Array?o:Float32Array.from(o);if(l.length!==a.size)throw new Error(`Observation size mismatch: expected ${a.size}, got ${l.length}`);i.set(l,s),s+=l.length}return i}normalizeArray(e,t,r){const i=new Float32Array(t);for(let s=0;s<t;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}}Dn.wasm.proxy=!1;Dn.wasm.numThreads=1;class ine{constructor(e){if(!e?.path)throw new Error("OnnxModule requires a path.");this.config=e,this.session=null;const t=e.meta?.in_keys??["policy"],r=e.meta?.out_keys??["action"];this.configuredInKeys=t.map(i=>Array.isArray(i)?i.join(","):i),this.inKeys=[...this.configuredInKeys],this.outKeys=r.map(i=>Array.isArray(i)?i.join(","):i),this.isRecurrent=this.inKeys.includes("adapt_hx")}async init(){const e=await fetch(this.config.path);if(!e.ok)throw new Error(`Failed to fetch ONNX model: ${e.status}`);const t=await e.arrayBuffer();this.session=await qC.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"}),this.inferInputKeys(),this.isRecurrent=this.inKeys.includes("adapt_hx")}initInput(){const e={};return this.isRecurrent&&(e.is_init=new ti("bool",[!0],[1]),e.adapt_hx=new ti("float32",new Float32Array(128),[1,128])),this.inKeys.includes("time_step")&&(e.time_step=new ti("float32",new Float32Array([0]),[1,1])),e}async runInference(e){if(!this.session)throw new Error("OnnxModule not initialized.");const t={};for(let a=0;a<this.inKeys.length;a++){const o=this.inKeys[a],l=this.session.inputNames[a];if(!l||!e[o])throw new Error(`Missing ONNX input for key: ${o}`);t[l]=e[o]}const r=await this.session.run(t),i={};for(let a=0;a<this.outKeys.length;a++){const o=this.outKeys[a],l=this.session.outputNames[a];l&&r[l]&&(i[o]=r[l])}const s={};return this.isRecurrent&&i["next,adapt_hx"]&&(s.is_init=new ti("bool",[!1],[1]),s.adapt_hx=i["next,adapt_hx"]),[i,s]}inferInputKeys(){if(!this.session)return;const e=this.session.inputNames;if(e.length<=1){this.inKeys=[...this.configuredInKeys];return}if(this.configuredInKeys.length===e.length){this.inKeys=[...this.configuredInKeys];return}this.inKeys=e.map(t=>this.configuredInKeys.includes(t)?t:t==="obs"&&this.configuredInKeys.includes("policy")?"policy":t)}}class sne{constructor(e,t,r,i){this.mujoco=e,this.mjModel=t,this.mjData=r;const s=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(const a of i){const o=s.indexOf(a);if(o<0)throw new Error(`Joint "${a}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[o]),this.qvelAdr.push(t.jnt_dofadr[o]),this.jointIndices.push(o)}this.numActions=i.length,this.ctrlAdr=this.buildCtrlAdr()}build(){const e=this.mjData.qpos,t=this.mjData.qvel,r=new Float32Array(this.numActions),i=new Float32Array(this.numActions);for(let c=0;c<this.numActions;c++)r[c]=e[this.qposAdr[c]],i[c]=t[this.qvelAdr[c]];const s=new Float32Array([e[0],e[1],e[2]]),a=new Float32Array([e[3],e[4],e[5],e[6]]),o=new Float32Array([t[0],t[1],t[2]]),l=new Float32Array([t[3],t[4],t[5]]);return{jointPos:r,jointVel:i,rootPos:s,rootQuat:a,rootLinVel:o,rootAngVel:l}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}getControlMappingFor(e,t){if(!this.ctrlAdr)return null;const r=e.map(c=>new RegExp(`^(?:${c})$`)),i=c=>r.some(d=>d.test(c)),s=[],a=[],o=[],l=[];for(let c=0;c<t.length;c++)i(t[c])&&(s.push(this.ctrlAdr[c]),a.push(this.qposAdr[c]),o.push(this.qvelAdr[c]),l.push(c));return s.length===0?null:{ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l}}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;const e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let i=0;i<this.mjModel.nu;i++){const s=this.mjModel.actuator_trntype[i];e===void 0||s===e?t.push(this.mjModel.actuator_trnid[2*i]):t.push(-1)}const r=[];for(const i of this.jointIndices){const s=t.findIndex(a=>a===i);if(s<0)return null;r.push(s)}return r}getJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;let l=r.decode(t.subarray(a,o));!l&&s===0&&(l="floating_base_joint"),i.push(l)}return i}}class Jz{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class ane{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName="default",this.currentDone=!0}reset(e){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName="default"}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}}class one extends Jz{constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.tracking=new ane(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class lne{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName="default",this.currentDone=!0}reset(e){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName="default"}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}}class cne extends Jz{constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.locomotion=new lne(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class une{constructor(e,t){this.terms=[];for(const r of e){const i=t[r.name];if(!i){console.warn(`[EventManager] Unknown event type: ${r.name}`);continue}this.terms.push(new i(r))}}onReset(e){for(const t of this.terms)t.onReset(e)}get size(){return this.terms.length}}class Xz{constructor(e){this.config=e}}const dne={};class Kz extends Xz{constructor(e){super(e),this.poseRange=e.params?.pose_range??{}}onReset(e){const{mjModel:t,mjData:r}=e;if(!t||!r)return;const i=this._findFreeJoint(t);if(i===-1)return;const s=t.jnt_qposadr[i],a=l=>{const c=this.poseRange[l];return c?c[0]+Math.random()*(c[1]-c[0]):0};r.qpos[s+0]+=a("x"),r.qpos[s+1]+=a("y"),r.qpos[s+2]+=a("z");const o=a("yaw");o!==0&&this._applyYawRotation(r.qpos,s+3,o)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}class hne extends Xz{constructor(e){super(e),this.patchName=e.params?.patch_name??"spawn",this.fallback=new Kz(e)}onReset(e){const{mjModel:t,mjData:r,terrainData:i}=e;if(!t||!r)return;const s=i?.flat_patches?.[this.patchName];if(!s||s.length===0){this.fallback.onReset(e);return}const a=this._findFreeJoint(t);if(a===-1)return;const o=t.jnt_qposadr[a],l=s[Math.floor(Math.random()*s.length)],c=r.qpos[o+2];r.qpos[o+0]=l[0],r.qpos[o+1]=l[1],r.qpos[o+2]=l[2]+c;const h=(this.config.params?.pose_range??{}).yaw??[-Math.PI,Math.PI],p=h[0]+Math.random()*(h[1]-h[0]);this._applyYawRotation(r.qpos,o+3,p)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}const fne={ResetRootStateUniform:Kz,ResetRootStateFromFlatPatches:hne},pne={...fne,...dne};class Zz extends Error{constructor(){super("This scene cannot be loaded because it exceeds the browser's WebAssembly 2 GB memory limit. Try closing other browser tabs or reloading the page to free memory."),this.name="WasmMemoryLimitError"}}function qR(n){const e=n instanceof Error?n.message:String(n);return e.includes("MjModel loading returned null")||e.includes("Could not allocate memory")||e.includes("memory allocation failed")||e.includes("bad_alloc")}class Ane{constructor(e,t,r={}){this.render=()=>{if(tr().updateDebugVisuals(),this.mjData&&$Z(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){F3(this.camera,this.lights);for(const[o,l]of this.lastSimState.bodies){const c=this.bodies[o];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion))}L3(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&hJ({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{const{width:o,height:l}=this.getSize();this.camera.aspect=o/l,this.camera.updateProjectionMatrix(),this.renderer.setSize(o,l)},this.mujoco=e,this.container=t,this.baseUrl=r.baseUrl||"/";const i="/working";try{this.mujoco.FS.mkdir(i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&console.warn("Failed to create /working directory:",o)}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:"."},i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&o.code!=="EBUSY"&&console.warn("Failed to mount MEMFS at /working:",o)}const{width:s,height:a}=this.getSize();this.scene=new s9,this.scene.name="scene",this.camera=new zr(45,s/a,.001,1e3),this.camera.name="PerspectiveCamera",this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new z7({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(s,a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=QN,this.renderer.outputColorSpace=ii,this.renderer.toneMapping=PN,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported("immersive-vr").then(o=>{o&&(this.vrButton=RC.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new O7(this.camera,this.renderer.domElement),this.controls.target.set(0,.2,0),this.controls.panSpeed=2,this.controls.zoomSpeed=1,this.controls.enableDamping=!0,this.controls.dampingFactor=.1,this.controls.screenSpacePanning=!0,this.controls.update(),this.renderer.setAnimationLoop(this.render),window.addEventListener("resize",this.onWindowResize),"ResizeObserver"in window?(this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),this.resizeObserver.observe(this.container)):this.resizeObserver=null,this.lastSimState={bodies:new Map,tendons:fJ()},this.dynamicBodyIds=null,this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.loopPromise=null,this.running=!1,this.timestep=.001,this.decimation=1,this.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null,this.eventManager=null,this.terrainData=null,this.splatMesh=null,this.colliderMesh=null,this.cameraState={trackBodyId:null,prevBodyPos:null},this.sceneCacheManager=Ew.getInstance(this.mujoco),this.resourceTracker=new GZ,this.memoryMonitor=new HZ}async loadEnvironment(e,t=null,r=null,i=null,s=null,a=null){this.terrainData=a,s&&s.length>0?(this.eventManager=new une(s,pne),console.log(`[EventManager] ${this.eventManager.size} reset event(s) loaded`)):this.eventManager=null,await this.stop(),this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null);const o=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const l=performance.now()-o;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:l})}else this.memoryMonitor.logCacheOperation("miss",e),await this.sceneCacheManager.prepareForNewScene(),this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.resourceTracker.startTracking(this.mujoco),await bJ(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);r&&(this.splatMesh=tB(r,this.scene),r.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(r.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.applyViewerConfig(i),this.running=!0,this.startLoop()}initializeCommands(){const e=tr();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e,t){tr().initialize(e,t),console.log("[mjswanRuntime] Commands loaded from policy config:",Object.keys(e))}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){const e=this.policyStateBuilder.build();this.policyRunner.reset(e)}console.log("[mjswanRuntime] Simulation reset")}async setSelectedMotion(e){const t=tr().getTerm("motion");t instanceof xp&&(await t.setSelectedMotion(e),this.resetSimulation())}setReferenceVisible(e){const t=tr().getTerm("motion");t instanceof xp&&t.setReferenceVisible(e)}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{const t=this.scene.getObjectByName("MuJoCo Root");t&&this.scene.remove(t);const r={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await vJ(this.mujoco,e,r),!this.mjModel||!this.mjData)throw new Error("Failed to load MuJoCo model.");this.mujocoRoot=this.scene.getObjectByName("MuJoCo Root"),this.mujoco.mj_forward(this.mjModel,this.mjData),L3(this.mujoco,this.mjData,this.lights),F3(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds}),this.loadingScene=null})(),await this.loadingScene}async loadSceneWithOomRetry(e){try{await this.loadScene(e)}catch(t){if(!qR(t))throw t;console.warn("[mjswanRuntime] OOM — clearing cache and retrying..."),this.loadingScene=null,await this.sceneCacheManager.clear();try{await this.loadScene(e)}catch(r){throw this.loadingScene=null,qR(r)?new Zz:r}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null),e&&(this.splatMesh=tB(e,this.scene),e.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&oP(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}async stop(){this.running=!1;const e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){const e=performance.now(),t=this.timestep*this.decimation;if(this.mjModel&&this.mjData){if(this.mujoco.mj_forward(this.mjModel,this.mjData),this.policyRunner&&this.policyStateBuilder){const s=this.policyStateBuilder.build(),a=this.policyRunner.collectObservationsByKey(s);if(await this.runOnnxInference(a),this.policyDebugCounter%60===0){const o="policy"in a?"policy":"observation"in a?"observation":Object.keys(a)[0],l=o?a[o]:null,c=l?Array.from(l.slice(0,8)):[];console.log("[PolicyRunner] obs",{key:o,size:l?l.length:0,sample:c})}this.policyDebugCounter+=1}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){const s=this.policyStateBuilder.build();if(this.terminationManager.evaluate(s).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){const o=this.policyStateBuilder.build();this.policyRunner.reset(o)}}tr().update(t),tr().updateDebugVisuals()}const r=(performance.now()-e)/1e3,i=Math.max(0,t-r);i>0&&await new Promise(s=>setTimeout(s,i*1e3))}this.loopPromise=null}async loadPolicyConfig(e){const t=this.policyConfigPath;this.policyConfigPath=e,this.policyRunner=null,this.policyStateBuilder=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null;const r=tr();if(r.clear(),r.setResetCallback(()=>this.resetSimulation()),!!e){if(!this.mjModel||!this.mjData){console.warn("Policy config loaded before MuJoCo model is ready.");return}e!==t&&this.resetSimulationState();try{const{config:i}=await this.fetchPolicyConfig(e);if(Array.isArray(i.motions)&&(i.motions=i.motions.map(o=>({...o,path:this.resolveAssetUrl(this.resolvePolicyAssetPath(e,o.path))}))),i.commands?.motion?.name==="TrackingCommand"&&Array.isArray(i.motions)&&(i.commands.motion={...i.commands.motion,motions:i.motions}),this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),i.commands&&typeof i.commands=="object"){this.initializeCommandsFromConfig(i.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,bodies:this.bodies,mujocoRoot:this.mujocoRoot,requestReset:()=>this.resetSimulation()}),tr().resetTerms();const o=tr().getTerm("motion");o instanceof xp&&(await o.setSelectedMotion(i.motions?.find(l=>l.default)?.name??i.motions?.[0]?.name??null),o.setReferenceVisible(!0)),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()}if(!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new rne(i,{policyModules:{tracking:one,locomotion:cne},observations:Mee});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),this.policyRunner=s,this.policyStateBuilder=new sne(this.mujoco,this.mjModel,this.mjData,s.getPolicyJointNames());const a=this.policyStateBuilder.build();if(this.policyRunner.reset(a),this.policyControl=this.buildPolicyControl(i,s,this.policyStateBuilder),i.terminations&&Object.keys(i.terminations).length>0&&(this.terminationManager=new Tee(i.terminations,Pee),console.log(`[TerminationManager] ${this.terminationManager.size} termination term(s) loaded`)),i.onnx?.path){const o=this.resolvePolicyAssetPath(e,i.onnx.path),l=this.resolveAssetUrl(o),c={...i.onnx,path:l},d=new ine(c);await d.init(),this.onnxModule=d,this.onnxInputDict=d.initInput()}console.log("[PolicyRunner] config loaded",{obsSize:s.getObservationSize(),obsLayout:s.getObservationLayout(),pdEnabled:this.policyControl!==null})}catch(i){console.warn("Failed to load policy config:",i)}}}async fetchPolicyConfig(e){const t=this.resolveAssetUrl(e),r=await fetch(t,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch policy config: ${r.status}`);return{config:await r.json(),resolvedUrl:t}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;const t=(this.baseUrl||"/").replace(/\/+$/,"/"),r=new URL(t,window.location.origin+"/").toString();return new URL(e.replace(/^\/+/,""),r).toString()}resolvePolicyAssetPath(e,t){const r=e.replace(/\\/g,"/"),i=r.lastIndexOf("/");return i>=0?`${r.slice(0,i+1)}${t}`.replace(/\/+/g,"/"):t}buildPolicyControl(e,t,r){const i=t.getPolicyJointNames(),s=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(c,d,h,p,A,y,m,x)=>{const g=h.qposAdr.length,_=h.actionIndices.map(B=>i[B]),b=this.normalizeControlArray(p,g,1,_),w=this.normalizeControlArray(A,g,0,_),C=x?t.getDefaultJointPos():new Float32Array(i.length),S=new Float32Array(g);for(let B=0;B<g;B++)S[B]=C[h.actionIndices[B]];const M=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(i.length),T=new Float32Array(g);for(let B=0;B<g;B++)T[B]=M[h.actionIndices[B]]??0;const R=this.normalizeControlArray(y,g,0,_),k=this.normalizeControlArray(m,g,0,_),G=h.ctrlAdr.map(B=>B<0||!this.mjModel?!1:this.mjModel.actuator_biastype[B]===s),P=G.some(Boolean),V=G.some(B=>!B);return P&&V&&console.warn(`[PolicyRunner] Action term "${c}": mixed actuator types detected.`),console.log(`[PolicyRunner] Action term "${c}" (${d}): ${g} joint(s), mode: ${P?"position (ctrl=target_pos)":"motor (ctrl=torque, external PD)"}`),{controlType:d,ctrlAdr:h.ctrlAdr,qposAdr:h.qposAdr,qvelAdr:h.qvelAdr,actionIndices:h.actionIndices,actionScale:b,actionOffset:w,defaultJointPos:S,encoderBias:T,positionActuator:G,kp:R,kd:k}},o=e.actions;if(!o||Object.keys(o).length===0){const c=e.control_type??"joint_position";if(c!=="joint_position"&&c!=="torque")return console.warn(`[PolicyRunner] Unsupported control_type: ${c}`),null;const d=r.getControlMapping();if(!d)return console.warn("[PolicyRunner] Failed to build control mapping."),null;const h={...d,actionIndices:Array.from({length:d.qposAdr.length},(p,A)=>A)};return[a("legacy",c,h,e.action_scale,void 0,e.stiffness,e.damping,!0)]}const l=[];for(const[c,d]of Object.entries(o)){const h=d.type??"joint_position";if(h!=="joint_position"&&h!=="torque"){console.warn(`[PolicyRunner] Action term "${c}": unsupported type "${h}", skipping.`);continue}const p=d.actuator_names??[".*"],A=p.length===1&&p[0]===".*";let y;if(A){const x=r.getControlMapping();if(!x){console.warn(`[PolicyRunner] Action term "${c}": failed to build control mapping, skipping.`);continue}y={...x,actionIndices:Array.from({length:x.qposAdr.length},(g,_)=>_)}}else if(y=r.getControlMappingFor(p,i),!y){console.warn(`[PolicyRunner] Action term "${c}": no joints matched patterns [${p.join(", ")}], skipping.`);continue}const m=d.use_default_offset!==void 0?d.use_default_offset:h==="joint_position";l.push(a(c,h,y,d.scale,d.offset,d.stiffness,d.damping,m))}return l.length===0?(console.warn("[PolicyRunner] No valid action terms found in config.actions."),null):l}normalizeControlArray(e,t,r,i){const s=new Float32Array(t);if(s.fill(r),typeof e=="number")return s.fill(e),s;if(Array.isArray(e)){for(let a=0;a<t;a++)s[a]=typeof e[a]=="number"?e[a]:r;return s}if(e!==null&&typeof e=="object"&&i){for(const[a,o]of Object.entries(e)){const l=i.indexOf(a);l>=0&&l<t?s[l]=o:console.warn(`[PolicyRunner] Joint name "${a}" not found in policy_joint_names; skipping.`)}return s}return s}resetSimulationState(){!this.mjModel||!this.mjData||(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),tr().resetTerms(),this.onnxModule&&(this.onnxInputDict=this.onnxModule.initInput()),this.onnxTimeStep=0,this.mujoco.mj_forward(this.mjModel,this.mjData),this.lastSimState.bodies.clear(),this.updateCachedState())}executeSimulationSteps(){if(!(!this.mjModel||!this.mjData)){this.applyDragForces();for(let e=0;e<this.decimation;e++)this.applyPolicyControl(),this.mujoco.mj_step(this.mjModel,this.mjData)}}applyPolicyControl(){if(!this.policyControl||!this.mjData)return;const e=this.mjData.ctrl;e.fill(0);const t=this.policyRunner?.getLastActions()??new Float32Array(0);for(const r of this.policyControl){const{controlType:i,ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l,actionScale:c,actionOffset:d,defaultJointPos:h,encoderBias:p,positionActuator:A,kp:y,kd:m}=r,x=s.length;if(i==="joint_position")for(let g=0;g<x;g++){const _=s[g];if(_<0)continue;const b=t[l[g]]??0,w=h[g]+d[g]+c[g]*b-p[g];if(A[g])e[_]=w;else{const C=this.mjData.qpos[a[g]],S=this.mjData.qvel[o[g]];e[_]=y[g]*(w-C)+m[g]*(0-S)}}else if(i==="torque")for(let g=0;g<x;g++){const _=s[g];_>=0&&(e[_]=c[g]*(t[l[g]]??0))}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||(this.onnxInputDict=this.onnxModule.initInput());const t={...this.onnxInputDict};this.onnxModule.inKeys.includes("time_step")&&(t.time_step=new ti("float32",new Float32Array([this.onnxTimeStep]),[1,1]));for(const[d,h]of Object.entries(e))t[d]=new ti("float32",h,[1,h.length]);for(const d of this.onnxModule.inKeys)if(!t[d]){console.warn("[PolicyRunner] Missing ONNX input:",{key:d,available:Object.keys(t)});return}const[r,i]=await this.onnxModule.runInference(t);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i}),this.onnxModule.inKeys.includes("time_step")&&(this.onnxTimeStep+=1);const s=this.onnxModule.outKeys[0],a=r.action??(s?r[s]:null)??r.policy??null;if(!a)return;const o=a.data,l=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&l.length!==c){console.warn("[PolicyRunner] Action size mismatch:",{expected:c,got:l.length});return}this.policyRunner.setLastActions(l)}catch(t){console.warn("[PolicyRunner] ONNX inference failed:",t)}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let p=0;p<this.mjData.xfrc_applied.length;p++)this.mjData.xfrc_applied[p]=0;const e=this.dragStateManager.physicsObject;if(!e||!("bodyID"in e)||typeof e.bodyID!="number"||e.bodyID<=0)return;const t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(Vc(this.mjData.xpos,p,this.bodies[p].position),pp(this.mjData.xquat,p,this.bodies[p].quaternion),this.bodies[p].updateWorldMatrix(!0,!1));this.dragStateManager.update();const r=this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale),i=P3(r),s=this.dragStateManager.worldHit.clone(),a=P3(s),o=new ue(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),l=new ue(a.x-o.x,a.y-o.y,a.z-o.z),c=new ue(i.x,i.y,i.z),d=new ue().crossVectors(l,c),h=t*6;this.mjData.xfrc_applied[h+0]=i.x,this.mjData.xfrc_applied[h+1]=i.y,this.mjData.xfrc_applied[h+2]=i.z,this.mjData.xfrc_applied[h+3]=d.x,this.mjData.xfrc_applied[h+4]=d.y,this.mjData.xfrc_applied[h+5]=d.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++)if(!(e&&!e.has(t))&&this.bodies[t]){this.lastSimState.bodies.has(t)||this.lastSimState.bodies.set(t,{position:new ue,quaternion:new Cn});const r=this.lastSimState.bodies.get(t);Vc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&dJ(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=OZ(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){const t=new Set;for(let r=1;r<e.nbody;r++){let i=r;for(;i>0;){if(e.body_jntnum[i]>0){t.add(r);break}i=e.body_parentid[i]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;const r=this.bodies[t];r&&(Vc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion))}}dispose(){this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.dragStateManager&&(this.dragStateManager.dispose(),this.dragStateManager=null),this.mjData=null,this.mjModel=null,window.removeEventListener("resize",this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.controls.dispose(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.vrButton?.parentElement&&(this.vrButton.parentElement.removeChild(this.vrButton),this.vrButton=null),this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.lastSimState.bodies.clear()}disposeThreeJSResources(){if(this.scene)for(this.scene.traverse(e=>{"geometry"in e&&e.geometry&&e.geometry.dispose(),"material"in e&&e.material&&(Array.isArray(e.material)?e.material.forEach(t=>this.disposeMaterial(t)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),e.dispose()}getSize(){const e=this.container.clientWidth||window.innerWidth,t=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,t)}}async restoreFromCache(e){const t=this.sceneCacheManager.get(e);if(!t)throw new Error(`Scene ${e} not found in cache`);const r=this.scene.getObjectByName("MuJoCo Root");r&&this.scene.remove(r),this.mjModel=t.mjModel,this.mjData=t.mjData,this.bodies=t.bodies,this.lights=t.lights,this.mujocoRoot=t.mujocoRoot,this.scene.add(this.mujocoRoot),this.scene.background=t.skybox,this.mujoco.mj_forward(this.mjModel,this.mjData),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds})}async captureAndCacheResources(e){const t=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot){console.warn("[SceneCache] Cannot cache scene: missing resources");return}const r=this.resourceTracker.estimateSceneMemory({mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,meshes:{},mujocoRoot:this.mujocoRoot});await this.sceneCacheManager.set(e,{scenePath:e,lastAccessed:Date.now(),loadedAt:Date.now(),mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,lights:this.lights,meshes:{},mujocoRoot:this.mujocoRoot,skybox:this.scene.background instanceof ph?this.scene.background:null,fsFiles:t,estimatedMemoryBytes:r});const i=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation("load",e,{memoryMB:r/1048576,totalScenes:i.totalScenes,totalMemoryMB:i.totalMemoryBytes/1048576})}}const ag="mjswan_oom_reload_scene",mne=({scenePath:n,baseUrl:e,policyConfigPath:t,splatConfig:r,cameraConfig:i,eventsConfig:s,terrainData:a,selectedMotion:o,showReferenceMotion:l=!0,onStatusChange:c,onError:d,onReady:h,onRuntimeReady:p})=>{const A=U.useRef(null),y=U.useRef(null),m=U.useRef(null),x=U.useRef(r);x.current=r;const g=U.useRef(o);g.current=o;const _=U.useRef(l);return _.current=l,U.useEffect(()=>{let b=!1;const w=S=>{c?.(S)};return(async()=>{if(w("Loading MuJoCo..."),!m.current){const T=await RH(()=>import("./mujoco-xH6B9zn7.js"),[]);m.current=await T.default()}if(b)return;const S=A.current;if(!S)throw new Error("Failed to find viewer container.");const M=m.current;if(!M)throw new Error("MuJoCo not loaded.");y.current||(y.current=new Ane(M,S,{baseUrl:e}),p?.(y.current)),w("Loading scene assets..."),await y.current.loadEnvironment(n,t??null,x.current??null,i??null,s??null,a??null),await y.current.setSelectedMotion(g.current??null),y.current.setReferenceVisible(_.current),!b&&(sessionStorage.removeItem(ag),w("Running simulation"),h?.())})().catch(S=>{if(!b){if(S instanceof Zz){if(sessionStorage.getItem(ag)!==n){console.warn("[MjswanViewer] OOM — reloading page to free memory..."),sessionStorage.setItem(ag,n),window.location.reload();return}sessionStorage.removeItem(ag)}console.error("Failed to initialize MuJoCo viewer:",S),d?.(S instanceof Error?S:new Error(String(S))),w("Failed to load scene")}}),()=>{b=!0,y.current?.dispose(),y.current=null}},[n,e,t,i,s,a,c,d,h]),U.useEffect(()=>{y.current&&y.current.setSelectedMotion(o??null)},[o]),U.useEffect(()=>{y.current?.setReferenceVisible(l)},[l]),j.jsx("div",{ref:A,className:"viewer"})};var gne={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};const ey=(n,e,t,r)=>{const i=U.forwardRef(({color:s="currentColor",size:a=24,stroke:o=2,title:l,className:c,children:d,...h},p)=>U.createElement("svg",{ref:p,...gne[n],width:a,height:a,className:["tabler-icon",`tabler-icon-${e}`,c].join(" "),strokeWidth:o,stroke:s,...h},[l&&U.createElement("title",{key:"svg-title"},l),...r.map(([A,y])=>U.createElement(A,y)),...Array.isArray(d)?d:[d]]));return i.displayName=`${t}`,i};const yne=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],e4=ey("outline","chevron-down","ChevronDown",yne);const xne=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],vne=ey("outline","chevron-up","ChevronUp",xne);const _ne=[["path",{d:"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4",key:"svg-0"}],["path",{d:"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4",key:"svg-1"}]],bne=ey("outline","refresh","Refresh",_ne);const wne=[["path",{d:"M18 6l-12 12",key:"svg-0"}],["path",{d:"M6 6l12 12",key:"svg-1"}]],Ene=ey("outline","x","X",wne),YR="0.5.1",JR=[{login:"ttktjmt",html_url:"https://github.com/ttktjmt"},{login:"claude",html_url:"https://github.com/claude"},{login:"julien-blanchon",html_url:"https://github.com/julien-blanchon"},{login:"unmoyai",html_url:"https://github.com/unmoyai"},{login:"brentyi",html_url:"https://github.com/brentyi"},{login:"Axellwppr",html_url:"https://github.com/Axellwppr"},{login:"CharlieLeee",html_url:"https://github.com/CharlieLeee"}],Cne={move:"touchmove",end:"touchend"},Ine={move:"mousemove",end:"mouseup"};function Sne(n){return n.type==="touchmove"}function Bne(n){return n.type==="mousemove"}const Wp=On.createContext(null);function Ao({children:n,width:e,visible:t=!0,onVisibleChange:r,hiddenButtonTooltip:i}){const s=On.useRef(null),[a,{toggle:o}]=s0(!0),[l,c]=On.useState(800),d=On.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),h=On.useRef({}),p=(x,g,_)=>Math.abs(x+g/2)<Math.abs(x-_+g/2)?x:x-_,A=15;function y(x,g){const _=s.current;if(_===null)return[x,g];const b=_.parentElement;if(b===null)return[x,g];let w=x,C=g;return w=Math.min(w,b.clientWidth-_.clientWidth-A),w=Math.max(w,A),C=Math.min(C,b.clientHeight-_.clientHeight-A),C=Math.max(C,A),_.style.top=`${C.toString()}px`,_.style.left=`${w.toString()}px`,[p(w,_.clientWidth,b.clientWidth),p(C,_.clientHeight,b.clientHeight)]}On.useEffect(()=>{const x=s.current;if(x===null)return;const g=x.parentElement;if(g===null)return;const _=new ResizeObserver(()=>{h.current.x===void 0&&(h.current.x=p(x.offsetLeft,x.clientWidth,g.clientWidth)),h.current.y===void 0&&(h.current.y=p(x.offsetTop,x.clientHeight,g.clientHeight));const b=g.clientHeight-A*2;l!==b&&c(b);let w=h.current.x,C=h.current.y;for(;w<0;)w+=g.clientWidth;for(;C<0;)C+=g.clientHeight;y(w,C)});return _.observe(x),_.observe(g),()=>{_.disconnect()}});const m=x=>{const g=d.current,_=s.current;if(!_)return;x.type=="touchstart"?(x=x,g.startClientX=x.touches[0].clientX,g.startClientY=x.touches[0].clientY):(x=x,g.startClientX=x.clientX,g.startClientY=x.clientY),g.startPosX=_.offsetLeft,g.startPosY=_.offsetTop;const b=x.type=="touchstart"?Cne:Ine;function w(C){let S=0,M=0;if(Sne(C)?(C=C,S=C.touches[0].clientX-g.startClientX,M=C.touches[0].clientY-g.startClientY):Bne(C)&&(C=C,S=C.clientX-g.startClientX,M=C.clientY-g.startClientY),Math.abs(S)<=3&&Math.abs(M)<=3)return;g.dragging=!0;const T=g.startPosX+S,R=g.startPosY+M;[h.current.x,h.current.y]=y(T,R)}window.addEventListener(b.move,w),window.addEventListener(b.end,()=>{x.type=="touchstart"&&(g.dragging=!1),window.removeEventListener(b.move,w)},{once:!0})};if(!t){const x=j.jsx(Xe,{component:"button","aria-label":i??"Show controls",onClick:()=>r?.(!0),style:{width:"0.85rem",height:"0.85rem",minWidth:"0.85rem",minHeight:"0.85rem",display:"block",padding:0,border:"none",borderRadius:"9999px",background:"rgba(255, 255, 255, 0.82)",boxShadow:"0 0 0 1px rgba(0, 0, 0, 0.14), 0 2px 8px rgba(0, 0, 0, 0.18)",cursor:"pointer"}});return j.jsx(Xe,{style:{zIndex:10,position:"absolute",top:"1em",right:"1em"},children:i?j.jsx(Pl,{label:i,children:j.jsx(Xe,{children:x})}):x})}return j.jsx(Wp.Provider,{value:{wrapperRef:s,expanded:a,width:e,maxHeight:l,toggleExpanded:o,dragHandler:m,dragInfo:d},children:j.jsx(Yc,{radius:"xs",shadow:"0.1em 0 1em 0 rgba(0,0,0,0.1)",style:{boxSizing:"border-box",width:e,zIndex:10,position:"absolute",top:"1em",right:"1em",margin:0,"& .expandIcon":{transform:"rotate(0)"},overflow:"hidden"},ref:s,children:n})})}Ao.Handle=function({children:e}){const t=On.useContext(Wp);return j.jsx(j.Fragment,{children:j.jsx(Xe,{style:{borderRadius:"0.2em 0.2em 0 0",lineHeight:"1.5em",cursor:"pointer",position:"relative",fontWeight:400,userSelect:"none",display:"flex",alignItems:"center",padding:"0 0.75em",height:"2.75em"},onClick:()=>{const r=t.dragInfo.current;if(r.dragging){r.dragging=!1;return}t.toggleExpanded()},onTouchStart:r=>{t.dragHandler(r)},onMouseDown:r=>{t.dragHandler(r)},children:e})})};Ao.Contents=function({children:e}){const t=On.useContext(Wp);return j.jsxs(Mg,{in:t.expanded,children:[j.jsx(Dd,{mx:"xs"}),j.jsx(iu.Autosize,{mah:t.maxHeight,children:j.jsx(Xe,{style:{width:t.width},children:e})})]})};Ao.HideWhenCollapsed=function({children:e}){return On.useContext(Wp)?.expanded??!0?e:null};Ao.HideWhenExpanded=function({children:e}){return On.useContext(Wp)?.expanded??!0?null:e};function og({id:n,label:e,children:t}){return j.jsx(Xe,{pb:"0.5em",px:"xs",children:j.jsxs(EE,{align:"center",children:[j.jsx(Xe,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:j.jsx(Js,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:j.jsx("label",{htmlFor:n,children:e})})}),j.jsx(Xe,{style:{flexGrow:1},children:t})]})})}function t4({label:n,expandByDefault:e=!0,children:t}){const[r,{toggle:i}]=s0(e),s=r?vne:e4;return j.jsxs(Yc,{withBorder:!0,style:{borderWidth:"1px",position:"relative",marginLeft:"var(--mantine-spacing-xs)",marginRight:"var(--mantine-spacing-xs)",marginTop:"var(--mantine-spacing-xs)",marginBottom:"var(--mantine-spacing-xs)",paddingBottom:"calc(var(--mantine-spacing-xs) - 0.5em)"},children:[j.jsxs(Yc,{onClick:i,style:{fontSize:"0.875em",position:"absolute",padding:"0 0.375em",top:0,left:"0.375em",transform:"translateY(-50%)",userSelect:"none",fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center"},children:[n,j.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),j.jsx(Mg,{in:r,children:j.jsx(Xe,{pt:"1em",children:t})}),j.jsx(Mg,{in:!r,children:j.jsx(Xe,{p:"xs"})})]})}const n4={fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"4.5em",flexShrink:0},Mne={root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}},Tne={flex:1,minWidth:0,height:"1.75em",fontSize:"0.8em",fontFamily:"inherit",border:"1px solid var(--mantine-color-default-border)",borderRadius:"var(--mantine-radius-sm)",background:"var(--mantine-color-default)",color:"var(--mantine-color-text)",textAlign:"right",padding:"0 0.4em",outline:"none",cursor:"ns-resize",touchAction:"none"};function q_({axis:n,value:e,min:t=-1/0,max:r=1/0,step:i,onChange:s}){const a=U.useRef(null),o=U.useRef(null);U.useEffect(()=>{const y=a.current;y&&document.activeElement!==y&&(y.value=e.toFixed(2))},[e]);const l=y=>Math.max(t,Math.min(r,parseFloat((Math.round(y/i)*i).toFixed(10)))),c=y=>{y.preventDefault(),y.currentTarget.setPointerCapture(y.pointerId),o.current={startY:y.clientY,startValue:e,moved:!1}},d=y=>{if(!o.current||!(y.buttons&1))return;const m=o.current.startY-y.clientY;if(Math.abs(m)>3&&(o.current.moved=!0),!o.current.moved)return;const x=l(o.current.startValue+m*i);s(x),a.current&&(a.current.value=x.toFixed(2))},h=()=>{if(o.current&&!o.current.moved){const y=a.current;y&&(y.focus(),y.select())}o.current=null},p=y=>{const m=parseFloat(y.target.value);isNaN(m)||s(l(m)),y.target.value=e.toFixed(2)},A=y=>{y.key==="Enter"&&y.currentTarget.blur(),y.key==="Escape"&&(a.current&&(a.current.value=e.toFixed(2)),a.current?.blur())};return j.jsxs(Xe,{style:{display:"flex",alignItems:"center",gap:"0.25em",flex:1},children:[j.jsx(Js,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,letterSpacing:"-0.75px",flexShrink:0},children:n}),j.jsx("input",{ref:a,size:1,defaultValue:e.toFixed(2),onPointerDown:c,onPointerMove:d,onPointerUp:h,onBlur:p,onKeyDown:A,onFocus:y=>y.currentTarget.style.outline="2px solid var(--mantine-color-blue-5)",onBlurCapture:y=>y.currentTarget.style.outline="none",style:Tne})]})}function XR({label:n,x:e,y:t,z:r,step:i,xLabel:s="X",yLabel:a="Y",zLabel:o="Z",onX:l,onY:c,onZ:d}){return j.jsxs(Xe,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Js,{c:"dimmed",style:n4,children:n}),j.jsx(q_,{axis:s,value:e,step:i,onChange:l}),j.jsx(q_,{axis:a,value:t,step:i,onChange:c}),j.jsx(q_,{axis:o,value:r,step:i,onChange:d})]})}function Rne({scale:n,xOffset:e,yOffset:t,zOffset:r,roll:i,pitch:s,yaw:a,onCalibrate:o}){const[l,c]=U.useState(n),[d,h]=U.useState(e),[p,A]=U.useState(t),[y,m]=U.useState(r),[x,g]=U.useState(i),[_,b]=U.useState(s),[w,C]=U.useState(a);U.useEffect(()=>{c(n)},[n]),U.useEffect(()=>{h(e)},[e]),U.useEffect(()=>{A(t)},[t]),U.useEffect(()=>{m(r)},[r]),U.useEffect(()=>{g(i)},[i]),U.useEffect(()=>{b(s)},[s]),U.useEffect(()=>{C(a)},[a]);const S=(M,T,R,k,G,P,V)=>o(M,T,R,k,G,P,V);return j.jsxs(t4,{label:"Control",expandByDefault:!0,children:[j.jsxs(Xe,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Js,{c:"dimmed",style:n4,children:"Scale"}),j.jsx(Xe,{style:{flex:1},children:j.jsx(P0,{value:l,onChange:M=>{c(M),S(M,d,p,y,x,_,w)},min:.1,max:5,step:.05,size:"xs",label:M=>M.toFixed(2),styles:Mne})})]}),j.jsx(XR,{label:"Position",x:d,y:p,z:y,step:.05,onX:M=>{h(M),S(l,M,p,y,x,_,w)},onY:M=>{A(M),S(l,d,M,y,x,_,w)},onZ:M=>{m(M),S(l,d,p,M,x,_,w)}}),j.jsx(XR,{label:"Rotation",x,y:_,z:w,step:.5,xLabel:"R",yLabel:"P",zLabel:"Y",onX:M=>{g(M),S(l,d,p,y,M,_,w)},onY:M=>{b(M),S(l,d,p,y,x,M,w)},onZ:M=>{C(M),S(l,d,p,y,x,_,M)}})]})}function Dne(n){return n instanceof HTMLElement?n.isContentEditable?!0:n.closest('input, textarea, select, [contenteditable], [role="textbox"], [role="searchbox"], [role="combobox"]')!==null:!1}function kne(n){return n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Nne({command:n,value:e,onChange:t,disabled:r}){const i=n.config;return j.jsxs(Xe,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[j.jsx(Js,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:i.label}),j.jsx(Xe,{style:{width:"50%"},children:j.jsx(P0,{value:e,onChange:s=>t(n.id,s),min:i.min,max:i.max,step:i.step,size:"xs",disabled:r,styles:{root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}}})})]})}function Qne(n){const{visible:e,onVisibleChange:t,projects:r,projectValue:i,projectLabel:s,onProjectChange:a,scenes:o,sceneValue:l,onSceneChange:c,splats:d,splatSection:h=!1,splatValue:p,onSplatChange:A,splatConfig:y,onCalibrateSplat:m,onSplatUrlLoad:x,policies:g,policyValue:_,onPolicyChange:b,motions:w,motionValue:C,onMotionChange:S,showReferenceMotion:M,onShowReferenceMotionChange:T,commandsEnabled:R=!1,onReset:k}=n,[G,{open:P,close:V}]=s0(!1),[B,W]=U.useState(""),[K,Y]=U.useState(null),[$,J]=U.useState(!1),re=U.useCallback(async ve=>{if(ve.key!=="Enter"||!x)return;const Ne=B.trim();if(d.some(Ge=>Ge.label===Ne||Ge.value===Ne))return;if(!Ne.toLowerCase().endsWith(".spz")){Y("URL must end with .spz");return}await x(Ne)?(Y(null),J(!0)):Y("File not found at the specified URL")},[x,B,d]),[L,H]=U.useState([]),[oe,Ae]=U.useState([]),[ye,he]=U.useState({});U.useEffect(()=>{const ve=tr(),Ne=()=>{H(ve.getCommands()),Ae(ve.getCommandGroups()),he(ve.getValues())};return Ne(),ve.addEventListener(Ne),()=>{ve.removeEventListener(Ne)}},[]),U.useEffect(()=>{const ve=Ne=>{if(Ne.defaultPrevented||Ne.repeat||Ne.altKey||Ne.ctrlKey||Ne.metaKey||Ne.key.toLowerCase()!=="c")return;const ct=Ne.target instanceof Element?Ne.target:document.activeElement;Dne(ct)||(Ne.preventDefault(),t(!e))};return window.addEventListener("keydown",ve),()=>{window.removeEventListener("keydown",ve)}},[e,t]);const fe=U.useCallback((ve,Ne)=>{tr().setValue(ve,Ne),he(Ge=>({...Ge,[ve]:Ne}))},[]),Ee=U.useCallback(()=>{tr().triggerButton("_system:reset"),k&&k()},[k]),Re=ve=>L.filter(Ne=>Ne.groupName===ve&&Ne.config.type==="slider");return!r.length&&!o.length&&!g.length?null:j.jsxs(j.Fragment,{children:[j.jsx(aa,{opened:G,onClose:V,size:"lg",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:j.jsxs(sC,{gap:"md",align:"center",children:[j.jsx(Pg,{src:"./logo-color.svg",style:{width:"8em",height:"auto"}}),j.jsx(Js,{size:"xl",fw:700,children:"powered by mjswan"}),j.jsxs(Js,{size:"sm",c:"dimmed",children:["version ",YR]}),j.jsx(Js,{size:"sm",c:"dimmed",children:"MuJoco Simulation on Web Assembly with Neural netwroks"}),j.jsx(Dd,{w:"100%"}),j.jsxs(Xe,{children:[j.jsx(up,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"})," • ",j.jsx(up,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]}),j.jsx(Dd,{w:"100%"}),j.jsxs(Xe,{style:{textAlign:"left",maxHeight:"120px",overflowY:"auto",lineHeight:"1",fontSize:"0.8rem",opacity:"0.75"},px:"md",children:["Thanks to our contributors! ",j.jsx("br",{}),JR.map((ve,Ne)=>j.jsxs("span",{children:[j.jsx(up,{href:ve.html_url,target:"_blank",style:{textDecoration:"none",fontSize:"0.75rem"},children:ve.login}),Ne<JR.length-1&&", "]},ve.login))]})]})}),j.jsxs(Ao,{width:"20em",visible:e,onVisibleChange:t,hiddenButtonTooltip:"Show controls (C)",children:[j.jsxs(Ao.Handle,{children:[j.jsx(Pl,{label:`mjswan ${YR}`,children:j.jsx(Xe,{component:"a",onClick:ve=>{ve.stopPropagation(),P()},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{position:"absolute",cursor:"pointer",display:"flex",top:"0.8em",left:"0.9em"},children:j.jsx(Pg,{src:"./logo.svg",style:{width:"1.2em",height:"auto"}})})}),j.jsx("div",{style:{width:"1.1em"}}),j.jsx(Ao.HideWhenCollapsed,{children:j.jsxs(Xe,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[j.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),r.length>1&&j.jsxs(pi,{position:"bottom-start",offset:5,children:[j.jsx(pi.Target,{children:j.jsx(Xe,{onClick:ve=>ve.stopPropagation(),onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center",flexShrink:0},children:j.jsx(e4,{size:16})})}),j.jsx(pi.Dropdown,{onClick:ve=>ve.stopPropagation(),children:r.map(ve=>j.jsx(pi.Item,{onClick:Ne=>{Ne.stopPropagation(),a(ve.value)},style:{fontWeight:ve.value===i?600:400,backgroundColor:ve.value===i?"rgba(34, 139, 230, 0.1)":void 0},children:ve.label},ve.value))})]})]})}),j.jsx(Ao.HideWhenExpanded,{children:j.jsx(Xe,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:s})}),j.jsx(Pl,{label:"Hide controls (C)",children:j.jsx(su,{variant:"subtle",color:"gray",size:"sm","aria-label":"Hide controls",onClick:ve=>{ve.stopPropagation(),t(!1)},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),children:j.jsx(Ene,{size:14})})})]}),j.jsx(Ao.Contents,{children:j.jsxs(Xe,{pt:"0.375em",children:[o.length>0&&j.jsx(og,{id:"scene-select",label:"Scene",children:j.jsx(Fc,{id:"scene-select",placeholder:"Select scene",data:o,value:l,onChange:c,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),(d.length>0||h)&&j.jsx(og,{id:"splat-select",label:"Splat",children:j.jsx(Pl,{label:K??"",color:"red",position:"bottom",opened:K!==null,withArrow:!0,children:j.jsx(Fc,{id:"splat-select",placeholder:x!==void 0?"Select splat or paste .spz URL":"Select splat",data:d,value:p,onChange:ve=>{A(ve),Y(null),J(!1)},searchable:x!==void 0,searchValue:B,onSearchChange:ve=>{W(ve),ve&&Y(null)},onKeyDown:re,size:"xs",radius:"xs",clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})})}),(y?.control&&p!==null||$)&&m&&j.jsx(Rne,{scale:y?.scale??1,xOffset:y?.xOffset??0,yOffset:y?.yOffset??0,zOffset:y?.zOffset??0,roll:y?.roll??0,pitch:y?.pitch??0,yaw:y?.yaw??0,onCalibrate:m}),g.length>0&&j.jsx(og,{id:"policy-select",label:"Policy",children:j.jsx(Fc,{id:"policy-select",placeholder:"Select policy",data:g,value:_,onChange:b,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),w.length>0&&j.jsxs(j.Fragment,{children:[j.jsx(og,{id:"motion-select",label:"Motion",children:j.jsx(Fc,{id:"motion-select",placeholder:"Select motion",data:w,value:C,onChange:S,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),j.jsx(Xe,{pb:"0.5em",px:"xs",children:j.jsx(au,{label:"Show reference",checked:M,onChange:ve=>T(ve.currentTarget.checked),size:"xs"})})]}),oe.length>0&&L.filter(ve=>ve.config.type==="slider").length>0&&j.jsx(j.Fragment,{children:oe.map(ve=>{const Ne=Re(ve);return Ne.length===0?null:j.jsx(t4,{label:kne(ve),expandByDefault:!0,children:Ne.map(ct=>j.jsx(Nne,{command:ct,value:ye[ct.id]??0,onChange:fe,disabled:!R},ct.id))},ve)})}),j.jsx(Dd,{mb:"xs",mx:"xs"}),j.jsx(Xe,{px:"xs",pb:"xs",children:j.jsx(lh,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:j.jsx(bne,{size:14}),onClick:Ee,children:"Reset"})})]})})]})]})}function Jf(n,e,t){return Object.keys(n[e]).reduce((r,i)=>(r[i]=`var(--mantine-${t}-${i})`,r),{})}function KR(n,e){return n in e.breakpoints?e.breakpoints[n]:X_(n)}function Pne(n){const e=wD(c0,n),t=Jf(e,"fontSizes","font-size"),r=Jf(e,"lineHeights","line-height"),i=Jf(e,"shadows","shadow"),s=Jf(e,"radius","radius"),a=Jf(e,"spacing","spacing"),o=Object.keys(e.headings.sizes).reduce((c,d)=>(c[d]={fontSize:`var(--mantine-${d}-font-size)`,lineHeight:`var(--mantine-${d}-line-height)`,fontWeight:`var(--mantine-${d}-font-weight)`},c),{}),l=Object.keys(e.colors).reduce((c,d)=>(c[d]={0:`var(--mantine-color-${d}-0)`,1:`var(--mantine-color-${d}-1)`,2:`var(--mantine-color-${d}-2)`,3:`var(--mantine-color-${d}-3)`,4:`var(--mantine-color-${d}-4)`,5:`var(--mantine-color-${d}-5)`,6:`var(--mantine-color-${d}-6)`,7:`var(--mantine-color-${d}-7)`,8:`var(--mantine-color-${d}-8)`,9:`var(--mantine-color-${d}-9)`,filled:`var(--mantine-color-${d}-filled)`,filledHover:`var(--mantine-color-${d}-filled-hover)`,light:`var(--mantine-color-${d}-light)`,lightHover:`var(--mantine-color-${d}-light-hover)`,lightColor:`var(--mantine-color-${d}-light-color)`,outline:`var(--mantine-color-${d}-outline)`,outlineHover:`var(--mantine-color-${d}-outline-hover)`},c),{primary:"var(--mantine-primary-color-filled)",primaryColors:{0:"var(--mantine-primary-color-0)",1:"var(--mantine-primary-color-1)",2:"var(--mantine-primary-color-2)",3:"var(--mantine-primary-color-3)",4:"var(--mantine-primary-color-4)",5:"var(--mantine-primary-color-5)",6:"var(--mantine-primary-color-6)",7:"var(--mantine-primary-color-7)",8:"var(--mantine-primary-color-8)",9:"var(--mantine-primary-color-9)",filled:"var(--mantine-primary-color-filled)",filledHover:"var(--mantine-primary-color-filled-hover)",light:"var(--mantine-primary-color-light)",lightHover:"var(--mantine-primary-color-light-hover)",lightColor:"var(--mantine-primary-color-light-color)",outline:"var(--mantine-primary-color-outline)",outlineHover:"var(--mantine-primary-color-outline-hover)"},white:"var(--mantine-color-white)",black:"var(--mantine-color-black)",text:"var(--mantine-color-text)",body:"var(--mantine-color-body)",error:"var(--mantine-color-error)",placeholder:"var(--mantine-color-placeholder)",anchor:"var(--mantine-color-anchor)",default:"var(--mantine-color-default)",defaultHover:"var(--mantine-color-default-hover)",defaultColor:"var(--mantine-color-default-color)",defaultBorder:"var(--mantine-color-default-border)",dimmed:"var(--mantine-color-dimmed)",disabledBody:"var(--mantine-color-disabled)",disabledText:"var(--mantine-color-disabled-color)",disabledBorder:"var(--mantine-color-disabled-border)"});return{scale:"var(--mantine-scale)",cursorType:"var(--mantine-cursor-type)",webkitFontSmoothing:"var(--mantine-webkit-font-smoothing)",mozFontSmoothing:"var(--mantine-moz-font-smoothing)",lineHeight:"var(--mantine-line-height)",fontFamily:"var(--mantine-font-family)",fontFamilyMonospace:"var(--mantine-font-family-monospace)",fontFamilyHeadings:"var(--mantine-font-family-headings)",headingFontWeight:"var(--mantine-heading-font-weight)",radiusDefault:"var(--mantine-radius-default)",breakpoints:e.breakpoints,fontSizes:t,lineHeights:r,shadows:i,radius:s,headings:o,spacing:a,colors:l,rtlSelector:'[dir="rtl"] &',darkSelector:'[data-mantine-color-scheme="dark"] &',lightSelector:'[data-mantine-color-scheme="light"] &',smallerThan:c=>`(max-width: ${KR(c,e)})`,largerThan:c=>`(min-width: ${KR(c,e)})`}}const Ow={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:au.extend({defaultProps:{radius:"xs"}}),ColorInput:jE.extend({defaultProps:{radius:"xs"}}),Select:Fc.extend({defaultProps:{radius:"sm"}}),Textarea:qE.extend({defaultProps:{radius:"xs"}}),TextInput:aC.extend({defaultProps:{radius:"xs"}}),NumberInput:nC.extend({defaultProps:{radius:"xs"}}),Paper:Yc.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:su.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:lh.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};Pne(Ow);const r4=U.createContext(void 0),i4=()=>{const n=U.useContext(r4);if(!n)throw new Error("useLoading must be used within a LoadingProvider");return n},Lne=({children:n})=>{const[e,t]=U.useState(!1),r=U.useRef(0),i=U.useCallback(()=>{r.current+=1,r.current>0&&t(!0)},[]),s=U.useCallback(()=>{r.current=Math.max(0,r.current-1),r.current===0&&t(!1)},[]);return j.jsx(r4.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:n})},Fne=()=>{const{isLoading:n}=i4();return n?j.jsx("div",{className:"loader-overlay",children:j.jsx("div",{className:"loader-content",children:j.jsx(sh,{size:64,type:"bars"})})}):null},$w="panel",Gw="ref";function zne(){const n="/".replace(/\/+$/,"/");let t=window.location.pathname.replace(/^\/+|\/+$/g,"");const r=n.replace(/^\/+|\/+$/g,"");if(r&&(t===r?t="":t.startsWith(`${r}/`)&&(t=t.slice(r.length+1))),!t)return null;const i=t.split("/")[0];return i==="main"||i.includes(".")||i==="assets"?null:i}function _I(n){return n.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function Une(n,e){const t=n.replace(/\/+$/,"/"),r=new Set,i=(h,p)=>{if(h)try{const A=new URL(h,p||window.location.href).toString();r.add(A)}catch{r.add(h.replace(/\/+/g,"/"))}},s=`${window.location.origin}/`,a=new URL(t,s).toString();i("assets/config.json",a);const l=window.location.pathname.split("/").filter(Boolean);l.length>0&&l[l.length-1]==="index.html"&&l.pop(),l.length>0&&l[l.length-1]===(e??"main")&&l.pop();const c=`/${l.join("/")}${l.length?"/":""}`,d=`${window.location.origin}${c}`;return i("assets/config.json",d),i("assets/config.json"),i("../assets/config.json"),i("../../assets/config.json"),Array.from(r)}async function One(n,e){const r=new URLSearchParams(window.location.search).get("config"),i=Une(n,e);if(r)try{i.unshift(new URL(r,window.location.href).toString())}catch{i.unshift(r)}let s=null;for(const a of i)try{const o=await fetch(a,{cache:"no-store"});if(!o.ok)throw new Error(`Failed to fetch ${a}: ${o.status}`);const l=await o.text(),c=l.trim();if((o.headers.get("content-type")||"").includes("text/html")||c.startsWith("<!doctype")||c.startsWith("<html"))throw new Error(`Received HTML from ${a}`);try{return JSON.parse(l)}catch(h){throw new Error(`Invalid JSON from ${a}: ${h instanceof Error?h.message:String(h)}`)}}catch(o){s=o instanceof Error?o:new Error(String(o))}throw s??new Error("Failed to load config.json.")}function ZR(n,e){if(!n.scenes.length)return null;if(!e)return n.scenes[0];const t=e.trim().toLowerCase();return n.scenes.find(r=>r.name.toLowerCase()===t)||n.scenes.find(r=>_I(r.name)===t)||n.scenes[0]}function Y_(n,e){if(!n.policies.length)return null;const t=n.policies.find(s=>s.default)??n.policies[0];if(!e)return t.name;const r=e.trim().toLowerCase();return(n.policies.find(s=>s.name.toLowerCase()===r)||n.policies.find(s=>_I(s.name)===r))?.name??t.name}function Xf(n,e){return n?.motions?.length?(n.motions.find(r=>r.default)??n.motions[0]).name:null}function $ne(n){return new URLSearchParams(n).get($w)!=="0"}function Gne(n){return new URLSearchParams(n).get(Gw)!=="0"}function Hne(n){const t="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let r=t?`/${t}/`:"/";return n&&n!=="main"&&(r+=`${n}/`),r}function Vne({projectId:n,sceneName:e,policyName:t,panelVisible:r,showReference:i}){const s=Hne(n),a=new URLSearchParams(window.location.search);e?a.set("scene",e):a.delete("scene"),t?a.set("policy",t):a.delete("policy"),r?a.delete($w):a.set($w,"0"),i?a.delete(Gw):a.set(Gw,"0");const o=a.toString(),l=s+(o?`?${o}`:"")+window.location.hash;window.history.replaceState({},"",l)}function jne(){const[n,e]=U.useState(null),[t,r]=U.useState(null),[i,s]=U.useState(null),[a,o]=U.useState(null),[l,c]=U.useState(null),[d,h]=U.useState(()=>Gne(window.location.search)),[p,A]=U.useState(null),[y,m]=U.useState(null),[x,g]=U.useState(null),[_,b]=U.useState(()=>$ne(window.location.search)),w=U.useRef(null),{showLoading:C,hideLoading:S}=i4(),M=U.useMemo(()=>zne(),[]),T=U.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),R=U.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);U.useEffect(()=>{C(),One("/",M).then(X=>{e(X);const ge=X.projects.find(Ce=>M===null?Ce.id===null:Ce.id===M);if(!ge)throw new Error(`Project "${M??"(main)"}" not found in config.json.`);r(ge);const te=ZR(ge,T);s(te);const ee=te?Y_(te,R):null;o(ee);const ie=te?.policies.find(Ce=>Ce.name===ee)??null;c(Xf(ie))}).catch(X=>{console.error("Failed to load config:",X),A(X.message||"Failed to load config."),S()})},[M,T,R,C,S]);const k=U.useMemo(()=>{if(!t||!i)return null;const X=t.id?t.id:"main",ge=i.path?i.path:`scene/${_I(i.name)}/scene.xml`;return`${X}/assets/${ge}`.replace(/\/+/g,"/")},[t,i]),G=U.useMemo(()=>!i||!a?null:i.policies.find(X=>X.name===a)??null,[i,a]),P=U.useMemo(()=>!t||!G?.config?null:`${t.id?t.id:"main"}/assets/${G.config}`.replace(/\/+/g,"/"),[t,G]),V=U.useMemo(()=>G?.motions?.length?G.motions.map(X=>({value:X.name,label:X.name})):[],[G]),B=U.useMemo(()=>{if(!t||!i?.splats?.length)return[];const X=t.id?t.id:"main";return i.splats.map(ge=>{if(ge.path){const te=`${X}/assets/${ge.path}`.replace(/\/+/g,"/");return{...ge,url:te}}return ge})},[t,i?.splats]),W=U.useMemo(()=>y?B.find(X=>X.name===y)??null:x?{name:"Custom",url:x}:null,[B,y,x]),K=U.useMemo(()=>n?n.projects.map(X=>({value:X.id??"main",label:X.name||(X.id??"Main")})):[],[n]),Y=U.useMemo(()=>t?t.scenes.map(X=>({value:X.name,label:X.name})):[],[t]),$=U.useMemo(()=>!i||!i.policies?[]:i.policies.map(X=>({value:X.name,label:X.name})),[i]),J=t?t.id??"main":null,re=i?.name??null,L=U.useCallback(X=>{A(X.message),S()},[S]),H=U.useCallback(()=>{S()},[S]);U.useEffect(()=>{const X=i?.splats?.[0];m(X?X.name:null),g(null)},[i]);const oe=U.useCallback(X=>{w.current=X},[]);U.useEffect(()=>{c(Xf(G)),h(!!G?.motions?.length)},[G]);const Ae=U.useMemo(()=>i?.splats?.length?i.splats.map(X=>({value:X.name,label:X.name})):[],[i?.splats]),ye=U.useCallback(X=>{if(X===null)w.current?.setSplat(null);else{const ge=B.find(te=>te.name===X);ge&&w.current?.setSplat(ge)}m(X),g(null)},[B]),he=U.useCallback(async X=>{try{if(!(await fetch(X,{method:"HEAD"})).ok)return!1}catch{return!1}return w.current?.setSplat({name:"Custom",url:X}),g(X),!0},[]),fe=U.useCallback((X,ge,te,ee,ie,Ce,be)=>{const de=W??(x?{name:"Custom",url:x}:null);de&&w.current?.calibrateSplat({...de,scale:X,xOffset:ge,yOffset:te,zOffset:ee,roll:ie,pitch:Ce,yaw:be})},[W,x]),Ee=U.useCallback(X=>{Vne({projectId:X.projectId??t?.id??null,sceneName:X.sceneName??i?.name??null,policyName:X.policyName??a,panelVisible:X.panelVisible??_,showReference:X.showReference??d})},[t?.id,i?.name,a,_,d]),Re=U.useCallback(X=>{if(!n||!X)return;const ge=X==="main"?null:X,te=n.projects.find(be=>(be.id??"main")===(ge??"main"));if(!te)return;C(),r(te);const ee=ZR(te,null);s(ee);const ie=ee?Y_(ee,null):null;o(ie);const Ce=ee?.policies.find(be=>be.name===ie)??null;c(Xf(Ce)),Ee({projectId:te.id,sceneName:ee?.name??null,policyName:ie})},[n,C,Ee]),ve=U.useCallback(X=>{if(!t||!X)return;const ge=t.scenes.find(ie=>ie.name===X);if(!ge)return;C(),s(ge);const te=Y_(ge,null);o(te);const ee=ge.policies.find(ie=>ie.name===te)??null;c(Xf(ee)),Ee({projectId:t.id,sceneName:X,policyName:te})},[t,C,Ee]),Ne=U.useCallback(X=>{X!==a&&C(),o(X);const ge=i?.policies.find(te=>te.name===X)??null;c(Xf(ge)),Ee({policyName:X})},[a,C,Ee]),ct=U.useCallback(X=>{b(X),Ee({panelVisible:X})},[Ee]),Ge=U.useCallback(X=>{c(X),w.current?.setSelectedMotion(X)},[]),F=U.useCallback(X=>{h(X),w.current?.setReferenceVisible(X),Ee({showReference:X})},[Ee]);return p?j.jsx(tb,{theme:Ow,defaultColorScheme:"auto",children:j.jsx("div",{className:"app",children:j.jsxs("div",{className:"hud hud-error",children:[j.jsx("h1",{className:"hud-title",children:"mjswan"}),j.jsx("p",{className:"hud-message",children:p})]})})}):!t||!i||!k?null:j.jsx(tb,{theme:Ow,defaultColorScheme:"auto",children:j.jsxs("div",{className:"app",children:[j.jsx(Fne,{}),j.jsx(Qne,{visible:_,onVisibleChange:ct,projects:K,projectValue:J,projectLabel:t?.name??"mjswan",onProjectChange:Re,scenes:Y,sceneValue:re,onSceneChange:ve,splats:Ae,splatSection:i?.splatSection??!1,splatValue:y,onSplatChange:ye,splatConfig:W,onCalibrateSplat:fe,onSplatUrlLoad:he,policies:$,policyValue:a,onPolicyChange:Ne,motions:V,motionValue:l,onMotionChange:Ge,showReferenceMotion:d,onShowReferenceMotionChange:F,commandsEnabled:!!P}),j.jsx(mne,{scenePath:k,baseUrl:"/",policyConfigPath:P,splatConfig:W,cameraConfig:i?.camera,eventsConfig:i?.events,terrainData:i?.terrainData,selectedMotion:l,showReferenceMotion:d,onError:L,onReady:H,onRuntimeReady:oe})]})})}function Wne(){return j.jsx(Lne,{children:j.jsx(jne,{})})}const eD=document.getElementById("root");eD&&W4.createRoot(eD).render(j.jsx(On.StrictMode,{children:j.jsx(Wne,{})}));export{RH as _};
|