mjswan 0.2.2 → 0.2.4

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.
@@ -15610,4 +15610,4 @@ fn calculateOutputIndex(index: u32) -> u32 {
15610
15610
  }`},xR=n=>{let e=n[1].dims,t=n[2].dims,r=n[0].dims,i=n[1].dataType,s=!(Pe.areEqual(e,t)&&Pe.areEqual(t,r)),a=e,o=Pe.size(e);if(s){let c=Hd.calcShape(Hd.calcShape(e,t,!1),r,!1);if(!c)throw new Error("Can't perform where op on the given tensors");a=c,o=Pe.size(a)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>yR(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)]})}},uz=n=>{n.compute(xR(n.inputs))}}),dz,ete=Ze(()=>{pee(),WC(),Aee(),mee(),gee(),yee(),xee(),Eee(),Iee(),See(),Bee(),Mee(),Tee(),Ree(),Dee(),kee(),Nee(),Qee(),Pee(),Lee(),Fee(),zee(),Uee(),Oee(),$ee(),TF(),Gee(),Hee(),Vee(),jee(),Wee(),jC(),qee(),QF(),Yee(),Xee(),Jee(),kF(),Kee(),zl(),qC(),Zee(),dz=new Map([["Abs",[iL]],["Acos",[sL]],["Acosh",[aL]],["Add",[UL]],["ArgMax",[eL,bw]],["ArgMin",[ZP,bw]],["Asin",[oL]],["Asinh",[lL]],["Atan",[cL]],["Atanh",[uL]],["Attention",[tL]],["AveragePool",[HF,GF]],["BatchNormalization",[nL]],["BiasAdd",[rL]],["BiasSplitGelu",[zL]],["Cast",[hL,dL]],["Ceil",[pL]],["Clip",[fL]],["Concat",[XL,JL]],["Conv",[Bw,Sw]],["ConvTranspose",[oF,aF]],["Cos",[AL]],["Cosh",[mL]],["CumSum",[lF,cF]],["DepthToSpace",[uF,dF]],["DequantizeLinear",[JF,KF]],["Div",[OL]],["Einsum",[hF,fF]],["Elu",[gL,Jf]],["Equal",[$L]],["Erf",[yL]],["Exp",[xL]],["Expand",[pF]],["FastGelu",[AF]],["Floor",[vL]],["FusedConv",[Bw,Sw]],["Gather",[gF,mF]],["GatherElements",[wF,bF]],["GatherBlockQuantized",[vF,_F]],["GatherND",[yF,xF]],["Gelu",[_L]],["Gemm",[CF,EF]],["GlobalAveragePool",[jF,VF]],["GlobalMaxPool",[XF,YF]],["Greater",[jL]],["GreaterOrEqual",[qL]],["GridSample",[IF,SF]],["GroupQueryAttention",[PF]],["HardSigmoid",[ML,BL]],["InstanceNormalization",[LF]],["LayerNormalization",[FF]],["LeakyRelu",[bL,Jf]],["Less",[WL]],["LessOrEqual",[YL]],["Log",[LL]],["MatMul",[zF]],["MatMulNBits",[UF,OF]],["MaxPool",[WF,qF]],["Mul",[GL]],["MultiHeadAttention",[MF,BF]],["Neg",[EL]],["Not",[wL]],["Pad",[$F]],["Pow",[HL]],["QuickGelu",[FL,Jf]],["Range",[ZF]],["Reciprocal",[CL]],["ReduceMin",[qP]],["ReduceMean",[GP]],["ReduceMax",[WP]],["ReduceSum",[XP]],["ReduceProd",[YP]],["ReduceL1",[HP]],["ReduceL2",[VP]],["ReduceLogSum",[KP]],["ReduceLogSumExp",[jP]],["ReduceSumSquare",[JP]],["Relu",[IL]],["Resize",[nz,rz]],["RotaryEmbedding",[NF]],["ScatterND",[tz,ez]],["Sigmoid",[SL]],["Sin",[TL]],["Sinh",[RL]],["Slice",[sz,az]],["SkipLayerNormalization",[iz]],["Split",[RF,DF]],["Sqrt",[DL]],["Softmax",[oz,lz]],["Sub",[VL]],["Tan",[kL]],["Tanh",[NL]],["ThresholdedRelu",[PL,Jf]],["Tile",[cz]],["Transpose",[RP,DP]],["Where",[uz]]])}),hz,tte=Ze(()=>{ms(),Ro(),Wt(),hz=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){Qa(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(),Js(n.programInfo.name)}dispose(){}build(n,e){Qa(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=TP(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 Js(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]}}}),fz={};hh(fz,{WebGpuBackend:()=>pz});var vR,_R,bR,pz,nte=Ze(()=>{ms(),Lt(),Ro(),CP(),hee(),ete(),tte(),vR=(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("|")},_R=(n,e,t)=>{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${vR(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},bR=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},pz=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 bR(e.info||await e.requestAdapterInfo()),this.gpuDataManager=BP(this),this.programManager=new hz(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,$C(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;Qa(),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 g=Number(p-this.queryTimeBase),y=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(y))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:uo(x.dataType)})),outputsMetadata:h.map(x=>({dims:x.dims,dataType:uo(x.dataType)})),kernelId:s,kernelType:o,kernelName:l,programName:c,startTime:g,endTime:y});else{let x="";d.forEach((_,b)=>{x+=`input[${b}]: [${_.dims}] | ${uo(_.dataType)}, `});let m="";h.forEach((_,b)=>{m+=`output[${b}]: [${_.dims}] | ${uo(_.dataType)}, `}),console.log(`[profiling] kernel "${s}|${o}|${l}|${c}" ${x}${m}start time: ${g} ns, execution time: ${y-g} ns`)}Ug("GPU",`${c}::${p}::${A}`)}n.unmap(),this.pendingQueries.delete(n)}),Js()}run(n,e,t,r,i,s){Qa(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 Js(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 D=M.type===10?2:4,k,G;M.type===10?(G=T.length>4?16:T.length>2?8:T.length*D,k=T.length>4?16:D*T.length):(G=T.length<=2?T.length*D: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*D});let w=16;_=Math.ceil(_/w)*w;let C=new ArrayBuffer(_);c.forEach((M,T)=>{let D=b[T],k=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(C,D,k.length).set(k);else if(M.type===12)new Uint32Array(C,D,k.length).set(k);else if(M.type===10)new Uint16Array(C,D,k.length).set(k);else if(M.type===1)new Float32Array(C,D,k.length).set(k);else throw new Error(`Unsupported uniform type: ${uo(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 g=this.programManager.normalizeDispatchGroupSize(l),y=g[1]===1&&g[2]===1,x=_R(n,e,y),m=this.programManager.getArtifact(x);if(m||(m=this.programManager.build(n,g),this.programManager.setArtifact(x,m),un("info",()=>`[artifact] key: ${x}, programName: ${n.name}`)),c&&m.uniformVariablesInfo){if(c.length!==m.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${m.uniformVariablesInfo.length}, got ${c.length} in program "${m.programInfo.name}".`);for(let _=0;_<c.length;_++){let b=c[_],w=b.type,C=typeof b.data=="number"?1:b.data.length,[S,M]=m.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 "${m.programInfo.name}".`)}}if(un("info",()=>`[ProgramManager] run "${n.name}" (key=${x}) with ${g[0]}x${g[1]}x${g[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let _={kernelId:this.currentKernelId,programName:m.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(_),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(_)}return this.programManager.run(m,a,p,g,A),Js(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=dz.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 xw(this,n,e);return GC(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()}}}),Az={};hh(Az,{init:()=>mz});var qm,wR,mz,rte=Ze(()=>{Lt(),Ro(),jt(),dee(),qm=class gz{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=Pe.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=Pe.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=Pe.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=Pe.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Pe.size(e)!==Pe.size(this.dims))throw new Error("Invalid new shape");return new gz(this.module,this.dataType,this.data,e)}},wR=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 qm(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 qm(this.module,o,this.output(a,l),l),s=(a,o)=>{let l=Mc(a,o);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new qm(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)}}},mz=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=(nte(),Bp(fz)).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 wR(e,a,Number(l));return a.computeKernel(Number(o),h,d)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let s=new SP(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])}}}),ER,eI,tI,wl,CR,N_,Wg,nI,rI,Q_,iI,sI,aI,yz=Ze(()=>{ms(),lee(),cee(),Lt(),Zc(),FC(),_P(),ER=(n,e)=>{kn()._OrtInit(n,e)!==0&&wn("Can't initialize onnxruntime.")},eI=async n=>{ER(n.wasm.numThreads,$g(n.logLevel))},tI=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=(rte(),Bp(Az)).init;e==="webgpu"&&await r("webgpu",kn(),n,t),e==="webnn"&&await r("webnn",kn(),n)}},wl=new Map,CR=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)}},N_=(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)}},Wg=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]},nI=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]=Wg(n);let s=0,a=0,o=0,l=[],c=[],d=[];try{if([a,l]=await vP(e),e?.externalData&&i.mountExternalData){let w=[];for(let C of e.externalData){let S=typeof C=="string"?C:C.path;w.push(OC(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,D=C?.powerPreference;S?i.currentContext=S:M?i.currentContext=await i.webnnCreateMLContext(M):i.currentContext=await i.webnnCreateMLContext({deviceType:T,powerPreference:D})}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]=CR(s),A=!!e?.enableGraphCapture,g=[],y=[],x=[],m=[],_=[];for(let w=0;w<h;w++){let[C,S,M]=N_(s,w);C===0&&wn("Can't get an input name."),c.push(C);let T=i.UTF8ToString(C);g.push(T),x.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:uo(S),shape:M})}for(let w=0;w<p;w++){let[C,S,M]=N_(s,w+h);C===0&&wn("Can't get an output name."),d.push(C);let T=i.UTF8ToString(C);y.push(T),m.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:uo(S),shape:M});{if(A&&e?.preferredOutputLocation===void 0){_.push("gpu-buffer");continue}let D=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[T]??"cpu",k=i.webnnIsGraphOutput;if(D==="cpu"&&k&&k(s,T)){_.push("ml-tensor-cpu-output");continue}if(D!=="cpu"&&D!=="cpu-pinned"&&D!=="gpu-buffer"&&D!=="ml-tensor")throw new Error(`Not supported preferred output location: ${D}.`);if(A&&D!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${D}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(D)}}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=>gw(w))}),wl.set(s,[s,c,d,b,A,!1]),[s,g,y,x,m]}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?.()}},rI=n=>{let e=kn(),t=wl.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."),wl.delete(n)},Q_=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,g;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 m=n[2].gpuBuffer;g=Mc(Bc(c),d);{let _=o.jsepRegisterBuffer;if(!_)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=_(r,s,m,g)}}else if(h==="ml-tensor"){let m=n[2].mlTensor;g=Mc(Bc(c),d);let _=o.webnnRegisterMLTensor;if(!_)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=_(r,m,Bc(c),d)}else{let m=n[2];if(Array.isArray(m)){g=l*m.length,A=o._malloc(g),t.push(A);for(let _=0;_<m.length;_++){if(typeof m[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);o.setValue(A+_*l,Us(m[_],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=Bc(c);g=Mc(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(m.buffer,m.byteOffset,m.byteLength)),A=T}else g=m.byteLength,A=o._malloc(g),t.push(A),o.HEAPU8.set(new Uint8Array(m.buffer,m.byteOffset,g),A)}else g=m.byteLength,A=o._malloc(g),t.push(A),o.HEAPU8.set(new Uint8Array(m.buffer,m.byteOffset,g),A)}}let y=o.stackSave(),x=o.stackAlloc(4*d.length);try{d.forEach((_,b)=>o.setValue(x+b*l,_,l===4?"i32":"i64"));let m=o._OrtCreateTensor(Bc(c),A,g,x,d.length,gw(p));m===0&&wn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(m)}finally{o.stackRestore(y)}},iI=async(n,e,t,r,i,s)=>{let a=kn(),o=a.PTR_SIZE,l=wl.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],g=l[5],y=e.length,x=r.length,m=0,_=[],b=[],w=[],C=[],S=[],M=a.stackSave(),T=a.stackAlloc(y*o),D=a.stackAlloc(y*o),k=a.stackAlloc(x*o),G=a.stackAlloc(x*o);try{[m,_]=xP(s),Fc("wasm prepareInputOutputTensor");for(let j=0;j<y;j++)await Q_(t[j],b,C,n,d[e[j]],e[j],A);for(let j=0;j<x;j++)await Q_(i[j],w,C,n,h[r[j]],y+r[j],A);zc("wasm prepareInputOutputTensor");for(let j=0;j<y;j++)a.setValue(T+j*o,b[j],"*"),a.setValue(D+j*o,d[e[j]],"*");for(let j=0;j<x;j++)a.setValue(k+j*o,w[j],"*"),a.setValue(G+j*o,h[r[j]],"*");if(p&&!g){let{handle:j,outputPreferredLocations:J,outputPreferredLocationsEncoded:X}=p;if(d.length!==y)throw new Error(`input count from feeds (${y}) is expected to be always equal to model's input count (${d.length}).`);Fc("wasm bindInputsOutputs");for(let $=0;$<y;$++){let Y=e[$];await a._OrtBindInput(j,d[Y],b[$])!==0&&wn(`Can't bind input[${$}] for session=${n}.`)}for(let $=0;$<x;$++){let Y=r[$];i[$]?.[3]?(S.push(w[$]),a._OrtBindOutput(j,h[Y],w[$],0)!==0&&wn(`Can't bind pre-allocated output[${$}] for session=${n}.`)):a._OrtBindOutput(j,h[Y],0,X[Y])!==0&&wn(`Can't bind output[${$}] to ${J[$]} for session=${n}.`)}zc("wasm bindInputsOutputs"),wl.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,m):P=await a._OrtRun(c,D,T,y,G,x,k,m),P!==0&&wn("failed to call OrtRun().");let H=[],B=[];Fc("wasm ProcessOutputTensor");for(let j=0;j<x;j++){let J=Number(a.getValue(k+j*o,"*"));if(J===w[j]||S.includes(w[j])){H.push(i[j]),J!==w[j]&&a._OrtReleaseTensor(J)!==0&&wn("Can't release tensor.");continue}let X=a.stackSave(),$=a.stackAlloc(4*o),Y=!1,ne,L=0;try{a._OrtGetTensorData(J,$,$+o,$+2*o,$+3*o)!==0&&wn(`Can't access output tensor data on index ${j}.`);let V=o===4?"i32":"i64",se=Number(a.getValue($,V));L=a.getValue($+o,"*");let ae=a.getValue($+o*2,"*"),Ae=Number(a.getValue($+o*3,V)),ue=[];for(let Te=0;Te<Ae;Te++)ue.push(Number(a.getValue(ae+Te*o,V)));a._OrtFree(ae)!==0&&wn("Can't free memory for tensor dims.");let fe=ue.reduce((Te,ke)=>Te*ke,1);ne=uo(se);let we=p?.outputPreferredLocations[r[j]];if(ne==="string"){if(we==="gpu-buffer"||we==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Te=[];for(let ke=0;ke<fe;ke++){let Oe=a.getValue(L+ke*o,"*"),ft=a.getValue(L+(ke+1)*o,"*"),He=ke===fe-1?void 0:ft-Oe;Te.push(a.UTF8ToString(Oe,He))}H.push([ne,ue,Te,"cpu"])}else if(we==="gpu-buffer"&&fe>0){let Te=a.jsepGetBuffer;if(!Te)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ke=Te(L),Oe=Mc(se,fe);if(Oe===void 0||!zC(ne))throw new Error(`Unsupported data type: ${ne}`);Y=!0,H.push([ne,ue,{gpuBuffer:ke,download:a.jsepCreateDownloader(ke,Oe,ne),dispose:()=>{a._OrtReleaseTensor(J)!==0&&wn("Can't release tensor.")}},"gpu-buffer"])}else if(we==="ml-tensor"&&fe>0){let Te=a.webnnEnsureTensor,ke=a.webnnIsGraphInputOutputTypeSupported;if(!Te||!ke)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Mc(se,fe)===void 0||!UC(ne))throw new Error(`Unsupported data type: ${ne}`);if(!ke(n,ne,!1))throw new Error(`preferredLocation "ml-tensor" for ${ne} output is not supported by current WebNN Context.`);let Oe=await Te(n,L,se,ue,!1);Y=!0,H.push([ne,ue,{mlTensor:Oe,download:a.webnnCreateMLTensorDownloader(L,ne),dispose:()=>{a.webnnReleaseTensorId(L),a._OrtReleaseTensor(J)}},"ml-tensor"])}else if(we==="ml-tensor-cpu-output"&&fe>0){let Te=a.webnnCreateMLTensorDownloader(L,ne)(),ke=H.length;Y=!0,B.push((async()=>{let Oe=[ke,await Te];return a.webnnReleaseTensorId(L),a._OrtReleaseTensor(J),Oe})()),H.push([ne,ue,[],"cpu"])}else{let Te=V0(ne),ke=new Te(fe);new Uint8Array(ke.buffer,ke.byteOffset,ke.byteLength).set(a.HEAPU8.subarray(L,L+ke.byteLength)),H.push([ne,ue,ke,"cpu"])}}finally{a.stackRestore(X),ne==="string"&&L&&a._free(L),Y||a._OrtReleaseTensor(J)}}p&&!A&&(a._OrtClearBoundOutputs(p.handle)!==0&&wn("Can't clear bound outputs."),wl.set(n,[c,d,h,p,A,!1]));for(let[j,J]of await Promise.all(B))H[j][2]=J;return zc("wasm ProcessOutputTensor"),H}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)),m!==0&&a._OrtReleaseRunOptions(m),_.forEach(P=>a._free(P))}},sI=n=>{let e=kn(),t=wl.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)},aI=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),El,Zi,fd,zf,Uf,Ym,P_,Xm,xc,vc,IR,xz,vz,_z,bz,wz,Ez,Cz,Iz=Ze(()=>{ms(),yz(),Zc(),PC(),El=()=>!!Dn.wasm.proxy&&typeof document<"u",fd=!1,zf=!1,Uf=!1,Xm=new Map,xc=(n,e)=>{let t=Xm.get(n);t?t.push(e):Xm.set(n,[e])},vc=()=>{if(fd||!zf||Uf||!Zi)throw new Error("worker not ready")},IR=n=>{switch(n.data.type){case"init-wasm":fd=!1,n.data.err?(Uf=!0,P_[1](n.data.err)):(zf=!0,P_[0]()),Ym&&(URL.revokeObjectURL(Ym),Ym=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Xm.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},xz=async()=>{if(!zf){if(fd)throw new Error("multiple calls to 'initWasm()' detected.");if(Uf)throw new Error("previous call to 'initWasm()' failed.");if(fd=!0,El())return new Promise((n,e)=>{Zi?.terminate(),gP().then(([t,r])=>{try{Zi=r,Zi.onerror=s=>e(s),Zi.onmessage=IR,P_=[n,e];let i={type:"init-wasm",in:Dn};!i.in.wasm.wasmPaths&&(t||mw)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href}),Zi.postMessage(i),Ym=t}catch(i){e(i)}},e)});try{await LC(Dn.wasm),await eI(Dn),zf=!0}catch(n){throw Uf=!0,n}finally{fd=!1}}},vz=async n=>{if(El())return vc(),new Promise((e,t)=>{xc("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Dn}};Zi.postMessage(r)});await tI(Dn,n)},_z=async n=>El()?(vc(),new Promise((e,t)=>{xc("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};Zi.postMessage(r,[n.buffer])})):Wg(n),bz=async(n,e)=>{if(El()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return vc(),new Promise((t,r)=>{xc("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},s=[];n instanceof Uint8Array&&s.push(n.buffer),Zi.postMessage(i,s)})}else return nI(n,e)},wz=async n=>{if(El())return vc(),new Promise((e,t)=>{xc("release",[e,t]);let r={type:"release",in:n};Zi.postMessage(r)});rI(n)},Ez=async(n,e,t,r,i,s)=>{if(El()){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 vc(),new Promise((a,o)=>{xc("run",[a,o]);let l=t,c={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:s}};Zi.postMessage(c,aI(l))})}else return iI(n,e,t,r,i,s)},Cz=async n=>{if(El())return vc(),new Promise((e,t)=>{xc("end-profiling",[e,t]);let r={type:"end-profiling",in:n};Zi.postMessage(r)});sI(n)}}),L_,SR,Sz,ite=Ze(()=>{ms(),Iz(),Lt(),QC(),_P(),L_=(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()}`)}},SR=n=>{switch(n[3]){case"cpu":return new Ci(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 Ci.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}case"ml-tensor":{let e=n[0];if(!UC(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:r,dispose:i}=n[2];return Ci.fromMLTensor(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},Sz=class{async fetchModelAndCopyToWasmMemory(n){return _z(await OC(n))}async loadModel(n,e){Qa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await bz(t,e),Js()}async dispose(){return wz(this.sessionId)}async run(n,e,t){Qa();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],A=h[1],g=this.inputNames.indexOf(p);if(g===-1)throw new Error(`invalid input '${p}'`);r.push(A),i.push(g)});let s=[],a=[];Object.entries(e).forEach(h=>{let p=h[0],A=h[1],g=this.outputNames.indexOf(p);if(g===-1)throw new Error(`invalid output '${p}'`);s.push(A),a.push(g)});let o=r.map((h,p)=>L_(h,()=>`input "${this.inputNames[i[p]]}"`)),l=s.map((h,p)=>h?L_(h,()=>`output "${this.outputNames[a[p]]}"`):null),c=await Ez(this.sessionId,i,o,a,l,t),d={};for(let h=0;h<c.length;h++)d[this.outputNames[a[h]]]=s[h]??SR(c[h]);return Js(),d}startProfiling(){}endProfiling(){Cz(this.sessionId)}}}),Bz={};hh(Bz,{OnnxruntimeWebAssemblyBackend:()=>Rw,initializeFlags:()=>Tw,wasmBackend:()=>Mz});var Tw,Rw,Mz,ste=Ze(()=>{ms(),Iz(),ite(),Tw=()=>{(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"?HZ("node:os").cpus().length:navigator.hardwareConcurrency;Dn.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Rw=class{async init(n){Tw(),await xz(),await vz(n)}async createInferenceSessionHandler(n,e){let t=new Sz;return await t.loadModel(n,e),t}},Mz=new Rw});ms();ms();ms();var ate="1.24.3";{let n=(ste(),Bp(Bz)).wasmBackend;gd("webgpu",n,5),gd("webnn",n,5),gd("cpu",n,10),gd("wasm",n,10)}Object.defineProperty(Dn.versions,"web",{value:ate,enumerable:!0});class ote{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)}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)}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.obs_config??{};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 lte{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.inKeys=t.map(i=>Array.isArray(i)?i.join(","):i),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 NC.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"})}initInput(){return this.isRecurrent?{is_init:new Ci("bool",[!0],[1]),adapt_hx:new Ci("float32",new Float32Array(128),[1,128])}:{}}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 Ci("bool",[!1],[1]),s.adapt_hx=i["next,adapt_hx"]),[i,s]}}class cte{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}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 Tz{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class ute{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 dte extends Tz{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 ute(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class hte{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 fte extends Tz{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 hte(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class Rz 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 BR(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 pte{constructor(e,t,r={}){this.render=()=>{if(this.controls.update(),this.mjModel&&this.mjData&&this.bodies){F7(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),c.updateWorldMatrix(!0,!1))}L7(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&H7({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 QV,this.scene.name="scene",this.camera=new Lr(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 A7({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=mN,this.renderer.outputColorSpace=ni,this.renderer.toneMapping=gN,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported("immersive-vr").then(o=>{o&&(this.vrButton=vC.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new g7(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:V7()},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.splatMesh=null,this.colliderMesh=null,this.sceneCacheManager=Aw.getInstance(this.mujoco),this.resourceTracker=new gZ,this.memoryMonitor=new yZ}async loadEnvironment(e,t=null,r=null){await this.stop(),this.splatMesh&&(z3(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(j3(this.colliderMesh,this.scene),this.colliderMesh=null);const i=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const s=performance.now()-i;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:s})}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.resourceTracker.startTracking(this.mujoco),await Z7(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);r&&(this.splatMesh=F3(r,this.scene),r.colliderUrl&&(this.colliderMesh=await V3(this.resolveAssetUrl(r.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.running=!0,this.startLoop()}initializeCommands(){const e=os();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e){os().registerCommandsFromConfig(e),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 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 K7(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),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=new W3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls})),this.loadingScene=null})(),await this.loadingScene}async loadSceneWithOomRetry(e){try{await this.loadScene(e)}catch(t){if(!BR(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,BR(r)?new Rz:r}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&(z3(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(j3(this.colliderMesh,this.scene),this.colliderMesh=null),e&&(this.splatMesh=F3(e,this.scene),e.colliderUrl&&(this.colliderMesh=await V3(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&$Q(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();if(this.mjModel&&this.mjData){if(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}this.executeSimulationSteps(),this.updateCachedState()}const t=(performance.now()-e)/1e3,r=this.timestep*this.decimation,i=Math.max(0,r-t);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;const r=os();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(i.commands&&typeof i.commands=="object"&&this.initializeCommandsFromConfig(i.commands),!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new ote(i,{policyModules:{tracking:dte,locomotion:fte},observations:UZ});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData}),this.policyRunner=s,this.policyStateBuilder=new cte(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.onnx?.path){const o=this.resolvePolicyAssetPath(e,i.onnx.path),l=this.resolveAssetUrl(o),c={...i.onnx,path:l},d=new lte(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=e.control_type??"joint_position";if(i!=="joint_position"&&i!=="torque")return console.warn(`[PolicyRunner] Unsupported control_type: ${i}`),null;const s=r.getControlMapping();if(!s)return console.warn("[PolicyRunner] Failed to build control mapping."),null;const a=s.qposAdr.length,o=this.normalizeControlArray(e.action_scale,a,1),l=t.getDefaultJointPos(),c=this.normalizeControlArray(e.stiffness,a,0),d=this.normalizeControlArray(e.damping,a,0),h=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,p=s.ctrlAdr.map(y=>y<0||!this.mjModel?!1:this.mjModel.actuator_biastype[y]===h),A=p.some(Boolean),g=p.some(y=>!y);return A&&g&&console.warn("[PolicyRunner] Mixed actuator types detected; behavior may be incorrect."),console.log(`[PolicyRunner] Actuator mode: ${A?"position (ctrl=target_pos)":"motor (ctrl=torque, external PD)"}`),{controlType:i,...s,actionScale:o,defaultJointPos:l,positionActuator:p,kp:c,kd:d}}normalizeControlArray(e,t,r){const i=new Float32Array(t);if(typeof e=="number")return i.fill(e),i;if(Array.isArray(e)){for(let s=0;s<t;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}return i.fill(r),i}resetSimulationState(){!this.mjModel||!this.mjData||(this.mujoco.mj_resetData(this.mjModel,this.mjData),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{controlType:e,ctrlAdr:t,qposAdr:r,qvelAdr:i,actionScale:s,defaultJointPos:a,positionActuator:o,kp:l,kd:c}=this.policyControl,d=t.length,h=this.policyRunner?.getLastActions()??new Float32Array(d),p=this.mjData.ctrl;if(p.fill(0),e==="joint_position")for(let A=0;A<d;A++){const g=a[A]+s[A]*h[A],y=t[A];if(!(y<0))if(o[A])p[y]=g;else{const x=this.mjData.qpos[r[A]],m=this.mjData.qvel[i[A]];p[y]=l[A]*(g-x)+c[A]*(0-m)}}else if(e==="torque")for(let A=0;A<d;A++){const g=t[A];g>=0&&(p[g]=s[A]*h[A])}}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};for(const[c,d]of Object.entries(e))t[c]=new Ci("float32",d,[1,d.length]);for(const c of this.onnxModule.inKeys)if(!t[c]){console.warn("[PolicyRunner] Missing ONNX input:",{key:c,available:Object.keys(t)});return}const[r,i]=await this.onnxModule.runInference(t);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i});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);if(this.policyControl&&l.length!==this.policyControl.ctrlAdr.length){console.warn("[PolicyRunner] Action size mismatch:",{expected:this.policyControl.ctrlAdr.length,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;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(wp(this.mjData.xpos,p,this.bodies[p].position),rw(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=_3(r),s=this.dragStateManager.worldHit.clone(),a=_3(s),o=new he(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),l=new he(a.x-o.x,a.y-o.y,a.z-o.z),c=new he(i.x,i.y,i.z),d=new he().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)){for(let e=0;e<this.mjModel.nbody;e++)if(this.bodies[e]){this.lastSimState.bodies.has(e)||this.lastSimState.bodies.set(e,{position:new he,quaternion:new Cn});const t=this.lastSimState.bodies.get(e);wp(this.mjData.xpos,e,t.position),rw(this.mjData.xquat,e,t.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&G7(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}}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.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.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=new W3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls}))}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 oh?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 Jm="mjswan_oom_reload_scene",Ate=({scenePath:n,baseUrl:e,policyConfigPath:t,splatConfig:r,onStatusChange:i,onError:s,onReady:a,onRuntimeReady:o})=>{const l=U.useRef(null),c=U.useRef(null),d=U.useRef(null),h=U.useRef(r);return h.current=r,U.useEffect(()=>{let p=!1;const A=y=>{i?.(y)};return(async()=>{if(A("Loading MuJoCo..."),!d.current){const b=await import("/assets/mujoco/mujoco.js".replace(/\/+/g,"/"));d.current=await b.default()}if(p)return;const y=l.current;if(!y)throw new Error("Failed to find viewer container.");const x=d.current;if(!x)throw new Error("MuJoCo not loaded.");c.current||(c.current=new pte(x,y,{baseUrl:e}),o?.(c.current)),A("Loading scene assets..."),await c.current.loadEnvironment(n,t??null,h.current??null),!p&&(sessionStorage.removeItem(Jm),A("Running simulation"),a?.())})().catch(y=>{if(!p){if(y instanceof Rz){if(sessionStorage.getItem(Jm)!==n){console.warn("[MjswanViewer] OOM — reloading page to free memory..."),sessionStorage.setItem(Jm,n),window.location.reload();return}sessionStorage.removeItem(Jm)}console.error("Failed to initialize MuJoCo viewer:",y),s?.(y instanceof Error?y:new Error(String(y))),A("Failed to load scene")}}),()=>{p=!0,c.current?.dispose(),c.current=null}},[n,e,t,i,s,a]),W.jsx("div",{ref:l,className:"viewer"})};var mte={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 oI=(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,...mte[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,g])=>U.createElement(A,g)),...Array.isArray(d)?d:[d]]));return i.displayName=`${t}`,i};const gte=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],Dz=oI("outline","chevron-down","ChevronDown",gte);const yte=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],xte=oI("outline","chevron-up","ChevronUp",yte);const vte=[["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"}]],_te=oI("outline","refresh","Refresh",vte),MR="0.2.2",TR=[{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"}],bte={move:"touchmove",end:"touchend"},wte={move:"mousemove",end:"mouseup"};function Ete(n){return n.type==="touchmove"}function Cte(n){return n.type==="mousemove"}const Fp=On.createContext(null);function ho({children:n,width:e}){const t=On.useRef(null),[r,{toggle:i}]=Jg(!0),[s,a]=On.useState(800),o=On.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),l=On.useRef({}),c=(A,g,y)=>Math.abs(A+g/2)<Math.abs(A-y+g/2)?A:A-y,d=15;function h(A,g){const y=t.current;if(y===null)return[A,g];const x=y.parentElement;if(x===null)return[A,g];let m=A,_=g;return m=Math.min(m,x.clientWidth-y.clientWidth-d),m=Math.max(m,d),_=Math.min(_,x.clientHeight-y.clientHeight-d),_=Math.max(_,d),y.style.top=`${_.toString()}px`,y.style.left=`${m.toString()}px`,[c(m,y.clientWidth,x.clientWidth),c(_,y.clientHeight,x.clientHeight)]}On.useEffect(()=>{const A=t.current;if(A===null)return;const g=A.parentElement;if(g===null)return;const y=new ResizeObserver(()=>{l.current.x===void 0&&(l.current.x=c(A.offsetLeft,A.clientWidth,g.clientWidth)),l.current.y===void 0&&(l.current.y=c(A.offsetTop,A.clientHeight,g.clientHeight));const x=g.clientHeight-d*2;s!==x&&a(x);let m=l.current.x,_=l.current.y;for(;m<0;)m+=g.clientWidth;for(;_<0;)_+=g.clientHeight;h(m,_)});return y.observe(A),y.observe(g),()=>{y.disconnect()}});const p=A=>{const g=o.current,y=t.current;if(!y)return;A.type=="touchstart"?(A=A,g.startClientX=A.touches[0].clientX,g.startClientY=A.touches[0].clientY):(A=A,g.startClientX=A.clientX,g.startClientY=A.clientY),g.startPosX=y.offsetLeft,g.startPosY=y.offsetTop;const x=A.type=="touchstart"?bte:wte;function m(_){let b=0,w=0;if(Ete(_)?(_=_,b=_.touches[0].clientX-g.startClientX,w=_.touches[0].clientY-g.startClientY):Cte(_)&&(_=_,b=_.clientX-g.startClientX,w=_.clientY-g.startClientY),Math.abs(b)<=3&&Math.abs(w)<=3)return;g.dragging=!0;const C=g.startPosX+b,S=g.startPosY+w;[l.current.x,l.current.y]=h(C,S)}window.addEventListener(x.move,m),window.addEventListener(x.end,()=>{A.type=="touchstart"&&(g.dragging=!1),window.removeEventListener(x.move,m)},{once:!0})};return W.jsx(Fp.Provider,{value:{wrapperRef:t,expanded:r,width:e,maxHeight:s,toggleExpanded:i,dragHandler:p,dragInfo:o},children:W.jsx(Oc,{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:t,children:n})})}ho.Handle=function({children:e}){const t=On.useContext(Fp);return W.jsx(W.Fragment,{children:W.jsx(nt,{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})})};ho.Contents=function({children:e}){const t=On.useContext(Fp);return W.jsxs(vg,{in:t.expanded,children:[W.jsx(_d,{mx:"xs"}),W.jsx(Xc.Autosize,{mah:t.maxHeight,children:W.jsx(nt,{style:{width:t.width},children:e})})]})};ho.HideWhenCollapsed=function({children:e}){return On.useContext(Fp)?.expanded??!0?e:null};ho.HideWhenExpanded=function({children:e}){return On.useContext(Fp)?.expanded??!0?null:e};function F_({id:n,label:e,children:t}){return W.jsx(nt,{pb:"0.5em",px:"xs",children:W.jsxs(fE,{align:"center",children:[W.jsx(nt,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:W.jsx("label",{htmlFor:n,children:e})})}),W.jsx(nt,{style:{flexGrow:1},children:t})]})})}function kz({label:n,expandByDefault:e=!0,children:t}){const[r,{toggle:i}]=Jg(e),s=r?xte:Dz;return W.jsxs(Oc,{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:[W.jsxs(Oc,{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,W.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),W.jsx(vg,{in:r,children:W.jsx(nt,{pt:"1em",children:t})}),W.jsx(vg,{in:!r,children:W.jsx(nt,{p:"xs"})})]})}const Nz={fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"4.5em",flexShrink:0},Ite={root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}},Ste={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 z_({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 g=a.current;g&&document.activeElement!==g&&(g.value=e.toFixed(2))},[e]);const l=g=>Math.max(t,Math.min(r,parseFloat((Math.round(g/i)*i).toFixed(10)))),c=g=>{g.preventDefault(),g.currentTarget.setPointerCapture(g.pointerId),o.current={startY:g.clientY,startValue:e,moved:!1}},d=g=>{if(!o.current||!(g.buttons&1))return;const y=o.current.startY-g.clientY;if(Math.abs(y)>3&&(o.current.moved=!0),!o.current.moved)return;const x=l(o.current.startValue+y*i);s(x),a.current&&(a.current.value=x.toFixed(2))},h=()=>{if(o.current&&!o.current.moved){const g=a.current;g&&(g.focus(),g.select())}o.current=null},p=g=>{const y=parseFloat(g.target.value);isNaN(y)||s(l(y)),g.target.value=e.toFixed(2)},A=g=>{g.key==="Enter"&&g.currentTarget.blur(),g.key==="Escape"&&(a.current&&(a.current.value=e.toFixed(2)),a.current?.blur())};return W.jsxs(nt,{style:{display:"flex",alignItems:"center",gap:"0.25em",flex:1},children:[W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,letterSpacing:"-0.75px",flexShrink:0},children:n}),W.jsx("input",{ref:a,size:1,defaultValue:e.toFixed(2),onPointerDown:c,onPointerMove:d,onPointerUp:h,onBlur:p,onKeyDown:A,onFocus:g=>g.currentTarget.style.outline="2px solid var(--mantine-color-blue-5)",onBlurCapture:g=>g.currentTarget.style.outline="none",style:Ste})]})}function RR({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 W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[W.jsx(qs,{c:"dimmed",style:Nz,children:n}),W.jsx(z_,{axis:s,value:e,step:i,onChange:l}),W.jsx(z_,{axis:a,value:t,step:i,onChange:c}),W.jsx(z_,{axis:o,value:r,step:i,onChange:d})]})}function Bte({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),[g,y]=U.useState(r),[x,m]=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(()=>{y(r)},[r]),U.useEffect(()=>{m(i)},[i]),U.useEffect(()=>{b(s)},[s]),U.useEffect(()=>{C(a)},[a]);const S=(M,T,D,k,G,P,H)=>o(M,T,D,k,G,P,H);return W.jsxs(kz,{label:"Control",expandByDefault:!0,children:[W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[W.jsx(qs,{c:"dimmed",style:Nz,children:"Scale"}),W.jsx(nt,{style:{flex:1},children:W.jsx(B0,{value:l,onChange:M=>{c(M),S(M,d,p,g,x,_,w)},min:.1,max:5,step:.05,size:"xs",label:M=>M.toFixed(2),styles:Ite})})]}),W.jsx(RR,{label:"Position",x:d,y:p,z:g,step:.05,onX:M=>{h(M),S(l,M,p,g,x,_,w)},onY:M=>{A(M),S(l,d,M,g,x,_,w)},onZ:M=>{y(M),S(l,d,p,M,x,_,w)}}),W.jsx(RR,{label:"Rotation",x,y:_,z:w,step:.5,xLabel:"R",yLabel:"P",zLabel:"Y",onX:M=>{m(M),S(l,d,p,g,M,_,w)},onY:M=>{b(M),S(l,d,p,g,x,M,w)},onZ:M=>{C(M),S(l,d,p,g,x,_,M)}})]})}function Mte(n){return n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Tte({command:n,value:e,onChange:t,disabled:r}){const i=n.config;return W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:i.label}),W.jsx(nt,{style:{width:"50%"},children:W.jsx(B0,{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 Rte(n){const{projects:e,projectValue:t,projectLabel:r,onProjectChange:i,scenes:s,sceneValue:a,onSceneChange:o,splats:l,splatSection:c=!1,splatValue:d,onSplatChange:h,splatConfig:p,onCalibrateSplat:A,onSplatUrlLoad:g,policies:y,policyValue:x,onPolicyChange:m,commandsEnabled:_=!1,onReset:b}=n,[w,{open:C,close:S}]=Jg(!1),[M,T]=U.useState(""),[D,k]=U.useState(null),[G,P]=U.useState(!1),H=U.useCallback(async se=>{if(se.key!=="Enter"||!g)return;const ae=M.trim();if(l.some(ue=>ue.label===ae||ue.value===ae))return;if(!ae.toLowerCase().endsWith(".spz")){k("URL must end with .spz");return}await g(ae)?(k(null),P(!0)):k("File not found at the specified URL")},[g,M,l]),[B,j]=U.useState([]),[J,X]=U.useState([]),[$,Y]=U.useState({});U.useEffect(()=>{const se=os(),ae=()=>{j(se.getCommands()),X(se.getCommandGroups()),Y(se.getValues())};return ae(),se.addEventListener(ae),()=>{se.removeEventListener(ae)}},[]);const ne=U.useCallback((se,ae)=>{os().setValue(se,ae),Y(ue=>({...ue,[se]:ae}))},[]),L=U.useCallback(()=>{os().triggerButton("_system:reset"),b&&b()},[b]),V=se=>B.filter(ae=>ae.groupName===se&&ae.config.type==="slider");return!e.length&&!s.length&&!y.length?null:W.jsxs(W.Fragment,{children:[W.jsx(ra,{opened:w,onClose:S,size:"lg",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:W.jsxs(qE,{gap:"md",align:"center",children:[W.jsx(Sg,{src:"./logo-color.svg",style:{width:"8em",height:"auto"}}),W.jsx(qs,{size:"xl",fw:700,children:"powered by mjswan"}),W.jsxs(qs,{size:"sm",c:"dimmed",children:["version ",MR]}),W.jsx(qs,{size:"sm",c:"dimmed",children:"MuJoco Simulation on Web Assembly with Neural netwroks"}),W.jsx(_d,{w:"100%"}),W.jsxs(nt,{children:[W.jsx(ep,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"}),"  •  ",W.jsx(ep,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]}),W.jsx(_d,{w:"100%"}),W.jsxs(nt,{style:{textAlign:"left",maxHeight:"120px",overflowY:"auto",lineHeight:"1",fontSize:"0.8rem",opacity:"0.75"},px:"md",children:["Thanks to our contributors! ",W.jsx("br",{}),TR.map((se,ae)=>W.jsxs("span",{children:[W.jsx(ep,{href:se.html_url,target:"_blank",style:{textDecoration:"none",fontSize:"0.75rem"},children:se.login}),ae<TR.length-1&&", "]},se.login))]})]})}),W.jsxs(ho,{width:"20em",children:[W.jsxs(ho.Handle,{children:[W.jsx(kd,{label:`mjswan ${MR}`,children:W.jsx(nt,{component:"a",onClick:se=>{se.stopPropagation(),C()},style:{position:"absolute",cursor:"pointer",display:"flex",top:"0.8em",left:"0.9em"},children:W.jsx(Sg,{src:"./logo.svg",style:{width:"1.2em",height:"auto"}})})}),W.jsx("div",{style:{width:"1.1em"}}),W.jsx(ho.HideWhenCollapsed,{children:W.jsxs(nt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[W.jsx("span",{style:{flexGrow:1},children:r}),e.length>1&&W.jsxs(hi,{position:"bottom-start",offset:5,children:[W.jsx(hi.Target,{children:W.jsx(nt,{onClick:se=>se.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center"},children:W.jsx(Dz,{size:16})})}),W.jsx(hi.Dropdown,{onClick:se=>se.stopPropagation(),children:e.map(se=>W.jsx(hi.Item,{onClick:ae=>{ae.stopPropagation(),i(se.value)},style:{fontWeight:se.value===t?600:400,backgroundColor:se.value===t?"rgba(34, 139, 230, 0.1)":void 0},children:se.label},se.value))})]})]})}),W.jsx(ho.HideWhenExpanded,{children:W.jsx(nt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:r})})]}),W.jsx(ho.Contents,{children:W.jsxs(nt,{pt:"0.375em",children:[s.length>0&&W.jsx(F_,{id:"scene-select",label:"Scene",children:W.jsx(wd,{id:"scene-select",placeholder:"Select scene",data:s,value:a,onChange:o,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),(l.length>0||c)&&W.jsx(F_,{id:"splat-select",label:"Splat",children:W.jsx(kd,{label:D??"",color:"red",position:"bottom",opened:D!==null,withArrow:!0,children:W.jsx(wd,{id:"splat-select",placeholder:g!==void 0?"Select splat or paste .spz URL":"Select splat",data:l,value:d,onChange:se=>{h(se),k(null),P(!1)},searchable:g!==void 0,searchValue:M,onSearchChange:se=>{T(se),se&&k(null)},onKeyDown:H,size:"xs",radius:"xs",clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})})}),(p?.control&&d!==null||G)&&A&&W.jsx(Bte,{scale:p?.scale??1,xOffset:p?.xOffset??0,yOffset:p?.yOffset??0,zOffset:p?.zOffset??0,roll:p?.roll??0,pitch:p?.pitch??0,yaw:p?.yaw??0,onCalibrate:A}),y.length>0&&W.jsx(F_,{id:"policy-select",label:"Policy",children:W.jsx(wd,{id:"policy-select",placeholder:"Select policy",data:y,value:x,onChange:m,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),J.length>0&&B.filter(se=>se.config.type==="slider").length>0&&W.jsx(W.Fragment,{children:J.map(se=>{const ae=V(se);return ae.length===0?null:W.jsx(kz,{label:Mte(se),expandByDefault:!0,children:ae.map(Ae=>W.jsx(Tte,{command:Ae,value:$[Ae.id]??0,onChange:ne,disabled:!_},Ae.id))},se)})}),W.jsx(_d,{mb:"xs",mx:"xs"}),W.jsx(nt,{px:"xs",pb:"xs",children:W.jsx(th,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:W.jsx(_te,{size:14}),onClick:L,children:"Reset"})})]})})]})]})}function Of(n,e,t){return Object.keys(n[e]).reduce((r,i)=>(r[i]=`var(--mantine-${t}-${i})`,r),{})}function DR(n,e){return n in e.breakpoints?e.breakpoints[n]:$_(n)}function Dte(n){const e=iD(t0,n),t=Of(e,"fontSizes","font-size"),r=Of(e,"lineHeights","line-height"),i=Of(e,"shadows","shadow"),s=Of(e,"radius","radius"),a=Of(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: ${DR(c,e)})`,largerThan:c=>`(min-width: ${DR(c,e)})`}}const Dw={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:Zd.extend({defaultProps:{radius:"xs"}}),ColorInput:QE.extend({defaultProps:{radius:"xs"}}),Select:wd.extend({defaultProps:{radius:"sm"}}),Textarea:LE.extend({defaultProps:{radius:"xs"}}),TextInput:YE.extend({defaultProps:{radius:"xs"}}),NumberInput:VE.extend({defaultProps:{radius:"xs"}}),Paper:Oc.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:Kd.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:th.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};Dte(Dw);const Qz=U.createContext(void 0),Pz=()=>{const n=U.useContext(Qz);if(!n)throw new Error("useLoading must be used within a LoadingProvider");return n},kte=({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 W.jsx(Qz.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:n})},Nte=()=>{const{isLoading:n}=Pz();return n?W.jsx("div",{className:"loader-overlay",children:W.jsx("div",{className:"loader-content",children:W.jsx(Xd,{size:64,type:"bars"})})}):null};function Qte(){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 lI(n){return n.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function Pte(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 Lte(n,e){const r=new URLSearchParams(window.location.search).get("config"),i=Pte(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 kR(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=>lI(r.name)===t)||n.scenes[0]}function NR(n,e){if(!n.policies.length)return null;if(!e)return n.policies[0].name;const t=e.trim().toLowerCase();return(n.policies.find(i=>i.name.toLowerCase()===t)||n.policies.find(i=>lI(i.name)===t))?.name??n.policies[0].name}function U_(n,e,t){const i="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let s=i?`/${i}/`:"/";n&&n!=="main"&&(s+=`${n}/`);const a=new URLSearchParams;e&&a.set("scene",e),t&&a.set("policy",t);const o=s+(a.toString()?"?"+a.toString():"");window.history.replaceState({},"",o)}function Fte(){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(null),[p,A]=U.useState(null),g=U.useRef(null),{showLoading:y,hideLoading:x}=Pz(),m=U.useMemo(()=>Qte(),[]),_=U.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),b=U.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);U.useEffect(()=>{y(),Lte("/",m).then(ae=>{e(ae);const Ae=ae.projects.find(we=>m===null?we.id===null:we.id===m);if(!Ae)throw new Error(`Project "${m??"(main)"}" not found in config.json.`);r(Ae);const ue=kR(Ae,_);s(ue);const fe=ue?NR(ue,b):null;o(fe)}).catch(ae=>{console.error("Failed to load config:",ae),c(ae.message||"Failed to load config."),x()})},[m,_,b,y,x]);const w=U.useMemo(()=>{if(!t||!i)return null;const ae=t.id?t.id:"main",Ae=i.path?i.path:`scene/${lI(i.name)}/scene.xml`;return`${ae}/assets/${Ae}`.replace(/\/+/g,"/")},[t,i]),C=U.useMemo(()=>!i||!a?null:i.policies.find(ae=>ae.name===a)??null,[i,a]),S=U.useMemo(()=>!t||!C?.config?null:`${t.id?t.id:"main"}/assets/${C.config}`.replace(/\/+/g,"/"),[t,C]),M=U.useMemo(()=>{if(!t||!i?.splats?.length)return[];const ae=t.id?t.id:"main";return i.splats.map(Ae=>{if(Ae.path){const ue=`${ae}/assets/${Ae.path}`.replace(/\/+/g,"/");return{...Ae,url:ue}}return Ae})},[t,i?.splats]),T=U.useMemo(()=>d?M.find(ae=>ae.name===d)??null:p?{name:"Custom",url:p}:null,[M,d,p]),D=U.useMemo(()=>n?n.projects.map(ae=>({value:ae.id??"main",label:ae.name||(ae.id??"Main")})):[],[n]),k=U.useMemo(()=>t?t.scenes.map(ae=>({value:ae.name,label:ae.name})):[],[t]),G=U.useMemo(()=>!i||!i.policies?[]:i.policies.map(ae=>({value:ae.name,label:ae.name})),[i]),P=t?t.id??"main":null,H=i?.name??null,B=U.useCallback(ae=>{c(ae.message),x()},[x]),j=U.useCallback(()=>{x()},[x]);U.useEffect(()=>{const ae=i?.splats?.[0];h(ae?ae.name:null),A(null)},[i]);const J=U.useCallback(ae=>{g.current=ae},[]),X=U.useMemo(()=>i?.splats?.length?i.splats.map(ae=>({value:ae.name,label:ae.name})):[],[i?.splats]),$=U.useCallback(ae=>{if(ae===null)g.current?.setSplat(null);else{const Ae=M.find(ue=>ue.name===ae);Ae&&g.current?.setSplat(Ae)}h(ae),A(null)},[M]),Y=U.useCallback(async ae=>{try{if(!(await fetch(ae,{method:"HEAD"})).ok)return!1}catch{return!1}return g.current?.setSplat({name:"Custom",url:ae}),A(ae),!0},[]),ne=U.useCallback((ae,Ae,ue,fe,we,Te,ke)=>{const Oe=T??(p?{name:"Custom",url:p}:null);Oe&&g.current?.calibrateSplat({...Oe,scale:ae,xOffset:Ae,yOffset:ue,zOffset:fe,roll:we,pitch:Te,yaw:ke})},[T,p]),L=U.useCallback(ae=>{if(!n||!ae)return;const Ae=ae==="main"?null:ae,ue=n.projects.find(Te=>(Te.id??"main")===(Ae??"main"));if(!ue)return;y(),r(ue);const fe=kR(ue,null);s(fe);const we=fe?.policies?.[0]?.name??null;o(we),U_(ue.id,fe?.name??null,we)},[n,y]),V=U.useCallback(ae=>{if(!t||!ae)return;const Ae=t.scenes.find(fe=>fe.name===ae);if(!Ae)return;y(),s(Ae);const ue=NR(Ae,null);o(ue),U_(t.id,ae,ue)},[t,y]),se=U.useCallback(ae=>{ae!==a&&y(),o(ae),U_(t?.id??null,i?.name??null,ae)},[t,i,a,y]);return l?W.jsx(j_,{theme:Dw,defaultColorScheme:"auto",children:W.jsx("div",{className:"app",children:W.jsxs("div",{className:"hud hud-error",children:[W.jsx("h1",{className:"hud-title",children:"mjswan"}),W.jsx("p",{className:"hud-message",children:l})]})})}):!t||!i||!w?null:W.jsx(j_,{theme:Dw,defaultColorScheme:"auto",children:W.jsxs("div",{className:"app",children:[W.jsx(Nte,{}),W.jsx(Rte,{projects:D,projectValue:P,projectLabel:t?.name??"mjswan",onProjectChange:L,scenes:k,sceneValue:H,onSceneChange:V,splats:X,splatSection:i?.splatSection??!1,splatValue:d,onSplatChange:$,splatConfig:T,onCalibrateSplat:ne,onSplatUrlLoad:Y,policies:G,policyValue:a,onPolicyChange:se,commandsEnabled:!!S}),W.jsx(Ate,{scenePath:w,baseUrl:"/",policyConfigPath:S,splatConfig:T,onError:B,onReady:j,onRuntimeReady:J})]})})}function zte(){return W.jsx(kte,{children:W.jsx(Fte,{})})}const QR=document.getElementById("root");QR&&C4.createRoot(QR).render(W.jsx(On.StrictMode,{children:W.jsx(zte,{})}));
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 Js(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]}}}),fz={};hh(fz,{WebGpuBackend:()=>pz});var vR,_R,bR,pz,nte=Ze(()=>{ms(),Lt(),Ro(),CP(),hee(),ete(),tte(),vR=(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("|")},_R=(n,e,t)=>{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${vR(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},bR=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},pz=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 bR(e.info||await e.requestAdapterInfo()),this.gpuDataManager=BP(this),this.programManager=new hz(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,$C(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;Qa(),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 g=Number(p-this.queryTimeBase),y=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(y))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:uo(x.dataType)})),outputsMetadata:h.map(x=>({dims:x.dims,dataType:uo(x.dataType)})),kernelId:s,kernelType:o,kernelName:l,programName:c,startTime:g,endTime:y});else{let x="";d.forEach((_,b)=>{x+=`input[${b}]: [${_.dims}] | ${uo(_.dataType)}, `});let m="";h.forEach((_,b)=>{m+=`output[${b}]: [${_.dims}] | ${uo(_.dataType)}, `}),console.log(`[profiling] kernel "${s}|${o}|${l}|${c}" ${x}${m}start time: ${g} ns, execution time: ${y-g} ns`)}Ug("GPU",`${c}::${p}::${A}`)}n.unmap(),this.pendingQueries.delete(n)}),Js()}run(n,e,t,r,i,s){Qa(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 Js(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 D=M.type===10?2:4,k,G;M.type===10?(G=T.length>4?16:T.length>2?8:T.length*D,k=T.length>4?16:D*T.length):(G=T.length<=2?T.length*D: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*D});let w=16;_=Math.ceil(_/w)*w;let C=new ArrayBuffer(_);c.forEach((M,T)=>{let D=b[T],k=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(C,D,k.length).set(k);else if(M.type===12)new Uint32Array(C,D,k.length).set(k);else if(M.type===10)new Uint16Array(C,D,k.length).set(k);else if(M.type===1)new Float32Array(C,D,k.length).set(k);else throw new Error(`Unsupported uniform type: ${uo(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 g=this.programManager.normalizeDispatchGroupSize(l),y=g[1]===1&&g[2]===1,x=_R(n,e,y),m=this.programManager.getArtifact(x);if(m||(m=this.programManager.build(n,g),this.programManager.setArtifact(x,m),un("info",()=>`[artifact] key: ${x}, programName: ${n.name}`)),c&&m.uniformVariablesInfo){if(c.length!==m.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${m.uniformVariablesInfo.length}, got ${c.length} in program "${m.programInfo.name}".`);for(let _=0;_<c.length;_++){let b=c[_],w=b.type,C=typeof b.data=="number"?1:b.data.length,[S,M]=m.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 "${m.programInfo.name}".`)}}if(un("info",()=>`[ProgramManager] run "${n.name}" (key=${x}) with ${g[0]}x${g[1]}x${g[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let _={kernelId:this.currentKernelId,programName:m.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(_),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(_)}return this.programManager.run(m,a,p,g,A),Js(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=dz.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 xw(this,n,e);return GC(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()}}}),Az={};hh(Az,{init:()=>mz});var qm,wR,mz,rte=Ze(()=>{Lt(),Ro(),jt(),dee(),qm=class gz{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=Pe.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=Pe.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=Pe.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=Pe.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Pe.size(e)!==Pe.size(this.dims))throw new Error("Invalid new shape");return new gz(this.module,this.dataType,this.data,e)}},wR=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 qm(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 qm(this.module,o,this.output(a,l),l),s=(a,o)=>{let l=Mc(a,o);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new qm(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)}}},mz=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=(nte(),Bp(fz)).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 wR(e,a,Number(l));return a.computeKernel(Number(o),h,d)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let s=new SP(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])}}}),ER,eI,tI,wl,CR,N_,Wg,nI,rI,Q_,iI,sI,aI,yz=Ze(()=>{ms(),lee(),cee(),Lt(),Zc(),FC(),_P(),ER=(n,e)=>{kn()._OrtInit(n,e)!==0&&wn("Can't initialize onnxruntime.")},eI=async n=>{ER(n.wasm.numThreads,$g(n.logLevel))},tI=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=(rte(),Bp(Az)).init;e==="webgpu"&&await r("webgpu",kn(),n,t),e==="webnn"&&await r("webnn",kn(),n)}},wl=new Map,CR=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)}},N_=(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)}},Wg=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]},nI=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]=Wg(n);let s=0,a=0,o=0,l=[],c=[],d=[];try{if([a,l]=await vP(e),e?.externalData&&i.mountExternalData){let w=[];for(let C of e.externalData){let S=typeof C=="string"?C:C.path;w.push(OC(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,D=C?.powerPreference;S?i.currentContext=S:M?i.currentContext=await i.webnnCreateMLContext(M):i.currentContext=await i.webnnCreateMLContext({deviceType:T,powerPreference:D})}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]=CR(s),A=!!e?.enableGraphCapture,g=[],y=[],x=[],m=[],_=[];for(let w=0;w<h;w++){let[C,S,M]=N_(s,w);C===0&&wn("Can't get an input name."),c.push(C);let T=i.UTF8ToString(C);g.push(T),x.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:uo(S),shape:M})}for(let w=0;w<p;w++){let[C,S,M]=N_(s,w+h);C===0&&wn("Can't get an output name."),d.push(C);let T=i.UTF8ToString(C);y.push(T),m.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:uo(S),shape:M});{if(A&&e?.preferredOutputLocation===void 0){_.push("gpu-buffer");continue}let D=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[T]??"cpu",k=i.webnnIsGraphOutput;if(D==="cpu"&&k&&k(s,T)){_.push("ml-tensor-cpu-output");continue}if(D!=="cpu"&&D!=="cpu-pinned"&&D!=="gpu-buffer"&&D!=="ml-tensor")throw new Error(`Not supported preferred output location: ${D}.`);if(A&&D!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${D}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(D)}}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=>gw(w))}),wl.set(s,[s,c,d,b,A,!1]),[s,g,y,x,m]}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?.()}},rI=n=>{let e=kn(),t=wl.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."),wl.delete(n)},Q_=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,g;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 m=n[2].gpuBuffer;g=Mc(Bc(c),d);{let _=o.jsepRegisterBuffer;if(!_)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=_(r,s,m,g)}}else if(h==="ml-tensor"){let m=n[2].mlTensor;g=Mc(Bc(c),d);let _=o.webnnRegisterMLTensor;if(!_)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=_(r,m,Bc(c),d)}else{let m=n[2];if(Array.isArray(m)){g=l*m.length,A=o._malloc(g),t.push(A);for(let _=0;_<m.length;_++){if(typeof m[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);o.setValue(A+_*l,Us(m[_],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=Bc(c);g=Mc(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(m.buffer,m.byteOffset,m.byteLength)),A=T}else g=m.byteLength,A=o._malloc(g),t.push(A),o.HEAPU8.set(new Uint8Array(m.buffer,m.byteOffset,g),A)}else g=m.byteLength,A=o._malloc(g),t.push(A),o.HEAPU8.set(new Uint8Array(m.buffer,m.byteOffset,g),A)}}let y=o.stackSave(),x=o.stackAlloc(4*d.length);try{d.forEach((_,b)=>o.setValue(x+b*l,_,l===4?"i32":"i64"));let m=o._OrtCreateTensor(Bc(c),A,g,x,d.length,gw(p));m===0&&wn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(m)}finally{o.stackRestore(y)}},iI=async(n,e,t,r,i,s)=>{let a=kn(),o=a.PTR_SIZE,l=wl.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],g=l[5],y=e.length,x=r.length,m=0,_=[],b=[],w=[],C=[],S=[],M=a.stackSave(),T=a.stackAlloc(y*o),D=a.stackAlloc(y*o),k=a.stackAlloc(x*o),G=a.stackAlloc(x*o);try{[m,_]=xP(s),Fc("wasm prepareInputOutputTensor");for(let j=0;j<y;j++)await Q_(t[j],b,C,n,d[e[j]],e[j],A);for(let j=0;j<x;j++)await Q_(i[j],w,C,n,h[r[j]],y+r[j],A);zc("wasm prepareInputOutputTensor");for(let j=0;j<y;j++)a.setValue(T+j*o,b[j],"*"),a.setValue(D+j*o,d[e[j]],"*");for(let j=0;j<x;j++)a.setValue(k+j*o,w[j],"*"),a.setValue(G+j*o,h[r[j]],"*");if(p&&!g){let{handle:j,outputPreferredLocations:J,outputPreferredLocationsEncoded:X}=p;if(d.length!==y)throw new Error(`input count from feeds (${y}) is expected to be always equal to model's input count (${d.length}).`);Fc("wasm bindInputsOutputs");for(let $=0;$<y;$++){let Y=e[$];await a._OrtBindInput(j,d[Y],b[$])!==0&&wn(`Can't bind input[${$}] for session=${n}.`)}for(let $=0;$<x;$++){let Y=r[$];i[$]?.[3]?(S.push(w[$]),a._OrtBindOutput(j,h[Y],w[$],0)!==0&&wn(`Can't bind pre-allocated output[${$}] for session=${n}.`)):a._OrtBindOutput(j,h[Y],0,X[Y])!==0&&wn(`Can't bind output[${$}] to ${J[$]} for session=${n}.`)}zc("wasm bindInputsOutputs"),wl.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,m):P=await a._OrtRun(c,D,T,y,G,x,k,m),P!==0&&wn("failed to call OrtRun().");let H=[],B=[];Fc("wasm ProcessOutputTensor");for(let j=0;j<x;j++){let J=Number(a.getValue(k+j*o,"*"));if(J===w[j]||S.includes(w[j])){H.push(i[j]),J!==w[j]&&a._OrtReleaseTensor(J)!==0&&wn("Can't release tensor.");continue}let X=a.stackSave(),$=a.stackAlloc(4*o),Y=!1,ne,L=0;try{a._OrtGetTensorData(J,$,$+o,$+2*o,$+3*o)!==0&&wn(`Can't access output tensor data on index ${j}.`);let V=o===4?"i32":"i64",se=Number(a.getValue($,V));L=a.getValue($+o,"*");let ae=a.getValue($+o*2,"*"),Ae=Number(a.getValue($+o*3,V)),ue=[];for(let Te=0;Te<Ae;Te++)ue.push(Number(a.getValue(ae+Te*o,V)));a._OrtFree(ae)!==0&&wn("Can't free memory for tensor dims.");let fe=ue.reduce((Te,ke)=>Te*ke,1);ne=uo(se);let we=p?.outputPreferredLocations[r[j]];if(ne==="string"){if(we==="gpu-buffer"||we==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Te=[];for(let ke=0;ke<fe;ke++){let Oe=a.getValue(L+ke*o,"*"),ft=a.getValue(L+(ke+1)*o,"*"),He=ke===fe-1?void 0:ft-Oe;Te.push(a.UTF8ToString(Oe,He))}H.push([ne,ue,Te,"cpu"])}else if(we==="gpu-buffer"&&fe>0){let Te=a.jsepGetBuffer;if(!Te)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ke=Te(L),Oe=Mc(se,fe);if(Oe===void 0||!zC(ne))throw new Error(`Unsupported data type: ${ne}`);Y=!0,H.push([ne,ue,{gpuBuffer:ke,download:a.jsepCreateDownloader(ke,Oe,ne),dispose:()=>{a._OrtReleaseTensor(J)!==0&&wn("Can't release tensor.")}},"gpu-buffer"])}else if(we==="ml-tensor"&&fe>0){let Te=a.webnnEnsureTensor,ke=a.webnnIsGraphInputOutputTypeSupported;if(!Te||!ke)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Mc(se,fe)===void 0||!UC(ne))throw new Error(`Unsupported data type: ${ne}`);if(!ke(n,ne,!1))throw new Error(`preferredLocation "ml-tensor" for ${ne} output is not supported by current WebNN Context.`);let Oe=await Te(n,L,se,ue,!1);Y=!0,H.push([ne,ue,{mlTensor:Oe,download:a.webnnCreateMLTensorDownloader(L,ne),dispose:()=>{a.webnnReleaseTensorId(L),a._OrtReleaseTensor(J)}},"ml-tensor"])}else if(we==="ml-tensor-cpu-output"&&fe>0){let Te=a.webnnCreateMLTensorDownloader(L,ne)(),ke=H.length;Y=!0,B.push((async()=>{let Oe=[ke,await Te];return a.webnnReleaseTensorId(L),a._OrtReleaseTensor(J),Oe})()),H.push([ne,ue,[],"cpu"])}else{let Te=V0(ne),ke=new Te(fe);new Uint8Array(ke.buffer,ke.byteOffset,ke.byteLength).set(a.HEAPU8.subarray(L,L+ke.byteLength)),H.push([ne,ue,ke,"cpu"])}}finally{a.stackRestore(X),ne==="string"&&L&&a._free(L),Y||a._OrtReleaseTensor(J)}}p&&!A&&(a._OrtClearBoundOutputs(p.handle)!==0&&wn("Can't clear bound outputs."),wl.set(n,[c,d,h,p,A,!1]));for(let[j,J]of await Promise.all(B))H[j][2]=J;return zc("wasm ProcessOutputTensor"),H}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)),m!==0&&a._OrtReleaseRunOptions(m),_.forEach(P=>a._free(P))}},sI=n=>{let e=kn(),t=wl.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)},aI=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),El,Zi,fd,zf,Uf,Ym,P_,Xm,xc,vc,IR,xz,vz,_z,bz,wz,Ez,Cz,Iz=Ze(()=>{ms(),yz(),Zc(),PC(),El=()=>!!Dn.wasm.proxy&&typeof document<"u",fd=!1,zf=!1,Uf=!1,Xm=new Map,xc=(n,e)=>{let t=Xm.get(n);t?t.push(e):Xm.set(n,[e])},vc=()=>{if(fd||!zf||Uf||!Zi)throw new Error("worker not ready")},IR=n=>{switch(n.data.type){case"init-wasm":fd=!1,n.data.err?(Uf=!0,P_[1](n.data.err)):(zf=!0,P_[0]()),Ym&&(URL.revokeObjectURL(Ym),Ym=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Xm.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},xz=async()=>{if(!zf){if(fd)throw new Error("multiple calls to 'initWasm()' detected.");if(Uf)throw new Error("previous call to 'initWasm()' failed.");if(fd=!0,El())return new Promise((n,e)=>{Zi?.terminate(),gP().then(([t,r])=>{try{Zi=r,Zi.onerror=s=>e(s),Zi.onmessage=IR,P_=[n,e];let i={type:"init-wasm",in:Dn};!i.in.wasm.wasmPaths&&(t||mw)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href}),Zi.postMessage(i),Ym=t}catch(i){e(i)}},e)});try{await LC(Dn.wasm),await eI(Dn),zf=!0}catch(n){throw Uf=!0,n}finally{fd=!1}}},vz=async n=>{if(El())return vc(),new Promise((e,t)=>{xc("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Dn}};Zi.postMessage(r)});await tI(Dn,n)},_z=async n=>El()?(vc(),new Promise((e,t)=>{xc("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};Zi.postMessage(r,[n.buffer])})):Wg(n),bz=async(n,e)=>{if(El()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return vc(),new Promise((t,r)=>{xc("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},s=[];n instanceof Uint8Array&&s.push(n.buffer),Zi.postMessage(i,s)})}else return nI(n,e)},wz=async n=>{if(El())return vc(),new Promise((e,t)=>{xc("release",[e,t]);let r={type:"release",in:n};Zi.postMessage(r)});rI(n)},Ez=async(n,e,t,r,i,s)=>{if(El()){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 vc(),new Promise((a,o)=>{xc("run",[a,o]);let l=t,c={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:s}};Zi.postMessage(c,aI(l))})}else return iI(n,e,t,r,i,s)},Cz=async n=>{if(El())return vc(),new Promise((e,t)=>{xc("end-profiling",[e,t]);let r={type:"end-profiling",in:n};Zi.postMessage(r)});sI(n)}}),L_,SR,Sz,ite=Ze(()=>{ms(),Iz(),Lt(),QC(),_P(),L_=(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()}`)}},SR=n=>{switch(n[3]){case"cpu":return new Ci(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 Ci.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}case"ml-tensor":{let e=n[0];if(!UC(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:r,dispose:i}=n[2];return Ci.fromMLTensor(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},Sz=class{async fetchModelAndCopyToWasmMemory(n){return _z(await OC(n))}async loadModel(n,e){Qa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await bz(t,e),Js()}async dispose(){return wz(this.sessionId)}async run(n,e,t){Qa();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],A=h[1],g=this.inputNames.indexOf(p);if(g===-1)throw new Error(`invalid input '${p}'`);r.push(A),i.push(g)});let s=[],a=[];Object.entries(e).forEach(h=>{let p=h[0],A=h[1],g=this.outputNames.indexOf(p);if(g===-1)throw new Error(`invalid output '${p}'`);s.push(A),a.push(g)});let o=r.map((h,p)=>L_(h,()=>`input "${this.inputNames[i[p]]}"`)),l=s.map((h,p)=>h?L_(h,()=>`output "${this.outputNames[a[p]]}"`):null),c=await Ez(this.sessionId,i,o,a,l,t),d={};for(let h=0;h<c.length;h++)d[this.outputNames[a[h]]]=s[h]??SR(c[h]);return Js(),d}startProfiling(){}endProfiling(){Cz(this.sessionId)}}}),Bz={};hh(Bz,{OnnxruntimeWebAssemblyBackend:()=>Rw,initializeFlags:()=>Tw,wasmBackend:()=>Mz});var Tw,Rw,Mz,ste=Ze(()=>{ms(),Iz(),ite(),Tw=()=>{(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"?HZ("node:os").cpus().length:navigator.hardwareConcurrency;Dn.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Rw=class{async init(n){Tw(),await xz(),await vz(n)}async createInferenceSessionHandler(n,e){let t=new Sz;return await t.loadModel(n,e),t}},Mz=new Rw});ms();ms();ms();var ate="1.24.3";{let n=(ste(),Bp(Bz)).wasmBackend;gd("webgpu",n,5),gd("webnn",n,5),gd("cpu",n,10),gd("wasm",n,10)}Object.defineProperty(Dn.versions,"web",{value:ate,enumerable:!0});class ote{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)}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)}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.obs_config??{};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 lte{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.inKeys=t.map(i=>Array.isArray(i)?i.join(","):i),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 NC.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"})}initInput(){return this.isRecurrent?{is_init:new Ci("bool",[!0],[1]),adapt_hx:new Ci("float32",new Float32Array(128),[1,128])}:{}}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 Ci("bool",[!1],[1]),s.adapt_hx=i["next,adapt_hx"]),[i,s]}}class cte{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}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 Tz{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class ute{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 dte extends Tz{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 ute(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class hte{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 fte extends Tz{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 hte(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class Rz 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 BR(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 pte{constructor(e,t,r={}){this.render=()=>{if(this.controls.update(),this.mjModel&&this.mjData&&this.bodies){F7(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),c.updateWorldMatrix(!0,!1))}L7(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&H7({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 QV,this.scene.name="scene",this.camera=new Lr(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 A7({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=mN,this.renderer.outputColorSpace=ni,this.renderer.toneMapping=gN,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported("immersive-vr").then(o=>{o&&(this.vrButton=vC.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new g7(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:V7()},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.splatMesh=null,this.colliderMesh=null,this.sceneCacheManager=Aw.getInstance(this.mujoco),this.resourceTracker=new gZ,this.memoryMonitor=new yZ}async loadEnvironment(e,t=null,r=null){await this.stop(),this.splatMesh&&(z3(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(j3(this.colliderMesh,this.scene),this.colliderMesh=null);const i=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const s=performance.now()-i;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:s})}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.resourceTracker.startTracking(this.mujoco),await Z7(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);r&&(this.splatMesh=F3(r,this.scene),r.colliderUrl&&(this.colliderMesh=await V3(this.resolveAssetUrl(r.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.running=!0,this.startLoop()}initializeCommands(){const e=os();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e){os().registerCommandsFromConfig(e),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 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 K7(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),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=new W3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls})),this.loadingScene=null})(),await this.loadingScene}async loadSceneWithOomRetry(e){try{await this.loadScene(e)}catch(t){if(!BR(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,BR(r)?new Rz:r}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&(z3(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(j3(this.colliderMesh,this.scene),this.colliderMesh=null),e&&(this.splatMesh=F3(e,this.scene),e.colliderUrl&&(this.colliderMesh=await V3(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&$Q(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();if(this.mjModel&&this.mjData){if(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}this.executeSimulationSteps(),this.updateCachedState()}const t=(performance.now()-e)/1e3,r=this.timestep*this.decimation,i=Math.max(0,r-t);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;const r=os();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(i.commands&&typeof i.commands=="object"&&this.initializeCommandsFromConfig(i.commands),!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new ote(i,{policyModules:{tracking:dte,locomotion:fte},observations:UZ});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData}),this.policyRunner=s,this.policyStateBuilder=new cte(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.onnx?.path){const o=this.resolvePolicyAssetPath(e,i.onnx.path),l=this.resolveAssetUrl(o),c={...i.onnx,path:l},d=new lte(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=e.control_type??"joint_position";if(i!=="joint_position"&&i!=="torque")return console.warn(`[PolicyRunner] Unsupported control_type: ${i}`),null;const s=r.getControlMapping();if(!s)return console.warn("[PolicyRunner] Failed to build control mapping."),null;const a=s.qposAdr.length,o=this.normalizeControlArray(e.action_scale,a,1),l=t.getDefaultJointPos(),c=this.normalizeControlArray(e.stiffness,a,0),d=this.normalizeControlArray(e.damping,a,0),h=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,p=s.ctrlAdr.map(y=>y<0||!this.mjModel?!1:this.mjModel.actuator_biastype[y]===h),A=p.some(Boolean),g=p.some(y=>!y);return A&&g&&console.warn("[PolicyRunner] Mixed actuator types detected; behavior may be incorrect."),console.log(`[PolicyRunner] Actuator mode: ${A?"position (ctrl=target_pos)":"motor (ctrl=torque, external PD)"}`),{controlType:i,...s,actionScale:o,defaultJointPos:l,positionActuator:p,kp:c,kd:d}}normalizeControlArray(e,t,r){const i=new Float32Array(t);if(typeof e=="number")return i.fill(e),i;if(Array.isArray(e)){for(let s=0;s<t;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}return i.fill(r),i}resetSimulationState(){!this.mjModel||!this.mjData||(this.mujoco.mj_resetData(this.mjModel,this.mjData),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{controlType:e,ctrlAdr:t,qposAdr:r,qvelAdr:i,actionScale:s,defaultJointPos:a,positionActuator:o,kp:l,kd:c}=this.policyControl,d=t.length,h=this.policyRunner?.getLastActions()??new Float32Array(d),p=this.mjData.ctrl;if(p.fill(0),e==="joint_position")for(let A=0;A<d;A++){const g=a[A]+s[A]*h[A],y=t[A];if(!(y<0))if(o[A])p[y]=g;else{const x=this.mjData.qpos[r[A]],m=this.mjData.qvel[i[A]];p[y]=l[A]*(g-x)+c[A]*(0-m)}}else if(e==="torque")for(let A=0;A<d;A++){const g=t[A];g>=0&&(p[g]=s[A]*h[A])}}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};for(const[c,d]of Object.entries(e))t[c]=new Ci("float32",d,[1,d.length]);for(const c of this.onnxModule.inKeys)if(!t[c]){console.warn("[PolicyRunner] Missing ONNX input:",{key:c,available:Object.keys(t)});return}const[r,i]=await this.onnxModule.runInference(t);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i});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);if(this.policyControl&&l.length!==this.policyControl.ctrlAdr.length){console.warn("[PolicyRunner] Action size mismatch:",{expected:this.policyControl.ctrlAdr.length,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;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(wp(this.mjData.xpos,p,this.bodies[p].position),rw(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=_3(r),s=this.dragStateManager.worldHit.clone(),a=_3(s),o=new he(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),l=new he(a.x-o.x,a.y-o.y,a.z-o.z),c=new he(i.x,i.y,i.z),d=new he().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)){for(let e=0;e<this.mjModel.nbody;e++)if(this.bodies[e]){this.lastSimState.bodies.has(e)||this.lastSimState.bodies.set(e,{position:new he,quaternion:new Cn});const t=this.lastSimState.bodies.get(e);wp(this.mjData.xpos,e,t.position),rw(this.mjData.xquat,e,t.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&G7(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}}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.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.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=new W3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls}))}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 oh?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 Jm="mjswan_oom_reload_scene",Ate=({scenePath:n,baseUrl:e,policyConfigPath:t,splatConfig:r,onStatusChange:i,onError:s,onReady:a,onRuntimeReady:o})=>{const l=U.useRef(null),c=U.useRef(null),d=U.useRef(null),h=U.useRef(r);return h.current=r,U.useEffect(()=>{let p=!1;const A=y=>{i?.(y)};return(async()=>{if(A("Loading MuJoCo..."),!d.current){const b=await import("/assets/mujoco/mujoco.js".replace(/\/+/g,"/"));d.current=await b.default()}if(p)return;const y=l.current;if(!y)throw new Error("Failed to find viewer container.");const x=d.current;if(!x)throw new Error("MuJoCo not loaded.");c.current||(c.current=new pte(x,y,{baseUrl:e}),o?.(c.current)),A("Loading scene assets..."),await c.current.loadEnvironment(n,t??null,h.current??null),!p&&(sessionStorage.removeItem(Jm),A("Running simulation"),a?.())})().catch(y=>{if(!p){if(y instanceof Rz){if(sessionStorage.getItem(Jm)!==n){console.warn("[MjswanViewer] OOM — reloading page to free memory..."),sessionStorage.setItem(Jm,n),window.location.reload();return}sessionStorage.removeItem(Jm)}console.error("Failed to initialize MuJoCo viewer:",y),s?.(y instanceof Error?y:new Error(String(y))),A("Failed to load scene")}}),()=>{p=!0,c.current?.dispose(),c.current=null}},[n,e,t,i,s,a]),W.jsx("div",{ref:l,className:"viewer"})};var mte={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 oI=(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,...mte[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,g])=>U.createElement(A,g)),...Array.isArray(d)?d:[d]]));return i.displayName=`${t}`,i};const gte=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],Dz=oI("outline","chevron-down","ChevronDown",gte);const yte=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],xte=oI("outline","chevron-up","ChevronUp",yte);const vte=[["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"}]],_te=oI("outline","refresh","Refresh",vte),MR="0.2.4",TR=[{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"}],bte={move:"touchmove",end:"touchend"},wte={move:"mousemove",end:"mouseup"};function Ete(n){return n.type==="touchmove"}function Cte(n){return n.type==="mousemove"}const Fp=On.createContext(null);function ho({children:n,width:e}){const t=On.useRef(null),[r,{toggle:i}]=Jg(!0),[s,a]=On.useState(800),o=On.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),l=On.useRef({}),c=(A,g,y)=>Math.abs(A+g/2)<Math.abs(A-y+g/2)?A:A-y,d=15;function h(A,g){const y=t.current;if(y===null)return[A,g];const x=y.parentElement;if(x===null)return[A,g];let m=A,_=g;return m=Math.min(m,x.clientWidth-y.clientWidth-d),m=Math.max(m,d),_=Math.min(_,x.clientHeight-y.clientHeight-d),_=Math.max(_,d),y.style.top=`${_.toString()}px`,y.style.left=`${m.toString()}px`,[c(m,y.clientWidth,x.clientWidth),c(_,y.clientHeight,x.clientHeight)]}On.useEffect(()=>{const A=t.current;if(A===null)return;const g=A.parentElement;if(g===null)return;const y=new ResizeObserver(()=>{l.current.x===void 0&&(l.current.x=c(A.offsetLeft,A.clientWidth,g.clientWidth)),l.current.y===void 0&&(l.current.y=c(A.offsetTop,A.clientHeight,g.clientHeight));const x=g.clientHeight-d*2;s!==x&&a(x);let m=l.current.x,_=l.current.y;for(;m<0;)m+=g.clientWidth;for(;_<0;)_+=g.clientHeight;h(m,_)});return y.observe(A),y.observe(g),()=>{y.disconnect()}});const p=A=>{const g=o.current,y=t.current;if(!y)return;A.type=="touchstart"?(A=A,g.startClientX=A.touches[0].clientX,g.startClientY=A.touches[0].clientY):(A=A,g.startClientX=A.clientX,g.startClientY=A.clientY),g.startPosX=y.offsetLeft,g.startPosY=y.offsetTop;const x=A.type=="touchstart"?bte:wte;function m(_){let b=0,w=0;if(Ete(_)?(_=_,b=_.touches[0].clientX-g.startClientX,w=_.touches[0].clientY-g.startClientY):Cte(_)&&(_=_,b=_.clientX-g.startClientX,w=_.clientY-g.startClientY),Math.abs(b)<=3&&Math.abs(w)<=3)return;g.dragging=!0;const C=g.startPosX+b,S=g.startPosY+w;[l.current.x,l.current.y]=h(C,S)}window.addEventListener(x.move,m),window.addEventListener(x.end,()=>{A.type=="touchstart"&&(g.dragging=!1),window.removeEventListener(x.move,m)},{once:!0})};return W.jsx(Fp.Provider,{value:{wrapperRef:t,expanded:r,width:e,maxHeight:s,toggleExpanded:i,dragHandler:p,dragInfo:o},children:W.jsx(Oc,{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:t,children:n})})}ho.Handle=function({children:e}){const t=On.useContext(Fp);return W.jsx(W.Fragment,{children:W.jsx(nt,{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})})};ho.Contents=function({children:e}){const t=On.useContext(Fp);return W.jsxs(vg,{in:t.expanded,children:[W.jsx(_d,{mx:"xs"}),W.jsx(Xc.Autosize,{mah:t.maxHeight,children:W.jsx(nt,{style:{width:t.width},children:e})})]})};ho.HideWhenCollapsed=function({children:e}){return On.useContext(Fp)?.expanded??!0?e:null};ho.HideWhenExpanded=function({children:e}){return On.useContext(Fp)?.expanded??!0?null:e};function F_({id:n,label:e,children:t}){return W.jsx(nt,{pb:"0.5em",px:"xs",children:W.jsxs(fE,{align:"center",children:[W.jsx(nt,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:W.jsx("label",{htmlFor:n,children:e})})}),W.jsx(nt,{style:{flexGrow:1},children:t})]})})}function kz({label:n,expandByDefault:e=!0,children:t}){const[r,{toggle:i}]=Jg(e),s=r?xte:Dz;return W.jsxs(Oc,{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:[W.jsxs(Oc,{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,W.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),W.jsx(vg,{in:r,children:W.jsx(nt,{pt:"1em",children:t})}),W.jsx(vg,{in:!r,children:W.jsx(nt,{p:"xs"})})]})}const Nz={fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"4.5em",flexShrink:0},Ite={root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}},Ste={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 z_({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 g=a.current;g&&document.activeElement!==g&&(g.value=e.toFixed(2))},[e]);const l=g=>Math.max(t,Math.min(r,parseFloat((Math.round(g/i)*i).toFixed(10)))),c=g=>{g.preventDefault(),g.currentTarget.setPointerCapture(g.pointerId),o.current={startY:g.clientY,startValue:e,moved:!1}},d=g=>{if(!o.current||!(g.buttons&1))return;const y=o.current.startY-g.clientY;if(Math.abs(y)>3&&(o.current.moved=!0),!o.current.moved)return;const x=l(o.current.startValue+y*i);s(x),a.current&&(a.current.value=x.toFixed(2))},h=()=>{if(o.current&&!o.current.moved){const g=a.current;g&&(g.focus(),g.select())}o.current=null},p=g=>{const y=parseFloat(g.target.value);isNaN(y)||s(l(y)),g.target.value=e.toFixed(2)},A=g=>{g.key==="Enter"&&g.currentTarget.blur(),g.key==="Escape"&&(a.current&&(a.current.value=e.toFixed(2)),a.current?.blur())};return W.jsxs(nt,{style:{display:"flex",alignItems:"center",gap:"0.25em",flex:1},children:[W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,letterSpacing:"-0.75px",flexShrink:0},children:n}),W.jsx("input",{ref:a,size:1,defaultValue:e.toFixed(2),onPointerDown:c,onPointerMove:d,onPointerUp:h,onBlur:p,onKeyDown:A,onFocus:g=>g.currentTarget.style.outline="2px solid var(--mantine-color-blue-5)",onBlurCapture:g=>g.currentTarget.style.outline="none",style:Ste})]})}function RR({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 W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[W.jsx(qs,{c:"dimmed",style:Nz,children:n}),W.jsx(z_,{axis:s,value:e,step:i,onChange:l}),W.jsx(z_,{axis:a,value:t,step:i,onChange:c}),W.jsx(z_,{axis:o,value:r,step:i,onChange:d})]})}function Bte({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),[g,y]=U.useState(r),[x,m]=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(()=>{y(r)},[r]),U.useEffect(()=>{m(i)},[i]),U.useEffect(()=>{b(s)},[s]),U.useEffect(()=>{C(a)},[a]);const S=(M,T,D,k,G,P,H)=>o(M,T,D,k,G,P,H);return W.jsxs(kz,{label:"Control",expandByDefault:!0,children:[W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[W.jsx(qs,{c:"dimmed",style:Nz,children:"Scale"}),W.jsx(nt,{style:{flex:1},children:W.jsx(B0,{value:l,onChange:M=>{c(M),S(M,d,p,g,x,_,w)},min:.1,max:5,step:.05,size:"xs",label:M=>M.toFixed(2),styles:Ite})})]}),W.jsx(RR,{label:"Position",x:d,y:p,z:g,step:.05,onX:M=>{h(M),S(l,M,p,g,x,_,w)},onY:M=>{A(M),S(l,d,M,g,x,_,w)},onZ:M=>{y(M),S(l,d,p,M,x,_,w)}}),W.jsx(RR,{label:"Rotation",x,y:_,z:w,step:.5,xLabel:"R",yLabel:"P",zLabel:"Y",onX:M=>{m(M),S(l,d,p,g,M,_,w)},onY:M=>{b(M),S(l,d,p,g,x,M,w)},onZ:M=>{C(M),S(l,d,p,g,x,_,M)}})]})}function Mte(n){return n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Tte({command:n,value:e,onChange:t,disabled:r}){const i=n.config;return W.jsxs(nt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[W.jsx(qs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:i.label}),W.jsx(nt,{style:{width:"50%"},children:W.jsx(B0,{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 Rte(n){const{projects:e,projectValue:t,projectLabel:r,onProjectChange:i,scenes:s,sceneValue:a,onSceneChange:o,splats:l,splatSection:c=!1,splatValue:d,onSplatChange:h,splatConfig:p,onCalibrateSplat:A,onSplatUrlLoad:g,policies:y,policyValue:x,onPolicyChange:m,commandsEnabled:_=!1,onReset:b}=n,[w,{open:C,close:S}]=Jg(!1),[M,T]=U.useState(""),[D,k]=U.useState(null),[G,P]=U.useState(!1),H=U.useCallback(async se=>{if(se.key!=="Enter"||!g)return;const ae=M.trim();if(l.some(ue=>ue.label===ae||ue.value===ae))return;if(!ae.toLowerCase().endsWith(".spz")){k("URL must end with .spz");return}await g(ae)?(k(null),P(!0)):k("File not found at the specified URL")},[g,M,l]),[B,j]=U.useState([]),[J,X]=U.useState([]),[$,Y]=U.useState({});U.useEffect(()=>{const se=os(),ae=()=>{j(se.getCommands()),X(se.getCommandGroups()),Y(se.getValues())};return ae(),se.addEventListener(ae),()=>{se.removeEventListener(ae)}},[]);const ne=U.useCallback((se,ae)=>{os().setValue(se,ae),Y(ue=>({...ue,[se]:ae}))},[]),L=U.useCallback(()=>{os().triggerButton("_system:reset"),b&&b()},[b]),V=se=>B.filter(ae=>ae.groupName===se&&ae.config.type==="slider");return!e.length&&!s.length&&!y.length?null:W.jsxs(W.Fragment,{children:[W.jsx(ra,{opened:w,onClose:S,size:"lg",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:W.jsxs(qE,{gap:"md",align:"center",children:[W.jsx(Sg,{src:"./logo-color.svg",style:{width:"8em",height:"auto"}}),W.jsx(qs,{size:"xl",fw:700,children:"powered by mjswan"}),W.jsxs(qs,{size:"sm",c:"dimmed",children:["version ",MR]}),W.jsx(qs,{size:"sm",c:"dimmed",children:"MuJoco Simulation on Web Assembly with Neural netwroks"}),W.jsx(_d,{w:"100%"}),W.jsxs(nt,{children:[W.jsx(ep,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"}),"  •  ",W.jsx(ep,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]}),W.jsx(_d,{w:"100%"}),W.jsxs(nt,{style:{textAlign:"left",maxHeight:"120px",overflowY:"auto",lineHeight:"1",fontSize:"0.8rem",opacity:"0.75"},px:"md",children:["Thanks to our contributors! ",W.jsx("br",{}),TR.map((se,ae)=>W.jsxs("span",{children:[W.jsx(ep,{href:se.html_url,target:"_blank",style:{textDecoration:"none",fontSize:"0.75rem"},children:se.login}),ae<TR.length-1&&", "]},se.login))]})]})}),W.jsxs(ho,{width:"20em",children:[W.jsxs(ho.Handle,{children:[W.jsx(kd,{label:`mjswan ${MR}`,children:W.jsx(nt,{component:"a",onClick:se=>{se.stopPropagation(),C()},style:{position:"absolute",cursor:"pointer",display:"flex",top:"0.8em",left:"0.9em"},children:W.jsx(Sg,{src:"./logo.svg",style:{width:"1.2em",height:"auto"}})})}),W.jsx("div",{style:{width:"1.1em"}}),W.jsx(ho.HideWhenCollapsed,{children:W.jsxs(nt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[W.jsx("span",{style:{flexGrow:1},children:r}),e.length>1&&W.jsxs(hi,{position:"bottom-start",offset:5,children:[W.jsx(hi.Target,{children:W.jsx(nt,{onClick:se=>se.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center"},children:W.jsx(Dz,{size:16})})}),W.jsx(hi.Dropdown,{onClick:se=>se.stopPropagation(),children:e.map(se=>W.jsx(hi.Item,{onClick:ae=>{ae.stopPropagation(),i(se.value)},style:{fontWeight:se.value===t?600:400,backgroundColor:se.value===t?"rgba(34, 139, 230, 0.1)":void 0},children:se.label},se.value))})]})]})}),W.jsx(ho.HideWhenExpanded,{children:W.jsx(nt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:r})})]}),W.jsx(ho.Contents,{children:W.jsxs(nt,{pt:"0.375em",children:[s.length>0&&W.jsx(F_,{id:"scene-select",label:"Scene",children:W.jsx(wd,{id:"scene-select",placeholder:"Select scene",data:s,value:a,onChange:o,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),(l.length>0||c)&&W.jsx(F_,{id:"splat-select",label:"Splat",children:W.jsx(kd,{label:D??"",color:"red",position:"bottom",opened:D!==null,withArrow:!0,children:W.jsx(wd,{id:"splat-select",placeholder:g!==void 0?"Select splat or paste .spz URL":"Select splat",data:l,value:d,onChange:se=>{h(se),k(null),P(!1)},searchable:g!==void 0,searchValue:M,onSearchChange:se=>{T(se),se&&k(null)},onKeyDown:H,size:"xs",radius:"xs",clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})})}),(p?.control&&d!==null||G)&&A&&W.jsx(Bte,{scale:p?.scale??1,xOffset:p?.xOffset??0,yOffset:p?.yOffset??0,zOffset:p?.zOffset??0,roll:p?.roll??0,pitch:p?.pitch??0,yaw:p?.yaw??0,onCalibrate:A}),y.length>0&&W.jsx(F_,{id:"policy-select",label:"Policy",children:W.jsx(wd,{id:"policy-select",placeholder:"Select policy",data:y,value:x,onChange:m,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),J.length>0&&B.filter(se=>se.config.type==="slider").length>0&&W.jsx(W.Fragment,{children:J.map(se=>{const ae=V(se);return ae.length===0?null:W.jsx(kz,{label:Mte(se),expandByDefault:!0,children:ae.map(Ae=>W.jsx(Tte,{command:Ae,value:$[Ae.id]??0,onChange:ne,disabled:!_},Ae.id))},se)})}),W.jsx(_d,{mb:"xs",mx:"xs"}),W.jsx(nt,{px:"xs",pb:"xs",children:W.jsx(th,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:W.jsx(_te,{size:14}),onClick:L,children:"Reset"})})]})})]})]})}function Of(n,e,t){return Object.keys(n[e]).reduce((r,i)=>(r[i]=`var(--mantine-${t}-${i})`,r),{})}function DR(n,e){return n in e.breakpoints?e.breakpoints[n]:$_(n)}function Dte(n){const e=iD(t0,n),t=Of(e,"fontSizes","font-size"),r=Of(e,"lineHeights","line-height"),i=Of(e,"shadows","shadow"),s=Of(e,"radius","radius"),a=Of(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: ${DR(c,e)})`,largerThan:c=>`(min-width: ${DR(c,e)})`}}const Dw={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:Zd.extend({defaultProps:{radius:"xs"}}),ColorInput:QE.extend({defaultProps:{radius:"xs"}}),Select:wd.extend({defaultProps:{radius:"sm"}}),Textarea:LE.extend({defaultProps:{radius:"xs"}}),TextInput:YE.extend({defaultProps:{radius:"xs"}}),NumberInput:VE.extend({defaultProps:{radius:"xs"}}),Paper:Oc.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:Kd.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:th.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};Dte(Dw);const Qz=U.createContext(void 0),Pz=()=>{const n=U.useContext(Qz);if(!n)throw new Error("useLoading must be used within a LoadingProvider");return n},kte=({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 W.jsx(Qz.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:n})},Nte=()=>{const{isLoading:n}=Pz();return n?W.jsx("div",{className:"loader-overlay",children:W.jsx("div",{className:"loader-content",children:W.jsx(Xd,{size:64,type:"bars"})})}):null};function Qte(){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 lI(n){return n.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function Pte(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 Lte(n,e){const r=new URLSearchParams(window.location.search).get("config"),i=Pte(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 kR(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=>lI(r.name)===t)||n.scenes[0]}function NR(n,e){if(!n.policies.length)return null;if(!e)return n.policies[0].name;const t=e.trim().toLowerCase();return(n.policies.find(i=>i.name.toLowerCase()===t)||n.policies.find(i=>lI(i.name)===t))?.name??n.policies[0].name}function U_(n,e,t){const i="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let s=i?`/${i}/`:"/";n&&n!=="main"&&(s+=`${n}/`);const a=new URLSearchParams;e&&a.set("scene",e),t&&a.set("policy",t);const o=s+(a.toString()?"?"+a.toString():"");window.history.replaceState({},"",o)}function Fte(){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(null),[p,A]=U.useState(null),g=U.useRef(null),{showLoading:y,hideLoading:x}=Pz(),m=U.useMemo(()=>Qte(),[]),_=U.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),b=U.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);U.useEffect(()=>{y(),Lte("/",m).then(ae=>{e(ae);const Ae=ae.projects.find(we=>m===null?we.id===null:we.id===m);if(!Ae)throw new Error(`Project "${m??"(main)"}" not found in config.json.`);r(Ae);const ue=kR(Ae,_);s(ue);const fe=ue?NR(ue,b):null;o(fe)}).catch(ae=>{console.error("Failed to load config:",ae),c(ae.message||"Failed to load config."),x()})},[m,_,b,y,x]);const w=U.useMemo(()=>{if(!t||!i)return null;const ae=t.id?t.id:"main",Ae=i.path?i.path:`scene/${lI(i.name)}/scene.xml`;return`${ae}/assets/${Ae}`.replace(/\/+/g,"/")},[t,i]),C=U.useMemo(()=>!i||!a?null:i.policies.find(ae=>ae.name===a)??null,[i,a]),S=U.useMemo(()=>!t||!C?.config?null:`${t.id?t.id:"main"}/assets/${C.config}`.replace(/\/+/g,"/"),[t,C]),M=U.useMemo(()=>{if(!t||!i?.splats?.length)return[];const ae=t.id?t.id:"main";return i.splats.map(Ae=>{if(Ae.path){const ue=`${ae}/assets/${Ae.path}`.replace(/\/+/g,"/");return{...Ae,url:ue}}return Ae})},[t,i?.splats]),T=U.useMemo(()=>d?M.find(ae=>ae.name===d)??null:p?{name:"Custom",url:p}:null,[M,d,p]),D=U.useMemo(()=>n?n.projects.map(ae=>({value:ae.id??"main",label:ae.name||(ae.id??"Main")})):[],[n]),k=U.useMemo(()=>t?t.scenes.map(ae=>({value:ae.name,label:ae.name})):[],[t]),G=U.useMemo(()=>!i||!i.policies?[]:i.policies.map(ae=>({value:ae.name,label:ae.name})),[i]),P=t?t.id??"main":null,H=i?.name??null,B=U.useCallback(ae=>{c(ae.message),x()},[x]),j=U.useCallback(()=>{x()},[x]);U.useEffect(()=>{const ae=i?.splats?.[0];h(ae?ae.name:null),A(null)},[i]);const J=U.useCallback(ae=>{g.current=ae},[]),X=U.useMemo(()=>i?.splats?.length?i.splats.map(ae=>({value:ae.name,label:ae.name})):[],[i?.splats]),$=U.useCallback(ae=>{if(ae===null)g.current?.setSplat(null);else{const Ae=M.find(ue=>ue.name===ae);Ae&&g.current?.setSplat(Ae)}h(ae),A(null)},[M]),Y=U.useCallback(async ae=>{try{if(!(await fetch(ae,{method:"HEAD"})).ok)return!1}catch{return!1}return g.current?.setSplat({name:"Custom",url:ae}),A(ae),!0},[]),ne=U.useCallback((ae,Ae,ue,fe,we,Te,ke)=>{const Oe=T??(p?{name:"Custom",url:p}:null);Oe&&g.current?.calibrateSplat({...Oe,scale:ae,xOffset:Ae,yOffset:ue,zOffset:fe,roll:we,pitch:Te,yaw:ke})},[T,p]),L=U.useCallback(ae=>{if(!n||!ae)return;const Ae=ae==="main"?null:ae,ue=n.projects.find(Te=>(Te.id??"main")===(Ae??"main"));if(!ue)return;y(),r(ue);const fe=kR(ue,null);s(fe);const we=fe?.policies?.[0]?.name??null;o(we),U_(ue.id,fe?.name??null,we)},[n,y]),V=U.useCallback(ae=>{if(!t||!ae)return;const Ae=t.scenes.find(fe=>fe.name===ae);if(!Ae)return;y(),s(Ae);const ue=NR(Ae,null);o(ue),U_(t.id,ae,ue)},[t,y]),se=U.useCallback(ae=>{ae!==a&&y(),o(ae),U_(t?.id??null,i?.name??null,ae)},[t,i,a,y]);return l?W.jsx(j_,{theme:Dw,defaultColorScheme:"auto",children:W.jsx("div",{className:"app",children:W.jsxs("div",{className:"hud hud-error",children:[W.jsx("h1",{className:"hud-title",children:"mjswan"}),W.jsx("p",{className:"hud-message",children:l})]})})}):!t||!i||!w?null:W.jsx(j_,{theme:Dw,defaultColorScheme:"auto",children:W.jsxs("div",{className:"app",children:[W.jsx(Nte,{}),W.jsx(Rte,{projects:D,projectValue:P,projectLabel:t?.name??"mjswan",onProjectChange:L,scenes:k,sceneValue:H,onSceneChange:V,splats:X,splatSection:i?.splatSection??!1,splatValue:d,onSplatChange:$,splatConfig:T,onCalibrateSplat:ne,onSplatUrlLoad:Y,policies:G,policyValue:a,onPolicyChange:se,commandsEnabled:!!S}),W.jsx(Ate,{scenePath:w,baseUrl:"/",policyConfigPath:S,splatConfig:T,onError:B,onReady:j,onRuntimeReady:J})]})})}function zte(){return W.jsx(kte,{children:W.jsx(Fte,{})})}const QR=document.getElementById("root");QR&&C4.createRoot(QR).render(W.jsx(On.StrictMode,{children:W.jsx(zte,{})}));
package/dist/index.html CHANGED
@@ -11,7 +11,7 @@
11
11
  />
12
12
  <link rel="manifest" href="manifest.json" />
13
13
  <title>mjswan</title>
14
- <script type="module" crossorigin src="/assets/index-Czn6IDu0.js"></script>
14
+ <script type="module" crossorigin src="/assets/index-4vhu8ouy.js"></script>
15
15
  <link rel="stylesheet" crossorigin href="/assets/index-B4SJqdSr.css">
16
16
  </head>
17
17
  <body>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mjswan",
3
3
  "type": "module",
4
- "version": "0.2.2",
4
+ "version": "0.2.4",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/ttktjmt/mjswan.git"