mjswan 0.5.5 → 0.5.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{index-BuyVQoco.js → index-BJWEa4j-.js} +1 -1
- package/dist/assets/{mujoco-Cp1xcNpc.js → mujoco-C2r0m8kN.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +14 -1
- package/src/core/cache/memoryMonitor.ts +170 -0
- package/src/core/cache/onnxCacheAdapter.ts +108 -0
- package/src/core/cache/resourceTracker.ts +289 -0
- package/src/core/cache/sceneCacheManager.ts +366 -0
- package/src/core/command/CommandManager.ts +375 -0
- package/src/core/command/TrackingCommand.ts +779 -0
- package/src/core/command/custom_commands.ts +6 -0
- package/src/core/command/index.ts +25 -0
- package/src/core/command/types.ts +109 -0
- package/src/core/engine/runtime.ts +1530 -0
- package/src/core/engine/viewer_config.ts +151 -0
- package/src/core/engine/viewer_config_defaults.ts +15 -0
- package/src/core/event/EventBase.ts +27 -0
- package/src/core/event/EventManager.ts +30 -0
- package/src/core/event/custom_events.ts +6 -0
- package/src/core/event/events.ts +162 -0
- package/src/core/observation/CommandObservation.ts +223 -0
- package/src/core/observation/ObservationBase.ts +25 -0
- package/src/core/observation/custom_observations.ts +4 -0
- package/src/core/observation/index.ts +2 -0
- package/src/core/observation/math.ts +96 -0
- package/src/core/observation/observations.ts +1248 -0
- package/src/core/policy/OnnxModule.ts +125 -0
- package/src/core/policy/PolicyModule.ts +28 -0
- package/src/core/policy/PolicyRunner.ts +319 -0
- package/src/core/policy/PolicyStateBuilder.ts +170 -0
- package/src/core/policy/modules/LocomotionPolicy.ts +97 -0
- package/src/core/policy/modules/TrackingPolicy.ts +97 -0
- package/src/core/policy/types.ts +82 -0
- package/src/core/scene/collider.ts +30 -0
- package/src/core/scene/coordinate.ts +9 -0
- package/src/core/scene/lights.ts +228 -0
- package/src/core/scene/npz.ts +291 -0
- package/src/core/scene/scene.ts +924 -0
- package/src/core/scene/splat.ts +64 -0
- package/src/core/scene/tendons.ts +125 -0
- package/src/core/scene/textures.ts +245 -0
- package/src/core/termination/TerminationBase.ts +19 -0
- package/src/core/termination/TerminationManager.ts +71 -0
- package/src/core/termination/custom_terminations.ts +6 -0
- package/src/core/termination/terminations.ts +96 -0
- package/src/core/types.ts +2 -0
- package/src/core/utils/dragStateManager.ts +265 -0
- package/src/core/utils/mjzLoader.ts +58 -0
- package/src/core/utils/mujocoAssetCollector.ts +329 -0
- package/src/core/utils/pathUtils.ts +17 -0
|
@@ -15606,4 +15606,4 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
15606
15606
|
}`},FR=n=>{let e=n[1].dims,t=n[2].dims,r=n[0].dims,i=n[1].dataType,s=!(Le.areEqual(e,t)&&Le.areEqual(t,r)),a=e,o=Le.size(e);if(s){let c=Zd.calcShape(Zd.calcShape(e,t,!1),r,!1);if(!c)throw new Error("Can't perform where op on the given tensors");a=c,o=Le.size(a)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>LR(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)]})}},T4=n=>{n.compute(FR(n.inputs))}}),R4,Jte=et(()=>{dte(),oI(),hte(),fte(),pte(),Ate(),mte(),_te(),wte(),Ete(),Cte(),Ite(),Ste(),Bte(),Mte(),Tte(),Rte(),Dte(),kte(),Nte(),Qte(),Pte(),Lte(),Fte(),zte(),XF(),Ute(),Ote(),$te(),Gte(),Vte(),aI(),Hte(),t4(),jte(),Wte(),qte(),ZF(),Yte(),jl(),lI(),Xte(),R4=new Map([["Abs",[EL]],["Acos",[CL]],["Acosh",[IL]],["Add",[aF]],["ArgMax",[vL,Rw]],["ArgMin",[xL,Rw]],["Asin",[SL]],["Asinh",[BL]],["Atan",[ML]],["Atanh",[TL]],["Attention",[_L]],["AveragePool",[u4,c4]],["BatchNormalization",[bL]],["BiasAdd",[wL]],["BiasSplitGelu",[sF]],["Cast",[DL,RL]],["Ceil",[NL]],["Clip",[kL]],["Concat",[mF,gF]],["Conv",[Lw,Pw]],["ConvTranspose",[SF,IF]],["Cos",[QL]],["Cosh",[PL]],["CumSum",[BF,MF]],["DepthToSpace",[TF,RF]],["DequantizeLinear",[g4,y4]],["Div",[oF]],["Einsum",[DF,kF]],["Elu",[LL,op]],["Equal",[lF]],["Erf",[FL]],["Exp",[zL]],["Expand",[NF]],["FastGelu",[QF]],["Floor",[UL]],["FusedConv",[Lw,Pw]],["Gather",[LF,PF]],["GatherElements",[GF,$F]],["GatherBlockQuantized",[UF,OF]],["GatherND",[FF,zF]],["Gelu",[OL]],["Gemm",[HF,VF]],["GlobalAveragePool",[h4,d4]],["GlobalMaxPool",[m4,A4]],["Greater",[hF]],["GreaterOrEqual",[pF]],["GridSample",[jF,WF]],["GroupQueryAttention",[n4]],["HardSigmoid",[YL,qL]],["InstanceNormalization",[r4]],["LayerNormalization",[i4]],["LeakyRelu",[$L,op]],["Less",[fF]],["LessOrEqual",[AF]],["Log",[rF]],["MatMul",[s4]],["MatMulNBits",[a4,o4]],["MaxPool",[f4,p4]],["Mul",[cF]],["MultiHeadAttention",[YF,qF]],["Neg",[VL]],["Not",[GL]],["Pad",[l4]],["Pow",[uF]],["QuickGelu",[iF,op]],["Range",[x4]],["Reciprocal",[HL]],["ReduceMin",[pL]],["ReduceMean",[cL]],["ReduceMax",[fL]],["ReduceSum",[mL]],["ReduceProd",[AL]],["ReduceL1",[uL]],["ReduceL2",[dL]],["ReduceLogSum",[yL]],["ReduceLogSumExp",[hL]],["ReduceSumSquare",[gL]],["Relu",[jL]],["Resize",[b4,w4]],["RotaryEmbedding",[e4]],["ScatterND",[_4,v4]],["Sigmoid",[WL]],["Sin",[XL]],["Sinh",[JL]],["Slice",[C4,I4]],["SkipLayerNormalization",[E4]],["Split",[JF,KF]],["Sqrt",[KL]],["Softmax",[S4,B4]],["Sub",[dF]],["Tan",[ZL]],["Tanh",[eF]],["ThresholdedRelu",[nF,op]],["Tile",[M4]],["Transpose",[JP,KP]],["Where",[T4]]])}),D4,Kte=et(()=>{xs(),No(),Wt(),D4=class{constructor(n){this.backend=n,this.repo=new Map,this.attributesBound=!1}getArtifact(n){return this.repo.get(n)}setArtifact(n,e){this.repo.set(n,e)}run(n,e,t,r,i){Fa(n.programInfo.name);let s=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let o=[];for(let c of e)o.push({binding:o.length,resource:{buffer:c.buffer}});for(let c of t)o.push({binding:o.length,resource:{buffer:c.buffer}});i&&o.push({binding:o.length,resource:i});let l=s.createBindGroup({layout:n.computePipeline.getBindGroupLayout(0),entries:o,label:n.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:n.computePipeline,bindGroup:l,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}a.setPipeline(n.computePipeline),a.setBindGroup(0,l),a.dispatchWorkgroups(...r),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Zs(n.programInfo.name)}dispose(){}build(n,e){Fa(n.name);let t=this.backend.device,r=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&r.push(`enable ${c.extension};`)});let i=XP(e,this.backend.device.limits),s=n.getShaderSource(i),a=`${r.join(`
|
|
15607
15607
|
`)}
|
|
15608
15608
|
${i.additionalImplementations}
|
|
15609
|
-
${s}`,o=t.createShaderModule({code:a,label:n.name});un("verbose",()=>`[WebGPU] ${n.name} shader code: ${a}`);let l=t.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:n.name});return Zs(n.name),{programInfo:n,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(n){let e=typeof n=="number"?n:n.x,t=typeof n=="number"?1:n.y||1,r=typeof n=="number"?1:n.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&t<=i&&r<=i)return[e,t,r];let s=e*t*r,a=Math.ceil(Math.sqrt(s));if(a>i){if(a=Math.ceil(Math.cbrt(s)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),k4={};vh(k4,{WebGpuBackend:()=>N4});var zR,UR,OR,N4,Zte=et(()=>{xs(),Lt(),No(),HP(),cte(),Jte(),Kte(),zR=(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("|")},UR=(n,e,t)=>{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${zR(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},OR=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},N4=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 OR(e.info||await e.requestAdapterInfo()),this.gpuDataManager=qP(this),this.programManager=new D4(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,nI(n.logLevel,!!n.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let n=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Fa(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(n.getMappedRange()),t=this.pendingQueries.get(n);for(let r=0;r<e.length/2;r++){let i=t[r],s=i.kernelId,a=this.kernels.get(s),o=a.kernelType,l=a.kernelName,c=i.programName,d=i.inputTensorViews,h=i.outputTensorViews,p=e[r*2],A=e[r*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=p);let y=Number(p-this.queryTimeBase),m=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(y)||!Number.isSafeInteger(m))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(x=>({dims:x.dims,dataType:po(x.dataType)})),outputsMetadata:h.map(x=>({dims:x.dims,dataType:po(x.dataType)})),kernelId:s,kernelType:o,kernelName:l,programName:c,startTime:y,endTime:m});else{let x="";d.forEach((_,b)=>{x+=`input[${b}]: [${_.dims}] | ${po(_.dataType)}, `});let g="";h.forEach((_,b)=>{g+=`output[${b}]: [${_.dims}] | ${po(_.dataType)}, `})}qg("GPU",`${c}::${p}::${A}`)}n.unmap(),this.pendingQueries.delete(n)}),Zs()}run(n,e,t,r,i,s){Fa(n.name);let a=[];for(let _=0;_<e.length;++_){let b=e[_].data;if(b===0)continue;let w=this.gpuDataManager.get(b);if(!w)throw new Error(`no GPU data for input: ${b}`);a.push(w)}let{outputs:o,dispatchGroup:l,programUniforms:c}=n.getRunData(e),d=t.length===0?o.map((_,b)=>b):t;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let h=[],p=[];for(let _=0;_<o.length;++_){if(!Number.isInteger(d[_])||d[_]<-3||d[_]>=s)throw new Error(`Invalid output index: ${d[_]}`);if(d[_]===-3)continue;let b=d[_]===-1,w=d[_]===-2,C=b||w?i(o[_].dataType,o[_].dims):r(d[_],o[_].dataType,o[_].dims);if(h.push(C),C.data===0)continue;let S=this.gpuDataManager.get(C.data);if(!S)throw new Error(`no GPU data for output: ${C.data}`);if(b&&this.temporaryData.push(S),w){let M=this.kernelPersistentData.get(this.currentKernelId);M||(M=[],this.kernelPersistentData.set(this.currentKernelId,M)),M.push(S)}p.push(S)}if(a.length!==e.length||p.length!==h.length){if(p.length===0)return Zs(n.name),h;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let A;if(c){let _=0,b=[];c.forEach(M=>{let T=typeof M.data=="number"?[M.data]:M.data;if(T.length===0)return;let R=M.type===10?2:4,k,$;M.type===10?($=T.length>4?16:T.length>2?8:T.length*R,k=T.length>4?16:R*T.length):($=T.length<=2?T.length*R:16,k=16),_=Math.ceil(_/$)*$,b.push(_);let Q=M.type===10?8:4;_+=T.length>4?Math.ceil(T.length/Q)*k:T.length*R});let w=16;_=Math.ceil(_/w)*w;let C=new ArrayBuffer(_);c.forEach((M,T)=>{let R=b[T],k=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(C,R,k.length).set(k);else if(M.type===12)new Uint32Array(C,R,k.length).set(k);else if(M.type===10)new Uint16Array(C,R,k.length).set(k);else if(M.type===1)new Float32Array(C,R,k.length).set(k);else throw new Error(`Unsupported uniform type: ${po(M.type)}`)});let S=this.gpuDataManager.create(_,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(S.buffer,0,C,0,_),this.gpuDataManager.release(S.id),A={offset:0,size:_,buffer:S.buffer}}let y=this.programManager.normalizeDispatchGroupSize(l),m=y[1]===1&&y[2]===1,x=UR(n,e,m),g=this.programManager.getArtifact(x);if(g||(g=this.programManager.build(n,y),this.programManager.setArtifact(x,g),un("info",()=>`[artifact] key: ${x}, programName: ${n.name}`)),c&&g.uniformVariablesInfo){if(c.length!==g.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${g.uniformVariablesInfo.length}, got ${c.length} in program "${g.programInfo.name}".`);for(let _=0;_<c.length;_++){let b=c[_],w=b.type,C=typeof b.data=="number"?1:b.data.length,[S,M]=g.uniformVariablesInfo[_];if(w!==S||C!==M)throw new Error(`Uniform variable ${_} mismatch: expect type ${S} with size ${M}, got type ${w} with size ${C} in program "${g.programInfo.name}".`)}}if(un("info",()=>`[ProgramManager] run "${n.name}" (key=${x}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let _={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(_),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(_)}return this.programManager.run(g,a,p,y,A),Zs(n.name),h}upload(n,e){this.gpuDataManager.upload(n,e)}memcpy(n,e){this.gpuDataManager.memcpy(n,e)}async download(n,e){await this.gpuDataManager.download(n,e)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,e,t,r){let i=R4.get(n);if(!i)throw new Error(`kernel not implemented: ${n}`);let s={kernelType:n,kernelName:r,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(e,s)}releaseKernel(n){let e=this.kernelPersistentData.get(n);if(e){for(let t of e)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,e,t){let r=this.kernels.get(n);if(!r)throw new Error(`kernel not created: ${n}`);let i=r.kernelType,s=r.kernelName,a=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${s}" is not allowed to be called recursively`);this.currentKernelId=n,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),un("info",()=>`[WebGPU] Start to run kernel "[${i}] ${s}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(e,o[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${s}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${s}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,e,t,r){let i=this.sessionExternalDataMapping.get(n);i||(i=new Map,this.sessionExternalDataMapping.set(n,i));let s=i.get(e),a=this.gpuDataManager.registerExternalBuffer(t,r,s);return i.set(e,[a,t]),a}unregisterBuffers(n){let e=this.sessionExternalDataMapping.get(n);e&&(e.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let e=this.gpuDataManager.get(n);if(!e)throw new Error(`no GPU data for buffer: ${n}`);return e.buffer}createDownloader(n,e,t){return async()=>{let r=await Bw(this,n,e);return rI(r.buffer,t)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){un("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){un("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){un("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),t=n.length;this.pendingKernels=[];for(let r=0;r<t;r++){let i=this.getComputePassEncoder(),s=n[r];this.writeTimestamp(this.pendingDispatchNumber*2),i.setPipeline(s.computePipeline),i.setBindGroup(0,s.bindGroup),i.dispatchWorkgroups(...s.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(e[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),Q4={};vh(Q4,{init:()=>P4});var ng,$R,P4,ene=et(()=>{Lt(),No(),jt(),lte(),ng=class L4{constructor(e,t,r,i){this.module=e,this.dataType=t,this.data=r,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Le.size(e)!==Le.size(this.dims))throw new Error("Invalid new shape");return new L4(this.module,this.dataType,this.data,e)}},$R=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 ng(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 ng(this.module,o,this.output(a,l),l),s=(a,o)=>{let l=Pc(a,o);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new ng(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)}}},P4=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=(Zte(),Pp(k4)).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 $R(e,a,Number(l));return a.computeKernel(Number(o),h,d)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let s=new WP(t);i("webnn",[s,()=>s.reserveTensorId(),a=>s.releaseTensorId(a),async(a,o,l,c,d)=>s.ensureTensor(a,o,l,c,d),(a,o)=>{s.uploadTensor(a,o)},async(a,o)=>s.downloadTensor(a,o),(a,o)=>s.registerMLContext(a,o),!!t.trace])}}}),GR,pI,AI,Il,VR,G_,t0,mI,gI,V_,yI,xI,vI,F4=et(()=>{xs(),ite(),ste(),Lt(),cu(),KC(),OP(),GR=(n,e)=>{kn()._OrtInit(n,e)!==0&&wn("Can't initialize onnxruntime.")},pI=async n=>{GR(n.wasm.numThreads,Xg(n.logLevel))},AI=async(n,e)=>{kn().asyncInit?.();let t=n.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(t){if(typeof t.limits!="object"||typeof t.features!="object"||typeof t.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=n.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let i=n.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:i}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let r=(ene(),Pp(Q4)).init;e==="webgpu"&&await r("webgpu",kn(),n,t),e==="webnn"&&await r("webnn",kn(),n)}},Il=new Map,VR=n=>{let e=kn(),t=e.stackSave();try{let r=e.PTR_SIZE,i=e.stackAlloc(2*r);e._OrtGetInputOutputCount(n,i,i+r)!==0&&wn("Can't get session input/output count.");let s=r===4?"i32":"i64";return[Number(e.getValue(i,s)),Number(e.getValue(i+r,s))]}finally{e.stackRestore(t)}},G_=(n,e)=>{let t=kn(),r=t.stackSave(),i=0;try{let s=t.PTR_SIZE,a=t.stackAlloc(2*s);t._OrtGetInputOutputMetadata(n,e,a,a+s)!==0&&wn("Can't get session input/output metadata.");let o=Number(t.getValue(a,"*"));i=Number(t.getValue(a+s,"*"));let l=t.HEAP32[i/4];if(l===0)return[o,0];let c=t.HEAPU32[i/4+1],d=[];for(let h=0;h<c;h++){let p=Number(t.getValue(i+8+h*s,"*"));d.push(p!==0?t.UTF8ToString(p):Number(t.getValue(i+8+(h+c)*s,"*")))}return[o,l,d]}finally{t.stackRestore(r),i!==0&&t._OrtFree(i)}},t0=n=>{let e=kn(),t=e._malloc(n.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,t),[t,n.byteLength]},mI=async(n,e)=>{let t,r,i=kn();Array.isArray(n)?[t,r]=n:n.buffer===i.HEAPU8.buffer?[t,r]=[n.byteOffset,n.byteLength]:[t,r]=t0(n);let s=0,a=0,o=0,l=[],c=[],d=[];try{if([a,l]=await UP(e),e?.externalData&&i.mountExternalData){let w=[];for(let C of e.externalData){let S=typeof C=="string"?C:C.path;w.push(tI(typeof C=="string"?C:C.data).then(M=>{i.mountExternalData(S,M)}))}await Promise.all(w)}for(let w of e?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof w!="string"){let C=w,S=C?.context,M=C?.gpuDevice,T=C?.deviceType,R=C?.powerPreference;S?i.currentContext=S:M?i.currentContext=await i.webnnCreateMLContext(M):i.currentContext=await i.webnnCreateMLContext({deviceType:T,powerPreference:R})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(t,r,a),i.webgpuOnCreateSession?.(s),s===0&&wn("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=VR(s),A=!!e?.enableGraphCapture,y=[],m=[],x=[],g=[],_=[];for(let w=0;w<h;w++){let[C,S,M]=G_(s,w);C===0&&wn("Can't get an input name."),c.push(C);let T=i.UTF8ToString(C);y.push(T),x.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M})}for(let w=0;w<p;w++){let[C,S,M]=G_(s,w+h);C===0&&wn("Can't get an output name."),d.push(C);let T=i.UTF8ToString(C);m.push(T),g.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M});{if(A&&e?.preferredOutputLocation===void 0){_.push("gpu-buffer");continue}let R=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[T]??"cpu",k=i.webnnIsGraphOutput;if(R==="cpu"&&k&&k(s,T)){_.push("ml-tensor-cpu-output");continue}if(R!=="cpu"&&R!=="cpu-pinned"&&R!=="gpu-buffer"&&R!=="ml-tensor")throw new Error(`Not supported preferred output location: ${R}.`);if(A&&R!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${R}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(R)}}let b=null;return _.some(w=>w==="gpu-buffer"||w==="ml-tensor"||w==="ml-tensor-cpu-output")&&(o=i._OrtCreateBinding(s),o===0&&wn("Can't create IO binding."),b={handle:o,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(w=>w==="ml-tensor-cpu-output"?"ml-tensor":w).map(w=>Iw(w))}),Il.set(s,[s,c,d,b,A,!1]),[s,y,m,x,g]}catch(h){throw c.forEach(p=>i._OrtFree(p)),d.forEach(p=>i._OrtFree(p)),o!==0&&i._OrtReleaseBinding(o)!==0&&wn("Can't release IO binding."),s!==0&&i._OrtReleaseSession(s)!==0&&wn("Can't release session."),h}finally{i._free(t),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&wn("Can't release session options."),l.forEach(h=>i._free(h)),i.unmountExternalData?.()}},gI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error(`cannot release session. invalid session id: ${n}`);let[r,i,s,a,o]=t;a&&(o&&e._OrtClearBoundOutputs(a.handle)!==0&&wn("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&wn("Can't release IO binding.")),e.jsepOnReleaseSession?.(n),e.webnnOnReleaseSession?.(n),e.webgpuOnReleaseSession?.(n),i.forEach(l=>e._OrtFree(l)),s.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(r)!==0&&wn("Can't release session."),Il.delete(n)},V_=async(n,e,t,r,i,s,a=!1)=>{if(!n){e.push(0);return}let o=kn(),l=o.PTR_SIZE,c=n[0],d=n[1],h=n[3],p=h,A,y;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let g=n[2].gpuBuffer;y=Pc(Qc(c),d);{let _=o.jsepRegisterBuffer;if(!_)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=_(r,s,g,y)}}else if(h==="ml-tensor"){let g=n[2].mlTensor;y=Pc(Qc(c),d);let _=o.webnnRegisterMLTensor;if(!_)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=_(r,g,Qc(c),d)}else{let g=n[2];if(Array.isArray(g)){y=l*g.length,A=o._malloc(y),t.push(A);for(let _=0;_<g.length;_++){if(typeof g[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);o.setValue(A+_*l,Gs(g[_],t),"*")}}else{let _=o.webnnIsGraphInput,b=o.webnnIsGraphOutput;if(c!=="string"&&_&&b){let w=o.UTF8ToString(i);if(_(r,w)||b(r,w)){let C=Qc(c);y=Pc(C,d),p="ml-tensor";let S=o.webnnCreateTemporaryTensor,M=o.webnnUploadTensor;if(!S||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let T=await S(r,C,d);M(T,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),A=T}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}}let m=o.stackSave(),x=o.stackAlloc(4*d.length);try{d.forEach((_,b)=>o.setValue(x+b*l,_,l===4?"i32":"i64"));let g=o._OrtCreateTensor(Qc(c),A,y,x,d.length,Iw(p));g===0&&wn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(g)}finally{o.stackRestore(m)}},yI=async(n,e,t,r,i,s)=>{let a=kn(),o=a.PTR_SIZE,l=Il.get(n);if(!l)throw new Error(`cannot run inference. invalid session id: ${n}`);let c=l[0],d=l[1],h=l[2],p=l[3],A=l[4],y=l[5],m=e.length,x=r.length,g=0,_=[],b=[],w=[],C=[],S=[],M=a.stackSave(),T=a.stackAlloc(m*o),R=a.stackAlloc(m*o),k=a.stackAlloc(x*o),$=a.stackAlloc(x*o);try{[g,_]=zP(s),Wc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)await V_(t[W],b,C,n,d[e[W]],e[W],A);for(let W=0;W<x;W++)await V_(i[W],w,C,n,h[r[W]],m+r[W],A);qc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)a.setValue(T+W*o,b[W],"*"),a.setValue(R+W*o,d[e[W]],"*");for(let W=0;W<x;W++)a.setValue(k+W*o,w[W],"*"),a.setValue($+W*o,h[r[W]],"*");if(p&&!y){let{handle:W,outputPreferredLocations:K,outputPreferredLocationsEncoded:Y}=p;if(d.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${d.length}).`);Wc("wasm bindInputsOutputs");for(let G=0;G<m;G++){let X=e[G];await a._OrtBindInput(W,d[X],b[G])!==0&&wn(`Can't bind input[${G}] for session=${n}.`)}for(let G=0;G<x;G++){let X=r[G];i[G]?.[3]?(S.push(w[G]),a._OrtBindOutput(W,h[X],w[G],0)!==0&&wn(`Can't bind pre-allocated output[${G}] for session=${n}.`)):a._OrtBindOutput(W,h[X],0,Y[X])!==0&&wn(`Can't bind output[${G}] to ${K[G]} for session=${n}.`)}qc("wasm bindInputsOutputs"),Il.set(n,[c,d,h,p,A,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let Q;p?Q=await a._OrtRunWithBinding(c,p.handle,x,k,g):Q=await a._OrtRun(c,R,T,m,$,x,k,g),Q!==0&&wn("failed to call OrtRun().");let H=[],B=[];Wc("wasm ProcessOutputTensor");for(let W=0;W<x;W++){let K=Number(a.getValue(k+W*o,"*"));if(K===w[W]||S.includes(w[W])){H.push(i[W]),K!==w[W]&&a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.");continue}let Y=a.stackSave(),G=a.stackAlloc(4*o),X=!1,re,L=0;try{a._OrtGetTensorData(K,G,G+o,G+2*o,G+3*o)!==0&&wn(`Can't access output tensor data on index ${W}.`);let V=o===4?"i32":"i64",oe=Number(a.getValue(G,V));L=a.getValue(G+o,"*");let Ae=a.getValue(G+o*2,"*"),ye=Number(a.getValue(G+o*3,V)),he=[];for(let Re=0;Re<ye;Re++)he.push(Number(a.getValue(Ae+Re*o,V)));a._OrtFree(Ae)!==0&&wn("Can't free memory for tensor dims.");let fe=he.reduce((Re,ve)=>Re*ve,1);re=po(oe);let Ee=p?.outputPreferredLocations[r[W]];if(re==="string"){if(Ee==="gpu-buffer"||Ee==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Re=[];for(let ve=0;ve<fe;ve++){let Ne=a.getValue(L+ve*o,"*"),rt=a.getValue(L+(ve+1)*o,"*"),Ge=ve===fe-1?void 0:rt-Ne;Re.push(a.UTF8ToString(Ne,Ge))}H.push([re,he,Re,"cpu"])}else if(Ee==="gpu-buffer"&&fe>0){let Re=a.jsepGetBuffer;if(!Re)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ve=Re(L),Ne=Pc(oe,fe);if(Ne===void 0||!ZC(re))throw new Error(`Unsupported data type: ${re}`);X=!0,H.push([re,he,{gpuBuffer:ve,download:a.jsepCreateDownloader(ve,Ne,re),dispose:()=>{a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.")}},"gpu-buffer"])}else if(Ee==="ml-tensor"&&fe>0){let Re=a.webnnEnsureTensor,ve=a.webnnIsGraphInputOutputTypeSupported;if(!Re||!ve)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Pc(oe,fe)===void 0||!eI(re))throw new Error(`Unsupported data type: ${re}`);if(!ve(n,re,!1))throw new Error(`preferredLocation "ml-tensor" for ${re} output is not supported by current WebNN Context.`);let Ne=await Re(n,L,oe,he,!1);X=!0,H.push([re,he,{mlTensor:Ne,download:a.webnnCreateMLTensorDownloader(L,re),dispose:()=>{a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K)}},"ml-tensor"])}else if(Ee==="ml-tensor-cpu-output"&&fe>0){let Re=a.webnnCreateMLTensorDownloader(L,re)(),ve=H.length;X=!0,B.push((async()=>{let Ne=[ve,await Re];return a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K),Ne})()),H.push([re,he,[],"cpu"])}else{let Re=Z0(re),ve=new Re(fe);new Uint8Array(ve.buffer,ve.byteOffset,ve.byteLength).set(a.HEAPU8.subarray(L,L+ve.byteLength)),H.push([re,he,ve,"cpu"])}}finally{a.stackRestore(Y),re==="string"&&L&&a._free(L),X||a._OrtReleaseTensor(K)}}p&&!A&&(a._OrtClearBoundOutputs(p.handle)!==0&&wn("Can't clear bound outputs."),Il.set(n,[c,d,h,p,A,!1]));for(let[W,K]of await Promise.all(B))H[W][2]=K;return qc("wasm ProcessOutputTensor"),H}finally{a.webnnOnRunEnd?.(c),a.stackRestore(M),b.forEach(Q=>a._OrtReleaseTensor(Q)),w.forEach(Q=>a._OrtReleaseTensor(Q)),C.forEach(Q=>a._free(Q)),g!==0&&a._OrtReleaseRunOptions(g),_.forEach(Q=>a._free(Q))}},xI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error("invalid session id");let r=t[0],i=e._OrtEndProfiling(r);i===0&&wn("Can't get an profile file name."),e._OrtFree(i)},vI=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),Sl,ts,Ed,qf,Yf,rg,H_,ig,Ic,Sc,HR,z4,U4,O4,$4,G4,V4,H4,j4=et(()=>{xs(),F4(),cu(),XC(),Sl=()=>!!Dn.wasm.proxy&&typeof document<"u",Ed=!1,qf=!1,Yf=!1,ig=new Map,Ic=(n,e)=>{let t=ig.get(n);t?t.push(e):ig.set(n,[e])},Sc=()=>{if(Ed||!qf||Yf||!ts)throw new Error("worker not ready")},HR=n=>{switch(n.data.type){case"init-wasm":Ed=!1,n.data.err?(Yf=!0,H_[1](n.data.err)):(qf=!0,H_[0]()),rg&&(URL.revokeObjectURL(rg),rg=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=ig.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},z4=async()=>{if(!qf){if(Ed)throw new Error("multiple calls to 'initWasm()' detected.");if(Yf)throw new Error("previous call to 'initWasm()' failed.");if(Ed=!0,Sl())return new Promise((n,e)=>{ts?.terminate(),LP().then(([t,r])=>{try{ts=r,ts.onerror=s=>e(s),ts.onmessage=HR,H_=[n,e];let i={type:"init-wasm",in:Dn};!i.in.wasm.wasmPaths&&(t||Cw)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href}),ts.postMessage(i),rg=t}catch(i){e(i)}},e)});try{await JC(Dn.wasm),await pI(Dn),qf=!0}catch(n){throw Yf=!0,n}finally{Ed=!1}}},U4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Dn}};ts.postMessage(r)});await AI(Dn,n)},O4=async n=>Sl()?(Sc(),new Promise((e,t)=>{Ic("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};ts.postMessage(r,[n.buffer])})):t0(n),$4=async(n,e)=>{if(Sl()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Sc(),new Promise((t,r)=>{Ic("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},s=[];n instanceof Uint8Array&&s.push(n.buffer),ts.postMessage(i,s)})}else return mI(n,e)},G4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("release",[e,t]);let r={type:"release",in:n};ts.postMessage(r)});gI(n)},V4=async(n,e,t,r,i,s)=>{if(Sl()){if(t.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Sc(),new Promise((a,o)=>{Ic("run",[a,o]);let l=t,c={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:s}};ts.postMessage(c,vI(l))})}else return yI(n,e,t,r,i,s)},H4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("end-profiling",[e,t]);let r={type:"end-profiling",in:n};ts.postMessage(r)});xI(n)}}),j_,jR,W4,tne=et(()=>{xs(),j4(),Lt(),YC(),OP(),j_=(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()}`)}},jR=n=>{switch(n[3]){case"cpu":return new ti(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!ZC(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:r,dispose:i}=n[2];return ti.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}case"ml-tensor":{let e=n[0];if(!eI(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:r,dispose:i}=n[2];return ti.fromMLTensor(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},W4=class{async fetchModelAndCopyToWasmMemory(n){return O4(await tI(n))}async loadModel(n,e){Fa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await $4(t,e),Zs()}async dispose(){return G4(this.sessionId)}async run(n,e,t){Fa();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],A=h[1],y=this.inputNames.indexOf(p);if(y===-1)throw new Error(`invalid input '${p}'`);r.push(A),i.push(y)});let s=[],a=[];Object.entries(e).forEach(h=>{let p=h[0],A=h[1],y=this.outputNames.indexOf(p);if(y===-1)throw new Error(`invalid output '${p}'`);s.push(A),a.push(y)});let o=r.map((h,p)=>j_(h,()=>`input "${this.inputNames[i[p]]}"`)),l=s.map((h,p)=>h?j_(h,()=>`output "${this.outputNames[a[p]]}"`):null),c=await V4(this.sessionId,i,o,a,l,t),d={};for(let h=0;h<c.length;h++)d[this.outputNames[a[h]]]=s[h]??jR(c[h]);return Zs(),d}startProfiling(){}endProfiling(){H4(this.sessionId)}}}),q4={};vh(q4,{OnnxruntimeWebAssemblyBackend:()=>Uw,initializeFlags:()=>zw,wasmBackend:()=>Y4});var zw,Uw,Y4,nne=et(()=>{xs(),j4(),tne(),zw=()=>{(typeof Dn.wasm.initTimeout!="number"||Dn.wasm.initTimeout<0)&&(Dn.wasm.initTimeout=0);let n=Dn.wasm.simd;if(typeof n!="boolean"&&n!==void 0&&n!=="fixed"&&n!=="relaxed"&&(Dn.wasm.simd=!1),typeof Dn.wasm.proxy!="boolean"&&(Dn.wasm.proxy=!1),typeof Dn.wasm.trace!="boolean"&&(Dn.wasm.trace=!1),typeof Dn.wasm.numThreads!="number"||!Number.isInteger(Dn.wasm.numThreads)||Dn.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Dn.wasm.numThreads=1;else{let e=typeof navigator>"u"?Uee("node:os").cpus().length:navigator.hardwareConcurrency;Dn.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Uw=class{async init(n){zw(),await z4(),await U4(n)}async createInferenceSessionHandler(n,e){let t=new W4;return await t.loadModel(n,e),t}},Y4=new Uw});xs();xs();xs();var rne="1.24.3";{let n=(nne(),Pp(q4)).wasmBackend;Bd("webgpu",n,5),Bd("webnn",n,5),Bd("cpu",n,10),Bd("wasm",n,10)}Object.defineProperty(Dn.versions,"web",{value:rne,enumerable:!0});class ine{constructor(e,t={}){this.config=e,this.options=t,this.policyModule=null,this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null,this.context=null,this.policyJointNames=(e.policy_joint_names??[]).slice(),this.numActions=this.policyJointNames.length,this.lastActions=new Float32Array(this.numActions),this.defaultJointPos=this.normalizeArray(e.default_joint_pos??[],this.numActions,0),this.encoderBias=this.normalizeArray(e.encoder_bias??[],this.numActions,0)}async init(e){this.context=e,this.policyModule=await this.buildPolicyModule(e),this.buildObservationGroups()}reset(e){this.lastActions.fill(0),this.policyModule?.reset();for(const t of Object.values(this.obsGroups))for(const r of t)r.reset&&r.reset(e);if(e){for(const[t,r]of Object.entries(this.historyConfig))if(r.steps>1){const i=this.buildFrame(this.obsGroups[t]??[],e),s=this.historyBuffers[t];for(let a=0;a<r.steps;a++)s.set(i,a*i.length)}}}update(e){this.policyModule?.update();for(const t of Object.values(this.obsGroups))for(const r of t)r.update&&r.update(e)}collectObservationsByKey(e){this.update(e);const t={};for(const[r,i]of Object.entries(this.obsGroups)){const s=this.historyConfig[r];if(s&&s.steps>1){const a=this.buildFrame(i,e),o=this.historyBuffers[r];for(let l=o.length-1;l>=a.length;l--)o[l]=o[l-a.length];o.set(a,0),t[r]=new Float32Array(o)}else t[r]=this.buildFrame(i,e)}return t}collectObservations(e){const t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];const r=Object.keys(t)[0];return r?t[r]:new Float32Array(0)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];const e=Object.keys(this.obsSizes)[0];return e?this.obsSizes[e]:0}getObservationLayout(){if(this.defaultObsKey&&this.obsLayouts[this.defaultObsKey])return this.obsLayouts[this.defaultObsKey].map(t=>({...t}));const e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(t=>({...t})):[]}getPolicyModuleContext(){return this.policyModule?.getContext()??{}}getPolicyModule(){return this.policyModule}getContext(){return this.context}getPolicyJointNames(){return this.policyJointNames.slice()}getNumActions(){return this.numActions}getDefaultJointPos(){return new Float32Array(this.defaultJointPos)}getEncoderBias(){return new Float32Array(this.encoderBias)}getLastActions(){return new Float32Array(this.lastActions)}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){const t=this.options.policyModules??{},r=this.config.policy_module,i=r?t[r]:t.default;if(r&&!i)throw new Error(`Unknown policy module: ${r}`);if(!i)return null;const s=new i(this.config);return await s.init(e),s}buildObservationGroups(){const e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;for(const[r,i]of Object.entries(t)){if(Array.isArray(i)){const s=i.map(a=>{const o=e[a.name];if(!o)throw new Error(`Unknown observation type: ${a.name}`);return new o(this,a)});this.registerGroup(r,s,i);continue}if(i&&typeof i=="object"){const s=i;if(Array.isArray(s.components)){const a=s.components.map(c=>{const d=e[c.name];if(!d)throw new Error(`Unknown observation type: ${c.name}`);const h={...c,history_steps:1};return new d(this,h)}),o=Math.max(1,Math.floor(s.history_steps??1)),l=!!s.interleaved;this.registerGroup(r,a,s.components,{steps:o,interleaved:l})}}}this.obsGroups.policy?this.defaultObsKey="policy":this.obsGroups.observation?this.defaultObsKey="observation":this.obsGroups.obs_history?this.defaultObsKey="obs_history":this.defaultObsKey=Object.keys(this.obsGroups)[0]??null}registerGroup(e,t,r,i){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((a,o)=>({name:r[o]?.name??`obs_${o}`,size:a.size}));const s=this.obsLayouts[e].reduce((a,o)=>a+o.size,0);i&&i.steps>1?(this.historyConfig[e]=i,this.historyBuffers[e]=new Float32Array(s*i.steps),this.obsSizes[e]=s*i.steps):this.obsSizes[e]=s}buildFrame(e,t){const r=e.reduce((a,o)=>a+o.size,0),i=new Float32Array(r);let s=0;for(const a of e){const o=a.compute(t),l=o instanceof Float32Array?o:Float32Array.from(o);if(l.length!==a.size)throw new Error(`Observation size mismatch: expected ${a.size}, got ${l.length}`);i.set(l,s),s+=l.length}return i}normalizeArray(e,t,r){const i=new Float32Array(t);for(let s=0;s<t;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}}Dn.wasm.proxy=!1;Dn.wasm.numThreads=1;class sne{constructor(e){if(!e?.path)throw new Error("OnnxModule requires a path.");this.config=e,this.session=null;const t=e.meta?.in_keys??["policy"],r=e.meta?.out_keys??["action"];this.configuredInKeys=t.map(i=>Array.isArray(i)?i.join(","):i),this.inKeys=[...this.configuredInKeys],this.outKeys=r.map(i=>Array.isArray(i)?i.join(","):i),this.isRecurrent=this.inKeys.includes("adapt_hx")}async init(){const e=await fetch(this.config.path);if(!e.ok)throw new Error(`Failed to fetch ONNX model: ${e.status}`);const t=await e.arrayBuffer();this.session=await qC.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"}),this.inferInputKeys(),this.isRecurrent=this.inKeys.includes("adapt_hx")}initInput(){const e={};return this.isRecurrent&&(e.is_init=new ti("bool",[!0],[1]),e.adapt_hx=new ti("float32",new Float32Array(128),[1,128])),this.inKeys.includes("time_step")&&(e.time_step=new ti("float32",new Float32Array([0]),[1,1])),e}async runInference(e){if(!this.session)throw new Error("OnnxModule not initialized.");const t={};for(let a=0;a<this.inKeys.length;a++){const o=this.inKeys[a],l=this.session.inputNames[a];if(!l||!e[o])throw new Error(`Missing ONNX input for key: ${o}`);t[l]=e[o]}const r=await this.session.run(t),i={};for(let a=0;a<this.outKeys.length;a++){const o=this.outKeys[a],l=this.session.outputNames[a];l&&r[l]&&(i[o]=r[l])}const s={};return this.isRecurrent&&i["next,adapt_hx"]&&(s.is_init=new ti("bool",[!1],[1]),s.adapt_hx=i["next,adapt_hx"]),[i,s]}inferInputKeys(){if(!this.session)return;const e=this.session.inputNames;if(e.length<=1){this.inKeys=[...this.configuredInKeys];return}if(this.configuredInKeys.length===e.length){this.inKeys=[...this.configuredInKeys];return}this.inKeys=e.map(t=>this.configuredInKeys.includes(t)?t:t==="obs"&&this.configuredInKeys.includes("policy")?"policy":t)}}class ane{constructor(e,t,r,i){this.mujoco=e,this.mjModel=t,this.mjData=r;const s=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(const a of i){const o=s.indexOf(a);if(o<0)throw new Error(`Joint "${a}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[o]),this.qvelAdr.push(t.jnt_dofadr[o]),this.jointIndices.push(o)}this.numActions=i.length,this.ctrlAdr=this.buildCtrlAdr()}build(){const e=this.mjData.qpos,t=this.mjData.qvel,r=new Float32Array(this.numActions),i=new Float32Array(this.numActions);for(let c=0;c<this.numActions;c++)r[c]=e[this.qposAdr[c]],i[c]=t[this.qvelAdr[c]];const s=new Float32Array([e[0],e[1],e[2]]),a=new Float32Array([e[3],e[4],e[5],e[6]]),o=new Float32Array([t[0],t[1],t[2]]),l=new Float32Array([t[3],t[4],t[5]]);return{jointPos:r,jointVel:i,rootPos:s,rootQuat:a,rootLinVel:o,rootAngVel:l}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}getControlMappingFor(e,t){if(!this.ctrlAdr)return null;const r=e.map(c=>new RegExp(`^(?:${c})$`)),i=c=>r.some(d=>d.test(c)),s=[],a=[],o=[],l=[];for(let c=0;c<t.length;c++)i(t[c])&&(s.push(this.ctrlAdr[c]),a.push(this.qposAdr[c]),o.push(this.qvelAdr[c]),l.push(c));return s.length===0?null:{ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l}}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;const e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let i=0;i<this.mjModel.nu;i++){const s=this.mjModel.actuator_trntype[i];e===void 0||s===e?t.push(this.mjModel.actuator_trnid[2*i]):t.push(-1)}const r=[];for(const i of this.jointIndices){const s=t.findIndex(a=>a===i);if(s<0)return null;r.push(s)}return r}getJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;let l=r.decode(t.subarray(a,o));!l&&s===0&&(l="floating_base_joint"),i.push(l)}return i}}class X4{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class one{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 lne extends X4{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 one(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class cne{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 une extends X4{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 cne(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class dne{constructor(e,t){this.terms=[];for(const r of e){const i=t[r.name];i&&this.terms.push(new i(r))}}onReset(e){for(const t of this.terms)t.onReset(e)}get size(){return this.terms.length}}class J4{constructor(e){this.config=e}}const hne={};class K4 extends J4{constructor(e){super(e),this.poseRange=e.params?.pose_range??{}}onReset(e){const{mjModel:t,mjData:r}=e;if(!t||!r)return;const i=this._findFreeJoint(t);if(i===-1)return;const s=t.jnt_qposadr[i],a=l=>{const c=this.poseRange[l];return c?c[0]+Math.random()*(c[1]-c[0]):0};r.qpos[s+0]+=a("x"),r.qpos[s+1]+=a("y"),r.qpos[s+2]+=a("z");const o=a("yaw");o!==0&&this._applyYawRotation(r.qpos,s+3,o)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}class fne extends J4{constructor(e){super(e),this.patchName=e.params?.patch_name??"spawn",this.fallback=new K4(e)}onReset(e){const{mjModel:t,mjData:r,terrainData:i}=e;if(!t||!r)return;const s=i?.flat_patches?.[this.patchName];if(!s||s.length===0){this.fallback.onReset(e);return}const a=this._findFreeJoint(t);if(a===-1)return;const o=t.jnt_qposadr[a],l=s[Math.floor(Math.random()*s.length)],c=r.qpos[o+2];r.qpos[o+0]=l[0],r.qpos[o+1]=l[1],r.qpos[o+2]=l[2]+c;const h=(this.config.params?.pose_range??{}).yaw??[-Math.PI,Math.PI],p=h[0]+Math.random()*(h[1]-h[0]);this._applyYawRotation(r.qpos,o+3,p)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}const pne={ResetRootStateUniform:K4,ResetRootStateFromFlatPatches:fne},Ane={...pne,...hne};function sg(n){return typeof n=="object"&&n!==null&&typeof n.setSelectedMotion=="function"}class Z4 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 WR(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 mne{constructor(e,t,r={}){this.render=()=>{if(Kn().updateDebugVisuals(),this.mjData&&$Z(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){F3(this.camera,this.lights);for(const[o,l]of this.lastSimState.bodies){const c=this.bodies[o];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion))}L3(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&hX({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}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:"."},i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&o.code}const{width:s,height:a}=this.getSize();this.scene=new s9,this.scene.name="scene",this.camera=new zr(45,s/a,.001,1e3),this.camera.name="PerspectiveCamera",this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new z7({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(s,a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=NN,this.renderer.outputColorSpace=ii,this.renderer.toneMapping=QN,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported("immersive-vr").then(o=>{o&&(this.vrButton=RC.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new O7(this.camera,this.renderer.domElement),this.controls.target.set(0,.2,0),this.controls.panSpeed=2,this.controls.zoomSpeed=1,this.controls.enableDamping=!0,this.controls.dampingFactor=.1,this.controls.screenSpacePanning=!0,this.controls.update(),this.renderer.setAnimationLoop(this.render),window.addEventListener("resize",this.onWindowResize),"ResizeObserver"in window?(this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),this.resizeObserver.observe(this.container)):this.resizeObserver=null,this.lastSimState={bodies:new Map,tendons:fX()},this.dynamicBodyIds=null,this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.loopPromise=null,this.running=!1,this.timestep=.001,this.decimation=1,this.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null,this.eventManager=null,this.terrainData=null,this.splatMesh=null,this.colliderMesh=null,this.cameraState={trackBodyId:null,prevBodyPos:null},this.sceneCacheManager=ww.getInstance(this.mujoco),this.resourceTracker=new GZ,this.memoryMonitor=new VZ}async loadEnvironment(e,t=null,r=null,i=null,s=null,a=null){this.terrainData=a,s&&s.length>0?this.eventManager=new dne(s,Ane):this.eventManager=null,await this.stop(),this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null);const o=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const l=performance.now()-o;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:l})}else this.memoryMonitor.logCacheOperation("miss",e),await this.sceneCacheManager.prepareForNewScene(),this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.resourceTracker.startTracking(this.mujoco),await bX(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);r&&(this.splatMesh=tB(r,this.scene),r.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(r.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.applyViewerConfig(i),this.running=!0,this.startLoop()}initializeCommands(){const e=Kn();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e,t){Kn().initialize(e,t)}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){const e=this.policyStateBuilder.build();this.policyRunner.reset(e)}}async setSelectedMotion(e){const t=Kn().getTerm("motion");if(!sg(t))return!1;const r=await t.setSelectedMotion(e);return r&&this.resetSimulation(),r}getSelectedMotionName(){const e=Kn().getTerm("motion");return sg(e)?e.getSelectedMotionName?.()??null:null}setReferenceVisible(e){const t=Kn().getTerm("motion");!sg(t)||typeof t.setReferenceVisible!="function"||t.setReferenceVisible(e)}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{const t=this.scene.getObjectByName("MuJoCo Root");t&&this.scene.remove(t);const r={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await vX(this.mujoco,e,r),!this.mjModel||!this.mjData)throw new Error("Failed to load MuJoCo model.");this.mujocoRoot=this.scene.getObjectByName("MuJoCo Root"),this.mujoco.mj_forward(this.mjModel,this.mjData),L3(this.mujoco,this.mjData,this.lights),F3(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds}),this.loadingScene=null})(),await this.loadingScene}async loadSceneWithOomRetry(e){try{await this.loadScene(e)}catch(t){if(!WR(t))throw t;this.loadingScene=null,await this.sceneCacheManager.clear();try{await this.loadScene(e)}catch(r){throw this.loadingScene=null,WR(r)?new Z4:r}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null),e&&(this.splatMesh=tB(e,this.scene),e.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&aP(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}async stop(){this.running=!1;const e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){const e=performance.now(),t=this.timestep*this.decimation;if(this.mjModel&&this.mjData){if(this.mujoco.mj_forward(this.mjModel,this.mjData),this.policyRunner&&this.policyStateBuilder){const s=this.policyStateBuilder.build(),a=this.policyRunner.collectObservationsByKey(s);if(await this.runOnnxInference(a),this.policyDebugCounter%60===0){const o="policy"in a?"policy":"observation"in a?"observation":Object.keys(a)[0],l=o?a[o]:null;l&&Array.from(l.slice(0,8))}this.policyDebugCounter+=1}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){const s=this.policyStateBuilder.build();if(this.terminationManager.evaluate(s).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){const o=this.policyStateBuilder.build();this.policyRunner.reset(o)}}Kn().update(t),Kn().updateDebugVisuals()}const r=(performance.now()-e)/1e3,i=Math.max(0,t-r);i>0&&await new Promise(s=>setTimeout(s,i*1e3))}this.loopPromise=null}async loadPolicyConfig(e){const t=this.policyConfigPath;this.policyConfigPath=e,this.policyRunner=null,this.policyStateBuilder=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null;const r=Kn();if(r.clear(),r.setResetCallback(()=>this.resetSimulation()),!!e&&!(!this.mjModel||!this.mjData)){e!==t&&this.resetSimulationState();try{const{config:i}=await this.fetchPolicyConfig(e);if(Array.isArray(i.motions)&&(i.motions=i.motions.map(o=>({...o,path:this.resolveAssetUrl(this.resolvePolicyAssetPath(e,o.path))}))),i.commands?.motion&&Array.isArray(i.motions)&&(i.commands.motion={...i.commands.motion,motions:i.motions}),this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),i.commands&&typeof i.commands=="object"){this.initializeCommandsFromConfig(i.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,bodies:this.bodies,mujocoRoot:this.mujocoRoot,requestReset:()=>this.resetSimulation()}),Kn().resetTerms();const o=Kn().getTerm("motion");sg(o)&&(await o.setSelectedMotion(i.motions?.find(l=>l.default)?.name??i.motions?.[0]?.name??null),o.setReferenceVisible?.(!0)),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()}if(!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new ine(i,{policyModules:{tracking:lne,locomotion:une},observations:Mee});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),this.policyRunner=s,this.policyStateBuilder=new ane(this.mujoco,this.mjModel,this.mjData,s.getPolicyJointNames());const a=this.policyStateBuilder.build();if(this.policyRunner.reset(a),this.policyControl=this.buildPolicyControl(i,s,this.policyStateBuilder),i.terminations&&Object.keys(i.terminations).length>0&&(this.terminationManager=new Tee(i.terminations,Pee)),i.onnx?.path){const o=this.resolvePolicyAssetPath(e,i.onnx.path),l=this.resolveAssetUrl(o),c={...i.onnx,path:l},d=new sne(c);await d.init(),this.onnxModule=d,this.onnxInputDict=d.initInput()}}catch{}}}async fetchPolicyConfig(e){const t=this.resolveAssetUrl(e),r=await fetch(t,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch policy config: ${r.status}`);return{config:await r.json(),resolvedUrl:t}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;const t=(this.baseUrl||"/").replace(/\/+$/,"/"),r=new URL(t,window.location.origin+"/").toString();return new URL(e.replace(/^\/+/,""),r).toString()}resolvePolicyAssetPath(e,t){const r=e.replace(/\\/g,"/"),i=r.lastIndexOf("/");return i>=0?`${r.slice(0,i+1)}${t}`.replace(/\/+/g,"/"):t}buildPolicyControl(e,t,r){const i=t.getPolicyJointNames(),s=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(c,d,h,p,A,y,m,x)=>{const g=h.qposAdr.length,_=h.actionIndices.map(Q=>i[Q]),b=this.normalizeControlArray(p,g,1,_),w=this.normalizeControlArray(A,g,0,_),C=x?t.getDefaultJointPos():new Float32Array(i.length),S=new Float32Array(g);for(let Q=0;Q<g;Q++)S[Q]=C[h.actionIndices[Q]];const M=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(i.length),T=new Float32Array(g);for(let Q=0;Q<g;Q++)T[Q]=M[h.actionIndices[Q]]??0;const R=this.normalizeControlArray(y,g,0,_),k=this.normalizeControlArray(m,g,0,_),$=h.ctrlAdr.map(Q=>Q<0||!this.mjModel?!1:this.mjModel.actuator_biastype[Q]===s);return $.some(Boolean),$.some(Q=>!Q),{controlType:d,ctrlAdr:h.ctrlAdr,qposAdr:h.qposAdr,qvelAdr:h.qvelAdr,actionIndices:h.actionIndices,actionScale:b,actionOffset:w,defaultJointPos:S,encoderBias:T,positionActuator:$,kp:R,kd:k}},o=e.actions;if(!o||Object.keys(o).length===0){const c=e.control_type??"joint_position";if(c!=="joint_position"&&c!=="torque")return null;const d=r.getControlMapping();if(!d)return null;const h={...d,actionIndices:Array.from({length:d.qposAdr.length},(p,A)=>A)};return[a("legacy",c,h,e.action_scale,void 0,e.stiffness,e.damping,!0)]}const l=[];for(const[c,d]of Object.entries(o)){const h=d.type??"joint_position";if(h!=="joint_position"&&h!=="torque")continue;const p=d.actuator_names??[".*"],A=p.length===1&&p[0]===".*";let y;if(A){const x=r.getControlMapping();if(!x)continue;y={...x,actionIndices:Array.from({length:x.qposAdr.length},(g,_)=>_)}}else if(y=r.getControlMappingFor(p,i),!y)continue;const m=d.use_default_offset!==void 0?d.use_default_offset:h==="joint_position";l.push(a(c,h,y,d.scale,d.offset,d.stiffness,d.damping,m))}return l.length===0?null:l}normalizeControlArray(e,t,r,i){const s=new Float32Array(t);if(s.fill(r),typeof e=="number")return s.fill(e),s;if(Array.isArray(e)){for(let a=0;a<t;a++)s[a]=typeof e[a]=="number"?e[a]:r;return s}if(e!==null&&typeof e=="object"&&i){for(const[a,o]of Object.entries(e)){const l=i.indexOf(a);l>=0&&l<t&&(s[l]=o)}return s}return s}resetSimulationState(){!this.mjModel||!this.mjData||(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),Kn().resetTerms(),this.onnxModule&&(this.onnxInputDict=this.onnxModule.initInput()),this.onnxTimeStep=0,this.mujoco.mj_forward(this.mjModel,this.mjData),this.lastSimState.bodies.clear(),this.updateCachedState())}executeSimulationSteps(){if(!(!this.mjModel||!this.mjData)){this.applyDragForces();for(let e=0;e<this.decimation;e++)this.applyPolicyControl(),this.mujoco.mj_step(this.mjModel,this.mjData)}}applyPolicyControl(){if(!this.policyControl||!this.mjData)return;const e=this.mjData.ctrl;e.fill(0);const t=this.policyRunner?.getLastActions()??new Float32Array(0);for(const r of this.policyControl){const{controlType:i,ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l,actionScale:c,actionOffset:d,defaultJointPos:h,encoderBias:p,positionActuator:A,kp:y,kd:m}=r,x=s.length;if(i==="joint_position")for(let g=0;g<x;g++){const _=s[g];if(_<0)continue;const b=t[l[g]]??0,w=h[g]+d[g]+c[g]*b-p[g];if(A[g])e[_]=w;else{const C=this.mjData.qpos[a[g]],S=this.mjData.qvel[o[g]];e[_]=y[g]*(w-C)+m[g]*(0-S)}}else if(i==="torque")for(let g=0;g<x;g++){const _=s[g];_>=0&&(e[_]=c[g]*(t[l[g]]??0))}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||(this.onnxInputDict=this.onnxModule.initInput());const t={...this.onnxInputDict};this.onnxModule.inKeys.includes("time_step")&&(t.time_step=new ti("float32",new Float32Array([this.onnxTimeStep]),[1,1]));for(const[d,h]of Object.entries(e))t[d]=new ti("float32",h,[1,h.length]);for(const d of this.onnxModule.inKeys)if(!t[d])return;const[r,i]=await this.onnxModule.runInference(t);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i}),this.onnxModule.inKeys.includes("time_step")&&(this.onnxTimeStep+=1);const s=this.onnxModule.outKeys[0],a=r.action??(s?r[s]:null)??r.policy??null;if(!a)return;const o=a.data,l=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&l.length!==c)return;this.policyRunner.setLastActions(l)}catch{}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let p=0;p<this.mjData.xfrc_applied.length;p++)this.mjData.xfrc_applied[p]=0;const e=this.dragStateManager.physicsObject;if(!e||!("bodyID"in e)||typeof e.bodyID!="number"||e.bodyID<=0)return;const t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(jc(this.mjData.xpos,p,this.bodies[p].position),pp(this.mjData.xquat,p,this.bodies[p].quaternion),this.bodies[p].updateWorldMatrix(!0,!1));this.dragStateManager.update();const r=this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale),i=P3(r),s=this.dragStateManager.worldHit.clone(),a=P3(s),o=new ue(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),l=new ue(a.x-o.x,a.y-o.y,a.z-o.z),c=new ue(i.x,i.y,i.z),d=new ue().crossVectors(l,c),h=t*6;this.mjData.xfrc_applied[h+0]=i.x,this.mjData.xfrc_applied[h+1]=i.y,this.mjData.xfrc_applied[h+2]=i.z,this.mjData.xfrc_applied[h+3]=d.x,this.mjData.xfrc_applied[h+4]=d.y,this.mjData.xfrc_applied[h+5]=d.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++)if(!(e&&!e.has(t))&&this.bodies[t]){this.lastSimState.bodies.has(t)||this.lastSimState.bodies.set(t,{position:new ue,quaternion:new Cn});const r=this.lastSimState.bodies.get(t);jc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&dX(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=OZ(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){const t=new Set;for(let r=1;r<e.nbody;r++){let i=r;for(;i>0;){if(e.body_jntnum[i]>0){t.add(r);break}i=e.body_parentid[i]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;const r=this.bodies[t];r&&(jc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion))}}dispose(){this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.dragStateManager&&(this.dragStateManager.dispose(),this.dragStateManager=null),this.mjData=null,this.mjModel=null,window.removeEventListener("resize",this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.controls.dispose(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.vrButton?.parentElement&&(this.vrButton.parentElement.removeChild(this.vrButton),this.vrButton=null),this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.lastSimState.bodies.clear()}disposeThreeJSResources(){if(this.scene)for(this.scene.traverse(e=>{"geometry"in e&&e.geometry&&e.geometry.dispose(),"material"in e&&e.material&&(Array.isArray(e.material)?e.material.forEach(t=>this.disposeMaterial(t)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),e.dispose()}getSize(){const e=this.container.clientWidth||window.innerWidth,t=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,t)}}async restoreFromCache(e){const t=this.sceneCacheManager.get(e);if(!t)throw new Error(`Scene ${e} not found in cache`);const r=this.scene.getObjectByName("MuJoCo Root");r&&this.scene.remove(r),this.mjModel=t.mjModel,this.mjData=t.mjData,this.bodies=t.bodies,this.lights=t.lights,this.mujocoRoot=t.mujocoRoot,this.scene.add(this.mujocoRoot),this.scene.background=t.skybox,this.mujoco.mj_forward(this.mjModel,this.mjData),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds})}async captureAndCacheResources(e){const t=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot)return;const r=this.resourceTracker.estimateSceneMemory({mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,meshes:{},mujocoRoot:this.mujocoRoot});await this.sceneCacheManager.set(e,{scenePath:e,lastAccessed:Date.now(),loadedAt:Date.now(),mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,lights:this.lights,meshes:{},mujocoRoot:this.mujocoRoot,skybox:this.scene.background instanceof ph?this.scene.background:null,fsFiles:t,estimatedMemoryBytes:r});const i=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation("load",e,{memoryMB:r/1048576,totalScenes:i.totalScenes,totalMemoryMB:i.totalMemoryBytes/1048576})}}const ag="mjswan_oom_reload_scene",gne=({scenePath:n,baseUrl:e,policyConfigPath:t,splatConfig:r,cameraConfig:i,eventsConfig:s,terrainData:a,selectedMotion:o,showReferenceMotion:l=!0,onStatusChange:c,onError:d,onReady:h,onRuntimeReady:p})=>{const A=U.useRef(null),y=U.useRef(null),m=U.useRef(null),x=U.useRef(r);x.current=r;const g=U.useRef(o);g.current=o;const _=U.useRef(l);return _.current=l,U.useEffect(()=>{let b=!1;const w=S=>{c?.(S)};return(async()=>{if(w("Loading MuJoCo..."),!m.current){const T=await RV(()=>import("./mujoco-Cp1xcNpc.js"),[]);m.current=await T.default()}if(b)return;const S=A.current;if(!S)throw new Error("Failed to find viewer container.");const M=m.current;if(!M)throw new Error("MuJoCo not loaded.");y.current||(y.current=new mne(M,S,{baseUrl:e}),p?.(y.current)),w("Loading scene assets..."),await y.current.loadEnvironment(n,t??null,x.current??null,i??null,s??null,a??null),await y.current.setSelectedMotion(g.current??null),y.current.setReferenceVisible(_.current),!b&&(sessionStorage.removeItem(ag),w("Running simulation"),h?.())})().catch(S=>{if(!b){if(S instanceof Z4){if(sessionStorage.getItem(ag)!==n){sessionStorage.setItem(ag,n),window.location.reload();return}sessionStorage.removeItem(ag)}d?.(S instanceof Error?S:new Error(String(S))),w("Failed to load scene")}}),()=>{b=!0,y.current?.dispose(),y.current=null}},[n,e,t,i,s,a,c,d,h]),U.useEffect(()=>{y.current&&y.current.setSelectedMotion(o??null)},[o]),U.useEffect(()=>{y.current?.setReferenceVisible(l)},[l]),j.jsx("div",{ref:A,className:"viewer"})};var yne={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};const ey=(n,e,t,r)=>{const i=U.forwardRef(({color:s="currentColor",size:a=24,stroke:o=2,title:l,className:c,children:d,...h},p)=>U.createElement("svg",{ref:p,...yne[n],width:a,height:a,className:["tabler-icon",`tabler-icon-${e}`,c].join(" "),strokeWidth:o,stroke:s,...h},[l&&U.createElement("title",{key:"svg-title"},l),...r.map(([A,y])=>U.createElement(A,y)),...Array.isArray(d)?d:[d]]));return i.displayName=`${t}`,i};const xne=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],ez=ey("outline","chevron-down","ChevronDown",xne);const vne=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],_ne=ey("outline","chevron-up","ChevronUp",vne);const bne=[["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"}]],wne=ey("outline","refresh","Refresh",bne);const Ene=[["path",{d:"M18 6l-12 12",key:"svg-0"}],["path",{d:"M6 6l12 12",key:"svg-1"}]],Cne=ey("outline","x","X",Ene),qR="0.5.5",YR=[{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"}],Ine={move:"touchmove",end:"touchend"},Sne={move:"mousemove",end:"mouseup"};function Bne(n){return n.type==="touchmove"}function Mne(n){return n.type==="mousemove"}const jp=On.createContext(null);function Ao({children:n,width:e,visible:t=!0,onVisibleChange:r,hiddenButtonTooltip:i}){const s=On.useRef(null),[a,{toggle:o}]=s0(!0),[l,c]=On.useState(800),d=On.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),h=On.useRef({}),p=(x,g,_)=>Math.abs(x+g/2)<Math.abs(x-_+g/2)?x:x-_,A=15;function y(x,g){const _=s.current;if(_===null)return[x,g];const b=_.parentElement;if(b===null)return[x,g];let w=x,C=g;return w=Math.min(w,b.clientWidth-_.clientWidth-A),w=Math.max(w,A),C=Math.min(C,b.clientHeight-_.clientHeight-A),C=Math.max(C,A),_.style.top=`${C.toString()}px`,_.style.left=`${w.toString()}px`,[p(w,_.clientWidth,b.clientWidth),p(C,_.clientHeight,b.clientHeight)]}On.useEffect(()=>{const x=s.current;if(x===null)return;const g=x.parentElement;if(g===null)return;const _=new ResizeObserver(()=>{h.current.x===void 0&&(h.current.x=p(x.offsetLeft,x.clientWidth,g.clientWidth)),h.current.y===void 0&&(h.current.y=p(x.offsetTop,x.clientHeight,g.clientHeight));const b=g.clientHeight-A*2;l!==b&&c(b);let w=h.current.x,C=h.current.y;for(;w<0;)w+=g.clientWidth;for(;C<0;)C+=g.clientHeight;y(w,C)});return _.observe(x),_.observe(g),()=>{_.disconnect()}});const m=x=>{const g=d.current,_=s.current;if(!_)return;x.type=="touchstart"?(x=x,g.startClientX=x.touches[0].clientX,g.startClientY=x.touches[0].clientY):(x=x,g.startClientX=x.clientX,g.startClientY=x.clientY),g.startPosX=_.offsetLeft,g.startPosY=_.offsetTop;const b=x.type=="touchstart"?Ine:Sne;function w(C){let S=0,M=0;if(Bne(C)?(C=C,S=C.touches[0].clientX-g.startClientX,M=C.touches[0].clientY-g.startClientY):Mne(C)&&(C=C,S=C.clientX-g.startClientX,M=C.clientY-g.startClientY),Math.abs(S)<=3&&Math.abs(M)<=3)return;g.dragging=!0;const T=g.startPosX+S,R=g.startPosY+M;[h.current.x,h.current.y]=y(T,R)}window.addEventListener(b.move,w),window.addEventListener(b.end,()=>{x.type=="touchstart"&&(g.dragging=!1),window.removeEventListener(b.move,w)},{once:!0})};if(!t){const x=j.jsx(Je,{component:"button","aria-label":i??"Show controls",onClick:()=>r?.(!0),style:{width:"0.85rem",height:"0.85rem",minWidth:"0.85rem",minHeight:"0.85rem",display:"block",padding:0,border:"none",borderRadius:"9999px",background:"rgba(255, 255, 255, 0.82)",boxShadow:"0 0 0 1px rgba(0, 0, 0, 0.14), 0 2px 8px rgba(0, 0, 0, 0.18)",cursor:"pointer"}});return j.jsx(Je,{style:{zIndex:10,position:"absolute",top:"1em",right:"1em"},children:i?j.jsx(Pl,{label:i,children:j.jsx(Je,{children:x})}):x})}return j.jsx(jp.Provider,{value:{wrapperRef:s,expanded:a,width:e,maxHeight:l,toggleExpanded:o,dragHandler:m,dragInfo:d},children:j.jsx(Xc,{radius:"xs",shadow:"0.1em 0 1em 0 rgba(0,0,0,0.1)",style:{boxSizing:"border-box",width:e,zIndex:10,position:"absolute",top:"1em",right:"1em",margin:0,"& .expandIcon":{transform:"rotate(0)"},overflow:"hidden"},ref:s,children:n})})}Ao.Handle=function({children:e}){const t=On.useContext(jp);return j.jsx(j.Fragment,{children:j.jsx(Je,{style:{borderRadius:"0.2em 0.2em 0 0",lineHeight:"1.5em",cursor:"pointer",position:"relative",fontWeight:400,userSelect:"none",display:"flex",alignItems:"center",padding:"0 0.75em",height:"2.75em"},onClick:()=>{const r=t.dragInfo.current;if(r.dragging){r.dragging=!1;return}t.toggleExpanded()},onTouchStart:r=>{t.dragHandler(r)},onMouseDown:r=>{t.dragHandler(r)},children:e})})};Ao.Contents=function({children:e}){const t=On.useContext(jp);return j.jsxs(Mg,{in:t.expanded,children:[j.jsx(Dd,{mx:"xs"}),j.jsx(su.Autosize,{mah:t.maxHeight,children:j.jsx(Je,{style:{width:t.width},children:e})})]})};Ao.HideWhenCollapsed=function({children:e}){return On.useContext(jp)?.expanded??!0?e:null};Ao.HideWhenExpanded=function({children:e}){return On.useContext(jp)?.expanded??!0?null:e};function og({id:n,label:e,children:t}){return j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsxs(EE,{align:"center",children:[j.jsx(Je,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:j.jsx("label",{htmlFor:n,children:e})})}),j.jsx(Je,{style:{flexGrow:1},children:t})]})})}function tz({label:n,expandByDefault:e=!0,children:t}){const[r,{toggle:i}]=s0(e),s=r?_ne:ez;return j.jsxs(Xc,{withBorder:!0,style:{borderWidth:"1px",position:"relative",marginLeft:"var(--mantine-spacing-xs)",marginRight:"var(--mantine-spacing-xs)",marginTop:"var(--mantine-spacing-xs)",marginBottom:"var(--mantine-spacing-xs)",paddingBottom:"calc(var(--mantine-spacing-xs) - 0.5em)"},children:[j.jsxs(Xc,{onClick:i,style:{fontSize:"0.875em",position:"absolute",padding:"0 0.375em",top:0,left:"0.375em",transform:"translateY(-50%)",userSelect:"none",fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center"},children:[n,j.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),j.jsx(Mg,{in:r,children:j.jsx(Je,{pt:"1em",children:t})}),j.jsx(Mg,{in:!r,children:j.jsx(Je,{p:"xs"})})]})}const nz={fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"4.5em",flexShrink:0},Tne={root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}},Rne={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 W_({axis:n,value:e,min:t=-1/0,max:r=1/0,step:i,onChange:s}){const a=U.useRef(null),o=U.useRef(null);U.useEffect(()=>{const y=a.current;y&&document.activeElement!==y&&(y.value=e.toFixed(2))},[e]);const l=y=>Math.max(t,Math.min(r,parseFloat((Math.round(y/i)*i).toFixed(10)))),c=y=>{y.preventDefault(),y.currentTarget.setPointerCapture(y.pointerId),o.current={startY:y.clientY,startValue:e,moved:!1}},d=y=>{if(!o.current||!(y.buttons&1))return;const m=o.current.startY-y.clientY;if(Math.abs(m)>3&&(o.current.moved=!0),!o.current.moved)return;const x=l(o.current.startValue+m*i);s(x),a.current&&(a.current.value=x.toFixed(2))},h=()=>{if(o.current&&!o.current.moved){const y=a.current;y&&(y.focus(),y.select())}o.current=null},p=y=>{const m=parseFloat(y.target.value);isNaN(m)||s(l(m)),y.target.value=e.toFixed(2)},A=y=>{y.key==="Enter"&&y.currentTarget.blur(),y.key==="Escape"&&(a.current&&(a.current.value=e.toFixed(2)),a.current?.blur())};return j.jsxs(Je,{style:{display:"flex",alignItems:"center",gap:"0.25em",flex:1},children:[j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,letterSpacing:"-0.75px",flexShrink:0},children:n}),j.jsx("input",{ref:a,size:1,defaultValue:e.toFixed(2),onPointerDown:c,onPointerMove:d,onPointerUp:h,onBlur:p,onKeyDown:A,onFocus:y=>y.currentTarget.style.outline="2px solid var(--mantine-color-blue-5)",onBlurCapture:y=>y.currentTarget.style.outline="none",style:Rne})]})}function XR({label:n,x:e,y:t,z:r,step:i,xLabel:s="X",yLabel:a="Y",zLabel:o="Z",onX:l,onY:c,onZ:d}){return j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Xs,{c:"dimmed",style:nz,children:n}),j.jsx(W_,{axis:s,value:e,step:i,onChange:l}),j.jsx(W_,{axis:a,value:t,step:i,onChange:c}),j.jsx(W_,{axis:o,value:r,step:i,onChange:d})]})}function Dne({scale:n,xOffset:e,yOffset:t,zOffset:r,roll:i,pitch:s,yaw:a,onCalibrate:o}){const[l,c]=U.useState(n),[d,h]=U.useState(e),[p,A]=U.useState(t),[y,m]=U.useState(r),[x,g]=U.useState(i),[_,b]=U.useState(s),[w,C]=U.useState(a);U.useEffect(()=>{c(n)},[n]),U.useEffect(()=>{h(e)},[e]),U.useEffect(()=>{A(t)},[t]),U.useEffect(()=>{m(r)},[r]),U.useEffect(()=>{g(i)},[i]),U.useEffect(()=>{b(s)},[s]),U.useEffect(()=>{C(a)},[a]);const S=(M,T,R,k,$,Q,H)=>o(M,T,R,k,$,Q,H);return j.jsxs(tz,{label:"Control",expandByDefault:!0,children:[j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Xs,{c:"dimmed",style:nz,children:"Scale"}),j.jsx(Je,{style:{flex:1},children:j.jsx(P0,{value:l,onChange:M=>{c(M),S(M,d,p,y,x,_,w)},min:.1,max:5,step:.05,size:"xs",label:M=>M.toFixed(2),styles:Tne})})]}),j.jsx(XR,{label:"Position",x:d,y:p,z:y,step:.05,onX:M=>{h(M),S(l,M,p,y,x,_,w)},onY:M=>{A(M),S(l,d,M,y,x,_,w)},onZ:M=>{m(M),S(l,d,p,M,x,_,w)}}),j.jsx(XR,{label:"Rotation",x,y:_,z:w,step:.5,xLabel:"R",yLabel:"P",zLabel:"Y",onX:M=>{g(M),S(l,d,p,y,M,_,w)},onY:M=>{b(M),S(l,d,p,y,x,M,w)},onZ:M=>{C(M),S(l,d,p,y,x,_,M)}})]})}function kne(n){return n instanceof HTMLElement?n.isContentEditable?!0:n.closest('input, textarea, select, [contenteditable], [role="textbox"], [role="searchbox"], [role="combobox"]')!==null:!1}function Nne(n){return n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Qne({command:n,value:e,onChange:t,disabled:r,enabledWhenValue:i}){const s=n.config,a=s.enabled_when!==void 0&&(i??0)<.5,o=r||a;return j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:s.label}),j.jsx(Je,{style:{width:"50%"},children:j.jsx(P0,{value:e,onChange:l=>t(n.id,l),min:s.min,max:s.max,step:s.step,size:"xs",disabled:o,styles:{root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}}})})]})}function Pne({command:n,value:e,onChange:t,disabled:r}){const i=n.config;return j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsx(Gl,{label:i.label,checked:e>=.5,onChange:s=>t(n.id,s.currentTarget.checked?1:0),size:"xs",disabled:r})})}function Lne(n){const{visible:e,onVisibleChange:t,projects:r,projectValue:i,projectLabel:s,onProjectChange:a,scenes:o,sceneValue:l,onSceneChange:c,splats:d,splatSection:h=!1,splatValue:p,onSplatChange:A,splatConfig:y,onCalibrateSplat:m,onSplatUrlLoad:x,policies:g,policyValue:_,onPolicyChange:b,motions:w,motionValue:C,onMotionChange:S,showReferenceMotion:M,onShowReferenceMotionChange:T,commandsEnabled:R=!1,onReset:k}=n,[$,{open:Q,close:H}]=s0(!1),[B,W]=U.useState(""),[K,Y]=U.useState(null),[G,X]=U.useState(!1),re=U.useCallback(async ve=>{if(ve.key!=="Enter"||!x)return;const Ne=B.trim();if(d.some(Ge=>Ge.label===Ne||Ge.value===Ne))return;if(!Ne.toLowerCase().endsWith(".spz")){Y("URL must end with .spz");return}await x(Ne)?(Y(null),X(!0)):Y("File not found at the specified URL")},[x,B,d]),[L,V]=U.useState([]),[oe,Ae]=U.useState([]),[ye,he]=U.useState({});U.useEffect(()=>{const ve=Kn(),Ne=()=>{V(ve.getCommands()),Ae(ve.getCommandGroups()),he(ve.getValues())};return Ne(),ve.addEventListener(Ne),()=>{ve.removeEventListener(Ne)}},[]),U.useEffect(()=>{const ve=Ne=>{if(Ne.defaultPrevented||Ne.repeat||Ne.altKey||Ne.ctrlKey||Ne.metaKey||Ne.key.toLowerCase()!=="c")return;const rt=Ne.target instanceof Element?Ne.target:document.activeElement;kne(rt)||(Ne.preventDefault(),t(!e))};return window.addEventListener("keydown",ve),()=>{window.removeEventListener("keydown",ve)}},[e,t]);const fe=U.useCallback((ve,Ne)=>{Kn().setValue(ve,Ne),he(Ge=>({...Ge,[ve]:Ne}))},[]),Ee=U.useCallback(()=>{Kn().triggerButton("_system:reset"),k&&k()},[k]),Re=ve=>L.filter(Ne=>Ne.groupName===ve&&(Ne.config.type==="slider"||Ne.config.type==="checkbox"));return!r.length&&!o.length&&!g.length?null:j.jsxs(j.Fragment,{children:[j.jsx(aa,{opened:$,onClose:H,size:"lg",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:j.jsxs(sC,{gap:"md",align:"center",children:[j.jsx(Pg,{src:"./logo-color.svg",style:{width:"8em",height:"auto"}}),j.jsx(Xs,{size:"xl",fw:700,children:"powered by mjswan"}),j.jsxs(Xs,{size:"sm",c:"dimmed",children:["version ",qR]}),j.jsx(Xs,{size:"sm",c:"dimmed",children:"MuJoco Simulation on Web Assembly with Neural netwroks"}),j.jsx(Dd,{w:"100%"}),j.jsxs(Je,{children:[j.jsx(up,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"})," • ",j.jsx(up,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]}),j.jsx(Dd,{w:"100%"}),j.jsxs(Je,{style:{textAlign:"left",maxHeight:"120px",overflowY:"auto",lineHeight:"1",fontSize:"0.8rem",opacity:"0.75"},px:"md",children:["Thanks to our contributors! ",j.jsx("br",{}),YR.map((ve,Ne)=>j.jsxs("span",{children:[j.jsx(up,{href:ve.html_url,target:"_blank",style:{textDecoration:"none",fontSize:"0.75rem"},children:ve.login}),Ne<YR.length-1&&", "]},ve.login))]})]})}),j.jsxs(Ao,{width:"20em",visible:e,onVisibleChange:t,hiddenButtonTooltip:"Show controls (C)",children:[j.jsxs(Ao.Handle,{children:[j.jsx(Pl,{label:`mjswan ${qR}`,children:j.jsx(Je,{component:"a",onClick:ve=>{ve.stopPropagation(),Q()},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{position:"absolute",cursor:"pointer",display:"flex",top:"0.8em",left:"0.9em"},children:j.jsx(Pg,{src:"./logo.svg",style:{width:"1.2em",height:"auto"}})})}),j.jsx("div",{style:{width:"1.1em"}}),j.jsx(Ao.HideWhenCollapsed,{children:j.jsxs(Je,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[j.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),r.length>1&&j.jsxs(pi,{position:"bottom-start",offset:5,children:[j.jsx(pi.Target,{children:j.jsx(Je,{onClick:ve=>ve.stopPropagation(),onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center",flexShrink:0},children:j.jsx(ez,{size:16})})}),j.jsx(pi.Dropdown,{onClick:ve=>ve.stopPropagation(),children:r.map(ve=>j.jsx(pi.Item,{onClick:Ne=>{Ne.stopPropagation(),a(ve.value)},style:{fontWeight:ve.value===i?600:400,backgroundColor:ve.value===i?"rgba(34, 139, 230, 0.1)":void 0},children:ve.label},ve.value))})]})]})}),j.jsx(Ao.HideWhenExpanded,{children:j.jsx(Je,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:s})}),j.jsx(Pl,{label:"Hide controls (C)",children:j.jsx(au,{variant:"subtle",color:"gray",size:"sm","aria-label":"Hide controls",onClick:ve=>{ve.stopPropagation(),t(!1)},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),children:j.jsx(Cne,{size:14})})})]}),j.jsx(Ao.Contents,{children:j.jsxs(Je,{pt:"0.375em",children:[o.length>0&&j.jsx(og,{id:"scene-select",label:"Scene",children:j.jsx(zc,{id:"scene-select",placeholder:"Select scene",data:o,value:l,onChange:c,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),(d.length>0||h)&&j.jsx(og,{id:"splat-select",label:"Splat",children:j.jsx(Pl,{label:K??"",color:"red",position:"bottom",opened:K!==null,withArrow:!0,children:j.jsx(zc,{id:"splat-select",placeholder:x!==void 0?"Select splat or paste .spz URL":"Select splat",data:d,value:p,onChange:ve=>{A(ve),Y(null),X(!1)},searchable:x!==void 0,searchValue:B,onSearchChange:ve=>{W(ve),ve&&Y(null)},onKeyDown:re,size:"xs",radius:"xs",clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})})}),(y?.control&&p!==null||G)&&m&&j.jsx(Dne,{scale:y?.scale??1,xOffset:y?.xOffset??0,yOffset:y?.yOffset??0,zOffset:y?.zOffset??0,roll:y?.roll??0,pitch:y?.pitch??0,yaw:y?.yaw??0,onCalibrate:m}),g.length>0&&j.jsx(og,{id:"policy-select",label:"Policy",children:j.jsx(zc,{id:"policy-select",placeholder:"Select policy",data:g,value:_,onChange:b,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),w.length>0&&j.jsxs(j.Fragment,{children:[j.jsx(og,{id:"motion-select",label:"Motion",children:j.jsx(zc,{id:"motion-select",placeholder:"Select motion",data:w,value:C,onChange:S,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsx(Gl,{label:"Show reference",checked:M,onChange:ve=>T(ve.currentTarget.checked),size:"xs"})})]}),oe.length>0&&L.some(ve=>ve.config.type==="slider"||ve.config.type==="checkbox")&&j.jsx(j.Fragment,{children:oe.map(ve=>{const Ne=Re(ve);return Ne.length===0?null:j.jsx(tz,{label:Nne(ve),expandByDefault:!0,children:Ne.map(rt=>rt.config.type==="checkbox"?j.jsx(Pne,{command:rt,value:ye[rt.id]??0,onChange:fe,disabled:!R},rt.id):rt.config.type!=="slider"?null:j.jsx(Qne,{command:rt,value:ye[rt.id]??0,onChange:fe,disabled:!R,enabledWhenValue:rt.config.enabled_when?ye[Ew(rt.groupName,rt.config.enabled_when)]:void 0},rt.id))},ve)})}),j.jsx(Dd,{mb:"xs",mx:"xs"}),j.jsx(Je,{px:"xs",pb:"xs",children:j.jsx(lh,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:j.jsx(wne,{size:14}),onClick:Ee,children:"Reset"})})]})})]})]})}function Xf(n,e,t){return Object.keys(n[e]).reduce((r,i)=>(r[i]=`var(--mantine-${t}-${i})`,r),{})}function JR(n,e){return n in e.breakpoints?e.breakpoints[n]:X_(n)}function Fne(n){const e=bD(c0,n),t=Xf(e,"fontSizes","font-size"),r=Xf(e,"lineHeights","line-height"),i=Xf(e,"shadows","shadow"),s=Xf(e,"radius","radius"),a=Xf(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: ${JR(c,e)})`,largerThan:c=>`(min-width: ${JR(c,e)})`}}const Ow={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:Gl.extend({defaultProps:{radius:"xs"}}),ColorInput:jE.extend({defaultProps:{radius:"xs"}}),Select:zc.extend({defaultProps:{radius:"sm"}}),Textarea:qE.extend({defaultProps:{radius:"xs"}}),TextInput:aC.extend({defaultProps:{radius:"xs"}}),NumberInput:nC.extend({defaultProps:{radius:"xs"}}),Paper:Xc.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:au.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:lh.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};Fne(Ow);const rz=U.createContext(void 0),iz=()=>{const n=U.useContext(rz);if(!n)throw new Error("useLoading must be used within a LoadingProvider");return n},zne=({children:n})=>{const[e,t]=U.useState(!1),r=U.useRef(0),i=U.useCallback(()=>{r.current+=1,r.current>0&&t(!0)},[]),s=U.useCallback(()=>{r.current=Math.max(0,r.current-1),r.current===0&&t(!1)},[]);return j.jsx(rz.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:n})},Une=()=>{const{isLoading:n}=iz();return n?j.jsx("div",{className:"loader-overlay",children:j.jsx("div",{className:"loader-content",children:j.jsx(sh,{size:64,type:"bars"})})}):null},$w="panel",Gw="ref";function One(){const n="/".replace(/\/+$/,"/");let t=window.location.pathname.replace(/^\/+|\/+$/g,"");const r=n.replace(/^\/+|\/+$/g,"");if(r&&(t===r?t="":t.startsWith(`${r}/`)&&(t=t.slice(r.length+1))),!t)return null;const i=t.split("/")[0];return i==="main"||i.includes(".")||i==="assets"?null:i}function _I(n){return n.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function $ne(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 Gne(n,e){const r=new URLSearchParams(window.location.search).get("config"),i=$ne(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=>_I(r.name)===t)||n.scenes[0]}function q_(n,e){if(!n.policies.length)return null;const t=n.policies.find(s=>s.default)??n.policies[0];if(!e)return t.name;const r=e.trim().toLowerCase();return(n.policies.find(s=>s.name.toLowerCase()===r)||n.policies.find(s=>_I(s.name)===r))?.name??t.name}function Jf(n,e){return n?.motions?.length?(n.motions.find(r=>r.default)??n.motions[0]).name:null}function Vne(n){return new URLSearchParams(n).get($w)!=="0"}function Hne(n){return new URLSearchParams(n).get(Gw)!=="0"}function jne(n){const t="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let r=t?`/${t}/`:"/";return n&&n!=="main"&&(r+=`${n}/`),r}function Wne({projectId:n,sceneName:e,policyName:t,panelVisible:r,showReference:i}){const s=jne(n),a=new URLSearchParams(window.location.search);e?a.set("scene",e):a.delete("scene"),t?a.set("policy",t):a.delete("policy"),r?a.delete($w):a.set($w,"0"),i?a.delete(Gw):a.set(Gw,"0");const o=a.toString(),l=s+(o?`?${o}`:"")+window.location.hash;window.history.replaceState({},"",l)}function qne(){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(()=>Hne(window.location.search)),[p,A]=U.useState(null),[y,m]=U.useState(null),[x,g]=U.useState(null),[_,b]=U.useState(()=>Vne(window.location.search)),w=U.useRef(null),{showLoading:C,hideLoading:S}=iz(),M=U.useMemo(()=>One(),[]),T=U.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),R=U.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);U.useEffect(()=>{C(),Gne("/",M).then(J=>{e(J);const ge=J.projects.find(Ce=>M===null?Ce.id===null:Ce.id===M);if(!ge)throw new Error(`Project "${M??"(main)"}" not found in config.json.`);r(ge);const te=KR(ge,T);s(te);const ee=te?q_(te,R):null;o(ee);const ie=te?.policies.find(Ce=>Ce.name===ee)??null;c(Jf(ie))}).catch(J=>{A(J.message||"Failed to load config."),S()})},[M,T,R,C,S]);const k=U.useMemo(()=>{if(!t||!i)return null;const J=t.id?t.id:"main",ge=i.path?i.path:`scene/${_I(i.name)}/scene.xml`;return`${J}/assets/${ge}`.replace(/\/+/g,"/")},[t,i]),$=U.useMemo(()=>!i||!a?null:i.policies.find(J=>J.name===a)??null,[i,a]),Q=U.useMemo(()=>!t||!$?.config?null:`${t.id?t.id:"main"}/assets/${$.config}`.replace(/\/+/g,"/"),[t,$]),H=U.useMemo(()=>$?.motions?.length?$.motions.map(J=>({value:J.name,label:J.name})):[],[$]),B=U.useMemo(()=>{if(!t||!i?.splats?.length)return[];const J=t.id?t.id:"main";return i.splats.map(ge=>{if(ge.path){const te=`${J}/assets/${ge.path}`.replace(/\/+/g,"/");return{...ge,url:te}}return ge})},[t,i?.splats]),W=U.useMemo(()=>y?B.find(J=>J.name===y)??null:x?{name:"Custom",url:x}:null,[B,y,x]),K=U.useMemo(()=>n?n.projects.map(J=>({value:J.id??"main",label:J.name||(J.id??"Main")})):[],[n]),Y=U.useMemo(()=>t?t.scenes.map(J=>({value:J.name,label:J.name})):[],[t]),G=U.useMemo(()=>!i||!i.policies?[]:i.policies.map(J=>({value:J.name,label:J.name})),[i]),X=t?t.id??"main":null,re=i?.name??null,L=U.useCallback(J=>{A(J.message),S()},[S]),V=U.useCallback(()=>{S()},[S]);U.useEffect(()=>{const J=i?.splats?.[0];m(J?J.name:null),g(null)},[i]);const oe=U.useCallback(J=>{w.current=J},[]);U.useEffect(()=>{c(Jf($)),h(!!$?.motions?.length)},[$]);const Ae=U.useMemo(()=>i?.splats?.length?i.splats.map(J=>({value:J.name,label:J.name})):[],[i?.splats]),ye=U.useCallback(J=>{if(J===null)w.current?.setSplat(null);else{const ge=B.find(te=>te.name===J);ge&&w.current?.setSplat(ge)}m(J),g(null)},[B]),he=U.useCallback(async J=>{try{if(!(await fetch(J,{method:"HEAD"})).ok)return!1}catch{return!1}return w.current?.setSplat({name:"Custom",url:J}),g(J),!0},[]),fe=U.useCallback((J,ge,te,ee,ie,Ce,be)=>{const de=W??(x?{name:"Custom",url:x}:null);de&&w.current?.calibrateSplat({...de,scale:J,xOffset:ge,yOffset:te,zOffset:ee,roll:ie,pitch:Ce,yaw:be})},[W,x]),Ee=U.useCallback(J=>{Wne({projectId:J.projectId??t?.id??null,sceneName:J.sceneName??i?.name??null,policyName:J.policyName??a,panelVisible:J.panelVisible??_,showReference:J.showReference??d})},[t?.id,i?.name,a,_,d]),Re=U.useCallback(J=>{if(!n||!J)return;const ge=J==="main"?null:J,te=n.projects.find(be=>(be.id??"main")===(ge??"main"));if(!te)return;C(),r(te);const ee=KR(te,null);s(ee);const ie=ee?q_(ee,null):null;o(ie);const Ce=ee?.policies.find(be=>be.name===ie)??null;c(Jf(Ce)),Ee({projectId:te.id,sceneName:ee?.name??null,policyName:ie})},[n,C,Ee]),ve=U.useCallback(J=>{if(!t||!J)return;const ge=t.scenes.find(ie=>ie.name===J);if(!ge)return;C(),s(ge);const te=q_(ge,null);o(te);const ee=ge.policies.find(ie=>ie.name===te)??null;c(Jf(ee)),Ee({projectId:t.id,sceneName:J,policyName:te})},[t,C,Ee]),Ne=U.useCallback(J=>{J!==a&&C(),o(J);const ge=i?.policies.find(te=>te.name===J)??null;c(Jf(ge)),Ee({policyName:J})},[a,C,Ee]),rt=U.useCallback(J=>{b(J),Ee({panelVisible:J})},[Ee]),Ge=U.useCallback(J=>{const ge=l;c(J),w.current?.setSelectedMotion(J)?.then(ee=>{ee===!1&&J!==null&&c(w.current?.getSelectedMotionName()??ge)})},[l]),F=U.useCallback(J=>{h(J),w.current?.setReferenceVisible(J),Ee({showReference:J})},[Ee]);return p?j.jsx(eb,{theme:Ow,defaultColorScheme:"auto",children:j.jsx("div",{className:"app",children:j.jsxs("div",{className:"hud hud-error",children:[j.jsx("h1",{className:"hud-title",children:"mjswan"}),j.jsx("p",{className:"hud-message",children:p})]})})}):!t||!i||!k?null:j.jsx(eb,{theme:Ow,defaultColorScheme:"auto",children:j.jsxs("div",{className:"app",children:[j.jsx(Une,{}),j.jsx(Lne,{visible:_,onVisibleChange:rt,projects:K,projectValue:X,projectLabel:t?.name??"mjswan",onProjectChange:Re,scenes:Y,sceneValue:re,onSceneChange:ve,splats:Ae,splatSection:i?.splatSection??!1,splatValue:y,onSplatChange:ye,splatConfig:W,onCalibrateSplat:fe,onSplatUrlLoad:he,policies:G,policyValue:a,onPolicyChange:Ne,motions:H,motionValue:l,onMotionChange:Ge,showReferenceMotion:d,onShowReferenceMotionChange:F,commandsEnabled:!!Q}),j.jsx(gne,{scenePath:k,baseUrl:"/",policyConfigPath:Q,splatConfig:W,cameraConfig:i?.camera,eventsConfig:i?.events,terrainData:i?.terrainData,selectedMotion:l,showReferenceMotion:d,onError:L,onReady:V,onRuntimeReady:oe})]})})}function Yne(){return j.jsx(zne,{children:j.jsx(qne,{})})}const ZR=document.getElementById("root");ZR&&Wz.createRoot(ZR).render(j.jsx(On.StrictMode,{children:j.jsx(Yne,{})}));export{RV as _};
|
|
15609
|
+
${s}`,o=t.createShaderModule({code:a,label:n.name});un("verbose",()=>`[WebGPU] ${n.name} shader code: ${a}`);let l=t.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:n.name});return Zs(n.name),{programInfo:n,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(n){let e=typeof n=="number"?n:n.x,t=typeof n=="number"?1:n.y||1,r=typeof n=="number"?1:n.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&t<=i&&r<=i)return[e,t,r];let s=e*t*r,a=Math.ceil(Math.sqrt(s));if(a>i){if(a=Math.ceil(Math.cbrt(s)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),k4={};vh(k4,{WebGpuBackend:()=>N4});var zR,UR,OR,N4,Zte=et(()=>{xs(),Lt(),No(),HP(),cte(),Jte(),Kte(),zR=(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("|")},UR=(n,e,t)=>{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${zR(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},OR=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},N4=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 OR(e.info||await e.requestAdapterInfo()),this.gpuDataManager=qP(this),this.programManager=new D4(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,nI(n.logLevel,!!n.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let n=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Fa(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(n.getMappedRange()),t=this.pendingQueries.get(n);for(let r=0;r<e.length/2;r++){let i=t[r],s=i.kernelId,a=this.kernels.get(s),o=a.kernelType,l=a.kernelName,c=i.programName,d=i.inputTensorViews,h=i.outputTensorViews,p=e[r*2],A=e[r*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=p);let y=Number(p-this.queryTimeBase),m=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(y)||!Number.isSafeInteger(m))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(x=>({dims:x.dims,dataType:po(x.dataType)})),outputsMetadata:h.map(x=>({dims:x.dims,dataType:po(x.dataType)})),kernelId:s,kernelType:o,kernelName:l,programName:c,startTime:y,endTime:m});else{let x="";d.forEach((_,b)=>{x+=`input[${b}]: [${_.dims}] | ${po(_.dataType)}, `});let g="";h.forEach((_,b)=>{g+=`output[${b}]: [${_.dims}] | ${po(_.dataType)}, `})}qg("GPU",`${c}::${p}::${A}`)}n.unmap(),this.pendingQueries.delete(n)}),Zs()}run(n,e,t,r,i,s){Fa(n.name);let a=[];for(let _=0;_<e.length;++_){let b=e[_].data;if(b===0)continue;let w=this.gpuDataManager.get(b);if(!w)throw new Error(`no GPU data for input: ${b}`);a.push(w)}let{outputs:o,dispatchGroup:l,programUniforms:c}=n.getRunData(e),d=t.length===0?o.map((_,b)=>b):t;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let h=[],p=[];for(let _=0;_<o.length;++_){if(!Number.isInteger(d[_])||d[_]<-3||d[_]>=s)throw new Error(`Invalid output index: ${d[_]}`);if(d[_]===-3)continue;let b=d[_]===-1,w=d[_]===-2,C=b||w?i(o[_].dataType,o[_].dims):r(d[_],o[_].dataType,o[_].dims);if(h.push(C),C.data===0)continue;let S=this.gpuDataManager.get(C.data);if(!S)throw new Error(`no GPU data for output: ${C.data}`);if(b&&this.temporaryData.push(S),w){let M=this.kernelPersistentData.get(this.currentKernelId);M||(M=[],this.kernelPersistentData.set(this.currentKernelId,M)),M.push(S)}p.push(S)}if(a.length!==e.length||p.length!==h.length){if(p.length===0)return Zs(n.name),h;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let A;if(c){let _=0,b=[];c.forEach(M=>{let T=typeof M.data=="number"?[M.data]:M.data;if(T.length===0)return;let R=M.type===10?2:4,k,$;M.type===10?($=T.length>4?16:T.length>2?8:T.length*R,k=T.length>4?16:R*T.length):($=T.length<=2?T.length*R:16,k=16),_=Math.ceil(_/$)*$,b.push(_);let Q=M.type===10?8:4;_+=T.length>4?Math.ceil(T.length/Q)*k:T.length*R});let w=16;_=Math.ceil(_/w)*w;let C=new ArrayBuffer(_);c.forEach((M,T)=>{let R=b[T],k=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(C,R,k.length).set(k);else if(M.type===12)new Uint32Array(C,R,k.length).set(k);else if(M.type===10)new Uint16Array(C,R,k.length).set(k);else if(M.type===1)new Float32Array(C,R,k.length).set(k);else throw new Error(`Unsupported uniform type: ${po(M.type)}`)});let S=this.gpuDataManager.create(_,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(S.buffer,0,C,0,_),this.gpuDataManager.release(S.id),A={offset:0,size:_,buffer:S.buffer}}let y=this.programManager.normalizeDispatchGroupSize(l),m=y[1]===1&&y[2]===1,x=UR(n,e,m),g=this.programManager.getArtifact(x);if(g||(g=this.programManager.build(n,y),this.programManager.setArtifact(x,g),un("info",()=>`[artifact] key: ${x}, programName: ${n.name}`)),c&&g.uniformVariablesInfo){if(c.length!==g.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${g.uniformVariablesInfo.length}, got ${c.length} in program "${g.programInfo.name}".`);for(let _=0;_<c.length;_++){let b=c[_],w=b.type,C=typeof b.data=="number"?1:b.data.length,[S,M]=g.uniformVariablesInfo[_];if(w!==S||C!==M)throw new Error(`Uniform variable ${_} mismatch: expect type ${S} with size ${M}, got type ${w} with size ${C} in program "${g.programInfo.name}".`)}}if(un("info",()=>`[ProgramManager] run "${n.name}" (key=${x}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let _={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(_),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(_)}return this.programManager.run(g,a,p,y,A),Zs(n.name),h}upload(n,e){this.gpuDataManager.upload(n,e)}memcpy(n,e){this.gpuDataManager.memcpy(n,e)}async download(n,e){await this.gpuDataManager.download(n,e)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,e,t,r){let i=R4.get(n);if(!i)throw new Error(`kernel not implemented: ${n}`);let s={kernelType:n,kernelName:r,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(e,s)}releaseKernel(n){let e=this.kernelPersistentData.get(n);if(e){for(let t of e)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,e,t){let r=this.kernels.get(n);if(!r)throw new Error(`kernel not created: ${n}`);let i=r.kernelType,s=r.kernelName,a=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${s}" is not allowed to be called recursively`);this.currentKernelId=n,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),un("info",()=>`[WebGPU] Start to run kernel "[${i}] ${s}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(e,o[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${s}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${s}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,e,t,r){let i=this.sessionExternalDataMapping.get(n);i||(i=new Map,this.sessionExternalDataMapping.set(n,i));let s=i.get(e),a=this.gpuDataManager.registerExternalBuffer(t,r,s);return i.set(e,[a,t]),a}unregisterBuffers(n){let e=this.sessionExternalDataMapping.get(n);e&&(e.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let e=this.gpuDataManager.get(n);if(!e)throw new Error(`no GPU data for buffer: ${n}`);return e.buffer}createDownloader(n,e,t){return async()=>{let r=await Bw(this,n,e);return rI(r.buffer,t)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){un("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){un("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){un("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),t=n.length;this.pendingKernels=[];for(let r=0;r<t;r++){let i=this.getComputePassEncoder(),s=n[r];this.writeTimestamp(this.pendingDispatchNumber*2),i.setPipeline(s.computePipeline),i.setBindGroup(0,s.bindGroup),i.dispatchWorkgroups(...s.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(e[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),Q4={};vh(Q4,{init:()=>P4});var ng,$R,P4,ene=et(()=>{Lt(),No(),jt(),lte(),ng=class L4{constructor(e,t,r,i){this.module=e,this.dataType=t,this.data=r,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Le.size(e)!==Le.size(this.dims))throw new Error("Invalid new shape");return new L4(this.module,this.dataType,this.data,e)}},$R=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 ng(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 ng(this.module,o,this.output(a,l),l),s=(a,o)=>{let l=Pc(a,o);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new ng(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)}}},P4=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=(Zte(),Pp(k4)).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 $R(e,a,Number(l));return a.computeKernel(Number(o),h,d)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let s=new WP(t);i("webnn",[s,()=>s.reserveTensorId(),a=>s.releaseTensorId(a),async(a,o,l,c,d)=>s.ensureTensor(a,o,l,c,d),(a,o)=>{s.uploadTensor(a,o)},async(a,o)=>s.downloadTensor(a,o),(a,o)=>s.registerMLContext(a,o),!!t.trace])}}}),GR,pI,AI,Il,VR,G_,t0,mI,gI,V_,yI,xI,vI,F4=et(()=>{xs(),ite(),ste(),Lt(),cu(),KC(),OP(),GR=(n,e)=>{kn()._OrtInit(n,e)!==0&&wn("Can't initialize onnxruntime.")},pI=async n=>{GR(n.wasm.numThreads,Xg(n.logLevel))},AI=async(n,e)=>{kn().asyncInit?.();let t=n.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(t){if(typeof t.limits!="object"||typeof t.features!="object"||typeof t.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=n.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let i=n.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:i}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let r=(ene(),Pp(Q4)).init;e==="webgpu"&&await r("webgpu",kn(),n,t),e==="webnn"&&await r("webnn",kn(),n)}},Il=new Map,VR=n=>{let e=kn(),t=e.stackSave();try{let r=e.PTR_SIZE,i=e.stackAlloc(2*r);e._OrtGetInputOutputCount(n,i,i+r)!==0&&wn("Can't get session input/output count.");let s=r===4?"i32":"i64";return[Number(e.getValue(i,s)),Number(e.getValue(i+r,s))]}finally{e.stackRestore(t)}},G_=(n,e)=>{let t=kn(),r=t.stackSave(),i=0;try{let s=t.PTR_SIZE,a=t.stackAlloc(2*s);t._OrtGetInputOutputMetadata(n,e,a,a+s)!==0&&wn("Can't get session input/output metadata.");let o=Number(t.getValue(a,"*"));i=Number(t.getValue(a+s,"*"));let l=t.HEAP32[i/4];if(l===0)return[o,0];let c=t.HEAPU32[i/4+1],d=[];for(let h=0;h<c;h++){let p=Number(t.getValue(i+8+h*s,"*"));d.push(p!==0?t.UTF8ToString(p):Number(t.getValue(i+8+(h+c)*s,"*")))}return[o,l,d]}finally{t.stackRestore(r),i!==0&&t._OrtFree(i)}},t0=n=>{let e=kn(),t=e._malloc(n.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,t),[t,n.byteLength]},mI=async(n,e)=>{let t,r,i=kn();Array.isArray(n)?[t,r]=n:n.buffer===i.HEAPU8.buffer?[t,r]=[n.byteOffset,n.byteLength]:[t,r]=t0(n);let s=0,a=0,o=0,l=[],c=[],d=[];try{if([a,l]=await UP(e),e?.externalData&&i.mountExternalData){let w=[];for(let C of e.externalData){let S=typeof C=="string"?C:C.path;w.push(tI(typeof C=="string"?C:C.data).then(M=>{i.mountExternalData(S,M)}))}await Promise.all(w)}for(let w of e?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof w!="string"){let C=w,S=C?.context,M=C?.gpuDevice,T=C?.deviceType,R=C?.powerPreference;S?i.currentContext=S:M?i.currentContext=await i.webnnCreateMLContext(M):i.currentContext=await i.webnnCreateMLContext({deviceType:T,powerPreference:R})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(t,r,a),i.webgpuOnCreateSession?.(s),s===0&&wn("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=VR(s),A=!!e?.enableGraphCapture,y=[],m=[],x=[],g=[],_=[];for(let w=0;w<h;w++){let[C,S,M]=G_(s,w);C===0&&wn("Can't get an input name."),c.push(C);let T=i.UTF8ToString(C);y.push(T),x.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M})}for(let w=0;w<p;w++){let[C,S,M]=G_(s,w+h);C===0&&wn("Can't get an output name."),d.push(C);let T=i.UTF8ToString(C);m.push(T),g.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M});{if(A&&e?.preferredOutputLocation===void 0){_.push("gpu-buffer");continue}let R=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[T]??"cpu",k=i.webnnIsGraphOutput;if(R==="cpu"&&k&&k(s,T)){_.push("ml-tensor-cpu-output");continue}if(R!=="cpu"&&R!=="cpu-pinned"&&R!=="gpu-buffer"&&R!=="ml-tensor")throw new Error(`Not supported preferred output location: ${R}.`);if(A&&R!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${R}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(R)}}let b=null;return _.some(w=>w==="gpu-buffer"||w==="ml-tensor"||w==="ml-tensor-cpu-output")&&(o=i._OrtCreateBinding(s),o===0&&wn("Can't create IO binding."),b={handle:o,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(w=>w==="ml-tensor-cpu-output"?"ml-tensor":w).map(w=>Iw(w))}),Il.set(s,[s,c,d,b,A,!1]),[s,y,m,x,g]}catch(h){throw c.forEach(p=>i._OrtFree(p)),d.forEach(p=>i._OrtFree(p)),o!==0&&i._OrtReleaseBinding(o)!==0&&wn("Can't release IO binding."),s!==0&&i._OrtReleaseSession(s)!==0&&wn("Can't release session."),h}finally{i._free(t),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&wn("Can't release session options."),l.forEach(h=>i._free(h)),i.unmountExternalData?.()}},gI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error(`cannot release session. invalid session id: ${n}`);let[r,i,s,a,o]=t;a&&(o&&e._OrtClearBoundOutputs(a.handle)!==0&&wn("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&wn("Can't release IO binding.")),e.jsepOnReleaseSession?.(n),e.webnnOnReleaseSession?.(n),e.webgpuOnReleaseSession?.(n),i.forEach(l=>e._OrtFree(l)),s.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(r)!==0&&wn("Can't release session."),Il.delete(n)},V_=async(n,e,t,r,i,s,a=!1)=>{if(!n){e.push(0);return}let o=kn(),l=o.PTR_SIZE,c=n[0],d=n[1],h=n[3],p=h,A,y;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let g=n[2].gpuBuffer;y=Pc(Qc(c),d);{let _=o.jsepRegisterBuffer;if(!_)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=_(r,s,g,y)}}else if(h==="ml-tensor"){let g=n[2].mlTensor;y=Pc(Qc(c),d);let _=o.webnnRegisterMLTensor;if(!_)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=_(r,g,Qc(c),d)}else{let g=n[2];if(Array.isArray(g)){y=l*g.length,A=o._malloc(y),t.push(A);for(let _=0;_<g.length;_++){if(typeof g[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);o.setValue(A+_*l,Gs(g[_],t),"*")}}else{let _=o.webnnIsGraphInput,b=o.webnnIsGraphOutput;if(c!=="string"&&_&&b){let w=o.UTF8ToString(i);if(_(r,w)||b(r,w)){let C=Qc(c);y=Pc(C,d),p="ml-tensor";let S=o.webnnCreateTemporaryTensor,M=o.webnnUploadTensor;if(!S||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let T=await S(r,C,d);M(T,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),A=T}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}}let m=o.stackSave(),x=o.stackAlloc(4*d.length);try{d.forEach((_,b)=>o.setValue(x+b*l,_,l===4?"i32":"i64"));let g=o._OrtCreateTensor(Qc(c),A,y,x,d.length,Iw(p));g===0&&wn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(g)}finally{o.stackRestore(m)}},yI=async(n,e,t,r,i,s)=>{let a=kn(),o=a.PTR_SIZE,l=Il.get(n);if(!l)throw new Error(`cannot run inference. invalid session id: ${n}`);let c=l[0],d=l[1],h=l[2],p=l[3],A=l[4],y=l[5],m=e.length,x=r.length,g=0,_=[],b=[],w=[],C=[],S=[],M=a.stackSave(),T=a.stackAlloc(m*o),R=a.stackAlloc(m*o),k=a.stackAlloc(x*o),$=a.stackAlloc(x*o);try{[g,_]=zP(s),Wc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)await V_(t[W],b,C,n,d[e[W]],e[W],A);for(let W=0;W<x;W++)await V_(i[W],w,C,n,h[r[W]],m+r[W],A);qc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)a.setValue(T+W*o,b[W],"*"),a.setValue(R+W*o,d[e[W]],"*");for(let W=0;W<x;W++)a.setValue(k+W*o,w[W],"*"),a.setValue($+W*o,h[r[W]],"*");if(p&&!y){let{handle:W,outputPreferredLocations:K,outputPreferredLocationsEncoded:Y}=p;if(d.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${d.length}).`);Wc("wasm bindInputsOutputs");for(let G=0;G<m;G++){let X=e[G];await a._OrtBindInput(W,d[X],b[G])!==0&&wn(`Can't bind input[${G}] for session=${n}.`)}for(let G=0;G<x;G++){let X=r[G];i[G]?.[3]?(S.push(w[G]),a._OrtBindOutput(W,h[X],w[G],0)!==0&&wn(`Can't bind pre-allocated output[${G}] for session=${n}.`)):a._OrtBindOutput(W,h[X],0,Y[X])!==0&&wn(`Can't bind output[${G}] to ${K[G]} for session=${n}.`)}qc("wasm bindInputsOutputs"),Il.set(n,[c,d,h,p,A,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let Q;p?Q=await a._OrtRunWithBinding(c,p.handle,x,k,g):Q=await a._OrtRun(c,R,T,m,$,x,k,g),Q!==0&&wn("failed to call OrtRun().");let H=[],B=[];Wc("wasm ProcessOutputTensor");for(let W=0;W<x;W++){let K=Number(a.getValue(k+W*o,"*"));if(K===w[W]||S.includes(w[W])){H.push(i[W]),K!==w[W]&&a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.");continue}let Y=a.stackSave(),G=a.stackAlloc(4*o),X=!1,re,L=0;try{a._OrtGetTensorData(K,G,G+o,G+2*o,G+3*o)!==0&&wn(`Can't access output tensor data on index ${W}.`);let V=o===4?"i32":"i64",oe=Number(a.getValue(G,V));L=a.getValue(G+o,"*");let Ae=a.getValue(G+o*2,"*"),ye=Number(a.getValue(G+o*3,V)),he=[];for(let Re=0;Re<ye;Re++)he.push(Number(a.getValue(Ae+Re*o,V)));a._OrtFree(Ae)!==0&&wn("Can't free memory for tensor dims.");let fe=he.reduce((Re,ve)=>Re*ve,1);re=po(oe);let Ee=p?.outputPreferredLocations[r[W]];if(re==="string"){if(Ee==="gpu-buffer"||Ee==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Re=[];for(let ve=0;ve<fe;ve++){let Ne=a.getValue(L+ve*o,"*"),rt=a.getValue(L+(ve+1)*o,"*"),Ge=ve===fe-1?void 0:rt-Ne;Re.push(a.UTF8ToString(Ne,Ge))}H.push([re,he,Re,"cpu"])}else if(Ee==="gpu-buffer"&&fe>0){let Re=a.jsepGetBuffer;if(!Re)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ve=Re(L),Ne=Pc(oe,fe);if(Ne===void 0||!ZC(re))throw new Error(`Unsupported data type: ${re}`);X=!0,H.push([re,he,{gpuBuffer:ve,download:a.jsepCreateDownloader(ve,Ne,re),dispose:()=>{a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.")}},"gpu-buffer"])}else if(Ee==="ml-tensor"&&fe>0){let Re=a.webnnEnsureTensor,ve=a.webnnIsGraphInputOutputTypeSupported;if(!Re||!ve)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Pc(oe,fe)===void 0||!eI(re))throw new Error(`Unsupported data type: ${re}`);if(!ve(n,re,!1))throw new Error(`preferredLocation "ml-tensor" for ${re} output is not supported by current WebNN Context.`);let Ne=await Re(n,L,oe,he,!1);X=!0,H.push([re,he,{mlTensor:Ne,download:a.webnnCreateMLTensorDownloader(L,re),dispose:()=>{a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K)}},"ml-tensor"])}else if(Ee==="ml-tensor-cpu-output"&&fe>0){let Re=a.webnnCreateMLTensorDownloader(L,re)(),ve=H.length;X=!0,B.push((async()=>{let Ne=[ve,await Re];return a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K),Ne})()),H.push([re,he,[],"cpu"])}else{let Re=Z0(re),ve=new Re(fe);new Uint8Array(ve.buffer,ve.byteOffset,ve.byteLength).set(a.HEAPU8.subarray(L,L+ve.byteLength)),H.push([re,he,ve,"cpu"])}}finally{a.stackRestore(Y),re==="string"&&L&&a._free(L),X||a._OrtReleaseTensor(K)}}p&&!A&&(a._OrtClearBoundOutputs(p.handle)!==0&&wn("Can't clear bound outputs."),Il.set(n,[c,d,h,p,A,!1]));for(let[W,K]of await Promise.all(B))H[W][2]=K;return qc("wasm ProcessOutputTensor"),H}finally{a.webnnOnRunEnd?.(c),a.stackRestore(M),b.forEach(Q=>a._OrtReleaseTensor(Q)),w.forEach(Q=>a._OrtReleaseTensor(Q)),C.forEach(Q=>a._free(Q)),g!==0&&a._OrtReleaseRunOptions(g),_.forEach(Q=>a._free(Q))}},xI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error("invalid session id");let r=t[0],i=e._OrtEndProfiling(r);i===0&&wn("Can't get an profile file name."),e._OrtFree(i)},vI=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),Sl,ts,Ed,qf,Yf,rg,H_,ig,Ic,Sc,HR,z4,U4,O4,$4,G4,V4,H4,j4=et(()=>{xs(),F4(),cu(),XC(),Sl=()=>!!Dn.wasm.proxy&&typeof document<"u",Ed=!1,qf=!1,Yf=!1,ig=new Map,Ic=(n,e)=>{let t=ig.get(n);t?t.push(e):ig.set(n,[e])},Sc=()=>{if(Ed||!qf||Yf||!ts)throw new Error("worker not ready")},HR=n=>{switch(n.data.type){case"init-wasm":Ed=!1,n.data.err?(Yf=!0,H_[1](n.data.err)):(qf=!0,H_[0]()),rg&&(URL.revokeObjectURL(rg),rg=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=ig.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},z4=async()=>{if(!qf){if(Ed)throw new Error("multiple calls to 'initWasm()' detected.");if(Yf)throw new Error("previous call to 'initWasm()' failed.");if(Ed=!0,Sl())return new Promise((n,e)=>{ts?.terminate(),LP().then(([t,r])=>{try{ts=r,ts.onerror=s=>e(s),ts.onmessage=HR,H_=[n,e];let i={type:"init-wasm",in:Dn};!i.in.wasm.wasmPaths&&(t||Cw)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href}),ts.postMessage(i),rg=t}catch(i){e(i)}},e)});try{await JC(Dn.wasm),await pI(Dn),qf=!0}catch(n){throw Yf=!0,n}finally{Ed=!1}}},U4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Dn}};ts.postMessage(r)});await AI(Dn,n)},O4=async n=>Sl()?(Sc(),new Promise((e,t)=>{Ic("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};ts.postMessage(r,[n.buffer])})):t0(n),$4=async(n,e)=>{if(Sl()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Sc(),new Promise((t,r)=>{Ic("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},s=[];n instanceof Uint8Array&&s.push(n.buffer),ts.postMessage(i,s)})}else return mI(n,e)},G4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("release",[e,t]);let r={type:"release",in:n};ts.postMessage(r)});gI(n)},V4=async(n,e,t,r,i,s)=>{if(Sl()){if(t.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Sc(),new Promise((a,o)=>{Ic("run",[a,o]);let l=t,c={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:s}};ts.postMessage(c,vI(l))})}else return yI(n,e,t,r,i,s)},H4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("end-profiling",[e,t]);let r={type:"end-profiling",in:n};ts.postMessage(r)});xI(n)}}),j_,jR,W4,tne=et(()=>{xs(),j4(),Lt(),YC(),OP(),j_=(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()}`)}},jR=n=>{switch(n[3]){case"cpu":return new ti(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!ZC(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:r,dispose:i}=n[2];return ti.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}case"ml-tensor":{let e=n[0];if(!eI(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:r,dispose:i}=n[2];return ti.fromMLTensor(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},W4=class{async fetchModelAndCopyToWasmMemory(n){return O4(await tI(n))}async loadModel(n,e){Fa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await $4(t,e),Zs()}async dispose(){return G4(this.sessionId)}async run(n,e,t){Fa();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],A=h[1],y=this.inputNames.indexOf(p);if(y===-1)throw new Error(`invalid input '${p}'`);r.push(A),i.push(y)});let s=[],a=[];Object.entries(e).forEach(h=>{let p=h[0],A=h[1],y=this.outputNames.indexOf(p);if(y===-1)throw new Error(`invalid output '${p}'`);s.push(A),a.push(y)});let o=r.map((h,p)=>j_(h,()=>`input "${this.inputNames[i[p]]}"`)),l=s.map((h,p)=>h?j_(h,()=>`output "${this.outputNames[a[p]]}"`):null),c=await V4(this.sessionId,i,o,a,l,t),d={};for(let h=0;h<c.length;h++)d[this.outputNames[a[h]]]=s[h]??jR(c[h]);return Zs(),d}startProfiling(){}endProfiling(){H4(this.sessionId)}}}),q4={};vh(q4,{OnnxruntimeWebAssemblyBackend:()=>Uw,initializeFlags:()=>zw,wasmBackend:()=>Y4});var zw,Uw,Y4,nne=et(()=>{xs(),j4(),tne(),zw=()=>{(typeof Dn.wasm.initTimeout!="number"||Dn.wasm.initTimeout<0)&&(Dn.wasm.initTimeout=0);let n=Dn.wasm.simd;if(typeof n!="boolean"&&n!==void 0&&n!=="fixed"&&n!=="relaxed"&&(Dn.wasm.simd=!1),typeof Dn.wasm.proxy!="boolean"&&(Dn.wasm.proxy=!1),typeof Dn.wasm.trace!="boolean"&&(Dn.wasm.trace=!1),typeof Dn.wasm.numThreads!="number"||!Number.isInteger(Dn.wasm.numThreads)||Dn.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Dn.wasm.numThreads=1;else{let e=typeof navigator>"u"?Uee("node:os").cpus().length:navigator.hardwareConcurrency;Dn.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Uw=class{async init(n){zw(),await z4(),await U4(n)}async createInferenceSessionHandler(n,e){let t=new W4;return await t.loadModel(n,e),t}},Y4=new Uw});xs();xs();xs();var rne="1.24.3";{let n=(nne(),Pp(q4)).wasmBackend;Bd("webgpu",n,5),Bd("webnn",n,5),Bd("cpu",n,10),Bd("wasm",n,10)}Object.defineProperty(Dn.versions,"web",{value:rne,enumerable:!0});class ine{constructor(e,t={}){this.config=e,this.options=t,this.policyModule=null,this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null,this.context=null,this.policyJointNames=(e.policy_joint_names??[]).slice(),this.numActions=this.policyJointNames.length,this.lastActions=new Float32Array(this.numActions),this.defaultJointPos=this.normalizeArray(e.default_joint_pos??[],this.numActions,0),this.encoderBias=this.normalizeArray(e.encoder_bias??[],this.numActions,0)}async init(e){this.context=e,this.policyModule=await this.buildPolicyModule(e),this.buildObservationGroups()}reset(e){this.lastActions.fill(0),this.policyModule?.reset();for(const t of Object.values(this.obsGroups))for(const r of t)r.reset&&r.reset(e);if(e){for(const[t,r]of Object.entries(this.historyConfig))if(r.steps>1){const i=this.buildFrame(this.obsGroups[t]??[],e),s=this.historyBuffers[t];for(let a=0;a<r.steps;a++)s.set(i,a*i.length)}}}update(e){this.policyModule?.update();for(const t of Object.values(this.obsGroups))for(const r of t)r.update&&r.update(e)}collectObservationsByKey(e){this.update(e);const t={};for(const[r,i]of Object.entries(this.obsGroups)){const s=this.historyConfig[r];if(s&&s.steps>1){const a=this.buildFrame(i,e),o=this.historyBuffers[r];for(let l=o.length-1;l>=a.length;l--)o[l]=o[l-a.length];o.set(a,0),t[r]=new Float32Array(o)}else t[r]=this.buildFrame(i,e)}return t}collectObservations(e){const t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];const r=Object.keys(t)[0];return r?t[r]:new Float32Array(0)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];const e=Object.keys(this.obsSizes)[0];return e?this.obsSizes[e]:0}getObservationLayout(){if(this.defaultObsKey&&this.obsLayouts[this.defaultObsKey])return this.obsLayouts[this.defaultObsKey].map(t=>({...t}));const e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(t=>({...t})):[]}getPolicyModuleContext(){return this.policyModule?.getContext()??{}}getPolicyModule(){return this.policyModule}getContext(){return this.context}getPolicyJointNames(){return this.policyJointNames.slice()}getNumActions(){return this.numActions}getDefaultJointPos(){return new Float32Array(this.defaultJointPos)}getEncoderBias(){return new Float32Array(this.encoderBias)}getLastActions(){return new Float32Array(this.lastActions)}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){const t=this.options.policyModules??{},r=this.config.policy_module,i=r?t[r]:t.default;if(r&&!i)throw new Error(`Unknown policy module: ${r}`);if(!i)return null;const s=new i(this.config);return await s.init(e),s}buildObservationGroups(){const e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;for(const[r,i]of Object.entries(t)){if(Array.isArray(i)){const s=i.map(a=>{const o=e[a.name];if(!o)throw new Error(`Unknown observation type: ${a.name}`);return new o(this,a)});this.registerGroup(r,s,i);continue}if(i&&typeof i=="object"){const s=i;if(Array.isArray(s.components)){const a=s.components.map(c=>{const d=e[c.name];if(!d)throw new Error(`Unknown observation type: ${c.name}`);const h={...c,history_steps:1};return new d(this,h)}),o=Math.max(1,Math.floor(s.history_steps??1)),l=!!s.interleaved;this.registerGroup(r,a,s.components,{steps:o,interleaved:l})}}}this.obsGroups.policy?this.defaultObsKey="policy":this.obsGroups.observation?this.defaultObsKey="observation":this.obsGroups.obs_history?this.defaultObsKey="obs_history":this.defaultObsKey=Object.keys(this.obsGroups)[0]??null}registerGroup(e,t,r,i){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((a,o)=>({name:r[o]?.name??`obs_${o}`,size:a.size}));const s=this.obsLayouts[e].reduce((a,o)=>a+o.size,0);i&&i.steps>1?(this.historyConfig[e]=i,this.historyBuffers[e]=new Float32Array(s*i.steps),this.obsSizes[e]=s*i.steps):this.obsSizes[e]=s}buildFrame(e,t){const r=e.reduce((a,o)=>a+o.size,0),i=new Float32Array(r);let s=0;for(const a of e){const o=a.compute(t),l=o instanceof Float32Array?o:Float32Array.from(o);if(l.length!==a.size)throw new Error(`Observation size mismatch: expected ${a.size}, got ${l.length}`);i.set(l,s),s+=l.length}return i}normalizeArray(e,t,r){const i=new Float32Array(t);for(let s=0;s<t;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}}Dn.wasm.proxy=!1;Dn.wasm.numThreads=1;class sne{constructor(e){if(!e?.path)throw new Error("OnnxModule requires a path.");this.config=e,this.session=null;const t=e.meta?.in_keys??["policy"],r=e.meta?.out_keys??["action"];this.configuredInKeys=t.map(i=>Array.isArray(i)?i.join(","):i),this.inKeys=[...this.configuredInKeys],this.outKeys=r.map(i=>Array.isArray(i)?i.join(","):i),this.isRecurrent=this.inKeys.includes("adapt_hx")}async init(){const e=await fetch(this.config.path);if(!e.ok)throw new Error(`Failed to fetch ONNX model: ${e.status}`);const t=await e.arrayBuffer();this.session=await qC.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"}),this.inferInputKeys(),this.isRecurrent=this.inKeys.includes("adapt_hx")}initInput(){const e={};return this.isRecurrent&&(e.is_init=new ti("bool",[!0],[1]),e.adapt_hx=new ti("float32",new Float32Array(128),[1,128])),this.inKeys.includes("time_step")&&(e.time_step=new ti("float32",new Float32Array([0]),[1,1])),e}async runInference(e){if(!this.session)throw new Error("OnnxModule not initialized.");const t={};for(let a=0;a<this.inKeys.length;a++){const o=this.inKeys[a],l=this.session.inputNames[a];if(!l||!e[o])throw new Error(`Missing ONNX input for key: ${o}`);t[l]=e[o]}const r=await this.session.run(t),i={};for(let a=0;a<this.outKeys.length;a++){const o=this.outKeys[a],l=this.session.outputNames[a];l&&r[l]&&(i[o]=r[l])}const s={};return this.isRecurrent&&i["next,adapt_hx"]&&(s.is_init=new ti("bool",[!1],[1]),s.adapt_hx=i["next,adapt_hx"]),[i,s]}inferInputKeys(){if(!this.session)return;const e=this.session.inputNames;if(e.length<=1){this.inKeys=[...this.configuredInKeys];return}if(this.configuredInKeys.length===e.length){this.inKeys=[...this.configuredInKeys];return}this.inKeys=e.map(t=>this.configuredInKeys.includes(t)?t:t==="obs"&&this.configuredInKeys.includes("policy")?"policy":t)}}class ane{constructor(e,t,r,i){this.mujoco=e,this.mjModel=t,this.mjData=r;const s=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(const a of i){const o=s.indexOf(a);if(o<0)throw new Error(`Joint "${a}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[o]),this.qvelAdr.push(t.jnt_dofadr[o]),this.jointIndices.push(o)}this.numActions=i.length,this.ctrlAdr=this.buildCtrlAdr()}build(){const e=this.mjData.qpos,t=this.mjData.qvel,r=new Float32Array(this.numActions),i=new Float32Array(this.numActions);for(let c=0;c<this.numActions;c++)r[c]=e[this.qposAdr[c]],i[c]=t[this.qvelAdr[c]];const s=new Float32Array([e[0],e[1],e[2]]),a=new Float32Array([e[3],e[4],e[5],e[6]]),o=new Float32Array([t[0],t[1],t[2]]),l=new Float32Array([t[3],t[4],t[5]]);return{jointPos:r,jointVel:i,rootPos:s,rootQuat:a,rootLinVel:o,rootAngVel:l}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}getControlMappingFor(e,t){if(!this.ctrlAdr)return null;const r=e.map(c=>new RegExp(`^(?:${c})$`)),i=c=>r.some(d=>d.test(c)),s=[],a=[],o=[],l=[];for(let c=0;c<t.length;c++)i(t[c])&&(s.push(this.ctrlAdr[c]),a.push(this.qposAdr[c]),o.push(this.qvelAdr[c]),l.push(c));return s.length===0?null:{ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l}}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;const e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let i=0;i<this.mjModel.nu;i++){const s=this.mjModel.actuator_trntype[i];e===void 0||s===e?t.push(this.mjModel.actuator_trnid[2*i]):t.push(-1)}const r=[];for(const i of this.jointIndices){const s=t.findIndex(a=>a===i);if(s<0)return null;r.push(s)}return r}getJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;let l=r.decode(t.subarray(a,o));!l&&s===0&&(l="floating_base_joint"),i.push(l)}return i}}class X4{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class one{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 lne extends X4{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 one(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class cne{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 une extends X4{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 cne(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class dne{constructor(e,t){this.terms=[];for(const r of e){const i=t[r.name];i&&this.terms.push(new i(r))}}onReset(e){for(const t of this.terms)t.onReset(e)}get size(){return this.terms.length}}class J4{constructor(e){this.config=e}}const hne={};class K4 extends J4{constructor(e){super(e),this.poseRange=e.params?.pose_range??{}}onReset(e){const{mjModel:t,mjData:r}=e;if(!t||!r)return;const i=this._findFreeJoint(t);if(i===-1)return;const s=t.jnt_qposadr[i],a=l=>{const c=this.poseRange[l];return c?c[0]+Math.random()*(c[1]-c[0]):0};r.qpos[s+0]+=a("x"),r.qpos[s+1]+=a("y"),r.qpos[s+2]+=a("z");const o=a("yaw");o!==0&&this._applyYawRotation(r.qpos,s+3,o)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}class fne extends J4{constructor(e){super(e),this.patchName=e.params?.patch_name??"spawn",this.fallback=new K4(e)}onReset(e){const{mjModel:t,mjData:r,terrainData:i}=e;if(!t||!r)return;const s=i?.flat_patches?.[this.patchName];if(!s||s.length===0){this.fallback.onReset(e);return}const a=this._findFreeJoint(t);if(a===-1)return;const o=t.jnt_qposadr[a],l=s[Math.floor(Math.random()*s.length)],c=r.qpos[o+2];r.qpos[o+0]=l[0],r.qpos[o+1]=l[1],r.qpos[o+2]=l[2]+c;const h=(this.config.params?.pose_range??{}).yaw??[-Math.PI,Math.PI],p=h[0]+Math.random()*(h[1]-h[0]);this._applyYawRotation(r.qpos,o+3,p)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}const pne={ResetRootStateUniform:K4,ResetRootStateFromFlatPatches:fne},Ane={...pne,...hne};function sg(n){return typeof n=="object"&&n!==null&&typeof n.setSelectedMotion=="function"}class Z4 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 WR(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 mne{constructor(e,t,r={}){this.render=()=>{if(Kn().updateDebugVisuals(),this.mjData&&$Z(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){F3(this.camera,this.lights);for(const[o,l]of this.lastSimState.bodies){const c=this.bodies[o];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion))}L3(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&hX({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}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:"."},i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&o.code}const{width:s,height:a}=this.getSize();this.scene=new s9,this.scene.name="scene",this.camera=new zr(45,s/a,.001,1e3),this.camera.name="PerspectiveCamera",this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new z7({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(s,a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=NN,this.renderer.outputColorSpace=ii,this.renderer.toneMapping=QN,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported("immersive-vr").then(o=>{o&&(this.vrButton=RC.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new O7(this.camera,this.renderer.domElement),this.controls.target.set(0,.2,0),this.controls.panSpeed=2,this.controls.zoomSpeed=1,this.controls.enableDamping=!0,this.controls.dampingFactor=.1,this.controls.screenSpacePanning=!0,this.controls.update(),this.renderer.setAnimationLoop(this.render),window.addEventListener("resize",this.onWindowResize),"ResizeObserver"in window?(this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),this.resizeObserver.observe(this.container)):this.resizeObserver=null,this.lastSimState={bodies:new Map,tendons:fX()},this.dynamicBodyIds=null,this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.loopPromise=null,this.running=!1,this.timestep=.001,this.decimation=1,this.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null,this.eventManager=null,this.terrainData=null,this.splatMesh=null,this.colliderMesh=null,this.cameraState={trackBodyId:null,prevBodyPos:null},this.sceneCacheManager=ww.getInstance(this.mujoco),this.resourceTracker=new GZ,this.memoryMonitor=new VZ}async loadEnvironment(e,t=null,r=null,i=null,s=null,a=null){this.terrainData=a,s&&s.length>0?this.eventManager=new dne(s,Ane):this.eventManager=null,await this.stop(),this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null);const o=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const l=performance.now()-o;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:l})}else this.memoryMonitor.logCacheOperation("miss",e),await this.sceneCacheManager.prepareForNewScene(),this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.resourceTracker.startTracking(this.mujoco),await bX(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);r&&(this.splatMesh=tB(r,this.scene),r.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(r.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.applyViewerConfig(i),this.running=!0,this.startLoop()}initializeCommands(){const e=Kn();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e,t){Kn().initialize(e,t)}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){const e=this.policyStateBuilder.build();this.policyRunner.reset(e)}}async setSelectedMotion(e){const t=Kn().getTerm("motion");if(!sg(t))return!1;const r=await t.setSelectedMotion(e);return r&&this.resetSimulation(),r}getSelectedMotionName(){const e=Kn().getTerm("motion");return sg(e)?e.getSelectedMotionName?.()??null:null}setReferenceVisible(e){const t=Kn().getTerm("motion");!sg(t)||typeof t.setReferenceVisible!="function"||t.setReferenceVisible(e)}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{const t=this.scene.getObjectByName("MuJoCo Root");t&&this.scene.remove(t);const r={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await vX(this.mujoco,e,r),!this.mjModel||!this.mjData)throw new Error("Failed to load MuJoCo model.");this.mujocoRoot=this.scene.getObjectByName("MuJoCo Root"),this.mujoco.mj_forward(this.mjModel,this.mjData),L3(this.mujoco,this.mjData,this.lights),F3(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds}),this.loadingScene=null})(),await this.loadingScene}async loadSceneWithOomRetry(e){try{await this.loadScene(e)}catch(t){if(!WR(t))throw t;this.loadingScene=null,await this.sceneCacheManager.clear();try{await this.loadScene(e)}catch(r){throw this.loadingScene=null,WR(r)?new Z4:r}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null),e&&(this.splatMesh=tB(e,this.scene),e.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&aP(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}async stop(){this.running=!1;const e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){const e=performance.now(),t=this.timestep*this.decimation;if(this.mjModel&&this.mjData){if(this.mujoco.mj_forward(this.mjModel,this.mjData),this.policyRunner&&this.policyStateBuilder){const s=this.policyStateBuilder.build(),a=this.policyRunner.collectObservationsByKey(s);if(await this.runOnnxInference(a),this.policyDebugCounter%60===0){const o="policy"in a?"policy":"observation"in a?"observation":Object.keys(a)[0],l=o?a[o]:null;l&&Array.from(l.slice(0,8))}this.policyDebugCounter+=1}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){const s=this.policyStateBuilder.build();if(this.terminationManager.evaluate(s).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){const o=this.policyStateBuilder.build();this.policyRunner.reset(o)}}Kn().update(t),Kn().updateDebugVisuals()}const r=(performance.now()-e)/1e3,i=Math.max(0,t-r);i>0&&await new Promise(s=>setTimeout(s,i*1e3))}this.loopPromise=null}async loadPolicyConfig(e){const t=this.policyConfigPath;this.policyConfigPath=e,this.policyRunner=null,this.policyStateBuilder=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null;const r=Kn();if(r.clear(),r.setResetCallback(()=>this.resetSimulation()),!!e&&!(!this.mjModel||!this.mjData)){e!==t&&this.resetSimulationState();try{const{config:i}=await this.fetchPolicyConfig(e);if(Array.isArray(i.motions)&&(i.motions=i.motions.map(o=>({...o,path:this.resolveAssetUrl(this.resolvePolicyAssetPath(e,o.path))}))),i.commands?.motion&&Array.isArray(i.motions)&&(i.commands.motion={...i.commands.motion,motions:i.motions}),this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),i.commands&&typeof i.commands=="object"){this.initializeCommandsFromConfig(i.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,bodies:this.bodies,mujocoRoot:this.mujocoRoot,requestReset:()=>this.resetSimulation()}),Kn().resetTerms();const o=Kn().getTerm("motion");sg(o)&&(await o.setSelectedMotion(i.motions?.find(l=>l.default)?.name??i.motions?.[0]?.name??null),o.setReferenceVisible?.(!0)),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()}if(!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new ine(i,{policyModules:{tracking:lne,locomotion:une},observations:Mee});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),this.policyRunner=s,this.policyStateBuilder=new ane(this.mujoco,this.mjModel,this.mjData,s.getPolicyJointNames());const a=this.policyStateBuilder.build();if(this.policyRunner.reset(a),this.policyControl=this.buildPolicyControl(i,s,this.policyStateBuilder),i.terminations&&Object.keys(i.terminations).length>0&&(this.terminationManager=new Tee(i.terminations,Pee)),i.onnx?.path){const o=this.resolvePolicyAssetPath(e,i.onnx.path),l=this.resolveAssetUrl(o),c={...i.onnx,path:l},d=new sne(c);await d.init(),this.onnxModule=d,this.onnxInputDict=d.initInput()}}catch{}}}async fetchPolicyConfig(e){const t=this.resolveAssetUrl(e),r=await fetch(t,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch policy config: ${r.status}`);return{config:await r.json(),resolvedUrl:t}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;const t=(this.baseUrl||"/").replace(/\/+$/,"/"),r=new URL(t,window.location.origin+"/").toString();return new URL(e.replace(/^\/+/,""),r).toString()}resolvePolicyAssetPath(e,t){const r=e.replace(/\\/g,"/"),i=r.lastIndexOf("/");return i>=0?`${r.slice(0,i+1)}${t}`.replace(/\/+/g,"/"):t}buildPolicyControl(e,t,r){const i=t.getPolicyJointNames(),s=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(c,d,h,p,A,y,m,x)=>{const g=h.qposAdr.length,_=h.actionIndices.map(Q=>i[Q]),b=this.normalizeControlArray(p,g,1,_),w=this.normalizeControlArray(A,g,0,_),C=x?t.getDefaultJointPos():new Float32Array(i.length),S=new Float32Array(g);for(let Q=0;Q<g;Q++)S[Q]=C[h.actionIndices[Q]];const M=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(i.length),T=new Float32Array(g);for(let Q=0;Q<g;Q++)T[Q]=M[h.actionIndices[Q]]??0;const R=this.normalizeControlArray(y,g,0,_),k=this.normalizeControlArray(m,g,0,_),$=h.ctrlAdr.map(Q=>Q<0||!this.mjModel?!1:this.mjModel.actuator_biastype[Q]===s);return $.some(Boolean),$.some(Q=>!Q),{controlType:d,ctrlAdr:h.ctrlAdr,qposAdr:h.qposAdr,qvelAdr:h.qvelAdr,actionIndices:h.actionIndices,actionScale:b,actionOffset:w,defaultJointPos:S,encoderBias:T,positionActuator:$,kp:R,kd:k}},o=e.actions;if(!o||Object.keys(o).length===0){const c=e.control_type??"joint_position";if(c!=="joint_position"&&c!=="torque")return null;const d=r.getControlMapping();if(!d)return null;const h={...d,actionIndices:Array.from({length:d.qposAdr.length},(p,A)=>A)};return[a("legacy",c,h,e.action_scale,void 0,e.stiffness,e.damping,!0)]}const l=[];for(const[c,d]of Object.entries(o)){const h=d.type??"joint_position";if(h!=="joint_position"&&h!=="torque")continue;const p=d.actuator_names??[".*"],A=p.length===1&&p[0]===".*";let y;if(A){const x=r.getControlMapping();if(!x)continue;y={...x,actionIndices:Array.from({length:x.qposAdr.length},(g,_)=>_)}}else if(y=r.getControlMappingFor(p,i),!y)continue;const m=d.use_default_offset!==void 0?d.use_default_offset:h==="joint_position";l.push(a(c,h,y,d.scale,d.offset,d.stiffness,d.damping,m))}return l.length===0?null:l}normalizeControlArray(e,t,r,i){const s=new Float32Array(t);if(s.fill(r),typeof e=="number")return s.fill(e),s;if(Array.isArray(e)){for(let a=0;a<t;a++)s[a]=typeof e[a]=="number"?e[a]:r;return s}if(e!==null&&typeof e=="object"&&i){for(const[a,o]of Object.entries(e)){const l=i.indexOf(a);l>=0&&l<t&&(s[l]=o)}return s}return s}resetSimulationState(){!this.mjModel||!this.mjData||(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),Kn().resetTerms(),this.onnxModule&&(this.onnxInputDict=this.onnxModule.initInput()),this.onnxTimeStep=0,this.mujoco.mj_forward(this.mjModel,this.mjData),this.lastSimState.bodies.clear(),this.updateCachedState())}executeSimulationSteps(){if(!(!this.mjModel||!this.mjData)){this.applyDragForces();for(let e=0;e<this.decimation;e++)this.applyPolicyControl(),this.mujoco.mj_step(this.mjModel,this.mjData)}}applyPolicyControl(){if(!this.policyControl||!this.mjData)return;const e=this.mjData.ctrl;e.fill(0);const t=this.policyRunner?.getLastActions()??new Float32Array(0);for(const r of this.policyControl){const{controlType:i,ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l,actionScale:c,actionOffset:d,defaultJointPos:h,encoderBias:p,positionActuator:A,kp:y,kd:m}=r,x=s.length;if(i==="joint_position")for(let g=0;g<x;g++){const _=s[g];if(_<0)continue;const b=t[l[g]]??0,w=h[g]+d[g]+c[g]*b-p[g];if(A[g])e[_]=w;else{const C=this.mjData.qpos[a[g]],S=this.mjData.qvel[o[g]];e[_]=y[g]*(w-C)+m[g]*(0-S)}}else if(i==="torque")for(let g=0;g<x;g++){const _=s[g];_>=0&&(e[_]=c[g]*(t[l[g]]??0))}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||(this.onnxInputDict=this.onnxModule.initInput());const t={...this.onnxInputDict};this.onnxModule.inKeys.includes("time_step")&&(t.time_step=new ti("float32",new Float32Array([this.onnxTimeStep]),[1,1]));for(const[d,h]of Object.entries(e))t[d]=new ti("float32",h,[1,h.length]);for(const d of this.onnxModule.inKeys)if(!t[d])return;const[r,i]=await this.onnxModule.runInference(t);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i}),this.onnxModule.inKeys.includes("time_step")&&(this.onnxTimeStep+=1);const s=this.onnxModule.outKeys[0],a=r.action??(s?r[s]:null)??r.policy??null;if(!a)return;const o=a.data,l=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&l.length!==c)return;this.policyRunner.setLastActions(l)}catch{}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let p=0;p<this.mjData.xfrc_applied.length;p++)this.mjData.xfrc_applied[p]=0;const e=this.dragStateManager.physicsObject;if(!e||!("bodyID"in e)||typeof e.bodyID!="number"||e.bodyID<=0)return;const t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(jc(this.mjData.xpos,p,this.bodies[p].position),pp(this.mjData.xquat,p,this.bodies[p].quaternion),this.bodies[p].updateWorldMatrix(!0,!1));this.dragStateManager.update();const r=this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale),i=P3(r),s=this.dragStateManager.worldHit.clone(),a=P3(s),o=new ue(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),l=new ue(a.x-o.x,a.y-o.y,a.z-o.z),c=new ue(i.x,i.y,i.z),d=new ue().crossVectors(l,c),h=t*6;this.mjData.xfrc_applied[h+0]=i.x,this.mjData.xfrc_applied[h+1]=i.y,this.mjData.xfrc_applied[h+2]=i.z,this.mjData.xfrc_applied[h+3]=d.x,this.mjData.xfrc_applied[h+4]=d.y,this.mjData.xfrc_applied[h+5]=d.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++)if(!(e&&!e.has(t))&&this.bodies[t]){this.lastSimState.bodies.has(t)||this.lastSimState.bodies.set(t,{position:new ue,quaternion:new Cn});const r=this.lastSimState.bodies.get(t);jc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&dX(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=OZ(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){const t=new Set;for(let r=1;r<e.nbody;r++){let i=r;for(;i>0;){if(e.body_jntnum[i]>0){t.add(r);break}i=e.body_parentid[i]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;const r=this.bodies[t];r&&(jc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion))}}dispose(){this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.dragStateManager&&(this.dragStateManager.dispose(),this.dragStateManager=null),this.mjData=null,this.mjModel=null,window.removeEventListener("resize",this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.controls.dispose(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.vrButton?.parentElement&&(this.vrButton.parentElement.removeChild(this.vrButton),this.vrButton=null),this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.lastSimState.bodies.clear()}disposeThreeJSResources(){if(this.scene)for(this.scene.traverse(e=>{"geometry"in e&&e.geometry&&e.geometry.dispose(),"material"in e&&e.material&&(Array.isArray(e.material)?e.material.forEach(t=>this.disposeMaterial(t)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),e.dispose()}getSize(){const e=this.container.clientWidth||window.innerWidth,t=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,t)}}async restoreFromCache(e){const t=this.sceneCacheManager.get(e);if(!t)throw new Error(`Scene ${e} not found in cache`);const r=this.scene.getObjectByName("MuJoCo Root");r&&this.scene.remove(r),this.mjModel=t.mjModel,this.mjData=t.mjData,this.bodies=t.bodies,this.lights=t.lights,this.mujocoRoot=t.mujocoRoot,this.scene.add(this.mujocoRoot),this.scene.background=t.skybox,this.mujoco.mj_forward(this.mjModel,this.mjData),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds})}async captureAndCacheResources(e){const t=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot)return;const r=this.resourceTracker.estimateSceneMemory({mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,meshes:{},mujocoRoot:this.mujocoRoot});await this.sceneCacheManager.set(e,{scenePath:e,lastAccessed:Date.now(),loadedAt:Date.now(),mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,lights:this.lights,meshes:{},mujocoRoot:this.mujocoRoot,skybox:this.scene.background instanceof ph?this.scene.background:null,fsFiles:t,estimatedMemoryBytes:r});const i=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation("load",e,{memoryMB:r/1048576,totalScenes:i.totalScenes,totalMemoryMB:i.totalMemoryBytes/1048576})}}const ag="mjswan_oom_reload_scene",gne=({scenePath:n,baseUrl:e,policyConfigPath:t,splatConfig:r,cameraConfig:i,eventsConfig:s,terrainData:a,selectedMotion:o,showReferenceMotion:l=!0,onStatusChange:c,onError:d,onReady:h,onRuntimeReady:p})=>{const A=U.useRef(null),y=U.useRef(null),m=U.useRef(null),x=U.useRef(r);x.current=r;const g=U.useRef(o);g.current=o;const _=U.useRef(l);return _.current=l,U.useEffect(()=>{let b=!1;const w=S=>{c?.(S)};return(async()=>{if(w("Loading MuJoCo..."),!m.current){const T=await RV(()=>import("./mujoco-C2r0m8kN.js"),[]);m.current=await T.default()}if(b)return;const S=A.current;if(!S)throw new Error("Failed to find viewer container.");const M=m.current;if(!M)throw new Error("MuJoCo not loaded.");y.current||(y.current=new mne(M,S,{baseUrl:e}),p?.(y.current)),w("Loading scene assets..."),await y.current.loadEnvironment(n,t??null,x.current??null,i??null,s??null,a??null),await y.current.setSelectedMotion(g.current??null),y.current.setReferenceVisible(_.current),!b&&(sessionStorage.removeItem(ag),w("Running simulation"),h?.())})().catch(S=>{if(!b){if(S instanceof Z4){if(sessionStorage.getItem(ag)!==n){sessionStorage.setItem(ag,n),window.location.reload();return}sessionStorage.removeItem(ag)}d?.(S instanceof Error?S:new Error(String(S))),w("Failed to load scene")}}),()=>{b=!0,y.current?.dispose(),y.current=null}},[n,e,t,i,s,a,c,d,h]),U.useEffect(()=>{y.current&&y.current.setSelectedMotion(o??null)},[o]),U.useEffect(()=>{y.current?.setReferenceVisible(l)},[l]),j.jsx("div",{ref:A,className:"viewer"})};var yne={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};const ey=(n,e,t,r)=>{const i=U.forwardRef(({color:s="currentColor",size:a=24,stroke:o=2,title:l,className:c,children:d,...h},p)=>U.createElement("svg",{ref:p,...yne[n],width:a,height:a,className:["tabler-icon",`tabler-icon-${e}`,c].join(" "),strokeWidth:o,stroke:s,...h},[l&&U.createElement("title",{key:"svg-title"},l),...r.map(([A,y])=>U.createElement(A,y)),...Array.isArray(d)?d:[d]]));return i.displayName=`${t}`,i};const xne=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],ez=ey("outline","chevron-down","ChevronDown",xne);const vne=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],_ne=ey("outline","chevron-up","ChevronUp",vne);const bne=[["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"}]],wne=ey("outline","refresh","Refresh",bne);const Ene=[["path",{d:"M18 6l-12 12",key:"svg-0"}],["path",{d:"M6 6l12 12",key:"svg-1"}]],Cne=ey("outline","x","X",Ene),qR="0.5.7",YR=[{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"}],Ine={move:"touchmove",end:"touchend"},Sne={move:"mousemove",end:"mouseup"};function Bne(n){return n.type==="touchmove"}function Mne(n){return n.type==="mousemove"}const jp=On.createContext(null);function Ao({children:n,width:e,visible:t=!0,onVisibleChange:r,hiddenButtonTooltip:i}){const s=On.useRef(null),[a,{toggle:o}]=s0(!0),[l,c]=On.useState(800),d=On.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),h=On.useRef({}),p=(x,g,_)=>Math.abs(x+g/2)<Math.abs(x-_+g/2)?x:x-_,A=15;function y(x,g){const _=s.current;if(_===null)return[x,g];const b=_.parentElement;if(b===null)return[x,g];let w=x,C=g;return w=Math.min(w,b.clientWidth-_.clientWidth-A),w=Math.max(w,A),C=Math.min(C,b.clientHeight-_.clientHeight-A),C=Math.max(C,A),_.style.top=`${C.toString()}px`,_.style.left=`${w.toString()}px`,[p(w,_.clientWidth,b.clientWidth),p(C,_.clientHeight,b.clientHeight)]}On.useEffect(()=>{const x=s.current;if(x===null)return;const g=x.parentElement;if(g===null)return;const _=new ResizeObserver(()=>{h.current.x===void 0&&(h.current.x=p(x.offsetLeft,x.clientWidth,g.clientWidth)),h.current.y===void 0&&(h.current.y=p(x.offsetTop,x.clientHeight,g.clientHeight));const b=g.clientHeight-A*2;l!==b&&c(b);let w=h.current.x,C=h.current.y;for(;w<0;)w+=g.clientWidth;for(;C<0;)C+=g.clientHeight;y(w,C)});return _.observe(x),_.observe(g),()=>{_.disconnect()}});const m=x=>{const g=d.current,_=s.current;if(!_)return;x.type=="touchstart"?(x=x,g.startClientX=x.touches[0].clientX,g.startClientY=x.touches[0].clientY):(x=x,g.startClientX=x.clientX,g.startClientY=x.clientY),g.startPosX=_.offsetLeft,g.startPosY=_.offsetTop;const b=x.type=="touchstart"?Ine:Sne;function w(C){let S=0,M=0;if(Bne(C)?(C=C,S=C.touches[0].clientX-g.startClientX,M=C.touches[0].clientY-g.startClientY):Mne(C)&&(C=C,S=C.clientX-g.startClientX,M=C.clientY-g.startClientY),Math.abs(S)<=3&&Math.abs(M)<=3)return;g.dragging=!0;const T=g.startPosX+S,R=g.startPosY+M;[h.current.x,h.current.y]=y(T,R)}window.addEventListener(b.move,w),window.addEventListener(b.end,()=>{x.type=="touchstart"&&(g.dragging=!1),window.removeEventListener(b.move,w)},{once:!0})};if(!t){const x=j.jsx(Je,{component:"button","aria-label":i??"Show controls",onClick:()=>r?.(!0),style:{width:"0.85rem",height:"0.85rem",minWidth:"0.85rem",minHeight:"0.85rem",display:"block",padding:0,border:"none",borderRadius:"9999px",background:"rgba(255, 255, 255, 0.82)",boxShadow:"0 0 0 1px rgba(0, 0, 0, 0.14), 0 2px 8px rgba(0, 0, 0, 0.18)",cursor:"pointer"}});return j.jsx(Je,{style:{zIndex:10,position:"absolute",top:"1em",right:"1em"},children:i?j.jsx(Pl,{label:i,children:j.jsx(Je,{children:x})}):x})}return j.jsx(jp.Provider,{value:{wrapperRef:s,expanded:a,width:e,maxHeight:l,toggleExpanded:o,dragHandler:m,dragInfo:d},children:j.jsx(Xc,{radius:"xs",shadow:"0.1em 0 1em 0 rgba(0,0,0,0.1)",style:{boxSizing:"border-box",width:e,zIndex:10,position:"absolute",top:"1em",right:"1em",margin:0,"& .expandIcon":{transform:"rotate(0)"},overflow:"hidden"},ref:s,children:n})})}Ao.Handle=function({children:e}){const t=On.useContext(jp);return j.jsx(j.Fragment,{children:j.jsx(Je,{style:{borderRadius:"0.2em 0.2em 0 0",lineHeight:"1.5em",cursor:"pointer",position:"relative",fontWeight:400,userSelect:"none",display:"flex",alignItems:"center",padding:"0 0.75em",height:"2.75em"},onClick:()=>{const r=t.dragInfo.current;if(r.dragging){r.dragging=!1;return}t.toggleExpanded()},onTouchStart:r=>{t.dragHandler(r)},onMouseDown:r=>{t.dragHandler(r)},children:e})})};Ao.Contents=function({children:e}){const t=On.useContext(jp);return j.jsxs(Mg,{in:t.expanded,children:[j.jsx(Dd,{mx:"xs"}),j.jsx(su.Autosize,{mah:t.maxHeight,children:j.jsx(Je,{style:{width:t.width},children:e})})]})};Ao.HideWhenCollapsed=function({children:e}){return On.useContext(jp)?.expanded??!0?e:null};Ao.HideWhenExpanded=function({children:e}){return On.useContext(jp)?.expanded??!0?null:e};function og({id:n,label:e,children:t}){return j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsxs(EE,{align:"center",children:[j.jsx(Je,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:j.jsx("label",{htmlFor:n,children:e})})}),j.jsx(Je,{style:{flexGrow:1},children:t})]})})}function tz({label:n,expandByDefault:e=!0,children:t}){const[r,{toggle:i}]=s0(e),s=r?_ne:ez;return j.jsxs(Xc,{withBorder:!0,style:{borderWidth:"1px",position:"relative",marginLeft:"var(--mantine-spacing-xs)",marginRight:"var(--mantine-spacing-xs)",marginTop:"var(--mantine-spacing-xs)",marginBottom:"var(--mantine-spacing-xs)",paddingBottom:"calc(var(--mantine-spacing-xs) - 0.5em)"},children:[j.jsxs(Xc,{onClick:i,style:{fontSize:"0.875em",position:"absolute",padding:"0 0.375em",top:0,left:"0.375em",transform:"translateY(-50%)",userSelect:"none",fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center"},children:[n,j.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),j.jsx(Mg,{in:r,children:j.jsx(Je,{pt:"1em",children:t})}),j.jsx(Mg,{in:!r,children:j.jsx(Je,{p:"xs"})})]})}const nz={fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"4.5em",flexShrink:0},Tne={root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}},Rne={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 W_({axis:n,value:e,min:t=-1/0,max:r=1/0,step:i,onChange:s}){const a=U.useRef(null),o=U.useRef(null);U.useEffect(()=>{const y=a.current;y&&document.activeElement!==y&&(y.value=e.toFixed(2))},[e]);const l=y=>Math.max(t,Math.min(r,parseFloat((Math.round(y/i)*i).toFixed(10)))),c=y=>{y.preventDefault(),y.currentTarget.setPointerCapture(y.pointerId),o.current={startY:y.clientY,startValue:e,moved:!1}},d=y=>{if(!o.current||!(y.buttons&1))return;const m=o.current.startY-y.clientY;if(Math.abs(m)>3&&(o.current.moved=!0),!o.current.moved)return;const x=l(o.current.startValue+m*i);s(x),a.current&&(a.current.value=x.toFixed(2))},h=()=>{if(o.current&&!o.current.moved){const y=a.current;y&&(y.focus(),y.select())}o.current=null},p=y=>{const m=parseFloat(y.target.value);isNaN(m)||s(l(m)),y.target.value=e.toFixed(2)},A=y=>{y.key==="Enter"&&y.currentTarget.blur(),y.key==="Escape"&&(a.current&&(a.current.value=e.toFixed(2)),a.current?.blur())};return j.jsxs(Je,{style:{display:"flex",alignItems:"center",gap:"0.25em",flex:1},children:[j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,letterSpacing:"-0.75px",flexShrink:0},children:n}),j.jsx("input",{ref:a,size:1,defaultValue:e.toFixed(2),onPointerDown:c,onPointerMove:d,onPointerUp:h,onBlur:p,onKeyDown:A,onFocus:y=>y.currentTarget.style.outline="2px solid var(--mantine-color-blue-5)",onBlurCapture:y=>y.currentTarget.style.outline="none",style:Rne})]})}function XR({label:n,x:e,y:t,z:r,step:i,xLabel:s="X",yLabel:a="Y",zLabel:o="Z",onX:l,onY:c,onZ:d}){return j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Xs,{c:"dimmed",style:nz,children:n}),j.jsx(W_,{axis:s,value:e,step:i,onChange:l}),j.jsx(W_,{axis:a,value:t,step:i,onChange:c}),j.jsx(W_,{axis:o,value:r,step:i,onChange:d})]})}function Dne({scale:n,xOffset:e,yOffset:t,zOffset:r,roll:i,pitch:s,yaw:a,onCalibrate:o}){const[l,c]=U.useState(n),[d,h]=U.useState(e),[p,A]=U.useState(t),[y,m]=U.useState(r),[x,g]=U.useState(i),[_,b]=U.useState(s),[w,C]=U.useState(a);U.useEffect(()=>{c(n)},[n]),U.useEffect(()=>{h(e)},[e]),U.useEffect(()=>{A(t)},[t]),U.useEffect(()=>{m(r)},[r]),U.useEffect(()=>{g(i)},[i]),U.useEffect(()=>{b(s)},[s]),U.useEffect(()=>{C(a)},[a]);const S=(M,T,R,k,$,Q,H)=>o(M,T,R,k,$,Q,H);return j.jsxs(tz,{label:"Control",expandByDefault:!0,children:[j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Xs,{c:"dimmed",style:nz,children:"Scale"}),j.jsx(Je,{style:{flex:1},children:j.jsx(P0,{value:l,onChange:M=>{c(M),S(M,d,p,y,x,_,w)},min:.1,max:5,step:.05,size:"xs",label:M=>M.toFixed(2),styles:Tne})})]}),j.jsx(XR,{label:"Position",x:d,y:p,z:y,step:.05,onX:M=>{h(M),S(l,M,p,y,x,_,w)},onY:M=>{A(M),S(l,d,M,y,x,_,w)},onZ:M=>{m(M),S(l,d,p,M,x,_,w)}}),j.jsx(XR,{label:"Rotation",x,y:_,z:w,step:.5,xLabel:"R",yLabel:"P",zLabel:"Y",onX:M=>{g(M),S(l,d,p,y,M,_,w)},onY:M=>{b(M),S(l,d,p,y,x,M,w)},onZ:M=>{C(M),S(l,d,p,y,x,_,M)}})]})}function kne(n){return n instanceof HTMLElement?n.isContentEditable?!0:n.closest('input, textarea, select, [contenteditable], [role="textbox"], [role="searchbox"], [role="combobox"]')!==null:!1}function Nne(n){return n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Qne({command:n,value:e,onChange:t,disabled:r,enabledWhenValue:i}){const s=n.config,a=s.enabled_when!==void 0&&(i??0)<.5,o=r||a;return j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:s.label}),j.jsx(Je,{style:{width:"50%"},children:j.jsx(P0,{value:e,onChange:l=>t(n.id,l),min:s.min,max:s.max,step:s.step,size:"xs",disabled:o,styles:{root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}}})})]})}function Pne({command:n,value:e,onChange:t,disabled:r}){const i=n.config;return j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsx(Gl,{label:i.label,checked:e>=.5,onChange:s=>t(n.id,s.currentTarget.checked?1:0),size:"xs",disabled:r})})}function Lne(n){const{visible:e,onVisibleChange:t,projects:r,projectValue:i,projectLabel:s,onProjectChange:a,scenes:o,sceneValue:l,onSceneChange:c,splats:d,splatSection:h=!1,splatValue:p,onSplatChange:A,splatConfig:y,onCalibrateSplat:m,onSplatUrlLoad:x,policies:g,policyValue:_,onPolicyChange:b,motions:w,motionValue:C,onMotionChange:S,showReferenceMotion:M,onShowReferenceMotionChange:T,commandsEnabled:R=!1,onReset:k}=n,[$,{open:Q,close:H}]=s0(!1),[B,W]=U.useState(""),[K,Y]=U.useState(null),[G,X]=U.useState(!1),re=U.useCallback(async ve=>{if(ve.key!=="Enter"||!x)return;const Ne=B.trim();if(d.some(Ge=>Ge.label===Ne||Ge.value===Ne))return;if(!Ne.toLowerCase().endsWith(".spz")){Y("URL must end with .spz");return}await x(Ne)?(Y(null),X(!0)):Y("File not found at the specified URL")},[x,B,d]),[L,V]=U.useState([]),[oe,Ae]=U.useState([]),[ye,he]=U.useState({});U.useEffect(()=>{const ve=Kn(),Ne=()=>{V(ve.getCommands()),Ae(ve.getCommandGroups()),he(ve.getValues())};return Ne(),ve.addEventListener(Ne),()=>{ve.removeEventListener(Ne)}},[]),U.useEffect(()=>{const ve=Ne=>{if(Ne.defaultPrevented||Ne.repeat||Ne.altKey||Ne.ctrlKey||Ne.metaKey||Ne.key.toLowerCase()!=="c")return;const rt=Ne.target instanceof Element?Ne.target:document.activeElement;kne(rt)||(Ne.preventDefault(),t(!e))};return window.addEventListener("keydown",ve),()=>{window.removeEventListener("keydown",ve)}},[e,t]);const fe=U.useCallback((ve,Ne)=>{Kn().setValue(ve,Ne),he(Ge=>({...Ge,[ve]:Ne}))},[]),Ee=U.useCallback(()=>{Kn().triggerButton("_system:reset"),k&&k()},[k]),Re=ve=>L.filter(Ne=>Ne.groupName===ve&&(Ne.config.type==="slider"||Ne.config.type==="checkbox"));return!r.length&&!o.length&&!g.length?null:j.jsxs(j.Fragment,{children:[j.jsx(aa,{opened:$,onClose:H,size:"lg",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:j.jsxs(sC,{gap:"md",align:"center",children:[j.jsx(Pg,{src:"./logo-color.svg",style:{width:"8em",height:"auto"}}),j.jsx(Xs,{size:"xl",fw:700,children:"powered by mjswan"}),j.jsxs(Xs,{size:"sm",c:"dimmed",children:["version ",qR]}),j.jsx(Xs,{size:"sm",c:"dimmed",children:"MuJoco Simulation on Web Assembly with Neural netwroks"}),j.jsx(Dd,{w:"100%"}),j.jsxs(Je,{children:[j.jsx(up,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"})," • ",j.jsx(up,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]}),j.jsx(Dd,{w:"100%"}),j.jsxs(Je,{style:{textAlign:"left",maxHeight:"120px",overflowY:"auto",lineHeight:"1",fontSize:"0.8rem",opacity:"0.75"},px:"md",children:["Thanks to our contributors! ",j.jsx("br",{}),YR.map((ve,Ne)=>j.jsxs("span",{children:[j.jsx(up,{href:ve.html_url,target:"_blank",style:{textDecoration:"none",fontSize:"0.75rem"},children:ve.login}),Ne<YR.length-1&&", "]},ve.login))]})]})}),j.jsxs(Ao,{width:"20em",visible:e,onVisibleChange:t,hiddenButtonTooltip:"Show controls (C)",children:[j.jsxs(Ao.Handle,{children:[j.jsx(Pl,{label:`mjswan ${qR}`,children:j.jsx(Je,{component:"a",onClick:ve=>{ve.stopPropagation(),Q()},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{position:"absolute",cursor:"pointer",display:"flex",top:"0.8em",left:"0.9em"},children:j.jsx(Pg,{src:"./logo.svg",style:{width:"1.2em",height:"auto"}})})}),j.jsx("div",{style:{width:"1.1em"}}),j.jsx(Ao.HideWhenCollapsed,{children:j.jsxs(Je,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[j.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),r.length>1&&j.jsxs(pi,{position:"bottom-start",offset:5,children:[j.jsx(pi.Target,{children:j.jsx(Je,{onClick:ve=>ve.stopPropagation(),onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center",flexShrink:0},children:j.jsx(ez,{size:16})})}),j.jsx(pi.Dropdown,{onClick:ve=>ve.stopPropagation(),children:r.map(ve=>j.jsx(pi.Item,{onClick:Ne=>{Ne.stopPropagation(),a(ve.value)},style:{fontWeight:ve.value===i?600:400,backgroundColor:ve.value===i?"rgba(34, 139, 230, 0.1)":void 0},children:ve.label},ve.value))})]})]})}),j.jsx(Ao.HideWhenExpanded,{children:j.jsx(Je,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:s})}),j.jsx(Pl,{label:"Hide controls (C)",children:j.jsx(au,{variant:"subtle",color:"gray",size:"sm","aria-label":"Hide controls",onClick:ve=>{ve.stopPropagation(),t(!1)},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),children:j.jsx(Cne,{size:14})})})]}),j.jsx(Ao.Contents,{children:j.jsxs(Je,{pt:"0.375em",children:[o.length>0&&j.jsx(og,{id:"scene-select",label:"Scene",children:j.jsx(zc,{id:"scene-select",placeholder:"Select scene",data:o,value:l,onChange:c,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),(d.length>0||h)&&j.jsx(og,{id:"splat-select",label:"Splat",children:j.jsx(Pl,{label:K??"",color:"red",position:"bottom",opened:K!==null,withArrow:!0,children:j.jsx(zc,{id:"splat-select",placeholder:x!==void 0?"Select splat or paste .spz URL":"Select splat",data:d,value:p,onChange:ve=>{A(ve),Y(null),X(!1)},searchable:x!==void 0,searchValue:B,onSearchChange:ve=>{W(ve),ve&&Y(null)},onKeyDown:re,size:"xs",radius:"xs",clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})})}),(y?.control&&p!==null||G)&&m&&j.jsx(Dne,{scale:y?.scale??1,xOffset:y?.xOffset??0,yOffset:y?.yOffset??0,zOffset:y?.zOffset??0,roll:y?.roll??0,pitch:y?.pitch??0,yaw:y?.yaw??0,onCalibrate:m}),g.length>0&&j.jsx(og,{id:"policy-select",label:"Policy",children:j.jsx(zc,{id:"policy-select",placeholder:"Select policy",data:g,value:_,onChange:b,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),w.length>0&&j.jsxs(j.Fragment,{children:[j.jsx(og,{id:"motion-select",label:"Motion",children:j.jsx(zc,{id:"motion-select",placeholder:"Select motion",data:w,value:C,onChange:S,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsx(Gl,{label:"Show reference",checked:M,onChange:ve=>T(ve.currentTarget.checked),size:"xs"})})]}),oe.length>0&&L.some(ve=>ve.config.type==="slider"||ve.config.type==="checkbox")&&j.jsx(j.Fragment,{children:oe.map(ve=>{const Ne=Re(ve);return Ne.length===0?null:j.jsx(tz,{label:Nne(ve),expandByDefault:!0,children:Ne.map(rt=>rt.config.type==="checkbox"?j.jsx(Pne,{command:rt,value:ye[rt.id]??0,onChange:fe,disabled:!R},rt.id):rt.config.type!=="slider"?null:j.jsx(Qne,{command:rt,value:ye[rt.id]??0,onChange:fe,disabled:!R,enabledWhenValue:rt.config.enabled_when?ye[Ew(rt.groupName,rt.config.enabled_when)]:void 0},rt.id))},ve)})}),j.jsx(Dd,{mb:"xs",mx:"xs"}),j.jsx(Je,{px:"xs",pb:"xs",children:j.jsx(lh,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:j.jsx(wne,{size:14}),onClick:Ee,children:"Reset"})})]})})]})]})}function Xf(n,e,t){return Object.keys(n[e]).reduce((r,i)=>(r[i]=`var(--mantine-${t}-${i})`,r),{})}function JR(n,e){return n in e.breakpoints?e.breakpoints[n]:X_(n)}function Fne(n){const e=bD(c0,n),t=Xf(e,"fontSizes","font-size"),r=Xf(e,"lineHeights","line-height"),i=Xf(e,"shadows","shadow"),s=Xf(e,"radius","radius"),a=Xf(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: ${JR(c,e)})`,largerThan:c=>`(min-width: ${JR(c,e)})`}}const Ow={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:Gl.extend({defaultProps:{radius:"xs"}}),ColorInput:jE.extend({defaultProps:{radius:"xs"}}),Select:zc.extend({defaultProps:{radius:"sm"}}),Textarea:qE.extend({defaultProps:{radius:"xs"}}),TextInput:aC.extend({defaultProps:{radius:"xs"}}),NumberInput:nC.extend({defaultProps:{radius:"xs"}}),Paper:Xc.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:au.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:lh.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};Fne(Ow);const rz=U.createContext(void 0),iz=()=>{const n=U.useContext(rz);if(!n)throw new Error("useLoading must be used within a LoadingProvider");return n},zne=({children:n})=>{const[e,t]=U.useState(!1),r=U.useRef(0),i=U.useCallback(()=>{r.current+=1,r.current>0&&t(!0)},[]),s=U.useCallback(()=>{r.current=Math.max(0,r.current-1),r.current===0&&t(!1)},[]);return j.jsx(rz.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:n})},Une=()=>{const{isLoading:n}=iz();return n?j.jsx("div",{className:"loader-overlay",children:j.jsx("div",{className:"loader-content",children:j.jsx(sh,{size:64,type:"bars"})})}):null},$w="panel",Gw="ref";function One(){const n="/".replace(/\/+$/,"/");let t=window.location.pathname.replace(/^\/+|\/+$/g,"");const r=n.replace(/^\/+|\/+$/g,"");if(r&&(t===r?t="":t.startsWith(`${r}/`)&&(t=t.slice(r.length+1))),!t)return null;const i=t.split("/")[0];return i==="main"||i.includes(".")||i==="assets"?null:i}function _I(n){return n.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function $ne(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 Gne(n,e){const r=new URLSearchParams(window.location.search).get("config"),i=$ne(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=>_I(r.name)===t)||n.scenes[0]}function q_(n,e){if(!n.policies.length)return null;const t=n.policies.find(s=>s.default)??n.policies[0];if(!e)return t.name;const r=e.trim().toLowerCase();return(n.policies.find(s=>s.name.toLowerCase()===r)||n.policies.find(s=>_I(s.name)===r))?.name??t.name}function Jf(n,e){return n?.motions?.length?(n.motions.find(r=>r.default)??n.motions[0]).name:null}function Vne(n){return new URLSearchParams(n).get($w)!=="0"}function Hne(n){return new URLSearchParams(n).get(Gw)!=="0"}function jne(n){const t="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let r=t?`/${t}/`:"/";return n&&n!=="main"&&(r+=`${n}/`),r}function Wne({projectId:n,sceneName:e,policyName:t,panelVisible:r,showReference:i}){const s=jne(n),a=new URLSearchParams(window.location.search);e?a.set("scene",e):a.delete("scene"),t?a.set("policy",t):a.delete("policy"),r?a.delete($w):a.set($w,"0"),i?a.delete(Gw):a.set(Gw,"0");const o=a.toString(),l=s+(o?`?${o}`:"")+window.location.hash;window.history.replaceState({},"",l)}function qne(){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(()=>Hne(window.location.search)),[p,A]=U.useState(null),[y,m]=U.useState(null),[x,g]=U.useState(null),[_,b]=U.useState(()=>Vne(window.location.search)),w=U.useRef(null),{showLoading:C,hideLoading:S}=iz(),M=U.useMemo(()=>One(),[]),T=U.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),R=U.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);U.useEffect(()=>{C(),Gne("/",M).then(J=>{e(J);const ge=J.projects.find(Ce=>M===null?Ce.id===null:Ce.id===M);if(!ge)throw new Error(`Project "${M??"(main)"}" not found in config.json.`);r(ge);const te=KR(ge,T);s(te);const ee=te?q_(te,R):null;o(ee);const ie=te?.policies.find(Ce=>Ce.name===ee)??null;c(Jf(ie))}).catch(J=>{A(J.message||"Failed to load config."),S()})},[M,T,R,C,S]);const k=U.useMemo(()=>{if(!t||!i)return null;const J=t.id?t.id:"main",ge=i.path?i.path:`scene/${_I(i.name)}/scene.xml`;return`${J}/assets/${ge}`.replace(/\/+/g,"/")},[t,i]),$=U.useMemo(()=>!i||!a?null:i.policies.find(J=>J.name===a)??null,[i,a]),Q=U.useMemo(()=>!t||!$?.config?null:`${t.id?t.id:"main"}/assets/${$.config}`.replace(/\/+/g,"/"),[t,$]),H=U.useMemo(()=>$?.motions?.length?$.motions.map(J=>({value:J.name,label:J.name})):[],[$]),B=U.useMemo(()=>{if(!t||!i?.splats?.length)return[];const J=t.id?t.id:"main";return i.splats.map(ge=>{if(ge.path){const te=`${J}/assets/${ge.path}`.replace(/\/+/g,"/");return{...ge,url:te}}return ge})},[t,i?.splats]),W=U.useMemo(()=>y?B.find(J=>J.name===y)??null:x?{name:"Custom",url:x}:null,[B,y,x]),K=U.useMemo(()=>n?n.projects.map(J=>({value:J.id??"main",label:J.name||(J.id??"Main")})):[],[n]),Y=U.useMemo(()=>t?t.scenes.map(J=>({value:J.name,label:J.name})):[],[t]),G=U.useMemo(()=>!i||!i.policies?[]:i.policies.map(J=>({value:J.name,label:J.name})),[i]),X=t?t.id??"main":null,re=i?.name??null,L=U.useCallback(J=>{A(J.message),S()},[S]),V=U.useCallback(()=>{S()},[S]);U.useEffect(()=>{const J=i?.splats?.[0];m(J?J.name:null),g(null)},[i]);const oe=U.useCallback(J=>{w.current=J},[]);U.useEffect(()=>{c(Jf($)),h(!!$?.motions?.length)},[$]);const Ae=U.useMemo(()=>i?.splats?.length?i.splats.map(J=>({value:J.name,label:J.name})):[],[i?.splats]),ye=U.useCallback(J=>{if(J===null)w.current?.setSplat(null);else{const ge=B.find(te=>te.name===J);ge&&w.current?.setSplat(ge)}m(J),g(null)},[B]),he=U.useCallback(async J=>{try{if(!(await fetch(J,{method:"HEAD"})).ok)return!1}catch{return!1}return w.current?.setSplat({name:"Custom",url:J}),g(J),!0},[]),fe=U.useCallback((J,ge,te,ee,ie,Ce,be)=>{const de=W??(x?{name:"Custom",url:x}:null);de&&w.current?.calibrateSplat({...de,scale:J,xOffset:ge,yOffset:te,zOffset:ee,roll:ie,pitch:Ce,yaw:be})},[W,x]),Ee=U.useCallback(J=>{Wne({projectId:J.projectId??t?.id??null,sceneName:J.sceneName??i?.name??null,policyName:J.policyName??a,panelVisible:J.panelVisible??_,showReference:J.showReference??d})},[t?.id,i?.name,a,_,d]),Re=U.useCallback(J=>{if(!n||!J)return;const ge=J==="main"?null:J,te=n.projects.find(be=>(be.id??"main")===(ge??"main"));if(!te)return;C(),r(te);const ee=KR(te,null);s(ee);const ie=ee?q_(ee,null):null;o(ie);const Ce=ee?.policies.find(be=>be.name===ie)??null;c(Jf(Ce)),Ee({projectId:te.id,sceneName:ee?.name??null,policyName:ie})},[n,C,Ee]),ve=U.useCallback(J=>{if(!t||!J)return;const ge=t.scenes.find(ie=>ie.name===J);if(!ge)return;C(),s(ge);const te=q_(ge,null);o(te);const ee=ge.policies.find(ie=>ie.name===te)??null;c(Jf(ee)),Ee({projectId:t.id,sceneName:J,policyName:te})},[t,C,Ee]),Ne=U.useCallback(J=>{J!==a&&C(),o(J);const ge=i?.policies.find(te=>te.name===J)??null;c(Jf(ge)),Ee({policyName:J})},[a,C,Ee]),rt=U.useCallback(J=>{b(J),Ee({panelVisible:J})},[Ee]),Ge=U.useCallback(J=>{const ge=l;c(J),w.current?.setSelectedMotion(J)?.then(ee=>{ee===!1&&J!==null&&c(w.current?.getSelectedMotionName()??ge)})},[l]),F=U.useCallback(J=>{h(J),w.current?.setReferenceVisible(J),Ee({showReference:J})},[Ee]);return p?j.jsx(eb,{theme:Ow,defaultColorScheme:"auto",children:j.jsx("div",{className:"app",children:j.jsxs("div",{className:"hud hud-error",children:[j.jsx("h1",{className:"hud-title",children:"mjswan"}),j.jsx("p",{className:"hud-message",children:p})]})})}):!t||!i||!k?null:j.jsx(eb,{theme:Ow,defaultColorScheme:"auto",children:j.jsxs("div",{className:"app",children:[j.jsx(Une,{}),j.jsx(Lne,{visible:_,onVisibleChange:rt,projects:K,projectValue:X,projectLabel:t?.name??"mjswan",onProjectChange:Re,scenes:Y,sceneValue:re,onSceneChange:ve,splats:Ae,splatSection:i?.splatSection??!1,splatValue:y,onSplatChange:ye,splatConfig:W,onCalibrateSplat:fe,onSplatUrlLoad:he,policies:G,policyValue:a,onPolicyChange:Ne,motions:H,motionValue:l,onMotionChange:Ge,showReferenceMotion:d,onShowReferenceMotionChange:F,commandsEnabled:!!Q}),j.jsx(gne,{scenePath:k,baseUrl:"/",policyConfigPath:Q,splatConfig:W,cameraConfig:i?.camera,eventsConfig:i?.events,terrainData:i?.terrainData,selectedMotion:l,showReferenceMotion:d,onError:L,onReady:V,onRuntimeReady:oe})]})})}function Yne(){return j.jsx(zne,{children:j.jsx(qne,{})})}const ZR=document.getElementById("root");ZR&&Wz.createRoot(ZR).render(j.jsx(On.StrictMode,{children:j.jsx(Yne,{})}));export{RV as _};
|