@babylonjs/lite 1.27.0 → 1.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/index.js +1 -1
- package/lib/engine/version.js +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
let VJ=null;function GCA(A){VJ=A}function U(A,...g){const I=new Error(VJ?.(A,g)??`#${A}`);throw I.lite=g,I}const X=Float32Array,S1=Float64Array,Vg=Uint32Array,R1=Int32Array,N1=Uint16Array,B3=Int16Array,mg=Uint8Array,Q3=Int8Array,si=Uint8ClampedArray,H1=DataView;function FCA(){return new X(16)}let WJ;function se(){return(WJ??FCA)()}function mCA(){return se()}function bCA(A){WJ=A}const dA=globalThis.GPUTextureUsage,SA=globalThis.GPUBufferUsage,NA=globalThis.GPUShaderStage,ai=globalThis.GPUColorWrite,HQ="greater-equal";function Ot(A){return`${A._colorFormat??"-"}|${A._depthStencilFormat??"-"}|${A._depthCompare??""}|${A._sampleCount}`}function wt(A){return{_descriptor:A,_colorTexture:null,_colorView:null,_depthTexture:null,_depthView:null,_width:0,_height:0}}function Kt(A,g){if(A._eager)return;Se(A);const I=A._descriptor,{width:e,height:t}=KCA(I);A._width=e,A._height=t;const i=g._device;I.format&&(A._colorTexture=i.createTexture({label:I.lbl,size:{width:e,height:t},format:I.format,sampleCount:I.samples,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING|dA.COPY_SRC|dA.COPY_DST}),A._colorView=A._colorTexture.createView()),I.dFormat&&(A._depthTexture=i.createTexture({label:I.lbl,size:{width:e,height:t},format:I.dFormat,sampleCount:I.samples,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING}),A._depthView=A._depthTexture.createView())}function Se(A){!A||A._eager||(A._colorTexture&&(A._colorTexture.destroy(),A._colorTexture=null,A._colorView=null),A._depthTexture&&(A._ownsDepthTexture!==!1&&A._depthTexture.destroy(),A._depthTexture=null,A._depthView=null),A._width=0,A._height=0)}function KCA(A){const g=A.size;if("canvas"in g){const I=g.canvas;return{width:I.width,height:I.height}}return g}const zJ="1.27.0",ZJ=`Babylon Lite v${zJ}`;function XG(A){return"clientWidth"in A}function kCA(A){return A.endsWith("-srgb")?A:`${A}-srgb`}let UCA=1;function LCA(A,g,I){const e=XJ(A,g,I);return A._surfaces.push(e),AF(e),$G(e),e}function XJ(A,g,I){const e=g.getContext("webgpu");e||U(48),XG(g)&&g.setAttribute("data-engine",ZJ);const t=I?.format??navigator.gpu.getPreferredCanvasFormat(),i=I?.srgb?kCA(t):t,o=I?.alphaMode??"opaque";e.configure({device:A._device,format:t,alphaMode:o,viewFormats:[i]});const Q=I?.msaaSamples===1?1:4,r=wt({lbl:"swapchain",format:i,samples:1,size:{width:0,height:0}});return r._eager=!0,{engine:A,canvas:g,format:i,msaaSamples:Q,scRT:r,maxDevicePixelRatio:I?.maxDevicePixelRatio??1/0,_uniqueId:UCA++,_context:e,_configureFormat:t,_alphaMode:o,_renderingContexts:[]}}function $G(A){const g=A._context.getCurrentTexture(),I=A.scRT;I._colorTexture=g,I._colorView=g.createView({format:A.format}),I._width=g.width,I._height=g.height}function AF(A){const g=A.canvas;if(!XG(g))return;const I=A._w??g.clientWidth,e=A._h??g.clientHeight;if(!(I>0&&e>0))return;const t=Math.min(globalThis.devicePixelRatio||1,A.maxDevicePixelRatio),i=I*t|0,o=e*t|0;r3(A,i,o)}function r3(A,g,I){const e=A.canvas,t=g|0,i=I|0;if(t>0&&i>0&&!(t===e.width&&i===e.height)){e.width=t,e.height=i,A.scRT._width=t,A.scRT._height=i;for(const o of A._renderingContexts)o._resize?.()}}function YCA(A){A===A.engine&&U(49),A._renderingContexts.length=0,A._ro?.disconnect(),A._context.unconfigure();const g=A.engine._surfaces,I=g.indexOf(A);I!==-1&&g.splice(I,1)}function E3(A){for(const g of A.splice(0))try{g()}catch{}}function G1(A,g){(A._retirements??=[]).push(g)}function gF(A){const g=A._retirements;if(!g)return;A._retirements=null;const I=A._retiring??=[];I.push(g),queueMicrotask(()=>{A._device.queue.onSubmittedWorkDone().then(()=>{const e=I.indexOf(g);e>=0&&I.splice(e,1),E3(g)}).catch(()=>{})})}function $J(A){const g=A._retirements,I=A._retiring;A._retirements=null,A._retiring=null,g&&E3(g),I?.forEach(E3)}let TQ=0;function cC(){TQ=TQ+1|0}function JCA(A){return A._renderingContexts}function vCA(A){if(!A||typeof A._kind!="string")throw new TypeError("Invalid RenderingContext: missing internal kind discriminator");return A._kind}function n3(A,g){return A._renderingContexts.indexOf(g)!==-1}function xQ(A,g){return A._renderingContexts.indexOf(g)!==-1?!1:(A._renderingContexts.push(g),!0)}function qQ(A,g){const I=A._renderingContexts,e=I.indexOf(g);return e===-1?!1:(I.splice(e,1),!0)}let YR=null;function HCA(A){YR=A}function TCA(){return YR?YR():{}}async function xCA(A,g){const I=await navigator.gpu.requestAdapter({powerPreference:"high-performance",...YR?YR():{}});I||U(46);const e=[];for(const l of["float32-filterable","texture-compression-astc","texture-compression-bc","texture-compression-etc2","timestamp-query","primitive-index"])I.features.has(l)&&e.push(l);const t=await I.requestDevice({requiredFeatures:e,requiredLimits:g?.requiredLimits});console.log(`${ZJ} - WebGPU engine`);const i=!!g?.useHighPrecisionMatrix,o=!!g?.useFloatingOrigin;if(o&&!i&&U(47),i){const{allocateF64Mat4:l}=await Promise.resolve().then(()=>k8A);bCA(l)}let Q,r,E,n;if(o){const[{wrapRenderableForFO:l,lightFoVersion:D,applyLightFoOffset:p},{makePackMeshWorld:y}]=await Promise.all([Promise.resolve().then(()=>_oA),Promise.resolve().then(()=>L8A)]);Q=l,r=y,E=D,n=p}const s={_device:t},c=[s];return Object.assign(s,{engine:s,surfaces:c,_surfaces:c,_device:t,_options:g,drawCallCount:0,gpuFrameTimeMs:0,useHighPrecisionMatrix:i,useFloatingOrigin:o,_animFrameId:0,_renderFn:null,_currentEncoder:void 0,_currentDelta:0,_cbs:[],_wrapRenderableForFO:Q,_makePackMeshWorld:r,_lightFoVersion:E,_applyLightFoOffset:n},XJ(s,A,g)),AF(s),$G(s),s}function s3(A){for(const g of A.surfaces)AF(g)}function qCA(A,g,I){r3(A,g,I)}function IF(A){const g=A.canvas;return{width:g.width,height:g.height}}function JR(A){return new Promise(g=>{let I=!0,e=0;A._renderFn=t=>{const i=I?0:e>0?t-e:16.667;e=t,s3(A),A6(A,i),I&&(I=!1,g()),A._renderFn&&(A._animFrameId=requestAnimationFrame(A._renderFn))},A._animFrameId=requestAnimationFrame(A._renderFn)})}function PCA(A){return A._device.queue.onSubmittedWorkDone()}function eF(A){A._animFrameId&&cancelAnimationFrame(A._animFrameId),A._animFrameId=0,A._renderFn=null,gF(A)}function OCA(A){$J(A),eF(A);const g=A._surfaces;for(const I of g)I._renderingContexts.length=0,I._ro?.disconnect(),I._context.unconfigure();g.length=0,A._disposeStorageBuffers?.(),A._device.destroy()}function A6(A,g){const I=A.surfaces;let e=0;for(let Q=0;Q<I.length;Q++)e+=I[Q]._renderingContexts.length;if(e===0){gF(A);return}const t=A._device.createCommandEncoder({label:"frame"});A._currentEncoder=t,A._currentDelta=g,A._gpuTimerBegin?.(t);let i=0;for(let Q=0;Q<I.length;Q++){const r=I[Q];r._capturePreFrame?.(r),$G(r);const E=r._renderingContexts;for(let n=0;n<E.length;n++){const s=E[n];s._update(),i+=s._drawCallsPre,i+=s._record()}}const o=A._currentEncoder;for(let Q=0;Q<I.length;Q++){const r=I[Q];r._captureService?.(r,o)}A._gpuTimerEnd?.(o),A._cbs[0]=o.finish(),A._device.queue.submit(A._cbs),gF(A),A.drawCallCount=i,A._gpuTimerResolve?.()}function g6(A){return A._device.features.has("timestamp-query")}function jCA(A,g){if(!g){A._gpuTimerWanted=!1,A.gpuFrameTimeMs=0,A._gpuTimerBegin=void 0,A._gpuTimerEnd=void 0,A._gpuTimerResolve=A._gpuTaskTimerResolve;return}g6(A)&&(A._gpuTimerWanted=!0,Promise.resolve().then(()=>T8A).then(({createGpuFrameTimer:I,gpuFrameTimerBegin:e,gpuFrameTimerEnd:t,gpuFrameTimerResolve:i})=>{A._gpuTimer===void 0&&(A._gpuTimer=I(A._device));const o=A._gpuTimer;o&&A._gpuTimerWanted&&(A._gpuTimerBegin=Q=>e(o,Q),A._gpuTimerEnd=Q=>t(o,Q),A._gpuTimerResolve=()=>{i(o),A.gpuFrameTimeMs=o.lastMs,A._gpuTaskTimerResolve?.()})}))}function VCA(A){const g={useHighPrecisionMatrix:!1,useFloatingOrigin:!1,drawCallCount:0,gpuFrameTimeMs:0,_animFrameId:0,_renderFn:null,_currentDelta:0,_cbs:[],_renderingContexts:[]};g.engine=g;const I=[g];return g.surfaces=I,g._surfaces=I,g}function I6(A,g,I){A._currentDelta=I,g._update()}function WCA(A,g,I,e=1e3/60){for(let t=0;t<I;t++)I6(A,g,e)}function tF(A){return A._device.features.has("timestamp-query")}function CF(A){if(!tF(A))return ci("unsupported",!1,!1,0,[],0);const g=A._gpuTaskTimingResult;return g||(A._gpuTaskTimerWanted?ci("pending",!0,!0,0,[],0):ci("disabled",!0,!1,0,[],0))}async function zCA(A,g){if(!g){A._gpuTaskTimerEpoch=(A._gpuTaskTimerEpoch??0)+1,A._gpuTaskTimerWanted=!1,A._gpuTaskTimerDisable?.(),A._gpuTaskTimerDisable=void 0,A._gpuTaskTimer=void 0;const o=tF(A);return A._gpuTaskTimingResult=ci(o?"disabled":"unsupported",o,!1,0,[],0),A._gpuTaskTimingResult}if(!tF(A))return A._gpuTaskTimerWanted=!1,A._gpuTaskTimingResult=ci("unsupported",!1,!1,0,[],0),A._gpuTaskTimingResult;if(A._gpuTaskTimerWanted)return CF(A);const I=(A._gpuTaskTimerEpoch??0)+1;A._gpuTaskTimerEpoch=I,A._gpuTaskTimerWanted=!0,A._gpuTaskTimingResult=ci("pending",!0,!0,0,[],0);const{createGpuTaskTimer:e,installGpuTaskTimer:t}=await Promise.resolve().then(()=>eLA);if(!A._gpuTaskTimerWanted||A._gpuTaskTimerEpoch!==I)return CF(A);A._gpuTaskTimer===void 0&&(A._gpuTaskTimer=e(A._device));const i=A._gpuTaskTimer;return i?(A._gpuTaskTimerDisable=t(i,A,o=>{A._gpuTaskTimerWanted&&A._gpuTaskTimerEpoch===I&&(A._gpuTaskTimingResult=o)}),CF(A)):(A._gpuTaskTimerWanted=!1,A._gpuTaskTimingResult=ci("unsupported",!1,!1,0,[],0),A._gpuTaskTimingResult)}async function ZCA(A,g,I){const{_measureRenderTaskOverdrawCost:e}=await Promise.resolve().then(()=>CLA);return e(A,g,I)}function ci(A,g,I,e,t,i,o){return{status:A,supported:g,enabled:I,frameIndex:e,tasks:t,droppedTaskCount:i,error:o}}function XCA(A){if(!XG(A.canvas)||typeof ResizeObserver>"u")return()=>{};A._ro?.disconnect();const g=A._ro=new ResizeObserver(([I])=>{A._w=Math.round(I.contentRect.width),A._h=Math.round(I.contentRect.height)});return g.observe(A.canvas),()=>{g.disconnect(),A._ro===g&&(A._ro=void 0,A._w=A._h=void 0)}}function $CA(A){const g=new Promise((I,e)=>{(A._captureQueue??=[]).push({resolve:I,reject:e})});return A._captureService||Promise.resolve().then(()=>nLA).then(({createCaptureService:I,createCapturePreFrame:e})=>{A._captureService??=I(),A._capturePreFrame??=e()}),g}function AiA(A){return A._deviceLostRecovery??={_forceNextLoss:!1,_requiredFeatures:[],_armedDevice:null,_registrations:[],_samplerDescriptors:new WeakMap,_captureRefs:0,_meshCaptureRefs:0,_textures:new Set,_texturesPruneAt:64}}function iF(A,g){const I=AiA(A),e=I._registrations;e.length===0&&(I._requiredFeatures=Array.from(A._device.features)),e.some(i=>i._kind===g._kind)||g._enable?.(A),e.push(g),e6(A,I);let t=!1;return{disable(){if(t)return;t=!0;const i=e.indexOf(g);i>=0&&e.splice(i,1),e.some(o=>o._kind===g._kind)||g._disable?.(A)}}}function giA(A){const g=A._deviceLostRecovery;return!!g?._registrations.length&&(g._forceNextLoss=!0)}function e6(A,g){const I=A._device;g._armedDevice===I||g._recovering||(g._armedDevice=I,I.lost.then(e=>{if(g._registrations.length===0||g._armedDevice!==I||e.reason==="destroyed"&&!g._forceNextLoss)return;g._forceNextLoss=!1,g._recovering=!0;const t=[...g._registrations];for(const i of t)i._onLost?.(e);Promise.resolve().then(()=>lLA).then(({runDeviceLostRecovery:i})=>i(A,g,t)).then(()=>{g._recovering=!1,e6(A,g);for(const i of t)i._onRecovered?.()},i=>{g._recovering=!1;for(const o of t)o._onRecoveryFailed?.(i)})}))}function IiA(A){giA(A)||U(45),A._device.destroy()}let a3=null;function PQ(){return a3||(a3=new WeakMap),a3}function rt(A){const g=PQ();g.set(A.texture,(g.get(A.texture)??0)+1)}function lC(A){const g=PQ(),I=(g.get(A.texture)??1)-1;return I<=0?(A.texture.destroy(),g.set(A.texture,0),!0):(g.set(A.texture,I),!1)}function eiA(A){return PQ().get(A.texture)===0}function t6(A){return PQ().get(A.texture)??0}function Qo(A){const g=PQ();g.set(A,(g.get(A)??0)+1)}function ro(A){const g=PQ(),I=(g.get(A)??1)-1;return I<=0?(A.destroy(),g.set(A,0),!0):(g.set(A,I),!1)}let vR=null;function tiA(A){return`${A.minFilter??"nearest"}:${A.magFilter??"nearest"}:${A.mipmapFilter??"nearest"}:${A.addressModeU??"clamp-to-edge"}:${A.addressModeV??"clamp-to-edge"}:${A.addressModeW??"clamp-to-edge"}:${A.maxAnisotropy??1}`}function Pe(A,g={}){const I=A._device;vR||(vR=new WeakMap);let e=vR.get(I);e||(e=new Map,vR.set(I,e));const t=tiA(g);let i=e.get(t);return i||(i=I.createSampler(g),e.set(t,i)),i}function c3(A){const g=A._device;vR?.delete(g)}function l3(A,g){const I={...A,...g};return C6?.(A,I),I}let C6=null;function CiA(A){C6=A}let oF=null;function OQ(A,g,I={}){const e=A._device;oF||(oF=new WeakMap);let t=oF.get(e);t||(t=new Map,oF.set(e,t));const i=`${g}\0${I.mipMaps??!0}\0${I.addressModeU??"repeat"}\0${I.addressModeV??"repeat"}\0${I.minFilter??"linear"}\0${I.magFilter??"linear"}\0${I.invertY??!0}\0${I.srgb??!1}\0${I.premultiplyAlpha??!1}`,o=t.get(i);if(o)return o;const Q=t,r=iiA(A,g,I);return Q.set(i,r),r.catch(()=>Q.delete(i)),r}async function iiA(A,g,I){const e=A._device,t=I.mipMaps??!0,i=I.addressModeU??"repeat",o=I.addressModeV??"repeat",Q=I.invertY??!0,r=I.srgb??!1,E=I.premultiplyAlpha??!1,n=r?"rgba8unorm-srgb":"rgba8unorm",c=await(await fetch(g)).blob(),l=await createImageBitmap(c,{premultiplyAlpha:E?"premultiply":"none",colorSpaceConversion:"none"}),D=l.width,p=l.height,y=t?Math.floor(Math.log2(Math.max(D,p)))+1:1,_=e.createTexture({size:{width:D,height:p},format:n,mipLevelCount:y,usage:dA.TEXTURE_BINDING|dA.COPY_DST|dA.RENDER_ATTACHMENT});if(e.queue.copyExternalImageToTexture({source:l,flipY:Q},{texture:_,premultipliedAlpha:E},{width:D,height:p}),l.close(),t&&y>1){const{generateMipmaps:R}=await Promise.resolve().then(()=>zR);R(A,_)}const u=I.minFilter??"linear",f=I.magFilter??"linear",h=t?"linear":"nearest",M=Pe(A,{addressModeU:i,addressModeV:o,minFilter:u,magFilter:f,mipmapFilter:h,maxAnisotropy:u==="linear"&&f==="linear"&&h==="linear"?4:1}),S={texture:_,view:_.createView(),sampler:M,width:D,height:p};return A._dlr?.u(S,g,I),rt(S),S}const oiA=64;let i6=null;function o6(A,g,I){g._recoverySource=I;const e=A._textures;if(e.size>=A._texturesPruneAt){for(const t of e)t.deref()||e.delete(t);A._texturesPruneAt=Math.max(oiA,e.size*2)}e.add(new WeakRef(g))}function B6(A,g){const I=A._recoverySource;if(!I)return;const e=i6?.get(I)?.deref();e&&o6(e,g,I)}function BiA(A){const g=A._deviceLostRecovery,I=new WeakRef(g),e=(t,i)=>{(i6??=new WeakMap).set(i,I),o6(g,t,i)};CiA(B6),A._dlr={t:e,d:B6,u(t,i,o){e(t,{kind:"url",url:i,opts:{...o}})},s(t,i,o,Q,r){e(t,{kind:"solid",rgba:[i,o,Q,r]})},b(t,i,o,Q,r){e(t,{kind:"bitmap",bitmap:i,srgb:o,mipMaps:Q,fallback:r})},p(t,i,o){e(t,{kind:"pixels",data:i.slice(0,t.width*t.height*4),width:t.width,height:t.height,options:{...o}})},r(t,i,o,Q,r){e(t,{kind:"render",width:i,height:o,format:Q,samplerDesc:r})},w(t,i,o,Q,r,E,n=0,s=r*4){const c=t._recoverySource;if(c?.kind!=="pixels")return;const l=r*4;for(let D=0;D<E;D++){const p=n+D*s,y=((Q+D)*c.width+o)*4;c.data.set(i.subarray(p,p+l),y)}},m(t,i,o,Q,r,E){A._deviceLostRecovery?._meshCaptureRefs&&(t._cpuUv2s=i??null,t._cpuTangents=o??null,t._cpuColors=Q??null,t._cpuGpuIndices=r,t._cpuIndexFormat=E)},e(t,i,o){g._meshCaptureRefs&&(t._envRecoverySource={kind:"env",url:i,brdfUrl:o})},h(t,i,o){g._meshCaptureRefs&&(t._envRecoverySource={kind:"hdr",url:i,faceSize:o})}}}function Q6(A,g=!1){const I=A._deviceLostRecovery;I||U(42),I._captureRefs++,g&&I._meshCaptureRefs++,I._captureRefs===1&&BiA(A)}function r6(A,g=!1){const I=A._deviceLostRecovery;!I||I._captureRefs===0||(I._captureRefs--,g&&I._meshCaptureRefs>0&&I._meshCaptureRefs--,I._captureRefs===0&&(A._dlr=void 0))}function QiA(A,g={}){return iF(A,{_kind:"scene",_recoverOrder:100,_enable(I){Q6(I,!0)},_disable(I){r6(I,!0)},async _recover(I){const{rebuildRegisteredScenes:e}=await Promise.resolve().then(()=>uLA);await e(I)},_onLost:g.onLost,_onRecovered:g.onRecovered,_onRecoveryFailed:g.onRecoveryFailed})}function riA(A,g={}){return iF(A,{_kind:"sprite-renderer",_enable:Q6,_disable:r6,async _recover(I){const{rebuildRegisteredSpriteRenderers:e}=await Promise.resolve().then(()=>dLA);await e(I)},_onLost:g.onLost,_onRecovered:g.onRecovered,_onRecoveryFailed:g.onRecoveryFailed})}function EiA(A,g={}){return iF(A,{_kind:"text-renderer",async _recover(I){const{rebuildRegisteredTextRenderers:e}=await Promise.resolve().then(()=>RLA);e(I)},_onLost:g.onLost,_onRecovered:g.onRecovered,_onRecoveryFailed:g.onRecoveryFailed})}function HR(A){A._refCount=(A._refCount??1)+1}function DC(A){const g=A._refCount;return g===void 0||g<=1?!0:(A._refCount=g-1,!1)}function E6(A,g,I,e=g.material){return Promise.resolve().then(()=>XK).then(t=>t.A(A,e,g,I)).catch(t=>console.error(t))}function D3(A,g,I){A._runtimeThinBuild=E6,A.thinInstances?(A.thinInstances.matrices=g,A.thinInstances.count=I,A.thinInstances._capacity=I,A.thinInstances._version++,A.thinInstances._dirtyMin=0,A.thinInstances._dirtyMax=I):A.thinInstances={matrices:g,count:I,_capacity:I,_version:1,_gpuBuffer:null,_gpuBufferStorage:!1,_gpuVersion:0,_dirtyMin:0,_dirtyMax:I,_colorVersion:0,_colorDirtyMin:0,_colorDirtyMax:0,_colorGpuBuffer:null,_colorGpuBufferStorage:!1,_colorGpuVersion:0,_gpuCullingEnabled:!1}}function p3(A,g){const I=A.thinInstances;I&&(I.count=g,I._version++,I._dirtyMin=0,I._dirtyMax=g)}function niA(A,g){const I=A.thinInstances;if(I){if(!Number.isInteger(g)||g<0||g>I._capacity)throw new RangeError(`Thin instance draw count ${g} must be an integer between 0 and capacity ${I._capacity}`);I.count!==g&&((!I._gpuBuffer||I._gpuVersion!==I._version||I.colors&&(!I._colorGpuBuffer||I._colorGpuVersion!==I._colorVersion))&&U(369),I.count=g,I._gpuVersion=++I._version)}}function siA(A){const g=A.thinInstances;g||U(370),g._drawArgsBuffer||(g._drawArgsInstanceCount=-1)}function aiA(A,g){A._runtimeThinBuild=E6;const I=A.thinInstances;if(!I){const i=new X(256);return i.set(g,0),A.thinInstances={matrices:i,count:1,_capacity:16,_version:1,_gpuBuffer:null,_gpuBufferStorage:!1,_gpuVersion:0,_dirtyMin:0,_dirtyMax:1,_colorVersion:0,_colorDirtyMin:0,_colorDirtyMax:0,_colorGpuBuffer:null,_colorGpuBufferStorage:!1,_colorGpuVersion:0,_gpuCullingEnabled:!1},0}const e=I.count;if(e>=I._capacity){const t=I._capacity*2,i=new X(t*16);i.set(I.matrices),I.matrices=i,I._capacity=t}return I.matrices.set(g,e*16),I.count++,I._version++,I._dirtyMin=0,I._dirtyMax=I.count,e}function ciA(A,g,I){const e=A.thinInstances;e.matrices.set(I,g*16),e._version++,e._dirtyMin=Math.min(e._dirtyMin,g),e._dirtyMax=Math.max(e._dirtyMax,g+1)}function liA(A,g){const I=A.thinInstances,e=I.count-1;g!==e&&I.matrices.copyWithin(g*16,e*16,e*16+16),I.count--,I._version++,I._dirtyMin=0,I._dirtyMax=I.count}function DiA(A){const g=A.thinInstances;g._version++,g._dirtyMin=0,g._dirtyMax=g.count}function piA(A,g){const I=A.thinInstances;I.colors=g,I._version++,I._colorVersion++,I._colorDirtyMin=0,I._colorDirtyMax=I.count}function yiA(A,g,I,e,t,i){const o=A.thinInstances,Q=o.colors,r=g*4;Q[r]=I,Q[r+1]=e,Q[r+2]=t,Q[r+3]=i,o._version++,o._colorVersion++,o._colorDirtyMin=Math.min(o._colorDirtyMin,g),o._colorDirtyMax=Math.max(o._colorDirtyMax,g+1)}function _iA(A,g=!0){const I=A.thinInstances;I||U(371),I._gpuCullingEnabled!==g&&(I._gpuCullingEnabled=g,I._gpuVersion=-1,I._colorGpuVersion=-1)}function uiA(A,g){const I=A.thinInstances;I||U(372),I._cullBoundsPad=g}function hiA(A,g,I){const e=A.thinInstances,t=g.thinInstances;if((!e||!t)&&U(373),A===g&&U(374),((e._refCount??1)>1||(t._refCount??1)>1)&&U(375),!Number.isFinite(I.distance)||I.distance<0)throw new RangeError("setThinInstanceLodPartner distance must be a finite non-negative number");const i=I.band??0;if(!Number.isFinite(i)||i<0)throw new RangeError("setThinInstanceLodPartner band must be a finite non-negative number");e._lodSource&&U(376),t._lodPartner&&U(377),t._lodSource&&t._lodSource!==A&&U(378),t.colors&&!e.colors&&U(379);const o=e._lodPartner;if(o&&o!==g){const r=o.thinInstances;r&&r._lodSource===A&&BF(r),o._clone=void 0,e._lodBuckets=null}e._lodPartner=g,e._lodDistance=I.distance,e._lodBand=i,t._lodSource=A,A._clone=g._clone="Cannot clone LOD-paired mesh";const Q=e._lodBuckets??new WeakMap;e._lodBuckets=Q,t._lodBuckets=Q,t._gpuCullingEnabled||(t._lodAutoCull=!0,t._gpuCullingEnabled=!0,t._gpuVersion=-1,t._colorGpuVersion=-1)}function fiA(A){const g=A.thinInstances;if(!g?._lodPartner)return;const I=g._lodPartner,e=I.thinInstances;g._lodPartner=null,g._lodDistance=void 0,g._lodBand=void 0,g._lodBuckets=null,A._clone=void 0,I._clone=void 0,e&&e._lodSource===A&&BF(e)}function diA(A){const g=A.thinInstances;if(!g)return;const I=g._lodSource,e=I?.thinInstances;I&&e?._lodPartner===A&&(e._lodPartner=null,e._lodDistance=void 0,e._lodBand=void 0,e._lodBuckets=null,I._clone=void 0),g._lodSource&&BF(g);const t=g._lodPartner,i=t?.thinInstances;g._lodPartner=null,g._lodDistance=void 0,g._lodBand=void 0,g._lodBuckets=null,A._clone=void 0,t&&i?._lodSource===A&&(t._clone=void 0,BF(i))}function BF(A){A._lodSource=null,A._lodBuckets=null,A._lodAutoCull&&(A._lodAutoCull=!1,A._gpuCullingEnabled=!1,A._gpuVersion=-1,A._colorGpuVersion=-1)}function X1(A){if(A._disposed)return;A._disposed=!0;const g=A._gpu;DC(g)&&(g.positionBuffer.destroy(),g.normalBuffer.destroy(),g.uvBuffer.destroy(),g.indexBuffer.destroy(),g.tangentBuffer?.destroy(),g.uv2Buffer?.destroy(),g.colorBuffer?.destroy());const I=A.thinInstances;I&&DC(I)&&(diA(A),I._gpuBuffer?.destroy(),I._colorGpuBuffer?.destroy(),I._drawArgsBuffer?.destroy());const e=A.skeleton;e&&DC(e)&&(e._disposed=!0,e.boneTexture.destroy(),DC(e._skinBuffers)&&(e.jointsBuffer.destroy(),e.weightsBuffer.destroy(),e.joints1Buffer?.destroy(),e.weights1Buffer?.destroy()));const t=A.vat;t&&DC(t)&&(t.settingsBuffer.destroy(),t.instanceTexture?.destroy(),DC(t._textureResource)&&t._textureResource.texture.destroy(),DC(t._skinBuffers)&&(t.jointsBuffer.destroy(),t.weightsBuffer.destroy(),t.joints1Buffer?.destroy(),t.weights1Buffer?.destroy()));const i=A.morphTargets;i&&DC(i)&&(i._disposed=!0,i.deltasBuffer.destroy(),i.weightsBuffer.destroy())}let y3=null;function QF(A,g){A._materialSwapQueue.includes(g)||A._materialSwapQueue.push(g)}function wiA(A){let g=A.material;Object.defineProperty(A,"material",{get(){return g},set(I){if(I!==g){g=I;const e=y3?.get(A);if(e)for(const t of e)QF(t,A)}},configurable:!0,enumerable:!0})}function MiA(A,g){g._disposed&&U(459,g.name);const I=y3??=new WeakMap;let e=I.get(g);e||(I.set(g,e=new Set),wiA(g)),e.add(A)}function n6(A,g){const I=y3?.get(g);return I?(I.delete(A),I.size===0):!0}function s6(A){const g=A._materialSwapQueue;if(!g[0]||A._runtimeBuilds?.w)return;let I,e,t;const i=A._renderables;for(const Q of g){const r=Q.material;if(!r)continue;const E=Q._runtimeThinBuild;if(E){e=E(A,Q,e);continue}const n=A._groups.get(r._buildGroup),s=n?.r;if(!s){(t??=[]).push(Q);continue}if(n._w?.(Q)){(t??=[]).push([Q,r]);continue}const c=A._meshDisposables.get(Q);c&&(A._meshDisposables.delete(Q),G1(A.surface.engine,()=>c.forEach(y=>y())));const l=n.o;let D;for(let y=i.length;y--;)i[y].mesh===Q&&(D=i.splice(y,1)[0]);r._csmGen=-~r._csmGen;const p=s(A,Q);if(l){const y=l.indexOf(D);y<0?l.push(p):l[y]=p}I=i.push(p)}if(I&&(i.sort((Q,r)=>Q.order-r.order),A._renderableVersion++,A._materialEpoch++),g.length=0,!t)return e;const o=t;return Promise.resolve().then(()=>XK).then(({C:Q})=>Q(A,o,e),Q=>{const r=A._runtimeBuilds;r?r._x(Q):console.error(Q)})}let a6=null;function SiA(A){a6=A}function RiA(A,g,I){a6?.(A,g,I)}function c6(A){const g={_tasks:[],_currentProcessedTask:null,build(){for(let I=0;I<g._tasks.length;I++)l6(g,g._tasks[I]);for(const I of g._tasks)for(const e of I._passes)e._initialize()},execute(){let I=0;for(const e of g._tasks)if(e.executionEnabled!==!1)if(e.execute)I+=e.execute();else for(const t of e._passes)I+=t._execute();return I},dispose(){for(const I of g._tasks)I.dispose();g._tasks.length=0,g._currentProcessedTask=null}};return g}function NiA(A,g){A._tasks.includes(g)||U(94,g.name),l6(A,g);for(const I of g._passes)I._initialize()}function l6(A,g){g._passes.length=0,A._currentProcessedTask=g;try{g.record()}finally{A._currentProcessedTask=null}}function D6(A,g){A._tasks.push(g)}function Oe(A,g,I,e,t,i){const o=I[e],Q=I[e+1],r=I[e+2],E=I[e+3],n=I[e+4],s=I[e+5],c=I[e+6],l=I[e+7],D=I[e+8],p=I[e+9],y=I[e+10],_=I[e+11],u=I[e+12],f=I[e+13],h=I[e+14],w=I[e+15];let M=t[i],S=t[i+1],R=t[i+2],N=t[i+3];A[g]=o*M+n*S+D*R+u*N,A[g+1]=Q*M+s*S+p*R+f*N,A[g+2]=r*M+c*S+y*R+h*N,A[g+3]=E*M+l*S+_*R+w*N,M=t[i+4],S=t[i+5],R=t[i+6],N=t[i+7],A[g+4]=o*M+n*S+D*R+u*N,A[g+5]=Q*M+s*S+p*R+f*N,A[g+6]=r*M+c*S+y*R+h*N,A[g+7]=E*M+l*S+_*R+w*N,M=t[i+8],S=t[i+9],R=t[i+10],N=t[i+11],A[g+8]=o*M+n*S+D*R+u*N,A[g+9]=Q*M+s*S+p*R+f*N,A[g+10]=r*M+c*S+y*R+h*N,A[g+11]=E*M+l*S+_*R+w*N,M=t[i+12],S=t[i+13],R=t[i+14],N=t[i+15],A[g+12]=o*M+n*S+D*R+u*N,A[g+13]=Q*M+s*S+p*R+f*N,A[g+14]=r*M+c*S+y*R+h*N,A[g+15]=E*M+l*S+_*R+w*N}function p6(A,g,I,e,t){const i=1/Math.tan(g*.5),o=t-e;A[0]=i/I,A[5]=i,A[10]=-e/o,A[11]=1,A[14]=t*e/o}function l1(A){const g=A.worldMatrixVersion;if(A._viewVer===g)return A._viewCache;const I=A._viewCache,e=A.worldMatrix,t=A._useFloatingOrigin,i=t?0:e[12],o=t?0:e[13],Q=t?0:e[14];return I[0]=e[0],I[1]=e[4],I[2]=e[8],I[3]=0,I[4]=e[1],I[5]=e[5],I[6]=e[9],I[7]=0,I[8]=e[2],I[9]=e[6],I[10]=e[10],I[11]=0,I[12]=-(e[0]*i+e[1]*o+e[2]*Q),I[13]=-(e[4]*i+e[5]*o+e[6]*Q),I[14]=-(e[8]*i+e[9]*o+e[10]*Q),I[15]=1,A._viewVer=g,I}let _3=null;function GiA(A){_3=A}function T1(A){return(A._projFov!==A.fov||A._projNear!==A.nearPlane||A._projFar!==A.farPlane)&&(A._projFov=A.fov,A._projNear=A.nearPlane,A._projFar=A.farPlane,A._projRev=(A._projRev??0)+1),A.worldMatrixVersion+(A._projRev??0)}function li(A,g){const I=T1(A);if(A._projVer===I&&A._projAspect===g)return A._projCache;const e=A._projCache;return _3!==null&&A.ortho?_3(A,g,e):p6(e,A.fov,g,A.nearPlane,A.farPlane),A._projVer=I,A._projAspect=g,e}function x1(A,g){const I=T1(A);if(A._vpVer===I&&A._vpAspect===g)return A._vpCache;const e=A._vpCache;return Oe(e,0,li(A,g),0,l1(A),0),A._vpVer=I,A._vpAspect=g,e}function jQ(A){const g=A.worldMatrix;return{x:g[12],y:g[13],z:g[14]}}function KC(A,g,I){const e=A?.viewport;return g/I*(e?e.width/e.height:1)}let TR=null,u3=null;function Mt(A){const g=A._device;return TR&&u3===g||(u3=g,TR=g.createBindGroupLayout({label:"scene",entries:[{binding:0,visibility:NA.VERTEX|NA.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:NA.FRAGMENT,buffer:{type:"uniform"}}]})),TR}function h3(){TR=null,u3=null}function rF(A){const g=A._blend?{format:A._format,blend:A._blend}:{format:A._format};return{label:A._label,layout:A._engine._device.createPipelineLayout({bindGroupLayouts:A._bgls}),vertex:{module:A._vertModule,entryPoint:"main",buffers:A._vertexBuffers},fragment:{module:A._fragModule,entryPoint:"main",targets:[g]},depthStencil:{format:A._depthStencilFormat??"depth24plus-stencil8",depthCompare:A._depthCompare??HQ,depthWriteEnabled:A._depthWriteEnabled??!0},multisample:{count:A._msaaSamples},primitive:{topology:"triangle-list",cullMode:A._cullMode??"back",frontFace:"ccw"}}}function et(A,g,I=0,e=0){const t=g;if(e===0&&t.length===16){A.set(t,I);return}const i=e,o=I;A[o+0]=t[i+0],A[o+1]=t[i+1],A[o+2]=t[i+2],A[o+3]=t[i+3],A[o+4]=t[i+4],A[o+5]=t[i+5],A[o+6]=t[i+6],A[o+7]=t[i+7],A[o+8]=t[i+8],A[o+9]=t[i+9],A[o+10]=t[i+10],A[o+11]=t[i+11],A[o+12]=t[i+12],A[o+13]=t[i+13],A[o+14]=t[i+14],A[o+15]=t[i+15]}function y6(A,g,I,e,t){A.fill(0);const i=x1(e,t),o=l1(e),Q=e.worldMatrix;et(A,i,0),et(A,o,16),g.useFloatingOrigin?(A[32]=0,A[33]=0,A[34]=0):(A[32]=Q[12],A[33]=Q[13],A[34]=Q[14]),A[87]=g.canvas.width;const r=I._envTextures,E=I.imageProcessing;A[76]=E.exposure,A[77]=E.contrast,A[78]=r?.lodGenerationScale??.8,A[79]=+E.toneMappingEnabled,A[37]=g.canvas.height}function EF(A,g){return A+g-1&~(g-1)}function Re(A,g,I){const e=A._device,t=e.createBuffer({label:I,size:EF(g.byteLength,16),usage:SA.UNIFORM|SA.COPY_DST});return e.queue.writeBuffer(t,0,g.buffer,g.byteOffset,g.byteLength),t}function jt(A,g,I){return A._device.createBuffer({label:I,size:EF(g,16),usage:SA.UNIFORM|SA.COPY_DST})}function wI(A,g,I,e){const t=EF(Math.max(g.byteLength,4),4),i=A._device.createBuffer({label:e,size:t,usage:I|SA.COPY_DST,mappedAtCreation:!0});return new mg(i.getMappedRange()).set(new mg(g.buffer,g.byteOffset,g.byteLength)),i.unmap(),i}const xR=368;let HI=16;function _6(A){if(!Number.isFinite(A)||A<1)throw new Error(`setMaxLights: expected positive integer, got ${A}`);HI=A|0}const f3=16,u6=new Vg(1),FiA=new X(u6.buffer),h6=20;function miA(){return Math.ceil(HI/4)}function d3(){return 16+HI*f3*4}function f6(A){let g=0;for(const I of A)g+=I._lightVersion??0;return g}function w3(A,g){A.fill(0);let I=0;const e=4;for(const t of g){if(I>=HI)break;t._writeLightUbo&&(t._writeLightUbo(A,e+I*f3),I++)}u6[0]=I,A[0]=FiA[0]}function VQ(A,g){let I=g._lightGpuState;const e=d3();if(I&&I._byteSize===e)return I;const t=!I;I?._buffer.destroy();const i=new X(e/4);return w3(i,g.lights),A._applyLightFoOffset?.(i,g),I={_buffer:Re(A,i),_scratch:i,_version:f6(g.lights)+(A._lightFoVersion?.(g)??0),_listVersion:g._lightListVersion??0,_lightCount:g.lights.length,_byteSize:e},g._lightGpuState=I,t&&g._disposables.push(()=>{g._lightGpuState?._buffer.destroy(),g._lightGpuState=void 0}),I}function biA(A,g){const I=VQ(A,g),e=f6(g.lights)+(A._lightFoVersion?.(g)??0),t=g._lightListVersion??0;return(e!==I._version||t!==I._listVersion||g.lights.length!==I._lightCount)&&(I._version=e,I._listVersion=t,I._lightCount=g.lights.length,w3(I._scratch,g.lights),A._applyLightFoOffset?.(I._scratch,g),A._device.queue.writeBuffer(I._buffer,0,I._scratch)),I._buffer}function KiA(A,g,I){w3(g,I.lights),A._applyLightFoOffset?.(g,I)}function d6(A){A.push({_name:"lc",_type:"u32"}),A.push({_name:"li",_type:`array<vec4<u32>, ${miA()}>`})}function w6(A,g="mli"){return`fn ${g}(i:u32)->u32{return ${A}.li[i/4u][i%4u];}`}function kiA(A,g){const I=g.id,e=A.includedOnlyMeshIds;return e?.size?!!I&&e.has(I):!I||!A.excludedMeshIds?.has(I)}function F1(A,g,I){const e=I?new Vg(I.buffer,I.byteOffset,I.byteLength/4):null;let t=0,i=-1,o=0;for(const Q of g){if(o>=HI)break;Q._writeLightUbo&&(kiA(Q,A)&&(i=o,e&&(e[h6+t]=o),t++),o++)}if(e){e[16]=t;for(let Q=t;Q<HI;Q++)e[h6+Q]=0}return t===1?i+1:-t}function Eo(A,g,I){const e=I;A.clr??=!0;const t=A.rt._descriptor,i={_colorFormat:t.format,_depthStencilFormat:A.depth?._descriptor.dFormat??t.dFormat,_depthCompare:t._depthCompare,_sampleCount:t.samples??1},o=Mt(g),Q=jt(g,xR),r=VQ(g,e)._buffer,E=g._device.createBindGroup({layout:o,entries:[{binding:0,resource:{buffer:Q}},{binding:1,resource:{buffer:r}}]}),n={loadOp:"clear",storeOp:"store"},s={targetWidth:0,targetHeight:0},c=A.autoMirror!==!1,l=!A.sharedRt,D={name:A.name,_config:A,engine:g,scene:e,_passes:[],_renderables:[],_opaqueBindings:[],_directBindings:[],_transparentBindings:[],_ob:[],_lastVersion:-1,_lastVis:0,_recorded:!1,_renderPassDescriptor:{colorAttachments:[n]},_colorAttachment:n,_sceneUBO:Q,_sceneBG:E,_lightsUBO:r,_suData:new X(xR/4),_sceneUboCacheKey:[],_targetSignature:i,_updateBatches:[],_pendingMeshes:[],addMesh(p,y){const _=y?.material??p.material;_&&(D._pendingMeshes.push({mesh:p,material:_}),D._recorded&&(nF(D,e),D._af=!1,sF(D,g,i)))},record(){D._af&&(D._renderables.length=0),nF(D,e),D._af=c&&!D._renderables.length,D._af&&D._renderables.push(...e._renderables);const p=A.rt;l&&(Kt(p,g),A.rst&&(p._descriptor.samples??1)>1&&Kt(A.rst,g)),A.depth&&!A.depth._eager&&Kt(A.depth,g),s.targetWidth=p._width,s.targetHeight=p._height,S6(D,g),sF(D,g,i),YiA(D,p),D._recorded=!0},execute(){return viA(D,g,i,s)},dispose(){D._passes.length=D._opaqueBindings.length=D._directBindings.length=0,D._transparentBindings.length=D._renderables.length=D._ob.length=0,l&&(Se(A.rt),Se(A.rst)),Se(A.depth),D._sceneUBO.destroy();for(const p of D._updateBatches)p.destroy();D._updateBatches.length=0}};return D}function qR(A,g){if(!A._renderables)return;let I=!1;for(let e=A._pendingMeshes.length-1;e>=0;e--)A._pendingMeshes[e].mesh===g&&(A._pendingMeshes.splice(e,1),I=!0);for(let e=A._renderables.length-1;e>=0;e--)A._renderables[e].mesh===g&&(A._renderables.splice(e,1),I=!0);for(const e of[A._opaqueBindings,A._directBindings,A._transparentBindings])for(let t=e.length-1;t>=0;t--)e[t].renderable.mesh===g&&(e.splice(t,1),I=!0);I&&(A._ob.length=0,A._lastVersion=-1)}function nF(A,g){if(A._pendingMeshes.length){for(const{mesh:I,material:e}of A._pendingMeshes){const t=e._buildGroup,i=g._groups.get(t),o=i?i.r:t._rebuildSingle;if(!o)throw Error();const Q=o(g,I,e);A._renderables.includes(Q)||A._renderables.push(Q)}A._pendingMeshes.length=0}}function UiA(A,g){return g._sortDistance-A._sortDistance||A.renderable.order-g.renderable.order}function M6(A,g){return A.renderable.order-g.renderable.order}function LiA(A,g){const I=A._transparentBindings;if(I.length<=1||!g)return;const e=l1(g);for(const t of I){const i=t.renderable._worldCenter;t._sortDistance=i?i[0]*e[2]+i[1]*e[6]+i[2]*e[10]+e[14]:0}I.sort(UiA)}function sF(A,g,I){const e=A._opaqueBindings,t=A._directBindings,i=A._transparentBindings;e.length=t.length=i.length=0;for(const o of A._renderables){const Q=o.bind(g,I);for(const r of Q._updateBatches??[])A._updateBatches.includes(r)||A._updateBatches.push(r);o.isTransparent||o._transmissive?i.push(Q):o._direct?t.push(Q):e.push(Q)}e.sort(M6),t.sort(M6),A._ob.length=0,A._lastVersion=A.scene._renderableVersion}function YiA(A,g){const I=A._config,e=A._colorAttachment;e.view=g._colorView,A._renderPassDescriptor.colorAttachments=g._colorView?[e]:[];const t=I.depth??g,i=t._depthView;let o;if(i){const Q=t._descriptor,r=(I.depth?t._eager:I.depthClear===!1)?"load":"clear";o={view:i,depthClearValue:Q._depthClearValue??0,depthLoadOp:r,depthStoreOp:"store"},Q.dFormat?.includes("stencil")&&(o.stencilClearValue=0,o.stencilLoadOp=r,o.stencilStoreOp="store")}A._renderPassDescriptor.depthStencilAttachment=o}function JiA(A,g,I,e){const t=A.scene;A._af&&A._lastVersion!==t._renderableVersion&&(A._renderables.length=0,A._renderables.push(...t._renderables),sF(A,g,I)),S6(A,g);const i=A._config.cam??t.camera;I._colorFormat&&(A._config._skipClusteredLights||t._clusteredLightUpdater?.(i,e.targetWidth,e.targetHeight),biA(g,t)),TiA(A,g,t,i),e._camera=i;for(const o of A._updateBatches)o.reset();M3(A._opaqueBindings,e),M3(A._directBindings,e),M3(A._transparentBindings,e);for(const o of A._updateBatches)o.flush(g);LiA(A,i)}function viA(A,g,I,e){if(A.enabled===!1)return 0;const t=A.scene,i=I._sampleCount;JiA(A,g,I,e);const o=A._colorAttachment,Q=A._config;if(Q.rt._colorView&&(Q.rt===t.surface.scRT&&(o.view=Q.rt._colorView),o.resolveTarget=Q.rst?._colorView??void 0,o.clearValue=Q.clrColor??t.clearColor,o.loadOp=Q.clr?"clear":"load"),A._executeWithTransmission)return A._executeWithTransmission(i);const r=g._currentEncoder.beginRenderPass(A._renderPassDescriptor),E=HiA(A,r);return r.end(),E}function HiA(A,g){const I=A.engine,e=A._config,t=e.rt,i=A.scene,o=A._opaqueBindings,Q=A._ob,r=A._sceneBG,n=(e.cam??i.camera)?.viewport;if(n){const c=t._width,l=t._height,D=Math.floor(n.x*c),p=Math.floor((1-n.y-n.height)*l),y=Math.ceil((n.x+n.width)*c)-D,_=Math.ceil((1-n.y)*l)-p;g.setViewport(D,p,y,_,0,1),g.setScissorRect(D,p,y,_)}if(g.setBindGroup(0,r),A._lastVersion!==i._renderableVersion||A._lastVis!==TQ||!Q.length){const c=t._descriptor,l=I._device.createRenderBundleEncoder({colorFormats:c.format?[c.format]:[],depthStencilFormat:A._targetSignature._depthStencilFormat,sampleCount:c.samples??1});l.setBindGroup(0,r),WQ(l,o,I),Q[0]=l.finish(),A._lastVersion=i._renderableVersion,A._lastVis=TQ}let s=o.length;return g.executeBundles(Q),g.setBindGroup(0,r),s+=WQ(g,A._directBindings,I),s+=WQ(g,A._transparentBindings,I),s}function S6(A,g){const I=VQ(g,A.scene)._buffer;I!==A._lightsUBO&&(A._lightsUBO=I,A._sceneBG=g._device.createBindGroup({layout:Mt(g),entries:[{binding:0,resource:{buffer:A._sceneUBO}},{binding:1,resource:{buffer:I}}]}),A._ob.length=0,A._lastVersion=-1)}function TiA(A,g,I,e){if(!e)return;const t=e.viewport,i=A._config.rt,o=(A._config.cs?g.canvas.width/g.canvas.height:i._width/i._height)*(t?t.width/t.height:1),Q=I.fog,r=I.imageProcessing,E=T1(e),n=I._envTextures,s=A._sceneUboCacheKey;if(s[0]===e&&s[1]===Q&&s[2]===E&&s[3]===o&&s[4]===r.exposure&&s[5]===r.contrast&&s[6]===n)return;s[0]=e,s[1]=Q,s[2]=E,s[3]=o,s[4]=r.exposure,s[5]=r.contrast,s[6]=n;const c=A._suData;y6(c,g,I,e,o);const l=I._sceneUboContributors;if(l)for(const D of l)D(c,I);g._device.queue.writeBuffer(A._sceneUBO,0,c)}function M3(A,g){for(const I of A)I.update?.(g)}function WQ(A,g,I){let e=null,t=0;for(const i of g){const o=i.renderable.mesh;o&&o.visible===!1||(i.pipeline!==e&&(A.setPipeline(i.pipeline),e=i.pipeline),t+=i.draw(A,I))}return t}let aF=null;function R6(A,g){const I=A.engine,t={_kind:"scene",surface:A,clearColor:{r:.2,g:.2,b:.3,a:1},camera:null,lights:[],meshes:[],animationGroups:[],fog:null,clipPlane:null,shadowGenerators:[],imageProcessing:{exposure:1,contrast:1,toneMappingEnabled:!1},_renderables:[],_prePasses:[],_pickSources:[],_uniformUpdaters:[],fixedDeltaMs:0,_beforeRender:[],_deferredBuilders:[],_groups:new Map,_disposables:[],_meshDisposables:new Map,_meshAuxDisposables:new Map,_materialSwapQueue:[],_renderableVersion:0,_materialEpoch:0,_built:!1,_drawCallsPre:0,_update(){I.useFloatingOrigin&&t.camera&&!t.camera._useFloatingOrigin&&(t.camera._useFloatingOrigin=!0,t.camera._viewVer=-1,t.camera._vpVer=-1);const o=t.fixedDeltaMs>0?t.fixedDeltaMs:I._currentDelta,Q=I._currentEncoder;let r=0;for(const E of t._beforeRender)E(o);t._materialSwapQueue.length&&s6(t);for(const E of t._prePasses)r+=E.execute(Q,I);for(const E of t._uniformUpdaters)E.update(I);t._drawCallsPre=r},_record(){return t._frameGraph.execute()},_resize(){t._frameGraph.build()}},i=c6();if(t._frameGraph=i,g?.defaultRenderTask!==!1){const o=A.msaaSamples>1,Q=o?wt({lbl:"scene-color",format:A.format,dFormat:"depth24plus-stencil8",samples:A.msaaSamples,size:A}):A.scRT,r=o?void 0:wt({lbl:"scene-depth",dFormat:"depth24plus-stencil8",samples:1,size:A});D6(i,Eo({name:"scene",rt:Q,rst:o?A.scRT:void 0,depth:r},I,t))}return t._disposables.push(()=>i.dispose()),t}function zQ(A,g){A._beforeRender.unshift(g)}function xiA(A,g){A._disposables.push(g)}function qiA(A){return A._frameGraph}function cF(A,g){const I=A;I._deferredBuilders.push(async()=>{const e=await g(I.surface.engine,I);I._renderables.push(...e.renderables),e.dispose&&I._disposables.push(e.dispose)})}function JI(A,g){const I=A;if("entities"in g){const t=g;for(const i of t.entities)JI(A,i);if(t.clearColor&&(I.clearColor=t.clearColor),t.camera&&!I.camera&&(I.camera=t.camera),t.animationGroups?.length){const i=I.surface.engine,o=t.animationGroups;I.animationGroups.push(...o);const Q=r=>{for(const E of o)RiA(E,r,i)};t._beforeRenderHook=Q,I._beforeRender.push(Q)}t._sceneSetup?.(I,t);return}if("_gpu"in g&&"material"in g){const t=g;MiA(I,t),I.meshes.push(t);const i=t.material?t.material._buildGroup:void 0;if(i){let o=I._groups.get(i);o||(o=[],I._groups.set(i,o),I._built||I._deferredBuilders.push(async()=>{const Q=await i(I,o);I._renderables.push(...Q.renderables),o.o=Q.renderables,Q.updater&&I._uniformUpdaters.push(Q.updater),o.r=Q.rebuildSingle})),o.push(t),(I._built||o.r)&&QF(I,t)}}else"lightType"in g&&I.lights.push(g);const e=g.children;if(e?.length)for(const t of e)t.parent=g,JI(A,t)}function N6(A){const g=A;if(g._z)return;g._z=!0;const I=aF??=new WeakMap;I.set(g,()=>1),qQ(g.surface,g),(()=>{I.set(g,()=>{for(const t of g._meshDisposables.values())t.forEach(i=>i());for(const t of g._meshAuxDisposables.values())t.forEach(i=>i());return g._meshDisposables.clear(),g._meshAuxDisposables.clear(),g._disposables.splice(0).forEach(t=>t()),g._renderables.length=g._uniformUpdaters.length=0,1});for(const t of g._disposables)t();for(const t of g._meshDisposables.values())for(const i of t)i();g._meshDisposables.clear();for(const t of g._meshAuxDisposables.values())for(const i of t)i();g._meshAuxDisposables.clear();for(const t of g.meshes)n6(g,t)&&X1(t);g._groups.clear(),g.meshes.length=0,g._renderables.length=0,g._prePasses.length=0,g._pickSources.length=0,g._uniformUpdaters.length=0,g._beforeRender.length=0,g._deferredBuilders.length=0,g._disposables.length=0,g._materialSwapQueue.length=0,g.lights.length=0,g.animationGroups.length=0,g.shadowGenerators.length=0,g.camera=null})()}async function G6(A){const g=A;for(g._built||(g._materialSwapQueue.length=0);g._deferredBuilders.length;){const I=g._deferredBuilders.splice(0);await Promise.all(I.map(e=>e()))}await s6(g),aF?.get(g)?.()||(g._runtimeBuilds?._e(),g._renderableVersion++,g._built=!0),await g._rebuildHook?.(g)}let PR=null;function PiA(A){PR=A}async function F6(A){const g=A,I=g.surface;n3(I,g)||(await G6(A),g._renderables.sort(m6),await Promise.all(g._frameGraph._tasks.map(e=>e._preload?.())),PR&&await PR(g),g._frameGraph.build(),I._renderingContexts[0]&&(await Promise.resolve().then(()=>fgA)).configureSwapchainOverlayScene(I,g),aF?.get(g)?.()||xQ(I,g))}async function OiA(A){const g=A,I=g.surface;n3(I,g)||(await G6(A),g._renderables.sort(m6),await jiA(I.engine,g),await Promise.all(g._frameGraph._tasks.map(e=>e._preload?.())),PR&&await PR(g),g._frameGraph.build(),I._renderingContexts[0]&&(await Promise.resolve().then(()=>fgA)).configureSwapchainOverlayScene(I,g),aF?.get(g)?.()||xQ(I,g))}const m6=(A,g)=>A.order-g.order;async function jiA(A,g){if(g._frameGraph._tasks.some(e=>e.name==="shadow"))return;const{createShadowTask:I}=await Promise.resolve().then(()=>JLA);g._frameGraph._tasks.unshift(I(A,g))}function ViA(A){qQ(A.surface,A)}function S3(A,g,I,e){A[3]=0,A[7]=0,A[11]=0,A[12]=g.x,A[13]=g.y,A[14]=g.z,A[15]=1;let t=I.x-g.x,i=I.y-g.y,o=I.z-g.z;const Q=Math.sqrt(t*t+i*i+o*o);let r=0,E=0,n=0,s=0;if(Q>=1e-10){const l=1/Q;t*=l,i*=l,o*=l,r=e.y*o-e.z*i,E=e.z*t-e.x*o,n=e.x*i-e.y*t,s=Math.sqrt(r*r+E*E+n*n)}if(s<1e-10){A[0]=1,A[1]=0,A[2]=0,A[4]=0,A[5]=1,A[6]=0,A[8]=0,A[9]=0,A[10]=1;return}const c=1/s;r*=c,E*=c,n*=c,A[0]=r,A[1]=E,A[2]=n,A[4]=i*n-o*E,A[5]=o*r-t*n,A[6]=t*E-i*r,A[8]=t,A[9]=i,A[10]=o}const R3={x:0,y:1,z:0};function Di(A,g,I,e,t,i,o,Q,r,E,n,s){const c=i*i,l=o*o,D=Q*Q,p=i*o,y=i*Q,_=o*Q,u=r*i,f=r*o,h=r*Q;A[g]=(1-2*(l+D))*E,A[g+1]=2*(p+h)*E,A[g+2]=2*(y-f)*E,A[g+3]=0,A[g+4]=2*(p-h)*n,A[g+5]=(1-2*(c+D))*n,A[g+6]=2*(_+u)*n,A[g+7]=0,A[g+8]=2*(y+f)*s,A[g+9]=2*(_-u)*s,A[g+10]=(1-2*(c+l))*s,A[g+11]=0,A[g+12]=I,A[g+13]=e,A[g+14]=t,A[g+15]=1}function N3(A,g,I,e,t,i,o,Q,r,E){const n=se();return Di(n,0,A,g,I,e,t,i,o,Q,r,E),n}function no(){const A=se();return A[0]=1,A[5]=1,A[10]=1,A[15]=1,A}const b6=Symbol("wmState");function tQ(A,g){A[b6]=g}function K6(A){return A===null?null:A[b6]??null}function OR(A){K6(A)?._invalidate()}function lF(A,g,I){return A.x===0&&A.y===0&&A.z===0&&g.x===0&&g.y===0&&g.z===0&&g.w===1&&I.x===1&&I.y===1&&I.z===1?no():N3(A.x,A.y,A.z,g.x,g.y,g.z,g.w,I.x,I.y,I.z)}function so(A){let g=0,I=-1,e=null;const t=se();let i=null,o=null;const Q=[];function r(){e=null,g++;for(const s of Q)s._invalidate()}function E(){const s=i.worldMatrixVersion;s!==I&&(I=s,r())}const n={get parent(){return i},set parent(s){s!==i&&(o!==null&&o._removeChild(n),i=s,o=K6(s),o!==null&&o._addChild(n),I=-1,r())},markLocalDirty(){r()},getWorldMatrix(){if(o===null&&i!==null&&E(),e!==null)return e;const s=A();if(i!==null){const c=i.worldMatrix;Oe(t,0,c,0,s,0),e=t}else e=s;return e},getWorldMatrixVersion(){return o===null&&i!==null&&E(),g},_invalidate(){r()},_addChild(s){Q.push(s)},_removeChild(s){const c=Q.indexOf(s);c>=0&&Q.splice(c,1)}};return n}class Ht{_x;_y;_z;_onDirty;constructor(g,I,e,t){this._x=g,this._y=I,this._z=e,this._onDirty=t}get x(){return this._x}set x(g){this._x!==g&&(this._x=g,this._onDirty())}get y(){return this._y}set y(g){this._y!==g&&(this._y=g,this._onDirty())}get z(){return this._z}set z(g){this._z!==g&&(this._z=g,this._onDirty())}set(g,I,e){this._x=g,this._y=I,this._z=e,this._onDirty()}copyFrom(g){this.set(g.x,g.y,g.z)}toArray(g,I=0){g[I]=this._x,g[I+1]=this._y,g[I+2]=this._z}}function k6(A,g,I,e){function t(){const s=Math.cos(n.alpha),c=Math.sin(n.alpha),l=Math.cos(n.beta);let D=Math.sin(n.beta);return D===0&&(D=1e-4),{x:n.target.x+n.radius*s*D,y:n.target.y+n.radius*l,z:n.target.z+n.radius*c*D}}const i=se();function o(){return S3(i,t(),n.target,R3),i}const Q=so(o),r=()=>Q.markLocalDirty(),E={alpha:A,beta:g,radius:I},n={alpha:0,beta:0,radius:0,target:new Ht(e.x,e.y,e.z,r),fov:.8,nearPlane:.1,farPlane:1e3,children:[],inertia:.9,panningInertia:.9,angularSensibility:1e3,panningSensibility:50,wheelPrecision:3,inertialAlphaOffset:0,inertialBetaOffset:0,inertialRadiusOffset:0,inertialPanningX:0,inertialPanningY:0,_viewCache:se(),_projCache:se(),_vpCache:se(),get parent(){return Q.parent},set parent(s){Q.parent=s},get worldMatrix(){return Q.getWorldMatrix()},get worldMatrixVersion(){return Q.getWorldMatrixVersion()}};for(const s of["alpha","beta","radius"])Object.defineProperty(n,s,{get:()=>E[s],set:c=>{E[s]!==c&&(E[s]=c,r(),n._clampToLimits?.())},configurable:!0,enumerable:!0});return tQ(n,Q),n}function U6(){return{minX:1/0,minY:1/0,minZ:1/0,maxX:-1/0,maxY:-1/0,maxZ:-1/0}}function WiA(A,g,I,e){const t=I-e,i=I+e,o=g===0?"minX":g===1?"minY":"minZ",Q=g===0?"maxX":g===1?"maxY":"maxZ";t<A[o]&&(A[o]=t),i>A[Q]&&(A[Q]=i)}function L6(A,g){const I=g.boundMin,e=g.boundMax;if(!I||!e)return;if(g._expandWorldBounds!==void 0){g._expandWorldBounds(A,g);return}const t=g.worldMatrix,i=[(I[0]+e[0])*.5,(I[1]+e[1])*.5,(I[2]+e[2])*.5],o=[(e[0]-I[0])*.5,(e[1]-I[1])*.5,(e[2]-I[2])*.5];for(let Q=0;Q<3;Q++){let r=t[12+Q],E=0;for(let n=0;n<3;n++){const s=t[n*4+Q];r+=s*i[n],E+=Math.abs(s)*o[n]}WiA(A,Q,r,E)}}function CQ(A,g,I){return{x:A,y:g,z:I}}function ziA(A){let g=1/0,I=1/0,e=1/0,t=-1/0,i=-1/0,o=-1/0;const Q=U6();for(const p of A.meshes)p.visible!==!1&&L6(Q,p);g=Q.minX,I=Q.minY,e=Q.minZ,t=Q.maxX,i=Q.maxY,o=Q.maxZ;const r=t-g,E=i-I,n=o-e;let c=Math.sqrt(r*r+E*E+n*n)*1.5,l=CQ(g+r*.5,I+E*.5,e+n*.5);(!isFinite(c)||c===0)&&(c=1,l=CQ(0,0,0));const D=k6(-(Math.PI/2),Math.PI/2,c,l);return D.nearPlane=c*.01,D.farPlane=c*1e3,A.camera=D,D}function ct(A,g){if("entities"in g){const I=g;for(const o of I.entities)ct(A,o);I.camera&&A.camera===I.camera&&(A.camera=null);const e=I.animationGroups;if(e?.length)for(const o of e)jR(A.animationGroups,o);const t=I._beforeRenderHook;t&&(jR(A._beforeRender,t),I._beforeRenderHook=void 0);const i=I._sceneCleanups;if(i){const o=i.get(A);o&&(jR(A._disposables,o),i.delete(A),A._z||o())}return}if("_gpu"in g&&"material"in g){eoA(A,g),v6(A,g);return}if("lightType"in g){jR(A.lights,g);const I=g.shadowGenerator;I?Y6(A,I):J6(A)}else"fov"in g&&"nearPlane"in g?A.camera===g&&(A.camera=null):"_shadowType"in g&&"_light"in g&&Y6(A,g);IoA(g),v6(A,g)}function ZiA(A,g){for(const I of g){const e=I.p;if(e){e._disposed=!0;const t=e._owner;if(t){const i=t.indexOf(e);i>=0&&t.splice(i,1),e._owner=void 0}}}XiA(A,()=>{for(const I of g)I()})}function XiA(A,g){if(A._z){g();return}G1(A.surface.engine,g)}function Y6(A,g){jR(A.shadowGenerators,g);const I=g._light;I&&I.shadowGenerator===g&&(I.shadowGenerator=void 0),J6(A);const e=g._shadowTaskState;e&&(g._shadowTaskState=void 0,$iA(A,()=>e._task.dispose()))}function $iA(A,g){A._pendingTopologyRetirements||(A._pendingTopologyRetirements=[],A._disposables.push(()=>AoA(A))),A._pendingTopologyRetirements.push(g)}function AoA(A){const g=A._pendingTopologyRetirements?.splice(0);if(!g?.length)return;const I=()=>{for(const t of g)try{t()}catch{}},e=A.surface.engine._device;e?e.queue.onSubmittedWorkDone().then(I,I):I()}function J6(A){A._lightListVersion=(A._lightListVersion??0)+1,A._built&&(A._rebuildHook=goA)}async function goA(A){const{rebuildSceneRenderables:g}=await Promise.resolve().then(()=>JP);await g(A)}function jR(A,g){const I=A.indexOf(g);I>=0&&A.splice(I,1)}function IoA(A){A&&typeof A=="object"&&"parent"in A&&(A.parent=null)}function v6(A,g){const I=g.children;if(I?.length)for(const e of[...I])ct(A,e)}function eoA(A,g){for(const E of A._frameGraph._tasks)E._removeMesh?.(g);const I=A._meshDisposables.get(g);let e=!1;const t=[];I&&(e=!0,t.push(...I),A._meshDisposables.delete(g));const i=A._meshAuxDisposables.get(g);i&&(e=!0,t.push(...i),A._meshAuxDisposables.delete(g));const o=A.meshes.indexOf(g);o>=0&&(A.meshes.splice(o,1),e=!0);const Q=A._renderables.findIndex(E=>E.mesh===g);Q>=0&&(A._renderables.splice(Q,1),e=!0),e&&A._renderableVersion++;for(const E of A._groups.values()){const n=E.indexOf(g);n>=0&&E.splice(n,1)}const r=A._materialSwapQueue.indexOf(g);r>=0&&A._materialSwapQueue.splice(r,1),A._runtimeBuilds?.remove(g),g.parent=null;for(const E of A._frameGraph._tasks)"_renderables"in E&&qR(E,g);n6(A,g)&&t.push(()=>X1(g)),t.length&&ZiA(A,t)}function ke(A,g){H6(A,g)&&cC()}function H6(A,g){let I=A.visible!==g;A.visible=g;const e=A.children;for(let t=0;t<e.length;t++)H6(e[t],g)&&(I=!0);return I}function toA(A,g){const I=g.fog;I&&(A[80]=I.mode,A[81]=I.start,A[82]=I.end,A[83]=I.density,A[84]=I.color[0],A[85]=I.color[1],A[86]=I.color[2])}function CoA(A,g){const I=g.clipPlane;I&&(A[88]=I[0],A[89]=I[1],A[90]=I[2],A[91]=I[3])}function ioA(A,g){A[36]=g._environmentRotation??0;const I=g._envTextures?.sphericalHarmonics;I&&A.set(I,40)}function DF(A,g){const I=A._sceneUboContributors??=[];I.includes(g)||I.push(g)}function T6(A){for(const g of A._frameGraph._tasks)g._sceneUboCacheKey&&(g._sceneUboCacheKey.length=0)}function ooA(A,g){A.fog=g,DF(A,toA)}function BoA(A,g){A.clipPlane=g,DF(A,CoA)}function pF(A){DF(A,ioA)}const x6=/textureSampleLevel\(\s*([^,]+?)\s*,\s*([^,]+?)\s*,\s*([^,]+?)\s*,\s*0(?:\.0?)?\s*\)\.rgb/,QoA=(A,g)=>{const I=A.match(x6),e=I?.[1],t=I?.[2],i=I?.[3];if(!e||!t||!i)throw new Error("Environment blur: skybox cubemap sample not found.");const Q=`clamp(scene._envPad1*log2(f32(textureDimensions(${e}).x))*${g==="dds"?"0.8":"scene.vImageInfos.z+scene._envPad2"},0.0,f32(textureNumLevels(${e})-1))`;return A.replace(x6,`textureSampleLevel(${e},${t},${i},0.0+(${Q})).rgb`)},roA=Object.freeze(Object.defineProperty({__proto__:null,_apply:QoA},Symbol.toStringTag,{value:"Module"})),EoA="struct a{viewProjection:mat4x4<f32>,view:mat4x4<f32>,vEyePosition:vec4<f32>,envRotationY:f32,_envPad0:f32,_envPad1:f32,_envPad2:f32,vSphericalL00:vec4<f32>,vSphericalL1_1:vec4<f32>,vSphericalL10:vec4<f32>,vSphericalL11:vec4<f32>,vSphericalL2_2:vec4<f32>,vSphericalL2_1:vec4<f32>,vSphericalL20:vec4<f32>,vSphericalL21:vec4<f32>,vSphericalL22:vec4<f32>,vImageInfos:vec4<f32>,vFogInfos:vec4<f32>,vFogColor:vec4<f32>,clipPlane:vec4<f32>}@group(0) @binding(0) var<uniform> scene:a;",n1=EoA;function q6(A,g,I){const e=A._environmentSkyboxShaderPatchLoaders??=[];e[g]=I,A._environmentSkyboxShaderComposer??=async(t,i)=>{t=i==="hdr"?n1+t:t;for(const o of e.slice())o&&(t=(await o())._apply(t,i));return t}}const noA=()=>roA;function soA(A,g){A[38]=g._environmentBlur??0,A[39]=g._envTextures?.lodGenerationOffset??0}function aoA(A,g){A._environmentBlur=g,q6(A,1,noA),DF(A,soA),T6(A)}const coA=()=>Promise.resolve().then(()=>HLA);function loA(A,g){pF(A),A._environmentRotation=g,q6(A,0,coA),T6(A)}function P6(A){const g=A.camera;if(!g)return{x:0,y:0,z:0};const I=g.worldMatrix;return{x:I[12],y:I[13],z:I[14]}}function DoA(A){return A.camera?A.camera.worldMatrixVersion:0}function poA(A,g){const e=g.camera?.worldMatrix;if(!e)return;const t=e[12],i=e[13],o=e[14];let Q=0;for(const r of g.lights){if(Q>=HI)break;if(!r._writeLightUbo)continue;const E=4+Q*f3,n=A[E+3];if(n===0||n===2){const s=r.worldMatrix;A[E]=s[12]-t,A[E+1]=s[13]-i,A[E+2]=s[14]-o}Q++}}function yoA(A,g,I){let e=-1;return()=>{const t=g.camera?g.camera.worldMatrixVersion:-1;t!==e&&(I(),e=t),A()}}const _oA=Object.freeze(Object.defineProperty({__proto__:null,applyLightFoOffset:poA,getFloatingOriginOffset:P6,lightFoVersion:DoA,wrapRenderableForFO:yoA},Symbol.toStringTag,{value:"Module"})),uoA=[A=>`AnimationGroup "${A}" is already attached to another AnimationManager`,()=>"Animation task category is required.",()=>"AnimationTask is already attached to another AnimationManager",()=>"AnimationManager autonomous mode requires requestAnimationFrame",A=>`Animation weight fade duration must be a finite positive number, got ${A}`,A=>`Animation weight must be a finite number between 0 and 1, got ${A}`,A=>`Animation weight must be a finite number between 0 and 1, got ${A}`,()=>"createPropertyAnimationClip requires at least one track",()=>"Animation play range must have toTime greater than fromTime",A=>`Animation track "${A}" requires at least one key`,A=>`Animation track "${A}" requires a positive frameRate`,A=>`Animation track "${A}" key times must be monotonically increasing`,A=>`Animation track "${A}" requires at least one key`,A=>`Animation key for "${A}" must provide exactly one of time or frame`,A=>`Animation key for "${A}" must have a non-negative time`,(A,g)=>`Animation key for "${A}" expected ${g} values`,(A,g)=>`Animation key for "${A}" expected ${g} values`,A=>`Invalid animation property path "${A}"`,(A,g)=>`Animation property path "${A}" could not resolve "${g}"`,(A,g)=>`Animation property path "${A}" could not resolve "${g}"`,A=>`Animation property path "${A}" reached a non-object value`,(A,g)=>`Animation property path "${A}" has unsupported vector size ${g}`,(A,g)=>`Animation property path "${A}" could not resolve component "${g}"`,()=>"Additive animation reference must use either referenceFrame or referenceTime, not both",A=>`Additive animation reference time must be a finite non-negative number, got ${A}`,()=>"Weighted glTF animation requires an AnimationManager engine",()=>"Weighted glTF animation requires an AnimationManager engine",()=>"Weighted animation channels for the same property must use the same value size",()=>"Audio engine media streams require a real-time AudioContext.",()=>"Unable to get a 2D context from the visualizer canvas.",()=>"setEffectUniforms: wrapper has no uniform binding.",A=>`setEffectUniforms: unknown uniform binding "${A}".`,A=>`setEffectTexture: unknown texture binding "${A}".`,A=>`EffectRenderTask "${A}" executed before record().`,A=>`EffectRenderer "${A}" recorded before registerEffectRenderer().`,A=>`createEffectWrapper: duplicate binding ${A}.`,(A,g)=>`Effect "${A}" missing uniform binding ${g}.`,(A,g)=>`Effect "${A}" missing texture binding ${g}.`,(A,g)=>`Effect "${A}" missing texture for sampler binding ${g}.`,(A,g,I)=>`writeUniformSlot: ${A} bytes exceeds uniform binding ${g} size ${I}.`,(A,g)=>`setUniformEffectUniforms: ${A} bytes exceeds uniform size ${g}.`,A=>`UniformEffectRenderTask "${A}" executed before record().`,()=>"Device-lost recovery capture requires an enabled recovery coordinator",()=>"WebGPU adapter not available during device recovery",A=>`WebGPU device recovery missing required features: ${A}`,()=>"forceWebGpuDeviceLossForTesting requires a device-lost recovery handler to be enabled first",()=>"WebGPU adapter not available",()=>"Babylon Lite: useFloatingOrigin requires useHighPrecisionMatrix on the engine.",()=>"WebGPU context not available",()=>"Babylon Lite: disposeSurface cannot dispose the engine's primary surface \u2014 use disposeEngine instead.",A=>`Flow Graph Editor: unsupported block class ${A}`,()=>"Flow Graph Editor: expected a serialized object",A=>`Flow Graph Editor: graph ${A} has no allBlocks array`,()=>"KHR_interactivity: duplicate type signatures",A=>`KHR_interactivity: unsupported type signature ${A}`,A=>`KHR_interactivity: node references missing declaration #${A}`,(A,g)=>`KHR_interactivity: variable ${A} references missing type #${g}`,(A,g,I)=>`KHR_interactivity: event ${A} value ${g} references missing type #${I}`,(A,g,I)=>`KHR_interactivity: ${A} node ${g} references invalid variable #${I}`,A=>`KHR_interactivity: variable/set node ${A} has invalid variable indices`,(A,g)=>`KHR_interactivity: variable/set node ${A} is missing input for variable #${g}`,(A,g)=>`KHR_interactivity: variable/set node ${A} input for variable #${g} has the wrong type`,A=>`KHR_interactivity: node ${A} is missing its pointer configuration`,(A,g)=>`KHR_interactivity: node ${A} is missing pointer parameter ${g}`,(A,g)=>`KHR_interactivity: node ${A} pointer parameter ${g} has the wrong type`,(A,g)=>`KHR_interactivity: ${A} node ${g} uses a reserved pointer parameter`,(A,g,I)=>`KHR_interactivity: ${A} node ${g} references invalid type #${I}`,(A,g)=>`KHR_interactivity: node ${A} references invalid event #${g}`,(A,g,I)=>`KHR_interactivity: ${A} node ${g} is missing required ${I} input`,(A,g)=>`KHR_interactivity: variable/interpolate node ${A} references invalid variable #${g}`,A=>`KHR_interactivity: variable/interpolate node ${A} can only use slerp with float4`,(A,g)=>`KHR_interactivity: pointer/interpolate node ${A} references invalid type #${g}`,(A,g,I)=>`KHR_interactivity: ${A} node ${g} cannot interpolate ${I}`,(A,g)=>`KHR_interactivity: node ${A} references missing producer node #${g}`,(A,g,I)=>`KHR_interactivity: node ${A} flow ${g} targets missing node #${I}`,A=>`invalid RFC 6901 escape in pointer segment ${A}`,A=>`literal pointer brackets must be doubled in ${A}`,()=>"JSON Pointer Templates must be absolute",A=>`duplicate pointer parameter ${A}`,A=>`CopyToTextureTask "${A}": either targetTexture or resolveTexture must be provided.`,A=>`CopyToTextureTask "${A}": sourceTexture cannot be the engine scRT because its GPU texture changes every frame.`,A=>`CopyToTextureTask "${A}": sourceTexture has no color texture. The source must be built before this task records.`,(A,g)=>`CopyToTextureTask "${A}": resolveTexture requires a multisampled sourceTexture (got sampleCount=${g}).`,(A,g)=>`CopyToTextureTask "${A}": resolveTexture must be single-sample (got sampleCount=${g}).`,(A,g,I,e,t)=>`CopyToTextureTask "${A}": sourceTexture (${g}x${I}) and resolveTexture (${e}x${t}) must have matching dimensions.`,(A,g)=>`CopyToTextureTask "${A}": resolveTexture requires a multisampled targetTexture (got sampleCount=${g}).`,(A,g)=>`CopyToTextureTask "${A}": resolveTexture must be single-sample (got sampleCount=${g}).`,(A,g,I)=>`CopyToTextureTask "${A}": resolveTexture format (${g}) must match targetTexture format (${I}).`,()=>"CopyToTextureTask: targetTexture has no color format.",A=>`DepthResolveTask "${A}": sourceTexture has no depth attachment.`,A=>`DepthResolveTask "${A}": sourceTexture must be multisampled (sampleCount > 1).`,A=>`DepthResolveTask "${A}": targetTexture has no depth format.`,()=>"FrameGraph target does not expose a frame graph.",A=>`addRenderPass("${A}"): no task is currently recording (called outside Task.record?)`,A=>`buildFrameGraphTask("${A}"): task is not registered in this graph.`,()=>"GeometryRendererTask: textureDescriptions must contain at least one entry.",A=>`GeometryRendererTask: textureDescriptions length ${A} exceeds the WebGPU max of 8 color attachments.`,A=>`GeometryRendererTask: unknown texture type ${A}.`,(A,g)=>`GeometryRendererTask: depthTexture sampleCount (${A}) must match samples (${g}).`,(A,g)=>`GeometryRendererTask: targetTexture sampleCount (${A}) must match samples (${g}).`,()=>"GeometryRendererTask: targetTexture must have a format.",()=>"overdraw probe: this device has no timestamp-query feature",()=>"overdraw probe: tasks that load existing depth cannot be measured with a fresh-depth replay",()=>"overdraw probe: task render target has no size (has the task rendered yet?)",()=>"overdraw probe: task target has no color+depth signature to replicate",()=>"overdraw probe: task has no draw bindings (has the task rendered yet?)",()=>"overdraw probe: timestamp readback produced no usable samples",A=>`PostProcessTask "${A}": sourceTexture has no color texture. Render the source to an offscreen RenderTarget before post-processing.`,A=>`PostProcessTask "${A}": multisampled source textures are not supported. Use a sampleCount: 1 source RenderTarget.`,A=>`PostProcessTask "${A}": outputTexture must have a format.`,(A,g)=>`PostProcessTask "${A}": extra texture ${g} has no color texture.`,A=>`PostProcessTask "${A}": sourceTexture must have a format.`,()=>"buildClusteredLightGpuState: scene.camera is required",()=>"ClusteredLightContainer: light count cannot grow after GPU state creation.",()=>"Device-lost Scene recovery requires environment loading after recovery was enabled",(A,g,I)=>`Device-lost Scene recovery could not refetch '${A}' (${g} ${I}).`,(A,g)=>`${A}: image ${g} not found`,(A,g)=>`${A}: bufferView ${g} not found`,(A,g,I)=>`${A}: failed to load image ${g} ${I}`,A=>`${A}: image has neither bufferView nor uri`,(A,g)=>`${A}: strided accessor uses unsupported component type: ${g}`,(A,g,I)=>`${A}: strided accessor ${g} uses unsupported component type: ${I}`,(A,g,I)=>`${A}: invalid accessor stride ${g} for accessor ${I}`,A=>`glTF camera ${A}: unsupported projection`,()=>"glTF camera nodes require non-zero uniform scale",A=>`EXT_mesh_gpu_instancing: accessor count mismatch on node ${A}`,A=>`EXT_meshopt_compression: compressed source buffer ${A} is not buffer 0 (unsupported)`,A=>`EXT_meshopt_compression: uncompressed bufferView in buffer ${A} is not buffer 0 (unsupported)`,A=>`glTF sparse: unsupported componentType ${A}`,A=>`glTF sparse: unsupported index componentType ${A}`,A=>`glTF sparse: unsupported value componentType ${A}`,()=>"glTF sparse: indices.componentType is required",(A,g)=>`glTF sparse: index ${A} out of range for accessor of count ${g}`,()=>"Not a valid GLB file",()=>"First GLB chunk is not JSON",()=>"Second GLB chunk is not BIN",(A,g)=>`Failed to load image: ${A} ${g}`,()=>"loadGltf: baseless input can't resolve relative URI; use self-contained GLB or URL with base.",A=>`Unsupported component type: ${A}`,()=>"Image has neither bufferView nor uri",(A,g)=>`Failed to load image: ${A} ${g}`,()=>"Image has neither bufferView nor uri",()=>"Invalid HDR: missing #? signature",A=>`Unsupported HDR format: ${A}`,A=>`Invalid HDR resolution: ${A}`,()=>"Invalid HDR: RLE scanline width does not match image",()=>"Invalid HDR: truncated RLE scanline",()=>"Invalid HDR: zero-length RLE packet",()=>"Invalid HDR: RLE run exceeds scanline",()=>"Invalid HDR: RLE literal exceeds scanline",()=>"Invalid HDR: truncated scanline",A=>`loadSOG: decoded WebP has zero dimensions (input size ${A})`,()=>"loadSOG: failed to acquire 2D context for WebP decode",()=>"loadSOG: means.mins/means.maxs must be arrays",()=>"loadSOG: SOG v2 missing scales codebook",()=>"loadSOG: scales.mins/maxs must be arrays for SOG v1",()=>"loadSOG: SOG v2 missing sh0 codebook",()=>"loadSOG: sh0.mins/maxs must be arrays for SOG v1",A=>`loadSOG: invalid quaternion mode ${A}`,()=>"loadSOG: SOG v2 missing shN codebook",(A,g)=>`loadSOG: HTTP ${A} for ${g}`,()=>"loadSOG: meta.json not found in archive",A=>`loadSOG: missing image '${A}' inside archive`,(A,g)=>`loadSplat: HTTP ${A} for ${g}`,A=>`loadSplat: failed to parse PLY at ${A} (unsupported property layout)`,()=>"loadSPZ: file too short to contain header",(A,g)=>`loadSPZ: unsupported SPZ stream (magic=0x${A} version=${g})`,(A,g)=>`loadSPZ: HTTP ${A} for ${g}`,()=>"Invalid compressed PLY: packed vertex properties require chunk metadata for every vertex",()=>"zip: EOCD record not found",()=>"zip: ZIP64 archives are not supported",A=>`zip: bad central directory signature at offset ${A}`,()=>"zip: encrypted entries are not supported",()=>"zip: ZIP64 archives are not supported",A=>`zip: bad local file header signature at offset ${A}`,(A,g)=>`zip: unsupported compression method ${A} for entry '${g}'`,(A,g,I)=>`zip: entry '${A}' decompressed size mismatch (got ${g}, expected ${I})`,A=>`LineMaterial "${A}" requires thin-instance data`,()=>"createLineMaterial requires useThinInstances when useThinInstanceColors is enabled",(A,g)=>`NodeMaterial: cannot pick common numeric type from ${A} and ${g}`,A=>`NodeMaterial: AmbientOcclusionBlock "${A}" requires an ImageSourceBlock source`,()=>"BiPlanarBlock: texture projection is supported only in the fragment stage",A=>`NodeMaterial: ColorSplitterBlock (id=${A}) has no connected input`,A=>`NodeMaterial: ColorSplitterBlock has no output "${A}"`,A=>`NodeMaterial: unknown CurveBlock curveType ${A}`,A=>`NodeMaterial: CurveBlock does not support ${A}`,()=>"NodeMaterial: FragDepthBlock requires `depth` or both `worldPos` and `viewProjection` inputs",A=>`NodeMaterial: HeightToNormalBlock "${A}" requires worldTangent when generateInWorldSpace is false`,A=>`InputBlock: unknown mesh attribute "${A}"`,(A,g)=>`InputBlock: unsupported systemValue ${A} on block "${g}"`,A=>`LoopBlock "${A}": index can only be read while emitting the loop body`,A=>`LoopBlock "${A}": loopID can only be consumed by StorageReadBlock/StorageWriteBlock`,(A,g)=>`LoopBlock "${A}": unsupported output "${g}"`,A=>`NodeMaterial: MatrixSplitterBlock has no output "${A}"`,A=>`NodeMaterial: unsupported matrix block "${A}"`,()=>"NodeMaterial: NLerpBlock requires a vector left/right input; Babylon.js emits normalize(mix(...)) for this block",()=>"NodeMaterial: PBR-MR core emitter cannot emit optional PBR feature code",()=>"NodeMaterial: PBR-MR core helper cannot emit optional PBR feature code",A=>`NodeMaterial: RandomNumberBlock requires a vector seed so Babylon.js getRand(seed.xy) can be emitted; got ${A}`,A=>`ReflectionTextureBaseBlock "${A}" is an abstract compatibility block and cannot be emitted directly.`,A=>`ReflectionTextureBlock: coordinatesMode ${A} not supported (only EQUIRECTANGULAR_MODE=7)`,A=>`NodeMaterial: ReplaceColorBlock requires a vector/color value; got ${A}`,(A,g)=>`StorageReadBlock "${A}": unsupported output "${g}"`,A=>`StorageReadBlock "${A}": loopID input is not connected`,(A,g)=>`StorageReadBlock "${A}": loop ${g} is not active`,()=>"NodeMaterial: TBNBlock object output is not supported; use row0/row1/row2 outputs",A=>`NodeMaterial: TeleportOutBlock (id=${A}) has no entryPoint`,(A,g)=>`NodeMaterial: TeleportOutBlock (id=${A}) points to missing TeleportInBlock ${g}`,()=>"TriPlanarBlock: texture projection is supported only in the fragment stage",A=>`NodeMaterial: VectorSplitterBlock (id=${A}) has no connected input`,A=>`NodeMaterial: VectorSplitterBlock has no output "${A}"`,A=>`NodeMaterial: WaveBlock does not support ${A}`,A=>`NodeMaterial: unknown WaveBlock kind ${A}`,(A,g,I)=>`NodeMaterial: cannot cast ${A} to ${g} for expression \`${I}\``,(A,g)=>`${A}: unsupported BJS connection point type 0x${g}`,(A,g,I)=>`NodeMaterial: block "${A}" (id=${g}) has no input "${I}"`,(A,g,I)=>`NodeMaterial: block "${A}" (id=${g}) input "${I}" is not connected`,(A,g,I)=>`NodeMaterial: dangling connection ${A}.${g} -> block ${I}`,A=>`NodeMaterial: no emitter loaded for block "${A}"`,()=>"NodeMaterial: only vertex->fragment varyings are supported",A=>`NodeMaterial: fragment root block ${A} not found`,A=>`NodeMaterial: no emitter for fragment root "${A}"`,A=>`NodeMaterial: vertex root block ${A} not found`,A=>`NodeMaterial: no emitter for vertex root "${A}"`,()=>"NodeMaterial: PBR/Reflection block requires scene environment but scene._envTextures is unset. Call loadEnvironment() before registerScene().",()=>"node-geometry view does not support scene group building",()=>"NodeMaterial geometry view: graph has no GeometryTextureOutputBlock",()=>"NodeMaterial geometry view: morph / env / shadow inputs are not supported in the geometry pass",()=>"node-geometry: render target has no color attachments",(A,g)=>`NodeMaterial geometry view: texture binding "${A}" not set. Provide it via material.inputs["${g}"].texture before the first render.`,()=>"NodeMaterial geometry view: NORMALIZED_VIEW_DEPTH requested but no geometry-params UBO was provided by the task.",()=>"NodeMaterial geometry view: emitColor (real-color target) is not supported \u2014 omit targetTexture on the geometry task.",()=>"NodeMaterial: graph has no FragmentOutputBlock",()=>"NodeMaterial: advanced PBR-MR helper request must be emitted by the full PBR-MR block",()=>"NodeMaterial: invalid source \u2014 expected `.blocks` array",A=>`NodeMaterial: block missing numeric id (name=${A})`,(A,g)=>`NodeMaterial: cycle detected through block ${A} (${g})`,A=>`NodeMaterial: dangling reference to block ${A}`,A=>`NodeMaterial: helper key "${A}" registered with conflicting source bodies`,A=>`NodeMaterial: no advanced extension emitter registered for block "${A}"`,A=>`NodeMaterial: no compatibility extension emitter registered for block "${A}"`,A=>`NodeMaterial: no math extension emitter registered for block "${A}"`,A=>`NodeMaterial: no procedural extension emitter registered for block "${A}"`,(A,g)=>`NodeMaterial: texture binding "${A}" not set. Provide it via options.textures or material.inputs["${g}"].texture before the first render.`,A=>`NodeMaterial: material requires shadow generator #${A} but none was supplied to parseNodeMaterialFromSnippet({ shadowGenerators }).`,A=>`NodeMaterial: unsupported attribute "${A}"`,(A,g)=>`NodeMaterial: snippet fetch failed (${A}) for ${g}`,A=>`NodeMaterial: snippet "${A}" has no jsonPayload`,A=>`NodeMaterial: snippet "${A}" has no nodeMaterial`,(A,g)=>`[babylon-lite] ${A} must contain three finite${g} values`,A=>`[babylon-lite] ${A} must be finite and positive`,A=>`[babylon-lite] local probe ${A} influenceInnerRadius must be finite, non-negative, and no larger than influenceOuterRadius`,A=>`[babylon-lite] local probe ${A} inner influence box must be non-negative and contained by the outer influence box`,A=>`[babylon-lite] local probe ${A} angleRadians must be finite`,A=>`[babylon-lite] local probe ${A} debugColor must contain three finite values from 0 to 1`,()=>"[babylon-lite] local probe cubemap dimensions must differ only by power-of-two mip levels",()=>"[babylon-lite] local probe voxelGrid.cellSize must be finite and positive",()=>"[babylon-lite] local probe voxelGrid.maximum must be greater than minimum on every axis",()=>"[babylon-lite] local probe voxel grid dimensions are too large",()=>"[babylon-lite] local probe voxel grid dimensions are too large",(A,g,I,e,t)=>`[babylon-lite] local probe voxel (${A}, ${g}, ${I}) intersects ${e} probes, exceeding maxCandidates ${t}`,()=>"[babylon-lite] local probe cubemaps require COPY_SRC usage; call enablePbrLocalCubemap() before loading DDS or HDR probe environments, or create custom probe textures with COPY_SRC",()=>"[babylon-lite] local probe cubemaps must be square six-face textures with one shared format",()=>"[babylon-lite] local probe cubemaps have no common mip range",(A,g)=>`[babylon-lite] local probe set has ${A} probes, but this device supports at most ${g} cube-array probes`,(A,g)=>`[babylon-lite] local probe UBO requires ${A} bytes, but this device supports ${g}`,A=>`[babylon-lite] local probe voxel grid requires ${A} bytes, exceeding this device's storage-buffer limits`,A=>`[babylon-lite] local probe sets require 1..${A} probes`,()=>"Environment rotation: skybox direction declaration not found.",(A,g)=>`${A}: expected to rewrite 1 occurrence, rewrote ${g}`,A=>`local probe array _postCompose: expected to rewrite 1 voxel-grid binding declaration, rewrote ${A}`,A=>`local probe array _postCompose: expected to rewrite 1 cube-array binding declaration, rewrote ${A}`,A=>`local cubemap _postCompose: expected to rewrite 1 clearcoat reflection direction, rewrote ${A}`,A=>`local cubemap _postCompose: expected to rewrite 1 clearcoat radiance sample, rewrote ${A}`,A=>`local cubemap _postCompose: expected to rewrite 1 sheen radiance sample, rewrote ${A}`,A=>`local cubemap _postCompose: expected to rewrite 1 reflection direction, rewrote ${A}`,()=>"local cubemap _postCompose: expected at least 1 environment LOD scale rewrite",A=>`local cubemap _postCompose: expected to rewrite 1 base radiance sample, rewrote ${A}`,A=>`[babylon-lite] local cubemap could not replace the scene ${A} binding`,()=>"PBR transmission requires a frame-graph refraction texture.",()=>"composePbrGeometryShader: PBR fragment signature mismatch \u2014 _noColorOutput/_esmShadowOutput should be off",()=>"composePbrGeometryShader: alpha-block return statement not found \u2014 template changed?",()=>"pbr-geometry view does not support scene group building",()=>"buildPbrGeometryRenderable: scene has no PBR context. Ensure regular PBR meshes have been built before recording the geometry task.",()=>"pbr-geometry: render target has no color attachments",A=>`[babylon-lite] local cubemap maxCandidates is already ${A} and cannot be changed after initialization`,A=>`[babylon-lite] local cubemap maxCandidates must be an integer from 1 to ${A}`,()=>"setShadowCasterMaterial: the caster chain must not cycle back to the source material",()=>"Async ShaderMaterial pipeline preparation could not capture the synchronous descriptor.",(A,g)=>`ShaderMaterial: ${A} name "${g}" is not a valid WGSL identifier.`,()=>"ShaderMaterial: vertexSource and fragmentSource must be non-empty WGSL strings.",A=>`ShaderMaterial: unsupported attribute "${A}". Supported attributes: position, normal, uv, uv2, tangent, color, joints, weights, joints1, weights1.`,A=>`ShaderMaterial: duplicate attribute "${A}".`,()=>'ShaderMaterial: "position" attribute is required for mesh rendering.',A=>`ShaderMaterial: define "${A}" must be a boolean or number.`,()=>"ShaderMaterial: `transmissive` requires `needAlphaBlending` (the surface composites over the grabbed opaque scene color).",A=>`ShaderMaterial: custom uniform "${A}" must use an explicit typed declaration.`,(A,g)=>`ShaderMaterial: unsupported uniform type "${A}" for "${g}".`,(A,g)=>`ShaderMaterial: duplicate generated identifier "${A}" while adding ${g}.`,(A,g,I,e)=>`ShaderMaterial: uniform "${A}" of type ${g} expects ${I} value(s), got ${e}.`,A=>`ShaderMaterial: uniform "${A}" was not declared.`,(A,g,I,e)=>`ShaderMaterial: uniform "${A}" of type ${g} expects ${I} value(s), got ${e}.`,A=>`ShaderMaterial: sampler "${A}" was not declared.`,A=>`ShaderMaterial: sampler "${A}" expects a depth Texture2D.`,A=>`ShaderMaterial: sampler "${A}" cannot use a depth Texture2D.`,A=>`ShaderMaterial: storage buffer "${A}" was not declared.`,()=>"setShaderStorageBuffer requires a StorageBuffer created by createStorageBuffer; raw GPUBuffer is not supported.",A=>`ShaderMaterial: storage buffer "${A}" has been disposed.`,()=>"setShaderStorageBuffer requires a live StorageBuffer created by createStorageBuffer.",A=>`ShaderMaterial: sampler "${A}" has no Texture2D. Call setShaderTexture() before rendering.`,A=>`ShaderMaterial storage "${A}" is invalid.`,()=>"Standard UV transform _bind requires the scene argument from the Standard bind-group builder",()=>"composeStandardGeometryShader: standard fragment signature mismatch \u2014 bypass active?",()=>"composeStandardGeometryShader: 'return color;' not found in composed fragment \u2014 template changed?",()=>"standard-geometry view does not support scene group building",()=>"standard-geometry: skeletal velocity feature was not preloaded",()=>"standard-geometry: thin instances were not preloaded",()=>"standard-geometry: morph targets require the scene Standard morph context",()=>"standard-geometry: thin instances were not preloaded",()=>"standard-geometry: skeletal velocity requires a previous-bone texture",()=>"standard-geometry: render target has no color attachments",()=>"Dashed lines require at least two points",()=>"createDashedLines produced no dash segments (degenerate points or dashNb)",()=>"updateDashedLines requires a mesh created by createDashedLines",A=>`Line system data requires finite ${A} components`,()=>"Line system data requires one color row per line",()=>"Line system data requires one color per point",()=>"createLineSystemData requires at least one point",()=>"createLineSystem requires material.useVertexColor to match the line color-buffer layout",()=>"updateLineSystem requires a mesh created by createLineSystem",()=>"updateLineSystem requires unchanged line and point counts",()=>"updateLineSystem requires unchanged line and point counts",()=>"updateLineSystem cannot add colors to a mesh created without vertex colors",A=>`createCsgFromMesh("${A}") requires CPU positions. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,A=>`createCsgFromMesh("${A}") requires CPU indices. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,A=>`createCsgFromMesh("${A}") requires CPU normals. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,(A,g)=>`createMeshesFromCsg("${A}") missing material for CSG material slot ${g}.`,()=>"CSG2 is not initialized. Call and await initializeCsg2Async() before using CSG2 operations.",A=>`${A} cannot use a disposed CSG2 solid.`,A=>`createCsg2FromMesh("${A}") requires CPU positions. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,A=>`createCsg2FromMesh("${A}") requires CPU indices. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,A=>`createCsg2FromMesh("${A}") requires CPU normals. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,(A,g)=>`createCsg2FromMesh("${A}") materialSlot must be an integer from 0 to ${g}.`,()=>"CSG2 operations require solids with the same vertex property layout.",(A,g)=>`createMeshesFromCsg2("${A}") received an unknown Manifold material original ID ${g}.`,A=>`Unable to build CSG2 mesh "${A}". Manifold has 0 vertices for this output.`,(A,g)=>`createMeshesFromCsg2("${A}") missing material for CSG2 material slot ${g}.`,()=>"enableThinInstanceWorldBounds requires mesh.thinInstances",()=>"createHierarchyInstancePool capacity must be a non-negative integer",()=>"createHierarchyInstancePool requires at least one mesh in the source hierarchy",A=>`createHierarchyInstancePool mesh "${A}" already has thin instances`,A=>`createHierarchyInstancePool requires an invertible world matrix for mesh "${A}"`,()=>"addHierarchyInstance exceeded pool capacity",()=>"setHierarchyInstanceCount count must be an integer within pool capacity",A=>`setHierarchyInstanceCount mesh "${A}" is missing thin instance data`,A=>`HierarchyInstancePool mesh "${A}" is missing thin instance data`,A=>`${A} index must reference an active hierarchy instance`,()=>"updateMeshGeometryCapacity requires unshared, tightly-packed mesh geometry",()=>"updateMeshGeometryCapacity requires coherent triangle-list geometry with uint32 indices",()=>"updateMeshGeometryCapacity requires unchanged optional-attribute layout",A=>`mesh attribute updates require unshared geometry: ${A}`,()=>"mesh attribute update requires a valid tightly-packed vertex range",()=>"mesh attribute update requires a valid destination vertex range",()=>"updateMeshGeometry requires unshared, tightly-packed mesh geometry",()=>"updateMeshGeometry requires unchanged vertex/index counts; use resizeMeshGeometry for topology changes",()=>"updateMeshGeometry requires unchanged optional-attribute layout; use resizeMeshGeometry for layout changes",()=>"updateMeshGeometryCapacity requires reserveFactor >= 1",()=>"Thin-instance LOD partners require an opaque, non-transmissive material",()=>"Thin-instance LOD partner requires the source draw to provide instance colors",()=>"setThinInstanceDrawCount requires a fully synchronized fixed-capacity pool",()=>"enableThinInstanceDynamicDrawCount requires mesh.thinInstances",()=>"enableThinInstanceGpuCulling requires mesh.thinInstances",()=>"setThinInstanceCullBoundsPad requires mesh.thinInstances",()=>"setThinInstanceLodPartner requires thinInstances on both meshes",()=>"setThinInstanceLodPartner requires two distinct meshes",()=>"setThinInstanceLodPartner does not support thin-instance data shared by mesh clones",()=>"setThinInstanceLodPartner fullMesh cannot already be an LOD partner",()=>"setThinInstanceLodPartner lodMesh cannot also own an LOD partner",()=>"setThinInstanceLodPartner lodMesh is already paired with another source mesh",()=>"setThinInstanceLodPartner requires source instance colors when the LOD partner uses instance colors",A=>`createNavMesh (tile cache) failed: ${A}`,A=>`createNavMesh (tiled) failed: ${A}`,A=>`createNavMesh failed: ${A}`,A=>`Mesh "${A}" missing CPU geometry for navmesh`,()=>"No navmesh generated. Call createNavMesh first.",()=>"Navmesh not ready. Call createNavMesh first.",()=>"Navmesh has no tile cache. Build with `maxObstacles > 0` to enable obstacles.",()=>"NodeParticle: BasicSpriteUpdateBlock requires SetupSpriteSheetBlock",()=>"NodeParticle: LocalPositionUpdated requires SystemBlock.isLocal",()=>"NodeParticle: LocalPositionUpdated read before local shape position creation",A=>`NodeParticle: ParticleLocalVariableBlock ${A} received an unsupported value`,A=>`NodeParticle: ParticleLocalVariableBlock ${A} received an unsupported value`,A=>`NodeParticle: ParticleLocalVariableBlock ${A} received an unsupported value`,A=>`NodeParticle: ParticleLocalVariableBlock ${A} received an unsupported value`,A=>`NodeParticle: ParticleLocalVariableBlock ${A} changed value type`,()=>"NodeParticle: emitter provider must return a finite 16-element matrix",()=>"NodeParticle: emitter provider must return a finite 16-element matrix",(A,g)=>`NodeParticle: ParticleTeleportInBlock ${A} does not expose output "${g}"`,(A,g,I)=>`NodeParticle: ${A} ${g} does not expose output "${I}"`,A=>`NodeParticle: graph plumbing cycle ${A}`,(A,g,I)=>`NodeParticle: ${A} ${g} does not support ${I} connections`,A=>`NodeParticle: ParticleTeleportOutBlock ${A} has invalid entryPoint`,(A,g)=>`NodeParticle: ParticleTeleportOutBlock ${A} references missing entryPoint ${g}`,(A,g)=>`NodeParticle: ParticleTeleportOutBlock ${A} entryPoint ${g} is not ParticleTeleportInBlock`,A=>`NodeParticle: graph plumbing cycle ${A}`,A=>`NodeParticle: ParticleTeleportInBlock ${A} input is not connected`,(A,g)=>`NodeParticle: ${A} ${g} input is not connected`,A=>`NodeParticle: ParticleLocalVariableBlock ${A} Particle scope requires particle-only evaluation`,()=>"NodeParticle: invalid source \u2014 expected a `blocks` array",A=>`NodeParticle: block missing numeric id (name=${A})`,()=>"NodeParticle: graph has no SystemBlock",A=>`NodeParticle: failed to load texture "${A}"`,()=>"NodeParticle: unable to decode texture content",()=>"BillboardSpriteSystem requires a depth-stencil render target.",()=>"createParticleBillboard: the particle system has no texture",A=>`syncParticleSprite2DBridgeWithBlendModes: pixelsPerUnit must be a positive finite number, got ${A}`,(A,g)=>`syncParticleSprite2DBridgeWithBlendModes: originPx must be finite, got [${A}, ${g}]`,()=>"syncParticleSprite2DBridgeWithBlendModes: bridge-owned layers cannot use the Sprite2D Handle API",()=>"createParticleSprite2DBridge: the particle system has no texture",A=>`createParticleSprite2DBridge: pixelsPerUnit must be a positive finite number, got ${A}`,(A,g)=>`createParticleSprite2DBridge: originPx must be finite, got [${A}, ${g}]`,()=>"syncParticleSprite2DBridge: the bridge-owned layer cannot use the Sprite2D Handle API",A=>`syncParticleSprite2DBridge: pixelsPerUnit must be a positive finite number, got ${A}`,(A,g)=>`syncParticleSprite2DBridge: originPx must be finite, got [${A}, ${g}]`,()=>"createHeightFieldShape requires either a groundMesh or full explicit heightfield parameters.",()=>"createHeightFieldShape ground mesh has no vertex positions.",A=>`createHeightFieldShape requires a regular (N+1)\xD7(N+1) grid mesh (e.g. from createGroundFromHeightMap); got ${A} vertices, which is not the square of an integer \u2265 2.`,()=>"createHeightFieldShape ground mesh has zero extent in X or Z; cannot build a heightfield.",()=>"Cannot create physics mesh shape from a singular root transform.",()=>"Cannot create physics mesh shape without vertex positions.",()=>"Cannot create physics mesh shape without triangle indices.",()=>"Physics mesh shapes require a mesh or transform hierarchy.",A=>`Unsupported shape type: ${A}`,()=>"Cannot add physics child shape from a singular parent transform.",()=>"Failed to read physics body mass properties.",A=>`Unknown physics rotation axis "${A}".`,()=>"createPhysicsAggregate supports only primitive physics shapes.",A=>`BloomPostProcessTask "${A}": sourceTexture must have a format.`,A=>`BloomPostProcessTask "${A}": sourceTexture must have a format.`,A=>`DepthOfFieldPostProcessTask "${A}": sourceTexture must have a format.`,A=>`ScreenSpaceContactShadowsPostProcessTask "${A}": sourceTexture must be single-sample.`,A=>`ScreenSpaceContactShadowsPostProcessTask "${A}": depthTexture must be single-sample.`,A=>`ScreenSpaceContactShadowsPostProcessTask "${A}": depth source has no depth attachment.`,A=>`ScreenSpaceGlobalIlluminationPostProcessTask "${A}": sourceTexture must be single-sample.`,A=>`ScreenSpaceGlobalIlluminationPostProcessTask "${A}": depthTexture must be single-sample.`,A=>`ScreenSpaceGlobalIlluminationPostProcessTask "${A}": depth source has no depth attachment.`,()=>"Alpha-to-coverage is not supported for NodeMaterial.",()=>"Uniform copies require 4-byte-aligned sizes and destination offsets.",()=>"StorageBuffer has been disposed.",()=>"StorageBuffer belongs to a different engine.",()=>"StorageBuffer is not a live registered allocation.",()=>"StorageBuffer has been disposed.",()=>"StorageBuffer is not a live registered allocation.",()=>"StorageBuffer belongs to a different engine.",()=>"StorageBuffer is not a live registered allocation.",()=>"StorageBuffer byteOffset must be a non-negative multiple of 4.",()=>"StorageBuffer update data must have a byte length that is a multiple of 4.",A=>`StorageBuffer update exceeds its ${A}-byte capacity.`,()=>"StorageBuffer is not a live registered allocation.",A=>`Mesh "${A}" cannot be added: it was disposed when it left its last scene. Create a new mesh instead.`,A=>`morph _postCompose: expected to rewrite 2 binding declarations, rewrote ${A}`,()=>"getCsmReceiverTexture requires a CSM shadow generator",()=>"Deformable shadows require a fully initialized shadow generator",A=>`Device-lost Scene recovery does not support shadow generator type "${A}"`,()=>"Device-lost Scene recovery could not find ESM shadow resources",()=>"Device-lost Scene recovery failed to create ESM shadow resources",()=>"AnimationController.tick requires an EngineContext for skeleton or morph animation",()=>"Cannot update disposed skeleton",()=>"Invalid bone matrices",()=>"createBillboardCustomShader: `fragment` must be a non-empty WGSL string.",()=>"BillboardSpriteSystem requires a depth-stencil render target.",()=>"addBillboardSprite: handle id space exhausted.",(A,g)=>`${A}: BillboardSpriteHandle ${g} has been removed.`,()=>"BillboardSpriteSystem: alphaCutoff must be a finite number.",()=>"BillboardSpriteSystem: opacity must be a finite number.",()=>"createAxisLockedBillboardSystem: axis components must be finite numbers.",()=>"createAxisLockedBillboardSystem: axis must be non-zero.",()=>"addBillboardSpriteIndex: props.position is required.",()=>"addBillboardSpriteIndex: props.sizeWorld is required.",(A,g)=>`updateBillboardSpriteIndex: index ${A} out of range [0, ${g})`,(A,g)=>`removeBillboardSpriteIndex: index ${A} out of range [0, ${g})`,(A,g)=>`setBillboardSpriteFrameIndex: index ${A} out of range [0, ${g})`,(A,g)=>`${A}: extra texture name "${g}" is not a valid WGSL identifier.`,(A,g,I,e)=>`${A}: frame ${g} has non-positive size ${I}x${e}.`,(A,g,I,e)=>`${A}: frame ${g} has negative sub-rect origin (srcX=${I}, srcY=${e}).`,(A,g,I,e)=>`${A}: frame ${g} sub-rect row extent (srcX + width) * 4 = ${I} exceeds srcStrideBytes ${e} (would spill into next row).`,(A,g,I,e)=>`${A}: frame ${g} width ${I} exceeds shelf max width ${e}.`,(A,g,I,e,t,i)=>`${A}: cannot fit frame ${g} (${I}x${e}) \u2014 atlas height capacity ${t} exhausted at y=${i}.`,()=>"createSpriteAtlasFromFrames: at least one frame is required, or pass options.capacityPx to create an empty atlas with reserved capacity for appendSpriteAtlasFrames.",(A,g)=>`createSpriteAtlasFromFrames: atlas dimensions must be >= 1 (got ${A}x${g}).`,(A,g,I,e)=>`createSpriteAtlasFromFrames: capacityPx ${A}x${g} too small for initial content ${I}x${e}.`,()=>"appendSpriteAtlasFrames: atlas was not built by createSpriteAtlasFromFrames (no packer state).",()=>"loadSpriteAtlas: metadataUrl unsupported.",()=>"loadSpriteAtlas: gridSize required.",(A,g)=>`resolveSpriteFrame: index ${A} out of range [0, ${g})`,()=>"addSprite2D: handle id space exhausted.",(A,g)=>`${A}: Sprite2DHandle ${g} has been removed.`,()=>'enableSprite2DYSort: only depth: "none" layers are supported.',()=>"enableSprite2DYSort: defaultBias must be finite.",()=>"setSprite2DYSortBias: Y-sort is not enabled for this layer.",(A,g)=>`setSprite2DYSortBias: index ${A} out of range [0, ${g})`,()=>"setSprite2DYSortBias: bias must be finite.",()=>"addSprite2DIndex: positionPx required.",(A,g)=>`updateSprite2DIndex: index ${A} out of range [0, ${g})`,(A,g)=>`removeSprite2DIndex: index ${A} out of range [0, ${g})`,(A,g)=>`setSprite2DFrameIndex: index ${A} out of range [0, ${g})`,()=>"SpriteAnimationManager is already attached to a render loop.",()=>"SpriteAnimationManager is already attached to an AnimationManager.",()=>"SpriteAnimationManager is already running autonomously.",()=>"SpriteAnimationManager is already attached to a render loop.",()=>"SpriteAnimationManager is already attached to an AnimationManager.",()=>"Sprite frame animation requires finite from/to frame indices.",()=>"Sprite frame animation requires finite from/to frame indices.",()=>"SpriteAnimationManager is already attached to a render loop.",()=>"SpriteAnimationManager is already attached to an AnimationManager.",()=>"SpriteAnimationManager is already running autonomously.",()=>"createSprite2DCustomShader: `fragment` must be a non-empty WGSL string.",()=>"Sprite pipeline: depth-enabled pipelines require a depth-stencil format.",()=>"Sprite pipeline: depth-enabled pipelines require a scene bind-group layout.",()=>'Depth-hosted sprites require depth != "none".',()=>"Depth-hosted Sprite2DLayer requires a depth-stencil render target.",()=>'SpriteRenderer requires depth: "none".',()=>"SpriteRenderer has been disposed.",A=>`TextData style palette cannot exceed ${A} entries.`,(A,g)=>`updateTextData ${A}: storage does not contain curveSet "${g}" \u2014 add it via updateGlyphStorage first.`,(A,g,I)=>`${A}: run index ${g} out of range (0..${I}).`,A=>`${A}: GlyphRun reference is not in this TextData.`,()=>"updateTextData addRun: GlyphRun reference is already in this TextData.",()=>"updateTextData removeRun: GlyphRun reference is not in this TextData.",()=>"updateTextData replaceRun: previous GlyphRun reference is not in this TextData.",()=>"updateTextData replaceRun: new GlyphRun reference is already in this TextData.",A=>`TextData style palette cannot exceed ${A} entries.`,()=>"Basis: no images in file",()=>"Basis: startTranscoding failed",A=>`Basis: transcoded size is 0 for mip ${A}`,A=>`Basis: transcodeImage failed for mip ${A}`,(A,g)=>`createDynamicTexture: width/height must be >= 1 (got ${A}x${g})`,()=>"createHtmlTexture: requires a DOM canvas rendering surface (HTML-in-Canvas is unavailable on OffscreenCanvas).",()=>"KTX: file too small",()=>"KTX: invalid magic",()=>"KTX: unsupported endianness",()=>"KTX: not a compressed texture (glType != 0)",()=>"KTX: not a compressed texture (glFormat != 0)",A=>`KTX: unknown glInternalFormat 0x${A}`,()=>"KTX: 3D textures not supported",()=>"KTX: texture arrays not supported",()=>"KTX: cubemaps not supported (use loadCubeTexture)",()=>"KTX: key/value data overflows buffer",A=>`KTX: truncated at mip ${A} size field`,A=>`KTX: mip ${A} data overflows buffer`,()=>"KTX: no mip levels found",A=>`KTX fetch failed: ${A}`,A=>`KTX2: ${A}`,()=>"KTX2: decoder produced no mipmaps",A=>`KTX2: decoder produced an empty mip ${A}`,A=>`KTX2: device does not support ${A}`,(A,g,I)=>`KTX2: uncompressed mip ${A} has ${g} bytes, expected ${I}`,A=>`KTX2: unsupported transcoded format 0x${A}`,(A,g)=>`KTX2 fetch failed: ${A} for ${g}`,()=>"KTX2: RGBA decode size does not match image dimensions",A=>`KTX2: ${A}`,()=>"KTX2: decoder produced no mipmaps",(A,g)=>`KTX2: expected ${A} base-level layers but decoded ${g}`,(A,g,I,e)=>`KTX2: base-level layer ${A} is malformed (expected ${g}x${I}, ${e} bytes)`,(A,g)=>`createTexture2DFromPixels: width/height must be >= 1 (got ${A}x${g})`,(A,g,I,e)=>`createTexture2DFromPixels: data too short \u2014 need ${A} bytes for ${g}x${I} RGBA, got ${e}`,(A,g)=>`createRenderTexture2D: width/height must be >= 1 (got ${A}x${g})`,(A,g)=>`updateTexture2DFromPixels: width/height must be >= 1 (got ${A}x${g})`,(A,g,I,e)=>`updateTexture2DFromPixels: data too short \u2014 need ${A} bytes for ${g}x${I} RGBA, got ${e}`,(A,g,I)=>`createTexture3DFromPixels: width/height/depth must be >= 1 (got ${A}x${g}x${I})`,(A,g,I,e,t)=>`createTexture3DFromPixels: data too short \u2014 need ${A} bytes for ${g}x${I}x${e} RGBA, got ${t}`,()=>"createRenderTargetTexture: descriptor.size must be fixed { width, height } pixels, not a SurfaceContext (would invalidate eagerly-allocated textures when the canvas resizes).",()=>"createRenderTargetTexture: render target has no color or depth texture (no format / depthStencilFormat?).",(A,g,I)=>`createTexture2DArray: width/height/layers must be >= 1 (got ${A}x${g}x${I})`,(A,g)=>`uploadImageToArrayLayer: layer must be an integer in [0, ${A}) (got ${g})`,(A,g)=>`loadImageToArrayLayer: fetch failed for ${A} (${g})`,(A,g)=>`createTexture2DArrayFromUrls: fetch failed for ${A} (${g})`,(A,g,I,e,t)=>`createTexture2DArrayFromUrls: all layers must share one size; layer 0 is ${A}x${g} but layer ${I} is ${e}x${t}`,(A,g)=>`updateTexture2DArrayFromPixels: mipLevel must be an integer in [0, ${A}) (got ${g})`,(A,g,I,e,t,i)=>`updateTexture2DArrayFromPixels: data too short \u2014 need ${A} bytes for ${g}x${I}x${e} RGBA at mip ${t}, got ${i}`,()=>"KTX2: the decoder does not report layerCount; a decoder with 2D array support is required (see setKtx2DecoderUrl)",(A,g)=>`KTX2: decoder produced ${A} mips, which is not a whole number of ${g}-layer levels`,(A,g,I)=>`KTX2: expected layer ${A} at mip index ${g} but the decoder reported layer ${I}`,(A,g)=>`KTX2: layers of one mip level must share a size (level ${A}, layer ${g})`,A=>`KTX2: device does not support ${A}`,(A,g,I,e)=>`KTX2: uncompressed mip ${A} layer ${g} has ${I} bytes, expected ${e}`,A=>`KTX2: unsupported transcoded format 0x${A}`,(A,g)=>`KTX2 fetch failed: ${A} for ${g}`,()=>"CPU-only animation evaluation is unavailable for this animation controller",A=>`VAT prepared payload: ${A} must be a positive integer.`,A=>`VAT prepared payload: ${A} must be a record.`,(A,g)=>`VAT prepared payload: ${A} contains invalid bone index "${g}".`,(A,g)=>`VAT prepared payload: ${A}[${g}] has an invalid length.`,()=>"VAT prepared payload: data length must equal boneCount * frameCount * 16.",()=>"VAT prepared payload: clips must be a record.",A=>`VAT prepared payload: clip "${A}" is invalid.`,A=>`VAT preparation: mesh "${A}" has no skeleton to bake.`,(A,g)=>`VAT preparation: mesh "${A}" has no skeleton binding for clip "${g}".`,A=>`VAT preparation: mesh "${A}" has inconsistent bone counts.`,()=>"setVatInstanceStorage: mesh has no VAT data.",()=>"setVatInstanceStorage requires a live StorageBuffer from the same engine.",()=>"setVatTime: mesh has no VAT data.",()=>"attachVat: mesh has no skeleton (bake first, attach before clearing it).",()=>"controllerModels requires XR input tracking; do not pass input:false to enterXr.",()=>"handTracking requires XR input tracking; do not pass input:false to enterXr.",()=>"pointerSelection requires XR input tracking; do not pass input:false to enterXr.",()=>"WebXR is not available (navigator.xr missing).",()=>"WebGPU XR is not supported by this browser (XRGPUBinding missing).",()=>"teleportation requires XR input tracking; do not pass input:false to enterXr."];function O6(A,g){const I=uoA[A];return I?I(...g):`Error #${A}`}function hoA(){GCA(O6)}function foA(A){if(!(A instanceof Error))return String(A);const g=A.lite;if(!Array.isArray(g))return A.message;const I=/^#(\d+)$/.exec(A.message);return I?O6(Number(I[1]),g):A.message}function doA(A,g){if(Array.isArray(g))for(const I of g)A._dependencies.add(I);else A._dependencies.add(g)}const woA={r:.2,g:.2,b:.3,a:1};function MoA(A,g){const I={name:A,_parentTask:g,_dependencies:new Set,_renderTarget:null,_renderTargetDepth:null,_renderPassDescriptor:{colorAttachments:[]},_colorAttachment:null,_depthAttachment:null,clearColor:{...woA},clear:!0,_executeFunc:null,_beforeExecute:null,_initialize(){const e=I._renderTarget;if(!e)throw new Error(`RenderPass "${I.name}": render target not set`);const t=e._colorView;let i=null;t&&(i={view:t,loadOp:I.clear?"clear":"load",storeOp:"store",clearValue:I.clearColor});const o=I._renderTargetDepth??e,Q=o._descriptor.dFormat,r=o._depthView,E=Q?Q==="depth24plus-stencil8"||Q==="depth32float-stencil8"||Q==="stencil8":!1;let n=null;r&&(n={view:r,depthClearValue:o._descriptor._depthClearValue??0,depthLoadOp:"clear",depthStoreOp:"store",...E?{stencilClearValue:0,stencilLoadOp:"clear",stencilStoreOp:"store"}:{}}),I._colorAttachment=i,I._depthAttachment=n,I._renderPassDescriptor={label:I.name,colorAttachments:i?[i]:[],depthStencilAttachment:n??void 0}},_execute(){const e=I._renderTarget;if(!e)return 0;I._beforeExecute?.();const t=I._parentTask.engine,i=I._colorAttachment;i&&(i.clearValue=I.clearColor,i.loadOp=I.clear?"clear":"load",i.view=e._colorView);const o=t._currentEncoder.beginRenderPass(I._renderPassDescriptor);let Q=0;return I._executeFunc&&(Q=I._executeFunc(o)),o.end(),Q},_dispose(){I._renderTarget=null,I._renderTargetDepth=null,I._colorAttachment=null,I._depthAttachment=null,I._renderPassDescriptor={colorAttachments:[]},I._executeFunc=null,I._beforeExecute=null,I._dependencies.clear()}};return g._passes.push(I),I}function j6(A){return typeof A=="object"&&A!==null&&"_tasks"in A}function VR(A){if(j6(A))return A;if("_frameGraph"in A&&j6(A._frameGraph))return A._frameGraph;U(92)}function SoA(A,g){D6(VR(A),g)}function RoA(A,g){const I=VR(A),e=I._tasks[0]?.name==="shadow"?1:0;I._tasks.splice(e,0,g)}function NoA(A,g,I){const e=VR(A),t=e._tasks.indexOf(I);t<0?e._tasks.push(g):e._tasks.splice(t,0,g)}function GoA(A,g,I){const e=VR(A),t=e._tasks.indexOf(I);t<0?e._tasks.push(g):e._tasks.splice(t+1,0,g)}function FoA(A,g){const e=VR(A)._currentProcessedTask;return e||U(93,g),MoA(g,e)}function moA(A,g){const I=A.engine,e=g?.update,t={_kind:"frame-graph-context",name:g?.name??"frame-graph",surface:A,frameGraph:c6(),clearColor:g?.clearColor??{r:0,g:0,b:0,a:1},_drawCallsPre:0,_disposed:!1,_update(){t._disposed||e?.(I._currentDelta)},_record(){return t._disposed?0:t.frameGraph.execute()},_resize(){t._disposed||t.frameGraph.build()}};return t}function boA(A){A._disposed||(A.frameGraph.build(),xQ(A.surface,A))}function V6(A){qQ(A.surface,A)}function KoA(A){const g=A;g._disposed||(V6(A),A.frameGraph.dispose(),g._disposed=!0)}function W6(A,g){return Math.floor(Math.log2(Math.max(A,g)))+1}const koA="@group(0)@binding(0)var src:texture_depth_2d;struct V{@builtin(position)p:vec4f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return V(vec4f(p,0,1));}@fragment fn fs(@builtin(position)fc:vec4f)->@location(0)f32{return textureLoad(src,vec2<i32>(fc.xy),0);}";function UoA(A){return`@group(0)@binding(0)var src:texture_2d<f32>;struct V{@builtin(position)p:vec4f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return V(vec4f(p,0,1));}@fragment fn fs(@builtin(position)fc:vec4f)->@location(0)f32{let c=vec2<i32>(fc.xy)*2;let sd=vec2<i32>(textureDimensions(src));let d=sd-vec2<i32>(1,1);let x1=min(c.x+1,d.x);let y1=min(c.y+1,d.y);let a=textureLoad(src,vec2<i32>(c.x,c.y),0).r;let b=textureLoad(src,vec2<i32>(x1,c.y),0).r;let e=textureLoad(src,vec2<i32>(c.x,y1),0).r;let f=textureLoad(src,vec2<i32>(x1,y1),0).r;var r=${A}(${A}(a,b),${A}(e,f));let dd=max(sd/vec2<i32>(2,2),vec2<i32>(1,1));let extraX=(sd.x&1)==1&&i32(fc.x)==dd.x-1;let extraY=(sd.y&1)==1&&i32(fc.y)==dd.y-1;if(extraX){let x2=min(c.x+2,d.x);r=${A}(r,${A}(textureLoad(src,vec2<i32>(x2,c.y),0).r,textureLoad(src,vec2<i32>(x2,y1),0).r));}if(extraY){let y2=min(c.y+2,d.y);r=${A}(r,${A}(textureLoad(src,vec2<i32>(c.x,y2),0).r,textureLoad(src,vec2<i32>(x1,y2),0).r));if(extraX){r=${A}(r,textureLoad(src,vec2<i32>(min(c.x+2,d.x),y2),0).r);}}return r;}`}function LoA(A,g){const I=A._device,e=g.reduce??"max",t=Pe(A,{minFilter:"nearest",magFilter:"nearest",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),i=I.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d"}}]}),o=I.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"unfilterable-float",viewDimension:"2d"}}]}),Q=(M,S)=>I.createRenderPipeline({layout:I.createPipelineLayout({bindGroupLayouts:[S]}),vertex:{module:I.createShaderModule({code:M}),entryPoint:"vs"},fragment:{module:I.createShaderModule({code:M}),entryPoint:"fs",targets:[{format:"r32float"}]},primitive:{topology:"triangle-list"}}),r=Q(koA,i),E=Q(UoA(e),o);let n=Math.max(1,g.width|0),s=Math.max(1,g.height|0),c=W6(n,s);function l(){return I.createTexture({label:"depth-pyramid",size:{width:n,height:s},format:"r32float",usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING,mipLevelCount:c})}function D(M){const S={texture:M,view:M.createView(),sampler:t,width:n,height:s,_sampleType:"float"};return rt(S),S}let p=l(),y=D(p),_,u=[],f=null,h=null;function w(){_=p.createView({baseMipLevel:0,mipLevelCount:1}),u=[];for(let M=1;M<c;M++){const S=p.createView({baseMipLevel:M-1,mipLevelCount:1}),R=p.createView({baseMipLevel:M,mipLevelCount:1});u.push({dst:R,bindGroup:I.createBindGroup({layout:o,entries:[{binding:0,resource:S}]})})}f=null,h=null}return w(),{get texture(){return y},get mipCount(){return c},build(M,S){const R=S??I.createCommandEncoder();(f===null||h!==M)&&(f=I.createBindGroup({layout:i,entries:[{binding:0,resource:M.view}]}),h=M);const N=R.beginRenderPass({label:"depth-pyramid-copy",colorAttachments:[{view:_,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});N.setPipeline(r),N.setBindGroup(0,f),N.draw(3),N.end();for(const F of u){const G=R.beginRenderPass({label:"depth-pyramid-reduce",colorAttachments:[{view:F.dst,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});G.setPipeline(E),G.setBindGroup(0,F.bindGroup),G.draw(3),G.end()}S||I.queue.submit([R.finish()])},resize(M,S){const R=Math.max(1,M|0),N=Math.max(1,S|0);if(R===n&&N===s)return;n=R,s=N,c=W6(n,s);const F=y;p=l(),y=D(p),w(),lC(F)},dispose(){lC(y)}}}function YoA(A,g,I){const{pyramid:e,source:t}=I;return{name:"depth-pyramid",engine:A,scene:g,_passes:[],record(){},execute(){const i=t();return i?(e.build(i,A._currentEncoder),e.mipCount):0},dispose(){e.dispose()}}}function z6(A,g,I){let e=null;return{name:A.name??"image-processing",engine:g,scene:I,_passes:[],record(){Z6(e),e=JoA(g,A.source)},execute(){if(!e)return 0;const i=I.imageProcessing,o=new X([i.exposure,i.contrast,i.toneMappingEnabled===!0?1:0,0]);g._device.queue.writeBuffer(e.params,0,o);const Q=g._currentEncoder.beginRenderPass({colorAttachments:[{view:g.scRT._colorView,loadOp:"clear",storeOp:"store",clearValue:I.clearColor}]});return Q.setPipeline(e.pipeline),Q.setBindGroup(0,e.bindGroup),Q.draw(3),Q.end(),1},dispose(){Z6(e),e=null,this._passes.length=0}}}function JoA(A,g){const I=voA(g);if(!I)throw new Error("Image processing source has no color texture");const e=A._device,i=(I.sampleCount??1)>1,o=e.createBuffer({size:16,usage:SA.UNIFORM|SA.COPY_DST}),Q=e.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:NA.FRAGMENT,texture:{sampleType:i?"unfilterable-float":"float",multisampled:i}}]}),r="struct P{e:f32,c:f32,t:f32,p:f32}@group(0)@binding(0)var<uniform>p:P;@vertex fn vs(@builtin(vertex_index)i:u32)->@builtin(position)vec4f{var a=array<vec2f,3>(vec2f(-1,-3),vec2f(3,1),vec2f(-1,1));return vec4f(a[i],0,1);}fn ip(r:vec4f)->vec4f{var c=r.rgb*p.e;if(p.t>0.5){c=1.0-exp2(-1.590579*c);}c=clamp(pow(max(c,vec3f(0)),vec3f(1/2.2)),vec3f(0),vec3f(1));let h=c*c*(3.0-2.0*c);if(p.c<1.0){c=mix(vec3f(0.5),c,p.c);}else{c=mix(c,h,p.c-1.0);}return vec4f(max(c,vec3f(0)),r.a);}",E=i?"@group(0)@binding(1)var s:texture_multisampled_2d<f32>;":"@group(0)@binding(1)var s:texture_2d<f32>;",n=i?"@fragment fn fs(@builtin(position)q:vec4f)->@location(0)vec4f{let d=textureDimensions(s);let px=clamp(vec2i(q.xy),vec2i(0),vec2i(d)-1);let n=textureNumSamples(s);var c=vec4f(0);for(var i=0u;i<n;i++){c+=ip(textureLoad(s,px,i));}return c/f32(n);}":"@fragment fn fs(@builtin(position)q:vec4f)->@location(0)vec4f{let d=textureDimensions(s);return ip(textureLoad(s,clamp(vec2i(q.xy),vec2i(0),vec2i(d)-1),0));}",s=e.createShaderModule({code:`${r}${E}${n}`}),c=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[Q]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:A.format}]},primitive:{topology:"triangle-list"}}),l=e.createBindGroup({layout:Q,entries:[{binding:0,resource:{buffer:o}},{binding:1,resource:I.createView()}]});return{pipeline:c,bindGroup:l,params:o}}function voA(A){const g=typeof A=="function"?A():A;return g?"_colorTexture"in g?g._colorTexture:g.texture:null}function Z6(A){A?.params.destroy()}const HoA={magFilter:"nearest",minFilter:"nearest"},ToA={magFilter:"linear",minFilter:"linear"},xoA={magFilter:"linear",minFilter:"linear",mipmapFilter:"linear"};function X6(A){return Pe(A,HoA)}function m1(A){return Pe(A,ToA)}function yF(A){return Pe(A,xoA)}const qoA="struct V{@builtin(position)p:vec4f,@location(0)u:vec2f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{var pos=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));var uv=array<vec2f,3>(vec2f(0,1),vec2f(2,1),vec2f(0,-1));return V(vec4f(pos[i],0,1),uv[i]);}";function PoA(A){return`@group(0)@binding(0)var t:texture_2d<f32>;@group(0)@binding(1)var s:sampler;@fragment fn fs(v:V)->@location(0)vec4f{return textureSampleLevel(t,s,v.u,${A.toFixed(1)});}`}const OoA="@group(0)@binding(0)var t:texture_multisampled_2d<f32>;@fragment fn fs(v:V)->@location(0)vec4f{let d=vec2i(textureDimensions(t));let q=v.u*vec2f(d)-.5;let p0=vec2i(floor(q));let fr=fract(q);let dmax=d-vec2i(1);let p00=clamp(p0,vec2i(0),dmax);let p10=clamp(p0+vec2i(1,0),vec2i(0),dmax);let p01=clamp(p0+vec2i(0,1),vec2i(0),dmax);let p11=clamp(p0+vec2i(1,1),vec2i(0),dmax);let n=textureNumSamples(t);var c00=vec4f(0);var c10=vec4f(0);var c01=vec4f(0);var c11=vec4f(0);for(var i=0u;i<n;i++){c00+=textureLoad(t,p00,i);c10+=textureLoad(t,p10,i);c01+=textureLoad(t,p01,i);c11+=textureLoad(t,p11,i);}let inv=1./f32(n);c00*=inv;c10*=inv;c01*=inv;c11*=inv;return mix(mix(c00,c10,fr.x),mix(c01,c11,fr.x),fr.y);}";let $6=null,_F=null,uF=null,G3=null,F3=null;function joA(A){$6!==A&&($6=A,_F=null,uF=null,G3=new Map,F3=new Map)}function VoA(A,g,I){const e=g,t=I;!A.targetTexture&&!A.resolveTexture&&U(79,A.name??"copy-to-texture");const i={view:void 0,loadOp:A.viewport!==void 0||A.resolveTexture&&!A.targetTexture?"load":"clear",storeOp:"store"},o={name:A.name??"copy-to-texture",engine:e,scene:t,_passes:[],sourceTexture:A.sourceTexture,targetTexture:A.targetTexture,ownsTargetTexture:A.ownsTargetTexture===!0,resolveTexture:A.resolveTexture,viewport:A.viewport,lodLevel:A.lodLevel??0,get outputTexture(){return this.resolveTexture??this.targetTexture},_ownedTarget:null,_fast:null,_blit:null,_resolve:null,_colorAttachment:i,_renderPassDescriptor:{label:A.name??"copy-to-texture",colorAttachments:[i]},record(){o._fast=null,o._blit=null,o._resolve=null;const Q=o.sourceTexture;Q===e.scRT&&U(80,o.name),Q._colorTexture||U(81,o.name);const r=n=>!n._colorTexture;if(o._ownedTarget&&(!o.ownsTargetTexture||o._ownedTarget!==o.targetTexture)&&(Se(o._ownedTarget),o._ownedTarget=null),o.targetTexture&&(o.ownsTargetTexture?(Kt(o.targetTexture,e),o._ownedTarget=o.targetTexture):r(o.targetTexture)&&Kt(o.targetTexture,e)),o.resolveTexture&&r(o.resolveTexture)&&Kt(o.resolveTexture,e),o.resolveTexture&&!o.targetTexture){WoA(o,Q,o.resolveTexture,e);return}const E=o.targetTexture;zoA(o,Q,E,e)||ZoA(o,Q,E,e)},execute(){const Q=o._fast;if(Q)return e._currentEncoder.copyTextureToTexture(Q._source,Q._target,Q._size),0;const r=o._resolve;if(r)return r._swapAsResolve&&(i.resolveTarget=e.scRT._colorView),e._currentEncoder.beginRenderPass(o._renderPassDescriptor).end(),0;const E=o._blit;E._swapAsView&&(i.view=e.scRT._colorView),E._swapAsResolve&&(i.resolveTarget=e.scRT._colorView);const n=e._currentEncoder.beginRenderPass(o._renderPassDescriptor),s=E._viewport;return s&&(n.setViewport(s.x,s.y,s.w,s.h,0,1),n.setScissorRect(s.x,s.y,s.w,s.h)),n.setPipeline(E._pipeline),n.setBindGroup(0,E._bindGroup),n.draw(3),n.end(),1},dispose(){o._passes.length=0,Se(o._ownedTarget),o.ownsTargetTexture&&o.targetTexture!==o._ownedTarget&&Se(o.targetTexture),o._ownedTarget=null,o._fast=null,o._blit=null,o._resolve=null}};return o}function WoA(A,g,I,e){const t=g._descriptor,i=I._descriptor,o=t.samples??1;o<2&&U(82,A.name,o),(i.samples??1)!==1&&U(83,A.name,i.samples);const Q=I===e.scRT;!Q&&(g._width!==I._width||g._height!==I._height)&&U(84,A.name,g._width,g._height,I._width,I._height),A._colorAttachment.view=g._colorView,Q||(A._colorAttachment.resolveTarget=I._colorView),A._resolve={_swapAsResolve:Q}}function zoA(A,g,I,e){if(A.viewport!==void 0||A.resolveTexture)return!1;const t=I._colorTexture;if(I===e.scRT||!t)return!1;const i=g._colorTexture;if(!i||(i.usage&dA.COPY_SRC)===0||(t.usage&dA.COPY_DST)===0)return!1;const o=g._descriptor,Q=I._descriptor,r=o.format,E=Q.format;if(!r||r!==E)return!1;const n=o.samples??1,s=Q.samples??1;if(n!==1||s!==1)return!1;const c=A.lodLevel;if(c>=i.mipLevelCount)return!1;const l=Math.max(1,g._width>>c),D=Math.max(1,g._height>>c);return l!==I._width||D!==I._height?!1:(A._fast={_source:{texture:i,mipLevel:c},_target:{texture:t},_size:{width:l,height:D}},!0)}function ZoA(A,g,I,e){joA(e._device);const t=$oA(I),i=I._descriptor.samples??1,o=(g._descriptor.samples??1)>1,Q=XoA(e,t,i,o,A.lodLevel),r=o?uF:_F,E=o?[{binding:0,resource:g._colorView}]:[{binding:0,resource:g._colorView},{binding:1,resource:A.lodLevel>0?yF(e):m1(e)}],n=e._device.createBindGroup({label:`${A.name}-bg`,layout:r,entries:E}),s=I===e.scRT,c=s&&i===1;let l=!1;if(A.resolveTexture){i<2&&U(85,A.name,i);const y=A.resolveTexture._descriptor;(y.samples??1)!==1&&U(86,A.name,y.samples),y.format!==I._descriptor.format&&U(87,A.name,y.format,I._descriptor.format),A.resolveTexture===e.scRT?l=!0:A._colorAttachment.resolveTarget=A.resolveTexture._colorView}else s&&i>1&&(l=!0);c||(A._colorAttachment.view=I._colorView),!l&&!A.resolveTexture&&(A._colorAttachment.resolveTarget=void 0);let D=null;const p=A.viewport;if(p){const y=I._width,_=I._height,u=Math.floor(p.x*y),f=Math.floor((p.x+p.width)*y)-u,h=Math.floor(p.y*_),w=Math.floor((p.y+p.height)*_)-h;D={x:u,y:_-h-w,w:f,h:w}}A._blit={_pipeline:Q,_bindGroup:n,_viewport:D,_swapAsView:c,_swapAsResolve:l}}function XoA(A,g,I,e,t){const i=A._device,o=`${g}|t${I}|${e?"m":"s"}|l${t}`;let Q=G3.get(o);if(Q)return Q;const r=e?"msaa":`s|l${t}`;let E=F3.get(r);if(!E){const s=e?OoA:PoA(t);E=i.createShaderModule({code:`${qoA} ${s}`,label:`copy-to-texture-${r}`}),F3.set(r,E)}let n;return e?(uF??=i.createBindGroupLayout({label:"copy-to-texture-msaa-bgl",entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"unfilterable-float",multisampled:!0}}]}),n=uF):(_F??=i.createBindGroupLayout({label:"copy-to-texture-bgl",entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:NA.FRAGMENT,sampler:{type:"filtering"}}]}),n=_F),Q=i.createRenderPipeline({label:`copy-to-texture-${o}`,layout:i.createPipelineLayout({label:`copy-to-texture-layout-${o}`,bindGroupLayouts:[n]}),vertex:{module:E,entryPoint:"vs"},fragment:{module:E,entryPoint:"fs",targets:[{format:g}]},primitive:{topology:"triangle-list"},multisample:{count:I}}),G3.set(o,Q),Q}function $oA(A){const g=A._descriptor.format;return g||U(88),g}const ABA="struct V{@builtin(position)p:vec4f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{var pos=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));return V(vec4f(pos[i],0,1));}",gBA="@group(0)@binding(0)var src:texture_depth_multisampled_2d;@fragment fn fs(v:V)->@builtin(frag_depth)f32{return textureLoad(src,vec2i(v.p.xy),0);}";let Av=null,hF=null,m3=null;function IBA(A,g){const I=A._device;Av!==I&&(Av=I,hF=null,m3=new Map);const e=m3.get(g);if(e)return e;hF??=I.createBindGroupLayout({label:"depth-resolve-bgl",entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"depth",multisampled:!0}}]});const t=I.createShaderModule({code:`${ABA} ${gBA}`,label:"depth-resolve"}),i=I.createRenderPipeline({label:`depth-resolve-${g}`,layout:I.createPipelineLayout({label:"depth-resolve-layout",bindGroupLayouts:[hF]}),vertex:{module:t,entryPoint:"vs"},fragment:{module:t,entryPoint:"fs",targets:[]},primitive:{topology:"triangle-list"},depthStencil:{format:g,depthWriteEnabled:!0,depthCompare:"always"}});return m3.set(g,i),i}function eBA(A,g,I){const e=g,t={view:void 0,depthClearValue:0,depthLoadOp:"clear",depthStoreOp:"store"},i={label:A.name??"depth-resolve",colorAttachments:[],depthStencilAttachment:t};let o=null,Q=null,r=null,E=null;const n=()=>{const s=A.sourceTexture,c=A.targetTexture;if(s._depthTexture||U(89,A.name),(s._descriptor.samples??1)<2&&U(90,A.name),(!c._depthTexture||c._width!==(s._width||0)||c._height!==(s._height||0))&&(Kt(c,e),c._width!==s._width||c._height!==s._height))throw new Error(`DepthResolveTask "${A.name}": targetTexture size ${c._width}\xD7${c._height} must match sourceTexture size ${s._width}\xD7${s._height} (size the target's descriptor like the source, e.g. both \`size: surface\`).`);const l=c._descriptor.dFormat;l||U(91,A.name),o=IBA(e,l);const D=s._depthTexture.createView({aspect:"depth-only"});Q=e._device.createBindGroup({label:`${A.name??"depth-resolve"}-bg`,layout:hF,entries:[{binding:0,resource:D}]}),t.view=c._depthView,r=s._depthTexture,E=c._depthTexture};return{name:A.name??"depth-resolve",engine:e,scene:I,_passes:[],record(){n()},execute(){(A.sourceTexture._depthTexture!==r||A.targetTexture._depthTexture!==E)&&n();const s=e._currentEncoder.beginRenderPass(i);return s.setPipeline(o),s.setBindGroup(0,Q),s.draw(3),s.end(),1},dispose(){o=null,Q=null,r=null,E=null}}}function tBA(A){return{_descriptor:A,_colorTextures:[],_colorViews:[],_resolveColorTextures:[],_resolveColorViews:[],_depthTexture:null,_depthView:null,_width:0,_height:0}}function CBA(A,g){gv(A);const I=A._descriptor,{width:e,height:t}=BBA(I);A._width=e,A._height=t;const i=g._device,o=I.colorFormats,Q=I.sampleCount,r=Q>1,E=I.label,n={width:e,height:t};for(let s=0;s<o.length;s++){const c=o[s],l=i.createTexture({label:E,size:n,format:c,sampleCount:Q,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING|dA.COPY_SRC});if(A._colorTextures.push(l),A._colorViews.push(l.createView()),r){const D=i.createTexture({label:E,size:n,format:c,sampleCount:1,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING|dA.COPY_SRC});A._resolveColorTextures.push(D),A._resolveColorViews.push(D.createView())}}I.depthStencilFormat&&(A._depthTexture=i.createTexture({label:E,size:n,format:I.depthStencilFormat,sampleCount:Q,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING}),A._depthView=A._depthTexture.createView())}function gv(A){for(const g of A._colorTextures)g.destroy();A._colorTextures.length=0,A._colorViews.length=0;for(const g of A._resolveColorTextures)g.destroy();A._resolveColorTextures.length=0,A._resolveColorViews.length=0,A._depthTexture&&(A._depthTexture.destroy(),A._depthTexture=null,A._depthView=null),A._width=0,A._height=0}function iBA(A,g){return A._resolveColorViews[g]??A._colorViews[g]}function oBA(A,g){return A._resolveColorTextures[g]??A._colorTextures[g]}function BBA(A){const g=A.size;if("canvas"in g){const I=g.canvas;return{width:I.width,height:I.height}}return g}function $1(A,g){const I=AC(A);return Object.create(I,{source:{value:I,enumerable:!0},_renderFeatures:{value:{features:g.features,features2:g.features2},writable:!0,enumerable:!0,configurable:!0}})}function Iv(A){const g=A;return!!g.source&&!!g._renderFeatures}function AC(A){return Iv(A)?A.source:A}var zg=(A=>(A[A.IRRADIANCE=0]="IRRADIANCE",A[A.WORLD_POSITION=1]="WORLD_POSITION",A[A.LOCAL_POSITION=2]="LOCAL_POSITION",A[A.REFLECTIVITY=3]="REFLECTIVITY",A[A.VIEW_DEPTH=4]="VIEW_DEPTH",A[A.NORMALIZED_VIEW_DEPTH=5]="NORMALIZED_VIEW_DEPTH",A[A.SCREENSPACE_DEPTH=6]="SCREENSPACE_DEPTH",A[A.VIEW_NORMAL=7]="VIEW_NORMAL",A[A.WORLD_NORMAL=8]="WORLD_NORMAL",A[A.ALBEDO=9]="ALBEDO",A[A.LINEAR_VELOCITY=10]="LINEAR_VELOCITY",A))(zg||{});const kC={r:0,g:0,b:0,a:0},QBA={r:1,g:1,b:1,a:1},ev=[{name:"Irradiance",defaultFormat:"rgba16float",clearValue:kC},{name:"WorldPosition",defaultFormat:"rgba16float",clearValue:kC},{name:"LocalPosition",defaultFormat:"rgba16float",clearValue:kC},{name:"Reflectivity",defaultFormat:"rgba8unorm",clearValue:kC},{name:"ViewDepth",defaultFormat:"r32float",clearValue:kC},{name:"NormalizedViewDepth",defaultFormat:"r16float",clearValue:QBA},{name:"ScreenspaceDepth",defaultFormat:"r16float",clearValue:kC},{name:"ViewNormal",defaultFormat:"rgba16float",clearValue:kC},{name:"WorldNormal",defaultFormat:"rgba16float",clearValue:kC},{name:"Albedo",defaultFormat:"rgba8unorm",clearValue:kC},{name:"LinearVelocity",defaultFormat:"rgba16float",clearValue:kC}];function rBA(A,g,I){const e=g,t=I;A.textureDescriptions.length===0&&U(95),A.textureDescriptions.length>8&&U(96,A.textureDescriptions.length);const i=A.textureDescriptions.map((m,K)=>{const k=ev[m.type];return k||U(97,m.type),{_type:m.type,_index:K,_format:m.format??k.defaultFormat,_clearValue:m.clearValue??k.clearValue}}),o=i.map(m=>m._type),Q=o.includes(zg.LINEAR_VELOCITY),r=Q||o.includes(zg.NORMALIZED_VIEW_DEPTH),E=A.samples??1,n=A.size??t.surface;if(A.depthTexture){const m=A.depthTexture._descriptor.samples??1;m!==E&&U(98,m,E)}if(A.targetTexture){const m=A.targetTexture._descriptor.samples??1;m!==E&&U(99,m,E),A.targetTexture._descriptor.format||U(100)}const s=i.map(m=>m._format),c=tBA({label:A.name??"geometry-renderer",colorFormats:s,depthStencilFormat:A.depthTexture?void 0:"depth32float",sampleCount:E,size:n}),l=[],D={};for(let m=0;m<ev.length;m++)D[m]=null;for(const m of i){const K=fBA(c,m);l.push(K),D[m._type]=K}const p=A.depthTexture?null:dBA(c,E),y=A.depthTexture??p,_=Mt(e),u=jt(e,xR),f=VQ(e,t)._buffer,h=e._device.createBindGroup({layout:_,entries:[{binding:0,resource:{buffer:u}},{binding:1,resource:{buffer:f}}]}),w=r?jt(e,80):null,M=r?new X(20):null,S=i.map(()=>({view:void 0,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}));if(A.targetTexture){const m=A.targetTextureClearColor!==void 0;S.push({view:void 0,loadOp:m?"clear":"load",storeOp:"store",...m?{clearValue:A.targetTextureClearColor}:{}})}const R={label:A.name??"geometry-renderer",colorAttachments:S},N=s.slice();A.targetTexture&&N.push(A.targetTexture._descriptor.format);const F={_colorFormat:N.join(),_colorFormats:N,_depthStencilFormat:(A.depthTexture?A.depthTexture._descriptor.dFormat:c._descriptor.depthStencilFormat)??"depth32float",_depthCompare:"greater-equal",_sampleCount:E},G={name:A.name??"geometry-renderer",engine:e,scene:t,_passes:[],_mrt:c,outputTexture:A.targetTexture,geometryDepthTexture:y,geometryIrradianceTexture:D[zg.IRRADIANCE],geometryWorldPositionTexture:D[zg.WORLD_POSITION],geometryLocalPositionTexture:D[zg.LOCAL_POSITION],geometryReflectivityTexture:D[zg.REFLECTIVITY],geometryViewDepthTexture:D[zg.VIEW_DEPTH],geometryNormalizedViewDepthTexture:D[zg.NORMALIZED_VIEW_DEPTH],geometryScreenspaceDepthTexture:D[zg.SCREENSPACE_DEPTH],geometryViewNormalTexture:D[zg.VIEW_NORMAL],geometryWorldNormalTexture:D[zg.WORLD_NORMAL],geometryAlbedoTexture:D[zg.ALBEDO],geometryLinearVelocityTexture:D[zg.LINEAR_VELOCITY],excludeFromVelocity(m){G._excludedFromVelocity.add(m)},includeInVelocity(m){G._excludedFromVelocity.delete(m)},_attachments:i,_views:new Map,_bound:[],_wrapperTargets:l,_ownedDepthWrapper:p,_sceneUBO:u,_sceneBG:h,_sceneData:new X(xR/4),_paramsUBO:w,_paramsData:M,_previousViewProjection:new X(16),_viewProjectionScratch:new X(16),_renderPassDescriptor:R,_colorAttachments:S,_depthAttachment:null,_removedMeshes:null,_boundVer:-1,_ownLightsUBO:null,_ownLightsScratch:null,_ownedDepth:!1,_excludedFromVelocity:new Set,_needsVelocity:Q,_needsParams:r,_signature:F,_createStandardGeometryView:null,_computeStandardFeatures:null,_createPbrGeometryView:null,_computePbrFeatures:null,_createNodeGeometryView:null,_removeMesh(m){(G._removedMeshes??=new WeakSet).add(m)},async _preload(){const m=A.meshes??t.meshes;let K=!1,k=!1,L=!1;for(const q of m){const CA=uBA(q.material);CA==="standard"?K=!0:CA==="pbr"?k=!0:CA==="node"&&(L=!0)}const H=[];K&&H.push((async()=>{const[q,CA]=await Promise.all([Promise.resolve().then(()=>iYA),Promise.resolve().then(()=>PcA)]);G._createStandardGeometryView=q.createStandardGeometryMaterialView,G._computeStandardFeatures=CA._computeStandardMaterialFeatures,await q.preloadStandardGeometryFeatures(m,G._needsVelocity)})()),k&&H.push((async()=>{const[q,CA]=await Promise.all([Promise.resolve().then(()=>RYA),Promise.resolve().then(()=>B0A)]);G._createPbrGeometryView=q.createPbrGeometryMaterialView,G._computePbrFeatures=CA._computePbrMaterialFeatures})()),L&&H.push((async()=>{const q=await Promise.resolve().then(()=>TYA);G._createNodeGeometryView=q.createNodeGeometryMaterialView})()),await Promise.all(H)},record(){EBA(G,A,e,t)},execute(){return DBA(G,e,t,A)},dispose(){_BA(G,e,t)}};return G}function EBA(A,g,I,e){CBA(A._mrt,I),A._ownedDepth=!g.depthTexture,g.targetTexture&&!g.targetTexture._colorTexture&&Kt(g.targetTexture,I);const t=A._mrt;for(const o of A._attachments){const Q=A._wrapperTargets[o._index];Q._colorTexture=oBA(t,o._index),Q._colorView=iBA(t,o._index),Q._width=t._width,Q._height=t._height}A._ownedDepthWrapper&&(A._ownedDepthWrapper._depthTexture=t._depthTexture,A._ownedDepthWrapper._depthView=t._depthView,A._ownedDepthWrapper._width=t._width,A._ownedDepthWrapper._height=t._height);const i=aBA(A,I,e,g);A._sceneBG=I._device.createBindGroup({layout:Mt(I),entries:[{binding:0,resource:{buffer:A._sceneUBO}},{binding:1,resource:{buffer:i}}]}),tv(A,g,I,e),sBA(A,g)}function tv(A,g,I,e){const t=A._bound,i=[...A._views.values()],o=[],Q=new Map,r=A._removedMeshes,E=g.meshes??e.meshes,n=A._attachments.map(s=>s._type);try{for(const s of E){if(r?.has(s)){if(!e.meshes.includes(s))continue;r.delete(s)}const c=hBA(A,s.material);if(!c)continue;const l=nBA(A,Q,c,n,g),p=l._buildGroup._rebuildSingle(e,s,l).bind(I,A._signature);o.push({_mesh:s,_binding:p,_view:l})}}catch(s){throw b3(I,e,o,[...Q.values()]),s}o.sort((s,c)=>(Cv(s._binding.renderable)?1:0)-(Cv(c._binding.renderable)?1:0)),A._bound=o,A._views=Q,A._boundVer=e._renderableVersion,(t.length>0||i.length>0)&&b3(I,e,t,i)}function b3(A,g,I,e){for(const t of I){const i=t._binding.renderable._geometryDispose;if(!i)continue;const o=g._meshAuxDisposables.get(t._mesh);if(!o)continue;const Q=o.indexOf(i);Q>=0&&o.splice(Q,1),o.length===0&&g._meshAuxDisposables.delete(t._mesh)}G1(A,()=>{for(const t of I)t._binding.renderable._geometryDispose?.();for(const t of e)t._disposeGeometryResources?.()})}function nBA(A,g,I,e,t){const i=g.get(I._mat);if(i)return i;const o={attachments:e,emitColor:t.targetTexture!==void 0,gpUBO:A._paramsUBO,reverseCulling:t.reverseCulling,camera:t.camera??null},Q=I._family==="standard"?A._createStandardGeometryView(I._mat,{...o,velocityExclusions:A._excludedFromVelocity}):I._family==="pbr"?A._createPbrGeometryView(I._mat,o):A._createNodeGeometryView(I._mat,o);return g.set(I._mat,Q),Q}function Cv(A){return A.isTransparent===!0}function sBA(A,g){const I=A._mrt;for(const o of A._attachments){const Q=A._colorAttachments[o._index];Q.view=I._colorViews[o._index],Q.resolveTarget=I._resolveColorViews[o._index]??void 0,Q.loadOp="clear",Q.storeOp="store",Q.clearValue=o._clearValue}if(g.targetTexture){const o=A._colorAttachments[A._attachments.length];o.view=g.targetTexture._colorView,o.resolveTarget=void 0}let e,t,i;g.depthTexture?(e=g.depthTexture._depthView,t=g.depthTexture._descriptor.dFormat,i=g.depthTexture._descriptor._depthClearValue??0):(e=I._depthView,t=I._descriptor.depthStencilFormat,i=0),A._depthAttachment=e?{view:e,depthClearValue:i,depthLoadOp:"clear",depthStoreOp:"store",...t?.includes("stencil")?{stencilClearValue:0,stencilLoadOp:"clear",stencilStoreOp:"store"}:{}}:null,A._renderPassDescriptor.colorAttachments=A._colorAttachments,A._renderPassDescriptor.depthStencilAttachment=A._depthAttachment??void 0}function iv(A,g){return!!A.useFloatingOrigin&&!!g.camera}function aBA(A,g,I,e){return iv(g,e)?(A._ownLightsUBO||(A._ownLightsScratch=new X(d3()/4),A._ownLightsUBO=jt(g,d3())),A._ownLightsUBO):VQ(g,I)._buffer}function cBA(A,g,I,e){const t=A._ownLightsScratch;!t||!iv(g,e)||(KiA(g,t,{camera:e.camera,lights:I.lights}),g._device.queue.writeBuffer(A._ownLightsUBO,0,t))}function lBA(A,g,I){A[28]=0,A[29]=0,A[30]=0;const e=li(g,I);Oe(A,0,e,0,A,16)}function DBA(A,g,I,e){const t=e.camera??I.camera;if(!t)return 0;const i=A._mrt;if(i._width===0||i._height===0)return 0;I._renderableVersion!==A._boundVer&&tv(A,e,g,I);const o=i._width/i._height;pBA(A,g,I,t,o),cBA(A,g,I,e),A._needsParams&&yBA(A,g,t);const Q={targetWidth:i._width,targetHeight:i._height,_camera:t};for(const s of A._bound)s._binding.update?.(Q);const r=g._currentEncoder.beginRenderPass(A._renderPassDescriptor);r.setBindGroup(0,A._sceneBG);let E=null,n=0;for(const s of A._bound){if(s._mesh.visible===!1)continue;const c=s._binding.pipeline;c!==E&&(r.setPipeline(c),E=c),n+=s._binding.draw(r,g)}return r.end(),A._needsVelocity&&A._previousViewProjection.set(A._viewProjectionScratch),n}function pBA(A,g,I,e,t){const i=A._sceneData;y6(i,g,I,e,t);const o=I._sceneUboContributors;if(o)for(const Q of o)Q(i,I);g.useFloatingOrigin&&lBA(i,e,t),A._viewProjectionScratch.set(i.subarray(0,16)),g._device.queue.writeBuffer(A._sceneUBO,0,i)}function yBA(A,g,I){const e=A._paramsData;e.set(A._previousViewProjection,0),e[16]=I.nearPlane,e[17]=I.farPlane,e[18]=0,e[19]=0,g._device.queue.writeBuffer(A._paramsUBO,0,e)}function _BA(A,g,I){(A._bound.length>0||A._views.size>0)&&b3(g,I,[...A._bound],[...A._views.values()]),A._passes.length=0,A._bound.length=0,A._views.clear(),gv(A._mrt),A._ownedDepth=!1,A._sceneUBO.destroy(),A._paramsUBO?.destroy(),A._ownLightsUBO?.destroy(),A._ownLightsUBO=null,A._ownLightsScratch=null,A._wrapperTargets.length=0}function uBA(A){if(!A)return null;const g=AC(A)._buildGroup?._materialFamily;return g==="standard"||g==="pbr"||g==="node"?g:null}function hBA(A,g){if(!g)return null;const I=AC(g),e=I._buildGroup;if(!e)return null;if(e._materialFamily==="standard"){const t=I;return t._renderFeatures||(t._renderFeatures={features:A._computeStandardFeatures(t)}),{_mat:t,_family:"standard"}}if(e._materialFamily==="pbr"){const t=I;return t._renderFeatures||(t._renderFeatures=A._computePbrFeatures(t)),{_mat:t,_family:"pbr"}}return e._materialFamily==="node"?{_mat:I,_family:"node"}:null}function fBA(A,g){const I=A._descriptor;return{_descriptor:{lbl:`${I.label??"geometry"}.${g._index}`,format:g._format,samples:1,size:I.size},_colorTexture:null,_colorView:null,_depthTexture:null,_depthView:null,_width:0,_height:0,_eager:!0}}function dBA(A,g){const I=A._descriptor;return{_descriptor:{lbl:`${I.label??"geometry"}.depth`,dFormat:I.depthStencilFormat,samples:g,size:I.size},_colorTexture:null,_colorView:null,_depthTexture:null,_depthView:null,_width:0,_height:0,_eager:!0}}function wBA(A,g){"canvas"in g.size&&U(571);const I=g.size,e=wt(g);if(Kt(e,A),e._eager=!0,!e._colorTexture||!e._colorView){e._depthTexture||U(572);const i={texture:e._depthTexture,view:e._depthTexture.createView({aspect:"depth-only"}),sampler:X6(A),width:I.width,height:I.height,invertY:!1,_sampleType:"depth"};return{rt:e,texture:i}}const t={texture:e._colorTexture,view:e._colorView,sampler:m1(A),width:I.width,height:I.height,invertY:!0};return{rt:e,texture:t}}const MBA={magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat",addressModeW:"repeat",maxAnisotropy:4};function ov(A){return Pe(A,MBA)}const SBA="@group(0)@binding(0)var t:texture_2d<f32>;@group(0)@binding(1)var s:sampler;struct V{@builtin(position)p:vec4f,@location(0)u:vec2f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return V(vec4f(p,0,1),p*vec2f(.5,-.5)+.5);}@fragment fn fs(v:V)->@location(0)vec4f{return textureSample(t,s,v.u);}";let WR=null,fF=null,K3=null,dF=null,k3=null;function RBA(){WR?.clear(),WR=null,fF=null,K3=null,dF=null,k3=null}function NBA(A){const g=A._device;g!==k3&&(RBA(),k3=g),fF??=g.createShaderModule({code:SBA}),K3??=m1(A),dF??=g.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:NA.FRAGMENT,sampler:{}}]})}function GBA(A,g){const I=A._device;NBA(A),WR??=new Map;let e=WR.get(g);return e||(e=I.createRenderPipeline({layout:I.createPipelineLayout({bindGroupLayouts:[dF]}),vertex:{module:fF,entryPoint:"vs"},fragment:{module:fF,entryPoint:"fs",targets:[{format:g}]},primitive:{topology:"triangle-list"}}),WR.set(g,e)),e}function ZQ(A,g,I){const e=A._device,t=e.createCommandEncoder();wF(A,g,t,I),e.queue.submit([t.finish()])}function wF(A,g,I,e){if(g.mipLevelCount<=1)return;const t=A._device,i=GBA(A,g.format),o=e!=null?{dimension:"2d",baseArrayLayer:e,arrayLayerCount:1}:{};for(let Q=1;Q<g.mipLevelCount;Q++){const r=g.createView({baseMipLevel:Q-1,mipLevelCount:1,...o}),E=g.createView({baseMipLevel:Q,mipLevelCount:1,...o}),n=t.createBindGroup({layout:dF,entries:[{binding:0,resource:r},{binding:1,resource:K3}]}),s=I.beginRenderPass({colorAttachments:[{view:E,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});s.setPipeline(i),s.setBindGroup(0,n),s.draw(3),s.end()}}const zR=Object.freeze(Object.defineProperty({__proto__:null,generateMipmaps:ZQ,recordMipmaps:wF},Symbol.toStringTag,{value:"Module"}));function XQ(A,g){return Math.floor(Math.log2(Math.max(A,g)))+1}function FBA(A,g,I){const e=Math.max(A,g);return Math.max(1,Math.floor(Math.log2(e)-I)+1)}let MF=null;function mBA(A){MF=A}const bBA="@group(0)@binding(0)var t:texture_2d<f32>;@group(0)@binding(1)var s:sampler;struct V{@builtin(position)p:vec4f,@location(0)u:vec2f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{var p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));var u=array<vec2f,3>(vec2f(0,1),vec2f(2,1),vec2f(0,-1));return V(vec4f(p[i],0,1),u[i]);}@fragment fn fs(v:V)->@location(0)vec4f{return textureSample(t,s,v.u);}",KBA="@group(0)@binding(0)var t:texture_multisampled_2d<f32>;struct V{@builtin(position)p:vec4f,@location(0)u:vec2f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{var p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));var u=array<vec2f,3>(vec2f(0,1),vec2f(2,1),vec2f(0,-1));return V(vec4f(p[i],0,1),u[i]);}fn l(p:vec2i)->vec4f{let n=textureNumSamples(t);var c=vec4f(0);for(var i=0u;i<n;i++){c+=textureLoad(t,p,i);}return c/f32(n);}@fragment fn fs(v:V)->@location(0)vec4f{let d=vec2i(textureDimensions(t));let q=clamp(v.u*vec2f(d)-.5,vec2f(0),vec2f(d-vec2i(1)));let p=vec2i(floor(q));let f=fract(q);let p1=min(p+vec2i(1),d-vec2i(1));return mix(mix(l(p),l(vec2i(p1.x,p.y)),f.x),mix(l(vec2i(p.x,p1.y)),l(p1),f.x),f.y);}",kBA=4;let ZR=null,SF=null,RF=null,NF=null,GF=null,Bv=null;function Qv(A,g){sv(A),rv(A,g)}function UBA(A,g){const I=A.meshes.flatMap(e=>{const t=e.material;return t?[[t,t._linearImageProcessing,t._renderFeatures]]:[]});return sv(A),[()=>rv(A,g),()=>{for(const[e,t,i]of I)e._linearImageProcessing=t,e._renderFeatures=i}]}function rv(A,g){let I=null;for(const e of A._frameGraph._tasks)if("_renderables"in e){const t=e;Ev(t,g),I=t}I&&!A._frameGraph._tasks.some(e=>e.name==="transmission-image-processing")&&A._frameGraph._tasks.push(z6({name:"transmission-image-processing",source:I._config.rt},g,A))}function Ev(A,g,I){const e=I?.linear!==!1;if(ZBA(A,I),A._config.transmission?.grabDepth){const E=A._preload?.bind(A);A._preload=async()=>{E&&await E(),await Promise.resolve().then(()=>VYA)}}const t={get texture(){return A._targetSignature._transmissionTexture??null},get depthTexture(){return A._targetSignature._transmissionDepthTexture??null}};if(A._executeWithTransmission)return t;e&&LBA(A);let i=null;const o=A.record.bind(A),Q=A.execute?.bind(A),r=A.dispose?.bind(A);return A.record=()=>{av(i),i=vBA(A,g),A._targetSignature._transmissionTexture=i.texture,o(),HBA(i,A,g)},e&&Q&&(A.execute=()=>YBA(A.scene,Q)),A.dispose=()=>{av(i),i=null,r?.()},A._executeWithTransmission=E=>TBA(A,g,i,E),t}function LBA(A){const g=A._config,I=g.rt._descriptor,e=A.scene.surface,t=e.msaaSamples,i=!g.depth,o=wt({lbl:"transmission-linear",format:"rgba16float",dFormat:i?I.dFormat??"depth24plus-stencil8":void 0,_depthClearValue:I._depthClearValue,_depthCompare:I._depthCompare,samples:t,size:e});g.rt=o,g.rst=void 0;const Q=A._targetSignature;Q._colorFormat="rgba16float",Q._depthStencilFormat=g.depth?._descriptor.dFormat??o._descriptor.dFormat,Q._depthCompare=o._descriptor._depthCompare,Q._sampleCount=t,A._ob.length=0,A._lastVersion=-1}function YBA(A,g){const I=A.imageProcessing,e=I.toneMappingEnabled,t=A.clearColor,i=JBA(t,I.exposure,I.contrast,e===!0);I.toneMappingEnabled=-1,A.clearColor=i;try{return g()}finally{A.clearColor=t,I.toneMappingEnabled=e}}function JBA(A,g,I,e){return{r:U3(A.r,g,I,e),g:U3(A.g,g,I,e),b:U3(A.b,g,I,e),a:A.a}}function U3(A,g,I,e){let t=nv(A);if(I<1)t=I>0?nv((t-.5*(1-I))/I):.5;else if(I>1){const i=I-1;let o=0,Q=1;for(let r=0;r<16;r++){const E=(o+Q)*.5,n=E*E*(3-2*E);E+(n-E)*i<t?o=E:Q=E}t=(o+Q)*.5}return t=t**2.2,e&&(t=-Math.log2(Math.max(1-t,1e-6))/1.5905790328979492),g>0?t/g:t}function nv(A){return Math.min(Math.max(A,0),1)}function sv(A){for(const g of A.meshes){const I=g.material;I&&(I._linearImageProcessing=!0,I._renderFeatures=void 0)}}function vBA(A,g){const I=A._config.rt,e=1024,t=1024,i="rgba16float",o=XBA(A._config.transmission,e,t),Q=o>1,r=g._device.createTexture({label:A.name,size:{width:e,height:t},format:i,mipLevelCount:o,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING|dA.COPY_DST});return{texture:{texture:r,view:r.createView(),sampler:ov(g),width:e,height:t,invertY:!1},_baseView:r.createView({baseMipLevel:0,mipLevelCount:1}),_sourceWidth:I._width,_sourceHeight:I._height,_sourceTexture:null,_blit:null,_depth:null,_copyCount:zBA(A._config.transmission),_generateMipmaps:Q,_copies:0}}function HBA(A,g,I){const e=g._config.rt;A._sourceWidth=e._width,A._sourceHeight=e._height,A._sourceTexture=e._colorTexture;const t=g._targetSignature._sampleCount,i=g._targetSignature;i._transmissionDepthTexture=null;const o=e._depthTexture;g._config.transmission?.grabDepth&&MF&&o&&e._width>0&&e._height>0&&(A._depth=MF.create(I,o,e._width,e._height,t>1),i._transmissionDepthTexture=A._depth.texture),A._sourceTexture&&(A._blit=PBA(A,t)?OBA(A,I,A._sourceTexture,t>1):null)}function av(A){A?.texture.texture.destroy(),A?._depth?.texture.texture.destroy()}function TBA(A,g,I,e){I._copies=0;const t=A._transparentBindings,i=e>1?A._config.rst?._colorView??null:null;let o=cv(A,i,e,!1),Q=WBA(A,o),r=null,E=null;for(let n=0;n<t.length;n++){const s=t[n];if(s.renderable.mesh?.renderOnTop===!0){(E??=[]).push(s);continue}s.renderable._transmissive===!0&&VBA(I)&&(o.end(),xBA(I,g),o=cv(A,i,e,!0),lv(A,o),r=null);const l=s.renderable.mesh;l&&l.visible===!1||(s.pipeline!==r&&(o.setPipeline(s.pipeline),r=s.pipeline),Q+=s.draw(o,g))}return E&&(Q+=WQ(o,E,g)),o.end(),Q}function xBA(A,g){if(!A._sourceTexture)throw new Error("No transmission source");A._blit?jBA(A,g):g._currentEncoder.copyTextureToTexture({texture:A._sourceTexture},{texture:A.texture.texture},{width:A.texture.width,height:A.texture.height}),A._generateMipmaps&&wF(g,A.texture.texture,g._currentEncoder),A._depth&&MF?.record(g,A._depth),A._copies++}function qBA(A,g,I){const e=A._device;e!==Bv&&(ZR?.clear(),ZR=null,SF=null,RF=null,NF=null,GF=null,Bv=e),I?(RF??=e.createShaderModule({code:KBA}),GF??=e.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"unfilterable-float",multisampled:!0}}]})):(SF??=e.createShaderModule({code:bBA}),NF??=e.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:NA.FRAGMENT,sampler:{}}]})),ZR??=new Map;const t=`${g}:${I?"msaa":""}`;let i=ZR.get(t);if(!i){const o=I?GF:NF;i=e.createRenderPipeline({label:"transmission-copy",layout:e.createPipelineLayout({bindGroupLayouts:[o]}),vertex:{module:I?RF:SF,entryPoint:"vs"},fragment:{module:I?RF:SF,entryPoint:"fs",targets:[{format:g}]},primitive:{topology:"triangle-list"}}),ZR.set(t,i)}return i}function PBA(A,g){return g>1||A._sourceWidth!==A.texture.width||A._sourceHeight!==A.texture.height}function OBA(A,g,I,e){const t=g._device,i=qBA(g,A.texture.texture.format,e),o=t.createBindGroup({layout:e?GF:NF,entries:e?[{binding:0,resource:I.createView()}]:[{binding:0,resource:I.createView()},{binding:1,resource:m1(g)}]});return{_pipeline:i,_bindGroup:o}}function jBA(A,g){const I=A._blit,e=g._currentEncoder.beginRenderPass({colorAttachments:[{view:A._baseView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});e.setPipeline(I._pipeline),e.setBindGroup(0,I._bindGroup),e.draw(3),e.end()}function VBA(A){return A._copyCount===0||A._copies<A._copyCount}function cv(A,g,I,e){const t=A._colorAttachment,i=e||!A._config.clr?"load":"clear";e&&(t.loadOp="load");const o=A._renderPassDescriptor.depthStencilAttachment;return o&&(o.depthLoadOp=i,o.stencilLoadOp&&(o.stencilLoadOp=i)),I>1?t.resolveTarget=g??void 0:t.resolveTarget=void 0,A.engine._currentEncoder.beginRenderPass(A._renderPassDescriptor)}function lv(A,g){const I=A._config,e=I.rt,t=A.scene,o=(I.cam??t.camera)?.viewport;if(o){const Q=e._width,r=e._height,E=Math.floor(o.x*Q),n=Math.floor((1-o.y-o.height)*r),s=Math.ceil((o.x+o.width)*Q)-E,c=Math.ceil((1-o.y)*r)-n;g.setViewport(E,n,s,c,0,1),g.setScissorRect(E,n,s,c)}g.setBindGroup(0,A._sceneBG)}function WBA(A,g){const I=A.engine,e=A._config.rt,t=A.scene,i=A._opaqueBindings,o=A._ob;if(lv(A,g),A._lastVersion!==t._renderableVersion||A._lastVis!==TQ||o.length===0){const r=e._descriptor,E=I._device.createRenderBundleEncoder({colorFormats:r.format?[r.format]:[],depthStencilFormat:r.dFormat,sampleCount:r.samples??1});E.setBindGroup(0,A._sceneBG),WQ(E,i,I),o[0]=E.finish(),A._lastVersion=t._renderableVersion,A._lastVis=TQ}let Q=i.length;return g.executeBundles(o),g.setBindGroup(0,A._sceneBG),Q+=WQ(g,A._directBindings,I),Q}function zBA(A){const g=A?.copyCount??1;return g===1/0?0:Math.max(0,g|0)}function ZBA(A,g){if(!g)return;let I=A._config.transmission,e=!1;const t=(i,o)=>{o!==void 0&&(I={...I,[i]:o},e=!0)};t("copyCount",g.copyCount),t("generateMipmaps",g.generateMipmaps),t("mipLevelCount",g.mipLevelCount),t("grabDepth",g.grabDepth),e&&(A._config.transmission=I)}function XBA(A,g,I){if(A?.generateMipmaps===!1)return 1;const e=Math.floor(Math.log2(Math.max(g,I)))+1,t=FBA(g,I,kBA),i=A?.mipLevelCount;return i===void 0?Math.min(e,t):Math.min(e,Math.max(1,i|0))}const $BA="struct EffectVertexOutput{@builtin(position)position:vec4<f32>,@location(0)uv:vec2<f32>};@vertex fn effectFullscreenVertex(@builtin(vertex_index)vertexIndex:u32)->EffectVertexOutput{var positions=array<vec2<f32>,3>(vec2<f32>(-1.0,-1.0),vec2<f32>(3.0,-1.0),vec2<f32>(-1.0,3.0));let p=positions[vertexIndex];var out:EffectVertexOutput;out.position=vec4<f32>(p,0.0,1.0);out.uv=p*0.5+vec2<f32>(0.5,0.5);return out;}";function AQA(A,g){const I=A,e={name:g.name??"effect-wrapper",options:g,_engine:I,_shader:null,_bindGroupLayout:null,_pipelineLayout:null,_bindGroup:null,_bindGroupDirty:!0,_pipelines:null,_uniforms:[],_textures:[]};return BQA(e),e}function gQA(A,g){const I=A;if(cQA(g)){const e=I._uniforms[0];e||U(30),dv(I,e,g);return}for(const e of Object.keys(g)){const t=hv(I,e);t||U(31,e),dv(I,t,g[e])}}function IQA(A,g,I){const e=A,t=Y3(e,g);t||U(32,String(g)),t.texture=I,e._bindGroupDirty=!0}function eQA(A,g,I){const e=g,t=A.effect,i=A.target;A.clearColor??={r:0,g:0,b:0,a:1};const o=i._descriptor.samples??1,Q={_colorFormat:i._descriptor.format,_sampleCount:o},r={loadOp:"clear",storeOp:"store"},E={name:A.name,_config:A,engine:e,scene:I,_passes:[],_rt:i,_targetSignature:Q,_renderPassDescriptor:{label:A.name,colorAttachments:[r]},_colorAttachment:r,_pipeline:null,_bindGroup:null,record(){Kt(i,e),E._pipeline=yv(t,E._targetSignature),E._bindGroup=L3(t)},execute(){const n=E._pipeline;n||U(33,E.name),E._bindGroup=L3(t),pv(E._colorAttachment,i,void 0,E._config.clear!==!1,E._config.clearColor);const s=e._currentEncoder.beginRenderPass(E._renderPassDescriptor);return s.setPipeline(n),E._bindGroup&&s.setBindGroup(0,E._bindGroup),s.draw(3),s.end(),1},dispose(){E._passes.length=0,Se(E._rt),E._pipeline=null,E._bindGroup=null}};return E}function tQA(A){const g=A;for(const I of g._uniforms)I.buffer.destroy();g._uniforms.length=0,g._textures.length=0,g._pipelines?.clear(),g._pipelines=null,g._shader=null,g._bindGroupLayout=null,g._pipelineLayout=null,g._bindGroup=null,g._bindGroupDirty=!0}function CQA(A,g,I){const e=A.engine,t=g,i=I?.name??g.name,o=I?.clear!==!1,Q=I?.clearColor??{r:0,g:0,b:0,a:1},r=I?.update,E=A.msaaSamples>1,n=E?wt({lbl:`${i}-msaa`,format:A.format,samples:A.msaaSamples,size:A}):A.scRT,s=E?A.scRT:void 0,c={_colorFormat:n._descriptor.format,_sampleCount:n._descriptor.samples??1},l={view:void 0,loadOp:"clear",storeOp:"store"},p={_kind:"effect-renderer",name:i,clearColor:Q,_drawCallsPre:0,_surface:A,_effect:t,_clear:o,_rt:n,_targetSignature:c,_renderPassDescriptor:{label:i,colorAttachments:[l]},_colorAttachment:l,_pipeline:null,_bindGroup:null,_disposed:!1,_update(){r?.(e._currentDelta)},_record(){if(p._disposed)return 0;QQA(p._rt),pv(p._colorAttachment,p._rt,s,p._clear,p.clearColor);const y=p._surface.engine._currentEncoder;if(!y)return 0;const _=p._pipeline;_||U(34,p.name);const u=y.beginRenderPass(p._renderPassDescriptor);return u.setPipeline(_),p._bindGroup&&u.setBindGroup(0,p._bindGroup),u.draw(3),u.end(),1},_resize(){p._disposed||Kt(p._rt,p._surface.engine)}};return p}function iQA(A){const g=A;nQA(g),xQ(g._surface,A)}function Dv(A){qQ(A._surface,A)}function oQA(A){const g=A;g._disposed||(Dv(A),Se(g._rt),g._disposed=!0)}function BQA(A){const g=[...A.options.bindings??[]].sort((e,t)=>e.binding-t.binding),I=new Set;for(const e of g)if(I.has(e.binding)&&U(35,e.binding),I.add(e.binding),e.kind==="uniform"){const t=lQA(e.uniformByteLength??16),i=A._engine._device.createBuffer({label:`${A.name}-${e.name??e.binding}-ubo`,size:t,usage:SA.UNIFORM|SA.COPY_DST});A._uniforms.push({layout:e,buffer:i,byteLength:t})}else e.kind==="texture"&&A._textures.push({layout:e,texture:null})}function pv(A,g,I,e,t){A.clearValue=t,A.loadOp=e?"clear":"load",A.view=g._colorView,A.resolveTarget=I?._colorView??void 0}function QQA(A){const g=A._descriptor.size;if(!("canvas"in g))return;const I=g.canvas;A._width===I.width&&A._height===I.height||Kt(A,g.engine)}function yv(A,g){const I=Ot(g);A._pipelines||(A._pipelines=new Map);const e=A._pipelines.get(I);if(e)return e;const i=A._engine._device.createRenderPipeline({label:`${A.name}-${I}`,layout:rQA(A),vertex:{module:_v(A),entryPoint:"effectFullscreenVertex"},fragment:{module:_v(A),entryPoint:"effectFragment",targets:[{format:g._colorFormat,blend:A.options.blend}]},primitive:{topology:"triangle-list"},multisample:{count:g._sampleCount}});return A._pipelines.set(I,i),i}function _v(A){return A._shader||(A._shader=A._engine._device.createShaderModule({label:A.name,code:`${A.options.vertexWGSL??$BA} ${A.options.fragmentWGSL}`})),A._shader}function rQA(A){return A._pipelineLayout||(A._pipelineLayout=A._engine._device.createPipelineLayout({label:`${A.name}-pipeline-layout`,bindGroupLayouts:[uv(A)]})),A._pipelineLayout}function uv(A){if(!A._bindGroupLayout){const g=(A.options.bindings??[]).slice().sort((I,e)=>I.binding-e.binding).map(I=>EQA(I));A._bindGroupLayout=A._engine._device.createBindGroupLayout({label:`${A.name}-bgl`,entries:g})}return A._bindGroupLayout}function EQA(A){const g=A.visibility??NA.FRAGMENT;return A.kind==="uniform"?{binding:A.binding,visibility:g,buffer:{type:"uniform"}}:A.kind==="texture"?{binding:A.binding,visibility:g,texture:{sampleType:A.textureSampleType??"float",viewDimension:A.viewDimension??"2d"}}:{binding:A.binding,visibility:g,sampler:{type:A.samplerType??"filtering"}}}function L3(A){const g=A.options.bindings??[];if(g.length===0)return null;if(!A._bindGroupDirty&&A._bindGroup)return A._bindGroup;const I=g.slice().sort((e,t)=>e.binding-t.binding).map(e=>sQA(A,e));return A._bindGroup=A._engine._device.createBindGroup({label:`${A.name}-bg`,layout:uv(A),entries:I}),A._bindGroupDirty=!1,A._bindGroup}function nQA(A){A._pipeline??=yv(A._effect,A._targetSignature),A._bindGroup=L3(A._effect)}function sQA(A,g){if(g.kind==="uniform"){const e=hv(A,g.binding);return e||U(36,A.name,g.binding),{binding:g.binding,resource:{buffer:e.buffer,size:e.byteLength}}}if(g.kind==="texture"){const e=Y3(A,g.binding);return e?.texture||U(37,A.name,g.binding),{binding:g.binding,resource:e.texture.view}}const I=g.textureBinding!=null?Y3(A,g.textureBinding):A._textures[0];return I?.texture||U(38,A.name,g.binding),{binding:g.binding,resource:I.texture.sampler}}function hv(A,g){return A._uniforms.find(I=>fv(I.layout,g))}function Y3(A,g){return A._textures.find(I=>fv(I.layout,g))}function fv(A,g){return typeof g=="number"?A.binding===g:A.name===g||String(A.binding)===g}function dv(A,g,I){const e=aQA(I);e.byteLength>g.byteLength&&U(39,e.byteLength,g.layout.binding,g.byteLength),A._engine._device.queue.writeBuffer(g.buffer,0,e.buffer,e.byteOffset,e.byteLength)}function aQA(A){return A instanceof ArrayBuffer?new mg(A):new mg(A.buffer,A.byteOffset,A.byteLength)}function cQA(A){return A instanceof ArrayBuffer||ArrayBuffer.isView(A)}function lQA(A){return A+3&-4}const DQA="struct EffectVertexOutput{@builtin(position)position:vec4<f32>,@location(0)uv:vec2<f32>};@vertex fn effectFullscreenVertex(@builtin(vertex_index)vertexIndex:u32)->EffectVertexOutput{var positions=array<vec2<f32>,3>(vec2<f32>(-1.0,-1.0),vec2<f32>(3.0,-1.0),vec2<f32>(-1.0,3.0));let p=positions[vertexIndex];var out:EffectVertexOutput;out.position=vec4<f32>(p,0.0,1.0);out.uv=p*0.5+vec2<f32>(0.5,0.5);return out;}";function pQA(A,g){const I=A,e=SQA(g.uniformByteLength);return{name:g.name??"uniform-effect-wrapper",options:g,_engine:I,_shader:null,_bindGroupLayout:null,_pipelineLayout:null,_bindGroup:null,_uniformBuffer:I._device.createBuffer({label:`${g.name??"uniform-effect-wrapper"}-ubo`,size:e,usage:SA.UNIFORM|SA.COPY_DST}),_uniformByteLength:e}}function yQA(A,g){const I=A,e=MQA(g);e.byteLength>I._uniformByteLength&&U(40,e.byteLength,I._uniformByteLength),I._engine._device.queue.writeBuffer(I._uniformBuffer,0,e.buffer,e.byteOffset,e.byteLength)}function _QA(A,g,I){const e=g,t=A.effect,i=A.target;A.clearColor??={r:0,g:0,b:0,a:1};const o=i._descriptor.samples??1,Q={_colorFormat:i._descriptor.format,_sampleCount:o},r={loadOp:"clear",storeOp:"store"},E={name:A.name,_config:A,engine:e,scene:I,_passes:[],_rt:i,_targetSignature:Q,_renderPassDescriptor:{label:A.name,colorAttachments:[r]},_colorAttachment:r,_pipeline:null,record(){Kt(i,e),E._pipeline=fQA(t,E._targetSignature)},execute(){const n=E._pipeline;n||U(41,E.name),hQA(E._colorAttachment,i,E._config.clear!==!1,E._config.clearColor);const s=e._currentEncoder.beginRenderPass(E._renderPassDescriptor);return s.setPipeline(n),s.setBindGroup(0,wQA(t)),s.draw(3),s.end(),1},dispose(){E._passes.length=0,Se(E._rt),E._pipeline=null}};return E}function uQA(A){const g=A;g._uniformBuffer.destroy(),g._shader=null,g._bindGroupLayout=null,g._pipelineLayout=null,g._bindGroup=null}function hQA(A,g,I,e){A.clearValue=e,A.loadOp=I?"clear":"load",A.view=g._colorView,A.resolveTarget=void 0}function fQA(A,g){return A._engine._device.createRenderPipeline({label:`${A.name}-${Ot(g)}`,layout:dQA(A),vertex:{module:wv(A),entryPoint:"effectFullscreenVertex"},fragment:{module:wv(A),entryPoint:"effectFragment",targets:[{format:g._colorFormat}]},primitive:{topology:"triangle-list"},multisample:{count:g._sampleCount}})}function wv(A){return A._shader||(A._shader=A._engine._device.createShaderModule({label:A.name,code:`${A.options.vertexWGSL??DQA} ${A.options.fragmentWGSL}`})),A._shader}function dQA(A){return A._pipelineLayout||(A._pipelineLayout=A._engine._device.createPipelineLayout({label:`${A.name}-pipeline-layout`,bindGroupLayouts:[Mv(A)]})),A._pipelineLayout}function Mv(A){return A._bindGroupLayout||(A._bindGroupLayout=A._engine._device.createBindGroupLayout({label:`${A.name}-bgl`,entries:[{binding:0,visibility:NA.FRAGMENT,buffer:{type:"uniform"}}]})),A._bindGroupLayout}function wQA(A){return A._bindGroup||(A._bindGroup=A._engine._device.createBindGroup({label:`${A.name}-bg`,layout:Mv(A),entries:[{binding:0,resource:{buffer:A._uniformBuffer,size:A._uniformByteLength}}]})),A._bindGroup}function MQA(A){return A instanceof ArrayBuffer?new mg(A):new mg(A.buffer,A.byteOffset,A.byteLength)}function SQA(A){return A+3&-4}const RQA=(A,g)=>`struct PostProcessVertexOutput{@builtin(position)position:vec4f,@location(0)uv:vec2f${A}}@vertex fn postProcessVertex(@builtin(vertex_index)vertexIndex:u32)->PostProcessVertexOutput{var positions=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));let p=positions[vertexIndex];var out:PostProcessVertexOutput;out.position=vec4f(p,0,1);out.uv=vec2f(p.x*0.5+0.5,0.5-p.y*0.5);${g}return out;}`,NQA="@group(0)@binding(0)var sourceSampler:sampler;@group(0)@binding(1)var sourceTextureSampler:texture_2d<f32>;fn samplePostProcessSource(uv:vec2f)->vec4f{return textureSample(sourceTextureSampler,sourceSampler,uv);}fn readPostProcessSource(uv:vec2f)->vec4f{let dims=vec2f(textureDimensions(sourceTextureSampler));let p=clamp(floor(uv*dims)+vec2f(0.5),vec2f(0.5),dims-vec2f(0.5));return textureSampleLevel(sourceTextureSampler,sourceSampler,p/dims,0);}",GQA="@fragment fn postProcessFragment(input:PostProcessVertexOutput)->@location(0)vec4f{return applyPostProcess(samplePostProcessSource(input.uv),input.uv);}";function Vt(A,g,I){const e=A.sourceTexture,t=A.targetTexture?null:Rv(A.name??"post-process",e),i={view:void 0,loadOp:"clear",storeOp:"store"},o={name:A.name??"post-process",engine:g,scene:I,_passes:[],sourceTexture:e,sourceSamplingMode:A.sourceSamplingMode??"linear",targetTexture:A.targetTexture??null,alphaMode:A.alphaMode??0,viewport:A.viewport??null,clear:A.clear??!0,outputTexture:A.targetTexture??t,_shader:A._shader,_internalTarget:t,_internalTargetKey:t?Nv(e):"",_pipeline:null,_bindGroup:null,_bindGroupLayout:null,_pipelineLayout:null,_shaderModule:null,_shaderModuleCode:"",_uniformBuffer:null,_uniformData:null,_renderPassDescriptor:{label:A.name??"post-process",colorAttachments:[i]},_colorAttachment:i,record(){FQA(o),Kt(o.outputTexture,g),Sv(o,g)},execute(){kQA(o._colorAttachment,o.outputTexture,o.clear);const Q=g._currentEncoder.beginRenderPass(o._renderPassDescriptor);return UQA(Q,o.viewport,o.outputTexture),Q.setPipeline(o._pipeline),Q.setBindGroup(0,o._bindGroup),Q.draw(3),Q.end(),1},updateUniforms(){mv(o,g)},_rebuildGpuState(){Sv(o,g)},dispose(){o._passes.length=0,o._uniformBuffer?.destroy(),o._uniformBuffer=null,o._uniformData=null,o._pipeline=null,o._bindGroup=null,o._bindGroupLayout=null,o._pipelineLayout=null,o._shaderModule=null,o._shaderModuleCode="",Se(o._internalTarget)}};return o}function Sv(A,g){const I=A.sourceTexture;(!I._colorTexture||!I._colorView)&&U(107,A.name),(I._descriptor.samples??1)!==1&&U(108,A.name);const e=A.outputTexture,t=e._descriptor.format;t||U(109,A.name),A._uniformBuffer??=bQA(A,g),A._uniformData??=KQA(A),mv(A,g);const i=mQA(A,g);A._pipelineLayout??=g._device.createPipelineLayout({label:`${A.name}-pipeline-layout`,bindGroupLayouts:[i]});const o={_colorFormat:t,_sampleCount:e._descriptor.samples??1};A._pipeline=g._device.createRenderPipeline({label:`${A.name}-${Ot(o)}-${A.alphaMode}`,layout:A._pipelineLayout,vertex:{module:Fv(A,g),entryPoint:"postProcessVertex"},fragment:{module:Fv(A,g),entryPoint:"postProcessFragment",targets:[{format:t,blend:LQA(A.alphaMode)}]},primitive:{topology:"triangle-list"},multisample:{count:o._sampleCount}});const Q=[{binding:0,resource:A.sourceSamplingMode==="nearest"?X6(g):m1(g)},{binding:1,resource:I._colorView}],r=A._shader.extraTextures??[];A._uniformBuffer&&Q.push({binding:Gv(A),resource:{buffer:A._uniformBuffer}});for(let E=0;E<r.length;E++){const n=r[E];n._colorView||U(110,A.name,E),Q.push({binding:2+E,resource:n._colorView})}A._bindGroup=g._device.createBindGroup({label:`${A.name}-bind-group`,layout:i,entries:Q})}function FQA(A){const g=A.targetTexture;if(g){A.outputTexture=g;return}const I=Nv(A.sourceTexture);if(A._internalTarget&&A._internalTargetKey===I){A.outputTexture=A._internalTarget;return}A._internalTarget&&Se(A._internalTarget),A._internalTarget=Rv(A.name,A.sourceTexture),A._internalTargetKey=I,A.outputTexture=A._internalTarget}function Rv(A,g){const I=g._descriptor;I.format||U(111,A);const e={lbl:`${A}-output`,format:I.format,samples:1,size:I.size};return wt(e)}function Nv(A){const g=A._descriptor,I=g.size,e="canvas"in I?`surface:${I._uniqueId}`:`${I.width}x${I.height}`;return`${g.format??"-"}|${g.samples??1}|${e}`}function mQA(A,g){const I=(A._shader.uniformByteLength??0)>0;if(A._bindGroupLayout)return A._bindGroupLayout;const e=[{binding:0,visibility:NA.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:NA.FRAGMENT,texture:{sampleType:"float"}}],t=A._shader.extraTextures??[];for(let i=0;i<t.length;i++)e.push({binding:2+i,visibility:NA.FRAGMENT,texture:{sampleType:"float"}});return I&&e.push({binding:Gv(A),visibility:NA.VERTEX|NA.FRAGMENT,buffer:{type:"uniform"}}),A._bindGroupLayout=g._device.createBindGroupLayout({label:`${A.name}-bind-group-layout`,entries:e}),A._bindGroupLayout}function Gv(A){return A._shader.uniformBinding??2+(A._shader.extraTextures?.length??0)}function Fv(A,g){const I=`${RQA(A._shader.vertexOutputWGSL??"",A._shader.vertexMainWGSL??"")} ${NQA} ${A._shader.extraTextureWGSL??""} ${A._shader.uniformWGSL??""} ${A._shader.fragmentWGSL} ${A._shader.fragmentWrapperWGSL??GQA}`;return(!A._shaderModule||A._shaderModuleCode!==I)&&(A._shaderModuleCode=I,A._shaderModule=g._device.createShaderModule({label:A.name,code:I})),A._shaderModule}function bQA(A,g){const I=bv(A._shader.uniformByteLength??0);return I===0?null:g._device.createBuffer({label:`${A.name}-uniforms`,size:I,usage:SA.UNIFORM|SA.COPY_DST})}function KQA(A){const g=bv(A._shader.uniformByteLength??0);return g===0?null:new X(g/4)}function mv(A,g){(A._shader.uniformByteLength??0)!==0&&(A._uniformData.fill(0),A._shader.writeUniforms?.(A._uniformData),g._device.queue.writeBuffer(A._uniformBuffer,0,A._uniformData))}function kQA(A,g,I){A.view=g._colorView,A.resolveTarget=void 0,A.loadOp=I?"clear":"load"}function UQA(A,g,I){if(!g)return;const e=Math.floor(g.x*I._width),t=Math.floor((1-g.y-g.height)*I._height),i=Math.ceil((g.x+g.width)*I._width)-e,o=Math.ceil((1-g.y)*I._height)-t;A.setViewport(e,t,i,o,0,1),A.setScissorRect(e,t,i,o)}function LQA(A){switch(A){case 1:return{color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one",operation:"add"}};case 2:return{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};case 7:return{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};default:return}}function bv(A){return Math.ceil(A/16)*16}const YQA="struct BlackAndWhiteParams{degree:f32,p0:f32,p1:f32,p2:f32}@group(0)@binding(2)var<uniform>blackAndWhiteParams:BlackAndWhiteParams;",JQA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let luminance=dot(color.rgb,vec3f(0.3,0.59,0.11));let gray=vec3f(luminance);return vec4f(mix(color.rgb,gray,clamp(blackAndWhiteParams.degree,0,1)),color.a);}";function vQA(A,g,I){const e={degree:A.degree??1},t=Vt({name:A.name??"black-and-white",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode,targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{uniformWGSL:YQA,uniformByteLength:16,writeUniforms(i){i[0]=e.degree},fragmentWGSL:JQA}},g,I);return Object.defineProperty(t,"degree",{get:()=>e.degree,set:i=>{e.degree=i}}),t}const HQA="@group(0)@binding(2)var leftTextureSampler:texture_2d<f32>;",TQA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let l=textureSampleLevel(leftTextureSampler,sourceSampler,clamp(uv,vec2f(0),vec2f(1)),0);let left=vec4f(1,l.g,l.b,1);let right=vec4f(color.r,1,1,1);return vec4f(right.rgb*left.rgb,1);}";function xQA(A,g,I){const e=Vt({name:A.name??"anaglyph",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode,targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{extraTextureWGSL:HQA,extraTextures:[A.leftTexture],fragmentWGSL:TQA}},g,I);return e.leftTexture=A.leftTexture,e}const qQA=8,PQA="struct BlurParams{delta:vec2f,p0:f32,p1:f32}@group(0)@binding(2)var<uniform>blurParams:BlurParams;";function OQA(A){const g=Math.max(1,Math.round(A));for(const I of[g,g-1,g+1,g-2,g+2])if(I>0&&I%2!==0&&Math.floor(I/2)%2===0)return Math.max(I,3);return Math.max(g,3)}function jQA(A){const g=.3333333333333333;return Math.exp(-(A*A)/(2*g*g))/(Math.sqrt(2*Math.PI)*g)}function VQA(A){const g=OQA(A),I=(g-1)/2,e=[],t=[];let i=0;for(let Q=0;Q<g;Q++){const r=jQA(Q/(g-1)*2-1);e[Q]=Q-I,t[Q]=r,i+=r}for(let Q=0;Q<t.length;Q++)t[Q]/=i;const o=[];for(let Q=0;Q<=I;Q+=2){const r=Math.min(Q+1,Math.floor(I));if(Q===r){o.push({offset:e[Q],weight:t[Q]});continue}const E=r===I,n=t[Q]+t[r]*(E?.5:1),s=e[Q]+1/(1+t[Q]/t[r]);s===0?o.push({offset:e[Q],weight:t[Q]},{offset:e[Q+1],weight:t[Q+1]}):o.push({offset:s,weight:n},{offset:-s,weight:n})}return o}function FF(A){return A.toFixed(7).replace(/0+$/,"").replace(/\.$/,".0")}function Kv(A,g){const I=VQA(g),e=Math.min(I.length,qQA);A.vertexOutputWGSL="",A.vertexMainWGSL="";for(let i=0;i<e;i++)A.vertexOutputWGSL=`${A.vertexOutputWGSL},@location(${i+1})sampleCoord${i}:vec2f`,A.vertexMainWGSL=`${A.vertexMainWGSL}out.sampleCoord${i}=out.uv+blurParams.delta*${FF(I[i].offset)};`;let t="var blend=vec4f(0);";for(let i=0;i<e;i++)t=`${t}blend+=textureSample(sourceTextureSampler,sourceSampler,input.sampleCoord${i})*${FF(I[i].weight)};`;for(let i=e;i<I.length;i++){const o=I[i];t=`${t}blend+=samplePostProcessSource(input.uv+blurParams.delta*${FF(o.offset)})*${FF(o.weight)};`}t=`${t}return blend;`,A.fragmentWGSL="",A.fragmentWrapperWGSL=`@fragment fn postProcessFragment(input:PostProcessVertexOutput)->@location(0)vec4f{${t}}`}function J3(A,g,I){const e={direction:A.direction??{x:1,y:0},kernel:A.kernel??9},t={uniformWGSL:PQA,uniformByteLength:16,writeUniforms(r){const E=Math.max(1,i.outputTexture._width||A.sourceTexture._width),n=Math.max(1,i.outputTexture._height||A.sourceTexture._height);r[0]=e.direction.x/E,r[1]=e.direction.y/n},fragmentWGSL:""};Kv(t,e.kernel);const i=Vt({name:A.name??"blur",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode,targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:t},g,I),o=i.updateUniforms;let Q=e.kernel;return i.updateUniforms=()=>{if(Q!==e.kernel){Q=e.kernel,Kv(i._shader,e.kernel),i._rebuildGpuState();return}o()},Object.defineProperties(i,{direction:{get:()=>e.direction,set:r=>{e.direction=r}},kernel:{get:()=>e.kernel,set:r=>{e.kernel=r}}}),i}const WQA=1/2.2,zQA="struct ExtractHighlightsParams{threshold:f32,exposure:f32,p0:f32,p1:f32}@group(0)@binding(2)var<uniform>extractHighlightsParams:ExtractHighlightsParams;",ZQA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let luma=dot(vec3f(0.2126,0.7152,0.0722),color.rgb*extractHighlightsParams.exposure);return vec4f(step(extractHighlightsParams.threshold,luma)*color.rgb,color.a);}";function kv(A,g,I){const e={threshold:A.threshold??.9,exposure:A.exposure??1},t=Vt({name:A.name??"extract-highlights",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode,targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{uniformWGSL:zQA,uniformByteLength:16,writeUniforms(i){i[0]=Math.pow(e.threshold,WQA),i[1]=e.exposure},fragmentWGSL:ZQA}},g,I);return Object.defineProperties(t,{threshold:{get:()=>e.threshold,set:i=>{e.threshold=i}},exposure:{get:()=>e.exposure,set:i=>{e.exposure=i}}}),t}const XQA="struct ChromaticAberrationParams{chromatic_aberration:f32,screen_width:f32,screen_height:f32,radialIntensity:f32,direction:vec2f,centerPosition:vec2f}@group(0)@binding(2)var<uniform>chromaticAberrationParams:ChromaticAberrationParams;",$QA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let centered=uv-chromaticAberrationParams.centerPosition;var dir=chromaticAberrationParams.direction;if(dir.x==0.0&&dir.y==0.0){dir=normalize(centered);}let radius=sqrt(dot(centered,centered));let amount=chromaticAberrationParams.chromatic_aberration*pow(radius,chromaticAberrationParams.radialIntensity);let shift=amount*dir/vec2f(chromaticAberrationParams.screen_width,chromaticAberrationParams.screen_height);let r=samplePostProcessSource(vec2f(uv.x+shift.x*-0.3,uv.y+shift.y*-0.3*0.5));let g=samplePostProcessSource(uv);let b=samplePostProcessSource(vec2f(uv.x+shift.x*0.3,uv.y+shift.y*0.3*0.5));return vec4f(r.r,g.g,b.b,clamp(r.a+g.a+b.a,0,1));}";function ArA(A,g,I){const e={aberrationAmount:A.aberrationAmount??30,screenWidth:1,screenHeight:1,direction:A.direction??{x:.707,y:.707},radialIntensity:A.radialIntensity??0,centerPosition:A.centerPosition??{x:.5,y:.5}},t=Vt({name:A.name??"chromatic-aberration",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode,targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{uniformWGSL:XQA,uniformByteLength:32,writeUniforms(o){o[0]=e.aberrationAmount,o[1]=e.screenWidth,o[2]=e.screenHeight,o[3]=e.radialIntensity,o[4]=e.direction.x,o[5]=e.direction.y,o[6]=e.centerPosition.x,o[7]=e.centerPosition.y},fragmentWGSL:$QA}},g,I),i=t.record;return t.record=()=>{e.screenWidth=t.sourceTexture._width,e.screenHeight=t.sourceTexture._height,i()},Object.defineProperties(t,{aberrationAmount:{get:()=>e.aberrationAmount,set:o=>{e.aberrationAmount=o}},direction:{get:()=>e.direction,set:o=>{e.direction=o}},radialIntensity:{get:()=>e.radialIntensity,set:o=>{e.radialIntensity=o}},centerPosition:{get:()=>e.centerPosition,set:o=>{e.centerPosition=o}}}),t}const grA="@group(0)@binding(2)var cocDepthTexture:texture_2d<f32>;",IrA="struct CircleOfConfusionParams{focusDistance:f32,cocPrecalculation:f32,minZ:f32,maxZRange:f32}@group(0)@binding(3)var<uniform>cocParams:CircleOfConfusionParams;";function erA(A){return`fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let depth=textureSample(cocDepthTexture,sourceSampler,uv).r;let pixelDistance=${A?"depth*1000.0":"(cocParams.minZ+cocParams.maxZRange*depth)*1000.0"};var coc=abs(cocParams.cocPrecalculation*((cocParams.focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);return vec4f(coc,coc,coc,1.0);}`}function Uv(A,g,I){const e={lensSize:A.lensSize??50,fStop:A.fStop??1.4,focusDistance:A.focusDistance??2e3,focalLength:A.focalLength??50},t=A.camera,i=A.depthNotNormalized??!1,o=Vt({name:A.name??"circle-of-confusion",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode??"linear",targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{extraTextures:[A.depthTexture],extraTextureWGSL:grA,uniformWGSL:IrA,uniformByteLength:16,writeUniforms(Q){const r=e.lensSize/e.fStop;Q[0]=e.focusDistance,Q[1]=r*e.focalLength/(e.focusDistance-e.focalLength),Q[2]=t.nearPlane,Q[3]=t.farPlane-t.nearPlane},fragmentWGSL:erA(i)}},g,I);return Object.defineProperties(o,{lensSize:{get:()=>e.lensSize,set:Q=>e.lensSize=Q},fStop:{get:()=>e.fStop,set:Q=>e.fStop=Q},focusDistance:{get:()=>e.focusDistance,set:Q=>e.focusDistance=Q},focalLength:{get:()=>e.focalLength,set:Q=>e.focalLength=Q}}),o}const trA="@group(0)@binding(2)var bloomBlur:texture_2d<f32>;",CrA="struct BloomMergeParams{weight:f32,p0:f32,p1:f32,p2:f32}@group(0)@binding(3)var<uniform>bloomMergeParams:BloomMergeParams;",irA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let blurred=textureSampleLevel(bloomBlur,sourceSampler,clamp(uv,vec2f(0),vec2f(1)),0).rgb;return vec4f(color.rgb+blurred*bloomMergeParams.weight,color.a);}",mF=(A,g)=>A*g;function orA(A,g,I){const e=g,t={sourceTexture:A.sourceTexture,targetTexture:A.targetTexture??null,sourceSamplingMode:A.sourceSamplingMode??"linear",alphaMode:A.alphaMode??0,viewport:A.viewport??null,clear:A.clear??!0,weight:A.weight??.25,kernel:A.kernel??64,threshold:A.threshold??.2,exposure:A.exposure??1,bloomScale:A.bloomScale??.5},i=A.name??"bloom",o=v3(`${i}-extract-output`,t.sourceTexture,t.bloomScale),Q=v3(`${i}-blur-x-output`,t.sourceTexture,t.bloomScale),r=v3(`${i}-blur-y-output`,t.sourceTexture,t.bloomScale),E=kv({name:`${i}-extract-highlights`,sourceTexture:t.sourceTexture,sourceSamplingMode:"linear",targetTexture:o,threshold:t.threshold,exposure:t.exposure},g,I),n=J3({name:`${i}-blur-x`,sourceTexture:o,sourceSamplingMode:"linear",targetTexture:Q,direction:{x:1,y:0},kernel:mF(t.kernel,t.bloomScale)},g,I),s=J3({name:`${i}-blur-y`,sourceTexture:Q,sourceSamplingMode:"linear",targetTexture:r,direction:{x:0,y:1},kernel:mF(t.kernel,t.bloomScale)},g,I),c=Vt({name:`${i}-merge`,sourceTexture:t.sourceTexture,sourceSamplingMode:t.sourceSamplingMode,targetTexture:t.targetTexture,alphaMode:t.alphaMode,viewport:t.viewport,clear:t.clear,_shader:{extraTextureWGSL:trA,extraTextures:[r],uniformWGSL:CrA,uniformBinding:3,uniformByteLength:16,writeUniforms(D){D[0]=t.weight},fragmentWGSL:irA}},g,I),l={name:i,engine:e,scene:I,_passes:[],sourceTexture:t.sourceTexture,sourceSamplingMode:t.sourceSamplingMode,targetTexture:t.targetTexture,alphaMode:t.alphaMode,viewport:t.viewport,clear:t.clear,outputTexture:c.outputTexture,_extract:E,_blurX:n,_blurY:s,_merge:c,_extractTarget:o,_blurXTarget:Q,_blurYTarget:r,record(){H3(l._extractTarget,t.sourceTexture,t.bloomScale),H3(l._blurXTarget,t.sourceTexture,t.bloomScale),H3(l._blurYTarget,t.sourceTexture,t.bloomScale),E.record(),n.record(),s.record(),c.record(),l.outputTexture=c.outputTexture},execute(){return(E.execute?.()??0)+(n.execute?.()??0)+(s.execute?.()??0)+(c.execute?.()??0)},updateUniforms(){E.updateUniforms(),n.updateUniforms(),s.updateUniforms(),c.updateUniforms()},dispose(){E.dispose(),n.dispose(),s.dispose(),c.dispose(),Se(l._extractTarget),Se(l._blurXTarget),Se(l._blurYTarget)},get weight(){return t.weight},set weight(D){t.weight=D},get kernel(){return t.kernel},set kernel(D){t.kernel=D,n.kernel=mF(D,t.bloomScale),s.kernel=mF(D,t.bloomScale)},get threshold(){return E.threshold},set threshold(D){t.threshold=D,E.threshold=D},get exposure(){return E.exposure},set exposure(D){t.exposure=D,E.exposure=D},get bloomScale(){return t.bloomScale}};return Object.defineProperties(l,{sourceTexture:{get:()=>t.sourceTexture,set:D=>{t.sourceTexture=D,E.sourceTexture=D,c.sourceTexture=D}},sourceSamplingMode:{get:()=>t.sourceSamplingMode,set:D=>{t.sourceSamplingMode=D,c.sourceSamplingMode=D}},targetTexture:{get:()=>t.targetTexture,set:D=>{t.targetTexture=D,c.targetTexture=D,l.outputTexture=c.outputTexture}},alphaMode:{get:()=>t.alphaMode,set:D=>{t.alphaMode=D,c.alphaMode=D}},viewport:{get:()=>t.viewport,set:D=>{t.viewport=D,c.viewport=D}},clear:{get:()=>t.clear,set:D=>{t.clear=D,c.clear=D}}}),l}function v3(A,g,I){const e=g._descriptor;e.format||U(437,A);const t=Lv(g);return wt({lbl:A,format:e.format,samples:1,size:{width:Math.max(1,Math.floor(t.width*I)),height:Math.max(1,Math.floor(t.height*I))}})}function H3(A,g,I){const e=g._descriptor.format;e||U(438,A._descriptor.lbl??"target");const t=Lv(g);A._descriptor.format=e,A._descriptor.size={width:Math.max(1,Math.floor(t.width*I)),height:Math.max(1,Math.floor(t.height*I))}}function Lv(A){if(A._width>0&&A._height>0)return{width:A._width,height:A._height};const g=A._descriptor;if("canvas"in g.size){const I=g.size.canvas;return{width:I.width,height:I.height}}return g.size}const BrA=8,QrA="@group(0)@binding(2)var dofCocTexture:texture_2d<f32>;",rrA="struct DofBlurParams{delta:vec2f,p0:f32,p1:f32}@group(0)@binding(3)var<uniform>dofBlurParams:DofBlurParams;",ErA="fn sampleCoC(uv:vec2f)->f32{return textureSample(dofCocTexture,sourceSampler,uv).r;}";function nrA(A){const g=Math.max(1,Math.round(A));for(const I of[g,g-1,g+1,g-2,g+2])if(I>0&&I%2!==0&&Math.floor(I/2)%2===0)return Math.max(I,3);return Math.max(g,3)}function srA(A){const g=.3333333333333333;return Math.exp(-(A*A)/(2*g*g))/(Math.sqrt(2*Math.PI)*g)}function arA(A){const g=nrA(A),I=(g-1)/2,e=[],t=[];let i=0;for(let Q=0;Q<g;Q++){const r=srA(Q/(g-1)*2-1);e[Q]=Q-I,t[Q]=r,i+=r}for(let Q=0;Q<t.length;Q++)t[Q]/=i;const o=[];for(let Q=0;Q<=I;Q+=2){const r=Math.min(Q+1,Math.floor(I));if(Q===r){o.push({offset:e[Q],weight:t[Q]});continue}const E=r===I,n=t[Q]+t[r]*(E?.5:1),s=e[Q]+1/(1+t[Q]/t[r]);s===0?o.push({offset:e[Q],weight:t[Q]},{offset:e[Q+1],weight:t[Q+1]}):o.push({offset:s,weight:n},{offset:-s,weight:n})}return o}function XR(A){return A.toFixed(7).replace(/0+$/,"").replace(/\.$/,".0")}function Yv(A,g){const I=arA(g),e=I[I.length-1],t=I.slice(0,I.length-1),i=Math.min(t.length,BrA);A.vertexOutputWGSL="",A.vertexMainWGSL="";for(let Q=0;Q<i;Q++)A.vertexOutputWGSL=`${A.vertexOutputWGSL},@location(${Q+1})sampleCoord${Q}:vec2f`,A.vertexMainWGSL=`${A.vertexMainWGSL}out.sampleCoord${Q}=out.uv+dofBlurParams.delta*${XR(t[Q].offset)};`;let o=`var blend=textureSample(sourceTextureSampler,sourceSampler,input.uv)*${XR(e.weight)};`;o=`${o}var sumOfWeights=${XR(e.weight)};`;for(let Q=0;Q<t.length;Q++){const r=t[Q],E=Q<i?`input.sampleCoord${Q}`:`(input.uv+dofBlurParams.delta*${XR(r.offset)})`;o=`${o}let f${Q}=sampleCoC(${E});let w${Q}=${XR(r.weight)}*f${Q};sumOfWeights=sumOfWeights+w${Q};`,o=`${o}blend=blend+textureSample(sourceTextureSampler,sourceSampler,${E})*w${Q};`}o=`${o}return blend/sumOfWeights;`,A.fragmentWGSL=ErA,A.fragmentWrapperWGSL=`@fragment fn postProcessFragment(input:PostProcessVertexOutput)->@location(0)vec4f{${o}}`}function Jv(A,g,I){const e={direction:A.direction??{x:1,y:0},kernel:A.kernel??9},t={extraTextureWGSL:QrA,extraTextures:[A.circleOfConfusionTexture],uniformWGSL:rrA,uniformBinding:3,uniformByteLength:16,writeUniforms(r){const E=Math.max(1,i.outputTexture._width||A.sourceTexture._width),n=Math.max(1,i.outputTexture._height||A.sourceTexture._height);r[0]=e.direction.x/E,r[1]=e.direction.y/n},fragmentWGSL:""};Yv(t,e.kernel);const i=Vt({name:A.name??"depth-of-field-blur",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode??"linear",targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:t},g,I),o=i.updateUniforms;let Q=e.kernel;return i.updateUniforms=()=>{if(Q!==e.kernel){Q=e.kernel,Yv(i._shader,e.kernel),i._rebuildGpuState();return}o()},Object.defineProperties(i,{direction:{get:()=>e.direction,set:r=>{e.direction=r}},kernel:{get:()=>e.kernel,set:r=>{e.kernel=r}}}),i}function crA(A){let g="@group(0)@binding(2)var dofCocTexture:texture_2d<f32>;@group(0)@binding(3)var blurStep0:texture_2d<f32>;";return A>0&&(g=`${g}@group(0)@binding(4)var blurStep1:texture_2d<f32>;`),A>1&&(g=`${g}@group(0)@binding(5)var blurStep2:texture_2d<f32>;`),g}function lrA(A){const g="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let coc=textureSampleLevel(dofCocTexture,sourceSampler,uv,0.0).r;let blurred0=textureSampleLevel(blurStep0,sourceSampler,uv,0.0);";return A===0?`${g}return mix(color,blurred0,coc);}`:A===1?`${g} let blurred1=textureSampleLevel(blurStep1,sourceSampler,uv,0.0);if(coc<0.5){return mix(color,blurred1,coc/0.5);}return mix(blurred1,blurred0,(coc-0.5)/0.5);}`:`${g} let blurred1=textureSampleLevel(blurStep1,sourceSampler,uv,0.0);let blurred2=textureSampleLevel(blurStep2,sourceSampler,uv,0.0);if(coc<0.33){return mix(color,blurred2,coc/0.33);}if(coc<0.66){return mix(blurred2,blurred1,(coc-0.33)/0.33);}return mix(blurred1,blurred0,(coc-0.66)/0.34);}`}function DrA(A,g,I){const e=A.blurSteps.length-1,t=[A.circleOfConfusionTexture];for(let i=A.blurSteps.length-1;i>=0;i--)t.push(A.blurSteps[i]);return Vt({name:A.name??"depth-of-field-merge",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode??"linear",targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{extraTextureWGSL:crA(e),extraTextures:t,fragmentWGSL:lrA(e)}},g,I)}var vv=(A=>(A[A.Low=0]="Low",A[A.Medium=1]="Medium",A[A.High=2]="High",A))(vv||{});function prA(A){switch(A){case 2:return{blurCount:3,kernel:51};case 1:return{blurCount:2,kernel:31};default:return{blurCount:1,kernel:15}}}function yrA(A){if(A._width>0&&A._height>0)return{width:A._width,height:A._height};if("canvas"in A._descriptor.size){const g=A._descriptor.size.canvas;return{width:g.width,height:g.height}}return A._descriptor.size}function Hv(A,g){const I=yrA(A);return{width:Math.max(1,Math.floor(I.width*g)),height:Math.max(1,Math.floor(I.height*g))}}function _rA(A,g,I){const e=g,t={sourceTexture:A.sourceTexture,targetTexture:A.targetTexture??null,sourceSamplingMode:A.sourceSamplingMode??"linear",alphaMode:A.alphaMode??0,viewport:A.viewport??null,clear:A.clear??!0,lensSize:A.lensSize??50,fStop:A.fStop??1.4,focusDistance:A.focusDistance??2e3,focalLength:A.focalLength??50},i=A.name??"depth-of-field",{blurCount:o,kernel:Q}=prA(A.blurLevel??0),r=Q/Math.pow(2,o-1),E=[];for(let h=0;h<o;h++)E.push(.75/Math.pow(2,h));const n=t.sourceTexture._descriptor.format;n||U(439,i);const s=wt({lbl:`${i}-coc`,format:"r16float",samples:1,size:t.sourceTexture._descriptor.size}),c=Uv({name:`${i}-coc`,sourceTexture:t.sourceTexture,sourceSamplingMode:"linear",depthTexture:A.depthTexture,camera:A.camera,lensSize:t.lensSize,fStop:t.fStop,focusDistance:t.focusDistance,focalLength:t.focalLength,depthNotNormalized:A.depthNotNormalized,targetTexture:s},g,I),l=[],D=[],p=[],y=[],_=[];for(let h=0;h<o;h++){const w=Hv(t.sourceTexture,E[h]),M=wt({lbl:`${i}-blur-y-${h}`,format:n,samples:1,size:w}),S=wt({lbl:`${i}-blur-x-${h}`,format:n,samples:1,size:w}),R=Jv({name:`${i}-blur-y-${h}`,sourceTexture:h===0?t.sourceTexture:y[h-1],sourceSamplingMode:"linear",circleOfConfusionTexture:s,direction:{x:0,y:1},kernel:r,targetTexture:M},g,I),N=Jv({name:`${i}-blur-x-${h}`,sourceTexture:M,sourceSamplingMode:"linear",circleOfConfusionTexture:s,direction:{x:1,y:0},kernel:r,targetTexture:S},g,I);l.push(R),D.push(N),p.push(M),y.push(S),_.push(S)}const u=DrA({name:`${i}-merge`,sourceTexture:t.sourceTexture,sourceSamplingMode:t.sourceSamplingMode,targetTexture:t.targetTexture,alphaMode:t.alphaMode,viewport:t.viewport,clear:t.clear,circleOfConfusionTexture:s,blurSteps:_},g,I),f={name:i,engine:e,scene:I,_passes:[],sourceTexture:t.sourceTexture,sourceSamplingMode:t.sourceSamplingMode,targetTexture:t.targetTexture,alphaMode:t.alphaMode,viewport:t.viewport,clear:t.clear,outputTexture:u.outputTexture,_coc:c,_blurX:D,_blurY:l,_merge:u,_cocTarget:s,_blurXTargets:y,_blurYTargets:p,record(){for(let h=0;h<o;h++){const w=Hv(t.sourceTexture,E[h]);p[h]._descriptor.size=w,y[h]._descriptor.size=w}c.record();for(let h=0;h<o;h++)l[h].record(),D[h].record();u.record(),f.outputTexture=u.outputTexture},execute(){let h=c.execute?.()??0;for(let w=0;w<o;w++)h+=l[w].execute?.()??0,h+=D[w].execute?.()??0;return h+=u.execute?.()??0,h},updateUniforms(){c.updateUniforms();for(let h=0;h<o;h++)l[h].updateUniforms(),D[h].updateUniforms();u.updateUniforms()},dispose(){c.dispose();for(let h=0;h<o;h++)l[h].dispose(),D[h].dispose();u.dispose(),Se(s);for(const h of p)Se(h);for(const h of y)Se(h)},get lensSize(){return c.lensSize},set lensSize(h){c.lensSize=h},get fStop(){return c.fStop},set fStop(h){c.fStop=h},get focusDistance(){return c.focusDistance},set focusDistance(h){c.focusDistance=h},get focalLength(){return c.focalLength},set focalLength(h){c.focalLength=h}};return Object.defineProperties(f,{sourceTexture:{get:()=>t.sourceTexture,set:h=>{t.sourceTexture=h,c.sourceTexture=h,u.sourceTexture=h,l[0].sourceTexture=h}},sourceSamplingMode:{get:()=>t.sourceSamplingMode,set:h=>{t.sourceSamplingMode=h,u.sourceSamplingMode=h}},targetTexture:{get:()=>t.targetTexture,set:h=>{t.targetTexture=h,u.targetTexture=h,f.outputTexture=u.outputTexture}},alphaMode:{get:()=>t.alphaMode,set:h=>{t.alphaMode=h,u.alphaMode=h}},viewport:{get:()=>t.viewport,set:h=>{t.viewport=h,u.viewport=h}},clear:{get:()=>t.clear,set:h=>{t.clear=h,u.clear=h}}}),f}const urA="@group(0)@binding(2)var taaHistory:texture_2d<f32>;",hrA="struct TaaParams{factor:f32,p0:f32,p1:f32,p2:f32}@group(0)@binding(3)var<uniform>taaParams:TaaParams;",frA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let h=textureSample(taaHistory,sourceSampler,uv);return mix(h,color,taaParams.factor);}",Tv="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{return color;}";function drA(A,g,I){const e=A.name??"taa",t=A.sourceTexture,i=A.targetTexture??null,o=Math.max(1,Math.floor(A.samples??8)),Q=t._descriptor.size,r=wt({lbl:`${e}-history`,format:"rgba16float",samples:1,size:Q}),E=wt({lbl:`${e}-temp`,format:"rgba16float",samples:1,size:Q}),n=Vt({name:`${e}-blend`,sourceTexture:t,sourceSamplingMode:"nearest",targetTexture:E,_shader:{extraTextureWGSL:urA,extraTextures:[r],uniformWGSL:hrA,uniformBinding:3,uniformByteLength:16,writeUniforms(D){D[0]=l._factor},fragmentWGSL:frA}},g,I),s=Vt({name:`${e}-present`,sourceTexture:E,sourceSamplingMode:"nearest",targetTexture:i??g.scRT,_shader:{fragmentWGSL:Tv}},g,I),c=Vt({name:`${e}-history-update`,sourceTexture:E,sourceSamplingMode:"nearest",targetTexture:r,_shader:{fragmentWGSL:Tv}},g,I),l={name:e,engine:g,scene:I,_passes:[],sourceTexture:t,targetTexture:i,outputTexture:i??g.scRT,factor:A.factor??.05,samples:o,disableOnCameraMove:A.disableOnCameraMove??!0,_blend:n,_present:s,_historyUpdate:c,_history:r,_temp:E,_sourceRenderTask:A.sourceRenderTask,_halton:MrA(o),_haltonIndex:0,_jitterScratch:new X(16),_firstUpdate:!0,_lastCamVer:-1,_factor:1,record(){const{width:D,height:p}=wrA(l.sourceTexture);xv(r,g,D,p),xv(E,g,D,p),n.record(),s.record(),c.record(),l._firstUpdate=!0,l._haltonIndex=0,l._lastCamVer=-1},execute(){const D=l._sourceRenderTask.scene.camera,p=D?T1(D):0,y=p!==l._lastCamVer;l._lastCamVer=p;const _=l._firstUpdate||y&&l.disableOnCameraMove;l._factor=_?1:l.factor,n.updateUniforms();let u=n.execute?.()??0;return u+=s.execute?.()??0,u+=c.execute?.()??0,l._firstUpdate=!1,SrA(l),u},updateUniforms(){n.updateUniforms()},dispose(){l._passes.length=0,n.dispose(),s.dispose(),c.dispose(),r._eager=!1,E._eager=!1,Se(r),Se(E)}};return l}function xv(A,g,I,e){A._eager&&A._width===I&&A._height===e||(A._eager=!1,Se(A),A._descriptor.size={width:I,height:e},Kt(A,g),A._eager=!0)}function wrA(A){if(A._width>0&&A._height>0)return{width:A._width,height:A._height};const g=A._descriptor.size;return"canvas"in g?{width:g.canvas.width,height:g.canvas.height}:{width:g.width,height:g.height}}function MrA(A){const g=new X(A*2);for(let I=1;I<=A;I++)g[(I-1)*2]=qv(I,2)-.5,g[(I-1)*2+1]=qv(I,3)-.5;return g}function qv(A,g){let I=1,e=0;for(;A>0;)I/=g,e+=I*(A%g),A=Math.floor(A/g);return e}function SrA(A){const g=A._sourceRenderTask,I=g._suData,e=A.sourceTexture._width,t=A.sourceTexture._height;if(e<=0||t<=0)return;const i=A._halton[A._haltonIndex]/(e/2),o=A._halton[A._haltonIndex+1]/(t/2);A._haltonIndex+=2,A._haltonIndex>=A._halton.length&&(A._haltonIndex=0);const Q=A._jitterScratch;for(let r=0;r<4;r++){const E=r*4,n=I[E+3];Q[E]=I[E]+i*n,Q[E+1]=I[E+1]+o*n,Q[E+2]=I[E+2],Q[E+3]=n}A.engine._device.queue.writeBuffer(g._sceneUBO,0,Q)}const RrA="struct SmaaEdgeParams{threshold:f32,srgb:f32,pad1:f32,pad2:f32}@group(0)@binding(2)var<uniform>smaaEdge:SmaaEdgeParams;",NrA="fn smaaLuma(c:vec3f)->f32{return dot(c,vec3f(0.2126,0.7152,0.0722));}fn smaaEnc(c:f32)->f32{return select(1.055*pow(c,1.0/2.4)-0.055,c*12.92,c<=0.0031308);}fn smaaDetectLuma(c:vec3f)->f32{if(smaaEdge.srgb>0.5){return smaaLuma(vec3f(smaaEnc(clamp(c.r,0.0,1.0)),smaaEnc(clamp(c.g,0.0,1.0)),smaaEnc(clamp(c.b,0.0,1.0))));}return smaaLuma(c);}fn smaaFetch(uv:vec2f)->vec4f{return textureSampleLevel(sourceTextureSampler,sourceSampler,uv,0.0);}fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let ts=1.0/vec2f(textureDimensions(sourceTextureSampler));let l=smaaDetectLuma(color.rgb);let ll=smaaDetectLuma(smaaFetch(uv+vec2f(-ts.x,0.0)).rgb);let lt=smaaDetectLuma(smaaFetch(uv+vec2f(0.0,-ts.y)).rgb);let delta=vec2f(abs(l-ll),abs(l-lt));var edges=step(vec2f(smaaEdge.threshold),delta);if(edges.x+edges.y==0.0){return vec4f(0.0,0.0,0.0,1.0);}let lr=smaaDetectLuma(smaaFetch(uv+vec2f(ts.x,0.0)).rgb);let lb=smaaDetectLuma(smaaFetch(uv+vec2f(0.0,ts.y)).rgb);let ll2=smaaDetectLuma(smaaFetch(uv+vec2f(-2.0*ts.x,0.0)).rgb);let lt2=smaaDetectLuma(smaaFetch(uv+vec2f(0.0,-2.0*ts.y)).rgb);let d2=max(max(delta,vec2f(abs(l-lr),abs(l-lb))),vec2f(abs(ll-ll2),abs(lt-lt2)));let m=max(d2.x,d2.y);edges*=step(vec2f(m),2.0*delta);return vec4f(edges,0.0,1.0);}",GrA="struct SmaaWeightParams{maxSearch:f32,diag:f32,corner:f32,pad:f32}@group(0)@binding(2)var<uniform>smaaWeight:SmaaWeightParams;",FrA="fn smaaEdgeAt(uv:vec2f)->vec2f{return textureSampleLevel(sourceTextureSampler,sourceSampler,uv,0.0).rg;}fn smaaBothEdges(uv:vec2f)->bool{let e=smaaEdgeAt(uv);return e.x>0.5&&e.y>0.5;}fn smaaDiagRunBoth(uv:vec2f,ts:vec2f,dir:vec2f,maxSteps:f32)->f32{var d=0.0;loop{if(d>=maxSteps){break;}if(!smaaBothEdges(uv+ts*dir*(d+1.0))){break;}d=d+1.0;}return d;}fn smaaDiagRunLeft(uv:vec2f,ts:vec2f,dir:vec2f,maxSteps:f32)->f32{var d=0.0;loop{if(d>=maxSteps){break;}if(smaaEdgeAt(uv+ts*dir*(d+1.0)).x<=0.5){break;}d=d+1.0;}return d;}fn smaaSearchX(uv:vec2f,ts:vec2f,dir:f32,maxSteps:f32,selfLeft:f32)->f32{var d=0.0;var behind=selfLeft;loop{if(d>=maxSteps){break;}if(dir<0.0&&behind>0.5){break;}let s=smaaEdgeAt(uv+vec2f(ts.x*dir*(d+1.0),0.0));if(dir>0.0&&s.x>0.5){break;}if(s.y<0.5){break;}behind=s.x;d=d+1.0;}return d;}fn smaaSearchY(uv:vec2f,ts:vec2f,dir:f32,maxSteps:f32,selfTop:f32)->f32{var d=0.0;var behind=selfTop;loop{if(d>=maxSteps){break;}if(dir<0.0&&behind>0.5){break;}let s=smaaEdgeAt(uv+vec2f(0.0,ts.y*dir*(d+1.0)));if(dir>0.0&&s.y>0.5){break;}if(s.x<0.5){break;}behind=s.y;d=d+1.0;}return d;}fn smaaHeight(x:f32,len:f32,cNear:f32,cFar:f32)->f32{let h=max(len*0.5,1e-4);if(x<h){return cNear*0.5*max(0.0,1.0-x/h);}return cFar*0.5*max(0.0,1.0-(len-x)/h);}fn smaaAccum(p:f32,q:f32,hp:f32,hq:f32)->vec2f{if(q<=p){return vec2f(0.0);}let w=q-p;if(hp*hq>=0.0){let a=0.5*(hp+hq)*w;return vec2f(max(a,0.0),max(-a,0.0));}let t=hp/(hp-hq);let a1=0.5*hp*(w*t);let a2=0.5*hq*(w*(1.0-t));return vec2f(max(a1,0.0)+max(a2,0.0),max(-a1,0.0)+max(-a2,0.0));}fn smaaResolveCrossings(cNear:vec2f,cFar:vec2f)->vec2f{let near=step(vec2f(0.5),cNear);let far=step(vec2f(0.5),cFar);let raw=vec2f(near.x-near.y,far.x-far.y);let nearBoth=near.x+near.y>1.5;let farBoth=far.x+far.y>1.5;return vec2f(select(raw.x,-raw.y,nearBoth&&abs(raw.y)>0.5),select(raw.y,-raw.x,farBoth&&abs(raw.x)>0.5));}fn smaaCoveragePair(x0:f32,len:f32,cNear:vec2f,cFar:vec2f)->vec2f{let crossing=smaaResolveCrossings(cNear,cFar);let x1=x0+1.0;let m=clamp(len*0.5,x0,x1);let h0=smaaHeight(x0,len,crossing.x,crossing.y);let hm=smaaHeight(m,len,crossing.x,crossing.y);let h1=smaaHeight(x1,len,crossing.x,crossing.y);return smaaAccum(x0,m,h0,hm)+smaaAccum(m,x1,hm,h1);}fn smaaCornerAttenuation(dNear:f32,dFar:f32)->vec2f{let nearest=vec2f(step(dNear,dFar),step(dFar,dNear));return 0.75*nearest/max(nearest.x+nearest.y,1.0);}fn smaaHorizontalCornerFactors(lEnd:vec2f,rEnd:vec2f,ts:vec2f,d1:f32,d2:f32)->vec2f{let attenuation=smaaCornerAttenuation(d1,d2);let below=vec2f(smaaEdgeAt(lEnd+vec2f(0.0,ts.y)).x,smaaEdgeAt(rEnd+vec2f(0.0,ts.y)).x);let above=vec2f(smaaEdgeAt(lEnd+vec2f(0.0,-2.0*ts.y)).x,smaaEdgeAt(rEnd+vec2f(0.0,-2.0*ts.y)).x);return clamp(vec2f(1.0-dot(attenuation,below),1.0-dot(attenuation,above)),vec2f(0.0),vec2f(1.0));}fn smaaVerticalCornerFactors(tEnd:vec2f,bEnd:vec2f,ts:vec2f,d1:f32,d2:f32)->vec2f{let attenuation=smaaCornerAttenuation(d1,d2);let right=vec2f(smaaEdgeAt(tEnd+vec2f(ts.x,0.0)).y,smaaEdgeAt(bEnd+vec2f(ts.x,0.0)).y);let left=vec2f(smaaEdgeAt(tEnd+vec2f(-2.0*ts.x,0.0)).y,smaaEdgeAt(bEnd+vec2f(-2.0*ts.x,0.0)).y);return clamp(vec2f(1.0-dot(attenuation,right),1.0-dot(attenuation,left)),vec2f(0.0),vec2f(1.0));}fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let ts=1.0/vec2f(textureDimensions(sourceTextureSampler));let e=color.rg;var w=vec4f(0.0);let maxSteps=smaaWeight.maxSearch;var diagonal=false;if(smaaWeight.diag>0.5){let minRun=smaaWeight.diag;if(e.x>0.5&&e.y>0.5){let a=smaaDiagRunBoth(uv,ts,vec2f(-1.0,1.0),maxSteps);let b=smaaDiagRunBoth(uv,ts,vec2f(1.0,-1.0),maxSteps);if(a+b+1.0>=minRun){w.x=0.5;diagonal=true;}}if(!diagonal&&e.x>0.5){let a=smaaDiagRunLeft(uv,ts,vec2f(-1.0,-1.0),maxSteps);let b=smaaDiagRunLeft(uv,ts,vec2f(1.0,1.0),maxSteps);if(a+b+1.0>=minRun){w.z=0.5;diagonal=true;}}}if(!diagonal&&e.y>0.5){let d1=smaaSearchX(uv,ts,-1.0,maxSteps,e.x);let d2=smaaSearchX(uv,ts,1.0,maxSteps,e.x);let len=d1+d2+1.0;let lEnd=uv+vec2f(-ts.x*d1,0.0);let rEnd=uv+vec2f(ts.x*(d2+1.0),0.0);let lCross=vec2f(smaaEdgeAt(lEnd).x,smaaEdgeAt(lEnd+vec2f(0.0,-ts.y)).x);let rCross=vec2f(smaaEdgeAt(rEnd).x,smaaEdgeAt(rEnd+vec2f(0.0,-ts.y)).x);var c=smaaCoveragePair(d1,len,lCross,rCross);if(smaaWeight.corner>0.5){c*=smaaHorizontalCornerFactors(lEnd,rEnd,ts,d1,d2);}w.x=c.x;w.y=c.y;}if(!diagonal&&e.x>0.5){let d1=smaaSearchY(uv,ts,-1.0,maxSteps,e.y);let d2=smaaSearchY(uv,ts,1.0,maxSteps,e.y);let len=d1+d2+1.0;let tEnd=uv+vec2f(0.0,-ts.y*d1);let bEnd=uv+vec2f(0.0,ts.y*(d2+1.0));let tCross=vec2f(smaaEdgeAt(tEnd).y,smaaEdgeAt(tEnd+vec2f(-ts.x,0.0)).y);let bCross=vec2f(smaaEdgeAt(bEnd).y,smaaEdgeAt(bEnd+vec2f(-ts.x,0.0)).y);var c=smaaCoveragePair(d1,len,tCross,bCross);if(smaaWeight.corner>0.5){c*=smaaVerticalCornerFactors(tEnd,bEnd,ts,d1,d2);}w.z=c.x;w.w=c.y;}return w;}",mrA="@group(0)@binding(2)var smaaWeights:texture_2d<f32>;",brA="struct SmaaBlendParams{dominant:f32,p0:f32,p1:f32,p2:f32}@group(0)@binding(3)var<uniform>smaaBlend:SmaaBlendParams;",KrA="fn smaaFetch(uv:vec2f)->vec4f{return textureSampleLevel(sourceTextureSampler,sourceSampler,uv,0.0);}fn smaaWeightAt(uv:vec2f)->vec4f{return textureSampleLevel(smaaWeights,sourceSampler,uv,0.0);}fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let ts=1.0/vec2f(textureDimensions(sourceTextureSampler));let wSelf=smaaWeightAt(uv);let wBelow=smaaWeightAt(uv+vec2f(0.0,ts.y));let wRight=smaaWeightAt(uv+vec2f(ts.x,0.0));let up=wSelf.x;let down=wBelow.y;let left=wSelf.z;let right=wRight.w;if(up+down+left+right<1e-4){return color;}var bUp=up;var bDown=down;var bLeft=left;var bRight=right;if(smaaBlend.dominant>0.5){if(max(left,right)>max(up,down)){bUp=0.0;bDown=0.0;}else{bLeft=0.0;bRight=0.0;}}let sum=bUp+bDown+bLeft+bRight;if(sum<1e-4){return color;}var acc=vec4f(0.0);acc+=(bUp/sum)*mix(color,smaaFetch(uv+vec2f(0.0,-ts.y)),clamp(bUp,0.0,1.0));acc+=(bDown/sum)*mix(color,smaaFetch(uv+vec2f(0.0,ts.y)),clamp(bDown,0.0,1.0));acc+=(bLeft/sum)*mix(color,smaaFetch(uv+vec2f(-ts.x,0.0)),clamp(bLeft,0.0,1.0));acc+=(bRight/sum)*mix(color,smaaFetch(uv+vec2f(ts.x,0.0)),clamp(bRight,0.0,1.0));return acc;}";function Pv(A,g,I,e){A._eager&&A._width===I&&A._height===e||(A._eager=!1,Se(A),A._descriptor.size={width:I,height:e},Kt(A,g),A._eager=!0)}function krA(A){if(A._width>0&&A._height>0)return{width:A._width,height:A._height};const g=A._descriptor.size,I="canvas"in g?g.canvas.width:g.width,e="canvas"in g?g.canvas.height:g.height;return{width:Math.max(1,I),height:Math.max(1,e)}}const UrA=112;function T3(A,g){return typeof A!="number"||!Number.isFinite(A)?g:Math.min(UrA,Math.max(1,Math.floor(A)))}const LrA=2;function Ov(A,g){return Math.max(LrA,T3(A,g))}function jv(A,g){return typeof A!="number"||!Number.isFinite(A)||A<=0?g:Math.min(.5,A)}function YrA(A,g,I){const e=A.name??"smaa",t=A.sourceTexture,i={threshold:jv(A.threshold,.05),sourceIsSrgb:A.sourceIsSrgb??!1,dominantAxisBlend:A.dominantAxisBlend??!0,maxSearchSteps:T3(A.maxSearchSteps,16),diagonalDetection:A.diagonalDetection??!1,minDiagonalRun:Ov(A.minDiagonalRun,4),cornerDetection:A.cornerDetection??!1},o=wt({lbl:`${e}-edges`,format:"rgba8unorm",samples:1,size:{width:1,height:1}}),Q=wt({lbl:`${e}-weights`,format:"rgba8unorm",samples:1,size:{width:1,height:1}}),r=Vt({name:`${e}-edges`,sourceTexture:t,targetTexture:o,sourceSamplingMode:"linear",_shader:{fragmentWGSL:NrA,uniformWGSL:RrA,uniformByteLength:16,writeUniforms(c){c[0]=i.threshold,c[1]=i.sourceIsSrgb?1:0}}},g,I),E=Vt({name:`${e}-weights`,sourceTexture:o,targetTexture:Q,sourceSamplingMode:"nearest",_shader:{fragmentWGSL:FrA,uniformWGSL:GrA,uniformByteLength:16,writeUniforms(c){c[0]=i.maxSearchSteps,c[1]=i.diagonalDetection?i.minDiagonalRun:0,c[2]=i.cornerDetection?1:0}}},g,I),n=Vt({name:`${e}-blend`,sourceTexture:t,targetTexture:A.targetTexture,sourceSamplingMode:"linear",alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{fragmentWGSL:KrA,extraTextureWGSL:mrA,extraTextures:[Q],uniformWGSL:brA,uniformByteLength:16,writeUniforms(c){c[0]=i.dominantAxisBlend?1:0}}},g,I),s={name:e,engine:g,scene:I,_passes:[],sourceTexture:t,sourceSamplingMode:A.sourceSamplingMode??"linear",targetTexture:A.targetTexture??null,alphaMode:A.alphaMode??0,viewport:A.viewport??null,clear:A.clear??!0,outputTexture:n.outputTexture,edgesTexture:o,weightsTexture:Q,get threshold(){return i.threshold},set threshold(c){i.threshold=jv(c,i.threshold)},get maxSearchSteps(){return i.maxSearchSteps},set maxSearchSteps(c){i.maxSearchSteps=T3(c,i.maxSearchSteps)},get diagonalDetection(){return i.diagonalDetection},set diagonalDetection(c){i.diagonalDetection=c},get minDiagonalRun(){return i.minDiagonalRun},set minDiagonalRun(c){i.minDiagonalRun=Ov(c,i.minDiagonalRun)},get cornerDetection(){return i.cornerDetection},set cornerDetection(c){i.cornerDetection=c},get sourceIsSrgb(){return i.sourceIsSrgb},set sourceIsSrgb(c){i.sourceIsSrgb=c},get dominantAxisBlend(){return i.dominantAxisBlend},set dominantAxisBlend(c){i.dominantAxisBlend=c},_edgeDetect:r,_blendWeights:E,_neighbourhood:n,_edges:o,_weights:Q,record(){r.sourceTexture=s.sourceTexture,n.sourceTexture=s.sourceTexture,n.targetTexture=s.targetTexture,n.viewport=s.viewport,n.clear=s.clear,n.alphaMode=s.alphaMode;const c=s.sourceTexture,{width:l,height:D}=krA(c);Pv(o,g,l,D),Pv(Q,g,l,D),r.record(),E.record(),n.record(),s.outputTexture=n.outputTexture},execute(){return(r.execute?.()??0)+(E.execute?.()??0)+(n.execute?.()??0)},updateUniforms(){r.updateUniforms(),E.updateUniforms(),n.updateUniforms()},dispose(){r.dispose(),E.dispose(),n.dispose(),o._eager=!1,Q._eager=!1,Se(o),Se(Q)}};return s}function lt(A){const g=A,I=g[0],e=g[1],t=g[2],i=g[3],o=g[4],Q=g[5],r=g[6],E=g[7],n=g[8],s=g[9],c=g[10],l=g[11],D=g[12],p=g[13],y=g[14],_=g[15],u=I*Q-e*o,f=I*r-t*o,h=I*E-i*o,w=e*r-t*Q,M=e*E-i*Q,S=t*E-i*r,R=n*p-s*D,N=n*y-c*D,F=n*_-l*D,G=s*y-c*p,m=s*_-l*p,K=c*_-l*y;let k=u*K-f*m+h*G+w*F-M*N+S*R;if(Math.abs(k)<1e-10)return null;k=1/k;const L=se();return L[0]=(Q*K-r*m+E*G)*k,L[1]=(t*m-e*K-i*G)*k,L[2]=(p*S-y*M+_*w)*k,L[3]=(c*M-s*S-l*w)*k,L[4]=(r*F-o*K-E*N)*k,L[5]=(I*K-t*F+i*N)*k,L[6]=(y*h-D*S-_*f)*k,L[7]=(n*S-c*h+l*f)*k,L[8]=(o*m-Q*F+E*R)*k,L[9]=(e*F-I*m-i*R)*k,L[10]=(D*M-p*h+_*u)*k,L[11]=(s*h-n*M-l*u)*k,L[12]=(Q*N-o*G-r*R)*k,L[13]=(I*G-e*N+t*R)*k,L[14]=(p*f-D*w-y*u)*k,L[15]=(n*w-s*f+c*u)*k,L}function x3(){return"struct SsHit{hit:bool,uv:vec2f,rayDist:f32,surfaceDist:f32}fn ssIsClearDepth(depth:f32)->bool{return depth<=0.0;}fn ssTexelUv(coord:vec2i,dims:vec2f)->vec2f{return(vec2f(coord)+vec2f(0.5))/dims;}fn ssClampCoord(coord:vec2i,dims:vec2f)->vec2i{return clamp(coord,vec2i(0,0),vec2i(dims)-vec2i(1,1));}fn ssUvToCoord(uv:vec2f,dims:vec2f)->vec2i{return ssClampCoord(vec2i(uv*dims),dims);}fn ssWorldFromDepth(uv:vec2f,depth:f32,invViewProj:mat4x4f)->vec3f{let ndc=vec3f(uv.x*2.0-1.0,1.0-uv.y*2.0,depth);let clip=invViewProj*vec4f(ndc,1.0);return clip.xyz/clip.w;}fn ssUvFromWorld(world:vec3f,viewProj:mat4x4f)->vec3f{let clip=viewProj*vec4f(world,1.0);let ndc=clip.xyz/clip.w;return vec3f(ndc.x*0.5+0.5,0.5-ndc.y*0.5,ndc.z);}fn ssBilinearDepth(uv:vec2f,dims:vec2f,depthTex:texture_depth_2d)->f32{let p=uv*dims-vec2f(0.5);let base=floor(p);let frac=p-base;let c00=ssClampCoord(vec2i(base),dims);let c10=ssClampCoord(vec2i(base)+vec2i(1,0),dims);let c01=ssClampCoord(vec2i(base)+vec2i(0,1),dims);let c11=ssClampCoord(vec2i(base)+vec2i(1,1),dims);let d00=textureLoad(depthTex,c00,0);let d10=textureLoad(depthTex,c10,0);let d01=textureLoad(depthTex,c01,0);let d11=textureLoad(depthTex,c11,0);let dx0=mix(d00,d10,frac.x);let dx1=mix(d01,d11,frac.x);return mix(dx0,dx1,frac.y);}fn ssNormalFromDepth(uv:vec2f,dims:vec2f,invViewProj:mat4x4f,depthTex:texture_depth_2d)->vec3f{let coord=ssUvToCoord(uv,dims);let dim=vec2i(dims);let cL=ssClampCoord(coord+vec2i(-1,0),dims);let cR=ssClampCoord(coord+vec2i(1,0),dims);let cU=ssClampCoord(coord+vec2i(0,-1),dims);let cD=ssClampCoord(coord+vec2i(0,1),dims);let dC=textureLoad(depthTex,coord,0);let dL=textureLoad(depthTex,cL,0);let dR=textureLoad(depthTex,cR,0);let dU=textureLoad(depthTex,cU,0);let dD=textureLoad(depthTex,cD,0);let pC=ssWorldFromDepth(ssTexelUv(coord,dims),dC,invViewProj);var pH:vec3f;if(coord.x<=0){pH=ssWorldFromDepth(ssTexelUv(cR,dims),dR,invViewProj)-pC;}else if(coord.x>=dim.x-1){pH=pC-ssWorldFromDepth(ssTexelUv(cL,dims),dL,invViewProj);}else if(abs(dL-dC)<abs(dR-dC)){pH=pC-ssWorldFromDepth(ssTexelUv(cL,dims),dL,invViewProj);}else{pH=ssWorldFromDepth(ssTexelUv(cR,dims),dR,invViewProj)-pC;}var pV:vec3f;if(coord.y<=0){pV=ssWorldFromDepth(ssTexelUv(cD,dims),dD,invViewProj)-pC;}else if(coord.y>=dim.y-1){pV=pC-ssWorldFromDepth(ssTexelUv(cU,dims),dU,invViewProj);}else if(abs(dU-dC)<abs(dD-dC)){pV=pC-ssWorldFromDepth(ssTexelUv(cU,dims),dU,invViewProj);}else{pV=ssWorldFromDepth(ssTexelUv(cD,dims),dD,invViewProj)-pC;}let n=cross(pH,pV);let n2=dot(n,n);if(n2<=1e-12){return vec3f(0.0,1.0,0.0);}return n*inverseSqrt(n2);}fn ssDualSurfaceHit(worldPos:vec3f,cameraPos:vec3f,viewProj:mat4x4f,invViewProj:mat4x4f,dims:vec2f,depthTex:texture_depth_2d,bias:f32,thickness:f32)->SsHit{let proj=ssUvFromWorld(worldPos,viewProj);let uv=proj.xy;if(uv.x<0.0||uv.x>1.0||uv.y<0.0||uv.y>1.0){return SsHit(false,uv,0.0,0.0);}let coord=ssUvToCoord(uv,dims);let discreteDepth=textureLoad(depthTex,coord,0);if(ssIsClearDepth(discreteDepth)){return SsHit(false,uv,0.0,0.0);}let continuousDepth=ssBilinearDepth(uv,dims,depthTex);let discreteWorld=ssWorldFromDepth(ssTexelUv(coord,dims),discreteDepth,invViewProj);let continuousWorld=ssWorldFromDepth(uv,continuousDepth,invViewProj);let rayDist=length(worldPos-cameraPos);let discreteDist=length(discreteWorld-cameraPos);let continuousDist=length(continuousWorld-cameraPos);let behindDiscrete=rayDist>discreteDist+bias;let behindContinuous=rayDist>continuousDist+bias;let withinThickness=(rayDist-discreteDist)<thickness&&(rayDist-continuousDist)<thickness;let hit=behindDiscrete&&behindContinuous&&withinThickness;return SsHit(hit,uv,rayDist,discreteDist);}fn ssHash(value:u32)->u32{var x=value;x=(x^(x>>16u))*2246822519u;x=(x^(x>>13u))*3266489917u;return x^(x>>16u);}fn ssScreenSpaceNoise(coord:vec2f)->f32{let p=vec2u(max(coord,vec2f(0.0))*256.0);return f32(ssHash(p.x*374761393u+p.y*668265263u))*2.3283064365386963e-10;}fn ssPhaseAngle(coord:vec2f,phase:f32)->f32{return fract(ssScreenSpaceNoise(coord)+phase);}"}function Vv(A,g){return Math.max(A,1/g)}function Wv(A,g,I){return g?1:Math.min(A+1,Math.max(1,I))}function zv(A,g){return g?0:A+1}function Zv(A,g){const I=Math.max(1,g);return A%I/I}function Xv(A){const g=A.firstAllocation||A.targetReallocated||A.sourceIdentityChanged||A.resetVersionChanged||A.enabledTransitionedOn||A.singularInverse;return{invalidateHistory:g,restartPhase:g}}function pi(A,g){return A!==g}function $v(A,g,I){return{width:Math.max(1,Math.round(A*I)),height:Math.max(1,Math.round(g*I))}}function AH(A){if(A._width>0&&A._height>0)return{width:A._width,height:A._height};const g=A._descriptor.size;return"canvas"in g?{width:g.canvas.width,height:g.canvas.height}:g}function gH(A,g,I){if(g&&g===I)throw new Error(`"${A}": targetTexture must differ from sourceTexture.`)}const JrA="struct SsTemporalParams{invViewProj:mat4x4f,currentView:mat4x4f,prevViewProj:mat4x4f,prevView:mat4x4f,effectDims:vec2f,depthDims:vec2f,params:vec4f}",IH=72,vrA=IH*4,HrA="@group(0)@binding(0)var ssLinearSampler:sampler;@group(0)@binding(1)var ssCurrentDepth:texture_depth_2d;@group(0)@binding(2)var ssRawTex:texture_2d<f32>;@group(0)@binding(3)var ssHistoryTex:texture_2d<f32>;@group(0)@binding(4)var<uniform>ssTemporal:SsTemporalParams;",TrA="struct SsVOut{@builtin(position)position:vec4f}@vertex fn ssResolveVertex(@builtin(vertex_index)i:u32)->SsVOut{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return SsVOut(vec4f(p,0,1));}",xrA="fn ssFusedGiFilter(coord:vec2i,effectDims:vec2f,depthDims:vec2f)->vec3f{let centerUv=ssTexelUv(coord,effectDims);let centerDepth=textureLoad(ssCurrentDepth,ssUvToCoord(centerUv,depthDims),0);let centerWorld=ssWorldFromDepth(centerUv,centerDepth,ssTemporal.invViewProj);let centerDist=(ssTemporal.currentView*vec4f(centerWorld,1.0)).z;var sum=textureLoad(ssRawTex,coord,0).rgb;var totalWeight=1.0;let offsets=array<vec2i,8>(vec2i(1,0),vec2i(-1,0),vec2i(0,1),vec2i(0,-1),vec2i(1,1),vec2i(-1,1),vec2i(1,-1),vec2i(-1,-1));let spatialWeights=array<f32,8>(0.75,0.75,0.75,0.75,0.5,0.5,0.5,0.5);for(var i=0;i<8;i=i+1){let nCoord=ssClampCoord(coord+offsets[i],effectDims);let nUv=ssTexelUv(nCoord,effectDims);let nDepth=textureLoad(ssCurrentDepth,ssUvToCoord(nUv,depthDims),0);if(ssIsClearDepth(nDepth)){continue;}let nWorld=ssWorldFromDepth(nUv,nDepth,ssTemporal.invViewProj);let nDist=(ssTemporal.currentView*vec4f(nWorld,1.0)).z;let agreement=max(0.0,1.0-abs(nDist-centerDist)/max(centerDist,1e-4));let w=spatialWeights[i]*agreement;sum=sum+textureLoad(ssRawTex,nCoord,0).rgb*w;totalWeight=totalWeight+w;}return sum/max(totalWeight,1e-4);}",qrA="fn ssFusedContactFilter(coord:vec2i,effectDims:vec2f,depthDims:vec2f)->f32{let centerUv=ssTexelUv(coord,effectDims);let centerDepth=textureLoad(ssCurrentDepth,ssUvToCoord(centerUv,depthDims),0);let centerWorld=ssWorldFromDepth(centerUv,centerDepth,ssTemporal.invViewProj);let centerDist=(ssTemporal.currentView*vec4f(centerWorld,1.0)).z;let offsets=array<vec2i,9>(vec2i(-1,-1),vec2i(0,-1),vec2i(1,-1),vec2i(-1,0),vec2i(0,0),vec2i(1,0),vec2i(-1,1),vec2i(0,1),vec2i(1,1));let spatialWeights=array<f32,9>(0.5,0.75,0.5,0.75,1.0,0.75,0.5,0.75,0.5);var sum=0.0;var totalWeight=0.0;for(var i=0;i<9;i=i+1){let tapCoord=ssClampCoord(coord+offsets[i],effectDims);let tapUv=ssTexelUv(tapCoord,effectDims);let tapDepth=textureLoad(ssCurrentDepth,ssUvToCoord(tapUv,depthDims),0);if(ssIsClearDepth(tapDepth)){continue;}let tapWorld=ssWorldFromDepth(tapUv,tapDepth,ssTemporal.invViewProj);let tapDist=(ssTemporal.currentView*vec4f(tapWorld,1.0)).z;let relErr=abs(tapDist-centerDist)/max(centerDist,0.001);if(relErr>0.04){continue;}let weight=spatialWeights[i]*(1.0-relErr/0.04);sum=sum+textureLoad(ssRawTex,tapCoord,0).r*weight;totalWeight=totalWeight+weight;}return sum/max(totalWeight,1e-4);}fn ssContactTemporalSample(coord:vec2i,effectDims:vec2f,depthDims:vec2f)->f32{let radius=max(ssTemporal.params.y,0.0);if(radius<=0.0){return ssFusedContactFilter(coord,effectDims,depthDims);}let phase=ssTemporal.params.z;let angle=phase*2.39996323;let radial=sqrt(fract(phase*0.754877666));let offset=vec2i(round(vec2f(cos(angle),sin(angle))*radial*radius));if(all(offset==vec2i(0))){return ssFusedContactFilter(coord,effectDims,depthDims);}let sampleCoord=ssClampCoord(coord+offset,effectDims);let centerUv=ssTexelUv(coord,effectDims);let sampleUv=ssTexelUv(sampleCoord,effectDims);let centerDepth=textureLoad(ssCurrentDepth,ssUvToCoord(centerUv,depthDims),0);let sampleDepth=textureLoad(ssCurrentDepth,ssUvToCoord(sampleUv,depthDims),0);if(ssIsClearDepth(sampleDepth)){return ssFusedContactFilter(coord,effectDims,depthDims);}let centerWorld=ssWorldFromDepth(centerUv,centerDepth,ssTemporal.invViewProj);let sampleWorld=ssWorldFromDepth(sampleUv,sampleDepth,ssTemporal.invViewProj);let centerDist=(ssTemporal.currentView*vec4f(centerWorld,1.0)).z;let sampleDist=(ssTemporal.currentView*vec4f(sampleWorld,1.0)).z;let relErr=abs(sampleDist-centerDist)/max(centerDist,0.001);if(relErr>0.04){return ssFusedContactFilter(coord,effectDims,depthDims);}return ssFusedContactFilter(sampleCoord,effectDims,depthDims);}";function PrA(A){const g=A==="color",I=g?"let rawValue=ssFusedGiFilter(coord,effectDims,depthDims);":"let rawValue=ssContactTemporalSample(coord,effectDims,depthDims);",e=g?"hist.rgb":"hist.r",t=g?"hist.a":"hist.g",i=g?"vec3f(0.0)":"0.0";return`${g?xrA:qrA} @fragment fn ssResolveFragment(v:SsVOut)->@location(0)vec4f{let coord=vec2i(v.position.xy);let effectDims=ssTemporal.effectDims;let depthDims=ssTemporal.depthDims;let uv=ssTexelUv(coord,effectDims);let depth=textureLoad(ssCurrentDepth,ssUvToCoord(uv,depthDims),0);if(ssIsClearDepth(depth)){return vec4f(0.0,0.0,0.0,0.0);}let worldPos=ssWorldFromDepth(uv,depth,ssTemporal.invViewProj);let curDist=(ssTemporal.currentView*vec4f(worldPos,1.0)).z;${I} var weight=ssTemporal.params.x;var historyValue=${i};var moved=false;let reproj=ssUvFromWorld(worldPos,ssTemporal.prevViewProj);if(reproj.x>=0.0&&reproj.x<=1.0&&reproj.y>=0.0&&reproj.y<=1.0){let expectedPrev=(ssTemporal.prevView*vec4f(worldPos,1.0)).z;let hist=textureSampleLevel(ssHistoryTex,ssLinearSampler,reproj.xy,0.0);let storedPrev=${t};let relErr=abs(expectedPrev-storedPrev)/max(expectedPrev,0.001);if(storedPrev>0.0&&relErr<=0.04){historyValue=${e};moved=length((reproj.xy-uv)*effectDims)>=1.0;}else{weight=1.0;}}else{weight=1.0;}if(moved){${g?"var mn=rawValue;var mx=rawValue;let nOffsets=array<vec2i,8>(vec2i(-1,-1),vec2i(0,-1),vec2i(1,-1),vec2i(-1,0),vec2i(1,0),vec2i(-1,1),vec2i(0,1),vec2i(1,1));for(var i=0;i<8;i=i+1){let n=textureLoad(ssRawTex,ssClampCoord(coord+nOffsets[i],effectDims),0).rgb;mn=min(mn,n);mx=max(mx,n);}historyValue=clamp(historyValue,mn,mx);":"var mn=rawValue;var mx=rawValue;let nOffsets=array<vec2i,8>(vec2i(-1,-1),vec2i(0,-1),vec2i(1,-1),vec2i(-1,0),vec2i(1,0),vec2i(-1,1),vec2i(0,1),vec2i(1,1));for(var i=0;i<8;i=i+1){let n=textureLoad(ssRawTex,ssClampCoord(coord+nOffsets[i],effectDims),0).r;mn=min(mn,n);mx=max(mx,n);}historyValue=clamp(historyValue,mn,mx);"}}return ${g?"vec4f(mix(historyValue,rawValue,weight),curDist)":"vec4f(mix(historyValue,rawValue,weight),curDist,0.0,0.0)"};}`}function OrA(A){return`${TrA} ${JrA} ${HrA} ${x3()} ${PrA(A)}`}const jrA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{return color;}";function eH(A){const{engine:g,kind:I,scene:e}=A,t=A.name,i=I==="color"?"rgba16float":"rg16float",o=wt({lbl:`${t}-stable`,format:i,samples:1,size:{width:1,height:1}}),Q=wt({lbl:`${t}-history`,format:i,samples:1,size:{width:1,height:1}});o._eager=!0,Q._eager=!0;const r=Vt({name:`${t}-history-copy`,sourceTexture:o,sourceSamplingMode:"nearest",targetTexture:Q,_shader:{fragmentWGSL:jrA}},g,e);let E=0,n=0,s=null,c=null,l=null,D=null;const p=new X(IH);let y=null,_=null,u=null;const f=new X(16),h=new X(16),w={label:`${t}-resolve`,colorAttachments:[{view:void 0,loadOp:"clear",storeOp:"store"}]};function M(){if(s)return;const R=g._device;c=R.createBindGroupLayout({label:`${t}-resolve-bgl`,entries:[{binding:0,visibility:NA.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:NA.FRAGMENT,texture:{sampleType:"depth"}},{binding:2,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:4,visibility:NA.FRAGMENT,buffer:{type:"uniform"}}]});const N=OrA(I),F=R.createShaderModule({label:`${t}-resolve`,code:N});s=R.createRenderPipeline({label:`${t}-resolve-pipeline`,layout:R.createPipelineLayout({label:`${t}-resolve-layout`,bindGroupLayouts:[c]}),vertex:{module:F,entryPoint:"ssResolveVertex"},fragment:{module:F,entryPoint:"ssResolveFragment",targets:[{format:i}]},primitive:{topology:"triangle-list"}}),D=R.createBuffer({label:`${t}-resolve-uniforms`,size:vrA,usage:SA.UNIFORM|SA.COPY_DST})}function S(R,N){const F=N._depthTexture.createView({aspect:"depth-only"});l=g._device.createBindGroup({label:`${t}-resolve-bind-group`,layout:c,entries:[{binding:0,resource:m1(g)},{binding:1,resource:F},{binding:2,resource:R._colorView},{binding:3,resource:Q._colorView},{binding:4,resource:{buffer:D}}]}),y=R._colorTexture,_=N._depthTexture,u=Q._colorTexture}return{get stableTexture(){return o},get historyTexture(){return Q},get allocated(){return E>0&&n>0},record(R,N){M();const F=Math.max(1,Math.floor(R)),G=Math.max(1,Math.floor(N));return F===E&&G===n?!1:(E=F,n=G,o._eager=!1,Q._eager=!1,Se(o),Se(Q),o._descriptor.size={width:F,height:G},Q._descriptor.size={width:F,height:G},Kt(o,g),Kt(Q,g),o._eager=!0,Q._eager=!0,r.record(),l=null,!0)},resolve(R){const N=pi(y,R.rawTexture._colorTexture),F=pi(_,R.depthTexture._depthTexture),G=pi(u,Q._colorTexture);(!l||N||F||G)&&S(R.rawTexture,R.depthTexture),p.fill(0),et(p,R.invViewProj,0),et(p,R.viewMatrix,16),et(p,f,32),et(p,h,48),p[64]=R.width,p[65]=R.height,p[66]=R.depthWidth,p[67]=R.depthHeight,p[68]=R.weight,p[69]=R.spatialRadius??0,p[70]=R.spatialPhase??0,g._device.queue.writeBuffer(D,0,p),w.colorAttachments=[{view:o._colorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}];const m=g._currentEncoder.beginRenderPass(w);m.setPipeline(s),m.setBindGroup(0,l),m.draw(3),m.end();const K=1+(r.execute?.()??0);return et(f,R.viewProjMatrix,0),et(h,R.viewMatrix,0),K},clearIdentity(){o._colorView&&g._currentEncoder.beginRenderPass({label:`${t}-clear-stable`,colorAttachments:[{view:o._colorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]}).end(),Q._colorView&&g._currentEncoder.beginRenderPass({label:`${t}-clear-history`,colorAttachments:[{view:Q._colorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]}).end()},dispose(){r.dispose(),o._eager=!1,Q._eager=!1,Se(o),Se(Q),s=null,l=null,c=null,D?.destroy(),D=null,y=null,_=null,u=null}}}const g1=(A,g,I)=>Math.min(I,Math.max(g,A));function VrA(A){return{resolutionScale:g1(A.resolutionScale??1,.25,1),intensity:g1(A.intensity??.6,0,4),tint:A.tint??[.35,.38,.48],stepCount:Math.round(g1(A.stepCount??8,1,64)),maxDistance:g1(A.maxDistance??.3,.001,1e3),thickness:g1(A.thickness??.35,.001,1e3),bias:g1(A.bias??.03,0,100),normalBias:g1(A.normalBias??.035,.001,100),temporalWeight:g1(A.temporalWeight??1/32,0,1),temporalSamples:Math.round(g1(A.temporalSamples??32,1,256)),spatialRadius:g1(A.spatialRadius??1.5,0,4)}}const tH=48,WrA=tH*4,zrA="struct SsContactParams{invViewProj:mat4x4f,viewProj:mat4x4f,rayDir:vec3f,stepCount:f32,cameraPos:vec3f,maxDistance:f32,outputDims:vec2f,depthDims:vec2f,bias:f32,normalBias:f32,thickness:f32,phase:f32}",ZrA="@group(0)@binding(0)var ssDepth:texture_depth_2d;@group(0)@binding(1)var<uniform>ssContact:SsContactParams;",XrA="fn ssTangentPlaneClearance(candidateWorld:vec3f,receiverWorld:vec3f,receiverNormal:vec3f)->f32{return dot(candidateWorld-receiverWorld,receiverNormal);}",$rA="struct SsCVOut{@builtin(position)position:vec4f}@vertex fn ssContactVertex(@builtin(vertex_index)i:u32)->SsCVOut{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return SsCVOut(vec4f(p,0,1));}",AEA="@fragment fn ssContactFragment(v:SsCVOut)->@location(0)vec4f{let coord=vec2i(v.position.xy);let uv=ssTexelUv(coord,ssContact.outputDims);let depth=textureLoad(ssDepth,ssUvToCoord(uv,ssContact.depthDims),0);if(ssIsClearDepth(depth)){return vec4f(0.0,0.0,0.0,0.0);}let worldPos=ssWorldFromDepth(uv,depth,ssContact.invViewProj);let normal=ssNormalFromDepth(uv,ssContact.depthDims,ssContact.invViewProj,ssDepth);let originPos=worldPos+normal*ssContact.bias;let stepCount=max(1u,u32(ssContact.stepCount));let stepLen=ssContact.maxDistance/f32(stepCount);let jitter=ssPhaseAngle(vec2f(coord),ssContact.phase);var occlusion=0.0;for(var i:u32=0u;i<stepCount;i=i+1u){let t=(f32(i)+jitter)*stepLen;let samplePos=originPos+ssContact.rayDir*t;let hit=ssDualSurfaceHit(samplePos,ssContact.cameraPos,ssContact.viewProj,ssContact.invViewProj,ssContact.depthDims,ssDepth,ssContact.bias,ssContact.thickness);if(hit.hit){let hitDepth=textureLoad(ssDepth,ssUvToCoord(hit.uv,ssContact.depthDims),0);let hitWorld=ssWorldFromDepth(hit.uv,hitDepth,ssContact.invViewProj);let clearance=ssTangentPlaneClearance(hitWorld,worldPos,normal);let clearanceFoot=ssContact.normalBias*0.35;if(clearance>clearanceFoot){let distFactor=clamp(1.0-t/ssContact.maxDistance,0.0,1.0);let penetration=clamp(1.0-abs(hit.rayDist-hit.surfaceDist)/max(ssContact.thickness,1e-4),0.0,1.0);let clearanceWeight=smoothstep(clearanceFoot,ssContact.normalBias,clearance);occlusion=max(occlusion,distFactor*penetration*clearanceWeight);}}}return vec4f(occlusion,0.0,0.0,0.0);}";function gEA(){return`${$rA} ${zrA} ${ZrA} ${x3()} ${XrA} ${AEA}`}const IEA="@group(0)@binding(2)var ssShadowTex:texture_2d<f32>;",eEA="struct SsContactCompositeParams{intensity:f32,enabled:f32,tintR:f32,tintG:f32,tintB:f32,p0:f32,p1:f32,p2:f32}@group(0)@binding(3)var<uniform>ssContactComposite:SsContactCompositeParams;",tEA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{if(ssContactComposite.enabled<0.5){return color;}let shadow=textureSample(ssShadowTex,sourceSampler,uv).r;let amount=clamp(shadow*ssContactComposite.intensity,0.0,1.0);let tint=vec3f(ssContactComposite.tintR,ssContactComposite.tintG,ssContactComposite.tintB);return vec4f(color.rgb*mix(vec3f(1.0),tint,amount),color.a);}";function CEA(A,g,I){const e=A.name??"screen-space-contact-shadows",t=A.sourceTexture,i=A.depthTexture??t;(t._descriptor.samples??1)!==1&&U(440,e),(i._descriptor.samples??1)!==1&&U(441,e),i._descriptor.dFormat||U(442,e),gH(`ScreenSpaceContactShadowsPostProcessTask "${e}"`,A.targetTexture,t);const o=VrA(A),Q={camera:A.camera,lightDirection:A.lightDirection,composition:A.composition??"multiply",resetVersion:A.resetVersion??0,...o},r=wt({lbl:`${e}-raw`,format:"r8unorm",samples:1,size:{width:1,height:1}}),E=eH({name:e,kind:"scalar",engine:g,scene:I});let n=null,s=null,c=null,l=null;const D=new X(tH);let p=null;const y=Q.composition==="none"?null:Vt({name:`${e}-composite`,sourceTexture:t,sourceSamplingMode:"linear",targetTexture:A.targetTexture??null,_shader:{extraTextureWGSL:IEA,extraTextures:[E.stableTexture],uniformWGSL:eEA,uniformBinding:3,uniformByteLength:32,writeUniforms(k){k[0]=K.intensity,k[1]=K.enabled?1:0,k[2]=K.tint[0],k[3]=K.tint[1],k[4]=K.tint[2]},fragmentWGSL:tEA}},g,I);let _=0,u=0,f=!0,h=!1,w,M,S=null,R=1,N=0,F=!1;function G(){if(n)return;const k=g._device;s=k.createBindGroupLayout({label:`${e}-producer-bgl`,entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"depth"}},{binding:1,visibility:NA.FRAGMENT,buffer:{type:"uniform"}}]});const L=k.createShaderModule({label:`${e}-producer`,code:gEA()});n=k.createRenderPipeline({label:`${e}-producer-pipeline`,layout:k.createPipelineLayout({label:`${e}-producer-layout`,bindGroupLayouts:[s]}),vertex:{module:L,entryPoint:"ssContactVertex"},fragment:{module:L,entryPoint:"ssContactFragment",targets:[{format:"r8unorm"}]},primitive:{topology:"triangle-list"}}),l=k.createBuffer({label:`${e}-producer-uniforms`,size:WrA,usage:SA.UNIFORM|SA.COPY_DST})}function m(){const k=i._depthTexture.createView({aspect:"depth-only"});c=g._device.createBindGroup({label:`${e}-producer-bind-group`,layout:s,entries:[{binding:0,resource:k},{binding:1,resource:{buffer:l}}]}),p=i._depthTexture}const K={name:e,engine:g,scene:I,_passes:[],sourceTexture:t,depthTexture:i,targetTexture:A.targetTexture??null,outputTexture:y?y.outputTexture:E.stableTexture,shadowTexture:E.stableTexture,enabled:!0,intensity:Q.intensity,tint:Q.tint,stepCount:Q.stepCount,maxDistance:Q.maxDistance,thickness:Q.thickness,bias:Q.bias,normalBias:Q.normalBias,temporalWeight:Q.temporalWeight,spatialRadius:Q.spatialRadius,resetVersion:Q.resetVersion,lightDirection:Q.lightDirection,record(){G();const k=AH(i),L=$v(k.width,k.height,Q.resolutionScale);(L.width!==_||L.height!==u)&&(_=L.width,u=L.height,r._eager=!1,Se(r),r._descriptor.size={width:_,height:u},Kt(r,g),r._eager=!0,c=null,h=!0),E.record(_,u)&&(h=!0),y?.record(),K.outputTexture=y?y.outputTexture:E.stableTexture},execute(){if(!K.enabled)return w&&E.clearIdentity(),w=!1,M=K.resetVersion,f=!1,h=!1,y?.updateUniforms(),y?.execute?.()??0;const L=Q.camera,H=KC(L,i._width||1,i._height||1),q=x1(L,H),CA=lt(q),eA=l1(L),Z=jQ(L);if(T1(L),!CA)return F=!0,w=!0,M=K.resetVersion,f=!1,h=!1,E.clearIdentity(),y?.updateUniforms(),y?.execute?.()??0;const O=pi(S,i._depthTexture),P=Xv({firstAllocation:f,targetReallocated:h,sourceIdentityChanged:O||F,resetVersionChanged:K.resetVersion!==M,enabledTransitionedOn:!w,singularInverse:!1});F=!1,R=Wv(R,P.invalidateHistory,Q.temporalSamples);const gA=Vv(g1(K.temporalWeight,0,1),R);N=zv(N,P.restartPhase);const yA=Zv(N,Q.temporalSamples);(pi(p,i._depthTexture)||!c)&&m();const cA=K.lightDirection,RA=Math.hypot(cA.x,cA.y,cA.z)||1,YA=Math.round(g1(K.stepCount,1,64)),Ag=g1(K.maxDistance,.001,1e3),lg=g1(K.bias,0,100),mA=g1(K.normalBias,.001,100),HA=g1(K.thickness,.001,1e3);D.fill(0),et(D,CA,0),et(D,q,16),D[32]=-cA.x/RA,D[33]=-cA.y/RA,D[34]=-cA.z/RA,D[35]=YA,D[36]=Z.x,D[37]=Z.y,D[38]=Z.z,D[39]=Ag,D[40]=_,D[41]=u,D[42]=i._width,D[43]=i._height,D[44]=lg,D[45]=mA,D[46]=HA,D[47]=yA,g._device.queue.writeBuffer(l,0,D);const Qg=g._currentEncoder.beginRenderPass({label:`${e}-producer`,colorAttachments:[{view:r._colorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});Qg.setPipeline(n),Qg.setBindGroup(0,c),Qg.draw(3),Qg.end();const Eg=1+E.resolve({width:_,height:u,depthWidth:i._width,depthHeight:i._height,rawTexture:r,depthTexture:i,invViewProj:CA,viewMatrix:eA,viewProjMatrix:q,weight:gA,spatialRadius:g1(K.spatialRadius,0,4),spatialPhase:N%Math.max(1,Q.temporalSamples)});return w=!0,M=K.resetVersion,S=i._depthTexture,f=!1,h=!1,y?.updateUniforms(),Eg+(y?.execute?.()??0)},dispose(){K._passes.length=0,y?.dispose(),E.dispose(),r._eager=!1,Se(r),n=null,c=null,s=null,l?.destroy(),l=null,p=null}};return K}const St=(A,g,I)=>Math.min(I,Math.max(g,A));function iEA(A){const g=St(A.fadeStart??20,0,1e5),I=Math.max(A.fadeEnd??60,g+.001);return{resolutionScale:St(A.resolutionScale??.5,.25,1),intensity:St(A.intensity??1,0,4),stepCount:Math.round(St(A.stepCount??8,1,64)),rayCount:Math.round(St(A.rayCount??1,1,8)),rayLength:St(A.rayLength??2,.001,1e3),thickness:St(A.thickness??.45,.001,1e3),bias:St(A.bias??.05,0,100),fadeStart:g,fadeEnd:I,edgeFade:St(A.edgeFade??.1,.001,.5),temporalWeight:St(A.temporalWeight??1/64,0,1),temporalSamples:Math.round(St(A.temporalSamples??64,1,256)),colorBleedGain:St(A.colorBleedGain??1,0,16),colorBleedMax:St(A.colorBleedMax??.45,0,1)}}const CH=48,oEA=CH*4,BEA="struct SsGiParams{invViewProj:mat4x4f,viewProj:mat4x4f,cameraPos:vec3f,stepCount:f32,rayLength:f32,thickness:f32,bias:f32,fadeStart:f32,fadeEnd:f32,edgeFade:f32,phase:f32,rayCount:f32,outputDims:vec2f,depthDims:vec2f}",QEA="@group(0)@binding(0)var ssGiDepth:texture_depth_2d;@group(0)@binding(1)var ssGiColorSampler:sampler;@group(0)@binding(2)var ssGiColor:texture_2d<f32>;@group(0)@binding(3)var<uniform>ssGi:SsGiParams;",rEA="fn ssCosineHemisphere(n:vec3f,u1:f32,u2:f32)->vec3f{let r=sqrt(u1);let theta=6.2831853*u2;let x=r*cos(theta);let y=r*sin(theta);let z=sqrt(max(0.0,1.0-u1));var up=vec3f(0.0,1.0,0.0);if(abs(n.y)>0.999){up=vec3f(1.0,0.0,0.0);}let tangent=normalize(cross(up,n));let bitangent=cross(n,tangent);return normalize(tangent*x+bitangent*y+n*z);}",EEA="struct SsGVOut{@builtin(position)position:vec4f}@vertex fn ssGiVertex(@builtin(vertex_index)i:u32)->SsGVOut{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return SsGVOut(vec4f(p,0,1));}",nEA="@fragment fn ssGiFragment(v:SsGVOut)->@location(0)vec4f{let coord=vec2i(v.position.xy);let uv=ssTexelUv(coord,ssGi.outputDims);let depth=textureLoad(ssGiDepth,ssUvToCoord(uv,ssGi.depthDims),0);if(ssIsClearDepth(depth)){return vec4f(0.0,0.0,0.0,0.0);}let worldPos=ssWorldFromDepth(uv,depth,ssGi.invViewProj);let normal=ssNormalFromDepth(uv,ssGi.depthDims,ssGi.invViewProj,ssGiDepth);let originPos=worldPos+normal*ssGi.bias;let stepCount=max(1u,u32(ssGi.stepCount));let stepLen=ssGi.rayLength/f32(stepCount);let rayCount=max(1u,min(8u,u32(ssGi.rayCount)));var colorSum=vec3f(0.0);for(var rayIndex:u32=0u;rayIndex<8u;rayIndex=rayIndex+1u){if(rayIndex>=rayCount){break;}let raySeed=f32(rayIndex);let seedOffset=vec2f(raySeed*37.719,raySeed*17.173);let u1=fract(ssPhaseAngle(vec2f(coord)+seedOffset,ssGi.phase)+raySeed*0.754877666);let u2=fract(ssScreenSpaceNoise(vec2f(coord)*1.7+vec2f(23.11,9.07)+seedOffset)+ssGi.phase*0.61803399);let dither=fract(ssScreenSpaceNoise(vec2f(coord)*0.731+vec2f(11.317,31.179)+seedOffset)+ssGi.phase*0.38196601);let rayDir=ssCosineHemisphere(normal,u1,u2);var rayColor=vec3f(0.0);for(var i:u32=0u;i<stepCount;i=i+1u){let t=(f32(i)+0.35+0.65*dither)*stepLen;let samplePos=originPos+rayDir*t;let hit=ssDualSurfaceHit(samplePos,ssGi.cameraPos,ssGi.viewProj,ssGi.invViewProj,ssGi.depthDims,ssGiDepth,ssGi.bias,ssGi.thickness);if(hit.hit){let edge=min(min(hit.uv.x,1.0-hit.uv.x),min(hit.uv.y,1.0-hit.uv.y))/max(ssGi.edgeFade,1e-4);let edgeFactor=clamp(edge,0.0,1.0);let distFade=clamp(1.0-smoothstep(ssGi.fadeStart,ssGi.fadeEnd,hit.rayDist),0.0,1.0);let litColor=textureSampleLevel(ssGiColor,ssGiColorSampler,hit.uv,0.0).rgb;rayColor=litColor*edgeFactor*distFade;break;}}colorSum=colorSum+rayColor;}return vec4f(colorSum/f32(rayCount),1.0);}";function sEA(){return`${EEA} ${BEA} ${QEA} ${x3()} ${rEA} ${nEA}`}const aEA="@group(0)@binding(2)var ssGiTex:texture_2d<f32>;",cEA="struct SsGiCompositeParams{intensity:f32,enabled:f32,colorBleedGain:f32,colorBleedMax:f32}@group(0)@binding(3)var<uniform>ssGiComposite:SsGiCompositeParams;";function lEA(A){return A==="color-bleed"?"fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{if(ssGiComposite.enabled<0.5){return color;}let illum=textureSample(ssGiTex,sourceSampler,uv).rgb;let luminance=dot(illum,vec3f(0.2126,0.7152,0.0722));let amount=min(ssGiComposite.intensity*min(luminance*ssGiComposite.colorBleedGain,1.0),ssGiComposite.colorBleedMax);return vec4f(color.rgb*mix(vec3f(1.0),illum/max(luminance,1e-4),amount),color.a);}":"fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{if(ssGiComposite.enabled<0.5){return color;}let illum=textureSample(ssGiTex,sourceSampler,uv).rgb;return vec4f(color.rgb+illum*ssGiComposite.intensity,color.a);}"}function DEA(A,g,I){const e=A.name??"screen-space-global-illumination",t=A.sourceTexture,i=A.depthTexture??t;(t._descriptor.samples??1)!==1&&U(443,e),(i._descriptor.samples??1)!==1&&U(444,e),i._descriptor.dFormat||U(445,e),gH(`ScreenSpaceGlobalIlluminationPostProcessTask "${e}"`,A.targetTexture,t);const o=iEA(A),Q={camera:A.camera,composition:A.composition??"additive",resetVersion:A.resetVersion??0,...o},r=wt({lbl:`${e}-raw`,format:"rgba16float",samples:1,size:{width:1,height:1}}),E=eH({name:e,kind:"color",engine:g,scene:I});let n=null,s=null,c=null,l=null;const D=new X(CH);let p=null,y=null;const _=Q.composition==="none"?null:Vt({name:`${e}-composite`,sourceTexture:t,sourceSamplingMode:"linear",targetTexture:A.targetTexture??null,_shader:{extraTextureWGSL:aEA,extraTextures:[E.stableTexture],uniformWGSL:cEA,uniformBinding:3,uniformByteLength:16,writeUniforms(H){H[0]=L.intensity,H[1]=L.enabled?1:0,H[2]=L.colorBleedGain,H[3]=L.colorBleedMax},fragmentWGSL:lEA(Q.composition==="color-bleed"?"color-bleed":"additive")}},g,I);let u=0,f=0,h=!0,w=!1,M,S,R=null,N=null,F=1,G=0,m=!1;function K(){if(n)return;const H=g._device;s=H.createBindGroupLayout({label:`${e}-producer-bgl`,entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"depth"}},{binding:1,visibility:NA.FRAGMENT,sampler:{type:"filtering"}},{binding:2,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:NA.FRAGMENT,buffer:{type:"uniform"}}]});const q=H.createShaderModule({label:`${e}-producer`,code:sEA()});n=H.createRenderPipeline({label:`${e}-producer-pipeline`,layout:H.createPipelineLayout({label:`${e}-producer-layout`,bindGroupLayouts:[s]}),vertex:{module:q,entryPoint:"ssGiVertex"},fragment:{module:q,entryPoint:"ssGiFragment",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list"}}),l=H.createBuffer({label:`${e}-producer-uniforms`,size:oEA,usage:SA.UNIFORM|SA.COPY_DST})}function k(){const H=i._depthTexture.createView({aspect:"depth-only"});c=g._device.createBindGroup({label:`${e}-producer-bind-group`,layout:s,entries:[{binding:0,resource:H},{binding:1,resource:m1(g)},{binding:2,resource:t._colorView},{binding:3,resource:{buffer:l}}]}),p=i._depthTexture,y=t._colorTexture}const L={name:e,engine:g,scene:I,_passes:[],sourceTexture:t,depthTexture:i,targetTexture:A.targetTexture??null,outputTexture:_?_.outputTexture:E.stableTexture,illuminationTexture:E.stableTexture,enabled:!0,intensity:Q.intensity,stepCount:Q.stepCount,rayCount:Q.rayCount,rayLength:Q.rayLength,thickness:Q.thickness,bias:Q.bias,fadeStart:Q.fadeStart,fadeEnd:Q.fadeEnd,edgeFade:Q.edgeFade,temporalWeight:Q.temporalWeight,colorBleedGain:Q.colorBleedGain,colorBleedMax:Q.colorBleedMax,resetVersion:Q.resetVersion,record(){K();const H=AH(i),q=$v(H.width,H.height,Q.resolutionScale);(q.width!==u||q.height!==f)&&(u=q.width,f=q.height,r._eager=!1,Se(r),r._descriptor.size={width:u,height:f},Kt(r,g),r._eager=!0,c=null,w=!0),E.record(u,f)&&(w=!0),_?.record(),L.outputTexture=_?_.outputTexture:E.stableTexture},execute(){if(!L.enabled)return M&&E.clearIdentity(),M=!1,S=L.resetVersion,h=!1,w=!1,_?.updateUniforms(),_?.execute?.()??0;const q=Q.camera,CA=KC(q,i._width||1,i._height||1),eA=x1(q,CA),Z=lt(eA),O=l1(q),P=jQ(q);if(T1(q),!Z)return m=!0,M=!0,S=L.resetVersion,h=!1,w=!1,E.clearIdentity(),_?.updateUniforms(),_?.execute?.()??0;const gA=pi(R,i._depthTexture),yA=pi(N,t._colorTexture),cA=Xv({firstAllocation:h,targetReallocated:w,sourceIdentityChanged:gA||yA||m,resetVersionChanged:L.resetVersion!==S,enabledTransitionedOn:!M,singularInverse:!1});m=!1,F=Wv(F,cA.invalidateHistory,Q.temporalSamples);const RA=Vv(St(L.temporalWeight,0,1),F);G=zv(G,cA.restartPhase);const YA=Zv(G,Q.temporalSamples);(pi(p,i._depthTexture)||pi(y,t._colorTexture)||!c)&&k();const Ag=Math.round(St(L.stepCount,1,64)),lg=Math.round(St(L.rayCount,1,8)),mA=St(L.rayLength,.001,1e3),HA=St(L.thickness,.001,1e3),Qg=St(L.bias,0,100),Eg=St(L.fadeStart,0,1e5),kA=Math.max(L.fadeEnd,Eg+.001),ug=St(L.edgeFade,.001,.5);D.fill(0),et(D,Z,0),et(D,eA,16),D[32]=P.x,D[33]=P.y,D[34]=P.z,D[35]=Ag,D[36]=mA,D[37]=HA,D[38]=Qg,D[39]=Eg,D[40]=kA,D[41]=ug,D[42]=YA,D[43]=lg,D[44]=u,D[45]=f,D[46]=i._width,D[47]=i._height,g._device.queue.writeBuffer(l,0,D);const fg=g._currentEncoder.beginRenderPass({label:`${e}-producer`,colorAttachments:[{view:r._colorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});fg.setPipeline(n),fg.setBindGroup(0,c),fg.draw(3),fg.end();const rg=1+E.resolve({width:u,height:f,depthWidth:i._width,depthHeight:i._height,rawTexture:r,depthTexture:i,invViewProj:Z,viewMatrix:O,viewProjMatrix:eA,weight:RA});return M=!0,S=L.resetVersion,R=i._depthTexture,N=t._colorTexture,h=!1,w=!1,_?.updateUniforms(),rg+(_?.execute?.()??0)},dispose(){L._passes.length=0,_?.dispose(),E.dispose(),r._eager=!1,Se(r),n=null,c=null,s=null,l?.destroy(),l=null,p=null,y=null,N=null}};return L}function pEA(A){A.lowerRadiusLimit!==void 0&&A.radius<A.lowerRadiusLimit?(A.radius=A.lowerRadiusLimit,A.inertialRadiusOffset=0):A.upperRadiusLimit!==void 0&&A.radius>A.upperRadiusLimit&&(A.radius=A.upperRadiusLimit,A.inertialRadiusOffset=0),A.lowerBetaLimit!==void 0&&A.beta<A.lowerBetaLimit?(A.beta=A.lowerBetaLimit,A.inertialBetaOffset=0):A.upperBetaLimit!==void 0&&A.beta>A.upperBetaLimit&&(A.beta=A.upperBetaLimit,A.inertialBetaOffset=0),A.lowerAlphaLimit!==void 0&&A.alpha<A.lowerAlphaLimit?(A.alpha=A.lowerAlphaLimit,A.inertialAlphaOffset=0):A.upperAlphaLimit!==void 0&&A.alpha>A.upperAlphaLimit&&(A.alpha=A.upperAlphaLimit,A.inertialAlphaOffset=0)}function yEA(A,g,I){"lowerAlphaLimit"in g&&(A.lowerAlphaLimit=g.lowerAlphaLimit),"upperAlphaLimit"in g&&(A.upperAlphaLimit=g.upperAlphaLimit),"lowerBetaLimit"in g&&(A.lowerBetaLimit=g.lowerBetaLimit),"upperBetaLimit"in g&&(A.upperBetaLimit=g.upperBetaLimit),"lowerRadiusLimit"in g&&(A.lowerRadiusLimit=g.lowerRadiusLimit),"upperRadiusLimit"in g&&(A.upperRadiusLimit=g.upperRadiusLimit);const e=()=>pEA(A);return A._clampToLimits=e,e(),()=>{A._clampToLimits===e&&(A._clampToLimits=void 0)}}function _EA(A,g,I,e){let Q=!1,r=!1,E=0,n=0;const s=new Map;let c=0,l=0;function D(N){e?.shouldHandlePointerDown&&!e.shouldHandlePointerDown(N)||(g.setPointerCapture(N.pointerId),E=N.clientX,n=N.clientY,N.button===0?(Q=!0,r=!1):N.button===2&&(Q=!1,r=!0))}function p(N){const F=N.clientX-E,G=N.clientY-n;if(E=N.clientX,n=N.clientY,!(s.size>=2)&&!(!Q&&!r)){if(e?.isExternalDragActive?.()){Q=!1,r=!1,A.inertialAlphaOffset=0,A.inertialBetaOffset=0,A.inertialPanningX=0,A.inertialPanningY=0;return}if(!e?.isExternalPickPending?.()){if(Q){const m=A.angularSensibility;A.inertialAlphaOffset-=F/m,A.inertialBetaOffset-=G/m}if(r){const m=A.panningSensibility;A.inertialPanningX+=-F/m,A.inertialPanningY+=G/m}}}}function y(N){g.releasePointerCapture(N.pointerId),Q=!1,r=!1}function _(N){N.preventDefault(),A.inertialRadiusOffset-=N.deltaY*A.radius/(A.wheelPrecision*1e3)}function u(N){N.preventDefault()}function f(N){for(let F=0;F<N.changedTouches.length;F++){const G=N.changedTouches[F];s.set(G.identifier,{x:G.clientX,y:G.clientY})}if(s.size>=2){Q=!1,r=!1;const F=s.values(),G=F.next().value,m=F.next().value;c=Math.hypot(m.x-G.x,m.y-G.y),l=A.radius,N.preventDefault()}}function h(N){for(let F=0;F<N.changedTouches.length;F++){const G=N.changedTouches[F];s.set(G.identifier,{x:G.clientX,y:G.clientY})}if(s.size>=2){N.preventDefault();const F=s.values(),G=F.next().value,m=F.next().value,K=Math.hypot(m.x-G.x,m.y-G.y);c>0&&K>0&&(A.radius=l*(c/K),A.radius=Math.max(.01,A.radius))}}function w(N){for(let F=0;F<N.changedTouches.length;F++)s.delete(N.changedTouches[F].identifier);if(s.size===1){const F=s.values().next().value;E=F.x,n=F.y}s.size<2&&(c=0)}function M(N){N.preventDefault()}function S(){if(A.inertialAlphaOffset!==0||A.inertialBetaOffset!==0){A.alpha+=A.inertialAlphaOffset,A.beta+=A.inertialBetaOffset;const N=.01;A.beta=Math.max(N,Math.min(Math.PI-N,A.beta)),A.inertialAlphaOffset*=A.inertia,A.inertialBetaOffset*=A.inertia,Math.abs(A.inertialAlphaOffset)<.001&&(A.inertialAlphaOffset=0),Math.abs(A.inertialBetaOffset)<.001&&(A.inertialBetaOffset=0)}if(A.inertialRadiusOffset!==0&&(A.radius-=A.inertialRadiusOffset,A.radius=Math.max(.01,A.radius),A.inertialRadiusOffset*=A.inertia,Math.abs(A.inertialRadiusOffset)<.001&&(A.inertialRadiusOffset=0)),A.inertialPanningX!==0||A.inertialPanningY!==0){const N=Math.cos(A.alpha),G=-Math.sin(A.alpha),m=N,K=A.radius*.001;A.target.x+=G*A.inertialPanningX*K,A.target.y+=A.inertialPanningY*K,A.target.z+=m*A.inertialPanningX*K,A.inertialPanningX*=A.panningInertia,A.inertialPanningY*=A.panningInertia,Math.abs(A.inertialPanningX)<1e-4&&(A.inertialPanningX=0),Math.abs(A.inertialPanningY)<1e-4&&(A.inertialPanningY=0)}}I&&I._beforeRender.push(S);const R=[["pointerdown",D],["pointermove",p],["pointerup",y],["wheel",_,{passive:!1}],["contextmenu",u],["touchstart",f,{passive:!1}],["touchmove",h,{passive:!1}],["touchend",w],["gesturestart",M,{passive:!1}],["gesturechange",M,{passive:!1}],["gestureend",M,{passive:!1}]];for(const[N,F,G]of R)g.addEventListener(N,F,G);return()=>{if(I){const N=I._beforeRender.indexOf(S);N>=0&&I._beforeRender.splice(N,1)}for(const[N,F]of R)g.removeEventListener(N,F)}}function q3(A){return A instanceof Error?A:new Error(String(A))}const iH=()=>{};function oH(A,g,I){return new Promise((e,t)=>{if(I?.aborted){t(q3(I.reason));return}let i=!1,o;const Q=()=>{if(i)return;i=!0;const E=A._beforeRender,n=E.indexOf(r);if(n>=0)for(E[n]=iH;E.length>0&&E[E.length-1]===iH;)E.pop();o&&I&&I.removeEventListener("abort",o)},r=E=>{if(i)return;const n=(E>0?E:1e3/60)/1e3;let s;try{s=g(n)}catch(c){Q(),t(q3(c));return}s||(Q(),e())};I&&(o=()=>{Q(),t(q3(I.reason))},I.addEventListener("abort",o)),A._beforeRender.push(r)})}function BH(A,g){return g<=0?1:A<=0?0:1-Math.pow(2,-A/g)}function QH(A,g,I){return A+(g-A)*I}function $R(A,g,I){const e=Math.PI*2;let t=(g-A)%e;return t>Math.PI?t-=e:t<-Math.PI&&(t+=e),A+t*I}function rH(A,g,I){return I.x=A.x+g.x,I.y=A.y+g.y,I.z=A.z+g.z,I}function uEA(A,g){return rH(A,g,A)}function EH(A,g,I){return I.x=A.x-g.x,I.y=A.y-g.y,I.z=A.z-g.z,I}function hEA(A,g){return EH(A,g,A)}function nH(A,g,I){return I.x=A.x*g,I.y=A.y*g,I.z=A.z*g,I}function fEA(A,g){return nH(A,g,A)}function sH(A,g,I){const e=A.y*g.z-A.z*g.y,t=A.z*g.x-A.x*g.z,i=A.x*g.y-A.y*g.x;return I.x=e,I.y=t,I.z=i,I}function dEA(A,g){return sH(A,g,A)}function aH(A,g,I=1e-10){const e=Math.hypot(A.x,A.y,A.z);if(e<=I)return g.x=0,g.y=0,g.z=0,g;const t=1/e;return g.x=A.x*t,g.y=A.y*t,g.z=A.z*t,g}function wEA(A,g=1e-10){return aH(A,A,g)}function cH(A,g){return g.x=-A.x,g.y=-A.y,g.z=-A.z,g}function MEA(A){return cH(A,A)}function P3(A,g,I,e){return e.x=A.x+(g.x-A.x)*I,e.y=A.y+(g.y-A.y)*I,e.z=A.z+(g.z-A.z)*I,e}function SEA(A,g,I){return P3(A,g,I,A)}const REA=.1,bF=.001;function O3(A,g,I){return g!==void 0&&A<g?g:I!==void 0&&A>I?I:A}function NEA(A,g,I,e,t){const i=t?.interpolationFactor??REA,o=I.alpha!==void 0&&!isNaN(I.alpha),Q=I.beta!==void 0&&!isNaN(I.beta),r=I.radius!==void 0&&!isNaN(I.radius),E=I.target!==void 0;let n=0,s=0,c=0;const l={x:0,y:0,z:0};let D=0,p=0,y=0;const _={x:0,y:0,z:0};let u=!0;return oH(g,h=>{if(u)u=!1,A.inertialAlphaOffset=0,A.inertialBetaOffset=0,A.inertialRadiusOffset=0,A.inertialPanningX=0,A.inertialPanningY=0,n=o?I.alpha:A.alpha,s=Q?I.beta:A.beta,c=r?I.radius:A.radius,l.x=E?I.target.x:A.target.x,l.y=E?I.target.y:A.target.y,l.z=E?I.target.z:A.target.z;else if(A.alpha!==D||A.beta!==p||A.radius!==y||A.target.x!==_.x||A.target.y!==_.y||A.target.z!==_.z)throw new Error("ArcRotate camera interpolation was interrupted.");const w=O3(n,A.lowerAlphaLimit,A.upperAlphaLimit),M=O3(s,A.lowerBetaLimit,A.upperBetaLimit),S=O3(c,A.lowerRadiusLimit,A.upperRadiusLimit),R=BH(h,i);A.alpha=$R(A.alpha,w,R),A.beta=$R(A.beta,M,R),A.radius=QH(A.radius,S,R),P3(A.target,l,R,A.target);const N=Math.abs(S)>1e-6?Math.abs(S):1,F=Math.abs($R(A.alpha,w,1)-A.alpha),G=Math.abs($R(A.beta,M,1)-A.beta),m=Math.abs(S-A.radius)/N,K=l.x-A.target.x,k=l.y-A.target.y,L=l.z-A.target.z,H=Math.hypot(K,k,L)/N;return F<bF&&G<bF&&m<bF&&H<bF?(A.alpha=w,A.beta=M,A.radius=S,A.target.x=l.x,A.target.y=l.y,A.target.z=l.z,!1):(D=A.alpha,p=A.beta,y=A.radius,_.x=A.target.x,_.y=A.target.y,_.z=A.target.z,!0)},e)}function j3(A,g){return lH(A,g,R3)}function lH(A,g,I){const e=g.x-A.x,t=g.y-A.y,i=g.z-A.z,o=se();function Q(){return S3(o,c.position,c.target,I),o}const r=so(Q),E=()=>r.markLocalDirty();let n=Math.atan2(e,i),s=Math.atan2(t,Math.sqrt(e*e+i*i));const c={position:new Ht(A.x,A.y,A.z,E),target:new Ht(g.x,g.y,g.z,E),fov:.8,nearPlane:1,farPlane:1e4,speed:2,angularSensitivity:2e3,inertia:.9,children:[],_viewCache:se(),_projCache:se(),_vpCache:se(),get parent(){return r.parent},set parent(l){r.parent=l},get worldMatrix(){return r.getWorldMatrix()},get worldMatrixVersion(){return r.getWorldMatrixVersion()}};return Object.defineProperty(c,"_yaw",{get(){return n},set(l){n!==l&&(n=l,E())},configurable:!0,enumerable:!0}),Object.defineProperty(c,"_pitch",{get(){return s},set(l){s!==l&&(s=l,E())},configurable:!0,enumerable:!0}),tQ(c,r),c}function GEA(A,g,I={x:0,y:1,z:0}){const e=new Ht(I.x,I.y,I.z,()=>OR(t)),t=lH(A,g,e);return Object.defineProperty(t,"upVector",{value:e,enumerable:!0}),t}function FEA(A,g,I){let e=0,t=0,i=0,o=0,Q=0,r=!1,E=0,n=0;const s=new Set;function c(f){(f.button===0||f.button===1||f.button===2)&&(g.setPointerCapture(f.pointerId),r=!0,E=f.clientX,n=f.clientY)}function l(f){if(!r)return;const h=f.clientX-E,w=f.clientY-n;E=f.clientX,n=f.clientY,Q+=h/A.angularSensitivity,o+=w/A.angularSensitivity}function D(f){g.releasePointerCapture(f.pointerId),r=!1}function p(f){f.preventDefault()}function y(f){s.add(f.code)}function _(f){s.delete(f.code)}function u(f){const h=Math.max(f,1),w=A.speed*Math.sqrt(h*h/1e5);(s.has("KeyW")||s.has("ArrowUp"))&&(i+=w),(s.has("KeyS")||s.has("ArrowDown"))&&(i-=w),(s.has("KeyA")||s.has("ArrowLeft"))&&(e-=w),(s.has("KeyD")||s.has("ArrowRight"))&&(e+=w),(s.has("Space")||s.has("PageUp"))&&(t+=w),(s.has("ShiftLeft")||s.has("ShiftRight")||s.has("PageDown"))&&(t-=w);const M=e!==0||t!==0||i!==0,S=o!==0||Q!==0;if(S){A._yaw+=Q,A._pitch-=o;const G=Math.PI/2-.01;A._pitch=Math.max(-G,Math.min(G,A._pitch))}if(M){const G=Math.cos(A._yaw),m=Math.sin(A._yaw),K=Math.cos(A._pitch),k=Math.sin(A._pitch);A.position.x+=m*K*i+G*e,A.position.y+=k*i+t,A.position.z+=G*K*i-m*e}if(M||S){const G=Math.cos(A._yaw),m=Math.sin(A._yaw),K=Math.cos(A._pitch);A.target.set(A.position.x+m*K,A.position.y+Math.sin(A._pitch),A.position.z+G*K)}const R=A.inertia,N=A.speed*.001,F=A.speed*.001;e*=R,t*=R,i*=R,o*=R,Q*=R,Math.abs(e)<N&&(e=0),Math.abs(t)<N&&(t=0),Math.abs(i)<N&&(i=0),Math.abs(o)<F&&(o=0),Math.abs(Q)<F&&(Q=0)}return I&&I._beforeRender.push(u),g.addEventListener("pointerdown",c),g.addEventListener("pointermove",l),g.addEventListener("pointerup",D),g.addEventListener("contextmenu",p),g.addEventListener("keydown",y),g.addEventListener("keyup",_),g.hasAttribute("tabindex")||(g.tabIndex=0),()=>{if(I){const f=I._beforeRender.indexOf(u);f>=0&&I._beforeRender.splice(f,1)}g.removeEventListener("pointerdown",c),g.removeEventListener("pointermove",l),g.removeEventListener("pointerup",D),g.removeEventListener("contextmenu",p),g.removeEventListener("keydown",y),g.removeEventListener("keyup",_)}}function mEA(A,g,I,e,t,i,o){const Q=o-i;A[0]=2/(I-g),A[1]=0,A[2]=0,A[3]=0,A[4]=0,A[5]=2/(t-e),A[6]=0,A[7]=0,A[8]=0,A[9]=0,A[10]=-1/Q,A[11]=0,A[12]=(g+I)/(g-I),A[13]=(t+e)/(e-t),A[14]=o/Q,A[15]=1}const bEA=["left","right","bottom","top"];function KF(A){A._projRev=(A._projRev??0)+1}function KEA(A,g){let I=g.halfHeight??1;const e={left:g.left??null,right:g.right??null,bottom:g.bottom??null,top:g.top??null},t={};Object.defineProperty(t,"halfHeight",{get(){return I},set(i){I!==i&&(I=i,KF(A))},enumerable:!0,configurable:!0});for(const i of bEA)Object.defineProperty(t,i,{get(){return e[i]},set(o){e[i]!==o&&(e[i]=o,KF(A))},enumerable:!0,configurable:!0});return t}function kEA(A,g,I){const e=A.ortho,t=e.halfHeight,i=t*g;mEA(I,e.left??-i,e.right??i,e.bottom??-t,e.top??t,A.nearPlane,A.farPlane)}function DH(A,g){GiA(kEA);const I=KEA(A,g??{});return A.ortho=I,KF(A),I}function pH(A){A.ortho=null;const g=A._projCache;g[12]=0,g[13]=0,g[15]=0,KF(A)}const UEA=Object.freeze(Object.defineProperty({__proto__:null,disableOrthographicCamera:pH,enableOrthographicCamera:DH},Symbol.toStringTag,{value:"Module"})),UC=.001;function yH(A){return{planetRadius:A,radiusMin:10,radiusMax:A*4,pitchMin:UC,pitchMax:Math.PI/2-.01,pitchDisabledRadiusScale:{x:2,y:4},yawMin:-1/0,yawMax:1/0}}function _H(A,g){const I=A.pitchDisabledRadiusScale;if(!I)return A.pitchMax;const e=I.x*A.planetRadius,t=I.y*A.planetRadius;if(g<=e)return A.pitchMax;if(g>=t)return A.pitchMin;const i=(g-e)/(t-e),o=i<0?0:i>1?1:i;return A.pitchMax*(1-o)+A.pitchMin*o}function uH(A,g,I,e){if(g>0){const i=(e??I)-A.radiusMin;return Math.min(g,Math.max(0,i))}const t=A.radiusMax-I;return Math.max(g,-Math.max(0,t))}const hH=Math.PI*2,LEA={x:0,y:0,z:1},YEA={x:1,y:0,z:0},V3=.998749218;function $Q(A){return A-hH*Math.floor((A+Math.PI)/hH)}function AN(A,g,I){return A<g?g:A>I?I:A}function Ar(A,g,I,e){const t=Math.hypot(A.x,A.y,A.z)||1;e.x=A.x/t,e.y=A.y/t,e.z=A.z/t,gr(e,LEA,g),MH(g)<UC&&gr(e,YEA,g),gN(g),gr(g,e,I),gN(I)}function fH(A,g,I,e){const t={x:0,y:0,z:0},i={x:0,y:0,z:0},o={x:0,y:0,z:0};Ar(I,t,i,o);const Q=Math.sin(g),r=Math.cos(g),E=Math.cos(A),n=Math.sin(A),s=i.x*E+t.x*n,c=i.y*E+t.y*n,l=i.z*E+t.z*n;return e.x=s*Q-o.x*r,e.y=c*Q-o.y*r,e.z=l*Q-o.z*r,gN(e)}function dH(A,g,I,e){const t={x:0,y:0,z:0},i={x:0,y:0,z:0},o={x:0,y:0,z:0};Ar(g,t,i,o);const r=-(A.x*o.x+A.y*o.y+A.z*o.z),E=Math.acos(AN(r,-1,1)),n=A.x+o.x*r,s=A.y+o.y*r,c=A.z+o.z*r,l=Math.sin(E);if(Math.abs(l)<UC)return e.x=I,e.y=E,e;const D=1/l,p=n*D,y=s*D,_=c*D,u=p*i.x+y*i.y+_*i.z,f=p*t.x+y*t.y+_*t.z;return e.x=Math.atan2(f,u),e.y=E,e}function wH(A){const g=Math.hypot(A.x,A.y,A.z);if(g>UC){const I=A.z/g;if(Math.abs(I)>V3){const e=AN(I,-V3,V3),t=Math.sqrt(1-e*e),i=Math.atan2(A.y,A.x);A.x=g*Math.cos(i)*t,A.y=g*Math.sin(i)*t,A.z=g*e}}return A}function JEA(A,g){A._setOrientation(g.yaw??A.yaw,g.pitch??A.pitch,g.radius??A.radius,g.center??A.center)}function vEA(A){const g=yH(A.planetRadius),I={x:A.planetRadius,y:0,z:0},e={x:0,y:0,z:0},t={x:0,y:1,z:0},i={x:0,y:0,z:0},o={yaw:0,pitch:0,radius:0},Q=se();function r(){const l={x:e.x+i.x,y:e.y+i.y,z:e.z+i.z};return S3(Q,e,l,t),Q}const E=so(r);function n(l,D,p,y){o.yaw=$Q(l),o.pitch=$Q(D),o.radius=p,I.x=y.x,I.y=y.y,I.z=y.z,o.yaw=AN(o.yaw,g.yawMin,g.yawMax),o.pitch=AN(o.pitch,g.pitchMin,_H(g,o.radius)),o.radius=AN(o.radius,g.radiusMin,g.radiusMax),wH(I);const _={x:0,y:0,z:0},u={x:0,y:0,z:0},f={x:0,y:0,z:0};Ar(I,_,u,f),fH(o.yaw,o.pitch,I,i);const h={x:0,y:0,z:0};if(gr(f,i,h),MH(h)<UC){const w=Math.cos(o.yaw),M=Math.sin(o.yaw),S={x:u.x*w+_.x*M,y:u.y*w+_.y*M,z:u.z*w+_.z*M};gr(S,i,h)}gN(h),gr(i,h,t),gN(t),e.x=I.x-i.x*o.radius,e.y=I.y-i.y*o.radius,e.z=I.z-i.z*o.radius,E.markLocalDirty()}const s={fov:.8,nearPlane:1,farPlane:A.planetRadius*16,children:[],limits:g,position:e,upVector:t,_lookAt:i,_setOrientation:n,_viewCache:se(),_projCache:se(),_vpCache:se(),get parent(){return E.parent},set parent(l){E.parent=l},get worldMatrix(){return E.getWorldMatrix()},get worldMatrixVersion(){return E.getWorldMatrixVersion()},get center(){return I},set center(l){n(o.yaw,o.pitch,o.radius,l)},get yaw(){return o.yaw},set yaw(l){l!==o.yaw&&n(l,o.pitch,o.radius,I)},get pitch(){return o.pitch},set pitch(l){l!==o.pitch&&n(o.yaw,l,o.radius,I)},get radius(){return o.radius},set radius(l){l!==o.radius&&n(o.yaw,o.pitch,l,I)}};tQ(s,E);const c=g.radiusMax!==1/0?g.radiusMax:A.planetRadius*4;return n(0,0,c,I),s}function gr(A,g,I){const e=A.y*g.z-A.z*g.y,t=A.z*g.x-A.x*g.z,i=A.x*g.y-A.y*g.x;I.x=e,I.y=t,I.z=i}function MH(A){return A.x*A.x+A.y*A.y+A.z*A.z}function gN(A){const g=Math.hypot(A.x,A.y,A.z);if(g>1e-10){const I=1/g;A.x*=I,A.y*=I,A.z*=I}return A}function HEA(A){if(A>=.5){const I=2*(1-A);return(1-I*I*I)*.5+.5}const g=2*A;return g*g*g*.5}function TEA(A,g,I,e){const t=Math.hypot(A.x,A.y,A.z)||1,i=Math.hypot(g.x,g.y,g.z)||1,o=A.x/t,Q=A.y/t,r=A.z/t,E=g.x/i,n=g.y/i,s=g.z/i;let c=o*E+Q*n+r*s;c=c<-1?-1:c>1?1:c;const l=Math.acos(c)*I;let D=E-o*c,p=n-Q*c,y=s-r*c;const _=Math.hypot(D,p,y);_>1e-9&&(D/=_,p/=_,y/=_);const u=Math.cos(l),f=Math.sin(l),h=t+(i-t)*I;e.x=(o*u+D*f)*h,e.y=(Q*u+p*f)*h,e.z=(r*u+y*f)*h}function SH(A,g,I){A._cancelFly?.();const e=Math.max(1,I.durationMs??1e3),t=I.centerHopScale??0,i=I.ease??HEA,o=A.yaw,Q=A.pitch,r=A.radius,E={x:A.center.x,y:A.center.y,z:A.center.z},n=I.yaw!==void 0?o+$Q($Q(I.yaw)-o):o,s=I.pitch!==void 0?$Q(I.pitch):Q,c=I.radius??r,l=I.center!==void 0,D=l?{x:I.center.x,y:I.center.y,z:I.center.z}:E,p=Math.hypot(D.x-E.x,D.y-E.y,D.z-E.z),y={x:0,y:0,z:0};let _=0;return new Promise(u=>{const f=w=>{_+=w>0?w:16.666666666666668;const M=Math.min(1,_/e),S=M>=1?1:i(M),R=o+(n-o)*S,N=Q+(s-Q)*S,F=r+(c-r)*S;let G=E;if(l){if(TEA(E,D,S,y),t>0){const K=t*p*Math.max(0,(S*S-S)/-.25),k=Math.hypot(y.x,y.y,y.z)||1,L=1+K/k;y.x*=L,y.y*=L,y.z*=L}G=y}A._setOrientation(R,N,F,G),M>=1&&h()};function h(){const w=g._beforeRender.indexOf(f);w>=0&&g._beforeRender.splice(w,1),A._cancelFly===h&&(A._cancelFly=void 0),u()}A._cancelFly=h,g._beforeRender.push(f)})}function W3(A,g,I,e,t){const i=lt(I);if(!i)return null;const o=2*A/e-1,Q=1-2*g/t,r=RH(i,o,Q,1),E=RH(i,o,Q,0),n=E[0]-r[0],s=E[1]-r[1],c=E[2]-r[2],l=Math.sqrt(n*n+s*s+c*c);if(l<1e-10)return null;const D=1/l;return{origin:r,direction:[n*D,s*D,c*D],length:l}}function RH(A,g,I,e){const t=A[0]*g+A[4]*I+A[8]*e+A[12],i=A[1]*g+A[5]*I+A[9]*e+A[13],o=A[2]*g+A[6]*I+A[10]*e+A[14],r=1/(A[3]*g+A[7]*I+A[11]*e+A[15]);return[t*r,i*r,o*r]}const NH=60,xEA=1e3/NH;function qEA(A,g,I=xEA){return Math.pow(A,g/I)}function PEA(A,g,I,e,t){if(e===0)return A;const i=qEA(I,e);let o=A*i;if(g!==0||t){const Q=1-I,r=Q>0?(1-i)/Q:1;o+=g/e*r}else Math.abs(o)<1e-6&&(o=0);return o}function OEA(A){return A<0?0:A>1?1:A}function jEA(A,g){const I=Math.hypot(A.x,A.y,A.z),e=Math.hypot(g.x,g.y,g.z),t=I>0?A.z/I:0,i=Math.sqrt(1-Math.min(1,t*t)),o=Math.sqrt(Math.abs(i)),Q=Math.max(e-I,UC),r=Math.max(1,I/Q);return OEA(r*o)}function VEA(A){return A*.01}function WEA(A,g,I,e){const t=e?.zoomToCursor??!0,i=e?.checkCollisions??!1,o=e?.doubleTapAnimationDurationMs??1e3,Q=e?.doubleTapEasingFunction??null,r=1,E=1,n=Math.PI/500,s=Math.PI/500,c=2,l=0,D=0,p=.9,y={x:0,y:0,z:0},_={x:0,y:0};let u=0,f=!1;const h={x:0,y:0,z:0},w={x:0,y:0};let M=0,S=0,R=1,N=1;const F={x:0,y:0,z:0},G={x:0,y:0};let m=0,K=null,k;const L={x:0,y:0,z:0},H={x:0,y:0,z:0},q={x:0,y:0,z:0},CA={x:0,y:0,z:0};let eA=0,Z=0,O="none",P=0,gA=0;const yA=new Set,cA=new Map;let RA=0,YA=0,Ag=0,lg=!1;const mA=20,HA=.05;function Qg(){const vA=g.getBoundingClientRect();return{width:vA.width||g.width,height:vA.height||g.height}}function Eg(vA){const ng=g.getBoundingClientRect();eA=vA.clientX-ng.left,Z=vA.clientY-ng.top}function kA(vA,ng){const{width:qA,height:Tg}=Qg(),jI=x1(A,qA/Tg),MI=W3(vA,ng,jI,qA,Tg);return MI?{origin:{x:MI.origin[0],y:MI.origin[1],z:MI.origin[2]},direction:{x:MI.direction[0],y:MI.direction[1],z:MI.direction[2]}}:null}function ug(vA,ng){const qA=A.limits.planetRadius,Tg=2*(vA.x*ng.x+vA.y*ng.y+vA.z*ng.z),jI=vA.x*vA.x+vA.y*vA.y+vA.z*vA.z-qA*qA,MI=Tg*Tg-4*jI;if(MI<0)return null;const VI=Math.sqrt(MI);let ie=(-Tg-VI)/2;return ie<0&&(ie=(-Tg+VI)/2),ie<0?null:{x:vA.x+ng.x*ie,y:vA.y+ng.y*ie,z:vA.z+ng.z*ie}}function fg(vA,ng){const qA=kA(vA,ng);if(!qA)return{hit:!1,point:null,ray:null};const Tg=ug(qA.origin,qA.direction);return{hit:!!Tg,point:Tg,ray:qA}}function rg(vA){return ug(A.position,vA)}function ag(vA,ng,qA){const Tg=Math.max(1e-5,Math.hypot(A.position.x,A.position.y,A.position.z)),jI=vA/Tg;H.x=A.position.x*jI,H.y=A.position.y*jI,H.z=A.position.z*jI;const MI={x:0,y:0,z:0},VI={x:0,y:0,z:0};Ar(H,MI,VI,L),qA[0]=MI.x,qA[1]=MI.y,qA[2]=MI.z,qA[3]=0,qA[4]=VI.x,qA[5]=VI.y,qA[6]=VI.z,qA[7]=0,qA[8]=L.x,qA[9]=L.y,qA[10]=L.z,qA[11]=0,qA[12]=H.x,qA[13]=H.y,qA[14]=H.z,qA[15]=1;const ie=lt(qA);if(!ie)return;const Zg=-(L.x*H.x+L.y*H.y+L.z*H.z),WI=L.x*ng.direction.x+L.y*ng.direction.y+L.z*ng.direction.z;if(Math.abs(WI)>1e-9){const De=-(L.x*ng.origin.x+L.y*ng.origin.y+L.z*ng.origin.z+Zg)/WI;if(De>=0){const pe=ng.origin.x+ng.direction.x*De,oe=ng.origin.y+ng.direction.y*De,Xe=ng.origin.z+ng.direction.z*De;zEA(pe,oe,Xe,ie,q)}}}function Rg(vA,ng){const qA=fg(vA,ng);if(qA.point&&qA.ray){k=Math.hypot(qA.point.x,qA.point.y,qA.point.z);const Tg=vg;ag(k,qA.ray,Tg),CA.x=q.x,CA.y=q.y,CA.z=q.z}else k=void 0}function UA(vA,ng){if(k===void 0)return;const qA=kA(vA,ng);if(!qA)return;const Tg=vg;ag(k,qA,Tg);let jI=q.x-CA.x,MI=q.y-CA.y,VI=q.z-CA.z;const ie=k*.1,Zg=Math.hypot(jI,MI,VI);if(Zg>ie){const oe=ie/Zg;jI*=oe,MI*=oe,VI*=oe}CA.x=q.x,CA.y=q.y,CA.z=q.z;const WI=jI*Tg[0]+MI*Tg[4]+VI*Tg[8],De=jI*Tg[1]+MI*Tg[5]+VI*Tg[9],pe=jI*Tg[2]+MI*Tg[6]+VI*Tg[10];H.x+=WI,H.y+=De,H.z+=pe,y.x-=WI,y.y-=De,y.z-=pe}function $A(){k=void 0}const vg=new Float32Array(16);function Jg(vA,ng){if(vA===0)return;u+=vA;const qA=fg(eA,Z);qA.hit&&qA.point&&t?K=qA.point:K=rg(A._lookAt)}function nI(){const vA=A.center.x+F.x,ng=A.center.y+F.y,qA=A.center.z+F.z,Tg=Math.hypot(vA,ng,qA)||1,MI=Math.hypot(A.center.x,A.center.y,A.center.z)/Tg;A._setOrientation(A.yaw,A.pitch,A.radius,{x:vA*MI,y:ng*MI,z:qA*MI})}function qI(){if(G.x===0&&G.y===0)return;const vA=G.x!==0?kF(A.pitch+G.x,0,.5*Math.PI-UC):A.pitch,ng=G.y!==0?A.yaw+G.y:A.yaw;A._setOrientation(ng,vA,A.radius,A.center)}function kI(vA,ng,qA){const Tg=A.limits,jI=vA.x-A.position.x,MI=vA.y-A.position.y,VI=vA.z-A.position.z,ie=Math.hypot(jI,MI,VI);if(ie<Tg.radiusMin)return qA.x=A.center.x,qA.y=A.center.y,qA.z=A.center.z,kF(A.radius-ng,Tg.radiusMin,Tg.radiusMax);const Zg=ng/ie,WI=A.position.x+jI*Zg,De=A.position.y+MI*Zg,pe=A.position.z+VI*Zg,oe=jI*Zg*A._lookAt.x+MI*Zg*A._lookAt.y+VI*Zg*A._lookAt.z,Xe=kF(A.radius-oe,Tg.radiusMin,Tg.radiusMax);return qA.x=WI+A._lookAt.x*Xe,qA.y=De+A._lookAt.y*Xe,qA.z=pe+A._lookAt.z*Xe,Xe}const pI={x:0,y:0,z:0};function Ye(){const vA=A.limits,ng=K?UF(A.position,K):void 0,qA=uH(vA,m,A.radius,ng);if(!(Math.abs(qA)<UC))if(K){const Tg=kI(K,qA,pI);A._setOrientation(A.yaw,A.pitch,Tg,pI)}else{const Tg=kF(A.radius-qA,vA.radiusMin,vA.radiusMax);A._setOrientation(A.yaw,A.pitch,Tg,A.center)}}let vI=!1;function Je(vA){const ng=vI&&!vA;if(vI=vA,!ng)return;const qA=rg(A._lookAt);if(!qA)return;const Tg=1/(Math.hypot(qA.x,qA.y,qA.z)||1);if(A._lookAt.x*-qA.x*Tg+A._lookAt.y*-qA.y*Tg+A._lookAt.z*-qA.z*Tg<=0)return;const MI=UF(A.position,qA);if(MI<=UC)return;const VI={x:0,y:0};dH(A._lookAt,qA,A.yaw,VI),A._setOrientation(VI.x,VI.y,MI,qA)}function Wg(){if(!i)return;const vA=A.limits.planetRadius+A.limits.radiusMin,ng=Math.hypot(A.position.x,A.position.y,A.position.z);if(ng>=vA||ng<1e-6)return;const qA=vA-ng,Tg=1/ng,jI=A.position.x*Tg*qA,MI=A.position.y*Tg*qA,VI=A.position.z*Tg*qA;A._setOrientation(A.yaw,A.pitch,A.radius,{x:A.center.x+jI,y:A.center.y+MI,z:A.center.z+VI})}function PI(vA){return vA>0?vA:S>0?S:1e3/NH}function jA(vA,ng,qA,Tg){return PEA(vA,ng,qA,PI(Tg),f)}function kg(){return k!==void 0}function tI(vA){const ng=A.center;if(y.x!==0||y.y!==0||y.z!==0?R=jEA(ng,A.position):R=1,kg()||_.x!==0||_.y!==0)N=0,M=0;else{const jI=K?UF(A.position,K):UF(A.position,ng);N=VEA(jI)}const qA=PI(vA);h.x=jA(h.x,y.x,l,vA),h.y=jA(h.y,y.y,l,vA),h.z=jA(h.z,y.z,l,vA);const Tg=r*E*R*qA;F.x=h.x*Tg,F.y=h.y*Tg,F.z=h.z*Tg,w.x=jA(w.x,_.x,D,vA),w.y=jA(w.y,_.y,D,vA),G.x=w.x*r*n*qA,G.y=w.y*r*s*qA,M=jA(M,u,p,vA),m=M*(r*c*N)*qA,vA>0&&(S=vA),u=0,y.x=y.y=y.z=0,_.x=_.y=0,f=!1}function UI(vA){Ke(),(y.x!==0||y.y!==0||y.z!==0||_.x!==0||_.y!==0||u!==0)&&A._cancelFly&&A._cancelFly(),tI(vA);let qA=!1;(F.x!==0||F.y!==0||F.z!==0)&&(nI(),qA=!0),(G.x!==0||G.y!==0)&&qI(),Math.abs(m)>UC&&(Ye(),qA=!0),Je(qA),Wg()}function Ke(){if(yA.size===0)return;f=!0;const vA=6,ng=4,qA=A.radius*.0015,Tg=yA.has("ControlLeft")||yA.has("ControlRight");if((yA.has("Equal")||yA.has("NumpadAdd"))&&(u+=ng,K=null),(yA.has("Minus")||yA.has("NumpadSubtract"))&&(u-=ng,K=null),Tg){yA.has("ArrowLeft")&&(_.y-=vA),yA.has("ArrowRight")&&(_.y+=vA),yA.has("ArrowUp")&&(_.x+=vA),yA.has("ArrowDown")&&(_.x-=vA);return}const jI={x:0,y:0,z:0},MI={x:0,y:0,z:0},VI={x:0,y:0,z:0};let ie=0,Zg=0;if(yA.has("ArrowUp")&&(ie+=1),yA.has("ArrowDown")&&(ie-=1),yA.has("ArrowRight")&&(Zg+=1),yA.has("ArrowLeft")&&(Zg-=1),ie!==0||Zg!==0){const WI=1/Math.hypot(ie,Zg);ie*=WI,Zg*=WI,Ar(A.center,jI,MI,VI),y.x+=(MI.x*ie+jI.x*Zg)*qA,y.y+=(MI.y*ie+jI.y*Zg)*qA,y.z+=(MI.z*ie+jI.z*Zg)*qA}}function Ge(vA){g.setPointerCapture(vA.pointerId),Eg(vA),P=vA.clientX,gA=vA.clientY,vA.button===0?(O="pan",Rg(eA,Z)):O="rotate"}function Ze(vA){Eg(vA);const ng=vA.clientX-P,qA=vA.clientY-gA;P=vA.clientX,gA=vA.clientY,!(cA.size>=2)&&O!=="none"&&(f=!0,O==="pan"?UA(eA,Z):O==="rotate"&&(_.y+=ng,_.x+=qA))}function st(vA){g.releasePointerCapture(vA.pointerId),O==="pan"&&$A(),O="none"}function Q1(vA){vA.preventDefault(),Eg(vA),Jg(-Math.sign(vA.deltaY))}function r1(vA){vA.preventDefault()}function _t(vA){if(vA.button!==0||vA.buttons!==0)return;vA.preventDefault();const ng=g.getBoundingClientRect(),qA=fg(vA.clientX-ng.left,vA.clientY-ng.top);qA.hit&&qA.point&&SH(A,I,{center:{x:qA.point.x,y:qA.point.y,z:qA.point.z},durationMs:o,ease:Q??void 0})}function k1(vA){yA.add(vA.code)}function at(vA){yA.delete(vA.code)}function ut(){const vA=cA.values(),ng=vA.next().value,qA=vA.next().value;return[ng,qA]}function z1(vA){for(let ng=0;ng<vA.changedTouches.length;ng++){const qA=vA.changedTouches[ng];cA.set(qA.identifier,{x:qA.clientX,y:qA.clientY})}if(cA.size>=2){vA.preventDefault(),O==="pan"&&$A(),O="none";const[ng,qA]=ut();RA=Math.hypot(qA.x-ng.x,qA.y-ng.y),YA=(ng.x+qA.x)/2,Ag=(ng.y+qA.y)/2,lg=!1}}function E1(vA){for(let Zg=0;Zg<vA.changedTouches.length;Zg++){const WI=vA.changedTouches[Zg];cA.has(WI.identifier)&&cA.set(WI.identifier,{x:WI.clientX,y:WI.clientY})}if(cA.size<2)return;vA.preventDefault(),f=!0;const[ng,qA]=ut(),Tg=Math.hypot(qA.x-ng.x,qA.y-ng.y),jI=(ng.x+qA.x)/2,MI=(ng.y+qA.y)/2,VI=g.getBoundingClientRect();eA=jI-VI.left,Z=MI-VI.top;const ie=Math.hypot(jI-YA,MI-Ag);if(!lg&&ie>mA&&(lg=!0,Rg(eA,Z)),lg)UA(eA,Z);else if(RA>0){const Zg=Tg-RA;if(Zg!==0){u+=Zg*HA;const WI=fg(eA,Z);K=WI.hit&&WI.point&&t?WI.point:rg(A._lookAt)}}RA=Tg}function mt(vA){for(let ng=0;ng<vA.changedTouches.length;ng++)cA.delete(vA.changedTouches[ng].identifier);if(cA.size<2&&(lg&&($A(),lg=!1),RA=0),cA.size===1){const ng=cA.values().next().value;P=ng.x,gA=ng.y}}function f1(vA){vA.preventDefault()}I._beforeRender.push(UI);const Z1=[[g,"pointerdown",Ge],[g,"pointermove",Ze],[g,"pointerup",st],[g,"wheel",Q1,{passive:!1}],[g,"contextmenu",r1],[g,"dblclick",_t],[g,"touchstart",z1,{passive:!1}],[g,"touchmove",E1,{passive:!1}],[g,"touchend",mt],[g,"gesturestart",f1,{passive:!1}],[g,"gesturechange",f1,{passive:!1}],[g,"gestureend",f1,{passive:!1}],[window,"keydown",k1],[window,"keyup",at]];for(const[vA,ng,qA,Tg]of Z1)vA.addEventListener(ng,qA,Tg);return()=>{const vA=I._beforeRender.indexOf(UI);vA>=0&&I._beforeRender.splice(vA,1);for(const[ng,qA,Tg]of Z1)ng.removeEventListener(qA,Tg)}}function kF(A,g,I){return A<g?g:A>I?I:A}function UF(A,g){return Math.hypot(A.x-g.x,A.y-g.y,A.z-g.z)}function zEA(A,g,I,e,t){const i=A*e[0]+g*e[4]+I*e[8]+e[12],o=A*e[1]+g*e[5]+I*e[9]+e[13],Q=A*e[2]+g*e[6]+I*e[10]+e[14],r=A*e[3]+g*e[7]+I*e[11]+e[15],E=r!==0?1/r:1;t.x=i*E,t.y=o*E,t.z=Q*E}function z3(A,g){A[0]=g[0],A[1]=g[1],A[2]=-g[2],A[3]=g[3],A[4]=g[4],A[5]=g[5],A[6]=-g[6],A[7]=g[7],A[8]=-g[8],A[9]=-g[9],A[10]=g[10],A[11]=-g[11],A[12]=g[12],A[13]=g[13],A[14]=-g[14],A[15]=g[15]}function ZEA(A,g){for(let I=0;I<16;I++)A[I]=g[I];A[8]=-A[8],A[9]=-A[9],A[10]=-A[10],A[11]=-A[11]}function XEA(A,g){const I=g.position,e=g.orientation;A.position.set(I.x,I.y,-I.z),A.rotationQuaternion.set(e.x,e.y,-e.z,-e.w)}function GH(A){const g=se();return g[0]=g[5]=g[10]=g[15]=1,{eye:A,fov:1,nearPlane:.1,farPlane:1e3,viewport:void 0,children:[],_viewCache:se(),_projCache:se(),_vpCache:se(),_world:g,_wmv:1,get worldMatrix(){return this._world},get worldMatrixVersion(){return this._wmv}}}function FH(A,g,I,e,t){const i=g.transform.matrix,o=A._world;z3(o,i),A._wmv=A._wmv+1,A.viewport=t;const Q=I/e*(t.width/t.height),r=A._projCache,E=g.projectionMatrix;ZEA(r,E),r[2]=r[3]-r[2],r[6]=r[7]-r[6],r[10]=r[11]-r[10],r[14]=r[15]-r[14],A._projVer=T1(A),A._projAspect=Q,A._viewVer=-1,A._vpVer=-1}function $EA(A){return{source:A,handedness:A.handedness,targetRayMode:A.targetRayMode,targetRayMatrix:new Float32Array(16),targetRayTracked:!1,gripMatrix:new Float32Array(16),gripTracked:!1,selecting:!1,squeezing:!1,gamepad:A.gamepad??null}}function mH(A,g){const I=[],e=new Map,t={get inputSources(){return t._list},_list:I,_bySource:e,_session:A,_cbs:g,_handlers:[]},i=E=>{const n=[];for(let s=0;s<E.length;s++){const c=E[s];if(e.has(c))continue;const l=$EA(c);e.set(c,l),I.push(l),n.push(l)}return n},o=E=>{const n=[];for(let s=0;s<E.length;s++){const c=E[s],l=e.get(c);if(!l)continue;e.delete(c);const D=I.indexOf(l);D>=0&&I.splice(D,1),n.push(l)}return n},Q=(E,n)=>{A.addEventListener(E,n),t._handlers.push({type:E,fn:n})};Q("inputsourceschange",(E=>{const n=i(E.added),s=o(E.removed);g.onInputSourcesChange?.(n,s)}));const r=(E,n,s)=>{Q(E,(c=>{const l=e.get(c.inputSource);l&&(E.endsWith("start")?l[n]=!0:E.endsWith("end")&&(l[n]=!1),s?.(l))}))};return r("selectstart","selecting",g.onSelectStart),r("select","selecting",g.onSelect),r("selectend","selecting",g.onSelectEnd),r("squeezestart","squeezing",g.onSqueezeStart),r("squeeze","squeezing",g.onSqueeze),r("squeezeend","squeezing",g.onSqueezeEnd),i(A.inputSources),t}function bH(A,g,I){for(const e of A._list){const t=g.getPose(e.source.targetRaySpace,I);t?(z3(e.targetRayMatrix,t.transform.matrix),e.targetRayTracked=!0):e.targetRayTracked=!1;const i=e.source.gripSpace;if(i){const o=g.getPose(i,I);o?(z3(e.gripMatrix,o.transform.matrix),e.gripTracked=!0):e.gripTracked=!1}else e.gripTracked=!1}}function KH(A){for(const{type:g,fn:I}of A._handlers)A._session.removeEventListener(g,I);A._handlers.length=0,A._list.length=0,A._bySource.clear()}function Z3(){return typeof navigator<"u"&&"xr"in navigator&&!!navigator.xr}function X3(){return typeof XRGPUBinding<"u"}async function AnA(A){if(!Z3()||!X3())return!1;try{return await navigator.xr.isSessionSupported(A)===!0}catch{return!1}}async function gnA(A,g={}){Z3()||U(606),X3()||U(607);const I=g.mode??"immersive-vr",e=A.surface.engine,t=e._device,i=g.referenceSpaceType??"local-floor",o=["webgpu",...g.requiredFeatures??[]],Q=[...g.optionalFeatures??[]];i!=="viewer"&&i!=="local"&&!o.includes(i)&&!Q.includes(i)&&Q.push(i);for(const n of g.features??[])for(const s of n.sessionFeatures??[])!o.includes(s)&&!Q.includes(s)&&Q.push(s);const r=await navigator.xr.requestSession(I,{requiredFeatures:o,optionalFeatures:Q});let E=null;try{let n;try{n=new XRGPUBinding(r,t)}catch(_){const u=_ instanceof Error?_.message:String(_);throw new Error(`Failed to construct XRGPUBinding: ${u}. Call enableXrCompatibleAdapter() before createEngine so its GPU adapter is XR-compatible.`,{cause:_})}const s=g.colorFormat??n.getPreferredColorFormat(),c=g.depthStencilFormat===void 0?"depth24plus":g.depthStencilFormat,l=n.createProjectionLayer({colorFormat:s,depthStencilFormat:c??void 0});await r.updateRenderState({layers:[l],depthNear:g.depthNear??.02,...g.depthFar!==void 0?{depthFar:g.depthFar}:{}});let D;try{D=await r.requestReferenceSpace(i)}catch(_){if(i==="local")throw _;D=await r.requestReferenceSpace("local")}const p=g.input===!1?null:mH(r,g.input??{}),y={mode:I,session:r,binding:n,layer:l,get referenceSpace(){return y._referenceSpace},scene:A,engine:e,colorFormat:s,depthFormat:c,get cameras(){return y._units.map(_=>_.camera)},input:p,_features:[],_referenceSpace:D,_units:[],_options:g,_rafId:0,_lastTime:0,_ended:!1,_canvasStopped:!1,_recovery:null};if(E=y,I==="immersive-ar"){const _=A.clearColor;y._savedClear={r:_.r,g:_.g,b:_.b,a:_.a},_.a=0}for(const _ of g.features??[])y._features.push(_.create(y));return r.addEventListener("end",()=>$3(y),{once:!0}),tnA(y),eF(e),y._canvasStopped=!0,y._rafId=r.requestAnimationFrame((_,u)=>UH(y,_,u)),y}catch(n){const s=E?._canvasStopped??!1;E&&$3(E,!1,!1);let c=n;try{await r.end()}catch(l){c=new AggregateError([n,l],"WebXR initialization failed and the session could not be ended.",{cause:l})}throw s&&JR(e).catch(l=>LF("canvas restart after initialization failure",l)),c}}async function InA(A){A._ended||await A.session.end()}function enA(A,g,I){const e=A._units[g];if(e)return e;const t=A.layer,i=wt({lbl:`xr-eye-${g}`,format:A.colorFormat,dFormat:A.depthFormat??void 0,samples:1,size:{width:t.textureWidth,height:t.textureHeight}});i._eager=!0;const o=GH(I),Q=Eo({name:`xr-eye-${g}`,rt:i,clr:!0,cam:o},A.engine,A.scene),r={rt:i,camera:o,task:Q,recorded:!1};return A._units[g]=r,r}function kH(A,g,I){const e=I.baseArrayLayer??0,t=I.baseMipLevel??0,i=A.some(o=>o.texture===g&&o.arrayLayer===e&&o.mipLevel===t);return A.push({texture:g,arrayLayer:e,mipLevel:t}),i}function UH(A,g,I){if(A._ended)return;A._rafId=A.session.requestAnimationFrame((D,p)=>UH(A,D,p));const e=I.getViewerPose(A.referenceSpace);A.input&&bH(A.input,I,A.referenceSpace),A._options.onFrame?.(A,I,g);for(const D of A._features)D.update?.(I,g);if(!e)return;const t=A.engine,i=A._lastTime?g-A._lastTime:0;A._lastTime=g;const o=t._device.createCommandEncoder({label:"xr-frame"}),Q=t._currentEncoder,r=t._currentDelta;t._currentEncoder=o,t._currentDelta=A.scene.fixedDeltaMs>0?A.scene.fixedDeltaMs:i,A.scene._update();const E=e.views,n=A.layer.textureWidth,s=A.layer.textureHeight,c=[],l=[];for(let D=0;D<E.length;D++){const p=E[D],y=A.binding.getViewSubImage(A.layer,p),_=enA(A,D,p.eye),u=y.getViewDescriptor(),f=y.colorTexture.createView(u),h=y.depthStencilTexture,w=h?h.createView(u):null,M=_.rt;M._colorTexture=y.colorTexture,M._colorView=f,M._depthTexture=h,M._depthView=w,M._width=n,M._height=s,_.recorded||(_.task.record(),_.recorded=!0),_.task._colorAttachment.view=f,_.task._config.clr=!kH(c,y.colorTexture,u);const S=_.task._renderPassDescriptor.depthStencilAttachment;if(S&&w&&h){S.view=w;const F=kH(l,h,u);S.depthLoadOp=F?"load":"clear",S.stencilLoadOp!==void 0&&(S.stencilLoadOp=F?"load":"clear")}const R=y.viewport,N={x:R.x/n,y:R.y/s,width:R.width/n,height:R.height/s};FH(_.camera,p,n,s,N),_.task.execute?.()}t._device.queue.submit([o.finish()]),gF(t),t._currentEncoder=Q,t._currentDelta=r}function LF(A,g){console.error(`Babylon Lite WebXR ${A} failed:`,g)}function $3(A,g=!0,I=!0){if(A._ended)return;A._ended=!0;const e=(i,o)=>{try{o()}catch(Q){LF(i,Q)}};e("frame cancellation",()=>{A._rafId&&(A.session.cancelAnimationFrame(A._rafId),A._rafId=0)}),e("recovery detachment",()=>{A._recovery?.disable(),A._recovery=null});for(let i=A._features.length-1;i>=0;i--)e("feature disposal",()=>A._features[i].dispose?.());A._features.length=0,A.input&&e("input disposal",()=>KH(A.input));for(const i of A._units)e("render-task disposal",()=>i.task.dispose());if(A._units.length=0,A._savedClear){const i=A.scene.clearColor;i.r=A._savedClear.r,i.g=A._savedClear.g,i.b=A._savedClear.b,i.a=A._savedClear.a,A._savedClear=void 0}I&&e("onEnd callback",()=>A._options.onEnd?.());const t=g&&A._canvasStopped;A._canvasStopped=!1,t&&JR(A.engine).catch(i=>LF("canvas restart",i))}function tnA(A){if(!A.engine._deviceLostRecovery?._registrations.length)return;let g=!1;A._recovery=iF(A.engine,{_kind:"xr-session",_recoverOrder:Number.MAX_SAFE_INTEGER,_onLost(){g=A._canvasStopped,$3(A,!1),A.session.end().catch(I=>LF("session end after device loss",I))},async _recover(){g&&await JR(A.engine)}})}function CnA(){HCA(()=>({xrCompatible:!0}))}function inA(A,g){const I=g.create(A);return A._features.push(I),I}function A4(A,g,I,e,t,i,o,Q,r){const E=A+t+r;let n;return E>0?(n=.5/Math.sqrt(E+1),{x:(Q-i)*n,y:(I-o)*n,z:(e-g)*n,w:.25/n}):A>t&&A>r?(n=2*Math.sqrt(1+A-t-r),{x:.25*n,y:(g+e)/n,z:(I+o)/n,w:(Q-i)/n}):t>r?(n=2*Math.sqrt(1+t-A-r),{x:(g+e)/n,y:.25*n,z:(i+Q)/n,w:(I-o)/n}):(n=2*Math.sqrt(1+r-A-t),{x:(I+o)/n,y:(i+Q)/n,z:.25*n,w:(e-g)/n})}function LH(A){return A4(A[0],A[4],A[8],A[1],A[5],A[9],A[2],A[6],A[10])}function IN(A){return A[0]*(A[5]*A[10]-A[6]*A[9])+A[1]*(A[6]*A[8]-A[4]*A[10])+A[2]*(A[4]*A[9]-A[5]*A[8])}function LC(A){const g=Math.hypot(A[0],A[1],A[2]),I=Math.hypot(A[4],A[5],A[6]),e=Math.hypot(A[8],A[9],A[10]),t=IN(A)<0?-I:I,i=g>1e-8?1/g:0,o=I>1e-8?1/t:0,Q=e>1e-8?1/e:0,r=A4(A[0]*i,A[4]*o,A[8]*Q,A[1]*i,A[5]*o,A[9]*Q,A[2]*i,A[6]*o,A[10]*Q),E=1/Math.hypot(r.x,r.y,r.z,r.w);return{translation:{x:A[12],y:A[13],z:A[14]},rotation:{x:r.x*E,y:r.y*E,z:r.z*E,w:r.w*E},scale:{x:g,y:t,z:e}}}class eN{_x;_y;_z;_w;_onDirty;_version=0;constructor(g,I,e,t,i){this._x=g,this._y=I,this._z=e,this._w=t,this._onDirty=i}get version(){return this._version}get x(){return this._x}set x(g){this._x!==g&&(this._x=g,this._version++,this._onDirty())}get y(){return this._y}set y(g){this._y!==g&&(this._y=g,this._version++,this._onDirty())}get z(){return this._z}set z(g){this._z!==g&&(this._z=g,this._version++,this._onDirty())}get w(){return this._w}set w(g){this._w!==g&&(this._w=g,this._version++,this._onDirty())}set(g,I,e,t){this._x=g,this._y=I,this._z=e,this._w=t,this._version++,this._onDirty()}copyFrom(g){this.set(g.x,g.y,g.z,g.w)}toArray(g,I=0){g[I]=this._x,g[I+1]=this._y,g[I+2]=this._z,g[I+3]=this._w}}function YF(A,g,I){const e=Math.cos(A*.5),t=Math.sin(A*.5),i=Math.cos(g*.5),o=Math.sin(g*.5),Q=Math.cos(I*.5),r=Math.sin(I*.5);return[t*i*Q+e*o*r,e*o*Q-t*i*r,e*i*r+t*o*Q,e*i*Q-t*o*r]}function YH(A,g,I,e){const t=2*(A*I+e*g),i=Math.asin(Math.max(-1,Math.min(1,t))),o=Math.atan2(-(2*(g*I-e*A)),1-2*(A*A+g*g)),Q=Math.atan2(-(2*(A*g-e*I)),1-2*(g*g+I*I));return[o,i,Q]}function JF(A){let g=0,I=0,e=0,t=-1;const i=()=>{if(A.version!==t){const Q=YH(A.x,A.y,A.z,A.w);g=Q[0],I=Q[1],e=Q[2],t=A.version}},o=(Q,r,E)=>{g=Q,I=r,e=E;const[n,s,c,l]=YF(Q,r,E);A.set(n,s,c,l),t=A.version};return{get x(){return i(),g},set x(Q){i(),o(Q,I,e)},get y(){return i(),I},set y(Q){i(),o(g,Q,e)},get z(){return i(),e},set z(Q){i(),o(g,I,Q)},set:o}}function onA(A,g=0,I=0,e=0,t=0,i=0,o=0,Q=1,r=1,E=1,n=1){return JH(A,null,g,I,e,t,i,o,Q,r,E,n)}function g4(A,g){return JH(A,g)}function JH(A,g,I=0,e=0,t=0,i=0,o=0,Q=0,r=1,E=1,n=1,s=1){const c=so(()=>u._localMatrix??lF(u.position,u.rotationQuaternion,u.scaling)),l=()=>{u._localMatrix||c.markLocalDirty()},D=new Ht(I,e,t,l),p=new eN(i,o,Q,r,l),y=JF(p),_=new Ht(E,n,s,l),u={name:A,children:[],position:D,rotationQuaternion:p,rotation:y,scaling:_,get parent(){return c.parent},set parent(f){c.parent=f},get worldMatrix(){return c.getWorldMatrix()},get worldMatrixVersion(){return c.getWorldMatrixVersion()}};return g&&(u._localMatrix=g),tQ(u,c),u}function tN(A,g=0,I=0,e=0,t=0,i=0,o=0,Q=1,r=1,E=1){const n=so(()=>lF(w.position,w.rotationQuaternion,w.scaling)),s=()=>n.markLocalDirty(),[c,l,D,p]=YF(t,i,o),y=new eN(c,l,D,p,s),_=y,u=JF(y),f=new Ht(g,I,e,s),h=new Ht(Q,r,E,s),w={...A,position:f,rotationQuaternion:_,rotation:u,scaling:h};return w.children||(w.children=[]),Object.defineProperty(w,"parent",{get(){return n.parent},set(M){n.parent=M},configurable:!0,enumerable:!0}),Object.defineProperty(w,"worldMatrix",{get(){return n.getWorldMatrix()},configurable:!0,enumerable:!1}),Object.defineProperty(w,"worldMatrixVersion",{get(){return n.getWorldMatrixVersion()},configurable:!0,enumerable:!1}),tQ(w,n),w}function I4(A,g,I,e,t,i,o,Q){const r=A._device,E=wI(A,g,SA.VERTEX),n=wI(A,I,SA.VERTEX),s=wI(A,e,SA.INDEX);let c;t&&t.length>0?c=wI(A,t,SA.VERTEX):(c=r.createBuffer({size:g.length/3*8,usage:SA.VERTEX,mappedAtCreation:!0}),c.unmap());let l=null;i&&i.length>0&&(l=wI(A,i,SA.VERTEX));const D=o&&o.length>0?wI(A,o,SA.VERTEX):null,p=Q&&Q.length>0?wI(A,Q,SA.VERTEX):null;return{positionBuffer:E,normalBuffer:n,uvBuffer:c,uv2Buffer:l,tangentBuffer:D,colorBuffer:p,hasUv:!!t&&t.length>0,hasUv2:!!i&&i.length>0,hasTangent:!!o&&o.length>0,hasColor:!!Q&&Q.length>0,indexBuffer:s,indexCount:e.length,indexFormat:"uint32"}}function yi(A,g){let I=1/0,e=1/0,t=1/0,i=-1/0,o=-1/0,Q=-1/0;if(g){const r=g[0],E=g[1],n=g[2],s=g[4],c=g[5],l=g[6],D=g[8],p=g[9],y=g[10],_=g[12],u=g[13],f=g[14];for(let h=0;h<A.length;h+=3){const w=A[h],M=A[h+1],S=A[h+2],R=r*w+s*M+D*S+_,N=E*w+c*M+p*S+u,F=n*w+l*M+y*S+f;R<I&&(I=R),R>i&&(i=R),N<e&&(e=N),N>o&&(o=N),F<t&&(t=F),F>Q&&(Q=F)}}else for(let r=0;r<A.length;r+=3){const E=A[r],n=A[r+1],s=A[r+2];E<I&&(I=E),E>i&&(i=E),n<e&&(e=n),n>o&&(o=n),s<t&&(t=s),s>Q&&(Q=s)}return[[I,e,t],[i,o,Q]]}function vH(A={}){const g=Math.max(3,A.segments??32),I=A.diameter??1,e=(A.diameterX??I)/2,t=(A.diameterY??I)/2,i=(A.diameterZ??I)/2,o=2+g,Q=2*o,r=(o+1)*(Q+1),E=o*Q*6,n=new X(r*3),s=new X(r*3),c=new X(r*2),l=new Vg(E);let D=0;for(let y=0;y<=o;y++){const _=y/o,u=_*Math.PI;for(let f=0;f<=Q;f++){const h=f/Q,w=h*Math.PI*2,M=Math.sin(u)*Math.cos(w),S=Math.cos(u),R=-Math.sin(u)*Math.sin(w);n[D*3]=e*M,n[D*3+1]=t*S,n[D*3+2]=i*R,s[D*3]=M,s[D*3+1]=S,s[D*3+2]=R,c[D*2]=h,c[D*2+1]=_,D++}}let p=0;for(let y=0;y<o;y++)for(let _=0;_<Q;_++){const u=y*(Q+1)+_,f=u+Q+1;l[p++]=u,l[p++]=u+1,l[p++]=f,l[p++]=f,l[p++]=u+1,l[p++]=f+1}return{positions:n,normals:s,uvs:c,indices:l,vertexCount:r,indexCount:E}}const BnA=[1260470181,3738583663,128],QnA=new X([0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0]),rnA=new X([1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0]),EnA=new Vg([0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]);function e4(A=1){let g;if(typeof A=="number")g=[A,A,A];else{const{size:e=1,width:t=e,height:i=e,depth:o=e}=A;g=[t,i,o]}const I=new X(72);for(let e=0;e<I.length;e++){const t=BnA[e>>5]>>>(e&31)&1;I[e]=(t-.5)*g[e%3]}return{positions:I,normals:QnA.slice(),uvs:rnA.slice(),indices:EnA.slice(),vertexCount:24,indexCount:36}}function nnA(A={}){const g=A.diameter??1,I=A.thickness??.5,e=A.tessellation??16,t=g/2,i=I/2,o=e+1,Q=o*o,r=o*o*6,E=new X(Q*3),n=new X(Q*3),s=new X(Q*2),c=new Vg(r),l=Math.PI*2;let D=0,p=0,y=0;for(let _=0;_<=e;_++){const u=_*l/e-Math.PI/2,f=Math.cos(u),h=Math.sin(u);for(let w=0;w<=e;w++){const M=w*l/e+Math.PI,S=Math.cos(M),R=Math.sin(M),N=S*i,F=(N+t)*f,G=R*i,m=-(N+t)*h;E[D]=F,E[D+1]=G,E[D+2]=m,n[D]=S*f,n[D+1]=R,n[D+2]=-S*h,D+=3,s[p]=_/e,s[p+1]=1-w/e,p+=2;const K=(_+1)%o,k=(w+1)%o;c[y++]=_*o+w,c[y++]=_*o+k,c[y++]=K*o+w,c[y++]=_*o+k,c[y++]=K*o+k,c[y++]=K*o+w}}return{positions:E,normals:n,uvs:s,indices:c}}function t4(A,g){const I=A.length,e=new S1(I);for(let E=0;E<I;E++)e[E]=A[E];const t=new Vg(g.length);for(let E=0;E<g.length;E++)t[E]=g[E];const i=new S1(I),o=g.length/3|0;for(let E=0;E<o;E++){const n=t[E*3]*3,s=t[E*3+1]*3,c=t[E*3+2]*3,l=e[n]-e[s],D=e[n+1]-e[s+1],p=e[n+2]-e[s+2],y=e[c]-e[s],_=e[c+1]-e[s+1],u=e[c+2]-e[s+2];let f=D*u-p*_,h=p*y-l*u,w=l*_-D*y,M=Math.sqrt(f*f+h*h+w*w);M===0&&(M=1),f/=M,h/=M,w/=M,i[n]=i[n]+f,i[n+1]=i[n+1]+h,i[n+2]=i[n+2]+w,i[s]=i[s]+f,i[s+1]=i[s+1]+h,i[s+2]=i[s+2]+w,i[c]=i[c]+f,i[c+1]=i[c+1]+h,i[c+2]=i[c+2]+w}const Q=I/3|0,r=new Array(I);for(let E=0;E<Q;E++){const n=i[E*3],s=i[E*3+1],c=i[E*3+2];let l=Math.sqrt(n*n+s*s+c*c);l===0&&(l=1),r[E*3]=n/l,r[E*3+1]=s/l,r[E*3+2]=c/l}return r}function HH(A={}){const g=A.radius??2,I=A.tube??.5,e=A.radialSegments??32,t=A.tubularSegments??32,i=A.p??2,o=A.q??3,Q=[],r=[],E=[],n=c=>{const l=Math.cos(c),D=Math.sin(c),p=o/i*c,y=Math.cos(p),_=g*(2+y)*.5*l,u=g*(2+y)*D*.5,f=g*Math.sin(p)*.5;return[_,u,f]};for(let c=0;c<=e;c++){const D=c%e/e*2*i*Math.PI,p=n(D),y=n(D+.01),_=y[0]-p[0],u=y[1]-p[1],f=y[2]-p[2];let h=y[0]+p[0],w=y[1]+p[1],M=y[2]+p[2],S=u*M-f*w,R=f*h-_*M,N=_*w-u*h;h=R*f-N*u,w=N*_-S*f,M=S*u-R*_;let F=Math.sqrt(S*S+R*R+N*N);F===0&&(F=1),S/=F,R/=F,N/=F;let G=Math.sqrt(h*h+w*w+M*M);G===0&&(G=1),h/=G,w/=G,M/=G;for(let m=0;m<t;m++){const k=m%t/t*2*Math.PI,L=-I*Math.cos(k),H=I*Math.sin(k);Q.push(p[0]+L*h+H*S),Q.push(p[1]+L*w+H*R),Q.push(p[2]+L*M+H*N),r.push(c/e),r.push(m/t)}}for(let c=0;c<e;c++)for(let l=0;l<t;l++){const D=(l+1)%t,p=c*t+l,y=(c+1)*t+l,_=(c+1)*t+D,u=c*t+D;E.push(u),E.push(y),E.push(p),E.push(u),E.push(_),E.push(y)}const s=t4(Q,E);return{positions:new Float32Array(Q),normals:new Float32Array(s),uvs:new Float32Array(r),indices:new Uint32Array(E)}}function TH(A={}){const g=A.width??1,I=A.height??1,e=A.subdivisions??1,t=e+1,i=t,o=t*i,Q=e*e*6,r=new X(o*3),E=new X(o*3),n=new X(o*2),s=new Vg(Q);let c=0,l=0;for(let _=0;_<i;_++)for(let u=0;u<t;u++){const f=-g/2+u/e*g,h=-I/2+(1-_/e)*I;r[c]=f,r[c+1]=0,r[c+2]=h,E[c]=0,E[c+1]=1,E[c+2]=0,c+=3,n[l]=u/e,n[l+1]=1-_/e,l+=2}const D=A.uvScale?.[0]??1,p=A.uvScale?.[1]??1;if(D!==1||p!==1)for(let _=0;_<n.length;_+=2)n[_]=n[_]*D,n[_+1]=n[_+1]*p;let y=0;for(let _=0;_<e;_++)for(let u=0;u<e;u++){const f=_*t+u,h=f+1,w=(_+1)*t+u,M=w+1;s[y++]=M,s[y++]=h,s[y++]=f,s[y++]=w,s[y++]=M,s[y++]=f}return{positions:r,normals:E,uvs:n,indices:s}}function snA(A,g,I,e,t,i,o){const Q=t+1,r=Q,E=o-i;for(let s=0;s<r;s++)for(let c=0;c<Q;c++){const l=s*Q+c,D=c/t,p=s/t,y=D*(I-1)|0,u=((p*(e-1)|0)*I+y)*4,f=g[u]/255,h=g[u+1]/255,w=g[u+2]/255,M=f*.3+h*.59+w*.11;A.positions[l*3+1]=i+M*E}A.normals.fill(0);for(let s=0;s<A.indices.length;s+=3){const c=A.indices[s],l=A.indices[s+1],D=A.indices[s+2],p=A.positions,y=p[c*3],_=p[c*3+1],u=p[c*3+2],f=p[l*3],h=p[l*3+1],w=p[l*3+2],M=p[D*3],S=p[D*3+1],R=p[D*3+2],N=f-y,F=h-_,G=w-u,m=M-y,K=S-_,k=R-u;let L=-(F*k-G*K),H=-(G*m-N*k),q=-(N*K-F*m);const CA=Math.sqrt(L*L+H*H+q*q)||1;L/=CA,H/=CA,q/=CA;const eA=A.normals;eA[c*3]=eA[c*3]+L,eA[c*3+1]=eA[c*3+1]+H,eA[c*3+2]=eA[c*3+2]+q,eA[l*3]=eA[l*3]+L,eA[l*3+1]=eA[l*3+1]+H,eA[l*3+2]=eA[l*3+2]+q,eA[D*3]=eA[D*3]+L,eA[D*3+1]=eA[D*3+1]+H,eA[D*3+2]=eA[D*3+2]+q}const n=A.positions.length/3;for(let s=0;s<n;s++){const c=A.normals[s*3],l=A.normals[s*3+1],D=A.normals[s*3+2],p=Math.sqrt(c*c+l*l+D*D)||1;A.normals[s*3]=c/p,A.normals[s*3+1]=l/p,A.normals[s*3+2]=D/p}}async function anA(A,g={}){const I=g.subdivisions??1,e=g.minHeight??0,t=g.maxHeight??1,i=TH(g),o=new Image;o.crossOrigin="anonymous",await new Promise((n,s)=>{o.onload=()=>n(),o.onerror=c=>s(c instanceof Error?c:new Error(String(c))),o.src=A});const Q=document.createElement("canvas");Q.width=o.width,Q.height=o.height;const r=Q.getContext("2d");r.drawImage(o,0,0);const E=r.getImageData(0,0,o.width,o.height);return snA(i,E.data,o.width,o.height,I,e,t),i}function xH(A={}){const g=A.height??2;let I=A.diameterTop===0?0:A.diameterTop??A.diameter??1,e=A.diameterBottom===0?0:A.diameterBottom??A.diameter??1;I===0&&(I=1e-5),e===0&&(e=1e-5);const t=Math.max(3,(A.tessellation??24)|0),i=Math.max(1,(A.subdivisions??1)|0),o=1,Q=[],r=[],E=[],n=[],s=Math.PI*2*o/t,c=(e-I)/2/g;for(let p=0;p<=i;p++){const y=p/i,_=(y*(I-e)+e)/2;for(let u=0;u<=t;u++){const f=u*s,h=Math.cos(-f)*_,w=-g/2+y*g,M=Math.sin(-f)*_;let S,R,N;if(A.diameterTop===0&&p===i){const F=r.length-(t+1)*3;S=r[F],R=r[F+1],N=r[F+2]}else{S=h,N=M,R=Math.sqrt(S*S+N*N)*c;const F=1/Math.sqrt(S*S+R*R+N*N);S*=F,R*=F,N*=F}Q.push(h,w,M),r.push(S,R,N),E.push(u/t,y)}}const l=t;for(let p=0;p<i;p++)for(let y=0;y<t;y++){const _=p*(l+1)+y,u=(p+1)*(l+1)+y,f=p*(l+1)+(y+1),h=(p+1)*(l+1)+(y+1);n.push(_,u,f),n.push(h,f,u)}const D=p=>{const y=p?I/2:e/2;if(y===0)return;const _=Q.length/3,u=p?g/2:-g/2;Q.push(0,u,0),r.push(0,p?1:-1,0),E.push(.5,.5);for(let f=0;f<=t;f++){const h=Math.PI*2*f*o/t,w=Math.cos(-h),M=Math.sin(-h);Q.push(w*y,u,M*y),r.push(0,p?1:-1,0),E.push(w*.5+.5,M*.5+.5)}for(let f=0;f<t;f++)p?n.push(_,_+(f+2),_+(f+1)):n.push(_,_+(f+1),_+(f+2))};return D(!1),D(!0),{positions:new X(Q),normals:new X(r),uvs:new X(E),indices:new Vg(n)}}function qH(A={}){const g=Math.max(A.subdivisions?A.subdivisions:2,1)|0,I=Math.max(A.tessellation?A.tessellation:16,3)|0,e=Math.max(A.height?A.height:1,0),t=Math.max(A.radius?A.radius:.25,0),i=Math.max(A.capSubdivisions?A.capSubdivisions:6,1)|0,o=I,Q=g,r=Math.max(A.radiusTop?A.radiusTop:t,0),E=Math.max(A.radiusBottom?A.radiusBottom:t,0),n=e-(r+E),s=0,c=2*Math.PI,l=Math.max(A.topCapSubdivisions?A.topCapSubdivisions:i,1),D=Math.max(A.bottomCapSubdivisions?A.bottomCapSubdivisions:i,1),p=Math.acos((E-r)/e);let y=[];const _=[],u=[],f=[];let h=0;const w=[],M=n*.5,S=Math.PI*.5;let R,N;const F=Math.cos(p),G=Math.sin(p),m=r*G-E*G,K=M+r*F-(-M+E*F),k=Math.sqrt(m*m+K*K),L=r*p+k+E*(S-p);let H=0;for(N=0;N<=l;N++){const eA=[],Z=S-p*(N/l);H+=r*p/l;const O=Math.cos(Z),P=Math.sin(Z),gA=O*r;for(R=0;R<=o;R++){const yA=R/o,cA=yA*c+s,RA=Math.sin(cA),YA=Math.cos(cA);_.push(gA*RA,M+P*r,gA*YA),u.push(O*RA,P,O*YA),f.push(yA,1-H/L),eA.push(h),h++}w.push(eA)}const q=e-r-E+F*r-F*E,CA=G*(E-r)/q;for(N=1;N<=Q;N++){const eA=[];H+=k/Q;const Z=G*(N*(E-r)/Q+r);for(R=0;R<=o;R++){const O=R/o,P=O*c+s,gA=Math.sin(P),yA=Math.cos(P);_.push(Z*gA,M+F*r-N*q/Q,Z*yA);const cA=1/Math.sqrt(gA*gA+CA*CA+yA*yA);u.push(gA*cA,CA*cA,yA*cA),f.push(O,1-H/L),eA.push(h),h++}w.push(eA)}for(N=1;N<=D;N++){const eA=[],Z=S-p-(Math.PI-p)*(N/D);H+=E*p/D;const O=Math.cos(Z),P=Math.sin(Z),gA=O*E;for(R=0;R<=o;R++){const yA=R/o,cA=yA*c+s,RA=Math.sin(cA),YA=Math.cos(cA);_.push(gA*RA,-M+P*E,gA*YA),u.push(O*RA,P,O*YA),f.push(yA,1-H/L),eA.push(h),h++}w.push(eA)}for(R=0;R<o;R++)for(N=0;N<l+Q+D;N++){const eA=w[N][R],Z=w[N+1][R],O=w[N+1][R+1],P=w[N][R+1];y.push(eA,Z,P),y.push(Z,O,P)}return y=y.reverse(),{positions:new X(_),normals:new X(u),uvs:new X(f),indices:new Vg(y)}}function cnA(A={}){const g=A.size??1,I=A.width??g,e=A.height??g,t=I/2,i=e/2,o=new X([-t,-i,0,t,-i,0,t,i,0,-t,i,0]),Q=new X([0,0,-1,0,0,-1,0,0,-1,0,0,-1]),r=new X([0,0,1,0,1,1,0,1]),E=new Vg([0,1,2,0,2,3]);return{positions:o,normals:Q,uvs:r,indices:E}}function lnA(A={}){const g=A.radius??.5,I=A.tessellation??64,e=A.arc&&(A.arc<=0||A.arc>1)?1:A.arc??1,t=[],i=[],o=[];t.push(0,0,0),i.push(.5,.5);const Q=Math.PI*2*e,r=e===1?Q/I:Q/(I-1);let E=0;for(let c=0;c<I;c++){const l=Math.cos(E),D=Math.sin(E);t.push(g*l,g*D,0),i.push((l+1)/2,(1-D)/2),E+=r}e===1&&(t.push(t[3],t[4],t[5]),i.push(i[2],i[3]));const n=t.length/3;for(let c=1;c<n-1;c++)o.push(c+1,0,c);const s=new X(n*3);for(let c=0;c<n;c++)s[c*3+2]=-1;return{positions:new X(t),normals:s,uvs:new X(i),indices:new Vg(o)}}const PH=[{vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},{vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},{vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},{vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},{vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},{vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},{vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},{vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},{vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},{vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},{vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},{vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},{vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},{vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},{vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]}];function DnA(A={}){const g=A.type!==void 0&&(A.type<0||A.type>=PH.length)?0:A.type??0,I=A.size,e=A.sizeX??I??1,t=A.sizeY??I??1,i=A.sizeZ??I??1,o=A.flat??!0,Q=PH[g],r=Q.face.length,E=[],n=[],s=[];if(o){let l=0,D=0;const p=[];for(let y=0;y<r;y++){const _=Q.face[y],u=_.length,f=2*Math.PI/u;let h=.5*Math.tan(f/2),w=.5;for(let M=0;M<u;M++){const S=Q.vertex[_[M]];E.push(S[0]*e,S[1]*t,S[2]*i),p.push(l),l++,n.push(.5+h,w-.5+.5);const R=h*Math.cos(f)-w*Math.sin(f);w=h*Math.sin(f)+w*Math.cos(f),h=R}for(let M=0;M<u-2;M++)s.push(p[0+D],p[M+2+D],p[M+1+D]);D+=u}}else{for(let l=0;l<Q.vertex.length;l++){const D=Q.vertex[l];E.push(D[0]*e,D[1]*t,D[2]*i),n.push(0,0)}for(let l=0;l<r;l++){const D=Q.face[l];for(let p=0;p<D.length-2;p++)s.push(D[0],D[p+2],D[p+1])}}const c=t4(E,s);return{positions:new X(E),normals:new X(c),uvs:new X(n),indices:new Vg(s)}}function C4(A){return Math.sqrt(A.x*A.x+A.y*A.y+A.z*A.z)}function i4(A,g){return{x:A.x-g.x,y:A.y-g.y,z:A.z-g.z}}function o4(A){let g=A.pathArray;const I=A.closeArray||!1,e=A.closePath||!1,t=Math.floor(g[0].length/2);let i=A.offset??t;if(i=i>t?t:Math.floor(i),g.length<2){const G=[],m=[],K=g[0];for(let k=0;k<K.length-i;k++)G.push(K[k]),m.push(K[k+i]);g=[G,m]}const o=[],Q=[],r=[],E=[],n=[],s=[],c=[],l=[],D=[],p=e?1:0,y=I?1:0;let _=g[0].length,u=0;for(let G=0;G<g.length+y;G++){s[G]=0,E[G]=[0];const m=G===g.length?g[0]:g[G],K=m.length;_=_<K?_:K;let k=0;for(;k<K;){const L=m[k];if(o.push(L.x,L.y,L.z),k>0){const q=C4(i4(m[k],m[k-1]))+s[G];E[G].push(q),s[G]=q}k++}if(e){k--,o.push(m[0].x,m[0].y,m[0].z);const H=C4(i4(m[k],m[0]))+s[G];E[G].push(H),s[G]=H}l[G]=K+p,D[G]=u,u+=K+p}for(let G=0;G<_+p;G++){c[G]=0,n[G]=[0];for(let m=0;m<g.length-1+y;m++){const K=g[m],k=m===g.length-1?g[0]:g[m+1];let L,H;G===_?(L=K[0],H=k[0]):(L=K[G],H=k[G]);const CA=C4(i4(H,L))+c[G];n[G].push(CA),c[G]=CA}}for(let G=0;G<g.length+y;G++)for(let m=0;m<_+p;m++){const K=s[G]!==0?E[G][m]/s[G]:0,k=c[m]!==0?n[m][G]/c[m]:0;r.push(K,k)}let f=0,h=0,w=l[f]-1,M=l[f+1]-1,S=w<M?w:M,R=D[1]-D[0];const N=l.length-1;for(;h<=S&&f<N;)Q.push(h,h+R,h+1),Q.push(h+R+1,h+1,h+R),h+=1,h===S&&(f++,R=D[f+1]-D[f],w=l[f]-1,M=l[f+1]-1,h=D[f],S=w<M?w+h:M+h);const F=t4(o,Q);if(e)for(let G=0;G<g.length;G++){const m=D[G]*3,K=G+1<g.length?(D[G+1]-1)*3:F.length-3;F[m]=(F[m]+F[K])*.5,F[m+1]=(F[m+1]+F[K+1])*.5,F[m+2]=(F[m+2]+F[K+2])*.5;const k=Math.sqrt(F[m]*F[m]+F[m+1]*F[m+1]+F[m+2]*F[m+2])||1;F[m]=F[m]/k,F[m+1]=F[m+1]/k,F[m+2]=F[m+2]/k,F[K]=F[m],F[K+1]=F[m+1],F[K+2]=F[m+2]}if(I){let G=D[0]*3,m=D[g.length]*3;for(let K=0;K<_+p;K++){F[G]=(F[G]+F[m])*.5,F[G+1]=(F[G+1]+F[m+1])*.5,F[G+2]=(F[G+2]+F[m+2])*.5;const k=Math.sqrt(F[G]*F[G]+F[G+1]*F[G+1]+F[G+2]*F[G+2])||1;F[G]=F[G]/k,F[G+1]=F[G+1]/k,F[G+2]=F[G+2]/k,F[m]=F[G],F[m+1]=F[G+1],F[m+2]=F[G+2],G+=3,m+=3}}return{positions:new X(o),normals:new X(F),uvs:new X(r),indices:new Vg(Q)}}function D1(A,g){return{x:A.y*g.z-A.z*g.y,y:A.z*g.x-A.x*g.z,z:A.x*g.y-A.y*g.x}}function ao(A){return Math.sqrt(A.x*A.x+A.y*A.y+A.z*A.z)}function pC(A){const g=ao(A);if(g<1e-10)return{x:0,y:0,z:0};const I=1/g;return{x:A.x*I,y:A.y*I,z:A.z*I}}function iQ(A,g){return{x:A.x-g.x,y:A.y-g.y,z:A.z-g.z}}const B4=.001;function Q4(A,g,I){return Math.abs(A-g)<=I}function OH(A,g){let I=1,e=iQ(A[g+I],A[g]);for(;ao(e)===0&&g+I+1<A.length;)I++,e=iQ(A[g+I],A[g]);return e}function pnA(A,g){let I=1,e=iQ(A[g],A[g-I]);for(;ao(e)===0&&g>I+1;)I++,e=iQ(A[g],A[g-I]);return e}function ynA(A,g){let I,e=ao(A);if(e===0&&(e=1),g===null){let t;Q4(Math.abs(A.y)/e,1,B4)?Q4(Math.abs(A.x)/e,1,B4)?Q4(Math.abs(A.z)/e,1,B4)?t=CQ(0,0,0):t=CQ(0,0,1):t=CQ(1,0,0):t=CQ(0,-1,0),I=D1(A,t)}else{const t=D1(A,g);I=D1(t,A)}return pC(I)}function jH(A,g=null){const I=A.length,e=new Array(I),t=new Array(I),i=new Array(I),o=new Array(I);if(I<2)return{tangents:e,normals:t,binormals:i,distances:o};e[0]=pC(OH(A,0)),e[I-1]=pC(iQ(A[I-1],A[I-2]));const Q=pC(ynA(e[0],g));t[0]=Q,i[0]=pC(D1(e[0],t[0])),o[0]=0;for(let r=1;r<I;r++){const E=pnA(A,r);if(r<I-1){const l=OH(A,r),D={x:E.x+l.x,y:E.y+l.y,z:E.z+l.z};e[r]=pC(D)}o[r]=o[r-1]+ao(iQ(A[r],A[r-1]));const n=e[r],s=i[r-1];let c=D1(s,n);if(ao(c)===0){const l=t[r-1];c={x:l.x,y:l.y,z:l.z}}else c=pC(c);t[r]=c,i[r]=pC(D1(n,c))}return{tangents:e,normals:t,binormals:i,distances:o}}const oQ=0,r4=1,CN=2,iN=3;function _nA(A,g,I){const e=Math.cos(I),t=Math.sin(I),i=g.x*A.x+g.y*A.y+g.z*A.z,o=g.y*A.z-g.z*A.y,Q=g.z*A.x-g.x*A.z,r=g.x*A.y-g.y*A.x;return{x:A.x*e+o*t+g.x*i*(1-e),y:A.y*e+Q*t+g.y*i*(1-e),z:A.z*e+r*t+g.z*i*(1-e)}}function unA(A){const g=A.path,I=A.radius??1,e=(A.tessellation??64)|0,t=A.radiusFunction??null;let i=A.cap??oQ;i=i<0||i>3?oQ:i;const o=A.arc&&(A.arc<=0||A.arc>1)?1:A.arc??1,Q=jH(g),{tangents:r,normals:E,distances:n}=Q,c=Math.PI*2/e*o,l=[];let D=i===oQ||i===CN?0:2;for(let y=0;y<g.length;y++){const _=t?t(y,n[y]):I,u=[],f=E[y],h=r[y];for(let w=0;w<e;w++){const M=_nA(f,h,c*w);u.push({x:M.x*_+g[y].x,y:M.y*_+g[y].y,z:M.z*_+g[y].z})}l[D]=u,D++}const p=(y,_)=>{const u=[];for(let f=0;f<y;f++)u.push(g[_]);return u};return(i===r4||i===iN)&&(l[0]=p(e,0),l[1]=l[2].slice(0)),(i===CN||i===iN)&&(l[D]=l[D-1].slice(0),l[D+1]=p(e,g.length-1)),o4({pathArray:l,closePath:!0,closeArray:!1})}function hnA(A,g,I){const e=Math.cos(I),t=Math.sin(I),i=g.x*A.x+g.y*A.y+g.z*A.z,o=g.y*A.z-g.z*A.y,Q=g.z*A.x-g.x*A.z,r=g.x*A.y-g.y*A.x;return{x:A.x*e+o*t+g.x*i*(1-e),y:A.y*e+Q*t+g.y*i*(1-e),z:A.z*e+r*t+g.z*i*(1-e)}}function fnA(A){const g=A.shape,I=A.path,e=A.scale??1,t=A.rotation??0;let i=A.cap??oQ;i=i<0||i>3?oQ:i;const o=jH(I),{tangents:Q,normals:r,binormals:E}=o,n=[];let s=i===oQ||i===CN?0:2,c=0;for(let D=0;D<I.length;D++){const p=[],y=Q[D],_=r[D],u=E[D];for(let f=0;f<g.length;f++){const h=g[f],w={x:y.x*h.z+_.x*h.x+u.x*h.y,y:y.y*h.z+_.y*h.x+u.y*h.y,z:y.z*h.z+_.z*h.x+u.z*h.y},M=hnA(w,y,c);p.push({x:M.x*e+I[D].x,y:M.y*e+I[D].y,z:M.z*e+I[D].z})}n[s]=p,c+=t,s++}const l=D=>{const p={x:0,y:0,z:0};for(const u of D)p.x+=u.x,p.y+=u.y,p.z+=u.z;const y=1/D.length;p.x*=y,p.y*=y,p.z*=y;const _=[];for(let u=0;u<D.length;u++)_.push(p);return _};return(i===r4||i===iN)&&(n[0]=l(n[2]),n[1]=n[2]),(i===CN||i===iN)&&(n[s]=n[s-1],n[s+1]=l(n[s-1])),o4({pathArray:n,closeArray:!1,closePath:!1})}function vF(A,g,I,e,t,i,o,Q,r){const[E,n]=yi(I);g.boundMin=isFinite(E[0])?E:void 0,g.boundMax=isFinite(n[0])?n:void 0,g._cpuPositions=I,g._cpuNormals=e,g._cpuUvs=i?.length?i:void 0,g._cpuUv2s=o?.length?o:null,g._cpuTangents=Q?.length?Q:null,g._cpuColors=r?.length?r:null,g._cpuIndices=t,g._cpuGpuIndices=t,g._cpuIndexFormat="uint32",A._dlr?.m(g,g._cpuUv2s,g._cpuTangents,g._cpuColors,t,"uint32")}function dnA(A,g,I,e,t,i,o,Q){const r=A._gpu,E=g.length/3;(r._vbLayout||(r._refCount??1)>1)&&U(357),(!Number.isInteger(E)||I.length!==g.length||e.length%3!==0||r.indexFormat!=="uint32")&&U(358);const n=!!t&&t.length>0,s=!!i&&i.length>0,c=!!o&&o.length>0,l=!!Q&&Q.length>0;return(n!==!!r.hasUv||n&&t.length!==E*2||s!==!!r.hasUv2||s&&i.length!==E*2||c!==!!r.hasTangent||c&&o.length!==E*4||l!==!!r.hasColor||l&&Q.length!==E*4)&&U(359),E}function Et(A,g,I,e,t,i,o,Q,r){const[E,n]=yi(I),s=tN({name:g,material:null,receiveShadows:!1,boundMin:isFinite(E[0])?E:void 0,boundMax:isFinite(n[0])?n:void 0,_gpu:I4(A,I,e,t,i,o,Q,r)});return s._cpuPositions=I,s._cpuNormals=e,s._cpuUvs=i,s._cpuIndices=t,A._dlr?.m(s,o??null,Q??null,r??null,t,"uint32"),s}function VH(A){cC();for(const g of A._renderingContexts){const I=g;I._renderableVersion!==void 0&&I._renderableVersion++}}function HF(A,g,I,e=0,t,i=0){Ir(A,g,g._gpu.positionBuffer,I,3,e,t,i)}function Ir(A,g,I,e,t,i,o,Q){(g._gpu._refCount??1)>1&&U(360,g.name);const r=e.length/t,E=o??r-Q;if((!Number.isInteger(r)||!Number.isInteger(i)||i<0||!Number.isInteger(Q)||Q<0||!Number.isInteger(E)||E<0||Q+E>r)&&U(361),E===0)return;const n=t*4,s=i*n,c=E*n;s+c>I.size&&U(362),A._device.queue.writeBuffer(I,s,e.buffer,e.byteOffset+Q*n,c),OR(g)}function wnA(A,g,I,e,t,i,o,Q,r){const E=g._gpu,n=I.length/3,s=!!i&&i.length>0,c=!!o&&o.length>0,l=!!Q&&Q.length>0,D=!!r&&r.length>0;(E._vbLayout||(E._refCount??1)>1)&&U(363),(!Number.isInteger(n)||g._cpuPositions?.length!==I.length||e.length!==I.length||g._cpuIndices?.length!==t.length||t.length>E.indexCount||E.indexFormat!=="uint32")&&U(364),(s!==!!E.hasUv||s&&i.length!==n*2||c!==!!E.hasUv2||c&&o.length!==n*2||l!==!!E.hasTangent||l&&Q.length!==n*4||D!==!!E.hasColor||D&&r.length!==n*4)&&U(365);const p=A._device.queue;p.writeBuffer(E.positionBuffer,0,I.buffer,I.byteOffset,I.byteLength),p.writeBuffer(E.normalBuffer,0,e.buffer,e.byteOffset,e.byteLength),p.writeBuffer(E.indexBuffer,0,t.buffer,t.byteOffset,t.byteLength),s&&p.writeBuffer(E.uvBuffer,0,i.buffer,i.byteOffset,i.byteLength),c&&p.writeBuffer(E.uv2Buffer,0,o.buffer,o.byteOffset,o.byteLength),l&&p.writeBuffer(E.tangentBuffer,0,Q.buffer,Q.byteOffset,Q.byteLength),D&&p.writeBuffer(E.colorBuffer,0,r.buffer,r.byteOffset,r.byteLength),vF(A,g,I,e,t,i,o,Q,r),OR(g)}function MnA(A,g,I,e,t,i,o,Q,r,E=1.25){(!Number.isFinite(E)||E<1)&&U(366);const n=dnA(g,I,e,t,i,o,Q,r),s=g._gpu,c=s._vertexCapacity??(g._cpuPositions?g._cpuPositions.length/3:n),l=s._indexCapacity??s.indexCount;if(n>c||t.length>l){const y=n>c?Math.ceil(n*E):c,_=t.length>l?Math.ceil(t.length*E):l,u=Math.ceil(_/3)*3,f=new Float32Array(y*3),h=new Float32Array(y*3),w=new Uint32Array(u);f.set(I),h.set(e),w.set(t);const M=i?.length?new Float32Array(y*2):void 0,S=o?.length?new Float32Array(y*2):void 0,R=Q?.length?new Float32Array(y*4):void 0,N=r?.length?new Float32Array(y*4):void 0;return M?.set(i),S?.set(o),R?.set(Q),N?.set(r),WH(A,g,f,h,w,M,S,R,N),g._gpu._vertexCapacity=y,g._gpu._indexCapacity=u,g._gpu._indexScratch=w,vF(A,g,I,e,t,i,o,Q,r),{stable:!1,vertexCapacity:y,indexCapacity:u}}s._vertexCapacity=c,s._indexCapacity=l;const D=s._indexScratch?.length===l?s._indexScratch:s._indexScratch=new Uint32Array(l);D.fill(0),D.set(t);const p=A._device.queue;return p.writeBuffer(s.positionBuffer,0,I.buffer,I.byteOffset,I.byteLength),p.writeBuffer(s.normalBuffer,0,e.buffer,e.byteOffset,e.byteLength),p.writeBuffer(s.indexBuffer,0,D.buffer,D.byteOffset,D.byteLength),i?.length&&p.writeBuffer(s.uvBuffer,0,i.buffer,i.byteOffset,i.byteLength),o?.length&&p.writeBuffer(s.uv2Buffer,0,o.buffer,o.byteOffset,o.byteLength),Q?.length&&p.writeBuffer(s.tangentBuffer,0,Q.buffer,Q.byteOffset,Q.byteLength),r?.length&&p.writeBuffer(s.colorBuffer,0,r.buffer,r.byteOffset,r.byteLength),vF(A,g,I,e,t,i,o,Q,r),OR(g),{stable:!0,vertexCapacity:c,indexCapacity:l}}function WH(A,g,I,e,t,i,o,Q,r){const E=g._gpu;VH(A),g._gpu=I4(A,I,e,t,i,o,Q,r),vF(A,g,I,e,t,i,o,Q,r),OR(g),DC(E)&&G1(A,()=>{E.positionBuffer.destroy(),E.normalBuffer.destroy(),E.indexBuffer.destroy(),E.uvBuffer.destroy(),E.uv2Buffer?.destroy(),E.tangentBuffer?.destroy(),E.colorBuffer?.destroy()})}function SnA(A,g,I,e=0,t,i=0){const o=g._gpu;o.normalBuffer&&Ir(A,g,o.normalBuffer,I,3,e,t,i)}function zH(A,g,I,e=0,t,i=0){const o=g._gpu;o.colorBuffer&&Ir(A,g,o.colorBuffer,I,4,e,t,i)}function RnA(A,g,I,e=0,t,i=0){const o=g._gpu;o.uvBuffer&&Ir(A,g,o.uvBuffer,I,2,e,t,i)}function NnA(A,g,I,e=0,t,i=0){const o=g._gpu;o.uv2Buffer&&Ir(A,g,o.uv2Buffer,I,2,e,t,i)}function GnA(A,g,I,e=0,t,i=0){const o=g._gpu;o.tangentBuffer&&Ir(A,g,o.tangentBuffer,I,4,e,t,i)}function oN(A,g){const I=vH(g);return Et(A,"sphere",I.positions,I.normals,I.indices,I.uvs)}function gC(A,g=1){const I=e4(g);return Et(A,"box",I.positions,I.normals,I.indices,I.uvs)}function BN(A,g){const I=nnA(g);return Et(A,"torus",I.positions,I.normals,I.indices,I.uvs)}function FnA(A,g){const I=HH(g);return Et(A,"torusKnot",I.positions,I.normals,I.indices,I.uvs)}async function mnA(A,g,I){const e=await anA(g,I);return Et(A,"ground",e.positions,e.normals,e.indices,e.uvs)}function bnA(A,g){const I=TH(g);return Et(A,"ground",I.positions,I.normals,I.indices,I.uvs)}function Wt(A,g){const I=xH(g);return Et(A,"cylinder",I.positions,I.normals,I.indices,I.uvs)}function KnA(A,g){const I=qH(g);return Et(A,"capsule",I.positions,I.normals,I.indices,I.uvs)}function E4(A,g){const I=cnA(g);return Et(A,"plane",I.positions,I.normals,I.indices,I.uvs)}function ZH(A,g){const I=lnA(g);return Et(A,"disc",I.positions,I.normals,I.indices,I.uvs)}function XH(A,g){const I=DnA(g);return Et(A,"polyhedron",I.positions,I.normals,I.indices,I.uvs)}function knA(A,g){const I=o4(g);return Et(A,"ribbon",I.positions,I.normals,I.indices,I.uvs)}function UnA(A,g){const I=unA(g);return Et(A,"tube",I.positions,I.normals,I.indices,I.uvs)}function LnA(A,g){const I=fnA(g);return Et(A,"extrude",I.positions,I.normals,I.indices,I.uvs)}const yC=1,TF=2,QN=4,rN=8,xF=16,qF=32,co=64,PF=128,OF=256,jF=512,VF=1024,EN=2048,$H=4096,AT=8192,gT=16384,lo=65536,IT=1<<17,WF=1<<18,eT=1<<19,er=1<<20,YnA=1<<21,tT=32768,CT=1<<22,n4=1<<24,zF=1<<26,s4=1<<27,JnA=1;let a4=null,ZF=null;function _C(A){(a4??=new Map).set(A._id,A),ZF=null}function iT(){return a4??=new Map}function XF(){if(!ZF){const A=a4;ZF=A?Array.from(A.values()).sort((g,I)=>g._id.localeCompare(I._id)):[]}return ZF}const BQ=yC|TF|QN|rN|xF|qF|co,c4=PF|OF|VF|EN;let l4=null;function D4(A,g){const I=A().then(e=>{_C(e[g])});return(l4??=[]).push(I),I}let p4=null;function $F(){if(p4)return p4;const A=async(g,I)=>{const e=I.some(u=>!!u.thinInstances),t=I.some(u=>!!u.thinInstances?._gpuCullingEnabled),i=I.some(u=>u.receiveShadows)&&g.lights.some(u=>!!u.shadowGenerator),o=I.some(u=>!!u.morphTargets);let Q,r,E,n,s,c,l=null;const D=[];if(e&&(D.push(Promise.resolve().then(()=>A5).then(u=>{Q=u.syncThinInstanceBuffers,r=u.syncThinInstanceForDraw}),Promise.resolve().then(()=>g5).then(u=>{E=u.createThinInstanceFragment})),t&&D.push(Promise.resolve().then(()=>o5).then(u=>{c=u}))),i&&D.push(Promise.resolve().then(()=>D5A).then(u=>{n=u.createStdShadowFragment})),o&&D.push(Promise.resolve().then(()=>_5A).then(u=>{s=u.createMorphFragment})),g.fog&&D.push(Promise.resolve().then(()=>h5A).then(u=>{l=u.createStandardFogFragment()})),l4)for(const u of l4)D.push(u);D.length>0&&await Promise.all(D);const p=await Promise.resolve().then(()=>d5A),y=g.fog?{_features:JnA,_fragments:[l]}:null,_=p.buildStandardMeshRenderables(g,I,{tiSync:Q,tiUpdate:r,tiFragment:E,shadowFragment:n,morphFragment:s,cull:c,sceneShader:y});return A._rebuildSingle=_.rebuildSingle,_};return A._materialFamily="standard",p4=A}function nt(){return{diffuseColor:[1,1,1],alpha:1,specularColor:[1,1,1],specularPower:64,emissiveColor:[0,0,0],ambientColor:[0,0,0],diffuseTexture:null,diffuseCoordIndex:0,bumpLevel:1,specularCoordIndex:0,ambientTexLevel:1,ambientCoordIndex:0,lightmapLevel:1,lightmapCoordIndex:1,useLightmapAsShadowmap:!1,opacityLevel:1,opacityFromRGB:!1,alphaCutOff:0,reflectionLevel:1,reflectionCoordMode:1,uvScale:[1,1],backFaceCulling:!0,disableLighting:!1,_buildGroup:$F(),_uboVersion:0}}function Do(){return{hit:!1,distance:0,pickedPoint:null,pickedNormal:null,pickedNormalWorld:null,pickedFaceNormal:null,pickedFaceNormalWorld:null,pickedMesh:null,faceId:-1,bu:0,bv:0,subMeshId:0,thinInstanceIndex:-1,ray:null,_normalsInvalid:!1}}function oT(A,g){const I=[],e=g?.predicate;for(const t of A){if(!g?.skipPickableCheck&&t.pickable===!1||e&&!e(t))continue;const i=TnA(t);if(!i)continue;const o=lt(t.worldMatrix);o&&I.push({mesh:t,aabb:i,invWorld:o})}return{candidates:I}}function BT(A,g){return oT(A.meshes,g)}let vnA=null;function HnA(){return vnA??=new WeakMap}function TnA(A){const g=A._cpuPositions;if(!g||g.length<3)return null;const I=HnA(),e=I.get(g);if(e)return e;let t=1/0,i=1/0,o=1/0,Q=-1/0,r=-1/0,E=-1/0;for(let s=0;s<g.length;s+=3){const c=g[s],l=g[s+1],D=g[s+2];c<t&&(t=c),l<i&&(i=l),D<o&&(o=D),c>Q&&(Q=c),l>r&&(r=l),D>E&&(E=D)}const n={min:[t,i,o],max:[Q,r,E]};return I.set(g,n),n}function xnA(A,g,I,e,t){const i=A[0]*g+A[4]*I+A[8]*e+A[12],o=A[1]*g+A[5]*I+A[9]*e+A[13],Q=A[2]*g+A[6]*I+A[10]*e+A[14],r=A[3]*g+A[7]*I+A[11]*e+A[15],E=r!==0?1/r:1;t[0]=i*E,t[1]=o*E,t[2]=Q*E}function qnA(A,g,I,e,t){t[0]=A[0]*g+A[4]*I+A[8]*e,t[1]=A[1]*g+A[5]*I+A[9]*e,t[2]=A[2]*g+A[6]*I+A[10]*e}function PnA(A,g,I,e,t,i,o,Q,r){let E=0,n=Q,s=-1;const c=[A,g,I],l=[e,t,i];for(let D=0;D<3;D++){const p=o.min[D],y=o.max[D],_=l[D],u=c[D];if(Math.abs(_)<1e-12){if(u<p||u>y)return-1}else{const f=1/_;let h=(p-u)*f,w=(y-u)*f;if(h>w){const M=h;h=w,w=M}if(h>E&&(E=h,s=D),w<n&&(n=w),E>n)return-1}}return r[0]=s,E}function Am(A,g,I){const e=Do();e.ray=g;const t=I?.predicate,[i,o,Q]=g.origin,[r,E,n]=g.direction,s=[0,0,0],c=[0,0,0],l=[-1];let D=g.length,p=null,y=-1,_=0,u=null;for(const f of A.candidates){const h=f.mesh;if(t&&!t(h))continue;const{aabb:w,invWorld:M}=f;xnA(M,i,o,Q,s),qnA(M,r,E,n,c),l[0]=-1;const S=PnA(s[0],s[1],s[2],c[0],c[1],c[2],w,D,l);S>=0&&S<D&&(D=S,p=h,y=l[0],_=y>=0?Math.sign(c[y]):0,u=M)}if(p&&(e.hit=!0,e.distance=D,e.pickedMesh=p,e.pickedPoint=[i+r*D,o+E*D,Q+n*D],y>=0&&u)){const f=[0,0,0];f[y]=-_,e.pickedNormal=[f[0],f[1],f[2]];const h=u;let w=h[0]*f[0]+h[1]*f[1]+h[2]*f[2],M=h[4]*f[0]+h[5]*f[1]+h[6]*f[2],S=h[8]*f[0]+h[9]*f[1]+h[10]*f[2];const R=Math.hypot(w,M,S)||1;w/=R,M/=R,S/=R,e.pickedNormalWorld=[w,M,S]}return e}function QT(A,g,I){return Am(BT(A,I),g)}function OnA(A,g,I){return Am(oT(A,I),g)}function _i(A){const g=AC(A);g._uboVersion++}const ui={maxLength:10,laserColor:[.7,.7,.7],laserPickedColor:[.9,.9,.9],cursorColor:[.8,.8,.8],cursorPickedColor:[.3,.3,1],laserThickness:.004,cursorSize:.03,enableOnAllControllers:!1,disableSwitchOnClick:!1},jnA=.02;function rT(A,g,I,e){const t=I>=0&&Number.isFinite(I),i=Math.max(1e-4,t?I:e),o=i*.5,Q=[A[0]+g[0]*o,A[1]+g[1]*o,A[2]+g[2]*o],r=t?[A[0]+g[0]*I,A[1]+g[1]*I,A[2]+g[2]*I]:[0,0,0];return{hit:t,beamLength:i,laserPosition:Q,cursorPosition:r}}function ET(A,g,I={}){return{_engine:A,_scene:g,_options:{maxLength:I.maxLength??ui.maxLength,laserColor:I.laserColor??ui.laserColor,laserPickedColor:I.laserPickedColor??ui.laserPickedColor,cursorColor:I.cursorColor??ui.cursorColor,cursorPickedColor:I.cursorPickedColor??ui.cursorPickedColor,laserThickness:I.laserThickness??ui.laserThickness,cursorSize:I.cursorSize??ui.cursorSize,enableOnAllControllers:I.enableOnAllControllers??ui.enableOnAllControllers,disableSwitchOnClick:I.disableSwitchOnClick??ui.disableSwitchOnClick,predicate:I.predicate,preferredHandedness:I.preferredHandedness,onHoverStart:I.onHoverStart,onHoverEnd:I.onHoverEnd,onSelect:I.onSelect},_units:new Map,_activeSource:null}}function nT(A,g=!1){const I=nt();return I.diffuseColor=[1,1,1],I.emissiveColor=[A[0],A[1],A[2]],I.disableLighting=!0,g&&(I.backFaceCulling=!1),I}function VnA(A,g){const I=g[1];if(I<-.999999){A.rotationQuaternion.set(1,0,0,0);return}const e=g[2],t=0,i=-g[0],o=1+I,Q=Math.hypot(e,t,i,o)||1;A.rotationQuaternion.set(e/Q,t/Q,i/Q,o/Q)}function WnA(A,g){const I=A._units.get(g);if(I)return I;const e=A._engine,t=A._options,i=gC(e,1);i.name="xr-pointer-laser";const o=nT(t.laserColor);i.material=o,i.pickable=!1,i.receiveShadows=!1,i.visible=!1;const Q=BN(e,{diameter:t.cursorSize,thickness:t.cursorSize*.12,tessellation:24});Q.name="xr-pointer-cursor";const r=nT(t.cursorColor,!0);Q.material=r,Q.pickable=!1,Q.receiveShadows=!1,Q.visible=!1,JI(A._scene,i),JI(A._scene,Q);const E={laser:i,cursor:Q,laserMat:o,cursorMat:r,hovered:null,lastInput:null,picked:!1,wasSelecting:!1};return A._units.set(g,E),E}function sT(A,g){g.hovered&&(g.lastInput&&A._options.onHoverEnd?.(g.hovered,g.lastInput),g.hovered=null),ct(A._scene,g.laser),ct(A._scene,g.cursor),X1(g.laser),X1(g.cursor)}function aT(A,g,I){const e=A._options,t=A._scene,i=new Set,o=!e.enableOnAllControllers;for(const r of g.inputSources)i.add(r.source),WnA(A,r.source);let Q=null;if(o&&!e.disableSwitchOnClick)for(const r of g.inputSources){const E=A._units.get(r.source);r.selecting&&!E.wasSelecting&&r.source!==A._activeSource&&(A._activeSource=r.source,Q=r.source)}if(o&&!(A._activeSource!==null&&i.has(A._activeSource))){A._activeSource=null;const E=e.preferredHandedness;let n=null;for(const s of g.inputSources)if(n??=s.source,E!==void 0&&s.handedness===E){A._activeSource=s.source;break}A._activeSource??=n}for(const r of g.inputSources){const E=A._units.get(r.source);if(E.lastInput=r,!(!o||r.source===A._activeSource)||!r.targetRayTracked){ke(E.laser,!1),ke(E.cursor,!1),E.hovered&&(e.onHoverEnd?.(E.hovered,r),E.hovered=null),E.wasSelecting=r.selecting;continue}const s=r.targetRayMatrix,c=[s[12],s[13],s[14]];let l=s[8],D=s[9],p=s[10];const y=Math.hypot(l,D,p)||1;l/=y,D/=y,p/=y;const _=[l,D,p],u=QT(t,{origin:c,direction:_,length:e.maxLength},{predicate:e.predicate}),f=u.hit&&u.distance>jnA,h=f?u.pickedMesh:null,w=rT(c,_,f?u.distance:-1,e.maxLength),M=LC(s).rotation;if(E.laser.rotationQuaternion.set(M.x,M.y,M.z,M.w),E.laser.position.set(w.laserPosition[0],w.laserPosition[1],w.laserPosition[2]),E.laser.scaling.set(e.laserThickness,e.laserThickness,w.beamLength),ke(E.laser,!0),w.hit){const R=w.cursorPosition,N=I&&Math.hypot(R[0]-I[0],R[1]-I[1],R[2]-I[2])||u.distance,F=.003*N,G=u.pickedNormalWorld??[-l,-D,-p];E.cursor.position.set(R[0]+G[0]*F,R[1]+G[1]*F,R[2]+G[2]*F),E.cursor.scaling.set(N,N,N),VnA(E.cursor,G),ke(E.cursor,!0)}else ke(E.cursor,!1);const S=h!==null;if(S!==E.picked){const R=S?e.laserPickedColor:e.laserColor,N=S?e.cursorPickedColor:e.cursorColor;E.laserMat.emissiveColor=[R[0],R[1],R[2]],E.cursorMat.emissiveColor=[N[0],N[1],N[2]],_i(E.laserMat),_i(E.cursorMat),E.picked=S}h!==E.hovered&&(E.hovered&&e.onHoverEnd?.(E.hovered,r),h&&e.onHoverStart?.(h,r),E.hovered=h),r.selecting&&!E.wasSelecting&&h&&r.source!==Q&&e.onSelect?.(h,u,r),E.wasSelecting=r.selecting}for(const[r,E]of A._units)i.has(r)||(sT(A,E),A._units.delete(r));A._activeSource!==null&&!i.has(A._activeSource)&&(A._activeSource=null)}function cT(A){for(const g of A._units.values())sT(A,g);A._units.clear()}function znA(A={}){return{create(g){g.input||U(605);const I=g.input,e=ET(g.engine,g.scene,A);return{update(t){const o=t.getViewerPose?.(g.referenceSpace)?.transform.position,Q=o?[o.x,o.y,-o.z]:null;aT(e,I,Q)},dispose(){cT(e)}}}}}function tr(A,g){const I=A[g];return I?{pressed:I.pressed,touched:I.touched,value:I.value}:null}function lT(A,g,I){const e=A[g],t=A[I];return e===void 0||t===void 0?null:[e,t]}function ZnA(A){const g=A.gamepad;if(!g)return null;const I=g.buttons,e=g.axes;return{handedness:A.handedness,trigger:tr(I,0),squeeze:tr(I,1),touchpad:tr(I,2),thumbstick:tr(I,3),buttonA:tr(I,4),buttonB:tr(I,5),touchpadAxes:lT(e,0,1),thumbstickAxes:lT(e,2,3)}}function gm(A){const g=[],I=new Set,e=t=>{if(I.has(t))return;I.add(t),t._gpu&&g.push(t);const i=t.children;if(i)for(const o of i)e(o)};for(const t of A.entities)"lightType"in t||e(t);return g}function XnA(A){return A==="left"?[.3,.5,.9]:A==="right"?[.9,.5,.3]:[.6,.6,.6]}function $nA(A,g,I){const e=gC(A,1);e.name=`xr-controller-${I}`;const t=nt();return t.diffuseColor=XnA(I),e.material=t,e.pickable=!1,e.receiveShadows=!1,e.scaling.set(.04,.04,.12),e.visible=!1,e}const Cr=[.55,.72,1];function AsA(A,g,I){const e=gC(A,1);e.name=`xr-controller-loading-${I}`;const t=nt();return t.diffuseColor=[1,1,1],t.emissiveColor=[Cr[0],Cr[1],Cr[2]],t.disableLighting=!0,t.alpha=.45,e.material=t,e.pickable=!1,e.receiveShadows=!1,e.scaling.set(.035,.035,.11),e.visible=!1,e}function DT(A,g,I={}){const e=I.profiles?I.profiles===!0?{}:I.profiles:null,t=!I.meshFactory&&e!==null;return{_engine:A,_scene:g,_factory:I.meshFactory??(t?AsA:$nA),_loadingStyle:t,_profiles:e,_mod:null,_units:new Map}}function gsA(A){A._mod||!A._profiles||Promise.resolve().then(()=>m0A).then(g=>{A._mod=g}).catch(()=>{A._profiles=null})}function y4(A,g){ct(A._scene,g.container);for(const I of gm(g.container))X1(I)}function IsA(A,g,I){const e=A._mod,t=A._profiles;!e||!t||I.loadStarted||(I.loadStarted=!0,(async()=>{try{const i=await e.loadMotionController(A._engine,g,I.handedness,t);if(!i)return;if(I.retired){y4(A,i);return}for(const Q of gm(i.container))Q.pickable=!1;const{enableMirroredMeshes:o}=await Promise.resolve().then(()=>Rq);if(await o(A._scene),I.retired){y4(A,i);return}JI(A._scene,i.container),ke(i.root,!1),I.model=i,I.active=i.root,I.visible=!1,I.mesh&&(ct(A._scene,I.mesh),X1(I.mesh),I.mesh=null)}catch{}})())}function esA(A,g,I){const e=A._units.get(g);if(e)return e;const t=A._factory(A._engine,A._scene,I);JI(A._scene,t);const i=A._loadingStyle?t.material:null,o={handedness:I,mesh:t,model:null,placeholderMat:i,active:t,loadStarted:!1,retired:!1,visible:null};return A._units.set(g,o),o}function pT(A,g){g.retired=!0,g.mesh&&(ct(A._scene,g.mesh),X1(g.mesh),g.mesh=null),g.model&&(y4(A,g.model),g.model=null)}function yT(A,g){A.visible!==g&&(A.model?ke(A.active,g):A.mesh&&ke(A.mesh,g),A.visible=g)}function _T(A,g){const I=new Set;gsA(A);for(const e of g.inputSources){if(e.source.hand)continue;I.add(e.source);const t=esA(A,e.source,e.handedness);if(IsA(A,e.source,t),!e.gripTracked){yT(t,!1);continue}const i=e.gripMatrix,o=LC(i).rotation;if(t.active.position.set(i[12],i[13],i[14]),t.model?t.active.rotationQuaternion.set(-o.z,o.w,o.x,-o.y):t.active.rotationQuaternion.set(o.x,o.y,o.z,o.w),yT(t,!0),t.placeholderMat&&t.mesh&&!t.model){const Q=.5+.5*Math.sin(performance.now()*.004);t.placeholderMat.alpha=.25+.35*Q;const r=.6+.4*Q;t.placeholderMat.emissiveColor=[Cr[0]*r,Cr[1]*r,Cr[2]*r],_i(t.placeholderMat)}t.model&&A._mod&&A._mod.updateMotionController(t.model,e.source.gamepad??null)}for(const[e,t]of A._units)I.has(e)||(pT(A,t),A._units.delete(e))}function uT(A){for(const g of A._units.values())pT(A,g);A._units.clear()}function tsA(A={}){return{create(g){g.input||U(603);const I=g.input,e=DT(g.engine,g.scene,A);return{update(){_T(e,I)},dispose(){uT(e)}}}}}const CsA=[.7,.78,.95],isA=[.455,.247,.796],osA=.008,BsA="https://assets.babylonjs.com/core/HandMeshes/",QsA="r_hand_rhs.glb",rsA="l_hand_rhs.glb";function EsA(A){return(g,I,e)=>{const t=oN(g,{diameter:1,segments:8});t.name=`xr-hand-${e}-joint`;const i=nt();return i.diffuseColor=[A[0],A[1],A[2]],t.material=i,t.pickable=!1,t.receiveShadows=!1,t.visible=!1,t}}function hT(A,g,I={}){return{_engine:A,_scene:g,_factory:I.jointMeshFactory??EsA(I.jointColor??CsA),_jointScale:I.jointScale??1,_handMeshes:I.handMeshes??!0,_handMeshOpts:{baseUrl:I.handMeshBaseUrl??BsA,leftFilename:I.handMeshLeftFilename??rsA,rightFilename:I.handMeshRightFilename??QsA,color:I.handColor??isA,alpha:I.handAlpha??1},_mod:null,_modLoading:!1,_units:new Map}}function nsA(A){A._mod||A._modLoading||!A._handMeshes||(A._modLoading=!0,Promise.resolve().then(()=>R5A).then(g=>{A._mod=g}).catch(()=>{A._handMeshes=!1}))}function ssA(A,g){const I=A._mod;!I||g.meshLoadStarted||(g.meshLoadStarted=!0,(async()=>{try{const e=await I.loadHandMesh(A._engine,A._scene,g.handedness,A._handMeshOpts);if(!e)return;if(g.retired){I.disposeHandMesh(A._scene,e);return}g.mesh=e,fT(A,g)}catch{}})())}function asA(A,g,I){const e=A._units.get(g);if(e)return e;const t={handedness:I,joints:new Map,mesh:null,meshLoadStarted:!1,retired:!1};return A._units.set(g,t),t}function csA(A,g,I){const e=g.joints.get(I);if(e)return e;const t=A._factory(A._engine,A._scene,g.handedness);return t.name=`xr-hand-${g.handedness}-${I}`,JI(A._scene,t),g.joints.set(I,t),t}function fT(A,g){for(const I of g.joints.values())ct(A._scene,I),X1(I);g.joints.clear()}function dT(A,g){g.retired=!0,fT(A,g),g.mesh&&A._mod&&(A._mod.disposeHandMesh(A._scene,g.mesh),g.mesh=null)}function wT(A,g,I,e){const t=new Set,i=I.getJointPose;A._handMeshes&&nsA(A);for(const o of g.inputSources){const Q=o.source.hand;if(!Q)continue;t.add(o.source);const r=asA(A,o.source,o.handedness);if(A._handMeshes&&(r.mesh||ssA(A,r),r.mesh)){A._mod.poseHandMesh(r.mesh,Q,I,e);continue}if(i)for(const[E,n]of Q){const s=csA(A,r,E),c=i.call(I,n,e);if(!c){ke(s,!1);continue}const l=(c.radius??osA)*2*A._jointScale;XEA(s,c.transform),s.scaling.set(l,l,l),ke(s,!0)}}for(const[o,Q]of A._units)t.has(o)||(dT(A,Q),A._units.delete(o))}function MT(A){for(const g of A._units.values())dT(A,g);A._units.clear()}function lsA(A={}){return{sessionFeatures:["hand-tracking"],create(g){g.input||U(604);const I=g.input,e=hT(g.engine,g.scene,A);return{update(t){wT(e,I,t,g.referenceSpace)},dispose(){MT(e)}}}}}const DsA=[.3,.6,1],psA=[1,.25,.25],_4=.4,ysA=.008,IC=32,_sA=.3,usA=.13,hsA=.05,fsA=.02,dsA=.6,wsA=.2,MsA=.35;function SsA(A){if(A.floorMeshes){const g=new Set(A.floorMeshes);return I=>g.has(I)}if(A.floorPredicate){const g=A.floorPredicate;return I=>g(I)}return(g,I)=>I!==null&&I[1]>=dsA}function RsA(A){const g=A.pickBlockerMeshes?new Set(A.pickBlockerMeshes):null,I=A.blockerPredicate;return!g&&!I?()=>!1:e=>g!==null&&g.has(e)||I!==void 0&&I(e)}function u4(A,g,I){const e=nt();return e.diffuseColor=[1,1,1],e.emissiveColor=[A[0],A[1],A[2]],e.disableLighting=!0,e.alpha=g,I&&(e.backFaceCulling=!1),e}function ST(A,g,I={}){const e=I.color??DsA,t=I.blockedColor??psA;return{_engine:A,_scene:g,_options:{color:[e[0],e[1],e[2]],blockedColor:[t[0],t[1],t[2]],blockAllPickableMeshes:I.blockAllPickableMeshes??!1,maxLength:I.maxLength??20,parabolic:I.parabolic??!0,parabolaSpeed:I.parabolaSpeed??7,gravity:I.gravity??9.8,rotateToDirection:I.rotateToDirection??!0,snapTurn:I.snapTurn??!0,rotationAngle:I.rotationAngle??Math.PI/4,thumbstickThreshold:I.thumbstickThreshold??.7},_isFloor:SsA(I),_isBlocker:RsA(I),_floorY:0,_units:new Map}}function NsA(){const A=new Uint32Array((IC-1)*6);for(let g=0;g<IC-1;g++){const I=2*g,e=2*g+1,t=2*g+2,i=2*g+3,o=g*6;A[o]=I,A[o+1]=e,A[o+2]=t,A[o+3]=e,A[o+4]=i,A[o+5]=t}return A}function GsA(A,g){const I=A._units.get(g);if(I)return I;const e=A._options.color,t=A._engine,i=new Float32Array(2*IC*3),o=new Float32Array(2*IC*3);for(let D=0;D<2*IC;D++)o[D*3+1]=1;const Q=Et(t,"xr-teleport-arc",i.slice(),o,NsA()),r=u4(e,.85,!0);Q.material=r,Q.pickable=!1,Q.receiveShadows=!1,Q.visible=!1;const E=BN(t,{diameter:_4,thickness:_4*.14,tessellation:40});E.name="xr-teleport-reticle",E.material=u4(e,1,!1),E.pickable=!1,E.receiveShadows=!1,E.visible=!1;const n=usA,s=_sA,c=Et(t,"xr-teleport-arrow",new Float32Array([-n,0,0,n,0,0,0,0,s]),new Float32Array([0,1,0,0,1,0,0,1,0]),new Uint32Array([0,1,2]));c.material=u4(e,1,!0),c.pickable=!1,c.receiveShadows=!1,c.visible=!1,JI(A._scene,Q),JI(A._scene,E),JI(A._scene,c);const l={arc:Q,arcMat:r,arcBlocked:!1,reticle:E,indicator:c,arcPath:new Float32Array(IC*3),arcVerts:i,aiming:!1,target:null,landingTurn:0,turnLatched:!1};return A._units.set(g,l),l}function RT(A,g){ct(A._scene,g.arc),ct(A._scene,g.reticle),ct(A._scene,g.indicator),X1(g.arc),X1(g.reticle),X1(g.indicator)}function FsA(A,g){const I=g[2],e=-g[0],t=g[1];if(t>.99999){A.rotationQuaternion.set(0,0,0,1);return}if(t<-.99999){A.rotationQuaternion.set(1,0,0,0);return}const i=Math.hypot(I,0,e)||1,Q=Math.atan2(i,t)/2,r=Math.sin(Q)/i;A.rotationQuaternion.set(I*r,0,e*r,Math.cos(Q))}function msA(A){const g=A.axes,I=(g.length>2?g[2]:g[0])??0,e=(g.length>3?g[3]:g[1])??0;return[I,e]}function bsA(A){const g=A.transform.orientation;if(!g)return null;const I=-2*(g.x*g.z+g.w*g.y),e=1-2*(g.x*g.x+g.y*g.y),t=Math.hypot(I,e)||1;return[I/t,0,e/t]}function KsA(A,g){const I=Math.cos(g),e=Math.sin(g);return[A[0]*I+A[2]*e,0,-A[0]*e+A[2]*I]}function ksA(A,g,I,e){const t=A._options,i=t.parabolaSpeed,o=t.parabolic?t.gravity:0,Q=BT(A._scene),r=t.maxLength/i;e[0]=g[0],e[1]=g[1],e[2]=g[2];let E=g[0],n=g[1],s=g[2];for(let c=1;c<IC;c++){const l=c/(IC-1),D=r*l*l,p=g[0]+I[0]*i*D,y=g[1]+I[1]*i*D-.5*o*D*D,_=g[2]+I[2]*i*D,u=p-E,f=y-n,h=_-s,w=Math.hypot(u,f,h)||1e-6,M={origin:[E,n,s],direction:[u/w,f/w,h/w],length:w};let S=Am(Q,M),R=null;for(;S.hit&&S.pickedMesh;){const N=S.pickedMesh;if(A._isBlocker(N)||A._isFloor(N,S.pickedNormalWorld)||t.blockAllPickableMeshes)break;if(R?.includes(N)){S.hit=!1;break}(R??=[]).push(N),S=Am(Q,M,{predicate:F=>!R.includes(F)})}if(S.hit&&S.pickedPoint){const N=S.pickedPoint;for(let F=c;F<IC;F++)e[F*3]=N[0],e[F*3+1]=N[1],e[F*3+2]=N[2];return{hit:!0,point:[N[0],N[1],N[2]],normal:S.pickedNormalWorld,mesh:S.pickedMesh}}e[c*3]=p,e[c*3+1]=y,e[c*3+2]=_,E=p,n=y,s=_}return{hit:!1,point:[E,n,s],normal:null,mesh:null}}function UsA(A,g,I){const e=g.arcPath,t=g.arcVerts,i=ysA;for(let o=0;o<IC;o++){const Q=e[o*3],r=e[o*3+1],E=e[o*3+2],n=o>0?o-1:0,s=o<IC-1?o+1:IC-1,c=e[s*3]-e[n*3],l=e[s*3+1]-e[n*3+1],D=e[s*3+2]-e[n*3+2],p=I[0]-Q,y=I[1]-r,_=I[2]-E;let u=l*_-D*y,f=D*p-c*_,h=c*y-l*p;const w=Math.hypot(u,f,h)||1;u=u/w*i,f=f/w*i,h=h/w*i;const M=o*6;t[M]=Q+u,t[M+1]=r+f,t[M+2]=E+h,t[M+3]=Q-u,t[M+4]=r-f,t[M+5]=E-h}HF(A._engine,g.arc,t)}function LsA(A,g,I){const e=_4/2+hsA;A.position.set(g[0]+I[0]*e,g[1]+fsA,g[2]+I[2]*e);const i=Math.atan2(I[0],I[2])/2;A.rotationQuaternion.set(0,Math.sin(i),0,Math.cos(i))}function YsA(A,g,I,e){const t={x:g[0]-I[0],y:e-I[1],z:-(g[2]-I[2])};return A.getOffsetReferenceSpace(new XRRigidTransform(t))}function NT(A,g,I){const e=Math.cos(I),t=Math.sin(I),i=g[0]*e-g[2]*t,o=g[0]*t+g[2]*e,Q=I/2,r={x:0,y:Math.sin(Q),z:0,w:Math.cos(Q)};return A.getOffsetReferenceSpace(new XRRigidTransform({x:g[0]-i,y:0,z:-(g[2]-o)},r))}function GT(A,g,I,e){const t=new Set,i=A._options;let o=e;for(const Q of g.inputSources){const r=Q.source.gamepad;if(!r)continue;t.add(Q.source);const E=GsA(A,Q.source),[n,s]=msA(r),c=Math.hypot(n,s),l=c<wsA;if(s<=-i.thumbstickThreshold&&(E.aiming=!0),!E.aiming)if(i.snapTurn&&Math.abs(n)>=i.thumbstickThreshold&&Math.abs(s)<i.thumbstickThreshold){if(!E.turnLatched){const D=I.getViewerPose(o);if(D){const p=D.transform.position;o=NT(o,[p.x,p.y,-p.z],n>0?i.rotationAngle:-i.rotationAngle)}E.turnLatched=!0}}else Math.abs(n)<i.thumbstickThreshold*.5&&(E.turnLatched=!1);if(E.aiming&&!l){if(Q.targetRayTracked){const D=Q.targetRayMatrix,p=[D[12],D[13],D[14]];let y=D[8],_=D[9],u=D[10];const f=Math.hypot(y,_,u)||1;y/=f,_/=f,u/=f;const w=ksA(A,p,[y,_,u],E.arcPath),M=I.getViewerPose(o),S=M?[M.transform.position.x,M.transform.position.y,-M.transform.position.z]:p;UsA(A,E,S),ke(E.arc,!0);const R=w.hit?w.mesh:null,N=R!==null&&A._isBlocker(R),F=!N&&w.hit&&A._isFloor(R,w.normal),G=w.hit&&!F&&(N||i.blockAllPickableMeshes&&R?.pickable!==!1);if(G!==E.arcBlocked){const m=G?i.blockedColor:i.color;E.arcMat.emissiveColor=[m[0],m[1],m[2]],_i(E.arcMat),E.arcBlocked=G}if(F)if(E.target=w.point,E.reticle.position.set(w.point[0],w.point[1],w.point[2]),FsA(E.reticle,w.normal??[0,1,0]),ke(E.reticle,!0),i.rotateToDirection){c>=MsA&&(E.landingTurn=Math.atan2(n,-s));const m=M?bsA(M):null;m?(LsA(E.indicator,w.point,KsA(m,E.landingTurn)),ke(E.indicator,!0)):ke(E.indicator,!1)}else E.landingTurn=0,ke(E.indicator,!1);else E.target=null,E.landingTurn=0,ke(E.reticle,!1),ke(E.indicator,!1)}}else if(E.aiming&&l){if(E.target){const D=I.getViewerPose(o);if(D){const p=D.transform.position,y=E.target;o=YsA(o,[p.x,p.y,-p.z],y,A._floorY),A._floorY=y[1],i.rotateToDirection&&Math.abs(E.landingTurn)>1e-4&&(o=NT(o,y,E.landingTurn))}}E.aiming=!1,E.turnLatched=!1,E.target=null,E.landingTurn=0,ke(E.arc,!1),ke(E.reticle,!1),ke(E.indicator,!1)}}for(const[Q,r]of A._units)t.has(Q)||(RT(A,r),A._units.delete(Q));return o}function FT(A){for(const g of A._units.values())RT(A,g);A._units.clear()}function JsA(A={}){return{create(g){g.input||U(608);const I=g.input,e=ST(g.engine,g.scene,A);return{update(t){g._referenceSpace=GT(e,I,t,g._referenceSpace)},dispose(){FT(e)}}}}}function b1(A,g=0,I=0,e=0,t=0,i=0,o=0,Q=1,r=1,E=1,n=1){return onA(A,g,I,e,t,i,o,Q,r,E,n)}function h4(A){if("_gpu"in A)return vsA(A);const g=A._localMatrix?g4(A.name+"_clone",A._localMatrix):b1(A.name+"_clone",A.position.x,A.position.y,A.position.z,A.rotationQuaternion.x,A.rotationQuaternion.y,A.rotationQuaternion.z,A.rotationQuaternion.w,A.scaling.x,A.scaling.y,A.scaling.z);for(const I of A.children)if("lightType"in I){const e={...I,name:I.name+"_clone",children:[]};e.parent=g,g.children.push(e)}else{const e=h4(I);e.parent=g,g.children.push(e)}return g}function vsA(A){if(A._clone)throw Error(A._clone);if(A._disposed)throw Error(`Mesh "${A.name}" cannot be cloned: it was disposed when it left its last scene.`);const g=tN({...A,name:A.name+"_clone",children:[],_gpu:A._gpu},A.position.x,A.position.y,A.position.z,0,0,0,A.scaling.x,A.scaling.y,A.scaling.z);for(const e of[A._gpu,A.skeleton,A.vat,A.morphTargets,A.thinInstances])e&&HR(e);const I=A.rotationQuaternion;g.rotationQuaternion.set(I.x,I.y,I.z,I.w);for(const e of A.children){const t=h4(e);t.parent=g,g.children.push(t)}return g}let HsA=null,TsA=null;function xsA(){return HsA??=se()}function qsA(){return TsA??=se()}const PsA=5126,OsA=5123,jsA=5125,VsA=5121,po={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};function p1(A,g,I){const e=A.accessors[I],t=po[e.type]??1,i=e.count,o=i*t;let Q;switch(e.componentType){case PsA:Q=X;break;case OsA:Q=N1;break;case jsA:Q=Vg;break;case VsA:Q=mg;break;case 5122:Q=B3;break;case 5120:Q=Q3;break;default:U(138,e.componentType)}return{_data:e.bufferView===void 0?new Q(o):new Q(g.buffer,g.byteOffset+(A.bufferViews[e.bufferView].byteOffset??0)+(e.byteOffset??0),o),_count:i,_componentCount:t}}function f4(A){return A.extensions?.EXT_texture_webp?.source??A.source}function QQ(A,g){for(const I of A.meshes??[])for(const e of I.primitives??[])if(g(e))return!0;return!1}function mT(A){const g=A.materials??[],I=A.textures??[];for(const e of g){const t=e.pbrMetallicRoughness?.metallicRoughnessTexture,i=e.occlusionTexture;if(t&&i&&I[t.index]&&I[i.index]&&f4(I[t.index])!==f4(I[i.index]))return!0}return!1}async function WsA(A,g,I,e){const t=A.images[I];if(t.bufferView!==void 0){const i=A.bufferViews[t.bufferView],o=g.byteOffset+(i.byteOffset??0),Q=g.buffer.slice(o,o+i.byteLength),r=new Blob([Q],{type:t.mimeType??"image/png"});return createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"})}if(t.uri)return(await Promise.resolve().then(()=>$gA)).resolveExternalImage(t.uri,e);U(139)}const zsA=new X([-1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ZsA(A){const g=new Map,I=A.nodes??[];for(let e=0;e<I.length;e++){const t=I[e].children;if(t)for(const i of t)g.set(i,e)}return g}function nN(A,g){return A.get(g)??-1}function rQ(A,g,I,e){const t=e.get(g);if(t)return t;const i=A.nodes[g],o=nN(I,g),Q=o!==-1?rQ(A,o,I,e):zsA;let r;if(i.matrix)r=new X(i.matrix);else{const n=i.translation??[0,0,0],s=i.rotation??[0,0,0,1],c=i.scale??[1,1,1],l=xsA();Di(l,0,n[0],n[1],n[2],s[0],s[1],s[2],s[3],c[0],c[1],c[2]),r=l}const E=new X(16);return Oe(E,0,Q,0,r,0),e.set(g,E),E}async function bT(A,g,I,e,t){const i=A.materials?.[I],o=i??{},Q=o.pbrMetallicRoughness??{},r=d4(A,g,e,t),[E,n,s,c,l]=await Promise.all([r(Q.baseColorTexture),r(Q.metallicRoughnessTexture),r(o.normalTexture),r(o.occlusionTexture),r(o.emissiveTexture)]);return{_baseColorFactor:Q.baseColorFactor??[1,1,1,1],_metallicFactor:Q.metallicFactor??1,_roughnessFactor:Q.roughnessFactor??1,_emissiveFactor:o.emissiveFactor??[0,0,0],_baseColorImage:E,_metallicRoughnessImage:n,_normalImage:s,_normalScale:typeof o.normalTexture?.scale=="number"?o.normalTexture.scale:1,_occlusionTexCoord:typeof o.occlusionTexture?.texCoord=="number"?o.occlusionTexture.texCoord:0,_occlusionImage:c,_emissiveImage:l,_doubleSided:!!o.doubleSided,_alphaMode:o.alphaMode??"OPAQUE",_alphaCutoff:o.alphaCutoff??.5,_rawMatDef:i}}function d4(A,g,I,e){return t=>{if(!t)return Promise.resolve(null);const i=f4(A.textures[t.index]);return e[i]??=WsA(A,g,i,I)}}function KT(A,g,I,e,t=1){const i=A._device,o=i.createTexture({size:{width:1,height:1},format:"rgba8unorm",usage:dA.TEXTURE_BINDING|dA.COPY_DST}),Q=new mg([Math.round(g*255),Math.round(I*255),Math.round(e*255),Math.round(t*255)]);i.queue.writeTexture({texture:o},Q,{bytesPerRow:4,rowsPerImage:1},{width:1,height:1});const r=m1(A),E={texture:o,view:o.createView(),sampler:r,width:1,height:1};return A._dlr?.s(E,g,I,e,t),E}const EQ=1,Im=2,em=4,kT=8,UT=16,w4=32,YC=64,tm=128,Cm=256,ir=1024,or=2048,LT=4096,YT=32768,JT=1<<17,vT=1<<20,M4=1<<21,S4=1<<22,R4=1<<23,N4=1<<25,HT=1<<26,G4=1<<27,Br=1<<28,F4=1<<29,TT=1<<30,sN=16,im=512,aN=1024,Qr=2048,xT=4096,rr=32768,yo=65536;let m4=null,om=null;function tt(A){(m4??=new Map).set(A.id,A),om=null}function nQ(){return m4??=new Map}function XsA(){if(!om){const A=m4;om=A?Array.from(A.values()).sort((g,I)=>g.id.localeCompare(I.id)):[]}return om}let qT=null;function PT(A){(qT??=new Set).add(A)}function $sA(){return qT??[]}const Er=1,Bm=2,cN=4,JC=8,eC=16,sQ=32,nr=64,sr=128,Qm=256,b4=512,OT=1024;let K4=null;function A0A(A){K4=A}function rm(A,g=!1){const I=A._gpu;let e=0;return I.tangentBuffer&&(e|=Er),A.vat?(e|=b4,A.vat.joints1Buffer&&(e|=cN)):A.skeleton&&(e|=Bm,A.skeleton.joints1Buffer&&(e|=cN)),A.morphTargets&&(e|=JC),A.thinInstances&&(e|=eC,A.thinInstances.colors&&(e|=sQ)),I.colorBuffer&&(e|=nr),I.uv2Buffer&&(e|=sr),A._flatNormal&&(e|=OT),g&&(e|=Qm),K4&&(e|=K4(A)),e}let jT=null;function g0A(A){jT=A}function aQ(){return jT}let Em=null;function I0A(A){Em=A}let k4=null;function e0A(A){k4=A}let VT=null;function t0A(A){VT=A}const nm=new Map;let U4=null;function WT(A){U4!==A._device&&(nm.clear(),U4=A._device)}function C0A(){nm.clear(),U4=null}function i0A(A,g,I,e,t,i,o="",Q=null){WT(A);const r=Q&&Em?Em(Q):null,E=`${g}:${I}:${e}:${t}:${o}${r?r._key:""}`,n=nm.get(E);if(n)return n;const s=A._device,c=s.createBindGroupLayout(i._meshBGLDescriptor);let l=null;i._shadowBGLDescriptor&&(l=s.createBindGroupLayout(i._shadowBGLDescriptor));const D={_features:g,_features2:I,_meshFeatures:e,_meshBGL:c,_shadowBGL:l,_composed:i,_pipelines:new Map};return r&&(D._stencil=r._desc),nm.set(E,D),D}function o0A(A,g,I,e){WT(A);const t=aQ(),i=g._sampleCount>1&&!!t?.(e),o=`${Ot(g)}${i?":a2c":""}`,Q=I._pipelines.get(o);if(Q)return Q;const r=A._device,{_features:E,_features2:n,_composed:s}=I,c=(n&yo)!==0,l=!c&&(E&YC)!==0,D=(E&Cm)!==0,p=Mt(A),y=I._shadowBGL?[p,I._meshBGL,I._shadowBGL]:[p,I._meshBGL],_=t?I._a2cVertModule??=r.createShaderModule({code:s._vertexWGSL}):r.createShaderModule({code:s._vertexWGSL}),u=(n&rr)!==0,f=!g._colorFormat&&!u?null:t?I._a2cFragModule??=r.createShaderModule({code:s._fragmentWGSL}):r.createShaderModule({code:s._fragmentWGSL}),h=u?null:{format:g._colorFormat,writeMask:ai.ALL};l&&h&&(h.blend={color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one",operation:"add"}});const w=r.createRenderPipeline({layout:r.createPipelineLayout({bindGroupLayouts:y}),vertex:{module:_,entryPoint:"main",buffers:s._vertexBufferLayouts},...f?{fragment:{module:f,entryPoint:"main",targets:h?[h]:[]}}:{},...g._depthStencilFormat?{depthStencil:{format:g._depthStencilFormat,depthCompare:g._depthCompare??HQ,depthWriteEnabled:u||c||!l,...Em&&I._stencil&&g._depthStencilFormat.includes("stencil")?I._stencil:{}}}:{},multisample:i?{count:g._sampleCount,alphaToCoverageEnabled:!0}:{count:g._sampleCount},primitive:{cullMode:D?"none":"back",...s._prim}});return I._pipelines.set(o,w),w}function L4(A,g,I,e,t,i,o,Q,r){const E=A._device,n=g._features,s=g._features2,c=g._meshFeatures,l=(n&EQ)!==0&&(c&Er)!==0,D=(n&EQ)!==0&&(c&Er)===0,p=l||D,y=(n&Im)!==0,_=(n&tm)!==0,u=(s&yo)!==0,f=[];let h=0;const w=F=>{f.push({binding:h++,resource:F.view}),f.push({binding:h++,resource:F.sampler})},M={_engine:A,_features:n,_features2:s,_meshFeatures:c,_material:i,_mesh:Q??void 0,_env:o??VT?.(i)??null,_refractionTexture:r},S=XsA(),R=I._fragmentKey?I._fragmentKey.split("|").filter(F=>F.length>0):[];f.push({binding:h++,resource:{buffer:e}}),f.push({binding:h++,resource:{buffer:t}});for(const F of S)F.phase==="vertex"&&F.bind&&(h=F.bind(M,f,h));w(i.baseColorTexture??k4?.(A)),p&&w(i.normalTexture),w(i.ormTexture??k4?.(A)),(s&Qr)!==0&&(c&sr)!==0&&i.occlusionTexture&&i.occlusionTexCoord===1&&w(i.occlusionTexture),y&&w(i.emissiveTexture),_&&w(i.specGlossTexture),u&&f.push({binding:h++,resource:{buffer:i._esmShadowParamsUBO}});const N=[];for(const F of R){const G=S.find(m=>m.id===F||F.startsWith(m.id+"-"));!G||G.phase==="vertex"||!G.bind||N.includes(G)||(N.push(G),h=G.bind(M,f,h))}return E.createBindGroup({layout:g._meshBGL,entries:f})}let Y4=null;function sm(){if(Y4)return Y4;const A=async(g,I)=>{const e=g._envTextures,i=await(await Promise.resolve().then(()=>QYA)).buildPbrRenderables(g,I,e);return A._rebuildSingle=i.rebuildSingle,i};return A._materialFamily="pbr",Y4=A}function J4(A){let g=(A.emissiveTexture?Im:0)|(A.normalTexture?EQ:0)|(A.alphaBlend===!0||(A._alphaCutOff??0)<=0&&A.alpha<1?YC:0)|(A.specGlossTexture?tm:0)|(A.doubleSided?Cm:0);(A.occlusionStrength??1)>0&&(g|=YT),A.enableSpecularAA&&(g|=JT);let I=0;for(const e of nQ().values())if(e.detect){const t=e.detect(A);g|=t.f,I|=t.f2}return A._uv2Mask&&(I|=Qr),A.baseColorFactor&&(I|=xT),{features:g,features2:I}}function zT(A){return e0A(g=>g._pbrFallbackTex??=KT(g,1,1,1)),{...A,_buildGroup:sm(),_uboVersion:0}}function lN(A){const g=[];for(const I of[A.baseColorTexture,A.normalTexture,A.ormTexture,A.occlusionTexture,A.emissiveTexture,A.specGlossTexture])I&&g.push(I);for(const I of nQ().values())I.textures?.(A,g);return g}const B0A=Object.freeze(Object.defineProperty({__proto__:null,_computePbrMaterialFeatures:J4,collectPbrBoundTextures:lN,createPbrMaterial:zT,getPbrGroupBuilder:sm},Symbol.toStringTag,{value:"Module"}));function am(A){const g=Math.max(0,Math.min(1,A));return Math.round((g<=.0031308?g*12.92:1.055*Math.pow(g,1/2.4)-.055)*255)}function cm(A){const g=Math.max(0,Math.min(255,A))/255;return g<=.04045?g/12.92:Math.pow((g+.055)/1.055,2.4)}function Q0A(A,g=1){return[cm(A>>16&255),cm(A>>8&255),cm(A&255),g]}const v4=A=>A;function _o(A,g,I,e,t,i){const o=A._device,Q=g?.width??1,r=g?.height??1,E=I?"rgba8unorm-srgb":"rgba8unorm",n=g?XQ(Q,r):1,s=o.createTexture({size:{width:Q,height:r},format:E,usage:dA.TEXTURE_BINDING|dA.COPY_DST|dA.COPY_SRC|dA.RENDER_ATTACHMENT,mipLevelCount:n});g?(o.queue.copyExternalImageToTexture({source:g},{texture:s,premultipliedAlpha:!1},{width:Q,height:r}),t(A,s)):o.queue.writeTexture({texture:s},i??new mg([255,255,255,255]),{bytesPerRow:4},{width:1,height:1});const c={texture:s,view:s.createView(),sampler:e,width:Q,height:r};return A._dlr?.b(c,g,I,!!g,i),c}function H4(A,g,I,e){return _o(A,null,!0,I,e,new mg([am(g[0]),am(g[1]),am(g[2]),Math.round(Math.max(0,Math.min(1,g[3]))*255)]))}function lm(A,g,I,e,t){const i=o=>Math.round(Math.max(0,Math.min(1,o))*255);return _o(A,null,!1,e,t,new mg([255,i(g),i(I),255]))}function r0A(A,g){const I=A._emissiveFactor;return!(I[0]===0&&I[1]===0&&I[2]===0||g&&I[0]===1&&I[1]===1&&I[2]===1)}async function ZT(A,g){if(!A._emissiveColor&&r0A(g,A.emissiveTexture)){const{setPbrEmissive:I}=await Promise.resolve().then(()=>$DA),e=g._emissiveFactor;I(A,[e[0],e[1],e[2]])}if(g._alphaMode==="MASK"){const{setPbrAlphaCutoff:I}=await Promise.resolve().then(()=>TDA);I(A,g._alphaCutoff)}}function E0A(A,g,I,e,t,i){return{baseColorTexture:g,normalTexture:e,ormTexture:I,emissiveTexture:t,...A._baseColorImage&&!n0A(A._baseColorFactor)?{baseColorFactor:A._baseColorFactor}:void 0,doubleSided:A._doubleSided,occlusionStrength:A._occlusionImage?1:0,...A._normalScale!==1?{normalTextureScale:A._normalScale}:void 0,...A._metallicRoughnessImage?{metallicFactor:A._metallicFactor,roughnessFactor:A._roughnessFactor}:void 0,enableSpecularAA:!0,...A._alphaMode==="BLEND"?{alphaBlend:!0,alpha:A._baseColorFactor[3]}:void 0,...A._alphaMode==="MASK"?{alpha:A._baseColorFactor[3]}:void 0,...A._rawMatDef?.name?{name:A._rawMatDef.name}:void 0,...i,_buildGroup:sm(),_uboVersion:0}}function n0A(A){return A[0]===1&&A[1]===1&&A[2]===1&&A[3]===1}function s0A(A,g,I,e,t){const i=g._baseColorImage?t(g._baseColorImage,!0):H4(A,g._baseColorFactor,I,e),o=g._normalImage?t(g._normalImage,!1):void 0,Q=g._emissiveImage?t(g._emissiveImage,!0):void 0,r=g._metallicRoughnessImage??g._occlusionImage;let E;return r&&(!g._metallicRoughnessImage||!g._occlusionImage||g._metallicRoughnessImage===g._occlusionImage)?E=t(r,!1):r?E=t(g._metallicRoughnessImage,!1):E=lm(A,g._roughnessFactor,g._metallicFactor,I,e),{baseColorTexture:i,ormTexture:E,normalTexture:o,emissiveTexture:Q}}let T4;function a0A(A,g){const I=T4;T4=(e,t)=>{I?.(e,t),A(e)&&t.push(g)}}function c0A(A,g){T4?.(A,g)}let l0A;function XT(){return l0A??=Promise.resolve().then(()=>CIA)}let D0A;function p0A(){return D0A??=Promise.resolve().then(()=>P5A)}let y0A;function x4(){return y0A??=Promise.resolve().then(()=>V5A)}function $T(A,g,I,e,t){const[i,o]=yi(g._positions),Q=g._indices,r=Q instanceof Vg,E=t?t._gpu:{positionBuffer:wI(A,g._positions,SA.VERTEX),normalBuffer:wI(A,g._normals,SA.VERTEX),tangentBuffer:g._tangents?wI(A,g._tangents,SA.VERTEX):null,uvBuffer:wI(A,g._uvs,SA.VERTEX),uv2Buffer:g._uv2s?wI(A,g._uv2s,SA.VERTEX):null,colorBuffer:g._colors?wI(A,g._colors,SA.VERTEX):null,indexBuffer:wI(A,Q,SA.INDEX),indexCount:g._indexCount,indexFormat:r?"uint32":"uint16"},n=tN({name:e,material:I,receiveShadows:!1,boundMin:i,boundMax:o,_gpu:E,_flatNormal:g._flatNormal});return n._cpuPositions=g._positions,n._cpuNormals=g._normals,n._cpuUvs=g._uvs,n._cpuIndices=t?t._cpuIndices:r?Q:new Vg(Q),A._dlr?.m(n,g._uv2s,g._tangents,g._colors,Q,E.indexFormat),n}async function q4(A,g){const{json:I,binChunk:e,baseUrl:t}=await _0A(g),i=ZsA(I),o=new Map,Q=u0A(I)?await p0A():void 0,r=Q?await Q.loadGltfFeatures(I):[];c0A(I,r);let E=e;for(const w of r)if(w.preParse){const M=await w.preParse(I,E);M&&(E=M)}const n=r.filter(w=>w.applyMaterial),s=r.filter(w=>w.wrapTexture).map(w=>w.wrapTexture),c=s.length?(w,M)=>s.reduce((S,R)=>R(S,M),w):v4,l=new Map;for(const w of await Promise.all(r.flatMap(M=>M.preMesh?[M.preMesh(I,E,t)]:[])))for(const[M,S]of w)l.set(M,S);const D=await f0A(I,E,t,i,o,l),p={_engine:A,_json:I,_binChunk:E,_baseUrl:t,_parentMap:i,_worldMatrixCache:o,_matExts:n,_runMatExts:Q?.runGltfMaterialFeatures,_wrapTex:c},y=await w0A(D,r,p),{root:_,nodeMap:u}=h0A(I,y,D);p._nodeMap=u;const f=await Promise.all(r.flatMap(w=>w.applyAsset?[w.applyAsset(y,_,p)]:[])),h={entities:[_]};for(const w of f){w.entities?.length&&h.entities.push(...w.entities);const{entities:M,_sceneSetup:S,...R}=w;if(Object.assign(h,R),S){const N=h._sceneSetup;h._sceneSetup=(F,G)=>{N?.(F,G),S(F,G)}}}return h}async function _0A(A){const g=typeof A=="string";let I="";if(g)try{I=new URL(".",new URL(A,globalThis.location?.href))+""}catch{}const e=g?await(await fetch(A)).arrayBuffer():A instanceof Blob?await A.arrayBuffer():A;return e.byteLength>=4&&new H1(e).getUint32(0,!0)===1179937895?{...(await Promise.resolve().then(()=>z5A)).parseGlbContainer(e),baseUrl:I}:(await Promise.resolve().then(()=>$gA)).parseGltfJsonAsset(e,I)}function u0A(A){return A.extensionsUsed?.length||A.animations?.length||/extras|sparse/.test(JSON.stringify(A))||A.skins?.length&&QQ(A,g=>g.attributes?.JOINTS_0!==void 0)||QQ(A,g=>!!g.targets?.length)||A.nodes?.some(g=>g.scale?g.scale[0]*g.scale[1]*g.scale[2]<0:g.matrix?IN(g.matrix)<0:!1)||QQ(A,g=>g.mode!==void 0&&g.mode!==4)||mT(A)}function h0A(A,g,I){const e=[];for(let E=0;E<I.length;E++){const n=I[E]._nodeIndex;(e[n]??=[]).push(g[E])}const t=new Array(A.nodes?.length??0);function i(E){const n=A.nodes[E],s=n.name??`node_${E}`;let c;if(n.matrix)c=g4(s,n.matrix);else{const D=n.translation??[0,0,0],p=n.rotation??[0,0,0,1],y=n.scale??[1,1,1];c=b1(s,D[0],D[1],D[2],p[0],p[1],p[2],p[3],y[0],y[1],y[2])}if(t[E]=c,n.children)for(const D of n.children)c.children.push(i(D));const l=e[E]??[];return c.children.push(...l),c}const Q=(A.scenes?.[A.scene??0]?.nodes??[]).map(E=>i(E)),r=b1("__root__",0,0,0,0,0,0,1,-1,1,1);return r.children.push(...Q),{root:r,nodeMap:t}}async function f0A(A,g,I,e,t,i){const o=[],Q=[],r=p=>{const y=(p??-1)+1;return Q[y]??=bT(A,g,y-1,I,o)},E=[],n=[],s=A.accessors,c=A.bufferViews,l=p=>{for(const y in p.attributes){const _=s[p.attributes[y]],u=c?.[_?.bufferView]?.byteStride;if(u!==void 0&&u!==(po[_.type]??1)*(_.componentType===5126||_.componentType===5125?4:_.componentType===5123||_.componentType===5122?2:1))return!0}return!1};for(let p=0;p<A.nodes.length;p++){const y=A.nodes[p];if(y.mesh===void 0)continue;const _=y.mesh,u=A.meshes[_],f=rQ(A,p,e,t);for(let h=0;h<u.primitives.length;h++){const w=u.primitives[h],M=w.attributes,S=i.get(w);if(!S&&l(w)){const P=await(await XT()).buildInterleavedPartial(A,g,w,f,p);if(P){n.push(r(w.material)),E.push(P);continue}}const R=P=>{if(S&&S._attributes.has(P)){const yA=S._attributes.get(P),cA=yA.length/S._vertexCount;return{_data:yA,_count:S._vertexCount,_componentCount:cA}}const gA=M[P];return gA!==void 0?p1(A,g,gA):null},N=R("POSITION"),F=R("NORMAL"),G=R("TEXCOORD_0"),m=R("TEXCOORD_1"),K=R("TANGENT"),k=R("COLOR_0"),L=S?S._indexCount>0?{_data:S._indices,_count:S._indexCount}:null:w.indices!==void 0?p1(A,g,w.indices):null,H=!L||!F?await Promise.resolve().then(()=>m5A):null,q=k?(await x4()).normalizeColorToVec4(k._data,k._count,k._componentCount):null,CA=G?G._data instanceof X?G._data:(await x4()).normalizeUvToVec2(G._data,G._count):new X(N._count*2),eA=m?m._data instanceof X?m._data:(await x4()).normalizeUvToVec2(m._data,m._count):null,Z=L?L._data instanceof Vg?new Vg(L._data):L._data instanceof mg?Uint16Array.from(L._data):new N1(L._data.buffer,L._data.byteOffset,L._count):H.createSequentialIndices(N._count);n.push(r(w.material));const O=F?F._data:H.computeSmoothNormals(N._data,Z,N._count);E.push({_positions:N._data,_normals:O,_tangents:K?K._data:null,_uvs:CA,_uv2s:eA,_colors:q,_flatNormal:!F,_indices:Z,_vertexCount:N._count,_indexCount:Z.length,_worldMatrix:f,_nodeIndex:p,_primitive:w,_decoded:S})}}const D=await Promise.all(n);return E.map((p,y)=>({...p,_material:D[y]}))}let cQ=null;async function d0A(){cQ||(cQ=(await Promise.resolve().then(()=>zR)).generateMipmaps)}async function w0A(A,g,I){const{_engine:e,_json:t,_binChunk:i,_baseUrl:o,_matExts:Q,_wrapTex:r}=I,E=Pe(e,{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat",maxAnisotropy:4});let n,s;if(t.samplers?.some(S=>S.wrapS>10497||S.wrapT>10497||S.magFilter===9728||S.minFilter!=null&&S.minFilter!==9729&&S.minFilter!==9987)){const S=await Promise.resolve().then(()=>AJA);n=S.makeSamplerFor(e,t,E),s=S.buildSampledPbrTextures}await d0A();const c=g.filter(S=>S.applyMesh),l=new Map,D=(S,R)=>{let N=l.get(S);N||l.set(S,N=[]);const F=+R;let G=N[F];return G||(G=_o(e,S,R,E,cQ),N[F]=G),G},p=Q.length?[]:null,y=p?d4(t,i,o,p):null,_={_engine:e,async _texture(S,R){if(!S||!y)return;const N=await y(S);return N?r(D(N,R),S):void 0},_uploadImage(S,R){return _o(e,S,R,E,cQ)}};let u=r!==v4;if(!u){const S=t.materials;S&&JSON.stringify(S).includes('"texCoord":1')&&(u=!0)}let f=null;const h=()=>f??=Promise.resolve().then(()=>CJA),w=new Map,M=S=>{let R=w.get(S);return R||(R=(async()=>{const N=Q.length?await I._runMatExts(S,Q,_):void 0;let F;if(u){const G=await h(),m=G.buildDefaultPbrTexturesExt(e,S,E,cQ,D,r,n);F=G.assemblePbrPropsExt(S,m,N),await G.applyGltfUvTransform(F,m)}else{const G=s?s(e,S,E,cQ,n,D):s0A(e,S,E,cQ,D);F=E0A(S,G.baseColorTexture,G.ormTexture,G.normalTexture,G.emissiveTexture,N)}return await ZT(F,S),F})(),w.set(S,R)),R};return new Set(A.map(S=>S._primitive)).size<A.length?Promise.resolve().then(()=>QJA).then(S=>S.share(A,M,$T,c,I)):Promise.all(A.map(async(S,R)=>{const N=await M(S._material),F=t.meshes[t.nodes[S._nodeIndex].mesh].name||`gltf_mesh_${R}`,G=S._vb?(await XT()).buildInterleavedMesh(e,S,R,N,F):$T(e,S,N,F);return G._authoredSign=-1,await Promise.all(c.map(m=>m.applyMesh(S,G,I))),G}))}function P4(A,g,I){return{x:A.x+(g.x-A.x)*I,y:A.y+(g.y-A.y)*I,z:A.z+(g.z-A.z)*I}}const O4="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets/dist/profiles/";async function Ax(A){const g=await fetch(A);if(!g.ok)throw new Error(`WebXR profiles: ${g.status} fetching ${A}`);return await g.json()}function M0A(A,g){for(const I of A){const e=g[I];if(e)return{id:I,path:e.path}}return null}function S0A(A,g){return A.layouts[g]??A.layouts.none??Object.values(A.layouts)[0]??null}function gx(A,g){A.name&&!g.has(A.name)&&g.set(A.name,A);for(const I of A.children)gx(I,g)}function R0A(A,g){const I=[];for(const e of Object.values(A.components)){const t=e.gamepadIndices,i=e.visualResponses;if(i)for(const o of Object.values(i)){const Q=g.get(o.valueNodeName);Q&&I.push({valueNode:Q,minNode:o.minNodeName?g.get(o.minNodeName)??null:null,maxNode:o.maxNodeName?g.get(o.maxNodeName)??null:null,property:o.valueNodeProperty,source:o.componentProperty,states:o.states,buttonIndex:t.button??-1,xAxisIndex:t.xAxis??-1,yAxisIndex:t.yAxis??-1})}}return I}async function Ix(A,g,I,e={}){try{const t=e.baseUrl??O4,i=await Ax(new URL("profilesList.json",t).href),o=M0A(g.profiles,i);if(!o)return null;const Q=new URL(o.path,t).href,r=await Ax(Q),E=S0A(r,I);if(!E?.assetPath)return null;const n=new URL(E.assetPath,Q).href,s=await q4(A,n),c=s.entities[0];if(!c)return null;const l=new Map;return gx(c,l),{container:s,root:c,profileId:r.profileId,_responses:R0A(E,l)}}catch{return null}}function N0A(A,g,I,e,t,i,o,Q,r,E){let n=A*t+g*i+I*o+e*Q;n<0&&(t=-t,i=-i,o=-o,Q=-Q,n=-n);let s,c;if(n>.9995)s=1-r,c=r;else{const u=Math.acos(n),f=Math.sin(u);s=Math.sin((1-r)*u)/f,c=Math.sin(r*u)/f}let l=s*A+c*t,D=s*g+c*i,p=s*I+c*o,y=s*e+c*Q;const _=Math.hypot(l,D,p,y)||1;l/=_,D/=_,p/=_,y/=_,E.x=l,E.y=D,E.z=p,E.w=y}function G0A(A){return A?A.pressed?"pressed":A.touched?"touched":"default":"default"}const DN={x:0,y:0,z:0,w:1};function F0A(A,g){if(!A.minNode||!A.maxNode)return;const I=A.minNode,e=A.maxNode,t=P4(I.position,e.position,g);A.valueNode.position.set(t.x,t.y,t.z);const i=P4(I.scaling,e.scaling,g);A.valueNode.scaling.set(i.x,i.y,i.z);const o=I.rotationQuaternion,Q=e.rotationQuaternion;N0A(o.x,o.y,o.z,o.w,Q.x,Q.y,Q.z,Q.w,g,DN),A.valueNode.rotationQuaternion.set(DN.x,DN.y,DN.z,DN.w)}function ex(A,g){if(!g)return;const I=g.buttons,e=g.axes;for(const t of A._responses){if(t.property==="visibility"){const o=G0A(I[t.buttonIndex]);ke(t.valueNode,t.states.includes(o));continue}let i;t.source==="xAxis"?i=(e[t.xAxisIndex]??0)*.5+.5:t.source==="yAxis"?i=(e[t.yAxisIndex]??0)*.5+.5:t.source==="button"?i=I[t.buttonIndex]?.value??0:i=I[t.buttonIndex]?.pressed?1:0,F0A(t,i)}}const m0A=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_PROFILES_BASE_URL:O4,loadMotionController:Ix,updateMotionController:ex},Symbol.toStringTag,{value:"Module"}));function Dm(A){const g=so(A),I={_lightVersion:0,b(){I._lightVersion++}};return{wm:g,onDirty:()=>{g.markLocalDirty(),I._lightVersion++},lvs:I}}function pm(A,g,I){return Object.defineProperties(A,{parent:{get(){return g.parent},set(e){g.parent=e},enumerable:!0,configurable:!0},worldMatrix:{get(){return g.getWorldMatrix()},enumerable:!0,configurable:!0},worldMatrixVersion:{get(){return g.getWorldMatrixVersion()},enumerable:!0,configurable:!0}}),I&&(Object.defineProperty(A,"_lightVersion",{get(){return I._lightVersion},enumerable:!1,configurable:!0}),A._bumpLightVersion=I.b),tQ(A,g),A}function j4(A,g,I,e=0,t=0,i=0,o){const Q=Math.sqrt(A*A+g*g+I*I)||1,r=A/Q,E=g/Q,n=I/Q;let s=-n,c=r;const l=0,D=Math.sqrt(s*s+l*l+c*c)||1;s/=D,c/=D;const p=E*c-n*l,y=n*s-r*c,_=r*l-E*s,u=o??new X(16),f=u;return f[0]=s,f[1]=l,f[2]=c,f[3]=0,f[4]=p,f[5]=y,f[6]=_,f[7]=0,f[8]=r,f[9]=E,f[10]=n,f[11]=0,f[12]=e,f[13]=t,f[14]=i,f[15]=1,u}function tx(A=[0,1,0],g=1){const I=se(),{wm:e,onDirty:t,lvs:i}=Dm(()=>j4(o.direction.x,o.direction.y,o.direction.z,0,0,0,I)),o=pm({lightType:"hemispheric",children:[],direction:new Ht(A[0],A[1],A[2],t),intensity:g,diffuseColor:[1,1,1],specularColor:[1,1,1],groundColor:[0,0,0],_writeLightUbo:(Q,r)=>{const E=r,n=o.worldMatrix;Q[E]=n[8],Q[E+1]=n[9],Q[E+2]=n[10],Q[E+3]=3,Q[E+4]=o.diffuseColor[0]*o.intensity,Q[E+5]=o.diffuseColor[1]*o.intensity,Q[E+6]=o.diffuseColor[2]*o.intensity,Q[E+8]=o.specularColor[0]*o.intensity,Q[E+9]=o.specularColor[1]*o.intensity,Q[E+10]=o.specularColor[2]*o.intensity,Q[E+12]=o.groundColor[0]*o.intensity,Q[E+13]=o.groundColor[1]*o.intensity,Q[E+14]=o.groundColor[2]*o.intensity}},e,i);return o}function Cx(A,g=1){const I=se();I[0]=1,I[5]=1,I[10]=1,I[15]=1;const e=I,{wm:t,onDirty:i,lvs:o}=Dm(()=>(I[12]=Q.position.x,I[13]=Q.position.y,I[14]=Q.position.z,e)),Q=pm({lightType:"point",children:[],position:new Ht(A[0],A[1],A[2],i),diffuse:[1,1,1],specular:[1,1,1],intensity:g,range:Number.MAX_VALUE,_writeLightUbo:(r,E)=>{const n=E,s=Q.worldMatrix;r[n]=s[12],r[n+1]=s[13],r[n+2]=s[14],r[n+3]=0,r[n+4]=Q.diffuse[0]*Q.intensity,r[n+5]=Q.diffuse[1]*Q.intensity,r[n+6]=Q.diffuse[2]*Q.intensity,r[n+7]=Q.range,r[n+8]=Q.specular[0]*Q.intensity,r[n+9]=Q.specular[1]*Q.intensity,r[n+10]=Q.specular[2]*Q.intensity}},t,o);return Q}const ix=Object.freeze(Object.defineProperty({__proto__:null,createPointLight:Cx},Symbol.toStringTag,{value:"Module"}));function ox(A,g=1){const I=se(),{wm:e,onDirty:t,lvs:i}=Dm(()=>j4(o.direction.x,o.direction.y,o.direction.z,o.position.x,o.position.y,o.position.z,I)),o=pm({lightType:"directional",children:[],direction:new Ht(A[0],A[1],A[2],t),position:new Ht(0,0,0,t),diffuse:[1,1,1],specular:[1,1,1],intensity:g,_writeLightUbo:(Q,r)=>{const E=r,n=o.worldMatrix;Q[E]=n[8],Q[E+1]=n[9],Q[E+2]=n[10],Q[E+3]=1,Q[E+4]=o.diffuse[0]*o.intensity,Q[E+5]=o.diffuse[1]*o.intensity,Q[E+6]=o.diffuse[2]*o.intensity,Q[E+7]=Number.MAX_VALUE,Q[E+8]=o.specular[0]*o.intensity,Q[E+9]=o.specular[1]*o.intensity,Q[E+10]=o.specular[2]*o.intensity}},e,i);return o}const b0A=Object.freeze(Object.defineProperty({__proto__:null,createDirectionalLight:ox},Symbol.toStringTag,{value:"Module"}));function Bx(A,g,I,e,t=1){const i=se(),{wm:o,onDirty:Q,lvs:r}=Dm(()=>j4(s.direction.x,s.direction.y,s.direction.z,s.position.x,s.position.y,s.position.z,i));let E=I,n=Math.cos(I*.5);const s=pm({lightType:"spot",children:[],position:new Ht(A[0],A[1],A[2],Q),direction:new Ht(g[0],g[1],g[2],Q),angle:0,exponent:e,diffuse:[1,1,1],specular:[1,1,1],intensity:t,range:Number.MAX_VALUE,_writeLightUbo:(c,l)=>{const D=l,p=s.worldMatrix;c[D]=p[12],c[D+1]=p[13],c[D+2]=p[14],c[D+3]=2,c[D+4]=s.diffuse[0]*s.intensity,c[D+5]=s.diffuse[1]*s.intensity,c[D+6]=s.diffuse[2]*s.intensity,c[D+7]=s.range,c[D+8]=s.specular[0]*s.intensity,c[D+9]=s.specular[1]*s.intensity,c[D+10]=s.specular[2]*s.intensity,c[D+11]=s.exponent,c[D+12]=p[8],c[D+13]=p[9],c[D+14]=p[10],c[D+15]=n}},o,r);return Object.defineProperty(s,"angle",{get(){return E},set(c){c!==E&&(E=c,n=Math.cos(c*.5),r.b())},configurable:!0,enumerable:!0}),s}const K0A=Object.freeze(Object.defineProperty({__proto__:null,createSpotLight:Bx},Symbol.toStringTag,{value:"Module"})),Qx="struct clusteredLightParamsUniforms{tileCountX:u32,tileCountY:u32,zSlices:u32,lightCount:u32,sliceScale:f32,sliceBias:f32,dataTextureWidth:u32,batchCount:u32,};fn clusteredTexel(index:u32)->vec2<u32>{return vec2<u32>(index%clusteredLightParams.dataTextureWidth,index/clusteredLightParams.dataTextureWidth);}";function rx(A,g){return`{let clip=scene.viewProjection*vec4<f32>(input.worldPos,1.0);let ndc=clip.xyz/clip.w;let tx=clamp(u32((ndc.x*0.5+0.5)*f32(clusteredLightParams.tileCountX)),0u,clusteredLightParams.tileCountX-1u);let ty=clamp(u32((0.5-ndc.y*0.5)*f32(clusteredLightParams.tileCountY)),0u,clusteredLightParams.tileCountY-1u);let viewPos=scene.view*vec4<f32>(input.worldPos,1.0);let tzi=clamp(i32(log(max(viewPos.z,0.0001))*clusteredLightParams.sliceScale+clusteredLightParams.sliceBias),0,i32(clusteredLightParams.zSlices)-1);let slice=textureLoad(clusteredCells,clusteredTexel(u32(tzi)),0);let directRoughnessCluster=max(roughness,AA_factor_x);let directAlphaGCluster=directRoughnessCluster*directRoughnessCluster+0.0005;if(slice.x<=slice.y){let firstLight=slice.x;let lastLight=min(slice.y,clusteredLightParams.lightCount-1u);let firstBatch=firstLight/32u;let lastBatch=lastLight/32u;for(var batch=firstBatch;batch<=lastBatch;batch++){let batchOffset=batch*32u;let tileMaskIndex=(tx*clusteredLightParams.tileCountY+ty)*clusteredLightParams.batchCount+batch;var mask=textureLoad(clusteredIndices,clusteredTexel(tileMaskIndex),0).x;let maskOffset=max(firstLight,batchOffset)-batchOffset;let maskWidth=min(lastLight-batchOffset+1u,32u);mask=extractBits(mask,maskOffset,maskWidth);while(mask!=0u){let trailing=firstTrailingBit(mask);mask^=1u<<trailing;let li=batchOffset+maskOffset+trailing;let lightTexel=li*${A};let positionRange=textureLoad(clusteredLights,clusteredTexel(lightTexel),0);let colorIntensity=textureLoad(clusteredLights,clusteredTexel(lightTexel+1u),0);let toLight=positionRange.xyz-input.worldPos;let d2=dot(toLight,toLight);let dist=sqrt(d2);let range=max(positionRange.w,0.0001);if(dist<range){let Lc=toLight/max(dist,0.0001);let NdotLc=max(dot(N,Lc),0.0);let range2=max(range*range,0.0000001);let falloffFactor=d2/range2;var rangeAtt=1.0/max(d2,0.0000001);var smoothRange=saturate(1.0-falloffFactor*falloffFactor);smoothRange*=smoothRange;rangeAtt*=smoothRange;${g}let lightRadiance=colorIntensity.rgb*colorIntensity.a*rangeAtt*material.directIntensity;directDiffuse+=surfaceAlbedo*(1.0/PI)*NdotLc*lightRadiance;if(NdotLc>0.0){let Hc=normalize(V+Lc);let NdotHc=clamp(dot(N,Hc),0.0000001,1.0);let VdotHc=saturate(dot(V,Hc));let Dc=distributionGGX(NdotHc,directAlphaGCluster);let Gc=geometrySmithGGX(NdotLc,NdotV,directAlphaGCluster);let Fc=fresnelSchlick(VdotHc,colorF0,colorF90);directSpecular+=Fc*Dc*Gc*NdotLc*lightRadiance;}}}}}}`}function k0A(){return rx("2u","")}function U0A(){return rx("3u","let dirCone=textureLoad(clusteredLights,clusteredTexel(lightTexel+2u),0);if(dirCone.w>=0.0){let cd=dot(-dirCone.xyz,Lc);let coneAtt=saturate((cd-dirCone.w)/max(1.0-dirCone.w,0.001));rangeAtt*=coneAtt*coneAtt;}")}const Ex=16384,L0A={id:"clustered-spot-lights",phase:"fragment",detect(A){return A._clusteredLightState?._hasSpots?{f:Ex,f2:0}:{f:0,f2:0}},frag(A){if((A._features&Ex)===0)return null;const g=U0A();return{_id:"clustered-spot-lights",_bindings:[{_name:"clusteredLightParams",_type:{_kind:"uniform-buffer"},_visibility:NA.FRAGMENT},{_name:"clusteredLights",_type:{_kind:"texture",_textureType:"texture_2d<f32>",_sampleType:"unfilterable-float"},_visibility:NA.FRAGMENT},{_name:"clusteredCells",_type:{_kind:"texture",_textureType:"texture_2d<u32>"},_visibility:NA.FRAGMENT},{_name:"clusteredIndices",_type:{_kind:"texture",_textureType:"texture_2d<u32>"},_visibility:NA.FRAGMENT}],_helperFunctions:Qx,_fragmentSlots:{AD:g,BL:g}}},bind(A,g,I){const e=A._material._clusteredLightState;return e&&(g.push({binding:I++,resource:{buffer:e.paramsBuffer}}),g.push({binding:I++,resource:e.lightsView}),g.push({binding:I++,resource:e.cellsView}),g.push({binding:I++,resource:e.indicesView})),I}};function Y0A(A){A._spotSupport||(A._spotSupport=J0A,tt(L0A))}const J0A={_create(A){const g=new X(A*4);return g.fill(Number.NaN),{_stride:3,_coneChanged(e,t){const i=e*4,o=g[i]!==t.direction[0]||g[i+1]!==t.direction[1]||g[i+2]!==t.direction[2]||g[i+3]!==t.angle;return g[i]=t.direction[0],g[i+1]=t.direction[1],g[i+2]=t.direction[2],g[i+3]=t.angle,o},_collect(e,t,i){for(const o of t)o.range>0&&o.intensity>0&&e.push({light:o,_spot:o,depth:i[2]*o.position[0]+i[6]*o.position[1]+i[10]*o.position[2]+i[14]})},_write(e,t,i){if(!i){e[t+8]=0,e[t+9]=0,e[t+10]=0,e[t+11]=-1;return}const o=i.direction[0],Q=i.direction[1],r=i.direction[2],E=Math.sqrt(o*o+Q*Q+r*r),n=E===0||E===1?1:1/E;e[t+8]=o*n,e[t+9]=Q*n,e[t+10]=r*n,e[t+11]=Math.cos(Math.min(Math.max(i.angle,0),Math.PI)*.5)},_markState(e){e._hasSpots=!0}}}},nx=8192,v0A=8192,pN=32,H0A=4294967295;function T0A(A){return{kind:"clusteredLightContainer",pointLights:[],spotLights:[],horizontalTiles:A?.horizontalTiles??64,verticalTiles:A?.verticalTiles??64,zSlices:A?.zSlices??16,_version:0}}function x0A(A,g){const I={position:g.position,diffuse:g.diffuse,range:g.range??1,intensity:g.intensity??1};return A.pointLights.push(I),A._version++,I}function q0A(A,g){Y0A(A);const I={position:g.position,direction:g.direction,diffuse:g.diffuse,range:g.range??1,intensity:g.intensity??1,angle:g.angle??Math.PI/2};return A.spotLights.push(I),A._version++,I}function P0A(A){A._version++}function O0A(A,g){const I=A;I._clusteredLightContainer=g,tt(j0A);const e=V0A(I.surface.engine,I,g);I._clusteredLightUpdater=(t,i,o)=>e.refresh(t,i,o),I._disposables.push(()=>e.dispose());for(const t of I.meshes)if(t.material){const i=t.material;i._clusteredLightState=e,i._renderFeatures=void 0}}const j0A={id:"clustered-lights",phase:"fragment",detect(A){const g=A._clusteredLightState;return g&&!g._hasSpots?{f:nx,f2:0}:{f:0,f2:0}},frag(A){if((A._features&nx)===0)return null;const g=k0A();return{_id:"clustered-lights",_bindings:[{_name:"clusteredLightParams",_type:{_kind:"uniform-buffer"},_visibility:NA.FRAGMENT},{_name:"clusteredLights",_type:{_kind:"texture",_textureType:"texture_2d<f32>",_sampleType:"unfilterable-float"},_visibility:NA.FRAGMENT},{_name:"clusteredCells",_type:{_kind:"texture",_textureType:"texture_2d<u32>"},_visibility:NA.FRAGMENT},{_name:"clusteredIndices",_type:{_kind:"texture",_textureType:"texture_2d<u32>"},_visibility:NA.FRAGMENT}],_helperFunctions:Qx,_fragmentSlots:{AD:g,BL:g}}},bind(A,g,I){const e=A._material._clusteredLightState;return e&&(g.push({binding:I++,resource:{buffer:e.paramsBuffer}}),g.push({binding:I++,resource:e.lightsView}),g.push({binding:I++,resource:e.cellsView}),g.push({binding:I++,resource:e.indicesView})),I}};function V0A(A,g,I){const e=g.camera;e||U(112);const t=Math.max(1,A.canvas.width),i=Math.max(1,A.canvas.height),o=Math.max(1,I.horizontalTiles|0),Q=Math.max(1,I.verticalTiles|0),r=Math.max(1,I.zSlices|0),E=Math.max(1,Math.min(v0A,A._device.limits.maxTextureDimension2D)),n=I.pointLights,s=I.spotLights,c=I._spotSupport?._create(s.length),l=n.length,D=c?s.length:0,p=l+D,y=c?._stride??2,_=Math.max(1,Math.ceil(p/pN)),u=Math.max(1,p*y),f=Math.max(1,o*Q*_),h=Math.min(E,Math.max(u,r,f)),w=new X(V4(u,4,h)),M=new Vg(V4(r,4,h)),S=new Vg(V4(f,1,h)),R=new X(p*8);R.fill(Number.NaN);const N=[],F=new ArrayBuffer(32),G=new Vg(F),m=new X(F);G[0]=o,G[1]=Q,G[2]=r,G[3]=p,m[4]=e.nearPlane,m[5]=e.farPlane,G[6]=h,G[7]=_;const K=Re(A,m,"clustered-light-params"),k=W4(A,"rgba32float",u,"clustered-light-data",h),L=W4(A,"rgba32uint",r,"clustered-slice-data",h),H=W4(A,"r32uint",f,"clustered-tile-mask-data",h);let q,CA=-1,eA=0,Z=0,O=-1,P=-1,gA=-1;const yA={paramsBuffer:K,lightsView:k.createView(),cellsView:L.createView(),indicesView:H.createView(),refresh(cA,RA,YA){if(!cA)return;const Ag=Math.max(1,RA),lg=Math.max(1,YA),mA=KC(cA,Ag,lg),HA=T1(cA),Qg=I.pointLights,Eg=I.spotLights,kA=I._version,ug=Qg.length+(c?Eg.length:0);if(cA===q&&HA===CA&&Ag===eA&&lg===Z&&mA===O&&kA===P&&ug===gA)return;(ug*y>u||Math.ceil(ug/pN)>_||!!I._spotSupport!=!!c)&&U(113);let fg=cA!==q||HA!==CA||Ag!==eA||lg!==Z||mA!==O||ug!==gA,rg=fg;if(kA!==P||ug!==gA){let ag=0;for(let Rg=0;Rg<Qg.length;Rg++){const UA=sx(R,ag++,Qg[Rg]);fg||=(UA&1)!==0,rg||=(UA&2)!==0}if(c)for(let Rg=0;Rg<Eg.length;Rg++){const UA=Eg[Rg],$A=sx(R,ag++,UA),vg=c._coneChanged(Rg,UA);fg||=($A&1)!==0,rg||=($A&2)!==0||vg}}if(!fg&&!rg){P=kA;return}if(fg){rg=!0,M.fill(0),N.length=0;const ag=l1(cA),Rg=li(cA,mA),UA=cA.nearPlane,$A=cA.farPlane,vg=Math.log($A/UA),Jg=r/vg,nI=-(r*Math.log(UA))/vg;for(const pI of Qg)pI.range>0&&pI.intensity>0&&N.push({light:pI,depth:z0A(pI.position,ag)});c?._collect(N,Eg,ag),N.sort((pI,Ye)=>pI.depth-Ye.depth);const qI=Math.max(1,Math.ceil(N.length/pN)),kI=o*Q*qI;S.fill(0,0,kI);for(let pI=0;pI<r;pI++){const Ye=pI*4;M[Ye]=H0A,M[Ye+1]=0}for(let pI=0;pI<N.length;pI++){const{light:Ye,depth:vI}=N[pI];W0A(M,S,Ye,vI,pI,ag,Rg,o,Q,r,Jg,nI,qI)}G[0]=o,G[1]=Q,G[2]=r,G[3]=N.length,m[4]=Jg,m[5]=nI,G[7]=qI,A._device.queue.writeBuffer(K,0,m),z4(A,L,M,4,r,h),N.length>0&&z4(A,H,S,1,kI,h)}if(rg){for(let ag=0;ag<N.length;ag++){const{light:Rg,_spot:UA}=N[ag],$A=ag*y*4;w.set(Rg.position,$A),w[$A+3]=Rg.range,w.set(Rg.diffuse,$A+4),w[$A+7]=Rg.intensity,c?._write(w,$A,UA)}N.length>0&&z4(A,k,w,4,N.length*y,h)}q=cA,CA=HA,eA=Ag,Z=lg,O=mA,P=kA,gA=ug},dispose(){K.destroy(),k.destroy(),L.destroy(),H.destroy()}};return c?._markState(yA),yA.refresh(e,t,i),yA}function V4(A,g,I){return I*Math.max(1,Math.ceil(A/I))*g}function sx(A,g,I){const e=g*8,t=I.position,i=I.diffuse,o=A[e+3]>0&&A[e+7]>0,Q=I.range>0&&I.intensity>0;let r=0;return(A[e]!==t[0]||A[e+1]!==t[1]||A[e+2]!==t[2]||A[e+3]!==I.range||o!==Q)&&(r|=1),(A[e+4]!==i[0]||A[e+5]!==i[1]||A[e+6]!==i[2]||A[e+7]!==I.intensity)&&(r|=2),A.set(t,e),A[e+3]=I.range,A.set(i,e+4),A[e+7]=I.intensity,r}function W4(A,g,I,e,t){const i=Math.max(1,Math.ceil(I/t));return A._device.createTexture({label:e,size:{width:t,height:i},format:g,usage:dA.TEXTURE_BINDING|dA.COPY_DST})}function z4(A,g,I,e,t,i){const o=Math.max(1,Math.ceil(t/i)),Q=o>1?i:Math.max(1,Math.min(t,i));A._device.queue.writeTexture({texture:g},I.buffer,{bytesPerRow:Q*e*4,rowsPerImage:o},{width:Q,height:o})}function W0A(A,g,I,e,t,i,o,Q,r,E,n,s,c){const l=i[0]*I.position[0]+i[4]*I.position[1]+i[8]*I.position[2]+i[12],D=i[1]*I.position[0]+i[5]*I.position[1]+i[9]*I.position[2]+i[13],p=e,y=Math.max(0,I.range),_=ax(p-y,n,s),u=ax(p+y,n,s);if(u<0||_>=E)return;const f=Z0A(l,D,p,y,o,Q,r),h=f[0],w=f[1],M=f[2],S=f[3],R=ar(_,0,E-1),N=ar(u,0,E-1);for(let m=R;m<=N;m++){const K=m*4;A[K]=Math.min(A[K],t),A[K+1]=Math.max(A[K+1],t)}const F=Math.floor(t/pN),G=1<<t%pN;for(let m=M;m<=S;m++)for(let K=h;K<=w;K++){const k=(K*r+m)*c+F;g[k]=g[k]|G}}function z0A(A,g){return g[2]*A[0]+g[6]*A[1]+g[10]*A[2]+g[14]}function ax(A,g,I){return A>0?Math.floor(Math.log(A)*g+I):-1}function ar(A,g,I){return A<g?g:A>I?I:A}function Z0A(A,g,I,e,t,i,o){const Q=e*e;let r=-1,E=1,n=-1,s=1;if(t[11]===0){const c=t[0],l=t[5],D=c*A+t[12],p=l*g+t[13],y=Math.abs(c*e),_=Math.abs(l*e);r=Math.max(D-y,-1),E=Math.min(D+y,1),n=Math.max(p-_,-1),s=Math.min(p+_,1)}else if(I>e){const c=ym(A,I,Q,t[0],-1),l=ym(A,I,Q,t[0],1);r=Math.min(c,l),E=Math.max(c,l);const D=ym(g,I,Q,t[5],-1),p=ym(g,I,Q,t[5],1);n=Math.min(D,p),s=Math.max(D,p)}return[ar(Math.floor((r*.5+.5)*i)-1,0,i-1),ar(Math.floor((E*.5+.5)*i)+1,0,i-1),ar(Math.floor((.5-s*.5)*o)-1,0,o-1),ar(Math.floor((.5-n*.5)*o)+1,0,o-1)]}function ym(A,g,I,e,t){const i=A*A+g*g;if(i<=I)return t;const o=I/i,Q=Math.max(1-o,.01),r=t*Math.sqrt(o*Q),E=Q*A+r*g,n=-r*A+Q*g;return e*E/Math.max(n,.01)}let Z4=null;function cx(){if(Z4)return Z4;const A=async(g,I)=>{const{buildShaderGroup:e}=await Promise.resolve().then(()=>tyA),t=await e(g,I);return A._rebuildSingle=t.rebuildSingle,t};return A._materialFamily="shader",Z4=A}function X0A(A){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(A)}function _m(A,g){X0A(g)||U(289,A,g)}function $0A(A){return A==="position"||A==="normal"||A==="uv"||A==="uv2"||A==="tangent"||A==="color"||A==="joints"||A==="weights"||A==="joints1"||A==="weights1"}function lx(A){return A==="world"||A==="view"||A==="projection"||A==="viewProjection"||A==="worldView"||A==="worldViewProjection"||A==="cameraPosition"||A==="screenSize"||A==="alphaCutoff"}function AaA(A){return A==="cameraPosition"?"vec3<f32>":A==="screenSize"?"vec2<f32>":A==="alphaCutoff"?"f32":"mat4x4<f32>"}function cr(A){return lx(A)}function yN(A){(!A.vertexSource||!A.fragmentSource)&&U(290);const g=[],I=new Set;for(const c of A.attributes)$0A(c)||U(291,String(c)),I.has(c)&&U(292,c),I.add(c),g.push(c);I.has("position")||U(293);const e=[],t=new Map,i=new Set;for(const c of A.uniforms??[]){const l=typeof c=="string"?gaA(c):IaA(c);_N(i,"uniform",l.name),e.push(l),t.set(l.name,{decl:l,value:CaA(l,l.defaultValue??taA(l)),_v:0})}const o=[],Q=new Map;for(const c of A.samplers??[]){const l=typeof c=="string"?{name:c,sampleType:"float"}:{name:c.name,sampleType:c.sampleType??(c.comparison?"depth":"float"),viewDimension:c.viewDimension??"2d",comparison:c.comparison??!1};_m("sampler",l.name),_N(i,"sampler",l.name),_N(i,"sampler",`${l.name}Sampler`),o.push(l),Q.set(l.name,{decl:l,current:null})}const r=[],E=new Map;for(const c of A.storageBuffers??[])_m("storage buffer",c.name),_N(i,"storage buffer",c.name),r.push(c),E.set(c.name,{decl:c,current:null});const n=[];for(const[c,l]of Object.entries(A.defines??{}))_m("define",c),_N(i,"define",c),typeof l!="boolean"&&typeof l!="number"&&U(294,c),n.push({name:c,value:l});n.sort((c,l)=>c.name.localeCompare(l.name));const s=A.needAlphaBlending??!!A.blend;return A.transmissive&&!s&&U(295),{name:A.name,vertexSource:A.vertexSource,fragmentSource:A.fragmentSource,attributes:g,uniformDecls:e,samplerDecls:o,storageBufferDecls:r,defines:n,_tic:A.useThinInstanceColors,needAlphaBlending:s,blendMode:A.blendMode??"alpha",...A.blend?{blend:A.blend}:{},transmissive:A.transmissive??!1,needAlphaTesting:A.needAlphaTesting??!1,backFaceCulling:A.backFaceCulling??!0,depthWrite:A.depthWrite??!s,depthCompare:A.depthCompare??"greater-equal",depthOnlyFragment:A.depthOnlyFragment??!1,depthBias:A.depthBias??0,depthBiasSlopeScale:A.depthBiasSlopeScale??0,_buildGroup:cx(),_uboVersion:0,_uniformValues:t,_textureSlots:Q,_storageBufferSlots:E,_uniformVersion:0,_resourceVersion:0}}function gaA(A){return lx(A)||U(296,A),{name:A,type:AaA(A)}}function IaA(A){return _m("uniform",A.name),eaA(A.type)||U(297,String(A.type),A.name),A}function eaA(A){return A==="f32"||A==="u32"||A==="i32"||A==="vec2<f32>"||A==="vec3<f32>"||A==="vec4<f32>"||A==="mat4x4<f32>"}function _N(A,g,I){A.has(I)&&U(298,I,g),A.add(I)}function Dx(A){switch(A){case"f32":case"u32":case"i32":return 1;case"vec2<f32>":return 2;case"vec3<f32>":return 3;case"vec4<f32>":return 4;case"mat4x4<f32>":return 16}}function taA(A){if(A.name==="alphaCutoff")return .4;const g=Dx(A.type);return g===1?0:new Array(g).fill(0)}function CaA(A,g){const I=Dx(A.type),e=typeof g=="number"?new X([g]):g instanceof X?new X(g):new X(g);return e.length!==I&&U(299,A.name,A.type,I,e.length),e}function px(A,g,I){const e=A._uniformValues.get(g);e||U(300,g);const t=e.value,i=t.length,o=typeof I=="number"?1:I.length;o!==i&&U(301,e.decl.name,e.decl.type,i,o);let Q=!1;if(typeof I=="number"){const r=Math.fround(I);t[0]!==r&&(t[0]=r,Q=!0)}else for(let r=0;r<i;r++){const E=Math.fround(I[r]);t[r]!==E&&(t[r]=E,Q=!0)}Q&&(e._v=(e._v|0)+1,A._uniformVersion++,A._uboVersion=A._uniformVersion)}function lQ(A,g,I){px(A,g,I)}function yx(A,g,I){const e=A._textureSlots.get(g);if(e||U(302,g),I){const t=e.decl.comparison||e.decl.sampleType==="depth",i=I._sampleType==="depth";t&&!i&&U(303,g),!t&&i&&U(304,g)}e.current!==I&&(e.current=I,A._resourceVersion++,cC())}function iaA(A,g,I){const e=A._storageBufferSlots.get(g);e||U(305,g),I&&!("_engine"in I)&&U(306),I?._destroyed&&U(307,g),I&&!I._engine._storageBuffers?.has(I)&&U(308),e.current!==I&&(e.current=I,A._resourceVersion++,cC())}function oaA(A,g,I){lQ(A,g,I)}function BaA(A,g,I){lQ(A,g,I)}function QaA(A,g,I){px(A,g,I)}let X4=null;function _x(A,g){g.useThinInstances&&!A.thinInstances&&U(177,g.name??"<unnamed>")}function raA(){if(X4)return X4;const A=cx(),g=async(I,e)=>{for(const Q of e)_x(Q,Q.material);const t=await A(I,e),i=t.rebuildSingle,o=(Q,r,E)=>(_x(r,E??r.material),i(Q,r,E));return g._rebuildSingle=o,{...t,rebuildSingle:o}};return g._materialFamily="shader",X4=g}function ux(A){return`struct VertexOutput{@builtin(position)position:vec4<f32>,${A?"@location(0) color:vec4<f32>,":""}};`}function EaA(A,g,I){const e=A||I,t=g?"let instanceWorld=mat4x4<f32>(input.world0,input.world1,input.world2,input.world3);let finalWorld=shaderSystem.world*instanceWorld;":"let finalWorld=shaderSystem.world;",i=A&&I?"out.color=input.color*input.instanceColor;":A?"out.color=input.color;":I?"out.color=input.instanceColor;":"";return`${ux(e)} @vertex fn mainVertex(input:VertexInput)->VertexOutput{var out:VertexOutput;${t}out.position=shaderSystem.viewProjection*finalWorld*vec4<f32>(input.position,1.0);${i}return out;}`}function naA(A){return`${ux(A)} @fragment fn mainFragment(input:VertexOutput)->@location(0)vec4<f32>{return ${A?"input.color":"shaderUniforms.lineColor"};}`}function hx(A={}){const g=A.useVertexColor??!1,I=A.useVertexAlpha??!0,e=A.useThinInstances??!1,t=A.useThinInstanceColors??!1;t&&!e&&U(178);const i=A.color??{r:1,g:1,b:1,a:1},o={r:i.r,g:i.g,b:i.b,a:i.a},Q=g||t,r=yN({name:A.name??"LineMaterial",vertexSource:EaA(g,e,t),fragmentSource:naA(Q),attributes:g?["position","color"]:["position"],uniforms:["world","viewProjection",...Q?[]:[{name:"lineColor",type:"vec4<f32>",defaultValue:[o.r,o.g,o.b,o.a]}]],useThinInstanceColors:t,needAlphaBlending:I,blendMode:"alpha",backFaceCulling:!1,depthWrite:A.depthWrite,depthCompare:A.depthCompare});return Object.assign(r,{useVertexColor:g,useVertexAlpha:I,useThinInstances:e,useThinInstanceColors:t,color:o,_topology:"line-list",_buildGroup:raA()}),r}function saA(A,g){A.color.r=g.r,A.color.g=g.g,A.color.b=g.b,A.color.a=g.a,!A.useVertexColor&&!A.useThinInstanceColors&&lQ(A,"lineColor",[g.r,g.g,g.b,g.a])}function DQ(A,g){Number.isFinite(g)||U(324,A)}function fx(A,g,I,e){const{lines:t,colors:i}=A;i&&i.length!==t.length&&U(325);const o=new Float32Array(g*3),Q=i?new Float32Array(g*4):void 0;let r=0,E=0;for(let n=0;n<t.length;n++){const s=t[n],c=i?.[n];c&&c.length!==s.length&&U(326),I&&(I[n]=s.length);for(let l=0;l<s.length;l++){const D=s[l];DQ("position",D.x),DQ("position",D.y),DQ("position",D.z);const p=r*3;if(o[p]=D.x,o[p+1]=D.y,o[p+2]=D.z,Q&&c){const y=c[l];DQ("color",y.r),DQ("color",y.g),DQ("color",y.b),DQ("color",y.a);const _=r*4;Q[_]=y.r,Q[_+1]=y.g,Q[_+2]=y.b,Q[_+3]=y.a}e&&l>0&&(e[E++]=r-1,e[E++]=r),r++}}return{positions:o,...Q?{colors:Q}:{}}}function dx(A){const{lines:g}=A;let I=0,e=0;for(let r=0;r<g.length;r++){const E=g[r];I+=E.length,e+=Math.max(0,E.length-1)*2}I===0&&U(327);const t=new Float32Array(I*3),i=new Uint32Array(e),o=new Uint32Array(g.length),Q=fx(A,I,o,i);return{positions:Q.positions,normals:t,indices:i,...Q.colors?{colors:Q.colors}:{},linePointCounts:o}}function $4(A,g){const I=dx(g),e=g.material??hx({color:g.color,useVertexColor:!!I.colors,useVertexAlpha:g.useVertexAlpha,useThinInstances:g.useThinInstances,useThinInstanceColors:g.useThinInstanceColors});e.useVertexColor!==!!I.colors&&U(328);const t=Et(A,g.name??"lineSystem",I.positions,I.normals,I.indices,void 0,void 0,void 0,I.colors);return t.material=e,t.hasVertexAlpha=!!I.colors&&e.useVertexAlpha,t._topology=2,t._linePointCounts=I.linePointCounts,t._cpuColors=I.colors??null,t}function aaA(A,g){return $4(A,{name:g.name??"lines",lines:[g.points],...g.colors?{colors:[g.colors]}:{},color:g.color,useVertexAlpha:g.useVertexAlpha,useThinInstances:g.useThinInstances,useThinInstanceColors:g.useThinInstanceColors,material:g.material})}function wx(A,g,I){const e=g._linePointCounts;e||U(329),I.lines.length!==e.length&&U(330);for(let r=0;r<e.length;r++)I.lines[r].length!==e[r]&&U(331);I.colors&&!g._gpu.colorBuffer&&U(332);let t=0;for(const r of e)t+=r;const i=fx(I,t);HF(A,g,i.positions),i.colors&&zH(A,g,i.colors);const[o,Q]=yi(i.positions);g.boundMin=o,g.boundMax=Q,g._cpuPositions=i.positions,i.colors&&(g._cpuColors=i.colors),A._dlr?.m(g,g._cpuUv2s??null,g._cpuTangents??null,g._cpuColors??null,g._cpuIndices,g._cpuIndexFormat??"uint32")}function Mx(A,g,I,e,t){A.length<2&&U(321);let i=0;for(let E=0;E<A.length-1;E++){const n=A[E],s=A[E+1];i+=Math.hypot(s.x-n.x,s.y-n.y,s.z-n.z)}const o=i/e,Q=g*o/(g+I),r=[];for(let E=0;E<A.length-1;E++){const n=A[E],s=A[E+1];let c=s.x-n.x,l=s.y-n.y,D=s.z-n.z;const p=Math.hypot(c,l,D),y=p>0?Math.floor(p/o):0;p>0&&(c/=p,l/=p,D/=p);for(let _=0;_<y&&(t===void 0||r.length<t);_++){const u=o*_;r.push([{x:n.x+u*c,y:n.y+u*l,z:n.z+u*D},{x:n.x+(u+Q)*c,y:n.y+(u+Q)*l,z:n.z+(u+Q)*D}])}}if(t!==void 0){const E=A[A.length-1];for(;r.length<t;)r.push([{x:E.x,y:E.y,z:E.z},{x:E.x,y:E.y,z:E.z}])}return r}function caA(A,g){const I=g.dashSize??3,e=g.gapSize??1,t=g.dashNb??200,i=Mx(g.points,I,e,t);i.length===0&&U(322);const o=$4(A,{name:g.name??"dashedLines",lines:i,color:g.color,useVertexAlpha:g.useVertexAlpha,material:g.material});return o._dashedLineOptions=[I,e],o}function laA(A,g,I){const e=g._dashedLineOptions,t=g._linePointCounts?.length;(!e||!t)&&U(323);const i=Mx(I.points,e[0],e[1],t,t);wx(A,g,{lines:i})}function DaA(A){const g=A._cpuPositions,I=A._cpuIndices;return!g||!I?null:{positions:g.slice(),indices:I.slice()}}function paA(A){const g=A._cpuPositions,I=A._cpuNormals,e=A._cpuIndices;if(!g||!I||!e)return null;const t=A._cpuUvs,i=A._cpuUv2s,o=A._cpuTangents,Q=A._cpuColors;return{positions:g.slice(),normals:I.slice(),indices:e.slice(),...t?{uvs:t.slice()}:{},...i?{uvs2:i.slice()}:{},...o?{tangents:o.slice()}:{},...Q?{colors:Q.slice()}:{}}}function tC(A,g,I,e=1e-10){const t=Math.hypot(A,g,I);return t<=e?[0,1,0]:[A/t,g/t,I/t]}class OJ{constructor(g,I,e,t){this.nx=g,this.ny=I,this.nz=e,this.w=t}clone(){return new OJ(this.nx,this.ny,this.nz,this.w)}flip(){this.nx=-this.nx,this.ny=-this.ny,this.nz=-this.nz,this.w=-this.w}}class WG{constructor(g,I=0){this.vertices=g,this.materialSlot=I,this.plane=_aA(g[0],g[1],g[2])}plane;clone(){return new WG(this.vertices.map(hm),this.materialSlot)}flip(){this.vertices.reverse(),this.vertices=this.vertices.map(g=>({...g,nx:-g.nx,ny:-g.ny,nz:-g.nz})),this.plane.flip()}}class ei{plane=null;polygons=[];front=null;back=null;constructor(g=[]){g.length>0&&this.build(g)}clone(){const g=new ei;return g.plane=this.plane?.clone()??null,g.polygons=this.polygons.map(I=>I.clone()),g.front=this.front?.clone()??null,g.back=this.back?.clone()??null,g}invert(){for(const I of this.polygons)I.flip();this.plane?.flip(),this.front?.invert(),this.back?.invert();const g=this.front;this.front=this.back,this.back=g}clipPolygons(g){if(!this.plane)return g.map(t=>t.clone());let I=[],e=[];for(const t of g)Rx(this.plane,t,I,e,I,e);return this.front&&(I=this.front.clipPolygons(I)),this.back?e=this.back.clipPolygons(e):e=[],I.concat(e)}clipTo(g){this.polygons=g.clipPolygons(this.polygons),this.front?.clipTo(g),this.back?.clipTo(g)}allPolygons(){let g=this.polygons.map(I=>I.clone());return this.front&&(g=g.concat(this.front.allPolygons())),this.back&&(g=g.concat(this.back.allPolygons())),g}build(g){if(g.length===0)return;this.plane||(this.plane=g[0].plane.clone());const I=[],e=[];for(const t of g)Rx(this.plane,t,this.polygons,this.polygons,I,e);I.length>0&&(this.front||(this.front=new ei),this.front.build(I)),e.length>0&&(this.back||(this.back=new ei),this.back.build(e))}}const um=1e-5,Sx=0,A9=1,g9=2,yaA=3;function hm(A){return{x:A.x,y:A.y,z:A.z,nx:A.nx,ny:A.ny,nz:A.nz,u:A.u,v:A.v}}function _aA(A,g,I){const e=g.x-A.x,t=g.y-A.y,i=g.z-A.z,o=I.x-A.x,Q=I.y-A.y,r=I.z-A.z,[E,n,s]=tC(Q*i-r*t,r*e-o*i,o*t-Q*e,1e-20);return new OJ(E,n,s,E*A.x+n*A.y+s*A.z)}function uaA(A,g,I){const e=g.x-A.x,t=g.y-A.y,i=g.z-A.z,o=I.x-A.x,Q=I.y-A.y,r=I.z-A.z,E=t*r-i*Q,n=i*o-e*r,s=e*Q-t*o;return E*E+n*n+s*s}function haA(A,g,I){const e=A.nx+(g.nx-A.nx)*I,t=A.ny+(g.ny-A.ny)*I,i=A.nz+(g.nz-A.nz)*I,[o,Q,r]=tC(e,t,i,1e-20);return{x:A.x+(g.x-A.x)*I,y:A.y+(g.y-A.y)*I,z:A.z+(g.z-A.z)*I,nx:o,ny:Q,nz:r,u:A.u+(g.u-A.u)*I,v:A.v+(g.v-A.v)*I}}function Rx(A,g,I,e,t,i){let o=0;const Q=[];for(const n of g.vertices){const s=A.nx*n.x+A.ny*n.y+A.nz*n.z-A.w,c=s<-um?g9:s>um?A9:Sx;o|=c,Q.push(c)}if(o===Sx){(A.nx*g.plane.nx+A.ny*g.plane.ny+A.nz*g.plane.nz>0?I:e).push(g);return}if(o===A9){t.push(g);return}if(o===g9){i.push(g);return}const r=[],E=[];for(let n=0;n<g.vertices.length;n++){const s=(n+1)%g.vertices.length,c=g.vertices[n],l=g.vertices[s],D=Q[n],p=Q[s];if(D!==g9&&r.push(hm(c)),D!==A9&&E.push(hm(c)),(D|p)===yaA){const y=A.nx*(l.x-c.x)+A.ny*(l.y-c.y)+A.nz*(l.z-c.z);if(Math.abs(y)>1e-20){const _=(A.w-A.nx*c.x-A.ny*c.y-A.nz*c.z)/y,u=haA(c,l,_);r.push(u),E.push(hm(u))}}}r.length>=3&&t.push(new WG(r,g.materialSlot)),E.length>=3&&i.push(new WG(E,g.materialSlot))}function fm(A){return{_polygons:A}}function lr(A){return A._polygons.map(g=>g.clone())}function faA(A,g,I,e){return[A[0]*g+A[4]*I+A[8]*e+A[12],A[1]*g+A[5]*I+A[9]*e+A[13],A[2]*g+A[6]*I+A[10]*e+A[14]]}function daA(A,g,I,e,t){return g?tC(g[0]*I+g[1]*e+g[2]*t,g[4]*I+g[5]*e+g[6]*t,g[8]*I+g[9]*e+g[10]*t,1e-20):tC(A[0]*I+A[4]*e+A[8]*t,A[1]*I+A[5]*e+A[9]*t,A[2]*I+A[6]*e+A[10]*t,1e-20)}function waA(A){return A._cpuPositions||U(333,A.name),A._cpuIndices||U(334,A.name),A._cpuNormals||U(335,A.name),A}function MaA(A,g=0){const I=waA(A),e=I._cpuPositions,t=I._cpuNormals,i=I._cpuIndices,o=I._cpuUvs,Q=A.worldMatrix,r=lt(Q),E=[];for(let n=0;n<i.length;n+=3){const s=[];for(let c=0;c<3;c++){const l=i[n+c],D=l*3,p=l*2,[y,_,u]=faA(Q,e[D],e[D+1],e[D+2]),[f,h,w]=daA(Q,r,t[D],t[D+1],t[D+2]);s.push({x:y,y:_,z:u,nx:f,ny:h,nz:w,u:o?.[p]??0,v:o?.[p+1]??0})}uaA(s[0],s[1],s[2])<=um*um||E.push(new WG(s,g))}return fm(E)}function SaA(A,g){const I=new ei(lr(A)),e=new ei(lr(g));return I.clipTo(e),e.clipTo(I),e.invert(),e.clipTo(I),e.invert(),I.build(e.allPolygons()),fm(I.allPolygons())}function RaA(A,g){const I=new ei(lr(A)),e=new ei(lr(g));return I.invert(),I.clipTo(e),e.clipTo(I),e.invert(),e.clipTo(I),e.invert(),I.build(e.allPolygons()),I.invert(),fm(I.allPolygons())}function NaA(A,g){const I=new ei(lr(A)),e=new ei(lr(g));return I.invert(),e.clipTo(I),e.invert(),I.clipTo(e),e.clipTo(I),I.build(e.allPolygons()),I.invert(),fm(I.allPolygons())}function GaA(A,g,I){const e=[],t=[],i=[],o=[];for(const Q of g){const r=e.length/3;for(const E of Q.vertices)e.push(E.x,E.y,E.z),t.push(E.nx,E.ny,E.nz),i.push(E.u,E.v);for(let E=2;E<Q.vertices.length;E++)o.push(r,r+E-1,r+E)}return Et(A,I,new X(e),new X(t),new Vg(o),new X(i))}function FaA(A,g,I="csg"){return GaA(A,g._polygons,I)}const dm=65536;let Dr=null,pr=null;function maA(){return Dr!==null}async function baA(){await KaA()}async function KaA(){return Dr||pr||(pr=(async()=>{const[A,g]=await Promise.all([Promise.resolve().then(()=>EJA),Promise.resolve().then(()=>sJA)]),I=import.meta.url,e=await A.default({locateFile:()=>new URL(g.default,I).href});e.setup();const t={Manifold:e.Manifold,Mesh:e.Mesh,firstMaterialId:e.Manifold.reserveIDs(dm)};return Dr=t,t})(),pr.catch(()=>{pr=null}),pr)}function wm(){return Dr||U(337),Dr}function Mm(A,g){const I=A._manifold;return I||U(338,g),I}function Nx(A,g){return{_manifold:A,_numProp:g}}function kaA(A,g,I,e){return[A[0]*g+A[4]*I+A[8]*e+A[12],A[1]*g+A[5]*I+A[9]*e+A[13],A[2]*g+A[6]*I+A[10]*e+A[14]]}function UaA(A,g,I,e,t){return g?tC(g[0]*I+g[1]*e+g[2]*t,g[4]*I+g[5]*e+g[6]*t,g[8]*I+g[9]*e+g[10]*t,1e-20):tC(A[0]*I+A[4]*e+A[8]*t,A[1]*I+A[5]*e+A[9]*t,A[2]*I+A[6]*e+A[10]*t,1e-20)}function LaA(A){return A._cpuPositions||U(339,A.name),A._cpuIndices||U(340,A.name),A._cpuNormals||U(341,A.name),{positions:A._cpuPositions,normals:A._cpuNormals,indices:A._cpuIndices,uvs:A._cpuUvs}}function YaA(A,g=0){const I=wm();(g<0||g>=dm||!Number.isInteger(g))&&U(342,A.name,dm-1);const e=LaA(A),t=e.positions.length/3,i=8,o=new X(t*i),Q=A.worldMatrix,r=lt(Q);for(let s=0;s<t;s++){const c=s*3,l=s*2,D=s*i,[p,y,_]=kaA(Q,e.positions[c],e.positions[c+1],e.positions[c+2]),[u,f,h]=UaA(Q,r,e.normals[c],e.normals[c+1],e.normals[c+2]);o[D]=p,o[D+1]=y,o[D+2]=_,o[D+3]=u,o[D+4]=f,o[D+5]=h,o[D+6]=e.uvs?.[l]??0,o[D+7]=e.uvs?.[l+1]??0}const E=new Vg(e.indices.length);for(let s=0;s<e.indices.length;s+=3)E[s]=e.indices[s+2],E[s+1]=e.indices[s+1],E[s+2]=e.indices[s];const n=new I.Mesh({numProp:i,vertProperties:o,triVerts:E,runIndex:new Vg([0]),runOriginalID:new Vg([I.firstMaterialId+g])});n.merge();try{const s=I.Manifold;return Nx(s(n),i)}catch(s){throw new Error(`Error while creating CSG2 from mesh "${A.name}".`,{cause:s})}}function I9(A,g,I){const e=wm();return g._numProp!==I._numProp&&U(343),Nx(e.Manifold[A](Mm(g,`csg2 ${A}`),Mm(I,`csg2 ${A}`)),g._numProp)}function JaA(A,g){return I9("difference",A,g)}function vaA(A,g){return I9("intersection",A,g)}function HaA(A,g){return I9("union",A,g)}function TaA(A){A._manifold&&(A._manifold.delete(),A._manifold=null)}function xaA(A,g,I){const e=g-A.firstMaterialId;return(e<0||e>=dm)&&U(344,I,g),e}function Gx(A,g,I,e,t){const i=A.positions.length/3;for(let o=2;o>=0;o--){const r=I[t+o]*e;A.positions.push(g.vertProperties[r],g.vertProperties[r+1],g.vertProperties[r+2]),A.normals.push(g.vertProperties[r+3],g.vertProperties[r+4],g.vertProperties[r+5]),A.uvs.push(g.vertProperties[r+6],g.vertProperties[r+7]),A.indices.push(i+(2-o))}}function Fx(A,g,I){return I.positions.length===0&&U(345,g),Et(A,g,new X(I.positions),new X(I.normals),new Vg(I.indices),new X(I.uvs))}function qaA(A,g,I="csg2"){wm();const e=Mm(g,`createMeshFromCsg2("${I}")`).getMesh(),t={positions:[],normals:[],uvs:[],indices:[]};for(let i=0;i<e.triVerts.length;i+=3)Gx(t,e,e.triVerts,g._numProp,i);return Fx(A,I,t)}function PaA(A,g,I,e="csg2"){const t=wm(),i=Mm(g,`createMeshesFromCsg2("${e}")`).getMesh(),o=[];for(let Q=0;Q<i.numRun;Q++){const r=i.runOriginalID[Q],E=xaA(t,r,e);let n=o.find(l=>l.materialSlot===E);n||(n={materialSlot:E,positions:[],normals:[],uvs:[],indices:[]},o.push(n));const s=i.runIndex[Q]??0,c=i.runIndex[Q+1]??i.triVerts.length;for(let l=s;l<c;l+=3)Gx(n,i,i.triVerts,g._numProp,l)}return o.sort((Q,r)=>Q.materialSlot-r.materialSlot),o.map(Q=>{const r=I[Q.materialSlot];r||U(346,e,Q.materialSlot);const E=Fx(A,`${e}_sub${Q.materialSlot}`,Q);return E.material=r,E})}function OaA(A,g,I){const e=EF(Math.max(g.byteLength,4),4),t=new Uint8Array(e);t.set(new Uint8Array(g.buffer,g.byteOffset,g.byteLength));const i={byteLength:e};if(Object.defineProperties(i,{_buffer:{value:wI(A,t,SA.STORAGE,I),writable:!0},_destroyed:{value:!1,writable:!0},_data:{value:t,writable:!0},_engine:{value:A},_label:{value:I}}),(A._storageBuffers??=new Set).add(i),!A._storageRequiredLimits){const o=A._device.limits;o&&(A._storageRequiredLimits={maxBufferSize:o.maxBufferSize,maxStorageBufferBindingSize:o.maxStorageBufferBindingSize,maxStorageBuffersPerShaderStage:o.maxStorageBuffersPerShaderStage})}return A._rebuildStorageBuffers??=()=>WaA(A),A._disposeStorageBuffers??=()=>zaA(A),i}function jaA(A,g){return(g._destroyed||!g._data)&&U(448),g._engine!==A&&U(449),A._storageBuffers?.has(g)||U(450),g._buffer}function VaA(A,g,I,e=0){if(g._destroyed&&U(451),"_engine"in g||U(452),g._engine!==A&&U(453),A._storageBuffers?.has(g)||U(454),(!Number.isInteger(e)||e<0||(e&3)!==0)&&U(455),(I.byteLength&3)!==0&&U(456),e+I.byteLength>g.byteLength&&U(457,g.byteLength),I.byteLength===0)return;A._device.queue.writeBuffer(g._buffer,e,I.buffer,I.byteOffset,I.byteLength);const t=I instanceof Uint8Array?I:new Uint8Array(I.buffer,I.byteOffset,I.byteLength);g._data.set(t,e)}function mx(A){A._destroyed||((!("_engine"in A)||!A._engine._storageBuffers?.has(A))&&U(458),A._buffer?.destroy(),A._buffer=null,A._engine._storageBuffers.delete(A),A._data=null,A._destroyed=!0,A._engine._storageBuffers.size===0&&(A._engine._storageBuffers=void 0,A._engine._storageRequiredLimits=void 0,A._engine._rebuildStorageBuffers=void 0,A._engine._disposeStorageBuffers=void 0))}function WaA(A){for(const g of A._storageBuffers??[])!g._destroyed&&g._data&&(g._buffer=wI(A,g._data,SA.STORAGE,g._label))}function zaA(A){for(const g of[...A._storageBuffers??[]])mx(g)}function bx(A,g,I,e,t={}){(I<1||e<1)&&U(564,I,e);const i=I*e*4;g.length<i&&U(565,i,I,e,g.length);const o=A._device,Q=t.srgb?"rgba8unorm-srgb":"rgba8unorm",r=o.createTexture({size:{width:I,height:e},format:Q,usage:dA.TEXTURE_BINDING|dA.COPY_DST});o.queue.writeTexture({texture:r},g,{bytesPerRow:I*4,rowsPerImage:e},{width:I,height:e});const E={addressModeU:t.addressModeU??"clamp-to-edge",addressModeV:t.addressModeV??"clamp-to-edge",minFilter:t.minFilter??"nearest",magFilter:t.magFilter??"nearest"},n=Pe(A,E),s={texture:r,view:r.createView(),sampler:n,width:I,height:e};return A._dlr?.p(s,g,t),rt(s),s}function ZaA(A,g,I,e={}){(g<1||I<1)&&U(566,g,I);const t=A._device,i=e.format??A.format,o=t.createTexture({size:{width:g,height:I},format:i,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST}),Q={addressModeU:e.addressModeU??"clamp-to-edge",addressModeV:e.addressModeV??"clamp-to-edge",minFilter:e.minFilter??"linear",magFilter:e.magFilter??"linear"},r=Pe(A,Q),E={texture:o,view:o.createView(),sampler:r,width:g,height:I};return A._dlr?.r(E,g,I,i,Q),rt(E),E}function XaA(A,g,I,e=0,t=0,i=g.width,o=g.height){(i<1||o<1)&&U(567,i,o);const Q=i*o*4;I.length<Q&&U(568,Q,i,o,I.length),A._device.queue.writeTexture({texture:g.texture,origin:{x:e,y:t}},I,{bytesPerRow:i*4,rowsPerImage:o},{width:i,height:o}),A._dlr?.w(g,I,e,t,i,o)}function $aA(A,g,I,e,t,i={}){(I<1||e<1||t<1)&&U(569,I,e,t);const o=I*e*t*4;g.length<o&&U(570,o,I,e,t,g.length);const Q=A._device,r=i.srgb?"rgba8unorm-srgb":"rgba8unorm",E=Q.createTexture({size:{width:I,height:e,depthOrArrayLayers:t},dimension:"3d",format:r,usage:dA.TEXTURE_BINDING|dA.COPY_DST});Q.queue.writeTexture({texture:E},g,{bytesPerRow:I*4,rowsPerImage:e},{width:I,height:e,depthOrArrayLayers:t});const n=i.addressMode??"clamp-to-edge",s=i.filter??"linear",c=Pe(A,{addressModeU:n,addressModeV:n,addressModeW:n,minFilter:s,magFilter:s}),l={texture:E,view:E.createView({dimension:"3d"}),sampler:c,width:I,height:e,depth:t};return rt(l),l}let e9=null;function AcA(){if(e9)return e9;const A=new Map;e9=A;function g(o,Q,r,E,n,s){A.set(o,{gpuFormat:Q,feature:r,blockW:E,blockH:n,blockBytes:s})}const I="texture-compression-bc",e="texture-compression-etc2",t="texture-compression-astc";g(33776,"bc1-rgba-unorm",I,4,4,8),g(33777,"bc1-rgba-unorm",I,4,4,8),g(33778,"bc2-rgba-unorm",I,4,4,16),g(33779,"bc3-rgba-unorm",I,4,4,16),g(36283,"bc4-r-unorm",I,4,4,8),g(36284,"bc4-r-snorm",I,4,4,8),g(36285,"bc5-rg-unorm",I,4,4,16),g(36286,"bc5-rg-snorm",I,4,4,16),g(36495,"bc6h-rgb-ufloat",I,4,4,16),g(36494,"bc6h-rgb-float",I,4,4,16),g(36492,"bc7-rgba-unorm",I,4,4,16),g(36493,"bc7-rgba-unorm-srgb",I,4,4,16),g(37488,"eac-r11unorm",e,4,4,8),g(37489,"eac-r11snorm",e,4,4,8),g(37490,"eac-rg11unorm",e,4,4,16),g(37491,"eac-rg11snorm",e,4,4,16),g(37492,"etc2-rgb8unorm",e,4,4,8),g(37493,"etc2-rgb8unorm-srgb",e,4,4,8),g(37494,"etc2-rgb8a1unorm",e,4,4,8),g(37495,"etc2-rgb8a1unorm-srgb",e,4,4,8),g(37496,"etc2-rgba8unorm",e,4,4,16),g(37497,"etc2-rgba8unorm-srgb",e,4,4,16);const i=[[4,4],[5,4],[5,5],[6,5],[6,6],[8,5],[8,6],[8,8],[10,5],[10,6],[10,8],[10,10],[12,10],[12,12]];for(let o=0;o<i.length;o++){const[Q,r]=i[o],E=`${Q}x${r}`;g(37808+o,`astc-${E}-unorm`,t,Q,r,16),g(37840+o,`astc-${E}-unorm-srgb`,t,Q,r,16)}return A}function t9(A){return AcA().get(A)}function gcA(A){const g=A.toLowerCase();if(g.includes("astc"))return"texture-compression-astc";if(g.includes("dxt")||g.includes("s3tc")||g.includes("bc"))return"texture-compression-bc";if(g.includes("etc"))return"texture-compression-etc2"}let Kx="https://cdn.babylonjs.com/babylon.ktx2Decoder.js",uN=null;function IcA(A,g){Kx=A,uN=g??null}let yr=null;const ecA=32856,tcA=33321,CcA=33323,kx={astc:!1,bptc:!1,s3tc:!1,pvrtc:!1,etc2:!1,etc1:!1};function icA(A){const g=A._device.features,I=g.has("texture-compression-bc"),e=g.has("texture-compression-etc2");return{astc:g.has("texture-compression-astc"),bptc:I,s3tc:I,pvrtc:!1,etc2:e,etc1:e}}function C9(){return yr||(yr=new Promise((A,g)=>{const I=globalThis,e=()=>{const i=I.KTX2DECODER;if(!i){g(new Error("KTX2: decoder global KTX2DECODER not found after script load"));return}if(i.MSCTranscoder.UseFromWorkerThread=!1,i.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,uN){const o=i;for(const Q of Object.keys(uN)){const r=o[Q];if(r)for(const E of Object.keys(uN[Q]))r[E]=uN[Q][E]}}A(new i.KTX2Decoder)};if(I.KTX2DECODER){e();return}const t=document.createElement("script");t.src=Kx,t.async=!0,t.onload=e,t.onerror=()=>g(new Error(`KTX2: failed to load ${t.src}`)),document.head.appendChild(t)}),yr.catch(()=>{yr=null}),yr)}function i9(A){switch(A){case"rgba8unorm":return"rgba8unorm-srgb";case"bc1-rgba-unorm":return"bc1-rgba-unorm-srgb";case"bc2-rgba-unorm":return"bc2-rgba-unorm-srgb";case"bc3-rgba-unorm":return"bc3-rgba-unorm-srgb";case"bc7-rgba-unorm":return"bc7-rgba-unorm-srgb";case"etc2-rgb8unorm":return"etc2-rgb8unorm-srgb";case"etc2-rgb8a1unorm":return"etc2-rgb8a1unorm-srgb";case"etc2-rgba8unorm":return"etc2-rgba8unorm-srgb";case"astc-4x4-unorm":return"astc-4x4-unorm-srgb";case"astc-5x4-unorm":return"astc-5x4-unorm-srgb";case"astc-5x5-unorm":return"astc-5x5-unorm-srgb";case"astc-6x5-unorm":return"astc-6x5-unorm-srgb";case"astc-6x6-unorm":return"astc-6x6-unorm-srgb";case"astc-8x5-unorm":return"astc-8x5-unorm-srgb";case"astc-8x6-unorm":return"astc-8x6-unorm-srgb";case"astc-8x8-unorm":return"astc-8x8-unorm-srgb";case"astc-10x5-unorm":return"astc-10x5-unorm-srgb";case"astc-10x6-unorm":return"astc-10x6-unorm-srgb";case"astc-10x8-unorm":return"astc-10x8-unorm-srgb";case"astc-10x10-unorm":return"astc-10x10-unorm-srgb";case"astc-12x10-unorm":return"astc-12x10-unorm-srgb";case"astc-12x12-unorm":return"astc-12x12-unorm-srgb";default:return A}}function Ux(A){switch(A){case ecA:return{format:"rgba8unorm",bytesPerPixel:4};case tcA:return{format:"r8unorm",bytesPerPixel:1};case CcA:return{format:"rg8unorm",bytesPerPixel:2};default:return null}}function Lx(A){A.errors&&U(552,A.errors),A.mipmaps.length||U(553);for(let g=0;g<A.mipmaps.length;g++)A.mipmaps[g]?.data||U(554,g);return A.mipmaps}function o9(A,g){return Pe(A,{addressModeU:"repeat",addressModeV:"repeat",minFilter:"linear",magFilter:"linear",mipmapFilter:g>1?"linear":"nearest",maxAnisotropy:g>1?4:1})}function ocA(A,g,I,e){A._device.features.has(I.feature)||U(555,I.feature);const t=g[0].width,i=g[0].height,o=A._device.createTexture({size:{width:t,height:i},format:e?i9(I.gpuFormat):I.gpuFormat,mipLevelCount:g.length,usage:dA.TEXTURE_BINDING|dA.COPY_DST});for(let r=0;r<g.length;r++){const E=g[r],n=Math.ceil(E.width/I.blockW),s=n*I.blockBytes,c=n*I.blockW,l=Math.ceil(E.height/I.blockH)*I.blockH;A._device.queue.writeTexture({texture:o,mipLevel:r},E.data,{bytesPerRow:s},{width:c,height:l})}const Q={texture:o,view:o.createView(),sampler:o9(A,g.length),width:t,height:i,invertY:!0};return rt(Q),Q}function BcA(A,g,I,e){const t=g[0].width,i=g[0].height,o=A._device.createTexture({size:{width:t,height:i},format:e?i9(I.format):I.format,mipLevelCount:g.length,usage:dA.TEXTURE_BINDING|dA.COPY_DST});for(let r=0;r<g.length;r++){const E=g[r],n=E.width*E.height*I.bytesPerPixel;E.data.length!==n&&U(556,r,E.data.length,n),A._device.queue.writeTexture({texture:o,mipLevel:r},E.data,{bytesPerRow:E.width*I.bytesPerPixel},{width:E.width,height:E.height})}const Q={texture:o,view:o.createView(),sampler:o9(A,g.length),width:t,height:i,invertY:!0};return rt(Q),Q}async function Yx(A,g){const e=await(await C9()).decode(new mg(g),icA(A));return Lx(e),e}async function Jx(A,g,I){const e=await Yx(A,g),t=e.mipmaps,i=t9(e.transcodedFormat);if(i)return ocA(A,t,i,I);const o=Ux(e.transcodedFormat);if(o)return BcA(A,t,o,I);U(557,e.transcodedFormat.toString(16))}async function QcA(A,g,I=!1){const e=await fetch(g);return e.ok||U(558,e.status,g),Jx(A,await e.arrayBuffer(),I)}async function rcA(A){const I=await(await C9()).decode(new mg(A),kx,{forceRGBA:!0}),e=Lx(I)[0];e.data.length!==e.width*e.height*4&&U(559);const t=new si(e.data.length);return t.set(e.data),createImageBitmap(new ImageData(t,e.width,e.height))}function B9(A,g,I,e,t={}){(g<1||I<1||e<1)&&U(573,g,I,e);const i=A._device,o=t.mipMaps??!0,Q=t.srgb?"rgba8unorm-srgb":"rgba8unorm",r=i.createTexture({size:{width:g,height:I,depthOrArrayLayers:e},dimension:"2d",format:Q,mipLevelCount:o?XQ(g,I):1,usage:dA.TEXTURE_BINDING|dA.COPY_DST|dA.RENDER_ATTACHMENT}),E=Pe(A,{addressModeU:t.addressModeU??"repeat",addressModeV:t.addressModeV??"repeat",minFilter:t.minFilter??"linear",magFilter:t.magFilter??"linear",mipmapFilter:o?"linear":"nearest"}),n={texture:r,view:r.createView({dimension:"2d-array"}),sampler:E,width:g,height:I,layers:e};return rt(n),n}function Q9(A,g,I,e,t={}){(I<0||I>=g.layers||(I|0)!==I)&&U(574,g.layers,I);const i=t.invertY??!0,o=t.premultiplyAlpha??!1;A._device.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:g.texture,origin:[0,0,I],premultipliedAlpha:o},[g.width,g.height,1]),g.texture.mipLevelCount>1&&ZQ(A,g.texture,I)}async function EcA(A,g,I,e,t={}){const i=await fetch(e);i.ok||U(575,e,i.status);const o=await createImageBitmap(await i.blob(),{premultiplyAlpha:t.premultiplyAlpha?"premultiply":"none",colorSpaceConversion:"none"});try{Q9(A,g,I,o,t)}finally{o.close()}}async function ncA(A,g,I={}){const e=await Promise.allSettled(g.map(async E=>{const n=await fetch(E);return n.ok||U(576,E,n.status),createImageBitmap(await n.blob(),{premultiplyAlpha:I.premultiplyAlpha?"premultiply":"none",colorSpaceConversion:"none"})})),t=e.find(E=>E.status==="rejected");if(t){for(const E of e)E.status==="fulfilled"&&E.value.close();throw t.reason}const i=e.filter(E=>E.status==="fulfilled").map(E=>E.value),o=i[0].width,Q=i[0].height;for(const[E,n]of i.entries())if(n.width!==o||n.height!==Q){for(const s of i)s.close();U(577,o,Q,E,n.width,n.height)}const r=B9(A,o,Q,i.length,I);for(const[E,n]of i.entries())Q9(A,r,E,n,I),n.close();return r}function vx(A,g,I,e,t,i={}){const o=B9(A,I,e,t,i);return Hx(A,o,g),o}function Hx(A,g,I,e=0){(e<0||e>=g.texture.mipLevelCount||(e|0)!==e)&&U(578,g.texture.mipLevelCount,e);const t=Math.max(1,g.width>>e),i=Math.max(1,g.height>>e),o=t*i*g.layers*4;if(I.length<o&&U(579,o,t,i,g.layers,e,I.length),A._device.queue.writeTexture({texture:g.texture,mipLevel:e},I,{bytesPerRow:t*4,rowsPerImage:i},{width:t,height:i,depthOrArrayLayers:g.layers}),e===0&&g.texture.mipLevelCount>1){const Q=A._device.createCommandEncoder();for(let r=0;r<g.layers;r++)wF(A,g.texture,Q,r);A._device.queue.submit([Q.finish()])}}function Tx(A){const g=A.mipmaps,I=A.layerCount;I===void 0&&U(580),(I<1||g.length%I!==0)&&U(581,g.length,I);const e=[];for(let t=0;t<g.length;t+=I){const i=g.slice(t,t+I);for(let o=0;o<I;o++){const Q=i[o];Q.layerIndex!==o&&U(582,o,t+o,Q.layerIndex),(Q.width!==i[0].width||Q.height!==i[0].height)&&U(583,e.length,o)}e.push(i)}return{layers:I,levels:e}}function xx(A,g,I,e,t,i,o){const Q=A._device.createTexture({size:{width:g,height:I,depthOrArrayLayers:e},dimension:"2d",format:o?i9(i):i,mipLevelCount:t,usage:dA.TEXTURE_BINDING|dA.COPY_DST}),r={texture:Q,view:Q.createView({dimension:"2d-array"}),sampler:o9(A,t),width:g,height:I,layers:e,invertY:!0};return rt(r),r}function scA(A,g,I,e){A._device.features.has(I.feature)||U(584,I.feature);const{layers:t,levels:i}=Tx(g),o=i[0][0].width,Q=i[0][0].height,r=xx(A,o,Q,t,i.length,I.gpuFormat,e);for(let E=0;E<i.length;E++){const n=Math.ceil(i[E][0].width/I.blockW),s=n*I.blockBytes,c=n*I.blockW,l=Math.ceil(i[E][0].height/I.blockH)*I.blockH;for(let D=0;D<t;D++){const p=i[E][D];A._device.queue.writeTexture({texture:r.texture,mipLevel:E,origin:{x:0,y:0,z:D}},p.data,{bytesPerRow:s},{width:c,height:l,depthOrArrayLayers:1})}}return r}function acA(A,g,I,e){const t=I.bytesPerPixel,{layers:i,levels:o}=Tx(g),Q=o[0][0].width,r=o[0][0].height,E=xx(A,Q,r,i,o.length,I.format,e);for(let n=0;n<o.length;n++){const s=o[n][0].width,c=o[n][0].height;for(let l=0;l<i;l++){const D=o[n][l],p=s*c*t;D.data.length!==p&&U(585,n,l,D.data.length,p),A._device.queue.writeTexture({texture:E.texture,mipLevel:n,origin:{x:0,y:0,z:l}},D.data,{bytesPerRow:s*t},{width:s,height:c,depthOrArrayLayers:1})}}return E}async function qx(A,g,I=!1){const e=await Yx(A,g),t=t9(e.transcodedFormat);if(t)return scA(A,e,t,I);const i=Ux(e.transcodedFormat);if(i)return acA(A,e,i,I);U(586,e.transcodedFormat.toString(16))}async function ccA(A,g,I=!1){const e=await fetch(g);return e.ok||U(587,e.status,g),qx(A,await e.arrayBuffer(),I)}function Px(A,g,I,e={}){(g<1||I<1)&&U(536,g,I);const t=A._device,i=e.mipMaps??!1,o=e.srgb?"rgba8unorm-srgb":"rgba8unorm",Q=i?XQ(g,I):1,r=t.createTexture({size:{width:g,height:I},format:o,mipLevelCount:Q,usage:dA.TEXTURE_BINDING|dA.COPY_DST|dA.RENDER_ATTACHMENT}),E={addressModeU:e.addressModeU??"clamp-to-edge",addressModeV:e.addressModeV??"clamp-to-edge",minFilter:e.minFilter??"linear",magFilter:e.magFilter??"linear",mipmapFilter:i?"linear":"nearest"},n=Pe(A,E),s={texture:r,view:r.createView(),sampler:n,width:g,height:I};return rt(s),A._dlr&&A._dlr.t(s,{kind:"dynamic",width:g,height:I,format:o,levels:Q,samplerDesc:E,source:null,flipY:!0,premultipliedAlpha:!1}),s}function Ox(A,g,I,e={}){const t=e.invertY??!0,i=e.premultiplyAlpha??!1;A._device.queue.copyExternalImageToTexture({source:I,flipY:t},{texture:g.texture,premultipliedAlpha:i},[g.width,g.height]);const o=g._recoverySource;o&&o.kind==="dynamic"&&(o.source=I,o.flipY=t,o.premultipliedAlpha=i),g.texture.mipLevelCount>1&&ZQ(A,g.texture)}function r9(A){return typeof A._device.queue.copyElementImageToTexture=="function"}function lcA(A,g,I={}){const e=A.surfaces[0].canvas;XG(e)||U(537);const t=r9(A),i=I.width??(g.offsetWidth||256),o=I.height??(g.offsetHeight||256),Q=Px(A,i,o,{srgb:I.srgb,mipMaps:I.mipMaps,addressModeU:I.addressModeU,addressModeV:I.addressModeV,minFilter:I.minFilter,magFilter:I.magFilter});if(Q._element=g,Q._host=e,Q._prevParent=g.parentNode,Q._prevNextSibling=g.nextSibling,Q._prevInert=g.inert,Q._paint=null,Q._invertY=I.invertY??!0,Q._autoUpdate=I.autoUpdate??!0,Q._useSvgFallback=I.useSvgFallback??!0,Q._forceNext=!1,Q._hosted=!1,Q._disposed=!1,Q._flipSrc=null,Q._flipDevice=null,(t||Q._useSvgFallback)&&(pcA(e),g.inert=!0,e.appendChild(g),Q._hosted=!0),t){const r=E=>{if(Q._disposed)return;const n=Q._forceNext;if(Q._forceNext=!1,!n){if(!Q._autoUpdate)return;const s=E.changedElements;if(s&&!s.some(c=>c===g||g.contains(c)))return}Sm(A,Q)};Q._paint=r,e.addEventListener("paint",r),jx(A,Q)}else Q._useSvgFallback&&Sm(A,Q);return Q}function Sm(A,g,I=g._invertY){if(g._disposed)return;const e=A._device.queue;if(typeof e.copyElementImageToTexture=="function"){if(I){const t=dcA(A,g);e.copyElementImageToTexture({source:g._element},{destination:{texture:t},width:g.width,height:g.height}),wcA(A,t,g.texture)}else e.copyElementImageToTexture({source:g._element},{destination:{texture:g.texture},width:g.width,height:g.height});g.texture.mipLevelCount>1&&ZQ(A,g.texture);return}g._useSvgFallback&&_cA(A,g,I)}function jx(A,g){if(g._disposed)return;const I=g._host,e=r9(A);e&&typeof I.requestPaint=="function"?(g._forceNext=!0,I.requestPaint()):!e&&g._useSvgFallback&&Sm(A,g)}function DcA(A){if(!A._disposed){if(A._disposed=!0,A._paint&&(A._host.removeEventListener("paint",A._paint),A._paint=null),A._hosted){const g=A._element;g.parentNode===A._host&&(A._prevParent?A._prevParent.insertBefore(g,A._prevNextSibling):A._host.removeChild(g)),g.inert=A._prevInert,ycA(A._host),A._hosted=!1}A._flipSrc?.destroy(),A._flipSrc=null,A._flipDevice=null,lC(A)}}let E9=null;function pcA(A){const g=E9??=new WeakMap;let I=g.get(A);I||(I={count:0,previousLayoutSubtree:A.layoutSubtree},g.set(A,I)),I.count++,A.layoutSubtree=!0}function ycA(A){const g=E9?.get(A);g&&(g.count--,!(g.count>0)&&(g.previousLayoutSubtree===void 0?delete A.layoutSubtree:A.layoutSubtree=g.previousLayoutSubtree,E9?.delete(A)))}async function _cA(A,g,I){try{const e=await ucA(g._element,g.width,g.height);g._disposed||Ox(A,g,e,{invertY:I})}catch{}}function ucA(A,g,I){const e=new XMLSerializer().serializeToString(A),t=`<svg xmlns="http://www.w3.org/2000/svg" width="${g}" height="${I}"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml">${e}</div></foreignObject></svg>`,i="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(t);return new Promise((o,Q)=>{const r=new Image(g,I);r.decoding="async",r.onload=()=>{const E=document.createElement("canvas");E.width=g,E.height=I;const n=E.getContext("2d");if(!n){Q(new Error("createHtmlTexture: SVG fallback could not acquire a 2D canvas context."));return}n.drawImage(r,0,0,g,I),o(E)},r.onerror=()=>Q(new Error("createHtmlTexture: SVG fallback failed to rasterise the element.")),r.src=i})}const hcA="@group(0)@binding(0)var t:texture_2d<f32>;@group(0)@binding(1)var s:sampler;struct V{@builtin(position)p:vec4f,@location(0)u:vec2f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return V(vec4f(p,0,1),p*vec2f(.5,.5)+.5);}@fragment fn fs(v:V)->@location(0)vec4f{return textureSample(t,s,v.u);}";let Vx=null,Rm=null,Nm=null,Gm=null;function fcA(A,g){const I=A._device;I!==Vx&&(Vx=I,Rm=null,Nm=null,Gm=null),Rm??=I.createShaderModule({code:hcA}),Nm??=I.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:NA.FRAGMENT,sampler:{}}]}),Gm??=new Map;let e=Gm.get(g);return e||(e=I.createRenderPipeline({layout:I.createPipelineLayout({bindGroupLayouts:[Nm]}),vertex:{module:Rm,entryPoint:"vs"},fragment:{module:Rm,entryPoint:"fs",targets:[{format:g}]},primitive:{topology:"triangle-list"}}),Gm.set(g,e)),e}function dcA(A,g){const I=A._device;let e=g._flipSrc;return(!e||g._flipDevice!==I||e.width!==g.width||e.height!==g.height)&&(e?.destroy(),e=I.createTexture({size:{width:g.width,height:g.height},format:g.texture.format,usage:dA.TEXTURE_BINDING|dA.COPY_DST|dA.RENDER_ATTACHMENT}),g._flipSrc=e,g._flipDevice=I),e}function wcA(A,g,I){const e=A._device,t=fcA(A,I.format),i=e.createBindGroup({layout:Nm,entries:[{binding:0,resource:g.createView()},{binding:1,resource:m1(A)}]}),o=e.createCommandEncoder(),Q=o.beginRenderPass({colorAttachments:[{view:I.createView({baseMipLevel:0,mipLevelCount:1}),loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});Q.setPipeline(t),Q.setBindGroup(0,i),Q.draw(3),Q.end(),e.queue.submit([o.finish()])}const McA=new mg([171,75,84,88,32,49,49,187,13,10,26,10]);function ScA(A){const g=new mg(A);A.byteLength<64&&U(538);for(let y=0;y<12;y++)g[y]!==McA[y]&&U(539);const I=new H1(A);I.getUint32(12,!0)!==67305985&&U(540),I.getUint32(16,!0)!==0&&U(541),I.getUint32(24,!0)!==0&&U(542);const e=I.getUint32(28,!0),t=t9(e);t||U(543,e.toString(16));const i=I.getUint32(36,!0),o=I.getUint32(40,!0),Q=I.getUint32(44,!0),r=I.getUint32(48,!0),E=I.getUint32(52,!0),n=Math.max(I.getUint32(56,!0),1),s=I.getUint32(60,!0);Q>0&&U(544),r>0&&U(545),E!==1&&U(546);let c=64+s;c>A.byteLength&&U(547);const l=[];let D=i,p=o;for(let y=0;y<n;y++){c+4>A.byteLength&&U(548,y);const _=I.getUint32(c,!0);c+=4,c+_>A.byteLength&&U(549,y),l.push({data:new mg(A,c,_),width:D,height:p}),c+=_,c=c+3&-4,D=Math.max(1,D>>1),p=Math.max(1,p>>1)}return l.length===0&&U(550),{format:t,width:i,height:o,mips:l}}function RcA(A,g,I){const e=A._device,t=g.format,i=e.createTexture({size:{width:g.width,height:g.height},format:t.gpuFormat,mipLevelCount:g.mips.length,usage:dA.TEXTURE_BINDING|dA.COPY_DST});for(let c=0;c<g.mips.length;c++){const l=g.mips[c],D=Math.ceil(l.width/t.blockW),p=D*t.blockBytes,y=D*t.blockW,_=Math.ceil(l.height/t.blockH)*t.blockH;e.queue.writeTexture({texture:i,mipLevel:c},l.data,{bytesPerRow:p},{width:y,height:_})}const o=I.minFilter??"linear",Q=I.magFilter??"linear",r=g.mips.length>1?"linear":"nearest",E=o==="linear"&&Q==="linear"&&r==="linear",n=Pe(A,{addressModeU:I.addressModeU??"repeat",addressModeV:I.addressModeV??"repeat",minFilter:o,magFilter:Q,mipmapFilter:r,maxAnisotropy:E?4:1}),s={texture:i,view:i.createView(),sampler:n,width:g.width,height:g.height};return rt(s),s}function NcA(A,g){const I=A.indexOf("?"),e=I>=0?A.substring(0,I):A,t=I>=0?A.substring(I):"",i=e.lastIndexOf(".");return i<0?e+g+t:e.substring(0,i)+g+t}async function GcA(A,g,I,e={}){const t=A._device,i=[];for(const o of I){const Q=gcA(o);Q&&t.features.has(Q)&&i.push(o)}for(const o of i)try{const Q=NcA(g,o),r=await fetch(Q);r.ok||U(551,r.status);const E=ScA(await r.arrayBuffer());return RcA(A,E,e)}catch(Q){console.warn(`KTX load failed for suffix "${o}":`,Q)}return OQ(A,g,e)}const FcA=0,mcA=1,bcA=2,KcA=3,kcA=6,UcA=10,LcA=13,Wx="https://cdn.babylonjs.com/basisTranscoder/1";let _r=null;function YcA(){return _r||(_r=new Promise((A,g)=>{const I=globalThis,e=()=>{const i=I.BASIS;if(!i){g(new Error("Basis: transcoder global BASIS not found after script load"));return}i({locateFile:o=>`${Wx}/${o}`}).then(o=>{o.initializeBasis(),A(o)}).catch(g)};if(I.BASIS){e();return}const t=document.createElement("script");t.src=`${Wx}/basis_transcoder.js`,t.async=!0,t.onload=e,t.onerror=()=>g(new Error(`Basis: failed to load ${t.src}`)),document.head.appendChild(t)}),_r.catch(()=>{_r=null}),_r)}const n9=[{basisFormat:kcA,gpuFormat:"bc7-rgba-unorm",gpuFormatSrgb:"bc7-rgba-unorm-srgb",feature:"texture-compression-bc",blockW:4,blockH:4,blockBytes:16,hasAlpha:!0},{basisFormat:UcA,gpuFormat:"astc-4x4-unorm",gpuFormatSrgb:"astc-4x4-unorm-srgb",feature:"texture-compression-astc",blockW:4,blockH:4,blockBytes:16,hasAlpha:!0},{basisFormat:mcA,gpuFormat:"etc2-rgba8unorm",gpuFormatSrgb:"etc2-rgba8unorm-srgb",feature:"texture-compression-etc2",blockW:4,blockH:4,blockBytes:16,hasAlpha:!0},{basisFormat:KcA,gpuFormat:"bc3-rgba-unorm",gpuFormatSrgb:"bc3-rgba-unorm-srgb",feature:"texture-compression-bc",blockW:4,blockH:4,blockBytes:16,hasAlpha:!0},{basisFormat:bcA,gpuFormat:"bc1-rgba-unorm",gpuFormatSrgb:"bc1-rgba-unorm-srgb",feature:"texture-compression-bc",blockW:4,blockH:4,blockBytes:8,hasAlpha:!1},{basisFormat:LcA,gpuFormat:"rgba8unorm",gpuFormatSrgb:"rgba8unorm-srgb",blockW:1,blockH:1,blockBytes:4,hasAlpha:!0},{basisFormat:FcA,gpuFormat:"etc2-rgb8unorm",gpuFormatSrgb:"etc2-rgb8unorm-srgb",feature:"texture-compression-etc2",blockW:4,blockH:4,blockBytes:8,hasAlpha:!1}];function JcA(A,g){for(const I of n9)if(!(!I.hasAlpha&&g)&&!(I.feature&&!A.features.has(I.feature)))return I;return n9[n9.length-2]}async function vcA(A,g,I={}){const e=A._device,[t,i]=await Promise.all([YcA(),fetch(g).then(r=>r.arrayBuffer())]),o=new mg(i),Q=new t.BasisFile(o);try{Q.getNumImages()===0&&U(532),Q.startTranscoding()===0&&U(533);const r=Q.getHasAlpha()!==0,E=JcA(e,r),n=Q.getImageWidth(0,0),s=Q.getImageHeight(0,0),c=Q.getNumLevels(0),D=(I.srgb??!1)&&E.gpuFormatSrgb?E.gpuFormatSrgb:E.gpuFormat,p=[];for(let S=0;S<c;S++){const R=Q.getImageWidth(0,S),N=Q.getImageHeight(0,S),F=Q.getImageTranscodedSizeInBytes(0,S,E.basisFormat);F===0&&U(534,S);const G=new mg(F);Q.transcodeImage(G,0,S,E.basisFormat,0,r?1:0)===0&&U(535,S),p.push({data:G,width:R,height:N})}const y=e.createTexture({size:{width:n,height:s},format:D,mipLevelCount:p.length,usage:dA.TEXTURE_BINDING|dA.COPY_DST});for(let S=0;S<p.length;S++){const R=p[S],N=Math.ceil(R.width/E.blockW),F=E.blockW===1?R.width*E.blockBytes:N*E.blockBytes;e.queue.writeTexture({texture:y,mipLevel:S},R.data,{bytesPerRow:F},{width:R.width,height:R.height})}const _=I.minFilter??"linear",u=I.magFilter??"linear",f=p.length>1?"linear":"nearest",h=_==="linear"&&u==="linear"&&f==="linear",w=Pe(A,{addressModeU:I.addressModeU??"repeat",addressModeV:I.addressModeV??"repeat",minFilter:_,magFilter:u,mipmapFilter:f,maxAnisotropy:h?4:1}),M={texture:y,view:y.createView(),sampler:w,width:n,height:s,invertY:!0};return rt(M),M}finally{Q.close(),Q.delete()}}async function HcA(A,g,I={}){const e=g instanceof ArrayBuffer?new mg(g):new mg(g.buffer,g.byteOffset,g.byteLength),i=await(await C9()).decode(e,kx,{forceRGBA:!0});i.errors&&U(560,i.errors),i.mipmaps.length||U(561);const o=Math.max(i.layerCount??1,1),Q=i.mipmaps.slice(0,o);Q.length!==o&&U(562,o,Q.length);const{width:r,height:E}=Q[0],n=r*E*4,s=new mg(n*o);for(let l=0;l<o;l++){const D=Q[l];(!D.data||D.width!==r||D.height!==E||D.data.byteLength!==n)&&U(563,l,r,E,n),s.set(D.data,l*n)}const c=vx(A,s,r,E,o,{mipMaps:I.generateMipMaps??!0,srgb:I.srgb??!1,minFilter:I.minFilter??"linear",magFilter:I.magFilter??"linear"});return I.mipmapFilter&&(c.sampler=Pe(A,{addressModeU:"repeat",addressModeV:"repeat",minFilter:I.minFilter??"linear",magFilter:I.magFilter??"linear",mipmapFilter:I.mipmapFilter})),c.invertY=I.invertY??!1,c}function zx(A){const g=A._renderFeatures??{features:0};return $1(A,{features:g.features|WF})}const TcA=Object.freeze(Object.defineProperty({__proto__:null,createStandardNoColorMaterialView:zx},Symbol.toStringTag,{value:"Module"}));let Zx=null;function xcA(A){Zx=A}function qcA(){return Zx}function Fm(A){const g=[];A.diffuseTexture&&g.push(A.diffuseTexture);for(const I of iT().values())I._textures?.(A,g);return g}function s9(A){let g=0;A.diffuseTexture&&(g|=yC,A.diffuseCoordIndex===1&&(g|=VF)),A.backFaceCulling||(g|=jF),A.disableLighting&&(g|=gT),A.alpha<1&&(g|=lo);for(const I of iT().values())I._detect&&(g|=I._detect(A));return g}function Xx(A,g,I,e=""){return e?`${A}:${g}:${I}:${e}`:`${A}:${g}:${I}`}function $x(A){return A.length===0?"":A.map(g=>`${g.lightIndex}${g.shadowType==="pcf"?"p":"e"}`).join(",")}const PcA=Object.freeze(Object.defineProperty({__proto__:null,_computeStandardMaterialFeatures:s9,_standardFeatureKey:Xx,_standardShaderVariantKey:$x,collectStdBoundTextures:Fm,createStandardMaterial:nt,getStandardGroupBuilder:$F},Symbol.toStringTag,{value:"Module"})),OcA=1,mm=2,jcA="fn computeLighting(viewDir:vec3<f32>,N:vec3<f32>,L:LightEntry,g:f32,P:vec3<f32>)->array<vec3<f32>,2>{var lv:vec3<f32>;var a:f32=1.0;let t=u32(L.vLightData.w);if(t==3u){let nl=0.5+0.5*dot(N,normalize(L.vLightData.xyz));let diff=mix(L.vLightDirection.xyz,L.vLightDiffuse.rgb,nl);let h=normalize(viewDir+normalize(L.vLightData.xyz));var s=pow(max(0.0,dot(N,h)),max(1.0,g));return array<vec3<f32>,2>(diff,s*L.vLightSpecular.rgb);}if(t==1u){lv=normalize(-L.vLightData.xyz);}else{let d=L.vLightData.xyz-P;a=max(0.0,1.0-length(d)/L.vLightDiffuse.a);lv=normalize(d);if(t==2u){let c=max(0.0,dot(L.vLightDirection.xyz,-lv));if(c>=L.vLightDirection.w){a*=max(0.0,pow(c,L.vLightSpecular.a));}else{a=0.0;}}}let nl=max(0.0,dot(N,lv));let diff=nl*L.vLightDiffuse.rgb*a;let h=normalize(viewDir+lv);var s=max(0.0,dot(N,h));s=pow(s,max(1.0,g));return array<vec3<f32>,2>(diff,s*L.vLightSpecular.rgb*a);}";function VcA(A,g=""){const{_diffuse:I,_needsUV:e,_needsUV2:t,_diffuseUsesUV2:i,_disableLighting:o,_noColorOutput:Q,_esmShadowOutput:r,_hasMorph:E}=A,n=[{_name:"position",_type:"vec3<f32>",_gpuFormat:"float32x3",_arrayStride:12},{_name:"normal",_type:"vec3<f32>",_gpuFormat:"float32x3",_arrayStride:12}];e&&n.push({_name:"uv",_type:"vec2<f32>",_gpuFormat:"float32x2",_arrayStride:8}),t&&n.push({_name:"uv2",_type:"vec2<f32>",_gpuFormat:"float32x2",_arrayStride:8});const s=[{_name:"vp",_type:"vec3<f32>"},{_name:"vn",_type:"vec3<f32>"}];e&&s.push({_name:"vu",_type:"vec2<f32>"}),t&&s.push({_name:"vv",_type:"vec2<f32>"});const c=[{_name:"world",_type:"mat4x4<f32>"}];d6(c);const l=[{_name:"mat",_type:{_kind:"uniform-buffer"},_visibility:mm}];I&&l.push({_name:"dT",_type:{_kind:"texture",_textureType:"texture_2d<f32>"},_visibility:mm},{_name:"dS",_type:{_kind:"sampler",_samplerType:"sampler"},_visibility:mm}),e&&l.push({_name:"up",_type:{_kind:"uniform-buffer"},_visibility:OcA}),r&&l.push({_name:"shadowParams",_type:{_kind:"uniform-buffer"},_visibility:mm});const f=`/*SU*/ /*MU*/@group(1)@binding(0)var<uniform>mesh:MeshUniforms;${e?"struct upUniforms{u:vec4<f32>,}":""} /*VH*/ /*VD*/ /*VO*/@vertex fn main( /*VP*/)->VertexOutput{var out:VertexOutput; /*VR*/var finalWorld=mesh.world; /*VW*/let worldPos4=finalWorld*vec4<f32>(${E?"morphedPos":"position"},1.0);out.vp=worldPos4.xyz;let normalWorld=mat3x3<f32>(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);out.vn=normalize(normalWorld* ${E?"morphedNorm":"normal"});out.clipPos=scene.viewProjection*worldPos4;${e?"out.vu=uv*up.u.xy+up.u.zw;":""} ${t?"out.vv=uv2;":""} /*VB*/return out;}`,h=`struct LightEntry{vLightData:vec4<f32>,vLightDiffuse:vec4<f32>,vLightSpecular:vec4<f32>,vLightDirection:vec4<f32>};struct lightsUniforms{count:u32,_p0:u32,_p1:u32,_p2:u32,lights:array<LightEntry,${HI}>};@group(0)@binding(1)var<uniform>lights:lightsUniforms;`,w="struct matUniforms{dc:vec4<f32>,sc:vec4<f32>,ec:vec3<f32>,bs:f32,ac:vec3<f32>,tl:f32,ambTexLvl:f32,lmLvl:f32,opLvl:f32,aCut:f32,rLvl:f32,rCm:f32,_0:f32,_1:f32,};",M=o?"":jcA,S=`@fragment fn main(input:FragmentInput)${Q?"":" -> @location(0) vec4<f32>"}{`,R=o?"":"let viewDirectionW=normalize(scene.vEyePosition.xyz-input.vp);",N=o?"":"var normalW=normalize(input.vn);",F="var alpha=mat.dc.a;",G=I?`let _ds=textureSample(dT,dS,${i?"input.vv":"input.vu"});if(_ds.a<mat.aCut){discard;}var baseColor=_ds.rgb*mat.tl;`:"var baseColor=vec3<f32>(1.0,1.0,1.0);",m="let diffuseColor=mat.dc.rgb;",K="var emissiveContrib=mat.ec;",k=o?"":"var specularColor=mat.sc.rgb;";let L;o?L="var color=vec4<f32>(clamp(emissiveContrib*diffuseColor,vec3<f32>(0.0),vec3<f32>(1.0))*baseColor,alpha);":L=`var glossiness=mat.sc.a;var diffuseBase=vec3<f32>(0.0);var specularBase=vec3<f32>(0.0);var shadowFactors=array<f32,${HI}>(${new Array(HI).fill("1.0").join(", ")});var baseAmbientColor=vec3<f32>(1.0,1.0,1.0);var reflectionColor=vec3<f32>(0.0);let lc=min(mesh.lc,${HI}u); /*AD*/for(var li=0u;li<lc;li++){let lightIndex=mli(li);let r=computeLighting(viewDirectionW,normalW,lights.lights[lightIndex],glossiness,input.vp);let sf=shadowFactors[lightIndex];diffuseBase+=r[0]*sf;specularBase+=r[1]*sf;}let finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveContrib+mat.ac,vec3<f32>(0.0),vec3<f32>(1.0))*baseColor;let finalSpecular=specularBase*specularColor;var color=vec4<f32>(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);`;const H=`/*SU*/ ${h} ${w} ${r?"struct shadowParamsUniforms { biasAndScale: vec4<f32>, depthValues: vec4<f32>, }":""} /*MU*/@group(1)@binding(0)var<uniform>mesh:MeshUniforms;${o?"":w6("mesh")} ${M} /*HF*/ /*FB*/ /*FI*/ ${S} /*SV*/ ${R} ${N} /*AC*/ ${F} ${G} ${m} ${K} ${k} /*AT*/ ${Q?"return;":`${r?g:""} ${L} /*BC*/color=vec4<f32>(max(color.rgb,vec3<f32>(0.0)),color.a); /*BA*/return color;`}}`;return{_vertexTemplate:f,_fragmentTemplate:H,_baseMeshUboFields:c,_baseVertexAttributes:n,_baseVaryings:s,_baseBindings:l}}const WcA={f32:{align:4,size:4},u32:{align:4,size:4},i32:{align:4,size:4},"vec2<f32>":{align:8,size:8},"vec3<f32>":{align:16,size:12},"vec4<f32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"mat4x4<f32>":{align:16,size:64}};function Aq(A,g){return A+g-1&~(g-1)}function zcA(A){const g=WcA[A];if(g)return g;const I=/^array<vec4<u32>,\s*(\d+)>$/.exec(A);if(I)return{align:16,size:Number(I[1])*16};throw new Error(`Unknown UBO field type: ${A}`)}function ur(A){const g=new Map,I=[];let e=0;for(const o of A){const Q=zcA(o._type);e=Aq(e,Q.align),g.set(o._name,e),I.push(`${o._name}: ${o._type},`),e+=Q.size}const t=A.length>0?Aq(e,16):0,i=I.join(`
|
|
1
|
+
let VJ=null;function GCA(A){VJ=A}function U(A,...g){const I=new Error(VJ?.(A,g)??`#${A}`);throw I.lite=g,I}const X=Float32Array,S1=Float64Array,Vg=Uint32Array,R1=Int32Array,N1=Uint16Array,B3=Int16Array,mg=Uint8Array,Q3=Int8Array,si=Uint8ClampedArray,H1=DataView;function FCA(){return new X(16)}let WJ;function se(){return(WJ??FCA)()}function mCA(){return se()}function bCA(A){WJ=A}const dA=globalThis.GPUTextureUsage,SA=globalThis.GPUBufferUsage,NA=globalThis.GPUShaderStage,ai=globalThis.GPUColorWrite,HQ="greater-equal";function Ot(A){return`${A._colorFormat??"-"}|${A._depthStencilFormat??"-"}|${A._depthCompare??""}|${A._sampleCount}`}function wt(A){return{_descriptor:A,_colorTexture:null,_colorView:null,_depthTexture:null,_depthView:null,_width:0,_height:0}}function Kt(A,g){if(A._eager)return;Se(A);const I=A._descriptor,{width:e,height:t}=KCA(I);A._width=e,A._height=t;const i=g._device;I.format&&(A._colorTexture=i.createTexture({label:I.lbl,size:{width:e,height:t},format:I.format,sampleCount:I.samples,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING|dA.COPY_SRC|dA.COPY_DST}),A._colorView=A._colorTexture.createView()),I.dFormat&&(A._depthTexture=i.createTexture({label:I.lbl,size:{width:e,height:t},format:I.dFormat,sampleCount:I.samples,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING}),A._depthView=A._depthTexture.createView())}function Se(A){!A||A._eager||(A._colorTexture&&(A._colorTexture.destroy(),A._colorTexture=null,A._colorView=null),A._depthTexture&&(A._ownsDepthTexture!==!1&&A._depthTexture.destroy(),A._depthTexture=null,A._depthView=null),A._width=0,A._height=0)}function KCA(A){const g=A.size;if("canvas"in g){const I=g.canvas;return{width:I.width,height:I.height}}return g}const zJ="1.28.0",ZJ=`Babylon Lite v${zJ}`;function XG(A){return"clientWidth"in A}function kCA(A){return A.endsWith("-srgb")?A:`${A}-srgb`}let UCA=1;function LCA(A,g,I){const e=XJ(A,g,I);return A._surfaces.push(e),AF(e),$G(e),e}function XJ(A,g,I){const e=g.getContext("webgpu");e||U(48),XG(g)&&g.setAttribute("data-engine",ZJ);const t=I?.format??navigator.gpu.getPreferredCanvasFormat(),i=I?.srgb?kCA(t):t,o=I?.alphaMode??"opaque";e.configure({device:A._device,format:t,alphaMode:o,viewFormats:[i]});const Q=I?.msaaSamples===1?1:4,r=wt({lbl:"swapchain",format:i,samples:1,size:{width:0,height:0}});return r._eager=!0,{engine:A,canvas:g,format:i,msaaSamples:Q,scRT:r,maxDevicePixelRatio:I?.maxDevicePixelRatio??1/0,_uniqueId:UCA++,_context:e,_configureFormat:t,_alphaMode:o,_renderingContexts:[]}}function $G(A){const g=A._context.getCurrentTexture(),I=A.scRT;I._colorTexture=g,I._colorView=g.createView({format:A.format}),I._width=g.width,I._height=g.height}function AF(A){const g=A.canvas;if(!XG(g))return;const I=A._w??g.clientWidth,e=A._h??g.clientHeight;if(!(I>0&&e>0))return;const t=Math.min(globalThis.devicePixelRatio||1,A.maxDevicePixelRatio),i=I*t|0,o=e*t|0;r3(A,i,o)}function r3(A,g,I){const e=A.canvas,t=g|0,i=I|0;if(t>0&&i>0&&!(t===e.width&&i===e.height)){e.width=t,e.height=i,A.scRT._width=t,A.scRT._height=i;for(const o of A._renderingContexts)o._resize?.()}}function YCA(A){A===A.engine&&U(49),A._renderingContexts.length=0,A._ro?.disconnect(),A._context.unconfigure();const g=A.engine._surfaces,I=g.indexOf(A);I!==-1&&g.splice(I,1)}function E3(A){for(const g of A.splice(0))try{g()}catch{}}function G1(A,g){(A._retirements??=[]).push(g)}function gF(A){const g=A._retirements;if(!g)return;A._retirements=null;const I=A._retiring??=[];I.push(g),queueMicrotask(()=>{A._device.queue.onSubmittedWorkDone().then(()=>{const e=I.indexOf(g);e>=0&&I.splice(e,1),E3(g)}).catch(()=>{})})}function $J(A){const g=A._retirements,I=A._retiring;A._retirements=null,A._retiring=null,g&&E3(g),I?.forEach(E3)}let TQ=0;function cC(){TQ=TQ+1|0}function JCA(A){return A._renderingContexts}function vCA(A){if(!A||typeof A._kind!="string")throw new TypeError("Invalid RenderingContext: missing internal kind discriminator");return A._kind}function n3(A,g){return A._renderingContexts.indexOf(g)!==-1}function xQ(A,g){return A._renderingContexts.indexOf(g)!==-1?!1:(A._renderingContexts.push(g),!0)}function qQ(A,g){const I=A._renderingContexts,e=I.indexOf(g);return e===-1?!1:(I.splice(e,1),!0)}let YR=null;function HCA(A){YR=A}function TCA(){return YR?YR():{}}async function xCA(A,g){const I=await navigator.gpu.requestAdapter({powerPreference:"high-performance",...YR?YR():{}});I||U(46);const e=[];for(const l of["float32-filterable","texture-compression-astc","texture-compression-bc","texture-compression-etc2","timestamp-query","primitive-index"])I.features.has(l)&&e.push(l);const t=await I.requestDevice({requiredFeatures:e,requiredLimits:g?.requiredLimits});console.log(`${ZJ} - WebGPU engine`);const i=!!g?.useHighPrecisionMatrix,o=!!g?.useFloatingOrigin;if(o&&!i&&U(47),i){const{allocateF64Mat4:l}=await Promise.resolve().then(()=>k8A);bCA(l)}let Q,r,E,n;if(o){const[{wrapRenderableForFO:l,lightFoVersion:D,applyLightFoOffset:p},{makePackMeshWorld:y}]=await Promise.all([Promise.resolve().then(()=>_oA),Promise.resolve().then(()=>L8A)]);Q=l,r=y,E=D,n=p}const s={_device:t},c=[s];return Object.assign(s,{engine:s,surfaces:c,_surfaces:c,_device:t,_options:g,drawCallCount:0,gpuFrameTimeMs:0,useHighPrecisionMatrix:i,useFloatingOrigin:o,_animFrameId:0,_renderFn:null,_currentEncoder:void 0,_currentDelta:0,_cbs:[],_wrapRenderableForFO:Q,_makePackMeshWorld:r,_lightFoVersion:E,_applyLightFoOffset:n},XJ(s,A,g)),AF(s),$G(s),s}function s3(A){for(const g of A.surfaces)AF(g)}function qCA(A,g,I){r3(A,g,I)}function IF(A){const g=A.canvas;return{width:g.width,height:g.height}}function JR(A){return new Promise(g=>{let I=!0,e=0;A._renderFn=t=>{const i=I?0:e>0?t-e:16.667;e=t,s3(A),A6(A,i),I&&(I=!1,g()),A._renderFn&&(A._animFrameId=requestAnimationFrame(A._renderFn))},A._animFrameId=requestAnimationFrame(A._renderFn)})}function PCA(A){return A._device.queue.onSubmittedWorkDone()}function eF(A){A._animFrameId&&cancelAnimationFrame(A._animFrameId),A._animFrameId=0,A._renderFn=null,gF(A)}function OCA(A){$J(A),eF(A);const g=A._surfaces;for(const I of g)I._renderingContexts.length=0,I._ro?.disconnect(),I._context.unconfigure();g.length=0,A._disposeStorageBuffers?.(),A._device.destroy()}function A6(A,g){const I=A.surfaces;let e=0;for(let Q=0;Q<I.length;Q++)e+=I[Q]._renderingContexts.length;if(e===0){gF(A);return}const t=A._device.createCommandEncoder({label:"frame"});A._currentEncoder=t,A._currentDelta=g,A._gpuTimerBegin?.(t);let i=0;for(let Q=0;Q<I.length;Q++){const r=I[Q];r._capturePreFrame?.(r),$G(r);const E=r._renderingContexts;for(let n=0;n<E.length;n++){const s=E[n];s._update(),i+=s._drawCallsPre,i+=s._record()}}const o=A._currentEncoder;for(let Q=0;Q<I.length;Q++){const r=I[Q];r._captureService?.(r,o)}A._gpuTimerEnd?.(o),A._cbs[0]=o.finish(),A._device.queue.submit(A._cbs),gF(A),A.drawCallCount=i,A._gpuTimerResolve?.()}function g6(A){return A._device.features.has("timestamp-query")}function jCA(A,g){if(!g){A._gpuTimerWanted=!1,A.gpuFrameTimeMs=0,A._gpuTimerBegin=void 0,A._gpuTimerEnd=void 0,A._gpuTimerResolve=A._gpuTaskTimerResolve;return}g6(A)&&(A._gpuTimerWanted=!0,Promise.resolve().then(()=>T8A).then(({createGpuFrameTimer:I,gpuFrameTimerBegin:e,gpuFrameTimerEnd:t,gpuFrameTimerResolve:i})=>{A._gpuTimer===void 0&&(A._gpuTimer=I(A._device));const o=A._gpuTimer;o&&A._gpuTimerWanted&&(A._gpuTimerBegin=Q=>e(o,Q),A._gpuTimerEnd=Q=>t(o,Q),A._gpuTimerResolve=()=>{i(o),A.gpuFrameTimeMs=o.lastMs,A._gpuTaskTimerResolve?.()})}))}function VCA(A){const g={useHighPrecisionMatrix:!1,useFloatingOrigin:!1,drawCallCount:0,gpuFrameTimeMs:0,_animFrameId:0,_renderFn:null,_currentDelta:0,_cbs:[],_renderingContexts:[]};g.engine=g;const I=[g];return g.surfaces=I,g._surfaces=I,g}function I6(A,g,I){A._currentDelta=I,g._update()}function WCA(A,g,I,e=1e3/60){for(let t=0;t<I;t++)I6(A,g,e)}function tF(A){return A._device.features.has("timestamp-query")}function CF(A){if(!tF(A))return ci("unsupported",!1,!1,0,[],0);const g=A._gpuTaskTimingResult;return g||(A._gpuTaskTimerWanted?ci("pending",!0,!0,0,[],0):ci("disabled",!0,!1,0,[],0))}async function zCA(A,g){if(!g){A._gpuTaskTimerEpoch=(A._gpuTaskTimerEpoch??0)+1,A._gpuTaskTimerWanted=!1,A._gpuTaskTimerDisable?.(),A._gpuTaskTimerDisable=void 0,A._gpuTaskTimer=void 0;const o=tF(A);return A._gpuTaskTimingResult=ci(o?"disabled":"unsupported",o,!1,0,[],0),A._gpuTaskTimingResult}if(!tF(A))return A._gpuTaskTimerWanted=!1,A._gpuTaskTimingResult=ci("unsupported",!1,!1,0,[],0),A._gpuTaskTimingResult;if(A._gpuTaskTimerWanted)return CF(A);const I=(A._gpuTaskTimerEpoch??0)+1;A._gpuTaskTimerEpoch=I,A._gpuTaskTimerWanted=!0,A._gpuTaskTimingResult=ci("pending",!0,!0,0,[],0);const{createGpuTaskTimer:e,installGpuTaskTimer:t}=await Promise.resolve().then(()=>eLA);if(!A._gpuTaskTimerWanted||A._gpuTaskTimerEpoch!==I)return CF(A);A._gpuTaskTimer===void 0&&(A._gpuTaskTimer=e(A._device));const i=A._gpuTaskTimer;return i?(A._gpuTaskTimerDisable=t(i,A,o=>{A._gpuTaskTimerWanted&&A._gpuTaskTimerEpoch===I&&(A._gpuTaskTimingResult=o)}),CF(A)):(A._gpuTaskTimerWanted=!1,A._gpuTaskTimingResult=ci("unsupported",!1,!1,0,[],0),A._gpuTaskTimingResult)}async function ZCA(A,g,I){const{_measureRenderTaskOverdrawCost:e}=await Promise.resolve().then(()=>CLA);return e(A,g,I)}function ci(A,g,I,e,t,i,o){return{status:A,supported:g,enabled:I,frameIndex:e,tasks:t,droppedTaskCount:i,error:o}}function XCA(A){if(!XG(A.canvas)||typeof ResizeObserver>"u")return()=>{};A._ro?.disconnect();const g=A._ro=new ResizeObserver(([I])=>{A._w=Math.round(I.contentRect.width),A._h=Math.round(I.contentRect.height)});return g.observe(A.canvas),()=>{g.disconnect(),A._ro===g&&(A._ro=void 0,A._w=A._h=void 0)}}function $CA(A){const g=new Promise((I,e)=>{(A._captureQueue??=[]).push({resolve:I,reject:e})});return A._captureService||Promise.resolve().then(()=>nLA).then(({createCaptureService:I,createCapturePreFrame:e})=>{A._captureService??=I(),A._capturePreFrame??=e()}),g}function AiA(A){return A._deviceLostRecovery??={_forceNextLoss:!1,_requiredFeatures:[],_armedDevice:null,_registrations:[],_samplerDescriptors:new WeakMap,_captureRefs:0,_meshCaptureRefs:0,_textures:new Set,_texturesPruneAt:64}}function iF(A,g){const I=AiA(A),e=I._registrations;e.length===0&&(I._requiredFeatures=Array.from(A._device.features)),e.some(i=>i._kind===g._kind)||g._enable?.(A),e.push(g),e6(A,I);let t=!1;return{disable(){if(t)return;t=!0;const i=e.indexOf(g);i>=0&&e.splice(i,1),e.some(o=>o._kind===g._kind)||g._disable?.(A)}}}function giA(A){const g=A._deviceLostRecovery;return!!g?._registrations.length&&(g._forceNextLoss=!0)}function e6(A,g){const I=A._device;g._armedDevice===I||g._recovering||(g._armedDevice=I,I.lost.then(e=>{if(g._registrations.length===0||g._armedDevice!==I||e.reason==="destroyed"&&!g._forceNextLoss)return;g._forceNextLoss=!1,g._recovering=!0;const t=[...g._registrations];for(const i of t)i._onLost?.(e);Promise.resolve().then(()=>lLA).then(({runDeviceLostRecovery:i})=>i(A,g,t)).then(()=>{g._recovering=!1,e6(A,g);for(const i of t)i._onRecovered?.()},i=>{g._recovering=!1;for(const o of t)o._onRecoveryFailed?.(i)})}))}function IiA(A){giA(A)||U(45),A._device.destroy()}let a3=null;function PQ(){return a3||(a3=new WeakMap),a3}function rt(A){const g=PQ();g.set(A.texture,(g.get(A.texture)??0)+1)}function lC(A){const g=PQ(),I=(g.get(A.texture)??1)-1;return I<=0?(A.texture.destroy(),g.set(A.texture,0),!0):(g.set(A.texture,I),!1)}function eiA(A){return PQ().get(A.texture)===0}function t6(A){return PQ().get(A.texture)??0}function Qo(A){const g=PQ();g.set(A,(g.get(A)??0)+1)}function ro(A){const g=PQ(),I=(g.get(A)??1)-1;return I<=0?(A.destroy(),g.set(A,0),!0):(g.set(A,I),!1)}let vR=null;function tiA(A){return`${A.minFilter??"nearest"}:${A.magFilter??"nearest"}:${A.mipmapFilter??"nearest"}:${A.addressModeU??"clamp-to-edge"}:${A.addressModeV??"clamp-to-edge"}:${A.addressModeW??"clamp-to-edge"}:${A.maxAnisotropy??1}`}function Pe(A,g={}){const I=A._device;vR||(vR=new WeakMap);let e=vR.get(I);e||(e=new Map,vR.set(I,e));const t=tiA(g);let i=e.get(t);return i||(i=I.createSampler(g),e.set(t,i)),i}function c3(A){const g=A._device;vR?.delete(g)}function l3(A,g){const I={...A,...g};return C6?.(A,I),I}let C6=null;function CiA(A){C6=A}let oF=null;function OQ(A,g,I={}){const e=A._device;oF||(oF=new WeakMap);let t=oF.get(e);t||(t=new Map,oF.set(e,t));const i=`${g}\0${I.mipMaps??!0}\0${I.addressModeU??"repeat"}\0${I.addressModeV??"repeat"}\0${I.minFilter??"linear"}\0${I.magFilter??"linear"}\0${I.invertY??!0}\0${I.srgb??!1}\0${I.premultiplyAlpha??!1}`,o=t.get(i);if(o)return o;const Q=t,r=iiA(A,g,I);return Q.set(i,r),r.catch(()=>Q.delete(i)),r}async function iiA(A,g,I){const e=A._device,t=I.mipMaps??!0,i=I.addressModeU??"repeat",o=I.addressModeV??"repeat",Q=I.invertY??!0,r=I.srgb??!1,E=I.premultiplyAlpha??!1,n=r?"rgba8unorm-srgb":"rgba8unorm",c=await(await fetch(g)).blob(),l=await createImageBitmap(c,{premultiplyAlpha:E?"premultiply":"none",colorSpaceConversion:"none"}),D=l.width,p=l.height,y=t?Math.floor(Math.log2(Math.max(D,p)))+1:1,_=e.createTexture({size:{width:D,height:p},format:n,mipLevelCount:y,usage:dA.TEXTURE_BINDING|dA.COPY_DST|dA.RENDER_ATTACHMENT});if(e.queue.copyExternalImageToTexture({source:l,flipY:Q},{texture:_,premultipliedAlpha:E},{width:D,height:p}),l.close(),t&&y>1){const{generateMipmaps:R}=await Promise.resolve().then(()=>zR);R(A,_)}const u=I.minFilter??"linear",f=I.magFilter??"linear",h=t?"linear":"nearest",M=Pe(A,{addressModeU:i,addressModeV:o,minFilter:u,magFilter:f,mipmapFilter:h,maxAnisotropy:u==="linear"&&f==="linear"&&h==="linear"?4:1}),S={texture:_,view:_.createView(),sampler:M,width:D,height:p};return A._dlr?.u(S,g,I),rt(S),S}const oiA=64;let i6=null;function o6(A,g,I){g._recoverySource=I;const e=A._textures;if(e.size>=A._texturesPruneAt){for(const t of e)t.deref()||e.delete(t);A._texturesPruneAt=Math.max(oiA,e.size*2)}e.add(new WeakRef(g))}function B6(A,g){const I=A._recoverySource;if(!I)return;const e=i6?.get(I)?.deref();e&&o6(e,g,I)}function BiA(A){const g=A._deviceLostRecovery,I=new WeakRef(g),e=(t,i)=>{(i6??=new WeakMap).set(i,I),o6(g,t,i)};CiA(B6),A._dlr={t:e,d:B6,u(t,i,o){e(t,{kind:"url",url:i,opts:{...o}})},s(t,i,o,Q,r){e(t,{kind:"solid",rgba:[i,o,Q,r]})},b(t,i,o,Q,r){e(t,{kind:"bitmap",bitmap:i,srgb:o,mipMaps:Q,fallback:r})},p(t,i,o){e(t,{kind:"pixels",data:i.slice(0,t.width*t.height*4),width:t.width,height:t.height,options:{...o}})},r(t,i,o,Q,r){e(t,{kind:"render",width:i,height:o,format:Q,samplerDesc:r})},w(t,i,o,Q,r,E,n=0,s=r*4){const c=t._recoverySource;if(c?.kind!=="pixels")return;const l=r*4;for(let D=0;D<E;D++){const p=n+D*s,y=((Q+D)*c.width+o)*4;c.data.set(i.subarray(p,p+l),y)}},m(t,i,o,Q,r,E){A._deviceLostRecovery?._meshCaptureRefs&&(t._cpuUv2s=i??null,t._cpuTangents=o??null,t._cpuColors=Q??null,t._cpuGpuIndices=r,t._cpuIndexFormat=E)},e(t,i,o){g._meshCaptureRefs&&(t._envRecoverySource={kind:"env",url:i,brdfUrl:o})},h(t,i,o){g._meshCaptureRefs&&(t._envRecoverySource={kind:"hdr",url:i,faceSize:o})}}}function Q6(A,g=!1){const I=A._deviceLostRecovery;I||U(42),I._captureRefs++,g&&I._meshCaptureRefs++,I._captureRefs===1&&BiA(A)}function r6(A,g=!1){const I=A._deviceLostRecovery;!I||I._captureRefs===0||(I._captureRefs--,g&&I._meshCaptureRefs>0&&I._meshCaptureRefs--,I._captureRefs===0&&(A._dlr=void 0))}function QiA(A,g={}){return iF(A,{_kind:"scene",_recoverOrder:100,_enable(I){Q6(I,!0)},_disable(I){r6(I,!0)},async _recover(I){const{rebuildRegisteredScenes:e}=await Promise.resolve().then(()=>uLA);await e(I)},_onLost:g.onLost,_onRecovered:g.onRecovered,_onRecoveryFailed:g.onRecoveryFailed})}function riA(A,g={}){return iF(A,{_kind:"sprite-renderer",_enable:Q6,_disable:r6,async _recover(I){const{rebuildRegisteredSpriteRenderers:e}=await Promise.resolve().then(()=>dLA);await e(I)},_onLost:g.onLost,_onRecovered:g.onRecovered,_onRecoveryFailed:g.onRecoveryFailed})}function EiA(A,g={}){return iF(A,{_kind:"text-renderer",async _recover(I){const{rebuildRegisteredTextRenderers:e}=await Promise.resolve().then(()=>RLA);e(I)},_onLost:g.onLost,_onRecovered:g.onRecovered,_onRecoveryFailed:g.onRecoveryFailed})}function HR(A){A._refCount=(A._refCount??1)+1}function DC(A){const g=A._refCount;return g===void 0||g<=1?!0:(A._refCount=g-1,!1)}function E6(A,g,I,e=g.material){return Promise.resolve().then(()=>XK).then(t=>t.A(A,e,g,I)).catch(t=>console.error(t))}function D3(A,g,I){A._runtimeThinBuild=E6,A.thinInstances?(A.thinInstances.matrices=g,A.thinInstances.count=I,A.thinInstances._capacity=I,A.thinInstances._version++,A.thinInstances._dirtyMin=0,A.thinInstances._dirtyMax=I):A.thinInstances={matrices:g,count:I,_capacity:I,_version:1,_gpuBuffer:null,_gpuBufferStorage:!1,_gpuVersion:0,_dirtyMin:0,_dirtyMax:I,_colorVersion:0,_colorDirtyMin:0,_colorDirtyMax:0,_colorGpuBuffer:null,_colorGpuBufferStorage:!1,_colorGpuVersion:0,_gpuCullingEnabled:!1}}function p3(A,g){const I=A.thinInstances;I&&(I.count=g,I._version++,I._dirtyMin=0,I._dirtyMax=g)}function niA(A,g){const I=A.thinInstances;if(I){if(!Number.isInteger(g)||g<0||g>I._capacity)throw new RangeError(`Thin instance draw count ${g} must be an integer between 0 and capacity ${I._capacity}`);I.count!==g&&((!I._gpuBuffer||I._gpuVersion!==I._version||I.colors&&(!I._colorGpuBuffer||I._colorGpuVersion!==I._colorVersion))&&U(369),I.count=g,I._gpuVersion=++I._version)}}function siA(A){const g=A.thinInstances;g||U(370),g._drawArgsBuffer||(g._drawArgsInstanceCount=-1)}function aiA(A,g){A._runtimeThinBuild=E6;const I=A.thinInstances;if(!I){const i=new X(256);return i.set(g,0),A.thinInstances={matrices:i,count:1,_capacity:16,_version:1,_gpuBuffer:null,_gpuBufferStorage:!1,_gpuVersion:0,_dirtyMin:0,_dirtyMax:1,_colorVersion:0,_colorDirtyMin:0,_colorDirtyMax:0,_colorGpuBuffer:null,_colorGpuBufferStorage:!1,_colorGpuVersion:0,_gpuCullingEnabled:!1},0}const e=I.count;if(e>=I._capacity){const t=I._capacity*2,i=new X(t*16);i.set(I.matrices),I.matrices=i,I._capacity=t}return I.matrices.set(g,e*16),I.count++,I._version++,I._dirtyMin=0,I._dirtyMax=I.count,e}function ciA(A,g,I){const e=A.thinInstances;e.matrices.set(I,g*16),e._version++,e._dirtyMin=Math.min(e._dirtyMin,g),e._dirtyMax=Math.max(e._dirtyMax,g+1)}function liA(A,g){const I=A.thinInstances,e=I.count-1;g!==e&&I.matrices.copyWithin(g*16,e*16,e*16+16),I.count--,I._version++,I._dirtyMin=0,I._dirtyMax=I.count}function DiA(A){const g=A.thinInstances;g._version++,g._dirtyMin=0,g._dirtyMax=g.count}function piA(A,g){const I=A.thinInstances;I.colors=g,I._version++,I._colorVersion++,I._colorDirtyMin=0,I._colorDirtyMax=I.count}function yiA(A,g,I,e,t,i){const o=A.thinInstances,Q=o.colors,r=g*4;Q[r]=I,Q[r+1]=e,Q[r+2]=t,Q[r+3]=i,o._version++,o._colorVersion++,o._colorDirtyMin=Math.min(o._colorDirtyMin,g),o._colorDirtyMax=Math.max(o._colorDirtyMax,g+1)}function _iA(A,g=!0){const I=A.thinInstances;I||U(371),I._gpuCullingEnabled!==g&&(I._gpuCullingEnabled=g,I._gpuVersion=-1,I._colorGpuVersion=-1)}function uiA(A,g){const I=A.thinInstances;I||U(372),I._cullBoundsPad=g}function hiA(A,g,I){const e=A.thinInstances,t=g.thinInstances;if((!e||!t)&&U(373),A===g&&U(374),((e._refCount??1)>1||(t._refCount??1)>1)&&U(375),!Number.isFinite(I.distance)||I.distance<0)throw new RangeError("setThinInstanceLodPartner distance must be a finite non-negative number");const i=I.band??0;if(!Number.isFinite(i)||i<0)throw new RangeError("setThinInstanceLodPartner band must be a finite non-negative number");e._lodSource&&U(376),t._lodPartner&&U(377),t._lodSource&&t._lodSource!==A&&U(378),t.colors&&!e.colors&&U(379);const o=e._lodPartner;if(o&&o!==g){const r=o.thinInstances;r&&r._lodSource===A&&BF(r),o._clone=void 0,e._lodBuckets=null}e._lodPartner=g,e._lodDistance=I.distance,e._lodBand=i,t._lodSource=A,A._clone=g._clone="Cannot clone LOD-paired mesh";const Q=e._lodBuckets??new WeakMap;e._lodBuckets=Q,t._lodBuckets=Q,t._gpuCullingEnabled||(t._lodAutoCull=!0,t._gpuCullingEnabled=!0,t._gpuVersion=-1,t._colorGpuVersion=-1)}function fiA(A){const g=A.thinInstances;if(!g?._lodPartner)return;const I=g._lodPartner,e=I.thinInstances;g._lodPartner=null,g._lodDistance=void 0,g._lodBand=void 0,g._lodBuckets=null,A._clone=void 0,I._clone=void 0,e&&e._lodSource===A&&BF(e)}function diA(A){const g=A.thinInstances;if(!g)return;const I=g._lodSource,e=I?.thinInstances;I&&e?._lodPartner===A&&(e._lodPartner=null,e._lodDistance=void 0,e._lodBand=void 0,e._lodBuckets=null,I._clone=void 0),g._lodSource&&BF(g);const t=g._lodPartner,i=t?.thinInstances;g._lodPartner=null,g._lodDistance=void 0,g._lodBand=void 0,g._lodBuckets=null,A._clone=void 0,t&&i?._lodSource===A&&(t._clone=void 0,BF(i))}function BF(A){A._lodSource=null,A._lodBuckets=null,A._lodAutoCull&&(A._lodAutoCull=!1,A._gpuCullingEnabled=!1,A._gpuVersion=-1,A._colorGpuVersion=-1)}function X1(A){if(A._disposed)return;A._disposed=!0;const g=A._gpu;DC(g)&&(g.positionBuffer.destroy(),g.normalBuffer.destroy(),g.uvBuffer.destroy(),g.indexBuffer.destroy(),g.tangentBuffer?.destroy(),g.uv2Buffer?.destroy(),g.colorBuffer?.destroy());const I=A.thinInstances;I&&DC(I)&&(diA(A),I._gpuBuffer?.destroy(),I._colorGpuBuffer?.destroy(),I._drawArgsBuffer?.destroy());const e=A.skeleton;e&&DC(e)&&(e._disposed=!0,e.boneTexture.destroy(),DC(e._skinBuffers)&&(e.jointsBuffer.destroy(),e.weightsBuffer.destroy(),e.joints1Buffer?.destroy(),e.weights1Buffer?.destroy()));const t=A.vat;t&&DC(t)&&(t.settingsBuffer.destroy(),t.instanceTexture?.destroy(),DC(t._textureResource)&&t._textureResource.texture.destroy(),DC(t._skinBuffers)&&(t.jointsBuffer.destroy(),t.weightsBuffer.destroy(),t.joints1Buffer?.destroy(),t.weights1Buffer?.destroy()));const i=A.morphTargets;i&&DC(i)&&(i._disposed=!0,i.deltasBuffer.destroy(),i.weightsBuffer.destroy())}let y3=null;function QF(A,g){A._materialSwapQueue.includes(g)||A._materialSwapQueue.push(g)}function wiA(A){let g=A.material;Object.defineProperty(A,"material",{get(){return g},set(I){if(I!==g){g=I;const e=y3?.get(A);if(e)for(const t of e)QF(t,A)}},configurable:!0,enumerable:!0})}function MiA(A,g){g._disposed&&U(459,g.name);const I=y3??=new WeakMap;let e=I.get(g);e||(I.set(g,e=new Set),wiA(g)),e.add(A)}function n6(A,g){const I=y3?.get(g);return I?(I.delete(A),I.size===0):!0}function s6(A){const g=A._materialSwapQueue;if(!g[0]||A._runtimeBuilds?.w)return;let I,e,t;const i=A._renderables;for(const Q of g){const r=Q.material;if(!r)continue;const E=Q._runtimeThinBuild;if(E){e=E(A,Q,e);continue}const n=A._groups.get(r._buildGroup),s=n?.r;if(!s){(t??=[]).push(Q);continue}if(n._w?.(Q)){(t??=[]).push([Q,r]);continue}const c=A._meshDisposables.get(Q);c&&(A._meshDisposables.delete(Q),G1(A.surface.engine,()=>c.forEach(y=>y())));const l=n.o;let D;for(let y=i.length;y--;)i[y].mesh===Q&&(D=i.splice(y,1)[0]);r._csmGen=-~r._csmGen;const p=s(A,Q);if(l){const y=l.indexOf(D);y<0?l.push(p):l[y]=p}I=i.push(p)}if(I&&(i.sort((Q,r)=>Q.order-r.order),A._renderableVersion++,A._materialEpoch++),g.length=0,!t)return e;const o=t;return Promise.resolve().then(()=>XK).then(({C:Q})=>Q(A,o,e),Q=>{const r=A._runtimeBuilds;r?r._x(Q):console.error(Q)})}let a6=null;function SiA(A){a6=A}function RiA(A,g,I){a6?.(A,g,I)}function c6(A){const g={_tasks:[],_currentProcessedTask:null,build(){for(let I=0;I<g._tasks.length;I++)l6(g,g._tasks[I]);for(const I of g._tasks)for(const e of I._passes)e._initialize()},execute(){let I=0;for(const e of g._tasks)if(e.executionEnabled!==!1)if(e.execute)I+=e.execute();else for(const t of e._passes)I+=t._execute();return I},dispose(){for(const I of g._tasks)I.dispose();g._tasks.length=0,g._currentProcessedTask=null}};return g}function NiA(A,g){A._tasks.includes(g)||U(94,g.name),l6(A,g);for(const I of g._passes)I._initialize()}function l6(A,g){g._passes.length=0,A._currentProcessedTask=g;try{g.record()}finally{A._currentProcessedTask=null}}function D6(A,g){A._tasks.push(g)}function Oe(A,g,I,e,t,i){const o=I[e],Q=I[e+1],r=I[e+2],E=I[e+3],n=I[e+4],s=I[e+5],c=I[e+6],l=I[e+7],D=I[e+8],p=I[e+9],y=I[e+10],_=I[e+11],u=I[e+12],f=I[e+13],h=I[e+14],w=I[e+15];let M=t[i],S=t[i+1],R=t[i+2],N=t[i+3];A[g]=o*M+n*S+D*R+u*N,A[g+1]=Q*M+s*S+p*R+f*N,A[g+2]=r*M+c*S+y*R+h*N,A[g+3]=E*M+l*S+_*R+w*N,M=t[i+4],S=t[i+5],R=t[i+6],N=t[i+7],A[g+4]=o*M+n*S+D*R+u*N,A[g+5]=Q*M+s*S+p*R+f*N,A[g+6]=r*M+c*S+y*R+h*N,A[g+7]=E*M+l*S+_*R+w*N,M=t[i+8],S=t[i+9],R=t[i+10],N=t[i+11],A[g+8]=o*M+n*S+D*R+u*N,A[g+9]=Q*M+s*S+p*R+f*N,A[g+10]=r*M+c*S+y*R+h*N,A[g+11]=E*M+l*S+_*R+w*N,M=t[i+12],S=t[i+13],R=t[i+14],N=t[i+15],A[g+12]=o*M+n*S+D*R+u*N,A[g+13]=Q*M+s*S+p*R+f*N,A[g+14]=r*M+c*S+y*R+h*N,A[g+15]=E*M+l*S+_*R+w*N}function p6(A,g,I,e,t){const i=1/Math.tan(g*.5),o=t-e;A[0]=i/I,A[5]=i,A[10]=-e/o,A[11]=1,A[14]=t*e/o}function l1(A){const g=A.worldMatrixVersion;if(A._viewVer===g)return A._viewCache;const I=A._viewCache,e=A.worldMatrix,t=A._useFloatingOrigin,i=t?0:e[12],o=t?0:e[13],Q=t?0:e[14];return I[0]=e[0],I[1]=e[4],I[2]=e[8],I[3]=0,I[4]=e[1],I[5]=e[5],I[6]=e[9],I[7]=0,I[8]=e[2],I[9]=e[6],I[10]=e[10],I[11]=0,I[12]=-(e[0]*i+e[1]*o+e[2]*Q),I[13]=-(e[4]*i+e[5]*o+e[6]*Q),I[14]=-(e[8]*i+e[9]*o+e[10]*Q),I[15]=1,A._viewVer=g,I}let _3=null;function GiA(A){_3=A}function T1(A){return(A._projFov!==A.fov||A._projNear!==A.nearPlane||A._projFar!==A.farPlane)&&(A._projFov=A.fov,A._projNear=A.nearPlane,A._projFar=A.farPlane,A._projRev=(A._projRev??0)+1),A.worldMatrixVersion+(A._projRev??0)}function li(A,g){const I=T1(A);if(A._projVer===I&&A._projAspect===g)return A._projCache;const e=A._projCache;return _3!==null&&A.ortho?_3(A,g,e):p6(e,A.fov,g,A.nearPlane,A.farPlane),A._projVer=I,A._projAspect=g,e}function x1(A,g){const I=T1(A);if(A._vpVer===I&&A._vpAspect===g)return A._vpCache;const e=A._vpCache;return Oe(e,0,li(A,g),0,l1(A),0),A._vpVer=I,A._vpAspect=g,e}function jQ(A){const g=A.worldMatrix;return{x:g[12],y:g[13],z:g[14]}}function KC(A,g,I){const e=A?.viewport;return g/I*(e?e.width/e.height:1)}let TR=null,u3=null;function Mt(A){const g=A._device;return TR&&u3===g||(u3=g,TR=g.createBindGroupLayout({label:"scene",entries:[{binding:0,visibility:NA.VERTEX|NA.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:NA.FRAGMENT,buffer:{type:"uniform"}}]})),TR}function h3(){TR=null,u3=null}function rF(A){const g=A._blend?{format:A._format,blend:A._blend}:{format:A._format};return{label:A._label,layout:A._engine._device.createPipelineLayout({bindGroupLayouts:A._bgls}),vertex:{module:A._vertModule,entryPoint:"main",buffers:A._vertexBuffers},fragment:{module:A._fragModule,entryPoint:"main",targets:[g]},depthStencil:{format:A._depthStencilFormat??"depth24plus-stencil8",depthCompare:A._depthCompare??HQ,depthWriteEnabled:A._depthWriteEnabled??!0},multisample:{count:A._msaaSamples},primitive:{topology:"triangle-list",cullMode:A._cullMode??"back",frontFace:"ccw"}}}function et(A,g,I=0,e=0){const t=g;if(e===0&&t.length===16){A.set(t,I);return}const i=e,o=I;A[o+0]=t[i+0],A[o+1]=t[i+1],A[o+2]=t[i+2],A[o+3]=t[i+3],A[o+4]=t[i+4],A[o+5]=t[i+5],A[o+6]=t[i+6],A[o+7]=t[i+7],A[o+8]=t[i+8],A[o+9]=t[i+9],A[o+10]=t[i+10],A[o+11]=t[i+11],A[o+12]=t[i+12],A[o+13]=t[i+13],A[o+14]=t[i+14],A[o+15]=t[i+15]}function y6(A,g,I,e,t){A.fill(0);const i=x1(e,t),o=l1(e),Q=e.worldMatrix;et(A,i,0),et(A,o,16),g.useFloatingOrigin?(A[32]=0,A[33]=0,A[34]=0):(A[32]=Q[12],A[33]=Q[13],A[34]=Q[14]),A[87]=g.canvas.width;const r=I._envTextures,E=I.imageProcessing;A[76]=E.exposure,A[77]=E.contrast,A[78]=r?.lodGenerationScale??.8,A[79]=+E.toneMappingEnabled,A[37]=g.canvas.height}function EF(A,g){return A+g-1&~(g-1)}function Re(A,g,I){const e=A._device,t=e.createBuffer({label:I,size:EF(g.byteLength,16),usage:SA.UNIFORM|SA.COPY_DST});return e.queue.writeBuffer(t,0,g.buffer,g.byteOffset,g.byteLength),t}function jt(A,g,I){return A._device.createBuffer({label:I,size:EF(g,16),usage:SA.UNIFORM|SA.COPY_DST})}function wI(A,g,I,e){const t=EF(Math.max(g.byteLength,4),4),i=A._device.createBuffer({label:e,size:t,usage:I|SA.COPY_DST,mappedAtCreation:!0});return new mg(i.getMappedRange()).set(new mg(g.buffer,g.byteOffset,g.byteLength)),i.unmap(),i}const xR=368;let HI=16;function _6(A){if(!Number.isFinite(A)||A<1)throw new Error(`setMaxLights: expected positive integer, got ${A}`);HI=A|0}const f3=16,u6=new Vg(1),FiA=new X(u6.buffer),h6=20;function miA(){return Math.ceil(HI/4)}function d3(){return 16+HI*f3*4}function f6(A){let g=0;for(const I of A)g+=I._lightVersion??0;return g}function w3(A,g){A.fill(0);let I=0;const e=4;for(const t of g){if(I>=HI)break;t._writeLightUbo&&(t._writeLightUbo(A,e+I*f3),I++)}u6[0]=I,A[0]=FiA[0]}function VQ(A,g){let I=g._lightGpuState;const e=d3();if(I&&I._byteSize===e)return I;const t=!I;I?._buffer.destroy();const i=new X(e/4);return w3(i,g.lights),A._applyLightFoOffset?.(i,g),I={_buffer:Re(A,i),_scratch:i,_version:f6(g.lights)+(A._lightFoVersion?.(g)??0),_listVersion:g._lightListVersion??0,_lightCount:g.lights.length,_byteSize:e},g._lightGpuState=I,t&&g._disposables.push(()=>{g._lightGpuState?._buffer.destroy(),g._lightGpuState=void 0}),I}function biA(A,g){const I=VQ(A,g),e=f6(g.lights)+(A._lightFoVersion?.(g)??0),t=g._lightListVersion??0;return(e!==I._version||t!==I._listVersion||g.lights.length!==I._lightCount)&&(I._version=e,I._listVersion=t,I._lightCount=g.lights.length,w3(I._scratch,g.lights),A._applyLightFoOffset?.(I._scratch,g),A._device.queue.writeBuffer(I._buffer,0,I._scratch)),I._buffer}function KiA(A,g,I){w3(g,I.lights),A._applyLightFoOffset?.(g,I)}function d6(A){A.push({_name:"lc",_type:"u32"}),A.push({_name:"li",_type:`array<vec4<u32>, ${miA()}>`})}function w6(A,g="mli"){return`fn ${g}(i:u32)->u32{return ${A}.li[i/4u][i%4u];}`}function kiA(A,g){const I=g.id,e=A.includedOnlyMeshIds;return e?.size?!!I&&e.has(I):!I||!A.excludedMeshIds?.has(I)}function F1(A,g,I){const e=I?new Vg(I.buffer,I.byteOffset,I.byteLength/4):null;let t=0,i=-1,o=0;for(const Q of g){if(o>=HI)break;Q._writeLightUbo&&(kiA(Q,A)&&(i=o,e&&(e[h6+t]=o),t++),o++)}if(e){e[16]=t;for(let Q=t;Q<HI;Q++)e[h6+Q]=0}return t===1?i+1:-t}function Eo(A,g,I){const e=I;A.clr??=!0;const t=A.rt._descriptor,i={_colorFormat:t.format,_depthStencilFormat:A.depth?._descriptor.dFormat??t.dFormat,_depthCompare:t._depthCompare,_sampleCount:t.samples??1},o=Mt(g),Q=jt(g,xR),r=VQ(g,e)._buffer,E=g._device.createBindGroup({layout:o,entries:[{binding:0,resource:{buffer:Q}},{binding:1,resource:{buffer:r}}]}),n={loadOp:"clear",storeOp:"store"},s={targetWidth:0,targetHeight:0},c=A.autoMirror!==!1,l=!A.sharedRt,D={name:A.name,_config:A,engine:g,scene:e,_passes:[],_renderables:[],_opaqueBindings:[],_directBindings:[],_transparentBindings:[],_ob:[],_lastVersion:-1,_lastVis:0,_recorded:!1,_renderPassDescriptor:{colorAttachments:[n]},_colorAttachment:n,_sceneUBO:Q,_sceneBG:E,_lightsUBO:r,_suData:new X(xR/4),_sceneUboCacheKey:[],_targetSignature:i,_updateBatches:[],_pendingMeshes:[],addMesh(p,y){const _=y?.material??p.material;_&&(D._pendingMeshes.push({mesh:p,material:_}),D._recorded&&(nF(D,e),D._af=!1,sF(D,g,i)))},record(){D._af&&(D._renderables.length=0),nF(D,e),D._af=c&&!D._renderables.length,D._af&&D._renderables.push(...e._renderables);const p=A.rt;l&&(Kt(p,g),A.rst&&(p._descriptor.samples??1)>1&&Kt(A.rst,g)),A.depth&&!A.depth._eager&&Kt(A.depth,g),s.targetWidth=p._width,s.targetHeight=p._height,S6(D,g),sF(D,g,i),YiA(D,p),D._recorded=!0},execute(){return viA(D,g,i,s)},dispose(){D._passes.length=D._opaqueBindings.length=D._directBindings.length=0,D._transparentBindings.length=D._renderables.length=D._ob.length=0,l&&(Se(A.rt),Se(A.rst)),Se(A.depth),D._sceneUBO.destroy();for(const p of D._updateBatches)p.destroy();D._updateBatches.length=0}};return D}function qR(A,g){if(!A._renderables)return;let I=!1;for(let e=A._pendingMeshes.length-1;e>=0;e--)A._pendingMeshes[e].mesh===g&&(A._pendingMeshes.splice(e,1),I=!0);for(let e=A._renderables.length-1;e>=0;e--)A._renderables[e].mesh===g&&(A._renderables.splice(e,1),I=!0);for(const e of[A._opaqueBindings,A._directBindings,A._transparentBindings])for(let t=e.length-1;t>=0;t--)e[t].renderable.mesh===g&&(e.splice(t,1),I=!0);I&&(A._ob.length=0,A._lastVersion=-1)}function nF(A,g){if(A._pendingMeshes.length){for(const{mesh:I,material:e}of A._pendingMeshes){const t=e._buildGroup,i=g._groups.get(t),o=i?i.r:t._rebuildSingle;if(!o)throw Error();const Q=o(g,I,e);A._renderables.includes(Q)||A._renderables.push(Q)}A._pendingMeshes.length=0}}function UiA(A,g){return g._sortDistance-A._sortDistance||A.renderable.order-g.renderable.order}function M6(A,g){return A.renderable.order-g.renderable.order}function LiA(A,g){const I=A._transparentBindings;if(I.length<=1||!g)return;const e=l1(g);for(const t of I){const i=t.renderable._worldCenter;t._sortDistance=i?i[0]*e[2]+i[1]*e[6]+i[2]*e[10]+e[14]:0}I.sort(UiA)}function sF(A,g,I){const e=A._opaqueBindings,t=A._directBindings,i=A._transparentBindings;e.length=t.length=i.length=0;for(const o of A._renderables){const Q=o.bind(g,I);for(const r of Q._updateBatches??[])A._updateBatches.includes(r)||A._updateBatches.push(r);o.isTransparent||o._transmissive?i.push(Q):o._direct?t.push(Q):e.push(Q)}e.sort(M6),t.sort(M6),A._ob.length=0,A._lastVersion=A.scene._renderableVersion}function YiA(A,g){const I=A._config,e=A._colorAttachment;e.view=g._colorView,A._renderPassDescriptor.colorAttachments=g._colorView?[e]:[];const t=I.depth??g,i=t._depthView;let o;if(i){const Q=t._descriptor,r=(I.depth?t._eager:I.depthClear===!1)?"load":"clear";o={view:i,depthClearValue:Q._depthClearValue??0,depthLoadOp:r,depthStoreOp:"store"},Q.dFormat?.includes("stencil")&&(o.stencilClearValue=0,o.stencilLoadOp=r,o.stencilStoreOp="store")}A._renderPassDescriptor.depthStencilAttachment=o}function JiA(A,g,I,e){const t=A.scene;A._af&&A._lastVersion!==t._renderableVersion&&(A._renderables.length=0,A._renderables.push(...t._renderables),sF(A,g,I)),S6(A,g);const i=A._config.cam??t.camera;I._colorFormat&&(A._config._skipClusteredLights||t._clusteredLightUpdater?.(i,e.targetWidth,e.targetHeight),biA(g,t)),TiA(A,g,t,i),e._camera=i;for(const o of A._updateBatches)o.reset();M3(A._opaqueBindings,e),M3(A._directBindings,e),M3(A._transparentBindings,e);for(const o of A._updateBatches)o.flush(g);LiA(A,i)}function viA(A,g,I,e){if(A.enabled===!1)return 0;const t=A.scene,i=I._sampleCount;JiA(A,g,I,e);const o=A._colorAttachment,Q=A._config;if(Q.rt._colorView&&(Q.rt===t.surface.scRT&&(o.view=Q.rt._colorView),o.resolveTarget=Q.rst?._colorView??void 0,o.clearValue=Q.clrColor??t.clearColor,o.loadOp=Q.clr?"clear":"load"),A._executeWithTransmission)return A._executeWithTransmission(i);const r=g._currentEncoder.beginRenderPass(A._renderPassDescriptor),E=HiA(A,r);return r.end(),E}function HiA(A,g){const I=A.engine,e=A._config,t=e.rt,i=A.scene,o=A._opaqueBindings,Q=A._ob,r=A._sceneBG,n=(e.cam??i.camera)?.viewport;if(n){const c=t._width,l=t._height,D=Math.floor(n.x*c),p=Math.floor((1-n.y-n.height)*l),y=Math.ceil((n.x+n.width)*c)-D,_=Math.ceil((1-n.y)*l)-p;g.setViewport(D,p,y,_,0,1),g.setScissorRect(D,p,y,_)}if(g.setBindGroup(0,r),A._lastVersion!==i._renderableVersion||A._lastVis!==TQ||!Q.length){const c=t._descriptor,l=I._device.createRenderBundleEncoder({colorFormats:c.format?[c.format]:[],depthStencilFormat:A._targetSignature._depthStencilFormat,sampleCount:c.samples??1});l.setBindGroup(0,r),WQ(l,o,I),Q[0]=l.finish(),A._lastVersion=i._renderableVersion,A._lastVis=TQ}let s=o.length;return g.executeBundles(Q),g.setBindGroup(0,r),s+=WQ(g,A._directBindings,I),s+=WQ(g,A._transparentBindings,I),s}function S6(A,g){const I=VQ(g,A.scene)._buffer;I!==A._lightsUBO&&(A._lightsUBO=I,A._sceneBG=g._device.createBindGroup({layout:Mt(g),entries:[{binding:0,resource:{buffer:A._sceneUBO}},{binding:1,resource:{buffer:I}}]}),A._ob.length=0,A._lastVersion=-1)}function TiA(A,g,I,e){if(!e)return;const t=e.viewport,i=A._config.rt,o=(A._config.cs?g.canvas.width/g.canvas.height:i._width/i._height)*(t?t.width/t.height:1),Q=I.fog,r=I.imageProcessing,E=T1(e),n=I._envTextures,s=A._sceneUboCacheKey;if(s[0]===e&&s[1]===Q&&s[2]===E&&s[3]===o&&s[4]===r.exposure&&s[5]===r.contrast&&s[6]===n)return;s[0]=e,s[1]=Q,s[2]=E,s[3]=o,s[4]=r.exposure,s[5]=r.contrast,s[6]=n;const c=A._suData;y6(c,g,I,e,o);const l=I._sceneUboContributors;if(l)for(const D of l)D(c,I);g._device.queue.writeBuffer(A._sceneUBO,0,c)}function M3(A,g){for(const I of A)I.update?.(g)}function WQ(A,g,I){let e=null,t=0;for(const i of g){const o=i.renderable.mesh;o&&o.visible===!1||(i.pipeline!==e&&(A.setPipeline(i.pipeline),e=i.pipeline),t+=i.draw(A,I))}return t}let aF=null;function R6(A,g){const I=A.engine,t={_kind:"scene",surface:A,clearColor:{r:.2,g:.2,b:.3,a:1},camera:null,lights:[],meshes:[],animationGroups:[],fog:null,clipPlane:null,shadowGenerators:[],imageProcessing:{exposure:1,contrast:1,toneMappingEnabled:!1},_renderables:[],_prePasses:[],_pickSources:[],_uniformUpdaters:[],fixedDeltaMs:0,_beforeRender:[],_deferredBuilders:[],_groups:new Map,_disposables:[],_meshDisposables:new Map,_meshAuxDisposables:new Map,_materialSwapQueue:[],_renderableVersion:0,_materialEpoch:0,_built:!1,_drawCallsPre:0,_update(){I.useFloatingOrigin&&t.camera&&!t.camera._useFloatingOrigin&&(t.camera._useFloatingOrigin=!0,t.camera._viewVer=-1,t.camera._vpVer=-1);const o=t.fixedDeltaMs>0?t.fixedDeltaMs:I._currentDelta,Q=I._currentEncoder;let r=0;for(const E of t._beforeRender)E(o);t._materialSwapQueue.length&&s6(t);for(const E of t._prePasses)r+=E.execute(Q,I);for(const E of t._uniformUpdaters)E.update(I);t._drawCallsPre=r},_record(){return t._frameGraph.execute()},_resize(){t._frameGraph.build()}},i=c6();if(t._frameGraph=i,g?.defaultRenderTask!==!1){const o=A.msaaSamples>1,Q=o?wt({lbl:"scene-color",format:A.format,dFormat:"depth24plus-stencil8",samples:A.msaaSamples,size:A}):A.scRT,r=o?void 0:wt({lbl:"scene-depth",dFormat:"depth24plus-stencil8",samples:1,size:A});D6(i,Eo({name:"scene",rt:Q,rst:o?A.scRT:void 0,depth:r},I,t))}return t._disposables.push(()=>i.dispose()),t}function zQ(A,g){A._beforeRender.unshift(g)}function xiA(A,g){A._disposables.push(g)}function qiA(A){return A._frameGraph}function cF(A,g){const I=A;I._deferredBuilders.push(async()=>{const e=await g(I.surface.engine,I);I._renderables.push(...e.renderables),e.dispose&&I._disposables.push(e.dispose)})}function JI(A,g){const I=A;if("entities"in g){const t=g;for(const i of t.entities)JI(A,i);if(t.clearColor&&(I.clearColor=t.clearColor),t.camera&&!I.camera&&(I.camera=t.camera),t.animationGroups?.length){const i=I.surface.engine,o=t.animationGroups;I.animationGroups.push(...o);const Q=r=>{for(const E of o)RiA(E,r,i)};t._beforeRenderHook=Q,I._beforeRender.push(Q)}t._sceneSetup?.(I,t);return}if("_gpu"in g&&"material"in g){const t=g;MiA(I,t),I.meshes.push(t);const i=t.material?t.material._buildGroup:void 0;if(i){let o=I._groups.get(i);o||(o=[],I._groups.set(i,o),I._built||I._deferredBuilders.push(async()=>{const Q=await i(I,o);I._renderables.push(...Q.renderables),o.o=Q.renderables,Q.updater&&I._uniformUpdaters.push(Q.updater),o.r=Q.rebuildSingle})),o.push(t),(I._built||o.r)&&QF(I,t)}}else"lightType"in g&&I.lights.push(g);const e=g.children;if(e?.length)for(const t of e)t.parent=g,JI(A,t)}function N6(A){const g=A;if(g._z)return;g._z=!0;const I=aF??=new WeakMap;I.set(g,()=>1),qQ(g.surface,g),(()=>{I.set(g,()=>{for(const t of g._meshDisposables.values())t.forEach(i=>i());for(const t of g._meshAuxDisposables.values())t.forEach(i=>i());return g._meshDisposables.clear(),g._meshAuxDisposables.clear(),g._disposables.splice(0).forEach(t=>t()),g._renderables.length=g._uniformUpdaters.length=0,1});for(const t of g._disposables)t();for(const t of g._meshDisposables.values())for(const i of t)i();g._meshDisposables.clear();for(const t of g._meshAuxDisposables.values())for(const i of t)i();g._meshAuxDisposables.clear();for(const t of g.meshes)n6(g,t)&&X1(t);g._groups.clear(),g.meshes.length=0,g._renderables.length=0,g._prePasses.length=0,g._pickSources.length=0,g._uniformUpdaters.length=0,g._beforeRender.length=0,g._deferredBuilders.length=0,g._disposables.length=0,g._materialSwapQueue.length=0,g.lights.length=0,g.animationGroups.length=0,g.shadowGenerators.length=0,g.camera=null})()}async function G6(A){const g=A;for(g._built||(g._materialSwapQueue.length=0);g._deferredBuilders.length;){const I=g._deferredBuilders.splice(0);await Promise.all(I.map(e=>e()))}await s6(g),aF?.get(g)?.()||(g._runtimeBuilds?._e(),g._renderableVersion++,g._built=!0),await g._rebuildHook?.(g)}let PR=null;function PiA(A){PR=A}async function F6(A){const g=A,I=g.surface;n3(I,g)||(await G6(A),g._renderables.sort(m6),await Promise.all(g._frameGraph._tasks.map(e=>e._preload?.())),PR&&await PR(g),g._frameGraph.build(),I._renderingContexts[0]&&(await Promise.resolve().then(()=>fgA)).configureSwapchainOverlayScene(I,g),aF?.get(g)?.()||xQ(I,g))}async function OiA(A){const g=A,I=g.surface;n3(I,g)||(await G6(A),g._renderables.sort(m6),await jiA(I.engine,g),await Promise.all(g._frameGraph._tasks.map(e=>e._preload?.())),PR&&await PR(g),g._frameGraph.build(),I._renderingContexts[0]&&(await Promise.resolve().then(()=>fgA)).configureSwapchainOverlayScene(I,g),aF?.get(g)?.()||xQ(I,g))}const m6=(A,g)=>A.order-g.order;async function jiA(A,g){if(g._frameGraph._tasks.some(e=>e.name==="shadow"))return;const{createShadowTask:I}=await Promise.resolve().then(()=>JLA);g._frameGraph._tasks.unshift(I(A,g))}function ViA(A){qQ(A.surface,A)}function S3(A,g,I,e){A[3]=0,A[7]=0,A[11]=0,A[12]=g.x,A[13]=g.y,A[14]=g.z,A[15]=1;let t=I.x-g.x,i=I.y-g.y,o=I.z-g.z;const Q=Math.sqrt(t*t+i*i+o*o);let r=0,E=0,n=0,s=0;if(Q>=1e-10){const l=1/Q;t*=l,i*=l,o*=l,r=e.y*o-e.z*i,E=e.z*t-e.x*o,n=e.x*i-e.y*t,s=Math.sqrt(r*r+E*E+n*n)}if(s<1e-10){A[0]=1,A[1]=0,A[2]=0,A[4]=0,A[5]=1,A[6]=0,A[8]=0,A[9]=0,A[10]=1;return}const c=1/s;r*=c,E*=c,n*=c,A[0]=r,A[1]=E,A[2]=n,A[4]=i*n-o*E,A[5]=o*r-t*n,A[6]=t*E-i*r,A[8]=t,A[9]=i,A[10]=o}const R3={x:0,y:1,z:0};function Di(A,g,I,e,t,i,o,Q,r,E,n,s){const c=i*i,l=o*o,D=Q*Q,p=i*o,y=i*Q,_=o*Q,u=r*i,f=r*o,h=r*Q;A[g]=(1-2*(l+D))*E,A[g+1]=2*(p+h)*E,A[g+2]=2*(y-f)*E,A[g+3]=0,A[g+4]=2*(p-h)*n,A[g+5]=(1-2*(c+D))*n,A[g+6]=2*(_+u)*n,A[g+7]=0,A[g+8]=2*(y+f)*s,A[g+9]=2*(_-u)*s,A[g+10]=(1-2*(c+l))*s,A[g+11]=0,A[g+12]=I,A[g+13]=e,A[g+14]=t,A[g+15]=1}function N3(A,g,I,e,t,i,o,Q,r,E){const n=se();return Di(n,0,A,g,I,e,t,i,o,Q,r,E),n}function no(){const A=se();return A[0]=1,A[5]=1,A[10]=1,A[15]=1,A}const b6=Symbol("wmState");function tQ(A,g){A[b6]=g}function K6(A){return A===null?null:A[b6]??null}function OR(A){K6(A)?._invalidate()}function lF(A,g,I){return A.x===0&&A.y===0&&A.z===0&&g.x===0&&g.y===0&&g.z===0&&g.w===1&&I.x===1&&I.y===1&&I.z===1?no():N3(A.x,A.y,A.z,g.x,g.y,g.z,g.w,I.x,I.y,I.z)}function so(A){let g=0,I=-1,e=null;const t=se();let i=null,o=null;const Q=[];function r(){e=null,g++;for(const s of Q)s._invalidate()}function E(){const s=i.worldMatrixVersion;s!==I&&(I=s,r())}const n={get parent(){return i},set parent(s){s!==i&&(o!==null&&o._removeChild(n),i=s,o=K6(s),o!==null&&o._addChild(n),I=-1,r())},markLocalDirty(){r()},getWorldMatrix(){if(o===null&&i!==null&&E(),e!==null)return e;const s=A();if(i!==null){const c=i.worldMatrix;Oe(t,0,c,0,s,0),e=t}else e=s;return e},getWorldMatrixVersion(){return o===null&&i!==null&&E(),g},_invalidate(){r()},_addChild(s){Q.push(s)},_removeChild(s){const c=Q.indexOf(s);c>=0&&Q.splice(c,1)}};return n}class Ht{_x;_y;_z;_onDirty;constructor(g,I,e,t){this._x=g,this._y=I,this._z=e,this._onDirty=t}get x(){return this._x}set x(g){this._x!==g&&(this._x=g,this._onDirty())}get y(){return this._y}set y(g){this._y!==g&&(this._y=g,this._onDirty())}get z(){return this._z}set z(g){this._z!==g&&(this._z=g,this._onDirty())}set(g,I,e){this._x=g,this._y=I,this._z=e,this._onDirty()}copyFrom(g){this.set(g.x,g.y,g.z)}toArray(g,I=0){g[I]=this._x,g[I+1]=this._y,g[I+2]=this._z}}function k6(A,g,I,e){function t(){const s=Math.cos(n.alpha),c=Math.sin(n.alpha),l=Math.cos(n.beta);let D=Math.sin(n.beta);return D===0&&(D=1e-4),{x:n.target.x+n.radius*s*D,y:n.target.y+n.radius*l,z:n.target.z+n.radius*c*D}}const i=se();function o(){return S3(i,t(),n.target,R3),i}const Q=so(o),r=()=>Q.markLocalDirty(),E={alpha:A,beta:g,radius:I},n={alpha:0,beta:0,radius:0,target:new Ht(e.x,e.y,e.z,r),fov:.8,nearPlane:.1,farPlane:1e3,children:[],inertia:.9,panningInertia:.9,angularSensibility:1e3,panningSensibility:50,wheelPrecision:3,inertialAlphaOffset:0,inertialBetaOffset:0,inertialRadiusOffset:0,inertialPanningX:0,inertialPanningY:0,_viewCache:se(),_projCache:se(),_vpCache:se(),get parent(){return Q.parent},set parent(s){Q.parent=s},get worldMatrix(){return Q.getWorldMatrix()},get worldMatrixVersion(){return Q.getWorldMatrixVersion()}};for(const s of["alpha","beta","radius"])Object.defineProperty(n,s,{get:()=>E[s],set:c=>{E[s]!==c&&(E[s]=c,r(),n._clampToLimits?.())},configurable:!0,enumerable:!0});return tQ(n,Q),n}function U6(){return{minX:1/0,minY:1/0,minZ:1/0,maxX:-1/0,maxY:-1/0,maxZ:-1/0}}function WiA(A,g,I,e){const t=I-e,i=I+e,o=g===0?"minX":g===1?"minY":"minZ",Q=g===0?"maxX":g===1?"maxY":"maxZ";t<A[o]&&(A[o]=t),i>A[Q]&&(A[Q]=i)}function L6(A,g){const I=g.boundMin,e=g.boundMax;if(!I||!e)return;if(g._expandWorldBounds!==void 0){g._expandWorldBounds(A,g);return}const t=g.worldMatrix,i=[(I[0]+e[0])*.5,(I[1]+e[1])*.5,(I[2]+e[2])*.5],o=[(e[0]-I[0])*.5,(e[1]-I[1])*.5,(e[2]-I[2])*.5];for(let Q=0;Q<3;Q++){let r=t[12+Q],E=0;for(let n=0;n<3;n++){const s=t[n*4+Q];r+=s*i[n],E+=Math.abs(s)*o[n]}WiA(A,Q,r,E)}}function CQ(A,g,I){return{x:A,y:g,z:I}}function ziA(A){let g=1/0,I=1/0,e=1/0,t=-1/0,i=-1/0,o=-1/0;const Q=U6();for(const p of A.meshes)p.visible!==!1&&L6(Q,p);g=Q.minX,I=Q.minY,e=Q.minZ,t=Q.maxX,i=Q.maxY,o=Q.maxZ;const r=t-g,E=i-I,n=o-e;let c=Math.sqrt(r*r+E*E+n*n)*1.5,l=CQ(g+r*.5,I+E*.5,e+n*.5);(!isFinite(c)||c===0)&&(c=1,l=CQ(0,0,0));const D=k6(-(Math.PI/2),Math.PI/2,c,l);return D.nearPlane=c*.01,D.farPlane=c*1e3,A.camera=D,D}function ct(A,g){if("entities"in g){const I=g;for(const o of I.entities)ct(A,o);I.camera&&A.camera===I.camera&&(A.camera=null);const e=I.animationGroups;if(e?.length)for(const o of e)jR(A.animationGroups,o);const t=I._beforeRenderHook;t&&(jR(A._beforeRender,t),I._beforeRenderHook=void 0);const i=I._sceneCleanups;if(i){const o=i.get(A);o&&(jR(A._disposables,o),i.delete(A),A._z||o())}return}if("_gpu"in g&&"material"in g){eoA(A,g),v6(A,g);return}if("lightType"in g){jR(A.lights,g);const I=g.shadowGenerator;I?Y6(A,I):J6(A)}else"fov"in g&&"nearPlane"in g?A.camera===g&&(A.camera=null):"_shadowType"in g&&"_light"in g&&Y6(A,g);IoA(g),v6(A,g)}function ZiA(A,g){for(const I of g){const e=I.p;if(e){e._disposed=!0;const t=e._owner;if(t){const i=t.indexOf(e);i>=0&&t.splice(i,1),e._owner=void 0}}}XiA(A,()=>{for(const I of g)I()})}function XiA(A,g){if(A._z){g();return}G1(A.surface.engine,g)}function Y6(A,g){jR(A.shadowGenerators,g);const I=g._light;I&&I.shadowGenerator===g&&(I.shadowGenerator=void 0),J6(A);const e=g._shadowTaskState;e&&(g._shadowTaskState=void 0,$iA(A,()=>e._task.dispose()))}function $iA(A,g){A._pendingTopologyRetirements||(A._pendingTopologyRetirements=[],A._disposables.push(()=>AoA(A))),A._pendingTopologyRetirements.push(g)}function AoA(A){const g=A._pendingTopologyRetirements?.splice(0);if(!g?.length)return;const I=()=>{for(const t of g)try{t()}catch{}},e=A.surface.engine._device;e?e.queue.onSubmittedWorkDone().then(I,I):I()}function J6(A){A._lightListVersion=(A._lightListVersion??0)+1,A._built&&(A._rebuildHook=goA)}async function goA(A){const{rebuildSceneRenderables:g}=await Promise.resolve().then(()=>JP);await g(A)}function jR(A,g){const I=A.indexOf(g);I>=0&&A.splice(I,1)}function IoA(A){A&&typeof A=="object"&&"parent"in A&&(A.parent=null)}function v6(A,g){const I=g.children;if(I?.length)for(const e of[...I])ct(A,e)}function eoA(A,g){for(const E of A._frameGraph._tasks)E._removeMesh?.(g);const I=A._meshDisposables.get(g);let e=!1;const t=[];I&&(e=!0,t.push(...I),A._meshDisposables.delete(g));const i=A._meshAuxDisposables.get(g);i&&(e=!0,t.push(...i),A._meshAuxDisposables.delete(g));const o=A.meshes.indexOf(g);o>=0&&(A.meshes.splice(o,1),e=!0);const Q=A._renderables.findIndex(E=>E.mesh===g);Q>=0&&(A._renderables.splice(Q,1),e=!0),e&&A._renderableVersion++;for(const E of A._groups.values()){const n=E.indexOf(g);n>=0&&E.splice(n,1)}const r=A._materialSwapQueue.indexOf(g);r>=0&&A._materialSwapQueue.splice(r,1),A._runtimeBuilds?.remove(g),g.parent=null;for(const E of A._frameGraph._tasks)"_renderables"in E&&qR(E,g);n6(A,g)&&t.push(()=>X1(g)),t.length&&ZiA(A,t)}function ke(A,g){H6(A,g)&&cC()}function H6(A,g){let I=A.visible!==g;A.visible=g;const e=A.children;for(let t=0;t<e.length;t++)H6(e[t],g)&&(I=!0);return I}function toA(A,g){const I=g.fog;I&&(A[80]=I.mode,A[81]=I.start,A[82]=I.end,A[83]=I.density,A[84]=I.color[0],A[85]=I.color[1],A[86]=I.color[2])}function CoA(A,g){const I=g.clipPlane;I&&(A[88]=I[0],A[89]=I[1],A[90]=I[2],A[91]=I[3])}function ioA(A,g){A[36]=g._environmentRotation??0;const I=g._envTextures?.sphericalHarmonics;I&&A.set(I,40)}function DF(A,g){const I=A._sceneUboContributors??=[];I.includes(g)||I.push(g)}function T6(A){for(const g of A._frameGraph._tasks)g._sceneUboCacheKey&&(g._sceneUboCacheKey.length=0)}function ooA(A,g){A.fog=g,DF(A,toA)}function BoA(A,g){A.clipPlane=g,DF(A,CoA)}function pF(A){DF(A,ioA)}const x6=/textureSampleLevel\(\s*([^,]+?)\s*,\s*([^,]+?)\s*,\s*([^,]+?)\s*,\s*0(?:\.0?)?\s*\)\.rgb/,QoA=(A,g)=>{const I=A.match(x6),e=I?.[1],t=I?.[2],i=I?.[3];if(!e||!t||!i)throw new Error("Environment blur: skybox cubemap sample not found.");const Q=`clamp(scene._envPad1*log2(f32(textureDimensions(${e}).x))*${g==="dds"?"0.8":"scene.vImageInfos.z+scene._envPad2"},0.0,f32(textureNumLevels(${e})-1))`;return A.replace(x6,`textureSampleLevel(${e},${t},${i},0.0+(${Q})).rgb`)},roA=Object.freeze(Object.defineProperty({__proto__:null,_apply:QoA},Symbol.toStringTag,{value:"Module"})),EoA="struct a{viewProjection:mat4x4<f32>,view:mat4x4<f32>,vEyePosition:vec4<f32>,envRotationY:f32,_envPad0:f32,_envPad1:f32,_envPad2:f32,vSphericalL00:vec4<f32>,vSphericalL1_1:vec4<f32>,vSphericalL10:vec4<f32>,vSphericalL11:vec4<f32>,vSphericalL2_2:vec4<f32>,vSphericalL2_1:vec4<f32>,vSphericalL20:vec4<f32>,vSphericalL21:vec4<f32>,vSphericalL22:vec4<f32>,vImageInfos:vec4<f32>,vFogInfos:vec4<f32>,vFogColor:vec4<f32>,clipPlane:vec4<f32>}@group(0) @binding(0) var<uniform> scene:a;",n1=EoA;function q6(A,g,I){const e=A._environmentSkyboxShaderPatchLoaders??=[];e[g]=I,A._environmentSkyboxShaderComposer??=async(t,i)=>{t=i==="hdr"?n1+t:t;for(const o of e.slice())o&&(t=(await o())._apply(t,i));return t}}const noA=()=>roA;function soA(A,g){A[38]=g._environmentBlur??0,A[39]=g._envTextures?.lodGenerationOffset??0}function aoA(A,g){A._environmentBlur=g,q6(A,1,noA),DF(A,soA),T6(A)}const coA=()=>Promise.resolve().then(()=>HLA);function loA(A,g){pF(A),A._environmentRotation=g,q6(A,0,coA),T6(A)}function P6(A){const g=A.camera;if(!g)return{x:0,y:0,z:0};const I=g.worldMatrix;return{x:I[12],y:I[13],z:I[14]}}function DoA(A){return A.camera?A.camera.worldMatrixVersion:0}function poA(A,g){const e=g.camera?.worldMatrix;if(!e)return;const t=e[12],i=e[13],o=e[14];let Q=0;for(const r of g.lights){if(Q>=HI)break;if(!r._writeLightUbo)continue;const E=4+Q*f3,n=A[E+3];if(n===0||n===2){const s=r.worldMatrix;A[E]=s[12]-t,A[E+1]=s[13]-i,A[E+2]=s[14]-o}Q++}}function yoA(A,g,I){let e=-1;return()=>{const t=g.camera?g.camera.worldMatrixVersion:-1;t!==e&&(I(),e=t),A()}}const _oA=Object.freeze(Object.defineProperty({__proto__:null,applyLightFoOffset:poA,getFloatingOriginOffset:P6,lightFoVersion:DoA,wrapRenderableForFO:yoA},Symbol.toStringTag,{value:"Module"})),uoA=[A=>`AnimationGroup "${A}" is already attached to another AnimationManager`,()=>"Animation task category is required.",()=>"AnimationTask is already attached to another AnimationManager",()=>"AnimationManager autonomous mode requires requestAnimationFrame",A=>`Animation weight fade duration must be a finite positive number, got ${A}`,A=>`Animation weight must be a finite number between 0 and 1, got ${A}`,A=>`Animation weight must be a finite number between 0 and 1, got ${A}`,()=>"createPropertyAnimationClip requires at least one track",()=>"Animation play range must have toTime greater than fromTime",A=>`Animation track "${A}" requires at least one key`,A=>`Animation track "${A}" requires a positive frameRate`,A=>`Animation track "${A}" key times must be monotonically increasing`,A=>`Animation track "${A}" requires at least one key`,A=>`Animation key for "${A}" must provide exactly one of time or frame`,A=>`Animation key for "${A}" must have a non-negative time`,(A,g)=>`Animation key for "${A}" expected ${g} values`,(A,g)=>`Animation key for "${A}" expected ${g} values`,A=>`Invalid animation property path "${A}"`,(A,g)=>`Animation property path "${A}" could not resolve "${g}"`,(A,g)=>`Animation property path "${A}" could not resolve "${g}"`,A=>`Animation property path "${A}" reached a non-object value`,(A,g)=>`Animation property path "${A}" has unsupported vector size ${g}`,(A,g)=>`Animation property path "${A}" could not resolve component "${g}"`,()=>"Additive animation reference must use either referenceFrame or referenceTime, not both",A=>`Additive animation reference time must be a finite non-negative number, got ${A}`,()=>"Weighted glTF animation requires an AnimationManager engine",()=>"Weighted glTF animation requires an AnimationManager engine",()=>"Weighted animation channels for the same property must use the same value size",()=>"Audio engine media streams require a real-time AudioContext.",()=>"Unable to get a 2D context from the visualizer canvas.",()=>"setEffectUniforms: wrapper has no uniform binding.",A=>`setEffectUniforms: unknown uniform binding "${A}".`,A=>`setEffectTexture: unknown texture binding "${A}".`,A=>`EffectRenderTask "${A}" executed before record().`,A=>`EffectRenderer "${A}" recorded before registerEffectRenderer().`,A=>`createEffectWrapper: duplicate binding ${A}.`,(A,g)=>`Effect "${A}" missing uniform binding ${g}.`,(A,g)=>`Effect "${A}" missing texture binding ${g}.`,(A,g)=>`Effect "${A}" missing texture for sampler binding ${g}.`,(A,g,I)=>`writeUniformSlot: ${A} bytes exceeds uniform binding ${g} size ${I}.`,(A,g)=>`setUniformEffectUniforms: ${A} bytes exceeds uniform size ${g}.`,A=>`UniformEffectRenderTask "${A}" executed before record().`,()=>"Device-lost recovery capture requires an enabled recovery coordinator",()=>"WebGPU adapter not available during device recovery",A=>`WebGPU device recovery missing required features: ${A}`,()=>"forceWebGpuDeviceLossForTesting requires a device-lost recovery handler to be enabled first",()=>"WebGPU adapter not available",()=>"Babylon Lite: useFloatingOrigin requires useHighPrecisionMatrix on the engine.",()=>"WebGPU context not available",()=>"Babylon Lite: disposeSurface cannot dispose the engine's primary surface \u2014 use disposeEngine instead.",A=>`Flow Graph Editor: unsupported block class ${A}`,()=>"Flow Graph Editor: expected a serialized object",A=>`Flow Graph Editor: graph ${A} has no allBlocks array`,()=>"KHR_interactivity: duplicate type signatures",A=>`KHR_interactivity: unsupported type signature ${A}`,A=>`KHR_interactivity: node references missing declaration #${A}`,(A,g)=>`KHR_interactivity: variable ${A} references missing type #${g}`,(A,g,I)=>`KHR_interactivity: event ${A} value ${g} references missing type #${I}`,(A,g,I)=>`KHR_interactivity: ${A} node ${g} references invalid variable #${I}`,A=>`KHR_interactivity: variable/set node ${A} has invalid variable indices`,(A,g)=>`KHR_interactivity: variable/set node ${A} is missing input for variable #${g}`,(A,g)=>`KHR_interactivity: variable/set node ${A} input for variable #${g} has the wrong type`,A=>`KHR_interactivity: node ${A} is missing its pointer configuration`,(A,g)=>`KHR_interactivity: node ${A} is missing pointer parameter ${g}`,(A,g)=>`KHR_interactivity: node ${A} pointer parameter ${g} has the wrong type`,(A,g)=>`KHR_interactivity: ${A} node ${g} uses a reserved pointer parameter`,(A,g,I)=>`KHR_interactivity: ${A} node ${g} references invalid type #${I}`,(A,g)=>`KHR_interactivity: node ${A} references invalid event #${g}`,(A,g,I)=>`KHR_interactivity: ${A} node ${g} is missing required ${I} input`,(A,g)=>`KHR_interactivity: variable/interpolate node ${A} references invalid variable #${g}`,A=>`KHR_interactivity: variable/interpolate node ${A} can only use slerp with float4`,(A,g)=>`KHR_interactivity: pointer/interpolate node ${A} references invalid type #${g}`,(A,g,I)=>`KHR_interactivity: ${A} node ${g} cannot interpolate ${I}`,(A,g)=>`KHR_interactivity: node ${A} references missing producer node #${g}`,(A,g,I)=>`KHR_interactivity: node ${A} flow ${g} targets missing node #${I}`,A=>`invalid RFC 6901 escape in pointer segment ${A}`,A=>`literal pointer brackets must be doubled in ${A}`,()=>"JSON Pointer Templates must be absolute",A=>`duplicate pointer parameter ${A}`,A=>`CopyToTextureTask "${A}": either targetTexture or resolveTexture must be provided.`,A=>`CopyToTextureTask "${A}": sourceTexture cannot be the engine scRT because its GPU texture changes every frame.`,A=>`CopyToTextureTask "${A}": sourceTexture has no color texture. The source must be built before this task records.`,(A,g)=>`CopyToTextureTask "${A}": resolveTexture requires a multisampled sourceTexture (got sampleCount=${g}).`,(A,g)=>`CopyToTextureTask "${A}": resolveTexture must be single-sample (got sampleCount=${g}).`,(A,g,I,e,t)=>`CopyToTextureTask "${A}": sourceTexture (${g}x${I}) and resolveTexture (${e}x${t}) must have matching dimensions.`,(A,g)=>`CopyToTextureTask "${A}": resolveTexture requires a multisampled targetTexture (got sampleCount=${g}).`,(A,g)=>`CopyToTextureTask "${A}": resolveTexture must be single-sample (got sampleCount=${g}).`,(A,g,I)=>`CopyToTextureTask "${A}": resolveTexture format (${g}) must match targetTexture format (${I}).`,()=>"CopyToTextureTask: targetTexture has no color format.",A=>`DepthResolveTask "${A}": sourceTexture has no depth attachment.`,A=>`DepthResolveTask "${A}": sourceTexture must be multisampled (sampleCount > 1).`,A=>`DepthResolveTask "${A}": targetTexture has no depth format.`,()=>"FrameGraph target does not expose a frame graph.",A=>`addRenderPass("${A}"): no task is currently recording (called outside Task.record?)`,A=>`buildFrameGraphTask("${A}"): task is not registered in this graph.`,()=>"GeometryRendererTask: textureDescriptions must contain at least one entry.",A=>`GeometryRendererTask: textureDescriptions length ${A} exceeds the WebGPU max of 8 color attachments.`,A=>`GeometryRendererTask: unknown texture type ${A}.`,(A,g)=>`GeometryRendererTask: depthTexture sampleCount (${A}) must match samples (${g}).`,(A,g)=>`GeometryRendererTask: targetTexture sampleCount (${A}) must match samples (${g}).`,()=>"GeometryRendererTask: targetTexture must have a format.",()=>"overdraw probe: this device has no timestamp-query feature",()=>"overdraw probe: tasks that load existing depth cannot be measured with a fresh-depth replay",()=>"overdraw probe: task render target has no size (has the task rendered yet?)",()=>"overdraw probe: task target has no color+depth signature to replicate",()=>"overdraw probe: task has no draw bindings (has the task rendered yet?)",()=>"overdraw probe: timestamp readback produced no usable samples",A=>`PostProcessTask "${A}": sourceTexture has no color texture. Render the source to an offscreen RenderTarget before post-processing.`,A=>`PostProcessTask "${A}": multisampled source textures are not supported. Use a sampleCount: 1 source RenderTarget.`,A=>`PostProcessTask "${A}": outputTexture must have a format.`,(A,g)=>`PostProcessTask "${A}": extra texture ${g} has no color texture.`,A=>`PostProcessTask "${A}": sourceTexture must have a format.`,()=>"buildClusteredLightGpuState: scene.camera is required",()=>"ClusteredLightContainer: light count cannot grow after GPU state creation.",()=>"Device-lost Scene recovery requires environment loading after recovery was enabled",(A,g,I)=>`Device-lost Scene recovery could not refetch '${A}' (${g} ${I}).`,(A,g)=>`${A}: image ${g} not found`,(A,g)=>`${A}: bufferView ${g} not found`,(A,g,I)=>`${A}: failed to load image ${g} ${I}`,A=>`${A}: image has neither bufferView nor uri`,(A,g)=>`${A}: strided accessor uses unsupported component type: ${g}`,(A,g,I)=>`${A}: strided accessor ${g} uses unsupported component type: ${I}`,(A,g,I)=>`${A}: invalid accessor stride ${g} for accessor ${I}`,A=>`glTF camera ${A}: unsupported projection`,()=>"glTF camera nodes require non-zero uniform scale",A=>`EXT_mesh_gpu_instancing: accessor count mismatch on node ${A}`,A=>`EXT_meshopt_compression: compressed source buffer ${A} is not buffer 0 (unsupported)`,A=>`EXT_meshopt_compression: uncompressed bufferView in buffer ${A} is not buffer 0 (unsupported)`,A=>`glTF sparse: unsupported componentType ${A}`,A=>`glTF sparse: unsupported index componentType ${A}`,A=>`glTF sparse: unsupported value componentType ${A}`,()=>"glTF sparse: indices.componentType is required",(A,g)=>`glTF sparse: index ${A} out of range for accessor of count ${g}`,()=>"Not a valid GLB file",()=>"First GLB chunk is not JSON",()=>"Second GLB chunk is not BIN",(A,g)=>`Failed to load image: ${A} ${g}`,()=>"loadGltf: baseless input can't resolve relative URI; use self-contained GLB or URL with base.",A=>`Unsupported component type: ${A}`,()=>"Image has neither bufferView nor uri",(A,g)=>`Failed to load image: ${A} ${g}`,()=>"Image has neither bufferView nor uri",()=>"Invalid HDR: missing #? signature",A=>`Unsupported HDR format: ${A}`,A=>`Invalid HDR resolution: ${A}`,()=>"Invalid HDR: RLE scanline width does not match image",()=>"Invalid HDR: truncated RLE scanline",()=>"Invalid HDR: zero-length RLE packet",()=>"Invalid HDR: RLE run exceeds scanline",()=>"Invalid HDR: RLE literal exceeds scanline",()=>"Invalid HDR: truncated scanline",A=>`loadSOG: decoded WebP has zero dimensions (input size ${A})`,()=>"loadSOG: failed to acquire 2D context for WebP decode",()=>"loadSOG: means.mins/means.maxs must be arrays",()=>"loadSOG: SOG v2 missing scales codebook",()=>"loadSOG: scales.mins/maxs must be arrays for SOG v1",()=>"loadSOG: SOG v2 missing sh0 codebook",()=>"loadSOG: sh0.mins/maxs must be arrays for SOG v1",A=>`loadSOG: invalid quaternion mode ${A}`,()=>"loadSOG: SOG v2 missing shN codebook",(A,g)=>`loadSOG: HTTP ${A} for ${g}`,()=>"loadSOG: meta.json not found in archive",A=>`loadSOG: missing image '${A}' inside archive`,(A,g)=>`loadSplat: HTTP ${A} for ${g}`,A=>`loadSplat: failed to parse PLY at ${A} (unsupported property layout)`,()=>"loadSPZ: file too short to contain header",(A,g)=>`loadSPZ: unsupported SPZ stream (magic=0x${A} version=${g})`,(A,g)=>`loadSPZ: HTTP ${A} for ${g}`,()=>"Invalid compressed PLY: packed vertex properties require chunk metadata for every vertex",()=>"zip: EOCD record not found",()=>"zip: ZIP64 archives are not supported",A=>`zip: bad central directory signature at offset ${A}`,()=>"zip: encrypted entries are not supported",()=>"zip: ZIP64 archives are not supported",A=>`zip: bad local file header signature at offset ${A}`,(A,g)=>`zip: unsupported compression method ${A} for entry '${g}'`,(A,g,I)=>`zip: entry '${A}' decompressed size mismatch (got ${g}, expected ${I})`,A=>`LineMaterial "${A}" requires thin-instance data`,()=>"createLineMaterial requires useThinInstances when useThinInstanceColors is enabled",(A,g)=>`NodeMaterial: cannot pick common numeric type from ${A} and ${g}`,A=>`NodeMaterial: AmbientOcclusionBlock "${A}" requires an ImageSourceBlock source`,()=>"BiPlanarBlock: texture projection is supported only in the fragment stage",A=>`NodeMaterial: ColorSplitterBlock (id=${A}) has no connected input`,A=>`NodeMaterial: ColorSplitterBlock has no output "${A}"`,A=>`NodeMaterial: unknown CurveBlock curveType ${A}`,A=>`NodeMaterial: CurveBlock does not support ${A}`,()=>"NodeMaterial: FragDepthBlock requires `depth` or both `worldPos` and `viewProjection` inputs",A=>`NodeMaterial: HeightToNormalBlock "${A}" requires worldTangent when generateInWorldSpace is false`,A=>`InputBlock: unknown mesh attribute "${A}"`,(A,g)=>`InputBlock: unsupported systemValue ${A} on block "${g}"`,A=>`LoopBlock "${A}": index can only be read while emitting the loop body`,A=>`LoopBlock "${A}": loopID can only be consumed by StorageReadBlock/StorageWriteBlock`,(A,g)=>`LoopBlock "${A}": unsupported output "${g}"`,A=>`NodeMaterial: MatrixSplitterBlock has no output "${A}"`,A=>`NodeMaterial: unsupported matrix block "${A}"`,()=>"NodeMaterial: NLerpBlock requires a vector left/right input; Babylon.js emits normalize(mix(...)) for this block",()=>"NodeMaterial: PBR-MR core emitter cannot emit optional PBR feature code",()=>"NodeMaterial: PBR-MR core helper cannot emit optional PBR feature code",A=>`NodeMaterial: RandomNumberBlock requires a vector seed so Babylon.js getRand(seed.xy) can be emitted; got ${A}`,A=>`ReflectionTextureBaseBlock "${A}" is an abstract compatibility block and cannot be emitted directly.`,A=>`ReflectionTextureBlock: coordinatesMode ${A} not supported (only EQUIRECTANGULAR_MODE=7)`,A=>`NodeMaterial: ReplaceColorBlock requires a vector/color value; got ${A}`,(A,g)=>`StorageReadBlock "${A}": unsupported output "${g}"`,A=>`StorageReadBlock "${A}": loopID input is not connected`,(A,g)=>`StorageReadBlock "${A}": loop ${g} is not active`,()=>"NodeMaterial: TBNBlock object output is not supported; use row0/row1/row2 outputs",A=>`NodeMaterial: TeleportOutBlock (id=${A}) has no entryPoint`,(A,g)=>`NodeMaterial: TeleportOutBlock (id=${A}) points to missing TeleportInBlock ${g}`,()=>"TriPlanarBlock: texture projection is supported only in the fragment stage",A=>`NodeMaterial: VectorSplitterBlock (id=${A}) has no connected input`,A=>`NodeMaterial: VectorSplitterBlock has no output "${A}"`,A=>`NodeMaterial: WaveBlock does not support ${A}`,A=>`NodeMaterial: unknown WaveBlock kind ${A}`,(A,g,I)=>`NodeMaterial: cannot cast ${A} to ${g} for expression \`${I}\``,(A,g)=>`${A}: unsupported BJS connection point type 0x${g}`,(A,g,I)=>`NodeMaterial: block "${A}" (id=${g}) has no input "${I}"`,(A,g,I)=>`NodeMaterial: block "${A}" (id=${g}) input "${I}" is not connected`,(A,g,I)=>`NodeMaterial: dangling connection ${A}.${g} -> block ${I}`,A=>`NodeMaterial: no emitter loaded for block "${A}"`,()=>"NodeMaterial: only vertex->fragment varyings are supported",A=>`NodeMaterial: fragment root block ${A} not found`,A=>`NodeMaterial: no emitter for fragment root "${A}"`,A=>`NodeMaterial: vertex root block ${A} not found`,A=>`NodeMaterial: no emitter for vertex root "${A}"`,()=>"NodeMaterial: PBR/Reflection block requires scene environment but scene._envTextures is unset. Call loadEnvironment() before registerScene().",()=>"node-geometry view does not support scene group building",()=>"NodeMaterial geometry view: graph has no GeometryTextureOutputBlock",()=>"NodeMaterial geometry view: morph / env / shadow inputs are not supported in the geometry pass",()=>"node-geometry: render target has no color attachments",(A,g)=>`NodeMaterial geometry view: texture binding "${A}" not set. Provide it via material.inputs["${g}"].texture before the first render.`,()=>"NodeMaterial geometry view: NORMALIZED_VIEW_DEPTH requested but no geometry-params UBO was provided by the task.",()=>"NodeMaterial geometry view: emitColor (real-color target) is not supported \u2014 omit targetTexture on the geometry task.",()=>"NodeMaterial: graph has no FragmentOutputBlock",()=>"NodeMaterial: advanced PBR-MR helper request must be emitted by the full PBR-MR block",()=>"NodeMaterial: invalid source \u2014 expected `.blocks` array",A=>`NodeMaterial: block missing numeric id (name=${A})`,(A,g)=>`NodeMaterial: cycle detected through block ${A} (${g})`,A=>`NodeMaterial: dangling reference to block ${A}`,A=>`NodeMaterial: helper key "${A}" registered with conflicting source bodies`,A=>`NodeMaterial: no advanced extension emitter registered for block "${A}"`,A=>`NodeMaterial: no compatibility extension emitter registered for block "${A}"`,A=>`NodeMaterial: no math extension emitter registered for block "${A}"`,A=>`NodeMaterial: no procedural extension emitter registered for block "${A}"`,(A,g)=>`NodeMaterial: texture binding "${A}" not set. Provide it via options.textures or material.inputs["${g}"].texture before the first render.`,A=>`NodeMaterial: material requires shadow generator #${A} but none was supplied to parseNodeMaterialFromSnippet({ shadowGenerators }).`,A=>`NodeMaterial: unsupported attribute "${A}"`,(A,g)=>`NodeMaterial: snippet fetch failed (${A}) for ${g}`,A=>`NodeMaterial: snippet "${A}" has no jsonPayload`,A=>`NodeMaterial: snippet "${A}" has no nodeMaterial`,(A,g)=>`[babylon-lite] ${A} must contain three finite${g} values`,A=>`[babylon-lite] ${A} must be finite and positive`,A=>`[babylon-lite] local probe ${A} influenceInnerRadius must be finite, non-negative, and no larger than influenceOuterRadius`,A=>`[babylon-lite] local probe ${A} inner influence box must be non-negative and contained by the outer influence box`,A=>`[babylon-lite] local probe ${A} angleRadians must be finite`,A=>`[babylon-lite] local probe ${A} debugColor must contain three finite values from 0 to 1`,()=>"[babylon-lite] local probe cubemap dimensions must differ only by power-of-two mip levels",()=>"[babylon-lite] local probe voxelGrid.cellSize must be finite and positive",()=>"[babylon-lite] local probe voxelGrid.maximum must be greater than minimum on every axis",()=>"[babylon-lite] local probe voxel grid dimensions are too large",()=>"[babylon-lite] local probe voxel grid dimensions are too large",(A,g,I,e,t)=>`[babylon-lite] local probe voxel (${A}, ${g}, ${I}) intersects ${e} probes, exceeding maxCandidates ${t}`,()=>"[babylon-lite] local probe cubemaps require COPY_SRC usage; call enablePbrLocalCubemap() before loading DDS or HDR probe environments, or create custom probe textures with COPY_SRC",()=>"[babylon-lite] local probe cubemaps must be square six-face textures with one shared format",()=>"[babylon-lite] local probe cubemaps have no common mip range",(A,g)=>`[babylon-lite] local probe set has ${A} probes, but this device supports at most ${g} cube-array probes`,(A,g)=>`[babylon-lite] local probe UBO requires ${A} bytes, but this device supports ${g}`,A=>`[babylon-lite] local probe voxel grid requires ${A} bytes, exceeding this device's storage-buffer limits`,A=>`[babylon-lite] local probe sets require 1..${A} probes`,()=>"Environment rotation: skybox direction declaration not found.",(A,g)=>`${A}: expected to rewrite 1 occurrence, rewrote ${g}`,A=>`local probe array _postCompose: expected to rewrite 1 voxel-grid binding declaration, rewrote ${A}`,A=>`local probe array _postCompose: expected to rewrite 1 cube-array binding declaration, rewrote ${A}`,A=>`local cubemap _postCompose: expected to rewrite 1 clearcoat reflection direction, rewrote ${A}`,A=>`local cubemap _postCompose: expected to rewrite 1 clearcoat radiance sample, rewrote ${A}`,A=>`local cubemap _postCompose: expected to rewrite 1 sheen radiance sample, rewrote ${A}`,A=>`local cubemap _postCompose: expected to rewrite 1 reflection direction, rewrote ${A}`,()=>"local cubemap _postCompose: expected at least 1 environment LOD scale rewrite",A=>`local cubemap _postCompose: expected to rewrite 1 base radiance sample, rewrote ${A}`,A=>`[babylon-lite] local cubemap could not replace the scene ${A} binding`,()=>"PBR transmission requires a frame-graph refraction texture.",()=>"composePbrGeometryShader: PBR fragment signature mismatch \u2014 _noColorOutput/_esmShadowOutput should be off",()=>"composePbrGeometryShader: alpha-block return statement not found \u2014 template changed?",()=>"pbr-geometry view does not support scene group building",()=>"buildPbrGeometryRenderable: scene has no PBR context. Ensure regular PBR meshes have been built before recording the geometry task.",()=>"pbr-geometry: render target has no color attachments",A=>`[babylon-lite] local cubemap maxCandidates is already ${A} and cannot be changed after initialization`,A=>`[babylon-lite] local cubemap maxCandidates must be an integer from 1 to ${A}`,()=>"setShadowCasterMaterial: the caster chain must not cycle back to the source material",()=>"Async ShaderMaterial pipeline preparation could not capture the synchronous descriptor.",(A,g)=>`ShaderMaterial: ${A} name "${g}" is not a valid WGSL identifier.`,()=>"ShaderMaterial: vertexSource and fragmentSource must be non-empty WGSL strings.",A=>`ShaderMaterial: unsupported attribute "${A}". Supported attributes: position, normal, uv, uv2, tangent, color, joints, weights, joints1, weights1.`,A=>`ShaderMaterial: duplicate attribute "${A}".`,()=>'ShaderMaterial: "position" attribute is required for mesh rendering.',A=>`ShaderMaterial: define "${A}" must be a boolean or number.`,()=>"ShaderMaterial: `transmissive` requires `needAlphaBlending` (the surface composites over the grabbed opaque scene color).",A=>`ShaderMaterial: custom uniform "${A}" must use an explicit typed declaration.`,(A,g)=>`ShaderMaterial: unsupported uniform type "${A}" for "${g}".`,(A,g)=>`ShaderMaterial: duplicate generated identifier "${A}" while adding ${g}.`,(A,g,I,e)=>`ShaderMaterial: uniform "${A}" of type ${g} expects ${I} value(s), got ${e}.`,A=>`ShaderMaterial: uniform "${A}" was not declared.`,(A,g,I,e)=>`ShaderMaterial: uniform "${A}" of type ${g} expects ${I} value(s), got ${e}.`,A=>`ShaderMaterial: sampler "${A}" was not declared.`,A=>`ShaderMaterial: sampler "${A}" expects a depth Texture2D.`,A=>`ShaderMaterial: sampler "${A}" cannot use a depth Texture2D.`,A=>`ShaderMaterial: storage buffer "${A}" was not declared.`,()=>"setShaderStorageBuffer requires a StorageBuffer created by createStorageBuffer; raw GPUBuffer is not supported.",A=>`ShaderMaterial: storage buffer "${A}" has been disposed.`,()=>"setShaderStorageBuffer requires a live StorageBuffer created by createStorageBuffer.",A=>`ShaderMaterial: sampler "${A}" has no Texture2D. Call setShaderTexture() before rendering.`,A=>`ShaderMaterial storage "${A}" is invalid.`,()=>"Standard UV transform _bind requires the scene argument from the Standard bind-group builder",()=>"composeStandardGeometryShader: standard fragment signature mismatch \u2014 bypass active?",()=>"composeStandardGeometryShader: 'return color;' not found in composed fragment \u2014 template changed?",()=>"standard-geometry view does not support scene group building",()=>"standard-geometry: skeletal velocity feature was not preloaded",()=>"standard-geometry: thin instances were not preloaded",()=>"standard-geometry: morph targets require the scene Standard morph context",()=>"standard-geometry: thin instances were not preloaded",()=>"standard-geometry: skeletal velocity requires a previous-bone texture",()=>"standard-geometry: render target has no color attachments",()=>"Dashed lines require at least two points",()=>"createDashedLines produced no dash segments (degenerate points or dashNb)",()=>"updateDashedLines requires a mesh created by createDashedLines",A=>`Line system data requires finite ${A} components`,()=>"Line system data requires one color row per line",()=>"Line system data requires one color per point",()=>"createLineSystemData requires at least one point",()=>"createLineSystem requires material.useVertexColor to match the line color-buffer layout",()=>"updateLineSystem requires a mesh created by createLineSystem",()=>"updateLineSystem requires unchanged line and point counts",()=>"updateLineSystem requires unchanged line and point counts",()=>"updateLineSystem cannot add colors to a mesh created without vertex colors",A=>`createCsgFromMesh("${A}") requires CPU positions. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,A=>`createCsgFromMesh("${A}") requires CPU indices. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,A=>`createCsgFromMesh("${A}") requires CPU normals. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,(A,g)=>`createMeshesFromCsg("${A}") missing material for CSG material slot ${g}.`,()=>"CSG2 is not initialized. Call and await initializeCsg2Async() before using CSG2 operations.",A=>`${A} cannot use a disposed CSG2 solid.`,A=>`createCsg2FromMesh("${A}") requires CPU positions. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,A=>`createCsg2FromMesh("${A}") requires CPU indices. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,A=>`createCsg2FromMesh("${A}") requires CPU normals. Use a Babylon Lite mesh factory or loader that retains CPU geometry.`,(A,g)=>`createCsg2FromMesh("${A}") materialSlot must be an integer from 0 to ${g}.`,()=>"CSG2 operations require solids with the same vertex property layout.",(A,g)=>`createMeshesFromCsg2("${A}") received an unknown Manifold material original ID ${g}.`,A=>`Unable to build CSG2 mesh "${A}". Manifold has 0 vertices for this output.`,(A,g)=>`createMeshesFromCsg2("${A}") missing material for CSG2 material slot ${g}.`,()=>"enableThinInstanceWorldBounds requires mesh.thinInstances",()=>"createHierarchyInstancePool capacity must be a non-negative integer",()=>"createHierarchyInstancePool requires at least one mesh in the source hierarchy",A=>`createHierarchyInstancePool mesh "${A}" already has thin instances`,A=>`createHierarchyInstancePool requires an invertible world matrix for mesh "${A}"`,()=>"addHierarchyInstance exceeded pool capacity",()=>"setHierarchyInstanceCount count must be an integer within pool capacity",A=>`setHierarchyInstanceCount mesh "${A}" is missing thin instance data`,A=>`HierarchyInstancePool mesh "${A}" is missing thin instance data`,A=>`${A} index must reference an active hierarchy instance`,()=>"updateMeshGeometryCapacity requires unshared, tightly-packed mesh geometry",()=>"updateMeshGeometryCapacity requires coherent triangle-list geometry with uint32 indices",()=>"updateMeshGeometryCapacity requires unchanged optional-attribute layout",A=>`mesh attribute updates require unshared geometry: ${A}`,()=>"mesh attribute update requires a valid tightly-packed vertex range",()=>"mesh attribute update requires a valid destination vertex range",()=>"updateMeshGeometry requires unshared, tightly-packed mesh geometry",()=>"updateMeshGeometry requires unchanged vertex/index counts; use resizeMeshGeometry for topology changes",()=>"updateMeshGeometry requires unchanged optional-attribute layout; use resizeMeshGeometry for layout changes",()=>"updateMeshGeometryCapacity requires reserveFactor >= 1",()=>"Thin-instance LOD partners require an opaque, non-transmissive material",()=>"Thin-instance LOD partner requires the source draw to provide instance colors",()=>"setThinInstanceDrawCount requires a fully synchronized fixed-capacity pool",()=>"enableThinInstanceDynamicDrawCount requires mesh.thinInstances",()=>"enableThinInstanceGpuCulling requires mesh.thinInstances",()=>"setThinInstanceCullBoundsPad requires mesh.thinInstances",()=>"setThinInstanceLodPartner requires thinInstances on both meshes",()=>"setThinInstanceLodPartner requires two distinct meshes",()=>"setThinInstanceLodPartner does not support thin-instance data shared by mesh clones",()=>"setThinInstanceLodPartner fullMesh cannot already be an LOD partner",()=>"setThinInstanceLodPartner lodMesh cannot also own an LOD partner",()=>"setThinInstanceLodPartner lodMesh is already paired with another source mesh",()=>"setThinInstanceLodPartner requires source instance colors when the LOD partner uses instance colors",A=>`createNavMesh (tile cache) failed: ${A}`,A=>`createNavMesh (tiled) failed: ${A}`,A=>`createNavMesh failed: ${A}`,A=>`Mesh "${A}" missing CPU geometry for navmesh`,()=>"No navmesh generated. Call createNavMesh first.",()=>"Navmesh not ready. Call createNavMesh first.",()=>"Navmesh has no tile cache. Build with `maxObstacles > 0` to enable obstacles.",()=>"NodeParticle: BasicSpriteUpdateBlock requires SetupSpriteSheetBlock",()=>"NodeParticle: LocalPositionUpdated requires SystemBlock.isLocal",()=>"NodeParticle: LocalPositionUpdated read before local shape position creation",A=>`NodeParticle: ParticleLocalVariableBlock ${A} received an unsupported value`,A=>`NodeParticle: ParticleLocalVariableBlock ${A} received an unsupported value`,A=>`NodeParticle: ParticleLocalVariableBlock ${A} received an unsupported value`,A=>`NodeParticle: ParticleLocalVariableBlock ${A} received an unsupported value`,A=>`NodeParticle: ParticleLocalVariableBlock ${A} changed value type`,()=>"NodeParticle: emitter provider must return a finite 16-element matrix",()=>"NodeParticle: emitter provider must return a finite 16-element matrix",(A,g)=>`NodeParticle: ParticleTeleportInBlock ${A} does not expose output "${g}"`,(A,g,I)=>`NodeParticle: ${A} ${g} does not expose output "${I}"`,A=>`NodeParticle: graph plumbing cycle ${A}`,(A,g,I)=>`NodeParticle: ${A} ${g} does not support ${I} connections`,A=>`NodeParticle: ParticleTeleportOutBlock ${A} has invalid entryPoint`,(A,g)=>`NodeParticle: ParticleTeleportOutBlock ${A} references missing entryPoint ${g}`,(A,g)=>`NodeParticle: ParticleTeleportOutBlock ${A} entryPoint ${g} is not ParticleTeleportInBlock`,A=>`NodeParticle: graph plumbing cycle ${A}`,A=>`NodeParticle: ParticleTeleportInBlock ${A} input is not connected`,(A,g)=>`NodeParticle: ${A} ${g} input is not connected`,A=>`NodeParticle: ParticleLocalVariableBlock ${A} Particle scope requires particle-only evaluation`,()=>"NodeParticle: invalid source \u2014 expected a `blocks` array",A=>`NodeParticle: block missing numeric id (name=${A})`,()=>"NodeParticle: graph has no SystemBlock",A=>`NodeParticle: failed to load texture "${A}"`,()=>"NodeParticle: unable to decode texture content",()=>"BillboardSpriteSystem requires a depth-stencil render target.",()=>"createParticleBillboard: the particle system has no texture",A=>`syncParticleSprite2DBridgeWithBlendModes: pixelsPerUnit must be a positive finite number, got ${A}`,(A,g)=>`syncParticleSprite2DBridgeWithBlendModes: originPx must be finite, got [${A}, ${g}]`,()=>"syncParticleSprite2DBridgeWithBlendModes: bridge-owned layers cannot use the Sprite2D Handle API",()=>"createParticleSprite2DBridge: the particle system has no texture",A=>`createParticleSprite2DBridge: pixelsPerUnit must be a positive finite number, got ${A}`,(A,g)=>`createParticleSprite2DBridge: originPx must be finite, got [${A}, ${g}]`,()=>"syncParticleSprite2DBridge: the bridge-owned layer cannot use the Sprite2D Handle API",A=>`syncParticleSprite2DBridge: pixelsPerUnit must be a positive finite number, got ${A}`,(A,g)=>`syncParticleSprite2DBridge: originPx must be finite, got [${A}, ${g}]`,()=>"createHeightFieldShape requires either a groundMesh or full explicit heightfield parameters.",()=>"createHeightFieldShape ground mesh has no vertex positions.",A=>`createHeightFieldShape requires a regular (N+1)\xD7(N+1) grid mesh (e.g. from createGroundFromHeightMap); got ${A} vertices, which is not the square of an integer \u2265 2.`,()=>"createHeightFieldShape ground mesh has zero extent in X or Z; cannot build a heightfield.",()=>"Cannot create physics mesh shape from a singular root transform.",()=>"Cannot create physics mesh shape without vertex positions.",()=>"Cannot create physics mesh shape without triangle indices.",()=>"Physics mesh shapes require a mesh or transform hierarchy.",A=>`Unsupported shape type: ${A}`,()=>"Cannot add physics child shape from a singular parent transform.",()=>"Failed to read physics body mass properties.",A=>`Unknown physics rotation axis "${A}".`,()=>"createPhysicsAggregate supports only primitive physics shapes.",A=>`BloomPostProcessTask "${A}": sourceTexture must have a format.`,A=>`BloomPostProcessTask "${A}": sourceTexture must have a format.`,A=>`DepthOfFieldPostProcessTask "${A}": sourceTexture must have a format.`,A=>`ScreenSpaceContactShadowsPostProcessTask "${A}": sourceTexture must be single-sample.`,A=>`ScreenSpaceContactShadowsPostProcessTask "${A}": depthTexture must be single-sample.`,A=>`ScreenSpaceContactShadowsPostProcessTask "${A}": depth source has no depth attachment.`,A=>`ScreenSpaceGlobalIlluminationPostProcessTask "${A}": sourceTexture must be single-sample.`,A=>`ScreenSpaceGlobalIlluminationPostProcessTask "${A}": depthTexture must be single-sample.`,A=>`ScreenSpaceGlobalIlluminationPostProcessTask "${A}": depth source has no depth attachment.`,()=>"Alpha-to-coverage is not supported for NodeMaterial.",()=>"Uniform copies require 4-byte-aligned sizes and destination offsets.",()=>"StorageBuffer has been disposed.",()=>"StorageBuffer belongs to a different engine.",()=>"StorageBuffer is not a live registered allocation.",()=>"StorageBuffer has been disposed.",()=>"StorageBuffer is not a live registered allocation.",()=>"StorageBuffer belongs to a different engine.",()=>"StorageBuffer is not a live registered allocation.",()=>"StorageBuffer byteOffset must be a non-negative multiple of 4.",()=>"StorageBuffer update data must have a byte length that is a multiple of 4.",A=>`StorageBuffer update exceeds its ${A}-byte capacity.`,()=>"StorageBuffer is not a live registered allocation.",A=>`Mesh "${A}" cannot be added: it was disposed when it left its last scene. Create a new mesh instead.`,A=>`morph _postCompose: expected to rewrite 2 binding declarations, rewrote ${A}`,()=>"getCsmReceiverTexture requires a CSM shadow generator",()=>"Deformable shadows require a fully initialized shadow generator",A=>`Device-lost Scene recovery does not support shadow generator type "${A}"`,()=>"Device-lost Scene recovery could not find ESM shadow resources",()=>"Device-lost Scene recovery failed to create ESM shadow resources",()=>"AnimationController.tick requires an EngineContext for skeleton or morph animation",()=>"Cannot update disposed skeleton",()=>"Invalid bone matrices",()=>"createBillboardCustomShader: `fragment` must be a non-empty WGSL string.",()=>"BillboardSpriteSystem requires a depth-stencil render target.",()=>"addBillboardSprite: handle id space exhausted.",(A,g)=>`${A}: BillboardSpriteHandle ${g} has been removed.`,()=>"BillboardSpriteSystem: alphaCutoff must be a finite number.",()=>"BillboardSpriteSystem: opacity must be a finite number.",()=>"createAxisLockedBillboardSystem: axis components must be finite numbers.",()=>"createAxisLockedBillboardSystem: axis must be non-zero.",()=>"addBillboardSpriteIndex: props.position is required.",()=>"addBillboardSpriteIndex: props.sizeWorld is required.",(A,g)=>`updateBillboardSpriteIndex: index ${A} out of range [0, ${g})`,(A,g)=>`removeBillboardSpriteIndex: index ${A} out of range [0, ${g})`,(A,g)=>`setBillboardSpriteFrameIndex: index ${A} out of range [0, ${g})`,(A,g)=>`${A}: extra texture name "${g}" is not a valid WGSL identifier.`,(A,g,I,e)=>`${A}: frame ${g} has non-positive size ${I}x${e}.`,(A,g,I,e)=>`${A}: frame ${g} has negative sub-rect origin (srcX=${I}, srcY=${e}).`,(A,g,I,e)=>`${A}: frame ${g} sub-rect row extent (srcX + width) * 4 = ${I} exceeds srcStrideBytes ${e} (would spill into next row).`,(A,g,I,e)=>`${A}: frame ${g} width ${I} exceeds shelf max width ${e}.`,(A,g,I,e,t,i)=>`${A}: cannot fit frame ${g} (${I}x${e}) \u2014 atlas height capacity ${t} exhausted at y=${i}.`,()=>"createSpriteAtlasFromFrames: at least one frame is required, or pass options.capacityPx to create an empty atlas with reserved capacity for appendSpriteAtlasFrames.",(A,g)=>`createSpriteAtlasFromFrames: atlas dimensions must be >= 1 (got ${A}x${g}).`,(A,g,I,e)=>`createSpriteAtlasFromFrames: capacityPx ${A}x${g} too small for initial content ${I}x${e}.`,()=>"appendSpriteAtlasFrames: atlas was not built by createSpriteAtlasFromFrames (no packer state).",()=>"loadSpriteAtlas: metadataUrl unsupported.",()=>"loadSpriteAtlas: gridSize required.",(A,g)=>`resolveSpriteFrame: index ${A} out of range [0, ${g})`,()=>"addSprite2D: handle id space exhausted.",(A,g)=>`${A}: Sprite2DHandle ${g} has been removed.`,()=>'enableSprite2DYSort: only depth: "none" layers are supported.',()=>"enableSprite2DYSort: defaultBias must be finite.",()=>"setSprite2DYSortBias: Y-sort is not enabled for this layer.",(A,g)=>`setSprite2DYSortBias: index ${A} out of range [0, ${g})`,()=>"setSprite2DYSortBias: bias must be finite.",()=>"addSprite2DIndex: positionPx required.",(A,g)=>`updateSprite2DIndex: index ${A} out of range [0, ${g})`,(A,g)=>`removeSprite2DIndex: index ${A} out of range [0, ${g})`,(A,g)=>`setSprite2DFrameIndex: index ${A} out of range [0, ${g})`,()=>"SpriteAnimationManager is already attached to a render loop.",()=>"SpriteAnimationManager is already attached to an AnimationManager.",()=>"SpriteAnimationManager is already running autonomously.",()=>"SpriteAnimationManager is already attached to a render loop.",()=>"SpriteAnimationManager is already attached to an AnimationManager.",()=>"Sprite frame animation requires finite from/to frame indices.",()=>"Sprite frame animation requires finite from/to frame indices.",()=>"SpriteAnimationManager is already attached to a render loop.",()=>"SpriteAnimationManager is already attached to an AnimationManager.",()=>"SpriteAnimationManager is already running autonomously.",()=>"createSprite2DCustomShader: `fragment` must be a non-empty WGSL string.",()=>"Sprite pipeline: depth-enabled pipelines require a depth-stencil format.",()=>"Sprite pipeline: depth-enabled pipelines require a scene bind-group layout.",()=>'Depth-hosted sprites require depth != "none".',()=>"Depth-hosted Sprite2DLayer requires a depth-stencil render target.",()=>'SpriteRenderer requires depth: "none".',()=>"SpriteRenderer has been disposed.",A=>`TextData style palette cannot exceed ${A} entries.`,(A,g)=>`updateTextData ${A}: storage does not contain curveSet "${g}" \u2014 add it via updateGlyphStorage first.`,(A,g,I)=>`${A}: run index ${g} out of range (0..${I}).`,A=>`${A}: GlyphRun reference is not in this TextData.`,()=>"updateTextData addRun: GlyphRun reference is already in this TextData.",()=>"updateTextData removeRun: GlyphRun reference is not in this TextData.",()=>"updateTextData replaceRun: previous GlyphRun reference is not in this TextData.",()=>"updateTextData replaceRun: new GlyphRun reference is already in this TextData.",A=>`TextData style palette cannot exceed ${A} entries.`,()=>"Basis: no images in file",()=>"Basis: startTranscoding failed",A=>`Basis: transcoded size is 0 for mip ${A}`,A=>`Basis: transcodeImage failed for mip ${A}`,(A,g)=>`createDynamicTexture: width/height must be >= 1 (got ${A}x${g})`,()=>"createHtmlTexture: requires a DOM canvas rendering surface (HTML-in-Canvas is unavailable on OffscreenCanvas).",()=>"KTX: file too small",()=>"KTX: invalid magic",()=>"KTX: unsupported endianness",()=>"KTX: not a compressed texture (glType != 0)",()=>"KTX: not a compressed texture (glFormat != 0)",A=>`KTX: unknown glInternalFormat 0x${A}`,()=>"KTX: 3D textures not supported",()=>"KTX: texture arrays not supported",()=>"KTX: cubemaps not supported (use loadCubeTexture)",()=>"KTX: key/value data overflows buffer",A=>`KTX: truncated at mip ${A} size field`,A=>`KTX: mip ${A} data overflows buffer`,()=>"KTX: no mip levels found",A=>`KTX fetch failed: ${A}`,A=>`KTX2: ${A}`,()=>"KTX2: decoder produced no mipmaps",A=>`KTX2: decoder produced an empty mip ${A}`,A=>`KTX2: device does not support ${A}`,(A,g,I)=>`KTX2: uncompressed mip ${A} has ${g} bytes, expected ${I}`,A=>`KTX2: unsupported transcoded format 0x${A}`,(A,g)=>`KTX2 fetch failed: ${A} for ${g}`,()=>"KTX2: RGBA decode size does not match image dimensions",A=>`KTX2: ${A}`,()=>"KTX2: decoder produced no mipmaps",(A,g)=>`KTX2: expected ${A} base-level layers but decoded ${g}`,(A,g,I,e)=>`KTX2: base-level layer ${A} is malformed (expected ${g}x${I}, ${e} bytes)`,(A,g)=>`createTexture2DFromPixels: width/height must be >= 1 (got ${A}x${g})`,(A,g,I,e)=>`createTexture2DFromPixels: data too short \u2014 need ${A} bytes for ${g}x${I} RGBA, got ${e}`,(A,g)=>`createRenderTexture2D: width/height must be >= 1 (got ${A}x${g})`,(A,g)=>`updateTexture2DFromPixels: width/height must be >= 1 (got ${A}x${g})`,(A,g,I,e)=>`updateTexture2DFromPixels: data too short \u2014 need ${A} bytes for ${g}x${I} RGBA, got ${e}`,(A,g,I)=>`createTexture3DFromPixels: width/height/depth must be >= 1 (got ${A}x${g}x${I})`,(A,g,I,e,t)=>`createTexture3DFromPixels: data too short \u2014 need ${A} bytes for ${g}x${I}x${e} RGBA, got ${t}`,()=>"createRenderTargetTexture: descriptor.size must be fixed { width, height } pixels, not a SurfaceContext (would invalidate eagerly-allocated textures when the canvas resizes).",()=>"createRenderTargetTexture: render target has no color or depth texture (no format / depthStencilFormat?).",(A,g,I)=>`createTexture2DArray: width/height/layers must be >= 1 (got ${A}x${g}x${I})`,(A,g)=>`uploadImageToArrayLayer: layer must be an integer in [0, ${A}) (got ${g})`,(A,g)=>`loadImageToArrayLayer: fetch failed for ${A} (${g})`,(A,g)=>`createTexture2DArrayFromUrls: fetch failed for ${A} (${g})`,(A,g,I,e,t)=>`createTexture2DArrayFromUrls: all layers must share one size; layer 0 is ${A}x${g} but layer ${I} is ${e}x${t}`,(A,g)=>`updateTexture2DArrayFromPixels: mipLevel must be an integer in [0, ${A}) (got ${g})`,(A,g,I,e,t,i)=>`updateTexture2DArrayFromPixels: data too short \u2014 need ${A} bytes for ${g}x${I}x${e} RGBA at mip ${t}, got ${i}`,()=>"KTX2: the decoder does not report layerCount; a decoder with 2D array support is required (see setKtx2DecoderUrl)",(A,g)=>`KTX2: decoder produced ${A} mips, which is not a whole number of ${g}-layer levels`,(A,g,I)=>`KTX2: expected layer ${A} at mip index ${g} but the decoder reported layer ${I}`,(A,g)=>`KTX2: layers of one mip level must share a size (level ${A}, layer ${g})`,A=>`KTX2: device does not support ${A}`,(A,g,I,e)=>`KTX2: uncompressed mip ${A} layer ${g} has ${I} bytes, expected ${e}`,A=>`KTX2: unsupported transcoded format 0x${A}`,(A,g)=>`KTX2 fetch failed: ${A} for ${g}`,()=>"CPU-only animation evaluation is unavailable for this animation controller",A=>`VAT prepared payload: ${A} must be a positive integer.`,A=>`VAT prepared payload: ${A} must be a record.`,(A,g)=>`VAT prepared payload: ${A} contains invalid bone index "${g}".`,(A,g)=>`VAT prepared payload: ${A}[${g}] has an invalid length.`,()=>"VAT prepared payload: data length must equal boneCount * frameCount * 16.",()=>"VAT prepared payload: clips must be a record.",A=>`VAT prepared payload: clip "${A}" is invalid.`,A=>`VAT preparation: mesh "${A}" has no skeleton to bake.`,(A,g)=>`VAT preparation: mesh "${A}" has no skeleton binding for clip "${g}".`,A=>`VAT preparation: mesh "${A}" has inconsistent bone counts.`,()=>"setVatInstanceStorage: mesh has no VAT data.",()=>"setVatInstanceStorage requires a live StorageBuffer from the same engine.",()=>"setVatTime: mesh has no VAT data.",()=>"attachVat: mesh has no skeleton (bake first, attach before clearing it).",()=>"controllerModels requires XR input tracking; do not pass input:false to enterXr.",()=>"handTracking requires XR input tracking; do not pass input:false to enterXr.",()=>"pointerSelection requires XR input tracking; do not pass input:false to enterXr.",()=>"WebXR is not available (navigator.xr missing).",()=>"WebGPU XR is not supported by this browser (XRGPUBinding missing).",()=>"teleportation requires XR input tracking; do not pass input:false to enterXr."];function O6(A,g){const I=uoA[A];return I?I(...g):`Error #${A}`}function hoA(){GCA(O6)}function foA(A){if(!(A instanceof Error))return String(A);const g=A.lite;if(!Array.isArray(g))return A.message;const I=/^#(\d+)$/.exec(A.message);return I?O6(Number(I[1]),g):A.message}function doA(A,g){if(Array.isArray(g))for(const I of g)A._dependencies.add(I);else A._dependencies.add(g)}const woA={r:.2,g:.2,b:.3,a:1};function MoA(A,g){const I={name:A,_parentTask:g,_dependencies:new Set,_renderTarget:null,_renderTargetDepth:null,_renderPassDescriptor:{colorAttachments:[]},_colorAttachment:null,_depthAttachment:null,clearColor:{...woA},clear:!0,_executeFunc:null,_beforeExecute:null,_initialize(){const e=I._renderTarget;if(!e)throw new Error(`RenderPass "${I.name}": render target not set`);const t=e._colorView;let i=null;t&&(i={view:t,loadOp:I.clear?"clear":"load",storeOp:"store",clearValue:I.clearColor});const o=I._renderTargetDepth??e,Q=o._descriptor.dFormat,r=o._depthView,E=Q?Q==="depth24plus-stencil8"||Q==="depth32float-stencil8"||Q==="stencil8":!1;let n=null;r&&(n={view:r,depthClearValue:o._descriptor._depthClearValue??0,depthLoadOp:"clear",depthStoreOp:"store",...E?{stencilClearValue:0,stencilLoadOp:"clear",stencilStoreOp:"store"}:{}}),I._colorAttachment=i,I._depthAttachment=n,I._renderPassDescriptor={label:I.name,colorAttachments:i?[i]:[],depthStencilAttachment:n??void 0}},_execute(){const e=I._renderTarget;if(!e)return 0;I._beforeExecute?.();const t=I._parentTask.engine,i=I._colorAttachment;i&&(i.clearValue=I.clearColor,i.loadOp=I.clear?"clear":"load",i.view=e._colorView);const o=t._currentEncoder.beginRenderPass(I._renderPassDescriptor);let Q=0;return I._executeFunc&&(Q=I._executeFunc(o)),o.end(),Q},_dispose(){I._renderTarget=null,I._renderTargetDepth=null,I._colorAttachment=null,I._depthAttachment=null,I._renderPassDescriptor={colorAttachments:[]},I._executeFunc=null,I._beforeExecute=null,I._dependencies.clear()}};return g._passes.push(I),I}function j6(A){return typeof A=="object"&&A!==null&&"_tasks"in A}function VR(A){if(j6(A))return A;if("_frameGraph"in A&&j6(A._frameGraph))return A._frameGraph;U(92)}function SoA(A,g){D6(VR(A),g)}function RoA(A,g){const I=VR(A),e=I._tasks[0]?.name==="shadow"?1:0;I._tasks.splice(e,0,g)}function NoA(A,g,I){const e=VR(A),t=e._tasks.indexOf(I);t<0?e._tasks.push(g):e._tasks.splice(t,0,g)}function GoA(A,g,I){const e=VR(A),t=e._tasks.indexOf(I);t<0?e._tasks.push(g):e._tasks.splice(t+1,0,g)}function FoA(A,g){const e=VR(A)._currentProcessedTask;return e||U(93,g),MoA(g,e)}function moA(A,g){const I=A.engine,e=g?.update,t={_kind:"frame-graph-context",name:g?.name??"frame-graph",surface:A,frameGraph:c6(),clearColor:g?.clearColor??{r:0,g:0,b:0,a:1},_drawCallsPre:0,_disposed:!1,_update(){t._disposed||e?.(I._currentDelta)},_record(){return t._disposed?0:t.frameGraph.execute()},_resize(){t._disposed||t.frameGraph.build()}};return t}function boA(A){A._disposed||(A.frameGraph.build(),xQ(A.surface,A))}function V6(A){qQ(A.surface,A)}function KoA(A){const g=A;g._disposed||(V6(A),A.frameGraph.dispose(),g._disposed=!0)}function W6(A,g){return Math.floor(Math.log2(Math.max(A,g)))+1}const koA="@group(0)@binding(0)var src:texture_depth_2d;struct V{@builtin(position)p:vec4f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return V(vec4f(p,0,1));}@fragment fn fs(@builtin(position)fc:vec4f)->@location(0)f32{return textureLoad(src,vec2<i32>(fc.xy),0);}";function UoA(A){return`@group(0)@binding(0)var src:texture_2d<f32>;struct V{@builtin(position)p:vec4f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return V(vec4f(p,0,1));}@fragment fn fs(@builtin(position)fc:vec4f)->@location(0)f32{let c=vec2<i32>(fc.xy)*2;let sd=vec2<i32>(textureDimensions(src));let d=sd-vec2<i32>(1,1);let x1=min(c.x+1,d.x);let y1=min(c.y+1,d.y);let a=textureLoad(src,vec2<i32>(c.x,c.y),0).r;let b=textureLoad(src,vec2<i32>(x1,c.y),0).r;let e=textureLoad(src,vec2<i32>(c.x,y1),0).r;let f=textureLoad(src,vec2<i32>(x1,y1),0).r;var r=${A}(${A}(a,b),${A}(e,f));let dd=max(sd/vec2<i32>(2,2),vec2<i32>(1,1));let extraX=(sd.x&1)==1&&i32(fc.x)==dd.x-1;let extraY=(sd.y&1)==1&&i32(fc.y)==dd.y-1;if(extraX){let x2=min(c.x+2,d.x);r=${A}(r,${A}(textureLoad(src,vec2<i32>(x2,c.y),0).r,textureLoad(src,vec2<i32>(x2,y1),0).r));}if(extraY){let y2=min(c.y+2,d.y);r=${A}(r,${A}(textureLoad(src,vec2<i32>(c.x,y2),0).r,textureLoad(src,vec2<i32>(x1,y2),0).r));if(extraX){r=${A}(r,textureLoad(src,vec2<i32>(min(c.x+2,d.x),y2),0).r);}}return r;}`}function LoA(A,g){const I=A._device,e=g.reduce??"max",t=Pe(A,{minFilter:"nearest",magFilter:"nearest",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),i=I.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"depth",viewDimension:"2d"}}]}),o=I.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"unfilterable-float",viewDimension:"2d"}}]}),Q=(M,S)=>I.createRenderPipeline({layout:I.createPipelineLayout({bindGroupLayouts:[S]}),vertex:{module:I.createShaderModule({code:M}),entryPoint:"vs"},fragment:{module:I.createShaderModule({code:M}),entryPoint:"fs",targets:[{format:"r32float"}]},primitive:{topology:"triangle-list"}}),r=Q(koA,i),E=Q(UoA(e),o);let n=Math.max(1,g.width|0),s=Math.max(1,g.height|0),c=W6(n,s);function l(){return I.createTexture({label:"depth-pyramid",size:{width:n,height:s},format:"r32float",usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING,mipLevelCount:c})}function D(M){const S={texture:M,view:M.createView(),sampler:t,width:n,height:s,_sampleType:"float"};return rt(S),S}let p=l(),y=D(p),_,u=[],f=null,h=null;function w(){_=p.createView({baseMipLevel:0,mipLevelCount:1}),u=[];for(let M=1;M<c;M++){const S=p.createView({baseMipLevel:M-1,mipLevelCount:1}),R=p.createView({baseMipLevel:M,mipLevelCount:1});u.push({dst:R,bindGroup:I.createBindGroup({layout:o,entries:[{binding:0,resource:S}]})})}f=null,h=null}return w(),{get texture(){return y},get mipCount(){return c},build(M,S){const R=S??I.createCommandEncoder();(f===null||h!==M)&&(f=I.createBindGroup({layout:i,entries:[{binding:0,resource:M.view}]}),h=M);const N=R.beginRenderPass({label:"depth-pyramid-copy",colorAttachments:[{view:_,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});N.setPipeline(r),N.setBindGroup(0,f),N.draw(3),N.end();for(const F of u){const G=R.beginRenderPass({label:"depth-pyramid-reduce",colorAttachments:[{view:F.dst,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});G.setPipeline(E),G.setBindGroup(0,F.bindGroup),G.draw(3),G.end()}S||I.queue.submit([R.finish()])},resize(M,S){const R=Math.max(1,M|0),N=Math.max(1,S|0);if(R===n&&N===s)return;n=R,s=N,c=W6(n,s);const F=y;p=l(),y=D(p),w(),lC(F)},dispose(){lC(y)}}}function YoA(A,g,I){const{pyramid:e,source:t}=I;return{name:"depth-pyramid",engine:A,scene:g,_passes:[],record(){},execute(){const i=t();return i?(e.build(i,A._currentEncoder),e.mipCount):0},dispose(){e.dispose()}}}function z6(A,g,I){let e=null;return{name:A.name??"image-processing",engine:g,scene:I,_passes:[],record(){Z6(e),e=JoA(g,A.source)},execute(){if(!e)return 0;const i=I.imageProcessing,o=new X([i.exposure,i.contrast,i.toneMappingEnabled===!0?1:0,0]);g._device.queue.writeBuffer(e.params,0,o);const Q=g._currentEncoder.beginRenderPass({colorAttachments:[{view:g.scRT._colorView,loadOp:"clear",storeOp:"store",clearValue:I.clearColor}]});return Q.setPipeline(e.pipeline),Q.setBindGroup(0,e.bindGroup),Q.draw(3),Q.end(),1},dispose(){Z6(e),e=null,this._passes.length=0}}}function JoA(A,g){const I=voA(g);if(!I)throw new Error("Image processing source has no color texture");const e=A._device,i=(I.sampleCount??1)>1,o=e.createBuffer({size:16,usage:SA.UNIFORM|SA.COPY_DST}),Q=e.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,buffer:{type:"uniform"}},{binding:1,visibility:NA.FRAGMENT,texture:{sampleType:i?"unfilterable-float":"float",multisampled:i}}]}),r="struct P{e:f32,c:f32,t:f32,p:f32}@group(0)@binding(0)var<uniform>p:P;@vertex fn vs(@builtin(vertex_index)i:u32)->@builtin(position)vec4f{var a=array<vec2f,3>(vec2f(-1,-3),vec2f(3,1),vec2f(-1,1));return vec4f(a[i],0,1);}fn ip(r:vec4f)->vec4f{var c=r.rgb*p.e;if(p.t>0.5){c=1.0-exp2(-1.590579*c);}c=clamp(pow(max(c,vec3f(0)),vec3f(1/2.2)),vec3f(0),vec3f(1));let h=c*c*(3.0-2.0*c);if(p.c<1.0){c=mix(vec3f(0.5),c,p.c);}else{c=mix(c,h,p.c-1.0);}return vec4f(max(c,vec3f(0)),r.a);}",E=i?"@group(0)@binding(1)var s:texture_multisampled_2d<f32>;":"@group(0)@binding(1)var s:texture_2d<f32>;",n=i?"@fragment fn fs(@builtin(position)q:vec4f)->@location(0)vec4f{let d=textureDimensions(s);let px=clamp(vec2i(q.xy),vec2i(0),vec2i(d)-1);let n=textureNumSamples(s);var c=vec4f(0);for(var i=0u;i<n;i++){c+=ip(textureLoad(s,px,i));}return c/f32(n);}":"@fragment fn fs(@builtin(position)q:vec4f)->@location(0)vec4f{let d=textureDimensions(s);return ip(textureLoad(s,clamp(vec2i(q.xy),vec2i(0),vec2i(d)-1),0));}",s=e.createShaderModule({code:`${r}${E}${n}`}),c=e.createRenderPipeline({layout:e.createPipelineLayout({bindGroupLayouts:[Q]}),vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:A.format}]},primitive:{topology:"triangle-list"}}),l=e.createBindGroup({layout:Q,entries:[{binding:0,resource:{buffer:o}},{binding:1,resource:I.createView()}]});return{pipeline:c,bindGroup:l,params:o}}function voA(A){const g=typeof A=="function"?A():A;return g?"_colorTexture"in g?g._colorTexture:g.texture:null}function Z6(A){A?.params.destroy()}const HoA={magFilter:"nearest",minFilter:"nearest"},ToA={magFilter:"linear",minFilter:"linear"},xoA={magFilter:"linear",minFilter:"linear",mipmapFilter:"linear"};function X6(A){return Pe(A,HoA)}function m1(A){return Pe(A,ToA)}function yF(A){return Pe(A,xoA)}const qoA="struct V{@builtin(position)p:vec4f,@location(0)u:vec2f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{var pos=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));var uv=array<vec2f,3>(vec2f(0,1),vec2f(2,1),vec2f(0,-1));return V(vec4f(pos[i],0,1),uv[i]);}";function PoA(A){return`@group(0)@binding(0)var t:texture_2d<f32>;@group(0)@binding(1)var s:sampler;@fragment fn fs(v:V)->@location(0)vec4f{return textureSampleLevel(t,s,v.u,${A.toFixed(1)});}`}const OoA="@group(0)@binding(0)var t:texture_multisampled_2d<f32>;@fragment fn fs(v:V)->@location(0)vec4f{let d=vec2i(textureDimensions(t));let q=v.u*vec2f(d)-.5;let p0=vec2i(floor(q));let fr=fract(q);let dmax=d-vec2i(1);let p00=clamp(p0,vec2i(0),dmax);let p10=clamp(p0+vec2i(1,0),vec2i(0),dmax);let p01=clamp(p0+vec2i(0,1),vec2i(0),dmax);let p11=clamp(p0+vec2i(1,1),vec2i(0),dmax);let n=textureNumSamples(t);var c00=vec4f(0);var c10=vec4f(0);var c01=vec4f(0);var c11=vec4f(0);for(var i=0u;i<n;i++){c00+=textureLoad(t,p00,i);c10+=textureLoad(t,p10,i);c01+=textureLoad(t,p01,i);c11+=textureLoad(t,p11,i);}let inv=1./f32(n);c00*=inv;c10*=inv;c01*=inv;c11*=inv;return mix(mix(c00,c10,fr.x),mix(c01,c11,fr.x),fr.y);}";let $6=null,_F=null,uF=null,G3=null,F3=null;function joA(A){$6!==A&&($6=A,_F=null,uF=null,G3=new Map,F3=new Map)}function VoA(A,g,I){const e=g,t=I;!A.targetTexture&&!A.resolveTexture&&U(79,A.name??"copy-to-texture");const i={view:void 0,loadOp:A.viewport!==void 0||A.resolveTexture&&!A.targetTexture?"load":"clear",storeOp:"store"},o={name:A.name??"copy-to-texture",engine:e,scene:t,_passes:[],sourceTexture:A.sourceTexture,targetTexture:A.targetTexture,ownsTargetTexture:A.ownsTargetTexture===!0,resolveTexture:A.resolveTexture,viewport:A.viewport,lodLevel:A.lodLevel??0,get outputTexture(){return this.resolveTexture??this.targetTexture},_ownedTarget:null,_fast:null,_blit:null,_resolve:null,_colorAttachment:i,_renderPassDescriptor:{label:A.name??"copy-to-texture",colorAttachments:[i]},record(){o._fast=null,o._blit=null,o._resolve=null;const Q=o.sourceTexture;Q===e.scRT&&U(80,o.name),Q._colorTexture||U(81,o.name);const r=n=>!n._colorTexture;if(o._ownedTarget&&(!o.ownsTargetTexture||o._ownedTarget!==o.targetTexture)&&(Se(o._ownedTarget),o._ownedTarget=null),o.targetTexture&&(o.ownsTargetTexture?(Kt(o.targetTexture,e),o._ownedTarget=o.targetTexture):r(o.targetTexture)&&Kt(o.targetTexture,e)),o.resolveTexture&&r(o.resolveTexture)&&Kt(o.resolveTexture,e),o.resolveTexture&&!o.targetTexture){WoA(o,Q,o.resolveTexture,e);return}const E=o.targetTexture;zoA(o,Q,E,e)||ZoA(o,Q,E,e)},execute(){const Q=o._fast;if(Q)return e._currentEncoder.copyTextureToTexture(Q._source,Q._target,Q._size),0;const r=o._resolve;if(r)return r._swapAsResolve&&(i.resolveTarget=e.scRT._colorView),e._currentEncoder.beginRenderPass(o._renderPassDescriptor).end(),0;const E=o._blit;E._swapAsView&&(i.view=e.scRT._colorView),E._swapAsResolve&&(i.resolveTarget=e.scRT._colorView);const n=e._currentEncoder.beginRenderPass(o._renderPassDescriptor),s=E._viewport;return s&&(n.setViewport(s.x,s.y,s.w,s.h,0,1),n.setScissorRect(s.x,s.y,s.w,s.h)),n.setPipeline(E._pipeline),n.setBindGroup(0,E._bindGroup),n.draw(3),n.end(),1},dispose(){o._passes.length=0,Se(o._ownedTarget),o.ownsTargetTexture&&o.targetTexture!==o._ownedTarget&&Se(o.targetTexture),o._ownedTarget=null,o._fast=null,o._blit=null,o._resolve=null}};return o}function WoA(A,g,I,e){const t=g._descriptor,i=I._descriptor,o=t.samples??1;o<2&&U(82,A.name,o),(i.samples??1)!==1&&U(83,A.name,i.samples);const Q=I===e.scRT;!Q&&(g._width!==I._width||g._height!==I._height)&&U(84,A.name,g._width,g._height,I._width,I._height),A._colorAttachment.view=g._colorView,Q||(A._colorAttachment.resolveTarget=I._colorView),A._resolve={_swapAsResolve:Q}}function zoA(A,g,I,e){if(A.viewport!==void 0||A.resolveTexture)return!1;const t=I._colorTexture;if(I===e.scRT||!t)return!1;const i=g._colorTexture;if(!i||(i.usage&dA.COPY_SRC)===0||(t.usage&dA.COPY_DST)===0)return!1;const o=g._descriptor,Q=I._descriptor,r=o.format,E=Q.format;if(!r||r!==E)return!1;const n=o.samples??1,s=Q.samples??1;if(n!==1||s!==1)return!1;const c=A.lodLevel;if(c>=i.mipLevelCount)return!1;const l=Math.max(1,g._width>>c),D=Math.max(1,g._height>>c);return l!==I._width||D!==I._height?!1:(A._fast={_source:{texture:i,mipLevel:c},_target:{texture:t},_size:{width:l,height:D}},!0)}function ZoA(A,g,I,e){joA(e._device);const t=$oA(I),i=I._descriptor.samples??1,o=(g._descriptor.samples??1)>1,Q=XoA(e,t,i,o,A.lodLevel),r=o?uF:_F,E=o?[{binding:0,resource:g._colorView}]:[{binding:0,resource:g._colorView},{binding:1,resource:A.lodLevel>0?yF(e):m1(e)}],n=e._device.createBindGroup({label:`${A.name}-bg`,layout:r,entries:E}),s=I===e.scRT,c=s&&i===1;let l=!1;if(A.resolveTexture){i<2&&U(85,A.name,i);const y=A.resolveTexture._descriptor;(y.samples??1)!==1&&U(86,A.name,y.samples),y.format!==I._descriptor.format&&U(87,A.name,y.format,I._descriptor.format),A.resolveTexture===e.scRT?l=!0:A._colorAttachment.resolveTarget=A.resolveTexture._colorView}else s&&i>1&&(l=!0);c||(A._colorAttachment.view=I._colorView),!l&&!A.resolveTexture&&(A._colorAttachment.resolveTarget=void 0);let D=null;const p=A.viewport;if(p){const y=I._width,_=I._height,u=Math.floor(p.x*y),f=Math.floor((p.x+p.width)*y)-u,h=Math.floor(p.y*_),w=Math.floor((p.y+p.height)*_)-h;D={x:u,y:_-h-w,w:f,h:w}}A._blit={_pipeline:Q,_bindGroup:n,_viewport:D,_swapAsView:c,_swapAsResolve:l}}function XoA(A,g,I,e,t){const i=A._device,o=`${g}|t${I}|${e?"m":"s"}|l${t}`;let Q=G3.get(o);if(Q)return Q;const r=e?"msaa":`s|l${t}`;let E=F3.get(r);if(!E){const s=e?OoA:PoA(t);E=i.createShaderModule({code:`${qoA} ${s}`,label:`copy-to-texture-${r}`}),F3.set(r,E)}let n;return e?(uF??=i.createBindGroupLayout({label:"copy-to-texture-msaa-bgl",entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"unfilterable-float",multisampled:!0}}]}),n=uF):(_F??=i.createBindGroupLayout({label:"copy-to-texture-bgl",entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:NA.FRAGMENT,sampler:{type:"filtering"}}]}),n=_F),Q=i.createRenderPipeline({label:`copy-to-texture-${o}`,layout:i.createPipelineLayout({label:`copy-to-texture-layout-${o}`,bindGroupLayouts:[n]}),vertex:{module:E,entryPoint:"vs"},fragment:{module:E,entryPoint:"fs",targets:[{format:g}]},primitive:{topology:"triangle-list"},multisample:{count:I}}),G3.set(o,Q),Q}function $oA(A){const g=A._descriptor.format;return g||U(88),g}const ABA="struct V{@builtin(position)p:vec4f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{var pos=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));return V(vec4f(pos[i],0,1));}",gBA="@group(0)@binding(0)var src:texture_depth_multisampled_2d;@fragment fn fs(v:V)->@builtin(frag_depth)f32{return textureLoad(src,vec2i(v.p.xy),0);}";let Av=null,hF=null,m3=null;function IBA(A,g){const I=A._device;Av!==I&&(Av=I,hF=null,m3=new Map);const e=m3.get(g);if(e)return e;hF??=I.createBindGroupLayout({label:"depth-resolve-bgl",entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"depth",multisampled:!0}}]});const t=I.createShaderModule({code:`${ABA} ${gBA}`,label:"depth-resolve"}),i=I.createRenderPipeline({label:`depth-resolve-${g}`,layout:I.createPipelineLayout({label:"depth-resolve-layout",bindGroupLayouts:[hF]}),vertex:{module:t,entryPoint:"vs"},fragment:{module:t,entryPoint:"fs",targets:[]},primitive:{topology:"triangle-list"},depthStencil:{format:g,depthWriteEnabled:!0,depthCompare:"always"}});return m3.set(g,i),i}function eBA(A,g,I){const e=g,t={view:void 0,depthClearValue:0,depthLoadOp:"clear",depthStoreOp:"store"},i={label:A.name??"depth-resolve",colorAttachments:[],depthStencilAttachment:t};let o=null,Q=null,r=null,E=null;const n=()=>{const s=A.sourceTexture,c=A.targetTexture;if(s._depthTexture||U(89,A.name),(s._descriptor.samples??1)<2&&U(90,A.name),(!c._depthTexture||c._width!==(s._width||0)||c._height!==(s._height||0))&&(Kt(c,e),c._width!==s._width||c._height!==s._height))throw new Error(`DepthResolveTask "${A.name}": targetTexture size ${c._width}\xD7${c._height} must match sourceTexture size ${s._width}\xD7${s._height} (size the target's descriptor like the source, e.g. both \`size: surface\`).`);const l=c._descriptor.dFormat;l||U(91,A.name),o=IBA(e,l);const D=s._depthTexture.createView({aspect:"depth-only"});Q=e._device.createBindGroup({label:`${A.name??"depth-resolve"}-bg`,layout:hF,entries:[{binding:0,resource:D}]}),t.view=c._depthView,r=s._depthTexture,E=c._depthTexture};return{name:A.name??"depth-resolve",engine:e,scene:I,_passes:[],record(){n()},execute(){(A.sourceTexture._depthTexture!==r||A.targetTexture._depthTexture!==E)&&n();const s=e._currentEncoder.beginRenderPass(i);return s.setPipeline(o),s.setBindGroup(0,Q),s.draw(3),s.end(),1},dispose(){o=null,Q=null,r=null,E=null}}}function tBA(A){return{_descriptor:A,_colorTextures:[],_colorViews:[],_resolveColorTextures:[],_resolveColorViews:[],_depthTexture:null,_depthView:null,_width:0,_height:0}}function CBA(A,g){gv(A);const I=A._descriptor,{width:e,height:t}=BBA(I);A._width=e,A._height=t;const i=g._device,o=I.colorFormats,Q=I.sampleCount,r=Q>1,E=I.label,n={width:e,height:t};for(let s=0;s<o.length;s++){const c=o[s],l=i.createTexture({label:E,size:n,format:c,sampleCount:Q,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING|dA.COPY_SRC});if(A._colorTextures.push(l),A._colorViews.push(l.createView()),r){const D=i.createTexture({label:E,size:n,format:c,sampleCount:1,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING|dA.COPY_SRC});A._resolveColorTextures.push(D),A._resolveColorViews.push(D.createView())}}I.depthStencilFormat&&(A._depthTexture=i.createTexture({label:E,size:n,format:I.depthStencilFormat,sampleCount:Q,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING}),A._depthView=A._depthTexture.createView())}function gv(A){for(const g of A._colorTextures)g.destroy();A._colorTextures.length=0,A._colorViews.length=0;for(const g of A._resolveColorTextures)g.destroy();A._resolveColorTextures.length=0,A._resolveColorViews.length=0,A._depthTexture&&(A._depthTexture.destroy(),A._depthTexture=null,A._depthView=null),A._width=0,A._height=0}function iBA(A,g){return A._resolveColorViews[g]??A._colorViews[g]}function oBA(A,g){return A._resolveColorTextures[g]??A._colorTextures[g]}function BBA(A){const g=A.size;if("canvas"in g){const I=g.canvas;return{width:I.width,height:I.height}}return g}function $1(A,g){const I=AC(A);return Object.create(I,{source:{value:I,enumerable:!0},_renderFeatures:{value:{features:g.features,features2:g.features2},writable:!0,enumerable:!0,configurable:!0}})}function Iv(A){const g=A;return!!g.source&&!!g._renderFeatures}function AC(A){return Iv(A)?A.source:A}var zg=(A=>(A[A.IRRADIANCE=0]="IRRADIANCE",A[A.WORLD_POSITION=1]="WORLD_POSITION",A[A.LOCAL_POSITION=2]="LOCAL_POSITION",A[A.REFLECTIVITY=3]="REFLECTIVITY",A[A.VIEW_DEPTH=4]="VIEW_DEPTH",A[A.NORMALIZED_VIEW_DEPTH=5]="NORMALIZED_VIEW_DEPTH",A[A.SCREENSPACE_DEPTH=6]="SCREENSPACE_DEPTH",A[A.VIEW_NORMAL=7]="VIEW_NORMAL",A[A.WORLD_NORMAL=8]="WORLD_NORMAL",A[A.ALBEDO=9]="ALBEDO",A[A.LINEAR_VELOCITY=10]="LINEAR_VELOCITY",A))(zg||{});const kC={r:0,g:0,b:0,a:0},QBA={r:1,g:1,b:1,a:1},ev=[{name:"Irradiance",defaultFormat:"rgba16float",clearValue:kC},{name:"WorldPosition",defaultFormat:"rgba16float",clearValue:kC},{name:"LocalPosition",defaultFormat:"rgba16float",clearValue:kC},{name:"Reflectivity",defaultFormat:"rgba8unorm",clearValue:kC},{name:"ViewDepth",defaultFormat:"r32float",clearValue:kC},{name:"NormalizedViewDepth",defaultFormat:"r16float",clearValue:QBA},{name:"ScreenspaceDepth",defaultFormat:"r16float",clearValue:kC},{name:"ViewNormal",defaultFormat:"rgba16float",clearValue:kC},{name:"WorldNormal",defaultFormat:"rgba16float",clearValue:kC},{name:"Albedo",defaultFormat:"rgba8unorm",clearValue:kC},{name:"LinearVelocity",defaultFormat:"rgba16float",clearValue:kC}];function rBA(A,g,I){const e=g,t=I;A.textureDescriptions.length===0&&U(95),A.textureDescriptions.length>8&&U(96,A.textureDescriptions.length);const i=A.textureDescriptions.map((m,K)=>{const k=ev[m.type];return k||U(97,m.type),{_type:m.type,_index:K,_format:m.format??k.defaultFormat,_clearValue:m.clearValue??k.clearValue}}),o=i.map(m=>m._type),Q=o.includes(zg.LINEAR_VELOCITY),r=Q||o.includes(zg.NORMALIZED_VIEW_DEPTH),E=A.samples??1,n=A.size??t.surface;if(A.depthTexture){const m=A.depthTexture._descriptor.samples??1;m!==E&&U(98,m,E)}if(A.targetTexture){const m=A.targetTexture._descriptor.samples??1;m!==E&&U(99,m,E),A.targetTexture._descriptor.format||U(100)}const s=i.map(m=>m._format),c=tBA({label:A.name??"geometry-renderer",colorFormats:s,depthStencilFormat:A.depthTexture?void 0:"depth32float",sampleCount:E,size:n}),l=[],D={};for(let m=0;m<ev.length;m++)D[m]=null;for(const m of i){const K=fBA(c,m);l.push(K),D[m._type]=K}const p=A.depthTexture?null:dBA(c,E),y=A.depthTexture??p,_=Mt(e),u=jt(e,xR),f=VQ(e,t)._buffer,h=e._device.createBindGroup({layout:_,entries:[{binding:0,resource:{buffer:u}},{binding:1,resource:{buffer:f}}]}),w=r?jt(e,80):null,M=r?new X(20):null,S=i.map(()=>({view:void 0,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}));if(A.targetTexture){const m=A.targetTextureClearColor!==void 0;S.push({view:void 0,loadOp:m?"clear":"load",storeOp:"store",...m?{clearValue:A.targetTextureClearColor}:{}})}const R={label:A.name??"geometry-renderer",colorAttachments:S},N=s.slice();A.targetTexture&&N.push(A.targetTexture._descriptor.format);const F={_colorFormat:N.join(),_colorFormats:N,_depthStencilFormat:(A.depthTexture?A.depthTexture._descriptor.dFormat:c._descriptor.depthStencilFormat)??"depth32float",_depthCompare:"greater-equal",_sampleCount:E},G={name:A.name??"geometry-renderer",engine:e,scene:t,_passes:[],_mrt:c,outputTexture:A.targetTexture,geometryDepthTexture:y,geometryIrradianceTexture:D[zg.IRRADIANCE],geometryWorldPositionTexture:D[zg.WORLD_POSITION],geometryLocalPositionTexture:D[zg.LOCAL_POSITION],geometryReflectivityTexture:D[zg.REFLECTIVITY],geometryViewDepthTexture:D[zg.VIEW_DEPTH],geometryNormalizedViewDepthTexture:D[zg.NORMALIZED_VIEW_DEPTH],geometryScreenspaceDepthTexture:D[zg.SCREENSPACE_DEPTH],geometryViewNormalTexture:D[zg.VIEW_NORMAL],geometryWorldNormalTexture:D[zg.WORLD_NORMAL],geometryAlbedoTexture:D[zg.ALBEDO],geometryLinearVelocityTexture:D[zg.LINEAR_VELOCITY],excludeFromVelocity(m){G._excludedFromVelocity.add(m)},includeInVelocity(m){G._excludedFromVelocity.delete(m)},_attachments:i,_views:new Map,_bound:[],_wrapperTargets:l,_ownedDepthWrapper:p,_sceneUBO:u,_sceneBG:h,_sceneData:new X(xR/4),_paramsUBO:w,_paramsData:M,_previousViewProjection:new X(16),_viewProjectionScratch:new X(16),_renderPassDescriptor:R,_colorAttachments:S,_depthAttachment:null,_removedMeshes:null,_boundVer:-1,_ownLightsUBO:null,_ownLightsScratch:null,_ownedDepth:!1,_excludedFromVelocity:new Set,_needsVelocity:Q,_needsParams:r,_signature:F,_createStandardGeometryView:null,_computeStandardFeatures:null,_createPbrGeometryView:null,_computePbrFeatures:null,_createNodeGeometryView:null,_removeMesh(m){(G._removedMeshes??=new WeakSet).add(m)},async _preload(){const m=A.meshes??t.meshes;let K=!1,k=!1,L=!1;for(const q of m){const CA=uBA(q.material);CA==="standard"?K=!0:CA==="pbr"?k=!0:CA==="node"&&(L=!0)}const H=[];K&&H.push((async()=>{const[q,CA]=await Promise.all([Promise.resolve().then(()=>iYA),Promise.resolve().then(()=>PcA)]);G._createStandardGeometryView=q.createStandardGeometryMaterialView,G._computeStandardFeatures=CA._computeStandardMaterialFeatures,await q.preloadStandardGeometryFeatures(m,G._needsVelocity)})()),k&&H.push((async()=>{const[q,CA]=await Promise.all([Promise.resolve().then(()=>RYA),Promise.resolve().then(()=>B0A)]);G._createPbrGeometryView=q.createPbrGeometryMaterialView,G._computePbrFeatures=CA._computePbrMaterialFeatures})()),L&&H.push((async()=>{const q=await Promise.resolve().then(()=>TYA);G._createNodeGeometryView=q.createNodeGeometryMaterialView})()),await Promise.all(H)},record(){EBA(G,A,e,t)},execute(){return DBA(G,e,t,A)},dispose(){_BA(G,e,t)}};return G}function EBA(A,g,I,e){CBA(A._mrt,I),A._ownedDepth=!g.depthTexture,g.targetTexture&&!g.targetTexture._colorTexture&&Kt(g.targetTexture,I);const t=A._mrt;for(const o of A._attachments){const Q=A._wrapperTargets[o._index];Q._colorTexture=oBA(t,o._index),Q._colorView=iBA(t,o._index),Q._width=t._width,Q._height=t._height}A._ownedDepthWrapper&&(A._ownedDepthWrapper._depthTexture=t._depthTexture,A._ownedDepthWrapper._depthView=t._depthView,A._ownedDepthWrapper._width=t._width,A._ownedDepthWrapper._height=t._height);const i=aBA(A,I,e,g);A._sceneBG=I._device.createBindGroup({layout:Mt(I),entries:[{binding:0,resource:{buffer:A._sceneUBO}},{binding:1,resource:{buffer:i}}]}),tv(A,g,I,e),sBA(A,g)}function tv(A,g,I,e){const t=A._bound,i=[...A._views.values()],o=[],Q=new Map,r=A._removedMeshes,E=g.meshes??e.meshes,n=A._attachments.map(s=>s._type);try{for(const s of E){if(r?.has(s)){if(!e.meshes.includes(s))continue;r.delete(s)}const c=hBA(A,s.material);if(!c)continue;const l=nBA(A,Q,c,n,g),p=l._buildGroup._rebuildSingle(e,s,l).bind(I,A._signature);o.push({_mesh:s,_binding:p,_view:l})}}catch(s){throw b3(I,e,o,[...Q.values()]),s}o.sort((s,c)=>(Cv(s._binding.renderable)?1:0)-(Cv(c._binding.renderable)?1:0)),A._bound=o,A._views=Q,A._boundVer=e._renderableVersion,(t.length>0||i.length>0)&&b3(I,e,t,i)}function b3(A,g,I,e){for(const t of I){const i=t._binding.renderable._geometryDispose;if(!i)continue;const o=g._meshAuxDisposables.get(t._mesh);if(!o)continue;const Q=o.indexOf(i);Q>=0&&o.splice(Q,1),o.length===0&&g._meshAuxDisposables.delete(t._mesh)}G1(A,()=>{for(const t of I)t._binding.renderable._geometryDispose?.();for(const t of e)t._disposeGeometryResources?.()})}function nBA(A,g,I,e,t){const i=g.get(I._mat);if(i)return i;const o={attachments:e,emitColor:t.targetTexture!==void 0,gpUBO:A._paramsUBO,reverseCulling:t.reverseCulling,camera:t.camera??null},Q=I._family==="standard"?A._createStandardGeometryView(I._mat,{...o,velocityExclusions:A._excludedFromVelocity}):I._family==="pbr"?A._createPbrGeometryView(I._mat,o):A._createNodeGeometryView(I._mat,o);return g.set(I._mat,Q),Q}function Cv(A){return A.isTransparent===!0}function sBA(A,g){const I=A._mrt;for(const o of A._attachments){const Q=A._colorAttachments[o._index];Q.view=I._colorViews[o._index],Q.resolveTarget=I._resolveColorViews[o._index]??void 0,Q.loadOp="clear",Q.storeOp="store",Q.clearValue=o._clearValue}if(g.targetTexture){const o=A._colorAttachments[A._attachments.length];o.view=g.targetTexture._colorView,o.resolveTarget=void 0}let e,t,i;g.depthTexture?(e=g.depthTexture._depthView,t=g.depthTexture._descriptor.dFormat,i=g.depthTexture._descriptor._depthClearValue??0):(e=I._depthView,t=I._descriptor.depthStencilFormat,i=0),A._depthAttachment=e?{view:e,depthClearValue:i,depthLoadOp:"clear",depthStoreOp:"store",...t?.includes("stencil")?{stencilClearValue:0,stencilLoadOp:"clear",stencilStoreOp:"store"}:{}}:null,A._renderPassDescriptor.colorAttachments=A._colorAttachments,A._renderPassDescriptor.depthStencilAttachment=A._depthAttachment??void 0}function iv(A,g){return!!A.useFloatingOrigin&&!!g.camera}function aBA(A,g,I,e){return iv(g,e)?(A._ownLightsUBO||(A._ownLightsScratch=new X(d3()/4),A._ownLightsUBO=jt(g,d3())),A._ownLightsUBO):VQ(g,I)._buffer}function cBA(A,g,I,e){const t=A._ownLightsScratch;!t||!iv(g,e)||(KiA(g,t,{camera:e.camera,lights:I.lights}),g._device.queue.writeBuffer(A._ownLightsUBO,0,t))}function lBA(A,g,I){A[28]=0,A[29]=0,A[30]=0;const e=li(g,I);Oe(A,0,e,0,A,16)}function DBA(A,g,I,e){const t=e.camera??I.camera;if(!t)return 0;const i=A._mrt;if(i._width===0||i._height===0)return 0;I._renderableVersion!==A._boundVer&&tv(A,e,g,I);const o=i._width/i._height;pBA(A,g,I,t,o),cBA(A,g,I,e),A._needsParams&&yBA(A,g,t);const Q={targetWidth:i._width,targetHeight:i._height,_camera:t};for(const s of A._bound)s._binding.update?.(Q);const r=g._currentEncoder.beginRenderPass(A._renderPassDescriptor);r.setBindGroup(0,A._sceneBG);let E=null,n=0;for(const s of A._bound){if(s._mesh.visible===!1)continue;const c=s._binding.pipeline;c!==E&&(r.setPipeline(c),E=c),n+=s._binding.draw(r,g)}return r.end(),A._needsVelocity&&A._previousViewProjection.set(A._viewProjectionScratch),n}function pBA(A,g,I,e,t){const i=A._sceneData;y6(i,g,I,e,t);const o=I._sceneUboContributors;if(o)for(const Q of o)Q(i,I);g.useFloatingOrigin&&lBA(i,e,t),A._viewProjectionScratch.set(i.subarray(0,16)),g._device.queue.writeBuffer(A._sceneUBO,0,i)}function yBA(A,g,I){const e=A._paramsData;e.set(A._previousViewProjection,0),e[16]=I.nearPlane,e[17]=I.farPlane,e[18]=0,e[19]=0,g._device.queue.writeBuffer(A._paramsUBO,0,e)}function _BA(A,g,I){(A._bound.length>0||A._views.size>0)&&b3(g,I,[...A._bound],[...A._views.values()]),A._passes.length=0,A._bound.length=0,A._views.clear(),gv(A._mrt),A._ownedDepth=!1,A._sceneUBO.destroy(),A._paramsUBO?.destroy(),A._ownLightsUBO?.destroy(),A._ownLightsUBO=null,A._ownLightsScratch=null,A._wrapperTargets.length=0}function uBA(A){if(!A)return null;const g=AC(A)._buildGroup?._materialFamily;return g==="standard"||g==="pbr"||g==="node"?g:null}function hBA(A,g){if(!g)return null;const I=AC(g),e=I._buildGroup;if(!e)return null;if(e._materialFamily==="standard"){const t=I;return t._renderFeatures||(t._renderFeatures={features:A._computeStandardFeatures(t)}),{_mat:t,_family:"standard"}}if(e._materialFamily==="pbr"){const t=I;return t._renderFeatures||(t._renderFeatures=A._computePbrFeatures(t)),{_mat:t,_family:"pbr"}}return e._materialFamily==="node"?{_mat:I,_family:"node"}:null}function fBA(A,g){const I=A._descriptor;return{_descriptor:{lbl:`${I.label??"geometry"}.${g._index}`,format:g._format,samples:1,size:I.size},_colorTexture:null,_colorView:null,_depthTexture:null,_depthView:null,_width:0,_height:0,_eager:!0}}function dBA(A,g){const I=A._descriptor;return{_descriptor:{lbl:`${I.label??"geometry"}.depth`,dFormat:I.depthStencilFormat,samples:g,size:I.size},_colorTexture:null,_colorView:null,_depthTexture:null,_depthView:null,_width:0,_height:0,_eager:!0}}function wBA(A,g){"canvas"in g.size&&U(571);const I=g.size,e=wt(g);if(Kt(e,A),e._eager=!0,!e._colorTexture||!e._colorView){e._depthTexture||U(572);const i={texture:e._depthTexture,view:e._depthTexture.createView({aspect:"depth-only"}),sampler:X6(A),width:I.width,height:I.height,invertY:!1,_sampleType:"depth"};return{rt:e,texture:i}}const t={texture:e._colorTexture,view:e._colorView,sampler:m1(A),width:I.width,height:I.height,invertY:!0};return{rt:e,texture:t}}const MBA={magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat",addressModeW:"repeat",maxAnisotropy:4};function ov(A){return Pe(A,MBA)}const SBA="@group(0)@binding(0)var t:texture_2d<f32>;@group(0)@binding(1)var s:sampler;struct V{@builtin(position)p:vec4f,@location(0)u:vec2f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return V(vec4f(p,0,1),p*vec2f(.5,-.5)+.5);}@fragment fn fs(v:V)->@location(0)vec4f{return textureSample(t,s,v.u);}";let WR=null,fF=null,K3=null,dF=null,k3=null;function RBA(){WR?.clear(),WR=null,fF=null,K3=null,dF=null,k3=null}function NBA(A){const g=A._device;g!==k3&&(RBA(),k3=g),fF??=g.createShaderModule({code:SBA}),K3??=m1(A),dF??=g.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:NA.FRAGMENT,sampler:{}}]})}function GBA(A,g){const I=A._device;NBA(A),WR??=new Map;let e=WR.get(g);return e||(e=I.createRenderPipeline({layout:I.createPipelineLayout({bindGroupLayouts:[dF]}),vertex:{module:fF,entryPoint:"vs"},fragment:{module:fF,entryPoint:"fs",targets:[{format:g}]},primitive:{topology:"triangle-list"}}),WR.set(g,e)),e}function ZQ(A,g,I){const e=A._device,t=e.createCommandEncoder();wF(A,g,t,I),e.queue.submit([t.finish()])}function wF(A,g,I,e){if(g.mipLevelCount<=1)return;const t=A._device,i=GBA(A,g.format),o=e!=null?{dimension:"2d",baseArrayLayer:e,arrayLayerCount:1}:{};for(let Q=1;Q<g.mipLevelCount;Q++){const r=g.createView({baseMipLevel:Q-1,mipLevelCount:1,...o}),E=g.createView({baseMipLevel:Q,mipLevelCount:1,...o}),n=t.createBindGroup({layout:dF,entries:[{binding:0,resource:r},{binding:1,resource:K3}]}),s=I.beginRenderPass({colorAttachments:[{view:E,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});s.setPipeline(i),s.setBindGroup(0,n),s.draw(3),s.end()}}const zR=Object.freeze(Object.defineProperty({__proto__:null,generateMipmaps:ZQ,recordMipmaps:wF},Symbol.toStringTag,{value:"Module"}));function XQ(A,g){return Math.floor(Math.log2(Math.max(A,g)))+1}function FBA(A,g,I){const e=Math.max(A,g);return Math.max(1,Math.floor(Math.log2(e)-I)+1)}let MF=null;function mBA(A){MF=A}const bBA="@group(0)@binding(0)var t:texture_2d<f32>;@group(0)@binding(1)var s:sampler;struct V{@builtin(position)p:vec4f,@location(0)u:vec2f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{var p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));var u=array<vec2f,3>(vec2f(0,1),vec2f(2,1),vec2f(0,-1));return V(vec4f(p[i],0,1),u[i]);}@fragment fn fs(v:V)->@location(0)vec4f{return textureSample(t,s,v.u);}",KBA="@group(0)@binding(0)var t:texture_multisampled_2d<f32>;struct V{@builtin(position)p:vec4f,@location(0)u:vec2f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{var p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));var u=array<vec2f,3>(vec2f(0,1),vec2f(2,1),vec2f(0,-1));return V(vec4f(p[i],0,1),u[i]);}fn l(p:vec2i)->vec4f{let n=textureNumSamples(t);var c=vec4f(0);for(var i=0u;i<n;i++){c+=textureLoad(t,p,i);}return c/f32(n);}@fragment fn fs(v:V)->@location(0)vec4f{let d=vec2i(textureDimensions(t));let q=clamp(v.u*vec2f(d)-.5,vec2f(0),vec2f(d-vec2i(1)));let p=vec2i(floor(q));let f=fract(q);let p1=min(p+vec2i(1),d-vec2i(1));return mix(mix(l(p),l(vec2i(p1.x,p.y)),f.x),mix(l(vec2i(p.x,p1.y)),l(p1),f.x),f.y);}",kBA=4;let ZR=null,SF=null,RF=null,NF=null,GF=null,Bv=null;function Qv(A,g){sv(A),rv(A,g)}function UBA(A,g){const I=A.meshes.flatMap(e=>{const t=e.material;return t?[[t,t._linearImageProcessing,t._renderFeatures]]:[]});return sv(A),[()=>rv(A,g),()=>{for(const[e,t,i]of I)e._linearImageProcessing=t,e._renderFeatures=i}]}function rv(A,g){let I=null;for(const e of A._frameGraph._tasks)if("_renderables"in e){const t=e;Ev(t,g),I=t}I&&!A._frameGraph._tasks.some(e=>e.name==="transmission-image-processing")&&A._frameGraph._tasks.push(z6({name:"transmission-image-processing",source:I._config.rt},g,A))}function Ev(A,g,I){const e=I?.linear!==!1;if(ZBA(A,I),A._config.transmission?.grabDepth){const E=A._preload?.bind(A);A._preload=async()=>{E&&await E(),await Promise.resolve().then(()=>VYA)}}const t={get texture(){return A._targetSignature._transmissionTexture??null},get depthTexture(){return A._targetSignature._transmissionDepthTexture??null}};if(A._executeWithTransmission)return t;e&&LBA(A);let i=null;const o=A.record.bind(A),Q=A.execute?.bind(A),r=A.dispose?.bind(A);return A.record=()=>{av(i),i=vBA(A,g),A._targetSignature._transmissionTexture=i.texture,o(),HBA(i,A,g)},e&&Q&&(A.execute=()=>YBA(A.scene,Q)),A.dispose=()=>{av(i),i=null,r?.()},A._executeWithTransmission=E=>TBA(A,g,i,E),t}function LBA(A){const g=A._config,I=g.rt._descriptor,e=A.scene.surface,t=e.msaaSamples,i=!g.depth,o=wt({lbl:"transmission-linear",format:"rgba16float",dFormat:i?I.dFormat??"depth24plus-stencil8":void 0,_depthClearValue:I._depthClearValue,_depthCompare:I._depthCompare,samples:t,size:e});g.rt=o,g.rst=void 0;const Q=A._targetSignature;Q._colorFormat="rgba16float",Q._depthStencilFormat=g.depth?._descriptor.dFormat??o._descriptor.dFormat,Q._depthCompare=o._descriptor._depthCompare,Q._sampleCount=t,A._ob.length=0,A._lastVersion=-1}function YBA(A,g){const I=A.imageProcessing,e=I.toneMappingEnabled,t=A.clearColor,i=JBA(t,I.exposure,I.contrast,e===!0);I.toneMappingEnabled=-1,A.clearColor=i;try{return g()}finally{A.clearColor=t,I.toneMappingEnabled=e}}function JBA(A,g,I,e){return{r:U3(A.r,g,I,e),g:U3(A.g,g,I,e),b:U3(A.b,g,I,e),a:A.a}}function U3(A,g,I,e){let t=nv(A);if(I<1)t=I>0?nv((t-.5*(1-I))/I):.5;else if(I>1){const i=I-1;let o=0,Q=1;for(let r=0;r<16;r++){const E=(o+Q)*.5,n=E*E*(3-2*E);E+(n-E)*i<t?o=E:Q=E}t=(o+Q)*.5}return t=t**2.2,e&&(t=-Math.log2(Math.max(1-t,1e-6))/1.5905790328979492),g>0?t/g:t}function nv(A){return Math.min(Math.max(A,0),1)}function sv(A){for(const g of A.meshes){const I=g.material;I&&(I._linearImageProcessing=!0,I._renderFeatures=void 0)}}function vBA(A,g){const I=A._config.rt,e=1024,t=1024,i="rgba16float",o=XBA(A._config.transmission,e,t),Q=o>1,r=g._device.createTexture({label:A.name,size:{width:e,height:t},format:i,mipLevelCount:o,usage:dA.RENDER_ATTACHMENT|dA.TEXTURE_BINDING|dA.COPY_DST});return{texture:{texture:r,view:r.createView(),sampler:ov(g),width:e,height:t,invertY:!1},_baseView:r.createView({baseMipLevel:0,mipLevelCount:1}),_sourceWidth:I._width,_sourceHeight:I._height,_sourceTexture:null,_blit:null,_depth:null,_copyCount:zBA(A._config.transmission),_generateMipmaps:Q,_copies:0}}function HBA(A,g,I){const e=g._config.rt;A._sourceWidth=e._width,A._sourceHeight=e._height,A._sourceTexture=e._colorTexture;const t=g._targetSignature._sampleCount,i=g._targetSignature;i._transmissionDepthTexture=null;const o=e._depthTexture;g._config.transmission?.grabDepth&&MF&&o&&e._width>0&&e._height>0&&(A._depth=MF.create(I,o,e._width,e._height,t>1),i._transmissionDepthTexture=A._depth.texture),A._sourceTexture&&(A._blit=PBA(A,t)?OBA(A,I,A._sourceTexture,t>1):null)}function av(A){A?.texture.texture.destroy(),A?._depth?.texture.texture.destroy()}function TBA(A,g,I,e){I._copies=0;const t=A._transparentBindings,i=e>1?A._config.rst?._colorView??null:null;let o=cv(A,i,e,!1),Q=WBA(A,o),r=null,E=null;for(let n=0;n<t.length;n++){const s=t[n];if(s.renderable.mesh?.renderOnTop===!0){(E??=[]).push(s);continue}s.renderable._transmissive===!0&&VBA(I)&&(o.end(),xBA(I,g),o=cv(A,i,e,!0),lv(A,o),r=null);const l=s.renderable.mesh;l&&l.visible===!1||(s.pipeline!==r&&(o.setPipeline(s.pipeline),r=s.pipeline),Q+=s.draw(o,g))}return E&&(Q+=WQ(o,E,g)),o.end(),Q}function xBA(A,g){if(!A._sourceTexture)throw new Error("No transmission source");A._blit?jBA(A,g):g._currentEncoder.copyTextureToTexture({texture:A._sourceTexture},{texture:A.texture.texture},{width:A.texture.width,height:A.texture.height}),A._generateMipmaps&&wF(g,A.texture.texture,g._currentEncoder),A._depth&&MF?.record(g,A._depth),A._copies++}function qBA(A,g,I){const e=A._device;e!==Bv&&(ZR?.clear(),ZR=null,SF=null,RF=null,NF=null,GF=null,Bv=e),I?(RF??=e.createShaderModule({code:KBA}),GF??=e.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"unfilterable-float",multisampled:!0}}]})):(SF??=e.createShaderModule({code:bBA}),NF??=e.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:NA.FRAGMENT,sampler:{}}]})),ZR??=new Map;const t=`${g}:${I?"msaa":""}`;let i=ZR.get(t);if(!i){const o=I?GF:NF;i=e.createRenderPipeline({label:"transmission-copy",layout:e.createPipelineLayout({bindGroupLayouts:[o]}),vertex:{module:I?RF:SF,entryPoint:"vs"},fragment:{module:I?RF:SF,entryPoint:"fs",targets:[{format:g}]},primitive:{topology:"triangle-list"}}),ZR.set(t,i)}return i}function PBA(A,g){return g>1||A._sourceWidth!==A.texture.width||A._sourceHeight!==A.texture.height}function OBA(A,g,I,e){const t=g._device,i=qBA(g,A.texture.texture.format,e),o=t.createBindGroup({layout:e?GF:NF,entries:e?[{binding:0,resource:I.createView()}]:[{binding:0,resource:I.createView()},{binding:1,resource:m1(g)}]});return{_pipeline:i,_bindGroup:o}}function jBA(A,g){const I=A._blit,e=g._currentEncoder.beginRenderPass({colorAttachments:[{view:A._baseView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});e.setPipeline(I._pipeline),e.setBindGroup(0,I._bindGroup),e.draw(3),e.end()}function VBA(A){return A._copyCount===0||A._copies<A._copyCount}function cv(A,g,I,e){const t=A._colorAttachment,i=e||!A._config.clr?"load":"clear";e&&(t.loadOp="load");const o=A._renderPassDescriptor.depthStencilAttachment;return o&&(o.depthLoadOp=i,o.stencilLoadOp&&(o.stencilLoadOp=i)),I>1?t.resolveTarget=g??void 0:t.resolveTarget=void 0,A.engine._currentEncoder.beginRenderPass(A._renderPassDescriptor)}function lv(A,g){const I=A._config,e=I.rt,t=A.scene,o=(I.cam??t.camera)?.viewport;if(o){const Q=e._width,r=e._height,E=Math.floor(o.x*Q),n=Math.floor((1-o.y-o.height)*r),s=Math.ceil((o.x+o.width)*Q)-E,c=Math.ceil((1-o.y)*r)-n;g.setViewport(E,n,s,c,0,1),g.setScissorRect(E,n,s,c)}g.setBindGroup(0,A._sceneBG)}function WBA(A,g){const I=A.engine,e=A._config.rt,t=A.scene,i=A._opaqueBindings,o=A._ob;if(lv(A,g),A._lastVersion!==t._renderableVersion||A._lastVis!==TQ||o.length===0){const r=e._descriptor,E=I._device.createRenderBundleEncoder({colorFormats:r.format?[r.format]:[],depthStencilFormat:r.dFormat,sampleCount:r.samples??1});E.setBindGroup(0,A._sceneBG),WQ(E,i,I),o[0]=E.finish(),A._lastVersion=t._renderableVersion,A._lastVis=TQ}let Q=i.length;return g.executeBundles(o),g.setBindGroup(0,A._sceneBG),Q+=WQ(g,A._directBindings,I),Q}function zBA(A){const g=A?.copyCount??1;return g===1/0?0:Math.max(0,g|0)}function ZBA(A,g){if(!g)return;let I=A._config.transmission,e=!1;const t=(i,o)=>{o!==void 0&&(I={...I,[i]:o},e=!0)};t("copyCount",g.copyCount),t("generateMipmaps",g.generateMipmaps),t("mipLevelCount",g.mipLevelCount),t("grabDepth",g.grabDepth),e&&(A._config.transmission=I)}function XBA(A,g,I){if(A?.generateMipmaps===!1)return 1;const e=Math.floor(Math.log2(Math.max(g,I)))+1,t=FBA(g,I,kBA),i=A?.mipLevelCount;return i===void 0?Math.min(e,t):Math.min(e,Math.max(1,i|0))}const $BA="struct EffectVertexOutput{@builtin(position)position:vec4<f32>,@location(0)uv:vec2<f32>};@vertex fn effectFullscreenVertex(@builtin(vertex_index)vertexIndex:u32)->EffectVertexOutput{var positions=array<vec2<f32>,3>(vec2<f32>(-1.0,-1.0),vec2<f32>(3.0,-1.0),vec2<f32>(-1.0,3.0));let p=positions[vertexIndex];var out:EffectVertexOutput;out.position=vec4<f32>(p,0.0,1.0);out.uv=p*0.5+vec2<f32>(0.5,0.5);return out;}";function AQA(A,g){const I=A,e={name:g.name??"effect-wrapper",options:g,_engine:I,_shader:null,_bindGroupLayout:null,_pipelineLayout:null,_bindGroup:null,_bindGroupDirty:!0,_pipelines:null,_uniforms:[],_textures:[]};return BQA(e),e}function gQA(A,g){const I=A;if(cQA(g)){const e=I._uniforms[0];e||U(30),dv(I,e,g);return}for(const e of Object.keys(g)){const t=hv(I,e);t||U(31,e),dv(I,t,g[e])}}function IQA(A,g,I){const e=A,t=Y3(e,g);t||U(32,String(g)),t.texture=I,e._bindGroupDirty=!0}function eQA(A,g,I){const e=g,t=A.effect,i=A.target;A.clearColor??={r:0,g:0,b:0,a:1};const o=i._descriptor.samples??1,Q={_colorFormat:i._descriptor.format,_sampleCount:o},r={loadOp:"clear",storeOp:"store"},E={name:A.name,_config:A,engine:e,scene:I,_passes:[],_rt:i,_targetSignature:Q,_renderPassDescriptor:{label:A.name,colorAttachments:[r]},_colorAttachment:r,_pipeline:null,_bindGroup:null,record(){Kt(i,e),E._pipeline=yv(t,E._targetSignature),E._bindGroup=L3(t)},execute(){const n=E._pipeline;n||U(33,E.name),E._bindGroup=L3(t),pv(E._colorAttachment,i,void 0,E._config.clear!==!1,E._config.clearColor);const s=e._currentEncoder.beginRenderPass(E._renderPassDescriptor);return s.setPipeline(n),E._bindGroup&&s.setBindGroup(0,E._bindGroup),s.draw(3),s.end(),1},dispose(){E._passes.length=0,Se(E._rt),E._pipeline=null,E._bindGroup=null}};return E}function tQA(A){const g=A;for(const I of g._uniforms)I.buffer.destroy();g._uniforms.length=0,g._textures.length=0,g._pipelines?.clear(),g._pipelines=null,g._shader=null,g._bindGroupLayout=null,g._pipelineLayout=null,g._bindGroup=null,g._bindGroupDirty=!0}function CQA(A,g,I){const e=A.engine,t=g,i=I?.name??g.name,o=I?.clear!==!1,Q=I?.clearColor??{r:0,g:0,b:0,a:1},r=I?.update,E=A.msaaSamples>1,n=E?wt({lbl:`${i}-msaa`,format:A.format,samples:A.msaaSamples,size:A}):A.scRT,s=E?A.scRT:void 0,c={_colorFormat:n._descriptor.format,_sampleCount:n._descriptor.samples??1},l={view:void 0,loadOp:"clear",storeOp:"store"},p={_kind:"effect-renderer",name:i,clearColor:Q,_drawCallsPre:0,_surface:A,_effect:t,_clear:o,_rt:n,_targetSignature:c,_renderPassDescriptor:{label:i,colorAttachments:[l]},_colorAttachment:l,_pipeline:null,_bindGroup:null,_disposed:!1,_update(){r?.(e._currentDelta)},_record(){if(p._disposed)return 0;QQA(p._rt),pv(p._colorAttachment,p._rt,s,p._clear,p.clearColor);const y=p._surface.engine._currentEncoder;if(!y)return 0;const _=p._pipeline;_||U(34,p.name);const u=y.beginRenderPass(p._renderPassDescriptor);return u.setPipeline(_),p._bindGroup&&u.setBindGroup(0,p._bindGroup),u.draw(3),u.end(),1},_resize(){p._disposed||Kt(p._rt,p._surface.engine)}};return p}function iQA(A){const g=A;nQA(g),xQ(g._surface,A)}function Dv(A){qQ(A._surface,A)}function oQA(A){const g=A;g._disposed||(Dv(A),Se(g._rt),g._disposed=!0)}function BQA(A){const g=[...A.options.bindings??[]].sort((e,t)=>e.binding-t.binding),I=new Set;for(const e of g)if(I.has(e.binding)&&U(35,e.binding),I.add(e.binding),e.kind==="uniform"){const t=lQA(e.uniformByteLength??16),i=A._engine._device.createBuffer({label:`${A.name}-${e.name??e.binding}-ubo`,size:t,usage:SA.UNIFORM|SA.COPY_DST});A._uniforms.push({layout:e,buffer:i,byteLength:t})}else e.kind==="texture"&&A._textures.push({layout:e,texture:null})}function pv(A,g,I,e,t){A.clearValue=t,A.loadOp=e?"clear":"load",A.view=g._colorView,A.resolveTarget=I?._colorView??void 0}function QQA(A){const g=A._descriptor.size;if(!("canvas"in g))return;const I=g.canvas;A._width===I.width&&A._height===I.height||Kt(A,g.engine)}function yv(A,g){const I=Ot(g);A._pipelines||(A._pipelines=new Map);const e=A._pipelines.get(I);if(e)return e;const i=A._engine._device.createRenderPipeline({label:`${A.name}-${I}`,layout:rQA(A),vertex:{module:_v(A),entryPoint:"effectFullscreenVertex"},fragment:{module:_v(A),entryPoint:"effectFragment",targets:[{format:g._colorFormat,blend:A.options.blend}]},primitive:{topology:"triangle-list"},multisample:{count:g._sampleCount}});return A._pipelines.set(I,i),i}function _v(A){return A._shader||(A._shader=A._engine._device.createShaderModule({label:A.name,code:`${A.options.vertexWGSL??$BA} ${A.options.fragmentWGSL}`})),A._shader}function rQA(A){return A._pipelineLayout||(A._pipelineLayout=A._engine._device.createPipelineLayout({label:`${A.name}-pipeline-layout`,bindGroupLayouts:[uv(A)]})),A._pipelineLayout}function uv(A){if(!A._bindGroupLayout){const g=(A.options.bindings??[]).slice().sort((I,e)=>I.binding-e.binding).map(I=>EQA(I));A._bindGroupLayout=A._engine._device.createBindGroupLayout({label:`${A.name}-bgl`,entries:g})}return A._bindGroupLayout}function EQA(A){const g=A.visibility??NA.FRAGMENT;return A.kind==="uniform"?{binding:A.binding,visibility:g,buffer:{type:"uniform"}}:A.kind==="texture"?{binding:A.binding,visibility:g,texture:{sampleType:A.textureSampleType??"float",viewDimension:A.viewDimension??"2d"}}:{binding:A.binding,visibility:g,sampler:{type:A.samplerType??"filtering"}}}function L3(A){const g=A.options.bindings??[];if(g.length===0)return null;if(!A._bindGroupDirty&&A._bindGroup)return A._bindGroup;const I=g.slice().sort((e,t)=>e.binding-t.binding).map(e=>sQA(A,e));return A._bindGroup=A._engine._device.createBindGroup({label:`${A.name}-bg`,layout:uv(A),entries:I}),A._bindGroupDirty=!1,A._bindGroup}function nQA(A){A._pipeline??=yv(A._effect,A._targetSignature),A._bindGroup=L3(A._effect)}function sQA(A,g){if(g.kind==="uniform"){const e=hv(A,g.binding);return e||U(36,A.name,g.binding),{binding:g.binding,resource:{buffer:e.buffer,size:e.byteLength}}}if(g.kind==="texture"){const e=Y3(A,g.binding);return e?.texture||U(37,A.name,g.binding),{binding:g.binding,resource:e.texture.view}}const I=g.textureBinding!=null?Y3(A,g.textureBinding):A._textures[0];return I?.texture||U(38,A.name,g.binding),{binding:g.binding,resource:I.texture.sampler}}function hv(A,g){return A._uniforms.find(I=>fv(I.layout,g))}function Y3(A,g){return A._textures.find(I=>fv(I.layout,g))}function fv(A,g){return typeof g=="number"?A.binding===g:A.name===g||String(A.binding)===g}function dv(A,g,I){const e=aQA(I);e.byteLength>g.byteLength&&U(39,e.byteLength,g.layout.binding,g.byteLength),A._engine._device.queue.writeBuffer(g.buffer,0,e.buffer,e.byteOffset,e.byteLength)}function aQA(A){return A instanceof ArrayBuffer?new mg(A):new mg(A.buffer,A.byteOffset,A.byteLength)}function cQA(A){return A instanceof ArrayBuffer||ArrayBuffer.isView(A)}function lQA(A){return A+3&-4}const DQA="struct EffectVertexOutput{@builtin(position)position:vec4<f32>,@location(0)uv:vec2<f32>};@vertex fn effectFullscreenVertex(@builtin(vertex_index)vertexIndex:u32)->EffectVertexOutput{var positions=array<vec2<f32>,3>(vec2<f32>(-1.0,-1.0),vec2<f32>(3.0,-1.0),vec2<f32>(-1.0,3.0));let p=positions[vertexIndex];var out:EffectVertexOutput;out.position=vec4<f32>(p,0.0,1.0);out.uv=p*0.5+vec2<f32>(0.5,0.5);return out;}";function pQA(A,g){const I=A,e=SQA(g.uniformByteLength);return{name:g.name??"uniform-effect-wrapper",options:g,_engine:I,_shader:null,_bindGroupLayout:null,_pipelineLayout:null,_bindGroup:null,_uniformBuffer:I._device.createBuffer({label:`${g.name??"uniform-effect-wrapper"}-ubo`,size:e,usage:SA.UNIFORM|SA.COPY_DST}),_uniformByteLength:e}}function yQA(A,g){const I=A,e=MQA(g);e.byteLength>I._uniformByteLength&&U(40,e.byteLength,I._uniformByteLength),I._engine._device.queue.writeBuffer(I._uniformBuffer,0,e.buffer,e.byteOffset,e.byteLength)}function _QA(A,g,I){const e=g,t=A.effect,i=A.target;A.clearColor??={r:0,g:0,b:0,a:1};const o=i._descriptor.samples??1,Q={_colorFormat:i._descriptor.format,_sampleCount:o},r={loadOp:"clear",storeOp:"store"},E={name:A.name,_config:A,engine:e,scene:I,_passes:[],_rt:i,_targetSignature:Q,_renderPassDescriptor:{label:A.name,colorAttachments:[r]},_colorAttachment:r,_pipeline:null,record(){Kt(i,e),E._pipeline=fQA(t,E._targetSignature)},execute(){const n=E._pipeline;n||U(41,E.name),hQA(E._colorAttachment,i,E._config.clear!==!1,E._config.clearColor);const s=e._currentEncoder.beginRenderPass(E._renderPassDescriptor);return s.setPipeline(n),s.setBindGroup(0,wQA(t)),s.draw(3),s.end(),1},dispose(){E._passes.length=0,Se(E._rt),E._pipeline=null}};return E}function uQA(A){const g=A;g._uniformBuffer.destroy(),g._shader=null,g._bindGroupLayout=null,g._pipelineLayout=null,g._bindGroup=null}function hQA(A,g,I,e){A.clearValue=e,A.loadOp=I?"clear":"load",A.view=g._colorView,A.resolveTarget=void 0}function fQA(A,g){return A._engine._device.createRenderPipeline({label:`${A.name}-${Ot(g)}`,layout:dQA(A),vertex:{module:wv(A),entryPoint:"effectFullscreenVertex"},fragment:{module:wv(A),entryPoint:"effectFragment",targets:[{format:g._colorFormat}]},primitive:{topology:"triangle-list"},multisample:{count:g._sampleCount}})}function wv(A){return A._shader||(A._shader=A._engine._device.createShaderModule({label:A.name,code:`${A.options.vertexWGSL??DQA} ${A.options.fragmentWGSL}`})),A._shader}function dQA(A){return A._pipelineLayout||(A._pipelineLayout=A._engine._device.createPipelineLayout({label:`${A.name}-pipeline-layout`,bindGroupLayouts:[Mv(A)]})),A._pipelineLayout}function Mv(A){return A._bindGroupLayout||(A._bindGroupLayout=A._engine._device.createBindGroupLayout({label:`${A.name}-bgl`,entries:[{binding:0,visibility:NA.FRAGMENT,buffer:{type:"uniform"}}]})),A._bindGroupLayout}function wQA(A){return A._bindGroup||(A._bindGroup=A._engine._device.createBindGroup({label:`${A.name}-bg`,layout:Mv(A),entries:[{binding:0,resource:{buffer:A._uniformBuffer,size:A._uniformByteLength}}]})),A._bindGroup}function MQA(A){return A instanceof ArrayBuffer?new mg(A):new mg(A.buffer,A.byteOffset,A.byteLength)}function SQA(A){return A+3&-4}const RQA=(A,g)=>`struct PostProcessVertexOutput{@builtin(position)position:vec4f,@location(0)uv:vec2f${A}}@vertex fn postProcessVertex(@builtin(vertex_index)vertexIndex:u32)->PostProcessVertexOutput{var positions=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));let p=positions[vertexIndex];var out:PostProcessVertexOutput;out.position=vec4f(p,0,1);out.uv=vec2f(p.x*0.5+0.5,0.5-p.y*0.5);${g}return out;}`,NQA="@group(0)@binding(0)var sourceSampler:sampler;@group(0)@binding(1)var sourceTextureSampler:texture_2d<f32>;fn samplePostProcessSource(uv:vec2f)->vec4f{return textureSample(sourceTextureSampler,sourceSampler,uv);}fn readPostProcessSource(uv:vec2f)->vec4f{let dims=vec2f(textureDimensions(sourceTextureSampler));let p=clamp(floor(uv*dims)+vec2f(0.5),vec2f(0.5),dims-vec2f(0.5));return textureSampleLevel(sourceTextureSampler,sourceSampler,p/dims,0);}",GQA="@fragment fn postProcessFragment(input:PostProcessVertexOutput)->@location(0)vec4f{return applyPostProcess(samplePostProcessSource(input.uv),input.uv);}";function Vt(A,g,I){const e=A.sourceTexture,t=A.targetTexture?null:Rv(A.name??"post-process",e),i={view:void 0,loadOp:"clear",storeOp:"store"},o={name:A.name??"post-process",engine:g,scene:I,_passes:[],sourceTexture:e,sourceSamplingMode:A.sourceSamplingMode??"linear",targetTexture:A.targetTexture??null,alphaMode:A.alphaMode??0,viewport:A.viewport??null,clear:A.clear??!0,outputTexture:A.targetTexture??t,_shader:A._shader,_internalTarget:t,_internalTargetKey:t?Nv(e):"",_pipeline:null,_bindGroup:null,_bindGroupLayout:null,_pipelineLayout:null,_shaderModule:null,_shaderModuleCode:"",_uniformBuffer:null,_uniformData:null,_renderPassDescriptor:{label:A.name??"post-process",colorAttachments:[i]},_colorAttachment:i,record(){FQA(o),Kt(o.outputTexture,g),Sv(o,g)},execute(){kQA(o._colorAttachment,o.outputTexture,o.clear);const Q=g._currentEncoder.beginRenderPass(o._renderPassDescriptor);return UQA(Q,o.viewport,o.outputTexture),Q.setPipeline(o._pipeline),Q.setBindGroup(0,o._bindGroup),Q.draw(3),Q.end(),1},updateUniforms(){mv(o,g)},_rebuildGpuState(){Sv(o,g)},dispose(){o._passes.length=0,o._uniformBuffer?.destroy(),o._uniformBuffer=null,o._uniformData=null,o._pipeline=null,o._bindGroup=null,o._bindGroupLayout=null,o._pipelineLayout=null,o._shaderModule=null,o._shaderModuleCode="",Se(o._internalTarget)}};return o}function Sv(A,g){const I=A.sourceTexture;(!I._colorTexture||!I._colorView)&&U(107,A.name),(I._descriptor.samples??1)!==1&&U(108,A.name);const e=A.outputTexture,t=e._descriptor.format;t||U(109,A.name),A._uniformBuffer??=bQA(A,g),A._uniformData??=KQA(A),mv(A,g);const i=mQA(A,g);A._pipelineLayout??=g._device.createPipelineLayout({label:`${A.name}-pipeline-layout`,bindGroupLayouts:[i]});const o={_colorFormat:t,_sampleCount:e._descriptor.samples??1};A._pipeline=g._device.createRenderPipeline({label:`${A.name}-${Ot(o)}-${A.alphaMode}`,layout:A._pipelineLayout,vertex:{module:Fv(A,g),entryPoint:"postProcessVertex"},fragment:{module:Fv(A,g),entryPoint:"postProcessFragment",targets:[{format:t,blend:LQA(A.alphaMode)}]},primitive:{topology:"triangle-list"},multisample:{count:o._sampleCount}});const Q=[{binding:0,resource:A.sourceSamplingMode==="nearest"?X6(g):m1(g)},{binding:1,resource:I._colorView}],r=A._shader.extraTextures??[];A._uniformBuffer&&Q.push({binding:Gv(A),resource:{buffer:A._uniformBuffer}});for(let E=0;E<r.length;E++){const n=r[E];n._colorView||U(110,A.name,E),Q.push({binding:2+E,resource:n._colorView})}A._bindGroup=g._device.createBindGroup({label:`${A.name}-bind-group`,layout:i,entries:Q})}function FQA(A){const g=A.targetTexture;if(g){A.outputTexture=g;return}const I=Nv(A.sourceTexture);if(A._internalTarget&&A._internalTargetKey===I){A.outputTexture=A._internalTarget;return}A._internalTarget&&Se(A._internalTarget),A._internalTarget=Rv(A.name,A.sourceTexture),A._internalTargetKey=I,A.outputTexture=A._internalTarget}function Rv(A,g){const I=g._descriptor;I.format||U(111,A);const e={lbl:`${A}-output`,format:I.format,samples:1,size:I.size};return wt(e)}function Nv(A){const g=A._descriptor,I=g.size,e="canvas"in I?`surface:${I._uniqueId}`:`${I.width}x${I.height}`;return`${g.format??"-"}|${g.samples??1}|${e}`}function mQA(A,g){const I=(A._shader.uniformByteLength??0)>0;if(A._bindGroupLayout)return A._bindGroupLayout;const e=[{binding:0,visibility:NA.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:NA.FRAGMENT,texture:{sampleType:"float"}}],t=A._shader.extraTextures??[];for(let i=0;i<t.length;i++)e.push({binding:2+i,visibility:NA.FRAGMENT,texture:{sampleType:"float"}});return I&&e.push({binding:Gv(A),visibility:NA.VERTEX|NA.FRAGMENT,buffer:{type:"uniform"}}),A._bindGroupLayout=g._device.createBindGroupLayout({label:`${A.name}-bind-group-layout`,entries:e}),A._bindGroupLayout}function Gv(A){return A._shader.uniformBinding??2+(A._shader.extraTextures?.length??0)}function Fv(A,g){const I=`${RQA(A._shader.vertexOutputWGSL??"",A._shader.vertexMainWGSL??"")} ${NQA} ${A._shader.extraTextureWGSL??""} ${A._shader.uniformWGSL??""} ${A._shader.fragmentWGSL} ${A._shader.fragmentWrapperWGSL??GQA}`;return(!A._shaderModule||A._shaderModuleCode!==I)&&(A._shaderModuleCode=I,A._shaderModule=g._device.createShaderModule({label:A.name,code:I})),A._shaderModule}function bQA(A,g){const I=bv(A._shader.uniformByteLength??0);return I===0?null:g._device.createBuffer({label:`${A.name}-uniforms`,size:I,usage:SA.UNIFORM|SA.COPY_DST})}function KQA(A){const g=bv(A._shader.uniformByteLength??0);return g===0?null:new X(g/4)}function mv(A,g){(A._shader.uniformByteLength??0)!==0&&(A._uniformData.fill(0),A._shader.writeUniforms?.(A._uniformData),g._device.queue.writeBuffer(A._uniformBuffer,0,A._uniformData))}function kQA(A,g,I){A.view=g._colorView,A.resolveTarget=void 0,A.loadOp=I?"clear":"load"}function UQA(A,g,I){if(!g)return;const e=Math.floor(g.x*I._width),t=Math.floor((1-g.y-g.height)*I._height),i=Math.ceil((g.x+g.width)*I._width)-e,o=Math.ceil((1-g.y)*I._height)-t;A.setViewport(e,t,i,o,0,1),A.setScissorRect(e,t,i,o)}function LQA(A){switch(A){case 1:return{color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one",operation:"add"}};case 2:return{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};case 7:return{color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};default:return}}function bv(A){return Math.ceil(A/16)*16}const YQA="struct BlackAndWhiteParams{degree:f32,p0:f32,p1:f32,p2:f32}@group(0)@binding(2)var<uniform>blackAndWhiteParams:BlackAndWhiteParams;",JQA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let luminance=dot(color.rgb,vec3f(0.3,0.59,0.11));let gray=vec3f(luminance);return vec4f(mix(color.rgb,gray,clamp(blackAndWhiteParams.degree,0,1)),color.a);}";function vQA(A,g,I){const e={degree:A.degree??1},t=Vt({name:A.name??"black-and-white",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode,targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{uniformWGSL:YQA,uniformByteLength:16,writeUniforms(i){i[0]=e.degree},fragmentWGSL:JQA}},g,I);return Object.defineProperty(t,"degree",{get:()=>e.degree,set:i=>{e.degree=i}}),t}const HQA="@group(0)@binding(2)var leftTextureSampler:texture_2d<f32>;",TQA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let l=textureSampleLevel(leftTextureSampler,sourceSampler,clamp(uv,vec2f(0),vec2f(1)),0);let left=vec4f(1,l.g,l.b,1);let right=vec4f(color.r,1,1,1);return vec4f(right.rgb*left.rgb,1);}";function xQA(A,g,I){const e=Vt({name:A.name??"anaglyph",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode,targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{extraTextureWGSL:HQA,extraTextures:[A.leftTexture],fragmentWGSL:TQA}},g,I);return e.leftTexture=A.leftTexture,e}const qQA=8,PQA="struct BlurParams{delta:vec2f,p0:f32,p1:f32}@group(0)@binding(2)var<uniform>blurParams:BlurParams;";function OQA(A){const g=Math.max(1,Math.round(A));for(const I of[g,g-1,g+1,g-2,g+2])if(I>0&&I%2!==0&&Math.floor(I/2)%2===0)return Math.max(I,3);return Math.max(g,3)}function jQA(A){const g=.3333333333333333;return Math.exp(-(A*A)/(2*g*g))/(Math.sqrt(2*Math.PI)*g)}function VQA(A){const g=OQA(A),I=(g-1)/2,e=[],t=[];let i=0;for(let Q=0;Q<g;Q++){const r=jQA(Q/(g-1)*2-1);e[Q]=Q-I,t[Q]=r,i+=r}for(let Q=0;Q<t.length;Q++)t[Q]/=i;const o=[];for(let Q=0;Q<=I;Q+=2){const r=Math.min(Q+1,Math.floor(I));if(Q===r){o.push({offset:e[Q],weight:t[Q]});continue}const E=r===I,n=t[Q]+t[r]*(E?.5:1),s=e[Q]+1/(1+t[Q]/t[r]);s===0?o.push({offset:e[Q],weight:t[Q]},{offset:e[Q+1],weight:t[Q+1]}):o.push({offset:s,weight:n},{offset:-s,weight:n})}return o}function FF(A){return A.toFixed(7).replace(/0+$/,"").replace(/\.$/,".0")}function Kv(A,g){const I=VQA(g),e=Math.min(I.length,qQA);A.vertexOutputWGSL="",A.vertexMainWGSL="";for(let i=0;i<e;i++)A.vertexOutputWGSL=`${A.vertexOutputWGSL},@location(${i+1})sampleCoord${i}:vec2f`,A.vertexMainWGSL=`${A.vertexMainWGSL}out.sampleCoord${i}=out.uv+blurParams.delta*${FF(I[i].offset)};`;let t="var blend=vec4f(0);";for(let i=0;i<e;i++)t=`${t}blend+=textureSample(sourceTextureSampler,sourceSampler,input.sampleCoord${i})*${FF(I[i].weight)};`;for(let i=e;i<I.length;i++){const o=I[i];t=`${t}blend+=samplePostProcessSource(input.uv+blurParams.delta*${FF(o.offset)})*${FF(o.weight)};`}t=`${t}return blend;`,A.fragmentWGSL="",A.fragmentWrapperWGSL=`@fragment fn postProcessFragment(input:PostProcessVertexOutput)->@location(0)vec4f{${t}}`}function J3(A,g,I){const e={direction:A.direction??{x:1,y:0},kernel:A.kernel??9},t={uniformWGSL:PQA,uniformByteLength:16,writeUniforms(r){const E=Math.max(1,i.outputTexture._width||A.sourceTexture._width),n=Math.max(1,i.outputTexture._height||A.sourceTexture._height);r[0]=e.direction.x/E,r[1]=e.direction.y/n},fragmentWGSL:""};Kv(t,e.kernel);const i=Vt({name:A.name??"blur",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode,targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:t},g,I),o=i.updateUniforms;let Q=e.kernel;return i.updateUniforms=()=>{if(Q!==e.kernel){Q=e.kernel,Kv(i._shader,e.kernel),i._rebuildGpuState();return}o()},Object.defineProperties(i,{direction:{get:()=>e.direction,set:r=>{e.direction=r}},kernel:{get:()=>e.kernel,set:r=>{e.kernel=r}}}),i}const WQA=1/2.2,zQA="struct ExtractHighlightsParams{threshold:f32,exposure:f32,p0:f32,p1:f32}@group(0)@binding(2)var<uniform>extractHighlightsParams:ExtractHighlightsParams;",ZQA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let luma=dot(vec3f(0.2126,0.7152,0.0722),color.rgb*extractHighlightsParams.exposure);return vec4f(step(extractHighlightsParams.threshold,luma)*color.rgb,color.a);}";function kv(A,g,I){const e={threshold:A.threshold??.9,exposure:A.exposure??1},t=Vt({name:A.name??"extract-highlights",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode,targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{uniformWGSL:zQA,uniformByteLength:16,writeUniforms(i){i[0]=Math.pow(e.threshold,WQA),i[1]=e.exposure},fragmentWGSL:ZQA}},g,I);return Object.defineProperties(t,{threshold:{get:()=>e.threshold,set:i=>{e.threshold=i}},exposure:{get:()=>e.exposure,set:i=>{e.exposure=i}}}),t}const XQA="struct ChromaticAberrationParams{chromatic_aberration:f32,screen_width:f32,screen_height:f32,radialIntensity:f32,direction:vec2f,centerPosition:vec2f}@group(0)@binding(2)var<uniform>chromaticAberrationParams:ChromaticAberrationParams;",$QA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let centered=uv-chromaticAberrationParams.centerPosition;var dir=chromaticAberrationParams.direction;if(dir.x==0.0&&dir.y==0.0){dir=normalize(centered);}let radius=sqrt(dot(centered,centered));let amount=chromaticAberrationParams.chromatic_aberration*pow(radius,chromaticAberrationParams.radialIntensity);let shift=amount*dir/vec2f(chromaticAberrationParams.screen_width,chromaticAberrationParams.screen_height);let r=samplePostProcessSource(vec2f(uv.x+shift.x*-0.3,uv.y+shift.y*-0.3*0.5));let g=samplePostProcessSource(uv);let b=samplePostProcessSource(vec2f(uv.x+shift.x*0.3,uv.y+shift.y*0.3*0.5));return vec4f(r.r,g.g,b.b,clamp(r.a+g.a+b.a,0,1));}";function ArA(A,g,I){const e={aberrationAmount:A.aberrationAmount??30,screenWidth:1,screenHeight:1,direction:A.direction??{x:.707,y:.707},radialIntensity:A.radialIntensity??0,centerPosition:A.centerPosition??{x:.5,y:.5}},t=Vt({name:A.name??"chromatic-aberration",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode,targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{uniformWGSL:XQA,uniformByteLength:32,writeUniforms(o){o[0]=e.aberrationAmount,o[1]=e.screenWidth,o[2]=e.screenHeight,o[3]=e.radialIntensity,o[4]=e.direction.x,o[5]=e.direction.y,o[6]=e.centerPosition.x,o[7]=e.centerPosition.y},fragmentWGSL:$QA}},g,I),i=t.record;return t.record=()=>{e.screenWidth=t.sourceTexture._width,e.screenHeight=t.sourceTexture._height,i()},Object.defineProperties(t,{aberrationAmount:{get:()=>e.aberrationAmount,set:o=>{e.aberrationAmount=o}},direction:{get:()=>e.direction,set:o=>{e.direction=o}},radialIntensity:{get:()=>e.radialIntensity,set:o=>{e.radialIntensity=o}},centerPosition:{get:()=>e.centerPosition,set:o=>{e.centerPosition=o}}}),t}const grA="@group(0)@binding(2)var cocDepthTexture:texture_2d<f32>;",IrA="struct CircleOfConfusionParams{focusDistance:f32,cocPrecalculation:f32,minZ:f32,maxZRange:f32}@group(0)@binding(3)var<uniform>cocParams:CircleOfConfusionParams;";function erA(A){return`fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let depth=textureSample(cocDepthTexture,sourceSampler,uv).r;let pixelDistance=${A?"depth*1000.0":"(cocParams.minZ+cocParams.maxZRange*depth)*1000.0"};var coc=abs(cocParams.cocPrecalculation*((cocParams.focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);return vec4f(coc,coc,coc,1.0);}`}function Uv(A,g,I){const e={lensSize:A.lensSize??50,fStop:A.fStop??1.4,focusDistance:A.focusDistance??2e3,focalLength:A.focalLength??50},t=A.camera,i=A.depthNotNormalized??!1,o=Vt({name:A.name??"circle-of-confusion",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode??"linear",targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{extraTextures:[A.depthTexture],extraTextureWGSL:grA,uniformWGSL:IrA,uniformByteLength:16,writeUniforms(Q){const r=e.lensSize/e.fStop;Q[0]=e.focusDistance,Q[1]=r*e.focalLength/(e.focusDistance-e.focalLength),Q[2]=t.nearPlane,Q[3]=t.farPlane-t.nearPlane},fragmentWGSL:erA(i)}},g,I);return Object.defineProperties(o,{lensSize:{get:()=>e.lensSize,set:Q=>e.lensSize=Q},fStop:{get:()=>e.fStop,set:Q=>e.fStop=Q},focusDistance:{get:()=>e.focusDistance,set:Q=>e.focusDistance=Q},focalLength:{get:()=>e.focalLength,set:Q=>e.focalLength=Q}}),o}const trA="@group(0)@binding(2)var bloomBlur:texture_2d<f32>;",CrA="struct BloomMergeParams{weight:f32,p0:f32,p1:f32,p2:f32}@group(0)@binding(3)var<uniform>bloomMergeParams:BloomMergeParams;",irA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let blurred=textureSampleLevel(bloomBlur,sourceSampler,clamp(uv,vec2f(0),vec2f(1)),0).rgb;return vec4f(color.rgb+blurred*bloomMergeParams.weight,color.a);}",mF=(A,g)=>A*g;function orA(A,g,I){const e=g,t={sourceTexture:A.sourceTexture,targetTexture:A.targetTexture??null,sourceSamplingMode:A.sourceSamplingMode??"linear",alphaMode:A.alphaMode??0,viewport:A.viewport??null,clear:A.clear??!0,weight:A.weight??.25,kernel:A.kernel??64,threshold:A.threshold??.2,exposure:A.exposure??1,bloomScale:A.bloomScale??.5},i=A.name??"bloom",o=v3(`${i}-extract-output`,t.sourceTexture,t.bloomScale),Q=v3(`${i}-blur-x-output`,t.sourceTexture,t.bloomScale),r=v3(`${i}-blur-y-output`,t.sourceTexture,t.bloomScale),E=kv({name:`${i}-extract-highlights`,sourceTexture:t.sourceTexture,sourceSamplingMode:"linear",targetTexture:o,threshold:t.threshold,exposure:t.exposure},g,I),n=J3({name:`${i}-blur-x`,sourceTexture:o,sourceSamplingMode:"linear",targetTexture:Q,direction:{x:1,y:0},kernel:mF(t.kernel,t.bloomScale)},g,I),s=J3({name:`${i}-blur-y`,sourceTexture:Q,sourceSamplingMode:"linear",targetTexture:r,direction:{x:0,y:1},kernel:mF(t.kernel,t.bloomScale)},g,I),c=Vt({name:`${i}-merge`,sourceTexture:t.sourceTexture,sourceSamplingMode:t.sourceSamplingMode,targetTexture:t.targetTexture,alphaMode:t.alphaMode,viewport:t.viewport,clear:t.clear,_shader:{extraTextureWGSL:trA,extraTextures:[r],uniformWGSL:CrA,uniformBinding:3,uniformByteLength:16,writeUniforms(D){D[0]=t.weight},fragmentWGSL:irA}},g,I),l={name:i,engine:e,scene:I,_passes:[],sourceTexture:t.sourceTexture,sourceSamplingMode:t.sourceSamplingMode,targetTexture:t.targetTexture,alphaMode:t.alphaMode,viewport:t.viewport,clear:t.clear,outputTexture:c.outputTexture,_extract:E,_blurX:n,_blurY:s,_merge:c,_extractTarget:o,_blurXTarget:Q,_blurYTarget:r,record(){H3(l._extractTarget,t.sourceTexture,t.bloomScale),H3(l._blurXTarget,t.sourceTexture,t.bloomScale),H3(l._blurYTarget,t.sourceTexture,t.bloomScale),E.record(),n.record(),s.record(),c.record(),l.outputTexture=c.outputTexture},execute(){return(E.execute?.()??0)+(n.execute?.()??0)+(s.execute?.()??0)+(c.execute?.()??0)},updateUniforms(){E.updateUniforms(),n.updateUniforms(),s.updateUniforms(),c.updateUniforms()},dispose(){E.dispose(),n.dispose(),s.dispose(),c.dispose(),Se(l._extractTarget),Se(l._blurXTarget),Se(l._blurYTarget)},get weight(){return t.weight},set weight(D){t.weight=D},get kernel(){return t.kernel},set kernel(D){t.kernel=D,n.kernel=mF(D,t.bloomScale),s.kernel=mF(D,t.bloomScale)},get threshold(){return E.threshold},set threshold(D){t.threshold=D,E.threshold=D},get exposure(){return E.exposure},set exposure(D){t.exposure=D,E.exposure=D},get bloomScale(){return t.bloomScale}};return Object.defineProperties(l,{sourceTexture:{get:()=>t.sourceTexture,set:D=>{t.sourceTexture=D,E.sourceTexture=D,c.sourceTexture=D}},sourceSamplingMode:{get:()=>t.sourceSamplingMode,set:D=>{t.sourceSamplingMode=D,c.sourceSamplingMode=D}},targetTexture:{get:()=>t.targetTexture,set:D=>{t.targetTexture=D,c.targetTexture=D,l.outputTexture=c.outputTexture}},alphaMode:{get:()=>t.alphaMode,set:D=>{t.alphaMode=D,c.alphaMode=D}},viewport:{get:()=>t.viewport,set:D=>{t.viewport=D,c.viewport=D}},clear:{get:()=>t.clear,set:D=>{t.clear=D,c.clear=D}}}),l}function v3(A,g,I){const e=g._descriptor;e.format||U(437,A);const t=Lv(g);return wt({lbl:A,format:e.format,samples:1,size:{width:Math.max(1,Math.floor(t.width*I)),height:Math.max(1,Math.floor(t.height*I))}})}function H3(A,g,I){const e=g._descriptor.format;e||U(438,A._descriptor.lbl??"target");const t=Lv(g);A._descriptor.format=e,A._descriptor.size={width:Math.max(1,Math.floor(t.width*I)),height:Math.max(1,Math.floor(t.height*I))}}function Lv(A){if(A._width>0&&A._height>0)return{width:A._width,height:A._height};const g=A._descriptor;if("canvas"in g.size){const I=g.size.canvas;return{width:I.width,height:I.height}}return g.size}const BrA=8,QrA="@group(0)@binding(2)var dofCocTexture:texture_2d<f32>;",rrA="struct DofBlurParams{delta:vec2f,p0:f32,p1:f32}@group(0)@binding(3)var<uniform>dofBlurParams:DofBlurParams;",ErA="fn sampleCoC(uv:vec2f)->f32{return textureSample(dofCocTexture,sourceSampler,uv).r;}";function nrA(A){const g=Math.max(1,Math.round(A));for(const I of[g,g-1,g+1,g-2,g+2])if(I>0&&I%2!==0&&Math.floor(I/2)%2===0)return Math.max(I,3);return Math.max(g,3)}function srA(A){const g=.3333333333333333;return Math.exp(-(A*A)/(2*g*g))/(Math.sqrt(2*Math.PI)*g)}function arA(A){const g=nrA(A),I=(g-1)/2,e=[],t=[];let i=0;for(let Q=0;Q<g;Q++){const r=srA(Q/(g-1)*2-1);e[Q]=Q-I,t[Q]=r,i+=r}for(let Q=0;Q<t.length;Q++)t[Q]/=i;const o=[];for(let Q=0;Q<=I;Q+=2){const r=Math.min(Q+1,Math.floor(I));if(Q===r){o.push({offset:e[Q],weight:t[Q]});continue}const E=r===I,n=t[Q]+t[r]*(E?.5:1),s=e[Q]+1/(1+t[Q]/t[r]);s===0?o.push({offset:e[Q],weight:t[Q]},{offset:e[Q+1],weight:t[Q+1]}):o.push({offset:s,weight:n},{offset:-s,weight:n})}return o}function XR(A){return A.toFixed(7).replace(/0+$/,"").replace(/\.$/,".0")}function Yv(A,g){const I=arA(g),e=I[I.length-1],t=I.slice(0,I.length-1),i=Math.min(t.length,BrA);A.vertexOutputWGSL="",A.vertexMainWGSL="";for(let Q=0;Q<i;Q++)A.vertexOutputWGSL=`${A.vertexOutputWGSL},@location(${Q+1})sampleCoord${Q}:vec2f`,A.vertexMainWGSL=`${A.vertexMainWGSL}out.sampleCoord${Q}=out.uv+dofBlurParams.delta*${XR(t[Q].offset)};`;let o=`var blend=textureSample(sourceTextureSampler,sourceSampler,input.uv)*${XR(e.weight)};`;o=`${o}var sumOfWeights=${XR(e.weight)};`;for(let Q=0;Q<t.length;Q++){const r=t[Q],E=Q<i?`input.sampleCoord${Q}`:`(input.uv+dofBlurParams.delta*${XR(r.offset)})`;o=`${o}let f${Q}=sampleCoC(${E});let w${Q}=${XR(r.weight)}*f${Q};sumOfWeights=sumOfWeights+w${Q};`,o=`${o}blend=blend+textureSample(sourceTextureSampler,sourceSampler,${E})*w${Q};`}o=`${o}return blend/sumOfWeights;`,A.fragmentWGSL=ErA,A.fragmentWrapperWGSL=`@fragment fn postProcessFragment(input:PostProcessVertexOutput)->@location(0)vec4f{${o}}`}function Jv(A,g,I){const e={direction:A.direction??{x:1,y:0},kernel:A.kernel??9},t={extraTextureWGSL:QrA,extraTextures:[A.circleOfConfusionTexture],uniformWGSL:rrA,uniformBinding:3,uniformByteLength:16,writeUniforms(r){const E=Math.max(1,i.outputTexture._width||A.sourceTexture._width),n=Math.max(1,i.outputTexture._height||A.sourceTexture._height);r[0]=e.direction.x/E,r[1]=e.direction.y/n},fragmentWGSL:""};Yv(t,e.kernel);const i=Vt({name:A.name??"depth-of-field-blur",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode??"linear",targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:t},g,I),o=i.updateUniforms;let Q=e.kernel;return i.updateUniforms=()=>{if(Q!==e.kernel){Q=e.kernel,Yv(i._shader,e.kernel),i._rebuildGpuState();return}o()},Object.defineProperties(i,{direction:{get:()=>e.direction,set:r=>{e.direction=r}},kernel:{get:()=>e.kernel,set:r=>{e.kernel=r}}}),i}function crA(A){let g="@group(0)@binding(2)var dofCocTexture:texture_2d<f32>;@group(0)@binding(3)var blurStep0:texture_2d<f32>;";return A>0&&(g=`${g}@group(0)@binding(4)var blurStep1:texture_2d<f32>;`),A>1&&(g=`${g}@group(0)@binding(5)var blurStep2:texture_2d<f32>;`),g}function lrA(A){const g="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let coc=textureSampleLevel(dofCocTexture,sourceSampler,uv,0.0).r;let blurred0=textureSampleLevel(blurStep0,sourceSampler,uv,0.0);";return A===0?`${g}return mix(color,blurred0,coc);}`:A===1?`${g} let blurred1=textureSampleLevel(blurStep1,sourceSampler,uv,0.0);if(coc<0.5){return mix(color,blurred1,coc/0.5);}return mix(blurred1,blurred0,(coc-0.5)/0.5);}`:`${g} let blurred1=textureSampleLevel(blurStep1,sourceSampler,uv,0.0);let blurred2=textureSampleLevel(blurStep2,sourceSampler,uv,0.0);if(coc<0.33){return mix(color,blurred2,coc/0.33);}if(coc<0.66){return mix(blurred2,blurred1,(coc-0.33)/0.33);}return mix(blurred1,blurred0,(coc-0.66)/0.34);}`}function DrA(A,g,I){const e=A.blurSteps.length-1,t=[A.circleOfConfusionTexture];for(let i=A.blurSteps.length-1;i>=0;i--)t.push(A.blurSteps[i]);return Vt({name:A.name??"depth-of-field-merge",sourceTexture:A.sourceTexture,sourceSamplingMode:A.sourceSamplingMode??"linear",targetTexture:A.targetTexture,alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{extraTextureWGSL:crA(e),extraTextures:t,fragmentWGSL:lrA(e)}},g,I)}var vv=(A=>(A[A.Low=0]="Low",A[A.Medium=1]="Medium",A[A.High=2]="High",A))(vv||{});function prA(A){switch(A){case 2:return{blurCount:3,kernel:51};case 1:return{blurCount:2,kernel:31};default:return{blurCount:1,kernel:15}}}function yrA(A){if(A._width>0&&A._height>0)return{width:A._width,height:A._height};if("canvas"in A._descriptor.size){const g=A._descriptor.size.canvas;return{width:g.width,height:g.height}}return A._descriptor.size}function Hv(A,g){const I=yrA(A);return{width:Math.max(1,Math.floor(I.width*g)),height:Math.max(1,Math.floor(I.height*g))}}function _rA(A,g,I){const e=g,t={sourceTexture:A.sourceTexture,targetTexture:A.targetTexture??null,sourceSamplingMode:A.sourceSamplingMode??"linear",alphaMode:A.alphaMode??0,viewport:A.viewport??null,clear:A.clear??!0,lensSize:A.lensSize??50,fStop:A.fStop??1.4,focusDistance:A.focusDistance??2e3,focalLength:A.focalLength??50},i=A.name??"depth-of-field",{blurCount:o,kernel:Q}=prA(A.blurLevel??0),r=Q/Math.pow(2,o-1),E=[];for(let h=0;h<o;h++)E.push(.75/Math.pow(2,h));const n=t.sourceTexture._descriptor.format;n||U(439,i);const s=wt({lbl:`${i}-coc`,format:"r16float",samples:1,size:t.sourceTexture._descriptor.size}),c=Uv({name:`${i}-coc`,sourceTexture:t.sourceTexture,sourceSamplingMode:"linear",depthTexture:A.depthTexture,camera:A.camera,lensSize:t.lensSize,fStop:t.fStop,focusDistance:t.focusDistance,focalLength:t.focalLength,depthNotNormalized:A.depthNotNormalized,targetTexture:s},g,I),l=[],D=[],p=[],y=[],_=[];for(let h=0;h<o;h++){const w=Hv(t.sourceTexture,E[h]),M=wt({lbl:`${i}-blur-y-${h}`,format:n,samples:1,size:w}),S=wt({lbl:`${i}-blur-x-${h}`,format:n,samples:1,size:w}),R=Jv({name:`${i}-blur-y-${h}`,sourceTexture:h===0?t.sourceTexture:y[h-1],sourceSamplingMode:"linear",circleOfConfusionTexture:s,direction:{x:0,y:1},kernel:r,targetTexture:M},g,I),N=Jv({name:`${i}-blur-x-${h}`,sourceTexture:M,sourceSamplingMode:"linear",circleOfConfusionTexture:s,direction:{x:1,y:0},kernel:r,targetTexture:S},g,I);l.push(R),D.push(N),p.push(M),y.push(S),_.push(S)}const u=DrA({name:`${i}-merge`,sourceTexture:t.sourceTexture,sourceSamplingMode:t.sourceSamplingMode,targetTexture:t.targetTexture,alphaMode:t.alphaMode,viewport:t.viewport,clear:t.clear,circleOfConfusionTexture:s,blurSteps:_},g,I),f={name:i,engine:e,scene:I,_passes:[],sourceTexture:t.sourceTexture,sourceSamplingMode:t.sourceSamplingMode,targetTexture:t.targetTexture,alphaMode:t.alphaMode,viewport:t.viewport,clear:t.clear,outputTexture:u.outputTexture,_coc:c,_blurX:D,_blurY:l,_merge:u,_cocTarget:s,_blurXTargets:y,_blurYTargets:p,record(){for(let h=0;h<o;h++){const w=Hv(t.sourceTexture,E[h]);p[h]._descriptor.size=w,y[h]._descriptor.size=w}c.record();for(let h=0;h<o;h++)l[h].record(),D[h].record();u.record(),f.outputTexture=u.outputTexture},execute(){let h=c.execute?.()??0;for(let w=0;w<o;w++)h+=l[w].execute?.()??0,h+=D[w].execute?.()??0;return h+=u.execute?.()??0,h},updateUniforms(){c.updateUniforms();for(let h=0;h<o;h++)l[h].updateUniforms(),D[h].updateUniforms();u.updateUniforms()},dispose(){c.dispose();for(let h=0;h<o;h++)l[h].dispose(),D[h].dispose();u.dispose(),Se(s);for(const h of p)Se(h);for(const h of y)Se(h)},get lensSize(){return c.lensSize},set lensSize(h){c.lensSize=h},get fStop(){return c.fStop},set fStop(h){c.fStop=h},get focusDistance(){return c.focusDistance},set focusDistance(h){c.focusDistance=h},get focalLength(){return c.focalLength},set focalLength(h){c.focalLength=h}};return Object.defineProperties(f,{sourceTexture:{get:()=>t.sourceTexture,set:h=>{t.sourceTexture=h,c.sourceTexture=h,u.sourceTexture=h,l[0].sourceTexture=h}},sourceSamplingMode:{get:()=>t.sourceSamplingMode,set:h=>{t.sourceSamplingMode=h,u.sourceSamplingMode=h}},targetTexture:{get:()=>t.targetTexture,set:h=>{t.targetTexture=h,u.targetTexture=h,f.outputTexture=u.outputTexture}},alphaMode:{get:()=>t.alphaMode,set:h=>{t.alphaMode=h,u.alphaMode=h}},viewport:{get:()=>t.viewport,set:h=>{t.viewport=h,u.viewport=h}},clear:{get:()=>t.clear,set:h=>{t.clear=h,u.clear=h}}}),f}const urA="@group(0)@binding(2)var taaHistory:texture_2d<f32>;",hrA="struct TaaParams{factor:f32,p0:f32,p1:f32,p2:f32}@group(0)@binding(3)var<uniform>taaParams:TaaParams;",frA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let h=textureSample(taaHistory,sourceSampler,uv);return mix(h,color,taaParams.factor);}",Tv="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{return color;}";function drA(A,g,I){const e=A.name??"taa",t=A.sourceTexture,i=A.targetTexture??null,o=Math.max(1,Math.floor(A.samples??8)),Q=t._descriptor.size,r=wt({lbl:`${e}-history`,format:"rgba16float",samples:1,size:Q}),E=wt({lbl:`${e}-temp`,format:"rgba16float",samples:1,size:Q}),n=Vt({name:`${e}-blend`,sourceTexture:t,sourceSamplingMode:"nearest",targetTexture:E,_shader:{extraTextureWGSL:urA,extraTextures:[r],uniformWGSL:hrA,uniformBinding:3,uniformByteLength:16,writeUniforms(D){D[0]=l._factor},fragmentWGSL:frA}},g,I),s=Vt({name:`${e}-present`,sourceTexture:E,sourceSamplingMode:"nearest",targetTexture:i??g.scRT,_shader:{fragmentWGSL:Tv}},g,I),c=Vt({name:`${e}-history-update`,sourceTexture:E,sourceSamplingMode:"nearest",targetTexture:r,_shader:{fragmentWGSL:Tv}},g,I),l={name:e,engine:g,scene:I,_passes:[],sourceTexture:t,targetTexture:i,outputTexture:i??g.scRT,factor:A.factor??.05,samples:o,disableOnCameraMove:A.disableOnCameraMove??!0,_blend:n,_present:s,_historyUpdate:c,_history:r,_temp:E,_sourceRenderTask:A.sourceRenderTask,_halton:MrA(o),_haltonIndex:0,_jitterScratch:new X(16),_firstUpdate:!0,_lastCamVer:-1,_factor:1,record(){const{width:D,height:p}=wrA(l.sourceTexture);xv(r,g,D,p),xv(E,g,D,p),n.record(),s.record(),c.record(),l._firstUpdate=!0,l._haltonIndex=0,l._lastCamVer=-1},execute(){const D=l._sourceRenderTask.scene.camera,p=D?T1(D):0,y=p!==l._lastCamVer;l._lastCamVer=p;const _=l._firstUpdate||y&&l.disableOnCameraMove;l._factor=_?1:l.factor,n.updateUniforms();let u=n.execute?.()??0;return u+=s.execute?.()??0,u+=c.execute?.()??0,l._firstUpdate=!1,SrA(l),u},updateUniforms(){n.updateUniforms()},dispose(){l._passes.length=0,n.dispose(),s.dispose(),c.dispose(),r._eager=!1,E._eager=!1,Se(r),Se(E)}};return l}function xv(A,g,I,e){A._eager&&A._width===I&&A._height===e||(A._eager=!1,Se(A),A._descriptor.size={width:I,height:e},Kt(A,g),A._eager=!0)}function wrA(A){if(A._width>0&&A._height>0)return{width:A._width,height:A._height};const g=A._descriptor.size;return"canvas"in g?{width:g.canvas.width,height:g.canvas.height}:{width:g.width,height:g.height}}function MrA(A){const g=new X(A*2);for(let I=1;I<=A;I++)g[(I-1)*2]=qv(I,2)-.5,g[(I-1)*2+1]=qv(I,3)-.5;return g}function qv(A,g){let I=1,e=0;for(;A>0;)I/=g,e+=I*(A%g),A=Math.floor(A/g);return e}function SrA(A){const g=A._sourceRenderTask,I=g._suData,e=A.sourceTexture._width,t=A.sourceTexture._height;if(e<=0||t<=0)return;const i=A._halton[A._haltonIndex]/(e/2),o=A._halton[A._haltonIndex+1]/(t/2);A._haltonIndex+=2,A._haltonIndex>=A._halton.length&&(A._haltonIndex=0);const Q=A._jitterScratch;for(let r=0;r<4;r++){const E=r*4,n=I[E+3];Q[E]=I[E]+i*n,Q[E+1]=I[E+1]+o*n,Q[E+2]=I[E+2],Q[E+3]=n}A.engine._device.queue.writeBuffer(g._sceneUBO,0,Q)}const RrA="struct SmaaEdgeParams{threshold:f32,srgb:f32,pad1:f32,pad2:f32}@group(0)@binding(2)var<uniform>smaaEdge:SmaaEdgeParams;",NrA="fn smaaLuma(c:vec3f)->f32{return dot(c,vec3f(0.2126,0.7152,0.0722));}fn smaaEnc(c:f32)->f32{return select(1.055*pow(c,1.0/2.4)-0.055,c*12.92,c<=0.0031308);}fn smaaDetectLuma(c:vec3f)->f32{if(smaaEdge.srgb>0.5){return smaaLuma(vec3f(smaaEnc(clamp(c.r,0.0,1.0)),smaaEnc(clamp(c.g,0.0,1.0)),smaaEnc(clamp(c.b,0.0,1.0))));}return smaaLuma(c);}fn smaaFetch(uv:vec2f)->vec4f{return textureSampleLevel(sourceTextureSampler,sourceSampler,uv,0.0);}fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let ts=1.0/vec2f(textureDimensions(sourceTextureSampler));let l=smaaDetectLuma(color.rgb);let ll=smaaDetectLuma(smaaFetch(uv+vec2f(-ts.x,0.0)).rgb);let lt=smaaDetectLuma(smaaFetch(uv+vec2f(0.0,-ts.y)).rgb);let delta=vec2f(abs(l-ll),abs(l-lt));var edges=step(vec2f(smaaEdge.threshold),delta);if(edges.x+edges.y==0.0){return vec4f(0.0,0.0,0.0,1.0);}let lr=smaaDetectLuma(smaaFetch(uv+vec2f(ts.x,0.0)).rgb);let lb=smaaDetectLuma(smaaFetch(uv+vec2f(0.0,ts.y)).rgb);let ll2=smaaDetectLuma(smaaFetch(uv+vec2f(-2.0*ts.x,0.0)).rgb);let lt2=smaaDetectLuma(smaaFetch(uv+vec2f(0.0,-2.0*ts.y)).rgb);let d2=max(max(delta,vec2f(abs(l-lr),abs(l-lb))),vec2f(abs(ll-ll2),abs(lt-lt2)));let m=max(d2.x,d2.y);edges*=step(vec2f(m),2.0*delta);return vec4f(edges,0.0,1.0);}",GrA="struct SmaaWeightParams{maxSearch:f32,diag:f32,corner:f32,pad:f32}@group(0)@binding(2)var<uniform>smaaWeight:SmaaWeightParams;",FrA="fn smaaEdgeAt(uv:vec2f)->vec2f{return textureSampleLevel(sourceTextureSampler,sourceSampler,uv,0.0).rg;}fn smaaBothEdges(uv:vec2f)->bool{let e=smaaEdgeAt(uv);return e.x>0.5&&e.y>0.5;}fn smaaDiagRunBoth(uv:vec2f,ts:vec2f,dir:vec2f,maxSteps:f32)->f32{var d=0.0;loop{if(d>=maxSteps){break;}if(!smaaBothEdges(uv+ts*dir*(d+1.0))){break;}d=d+1.0;}return d;}fn smaaDiagRunLeft(uv:vec2f,ts:vec2f,dir:vec2f,maxSteps:f32)->f32{var d=0.0;loop{if(d>=maxSteps){break;}if(smaaEdgeAt(uv+ts*dir*(d+1.0)).x<=0.5){break;}d=d+1.0;}return d;}fn smaaSearchX(uv:vec2f,ts:vec2f,dir:f32,maxSteps:f32,selfLeft:f32)->f32{var d=0.0;var behind=selfLeft;loop{if(d>=maxSteps){break;}if(dir<0.0&&behind>0.5){break;}let s=smaaEdgeAt(uv+vec2f(ts.x*dir*(d+1.0),0.0));if(dir>0.0&&s.x>0.5){break;}if(s.y<0.5){break;}behind=s.x;d=d+1.0;}return d;}fn smaaSearchY(uv:vec2f,ts:vec2f,dir:f32,maxSteps:f32,selfTop:f32)->f32{var d=0.0;var behind=selfTop;loop{if(d>=maxSteps){break;}if(dir<0.0&&behind>0.5){break;}let s=smaaEdgeAt(uv+vec2f(0.0,ts.y*dir*(d+1.0)));if(dir>0.0&&s.y>0.5){break;}if(s.x<0.5){break;}behind=s.y;d=d+1.0;}return d;}fn smaaHeight(x:f32,len:f32,cNear:f32,cFar:f32)->f32{let h=max(len*0.5,1e-4);if(x<h){return cNear*0.5*max(0.0,1.0-x/h);}return cFar*0.5*max(0.0,1.0-(len-x)/h);}fn smaaAccum(p:f32,q:f32,hp:f32,hq:f32)->vec2f{if(q<=p){return vec2f(0.0);}let w=q-p;if(hp*hq>=0.0){let a=0.5*(hp+hq)*w;return vec2f(max(a,0.0),max(-a,0.0));}let t=hp/(hp-hq);let a1=0.5*hp*(w*t);let a2=0.5*hq*(w*(1.0-t));return vec2f(max(a1,0.0)+max(a2,0.0),max(-a1,0.0)+max(-a2,0.0));}fn smaaResolveCrossings(cNear:vec2f,cFar:vec2f)->vec2f{let near=step(vec2f(0.5),cNear);let far=step(vec2f(0.5),cFar);let raw=vec2f(near.x-near.y,far.x-far.y);let nearBoth=near.x+near.y>1.5;let farBoth=far.x+far.y>1.5;return vec2f(select(raw.x,-raw.y,nearBoth&&abs(raw.y)>0.5),select(raw.y,-raw.x,farBoth&&abs(raw.x)>0.5));}fn smaaCoveragePair(x0:f32,len:f32,cNear:vec2f,cFar:vec2f)->vec2f{let crossing=smaaResolveCrossings(cNear,cFar);let x1=x0+1.0;let m=clamp(len*0.5,x0,x1);let h0=smaaHeight(x0,len,crossing.x,crossing.y);let hm=smaaHeight(m,len,crossing.x,crossing.y);let h1=smaaHeight(x1,len,crossing.x,crossing.y);return smaaAccum(x0,m,h0,hm)+smaaAccum(m,x1,hm,h1);}fn smaaCornerAttenuation(dNear:f32,dFar:f32)->vec2f{let nearest=vec2f(step(dNear,dFar),step(dFar,dNear));return 0.75*nearest/max(nearest.x+nearest.y,1.0);}fn smaaHorizontalCornerFactors(lEnd:vec2f,rEnd:vec2f,ts:vec2f,d1:f32,d2:f32)->vec2f{let attenuation=smaaCornerAttenuation(d1,d2);let below=vec2f(smaaEdgeAt(lEnd+vec2f(0.0,ts.y)).x,smaaEdgeAt(rEnd+vec2f(0.0,ts.y)).x);let above=vec2f(smaaEdgeAt(lEnd+vec2f(0.0,-2.0*ts.y)).x,smaaEdgeAt(rEnd+vec2f(0.0,-2.0*ts.y)).x);return clamp(vec2f(1.0-dot(attenuation,below),1.0-dot(attenuation,above)),vec2f(0.0),vec2f(1.0));}fn smaaVerticalCornerFactors(tEnd:vec2f,bEnd:vec2f,ts:vec2f,d1:f32,d2:f32)->vec2f{let attenuation=smaaCornerAttenuation(d1,d2);let right=vec2f(smaaEdgeAt(tEnd+vec2f(ts.x,0.0)).y,smaaEdgeAt(bEnd+vec2f(ts.x,0.0)).y);let left=vec2f(smaaEdgeAt(tEnd+vec2f(-2.0*ts.x,0.0)).y,smaaEdgeAt(bEnd+vec2f(-2.0*ts.x,0.0)).y);return clamp(vec2f(1.0-dot(attenuation,right),1.0-dot(attenuation,left)),vec2f(0.0),vec2f(1.0));}fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let ts=1.0/vec2f(textureDimensions(sourceTextureSampler));let e=color.rg;var w=vec4f(0.0);let maxSteps=smaaWeight.maxSearch;var diagonal=false;if(smaaWeight.diag>0.5){let minRun=smaaWeight.diag;if(e.x>0.5&&e.y>0.5){let a=smaaDiagRunBoth(uv,ts,vec2f(-1.0,1.0),maxSteps);let b=smaaDiagRunBoth(uv,ts,vec2f(1.0,-1.0),maxSteps);if(a+b+1.0>=minRun){w.x=0.5;diagonal=true;}}if(!diagonal&&e.x>0.5){let a=smaaDiagRunLeft(uv,ts,vec2f(-1.0,-1.0),maxSteps);let b=smaaDiagRunLeft(uv,ts,vec2f(1.0,1.0),maxSteps);if(a+b+1.0>=minRun){w.z=0.5;diagonal=true;}}}if(!diagonal&&e.y>0.5){let d1=smaaSearchX(uv,ts,-1.0,maxSteps,e.x);let d2=smaaSearchX(uv,ts,1.0,maxSteps,e.x);let len=d1+d2+1.0;let lEnd=uv+vec2f(-ts.x*d1,0.0);let rEnd=uv+vec2f(ts.x*(d2+1.0),0.0);let lCross=vec2f(smaaEdgeAt(lEnd).x,smaaEdgeAt(lEnd+vec2f(0.0,-ts.y)).x);let rCross=vec2f(smaaEdgeAt(rEnd).x,smaaEdgeAt(rEnd+vec2f(0.0,-ts.y)).x);var c=smaaCoveragePair(d1,len,lCross,rCross);if(smaaWeight.corner>0.5){c*=smaaHorizontalCornerFactors(lEnd,rEnd,ts,d1,d2);}w.x=c.x;w.y=c.y;}if(!diagonal&&e.x>0.5){let d1=smaaSearchY(uv,ts,-1.0,maxSteps,e.y);let d2=smaaSearchY(uv,ts,1.0,maxSteps,e.y);let len=d1+d2+1.0;let tEnd=uv+vec2f(0.0,-ts.y*d1);let bEnd=uv+vec2f(0.0,ts.y*(d2+1.0));let tCross=vec2f(smaaEdgeAt(tEnd).y,smaaEdgeAt(tEnd+vec2f(-ts.x,0.0)).y);let bCross=vec2f(smaaEdgeAt(bEnd).y,smaaEdgeAt(bEnd+vec2f(-ts.x,0.0)).y);var c=smaaCoveragePair(d1,len,tCross,bCross);if(smaaWeight.corner>0.5){c*=smaaVerticalCornerFactors(tEnd,bEnd,ts,d1,d2);}w.z=c.x;w.w=c.y;}return w;}",mrA="@group(0)@binding(2)var smaaWeights:texture_2d<f32>;",brA="struct SmaaBlendParams{dominant:f32,p0:f32,p1:f32,p2:f32}@group(0)@binding(3)var<uniform>smaaBlend:SmaaBlendParams;",KrA="fn smaaFetch(uv:vec2f)->vec4f{return textureSampleLevel(sourceTextureSampler,sourceSampler,uv,0.0);}fn smaaWeightAt(uv:vec2f)->vec4f{return textureSampleLevel(smaaWeights,sourceSampler,uv,0.0);}fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{let ts=1.0/vec2f(textureDimensions(sourceTextureSampler));let wSelf=smaaWeightAt(uv);let wBelow=smaaWeightAt(uv+vec2f(0.0,ts.y));let wRight=smaaWeightAt(uv+vec2f(ts.x,0.0));let up=wSelf.x;let down=wBelow.y;let left=wSelf.z;let right=wRight.w;if(up+down+left+right<1e-4){return color;}var bUp=up;var bDown=down;var bLeft=left;var bRight=right;if(smaaBlend.dominant>0.5){if(max(left,right)>max(up,down)){bUp=0.0;bDown=0.0;}else{bLeft=0.0;bRight=0.0;}}let sum=bUp+bDown+bLeft+bRight;if(sum<1e-4){return color;}var acc=vec4f(0.0);acc+=(bUp/sum)*mix(color,smaaFetch(uv+vec2f(0.0,-ts.y)),clamp(bUp,0.0,1.0));acc+=(bDown/sum)*mix(color,smaaFetch(uv+vec2f(0.0,ts.y)),clamp(bDown,0.0,1.0));acc+=(bLeft/sum)*mix(color,smaaFetch(uv+vec2f(-ts.x,0.0)),clamp(bLeft,0.0,1.0));acc+=(bRight/sum)*mix(color,smaaFetch(uv+vec2f(ts.x,0.0)),clamp(bRight,0.0,1.0));return acc;}";function Pv(A,g,I,e){A._eager&&A._width===I&&A._height===e||(A._eager=!1,Se(A),A._descriptor.size={width:I,height:e},Kt(A,g),A._eager=!0)}function krA(A){if(A._width>0&&A._height>0)return{width:A._width,height:A._height};const g=A._descriptor.size,I="canvas"in g?g.canvas.width:g.width,e="canvas"in g?g.canvas.height:g.height;return{width:Math.max(1,I),height:Math.max(1,e)}}const UrA=112;function T3(A,g){return typeof A!="number"||!Number.isFinite(A)?g:Math.min(UrA,Math.max(1,Math.floor(A)))}const LrA=2;function Ov(A,g){return Math.max(LrA,T3(A,g))}function jv(A,g){return typeof A!="number"||!Number.isFinite(A)||A<=0?g:Math.min(.5,A)}function YrA(A,g,I){const e=A.name??"smaa",t=A.sourceTexture,i={threshold:jv(A.threshold,.05),sourceIsSrgb:A.sourceIsSrgb??!1,dominantAxisBlend:A.dominantAxisBlend??!0,maxSearchSteps:T3(A.maxSearchSteps,16),diagonalDetection:A.diagonalDetection??!1,minDiagonalRun:Ov(A.minDiagonalRun,4),cornerDetection:A.cornerDetection??!1},o=wt({lbl:`${e}-edges`,format:"rgba8unorm",samples:1,size:{width:1,height:1}}),Q=wt({lbl:`${e}-weights`,format:"rgba8unorm",samples:1,size:{width:1,height:1}}),r=Vt({name:`${e}-edges`,sourceTexture:t,targetTexture:o,sourceSamplingMode:"linear",_shader:{fragmentWGSL:NrA,uniformWGSL:RrA,uniformByteLength:16,writeUniforms(c){c[0]=i.threshold,c[1]=i.sourceIsSrgb?1:0}}},g,I),E=Vt({name:`${e}-weights`,sourceTexture:o,targetTexture:Q,sourceSamplingMode:"nearest",_shader:{fragmentWGSL:FrA,uniformWGSL:GrA,uniformByteLength:16,writeUniforms(c){c[0]=i.maxSearchSteps,c[1]=i.diagonalDetection?i.minDiagonalRun:0,c[2]=i.cornerDetection?1:0}}},g,I),n=Vt({name:`${e}-blend`,sourceTexture:t,targetTexture:A.targetTexture,sourceSamplingMode:"linear",alphaMode:A.alphaMode,viewport:A.viewport,clear:A.clear,_shader:{fragmentWGSL:KrA,extraTextureWGSL:mrA,extraTextures:[Q],uniformWGSL:brA,uniformByteLength:16,writeUniforms(c){c[0]=i.dominantAxisBlend?1:0}}},g,I),s={name:e,engine:g,scene:I,_passes:[],sourceTexture:t,sourceSamplingMode:A.sourceSamplingMode??"linear",targetTexture:A.targetTexture??null,alphaMode:A.alphaMode??0,viewport:A.viewport??null,clear:A.clear??!0,outputTexture:n.outputTexture,edgesTexture:o,weightsTexture:Q,get threshold(){return i.threshold},set threshold(c){i.threshold=jv(c,i.threshold)},get maxSearchSteps(){return i.maxSearchSteps},set maxSearchSteps(c){i.maxSearchSteps=T3(c,i.maxSearchSteps)},get diagonalDetection(){return i.diagonalDetection},set diagonalDetection(c){i.diagonalDetection=c},get minDiagonalRun(){return i.minDiagonalRun},set minDiagonalRun(c){i.minDiagonalRun=Ov(c,i.minDiagonalRun)},get cornerDetection(){return i.cornerDetection},set cornerDetection(c){i.cornerDetection=c},get sourceIsSrgb(){return i.sourceIsSrgb},set sourceIsSrgb(c){i.sourceIsSrgb=c},get dominantAxisBlend(){return i.dominantAxisBlend},set dominantAxisBlend(c){i.dominantAxisBlend=c},_edgeDetect:r,_blendWeights:E,_neighbourhood:n,_edges:o,_weights:Q,record(){r.sourceTexture=s.sourceTexture,n.sourceTexture=s.sourceTexture,n.targetTexture=s.targetTexture,n.viewport=s.viewport,n.clear=s.clear,n.alphaMode=s.alphaMode;const c=s.sourceTexture,{width:l,height:D}=krA(c);Pv(o,g,l,D),Pv(Q,g,l,D),r.record(),E.record(),n.record(),s.outputTexture=n.outputTexture},execute(){return(r.execute?.()??0)+(E.execute?.()??0)+(n.execute?.()??0)},updateUniforms(){r.updateUniforms(),E.updateUniforms(),n.updateUniforms()},dispose(){r.dispose(),E.dispose(),n.dispose(),o._eager=!1,Q._eager=!1,Se(o),Se(Q)}};return s}function lt(A){const g=A,I=g[0],e=g[1],t=g[2],i=g[3],o=g[4],Q=g[5],r=g[6],E=g[7],n=g[8],s=g[9],c=g[10],l=g[11],D=g[12],p=g[13],y=g[14],_=g[15],u=I*Q-e*o,f=I*r-t*o,h=I*E-i*o,w=e*r-t*Q,M=e*E-i*Q,S=t*E-i*r,R=n*p-s*D,N=n*y-c*D,F=n*_-l*D,G=s*y-c*p,m=s*_-l*p,K=c*_-l*y;let k=u*K-f*m+h*G+w*F-M*N+S*R;if(Math.abs(k)<1e-10)return null;k=1/k;const L=se();return L[0]=(Q*K-r*m+E*G)*k,L[1]=(t*m-e*K-i*G)*k,L[2]=(p*S-y*M+_*w)*k,L[3]=(c*M-s*S-l*w)*k,L[4]=(r*F-o*K-E*N)*k,L[5]=(I*K-t*F+i*N)*k,L[6]=(y*h-D*S-_*f)*k,L[7]=(n*S-c*h+l*f)*k,L[8]=(o*m-Q*F+E*R)*k,L[9]=(e*F-I*m-i*R)*k,L[10]=(D*M-p*h+_*u)*k,L[11]=(s*h-n*M-l*u)*k,L[12]=(Q*N-o*G-r*R)*k,L[13]=(I*G-e*N+t*R)*k,L[14]=(p*f-D*w-y*u)*k,L[15]=(n*w-s*f+c*u)*k,L}function x3(){return"struct SsHit{hit:bool,uv:vec2f,rayDist:f32,surfaceDist:f32}fn ssIsClearDepth(depth:f32)->bool{return depth<=0.0;}fn ssTexelUv(coord:vec2i,dims:vec2f)->vec2f{return(vec2f(coord)+vec2f(0.5))/dims;}fn ssClampCoord(coord:vec2i,dims:vec2f)->vec2i{return clamp(coord,vec2i(0,0),vec2i(dims)-vec2i(1,1));}fn ssUvToCoord(uv:vec2f,dims:vec2f)->vec2i{return ssClampCoord(vec2i(uv*dims),dims);}fn ssWorldFromDepth(uv:vec2f,depth:f32,invViewProj:mat4x4f)->vec3f{let ndc=vec3f(uv.x*2.0-1.0,1.0-uv.y*2.0,depth);let clip=invViewProj*vec4f(ndc,1.0);return clip.xyz/clip.w;}fn ssUvFromWorld(world:vec3f,viewProj:mat4x4f)->vec3f{let clip=viewProj*vec4f(world,1.0);let ndc=clip.xyz/clip.w;return vec3f(ndc.x*0.5+0.5,0.5-ndc.y*0.5,ndc.z);}fn ssBilinearDepth(uv:vec2f,dims:vec2f,depthTex:texture_depth_2d)->f32{let p=uv*dims-vec2f(0.5);let base=floor(p);let frac=p-base;let c00=ssClampCoord(vec2i(base),dims);let c10=ssClampCoord(vec2i(base)+vec2i(1,0),dims);let c01=ssClampCoord(vec2i(base)+vec2i(0,1),dims);let c11=ssClampCoord(vec2i(base)+vec2i(1,1),dims);let d00=textureLoad(depthTex,c00,0);let d10=textureLoad(depthTex,c10,0);let d01=textureLoad(depthTex,c01,0);let d11=textureLoad(depthTex,c11,0);let dx0=mix(d00,d10,frac.x);let dx1=mix(d01,d11,frac.x);return mix(dx0,dx1,frac.y);}fn ssNormalFromDepth(uv:vec2f,dims:vec2f,invViewProj:mat4x4f,depthTex:texture_depth_2d)->vec3f{let coord=ssUvToCoord(uv,dims);let dim=vec2i(dims);let cL=ssClampCoord(coord+vec2i(-1,0),dims);let cR=ssClampCoord(coord+vec2i(1,0),dims);let cU=ssClampCoord(coord+vec2i(0,-1),dims);let cD=ssClampCoord(coord+vec2i(0,1),dims);let dC=textureLoad(depthTex,coord,0);let dL=textureLoad(depthTex,cL,0);let dR=textureLoad(depthTex,cR,0);let dU=textureLoad(depthTex,cU,0);let dD=textureLoad(depthTex,cD,0);let pC=ssWorldFromDepth(ssTexelUv(coord,dims),dC,invViewProj);var pH:vec3f;if(coord.x<=0){pH=ssWorldFromDepth(ssTexelUv(cR,dims),dR,invViewProj)-pC;}else if(coord.x>=dim.x-1){pH=pC-ssWorldFromDepth(ssTexelUv(cL,dims),dL,invViewProj);}else if(abs(dL-dC)<abs(dR-dC)){pH=pC-ssWorldFromDepth(ssTexelUv(cL,dims),dL,invViewProj);}else{pH=ssWorldFromDepth(ssTexelUv(cR,dims),dR,invViewProj)-pC;}var pV:vec3f;if(coord.y<=0){pV=ssWorldFromDepth(ssTexelUv(cD,dims),dD,invViewProj)-pC;}else if(coord.y>=dim.y-1){pV=pC-ssWorldFromDepth(ssTexelUv(cU,dims),dU,invViewProj);}else if(abs(dU-dC)<abs(dD-dC)){pV=pC-ssWorldFromDepth(ssTexelUv(cU,dims),dU,invViewProj);}else{pV=ssWorldFromDepth(ssTexelUv(cD,dims),dD,invViewProj)-pC;}let n=cross(pH,pV);let n2=dot(n,n);if(n2<=1e-12){return vec3f(0.0,1.0,0.0);}return n*inverseSqrt(n2);}fn ssDualSurfaceHit(worldPos:vec3f,cameraPos:vec3f,viewProj:mat4x4f,invViewProj:mat4x4f,dims:vec2f,depthTex:texture_depth_2d,bias:f32,thickness:f32)->SsHit{let proj=ssUvFromWorld(worldPos,viewProj);let uv=proj.xy;if(uv.x<0.0||uv.x>1.0||uv.y<0.0||uv.y>1.0){return SsHit(false,uv,0.0,0.0);}let coord=ssUvToCoord(uv,dims);let discreteDepth=textureLoad(depthTex,coord,0);if(ssIsClearDepth(discreteDepth)){return SsHit(false,uv,0.0,0.0);}let continuousDepth=ssBilinearDepth(uv,dims,depthTex);let discreteWorld=ssWorldFromDepth(ssTexelUv(coord,dims),discreteDepth,invViewProj);let continuousWorld=ssWorldFromDepth(uv,continuousDepth,invViewProj);let rayDist=length(worldPos-cameraPos);let discreteDist=length(discreteWorld-cameraPos);let continuousDist=length(continuousWorld-cameraPos);let behindDiscrete=rayDist>discreteDist+bias;let behindContinuous=rayDist>continuousDist+bias;let withinThickness=(rayDist-discreteDist)<thickness&&(rayDist-continuousDist)<thickness;let hit=behindDiscrete&&behindContinuous&&withinThickness;return SsHit(hit,uv,rayDist,discreteDist);}fn ssHash(value:u32)->u32{var x=value;x=(x^(x>>16u))*2246822519u;x=(x^(x>>13u))*3266489917u;return x^(x>>16u);}fn ssScreenSpaceNoise(coord:vec2f)->f32{let p=vec2u(max(coord,vec2f(0.0))*256.0);return f32(ssHash(p.x*374761393u+p.y*668265263u))*2.3283064365386963e-10;}fn ssPhaseAngle(coord:vec2f,phase:f32)->f32{return fract(ssScreenSpaceNoise(coord)+phase);}"}function Vv(A,g){return Math.max(A,1/g)}function Wv(A,g,I){return g?1:Math.min(A+1,Math.max(1,I))}function zv(A,g){return g?0:A+1}function Zv(A,g){const I=Math.max(1,g);return A%I/I}function Xv(A){const g=A.firstAllocation||A.targetReallocated||A.sourceIdentityChanged||A.resetVersionChanged||A.enabledTransitionedOn||A.singularInverse;return{invalidateHistory:g,restartPhase:g}}function pi(A,g){return A!==g}function $v(A,g,I){return{width:Math.max(1,Math.round(A*I)),height:Math.max(1,Math.round(g*I))}}function AH(A){if(A._width>0&&A._height>0)return{width:A._width,height:A._height};const g=A._descriptor.size;return"canvas"in g?{width:g.canvas.width,height:g.canvas.height}:g}function gH(A,g,I){if(g&&g===I)throw new Error(`"${A}": targetTexture must differ from sourceTexture.`)}const JrA="struct SsTemporalParams{invViewProj:mat4x4f,currentView:mat4x4f,prevViewProj:mat4x4f,prevView:mat4x4f,effectDims:vec2f,depthDims:vec2f,params:vec4f}",IH=72,vrA=IH*4,HrA="@group(0)@binding(0)var ssLinearSampler:sampler;@group(0)@binding(1)var ssCurrentDepth:texture_depth_2d;@group(0)@binding(2)var ssRawTex:texture_2d<f32>;@group(0)@binding(3)var ssHistoryTex:texture_2d<f32>;@group(0)@binding(4)var<uniform>ssTemporal:SsTemporalParams;",TrA="struct SsVOut{@builtin(position)position:vec4f}@vertex fn ssResolveVertex(@builtin(vertex_index)i:u32)->SsVOut{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return SsVOut(vec4f(p,0,1));}",xrA="fn ssFusedGiFilter(coord:vec2i,effectDims:vec2f,depthDims:vec2f)->vec3f{let centerUv=ssTexelUv(coord,effectDims);let centerDepth=textureLoad(ssCurrentDepth,ssUvToCoord(centerUv,depthDims),0);let centerWorld=ssWorldFromDepth(centerUv,centerDepth,ssTemporal.invViewProj);let centerDist=(ssTemporal.currentView*vec4f(centerWorld,1.0)).z;var sum=textureLoad(ssRawTex,coord,0).rgb;var totalWeight=1.0;let offsets=array<vec2i,8>(vec2i(1,0),vec2i(-1,0),vec2i(0,1),vec2i(0,-1),vec2i(1,1),vec2i(-1,1),vec2i(1,-1),vec2i(-1,-1));let spatialWeights=array<f32,8>(0.75,0.75,0.75,0.75,0.5,0.5,0.5,0.5);for(var i=0;i<8;i=i+1){let nCoord=ssClampCoord(coord+offsets[i],effectDims);let nUv=ssTexelUv(nCoord,effectDims);let nDepth=textureLoad(ssCurrentDepth,ssUvToCoord(nUv,depthDims),0);if(ssIsClearDepth(nDepth)){continue;}let nWorld=ssWorldFromDepth(nUv,nDepth,ssTemporal.invViewProj);let nDist=(ssTemporal.currentView*vec4f(nWorld,1.0)).z;let agreement=max(0.0,1.0-abs(nDist-centerDist)/max(centerDist,1e-4));let w=spatialWeights[i]*agreement;sum=sum+textureLoad(ssRawTex,nCoord,0).rgb*w;totalWeight=totalWeight+w;}return sum/max(totalWeight,1e-4);}",qrA="fn ssFusedContactFilter(coord:vec2i,effectDims:vec2f,depthDims:vec2f)->f32{let centerUv=ssTexelUv(coord,effectDims);let centerDepth=textureLoad(ssCurrentDepth,ssUvToCoord(centerUv,depthDims),0);let centerWorld=ssWorldFromDepth(centerUv,centerDepth,ssTemporal.invViewProj);let centerDist=(ssTemporal.currentView*vec4f(centerWorld,1.0)).z;let offsets=array<vec2i,9>(vec2i(-1,-1),vec2i(0,-1),vec2i(1,-1),vec2i(-1,0),vec2i(0,0),vec2i(1,0),vec2i(-1,1),vec2i(0,1),vec2i(1,1));let spatialWeights=array<f32,9>(0.5,0.75,0.5,0.75,1.0,0.75,0.5,0.75,0.5);var sum=0.0;var totalWeight=0.0;for(var i=0;i<9;i=i+1){let tapCoord=ssClampCoord(coord+offsets[i],effectDims);let tapUv=ssTexelUv(tapCoord,effectDims);let tapDepth=textureLoad(ssCurrentDepth,ssUvToCoord(tapUv,depthDims),0);if(ssIsClearDepth(tapDepth)){continue;}let tapWorld=ssWorldFromDepth(tapUv,tapDepth,ssTemporal.invViewProj);let tapDist=(ssTemporal.currentView*vec4f(tapWorld,1.0)).z;let relErr=abs(tapDist-centerDist)/max(centerDist,0.001);if(relErr>0.04){continue;}let weight=spatialWeights[i]*(1.0-relErr/0.04);sum=sum+textureLoad(ssRawTex,tapCoord,0).r*weight;totalWeight=totalWeight+weight;}return sum/max(totalWeight,1e-4);}fn ssContactTemporalSample(coord:vec2i,effectDims:vec2f,depthDims:vec2f)->f32{let radius=max(ssTemporal.params.y,0.0);if(radius<=0.0){return ssFusedContactFilter(coord,effectDims,depthDims);}let phase=ssTemporal.params.z;let angle=phase*2.39996323;let radial=sqrt(fract(phase*0.754877666));let offset=vec2i(round(vec2f(cos(angle),sin(angle))*radial*radius));if(all(offset==vec2i(0))){return ssFusedContactFilter(coord,effectDims,depthDims);}let sampleCoord=ssClampCoord(coord+offset,effectDims);let centerUv=ssTexelUv(coord,effectDims);let sampleUv=ssTexelUv(sampleCoord,effectDims);let centerDepth=textureLoad(ssCurrentDepth,ssUvToCoord(centerUv,depthDims),0);let sampleDepth=textureLoad(ssCurrentDepth,ssUvToCoord(sampleUv,depthDims),0);if(ssIsClearDepth(sampleDepth)){return ssFusedContactFilter(coord,effectDims,depthDims);}let centerWorld=ssWorldFromDepth(centerUv,centerDepth,ssTemporal.invViewProj);let sampleWorld=ssWorldFromDepth(sampleUv,sampleDepth,ssTemporal.invViewProj);let centerDist=(ssTemporal.currentView*vec4f(centerWorld,1.0)).z;let sampleDist=(ssTemporal.currentView*vec4f(sampleWorld,1.0)).z;let relErr=abs(sampleDist-centerDist)/max(centerDist,0.001);if(relErr>0.04){return ssFusedContactFilter(coord,effectDims,depthDims);}return ssFusedContactFilter(sampleCoord,effectDims,depthDims);}";function PrA(A){const g=A==="color",I=g?"let rawValue=ssFusedGiFilter(coord,effectDims,depthDims);":"let rawValue=ssContactTemporalSample(coord,effectDims,depthDims);",e=g?"hist.rgb":"hist.r",t=g?"hist.a":"hist.g",i=g?"vec3f(0.0)":"0.0";return`${g?xrA:qrA} @fragment fn ssResolveFragment(v:SsVOut)->@location(0)vec4f{let coord=vec2i(v.position.xy);let effectDims=ssTemporal.effectDims;let depthDims=ssTemporal.depthDims;let uv=ssTexelUv(coord,effectDims);let depth=textureLoad(ssCurrentDepth,ssUvToCoord(uv,depthDims),0);if(ssIsClearDepth(depth)){return vec4f(0.0,0.0,0.0,0.0);}let worldPos=ssWorldFromDepth(uv,depth,ssTemporal.invViewProj);let curDist=(ssTemporal.currentView*vec4f(worldPos,1.0)).z;${I} var weight=ssTemporal.params.x;var historyValue=${i};var moved=false;let reproj=ssUvFromWorld(worldPos,ssTemporal.prevViewProj);if(reproj.x>=0.0&&reproj.x<=1.0&&reproj.y>=0.0&&reproj.y<=1.0){let expectedPrev=(ssTemporal.prevView*vec4f(worldPos,1.0)).z;let hist=textureSampleLevel(ssHistoryTex,ssLinearSampler,reproj.xy,0.0);let storedPrev=${t};let relErr=abs(expectedPrev-storedPrev)/max(expectedPrev,0.001);if(storedPrev>0.0&&relErr<=0.04){historyValue=${e};moved=length((reproj.xy-uv)*effectDims)>=1.0;}else{weight=1.0;}}else{weight=1.0;}if(moved){${g?"var mn=rawValue;var mx=rawValue;let nOffsets=array<vec2i,8>(vec2i(-1,-1),vec2i(0,-1),vec2i(1,-1),vec2i(-1,0),vec2i(1,0),vec2i(-1,1),vec2i(0,1),vec2i(1,1));for(var i=0;i<8;i=i+1){let n=textureLoad(ssRawTex,ssClampCoord(coord+nOffsets[i],effectDims),0).rgb;mn=min(mn,n);mx=max(mx,n);}historyValue=clamp(historyValue,mn,mx);":"var mn=rawValue;var mx=rawValue;let nOffsets=array<vec2i,8>(vec2i(-1,-1),vec2i(0,-1),vec2i(1,-1),vec2i(-1,0),vec2i(1,0),vec2i(-1,1),vec2i(0,1),vec2i(1,1));for(var i=0;i<8;i=i+1){let n=textureLoad(ssRawTex,ssClampCoord(coord+nOffsets[i],effectDims),0).r;mn=min(mn,n);mx=max(mx,n);}historyValue=clamp(historyValue,mn,mx);"}}return ${g?"vec4f(mix(historyValue,rawValue,weight),curDist)":"vec4f(mix(historyValue,rawValue,weight),curDist,0.0,0.0)"};}`}function OrA(A){return`${TrA} ${JrA} ${HrA} ${x3()} ${PrA(A)}`}const jrA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{return color;}";function eH(A){const{engine:g,kind:I,scene:e}=A,t=A.name,i=I==="color"?"rgba16float":"rg16float",o=wt({lbl:`${t}-stable`,format:i,samples:1,size:{width:1,height:1}}),Q=wt({lbl:`${t}-history`,format:i,samples:1,size:{width:1,height:1}});o._eager=!0,Q._eager=!0;const r=Vt({name:`${t}-history-copy`,sourceTexture:o,sourceSamplingMode:"nearest",targetTexture:Q,_shader:{fragmentWGSL:jrA}},g,e);let E=0,n=0,s=null,c=null,l=null,D=null;const p=new X(IH);let y=null,_=null,u=null;const f=new X(16),h=new X(16),w={label:`${t}-resolve`,colorAttachments:[{view:void 0,loadOp:"clear",storeOp:"store"}]};function M(){if(s)return;const R=g._device;c=R.createBindGroupLayout({label:`${t}-resolve-bgl`,entries:[{binding:0,visibility:NA.FRAGMENT,sampler:{type:"filtering"}},{binding:1,visibility:NA.FRAGMENT,texture:{sampleType:"depth"}},{binding:2,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:4,visibility:NA.FRAGMENT,buffer:{type:"uniform"}}]});const N=OrA(I),F=R.createShaderModule({label:`${t}-resolve`,code:N});s=R.createRenderPipeline({label:`${t}-resolve-pipeline`,layout:R.createPipelineLayout({label:`${t}-resolve-layout`,bindGroupLayouts:[c]}),vertex:{module:F,entryPoint:"ssResolveVertex"},fragment:{module:F,entryPoint:"ssResolveFragment",targets:[{format:i}]},primitive:{topology:"triangle-list"}}),D=R.createBuffer({label:`${t}-resolve-uniforms`,size:vrA,usage:SA.UNIFORM|SA.COPY_DST})}function S(R,N){const F=N._depthTexture.createView({aspect:"depth-only"});l=g._device.createBindGroup({label:`${t}-resolve-bind-group`,layout:c,entries:[{binding:0,resource:m1(g)},{binding:1,resource:F},{binding:2,resource:R._colorView},{binding:3,resource:Q._colorView},{binding:4,resource:{buffer:D}}]}),y=R._colorTexture,_=N._depthTexture,u=Q._colorTexture}return{get stableTexture(){return o},get historyTexture(){return Q},get allocated(){return E>0&&n>0},record(R,N){M();const F=Math.max(1,Math.floor(R)),G=Math.max(1,Math.floor(N));return F===E&&G===n?!1:(E=F,n=G,o._eager=!1,Q._eager=!1,Se(o),Se(Q),o._descriptor.size={width:F,height:G},Q._descriptor.size={width:F,height:G},Kt(o,g),Kt(Q,g),o._eager=!0,Q._eager=!0,r.record(),l=null,!0)},resolve(R){const N=pi(y,R.rawTexture._colorTexture),F=pi(_,R.depthTexture._depthTexture),G=pi(u,Q._colorTexture);(!l||N||F||G)&&S(R.rawTexture,R.depthTexture),p.fill(0),et(p,R.invViewProj,0),et(p,R.viewMatrix,16),et(p,f,32),et(p,h,48),p[64]=R.width,p[65]=R.height,p[66]=R.depthWidth,p[67]=R.depthHeight,p[68]=R.weight,p[69]=R.spatialRadius??0,p[70]=R.spatialPhase??0,g._device.queue.writeBuffer(D,0,p),w.colorAttachments=[{view:o._colorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}];const m=g._currentEncoder.beginRenderPass(w);m.setPipeline(s),m.setBindGroup(0,l),m.draw(3),m.end();const K=1+(r.execute?.()??0);return et(f,R.viewProjMatrix,0),et(h,R.viewMatrix,0),K},clearIdentity(){o._colorView&&g._currentEncoder.beginRenderPass({label:`${t}-clear-stable`,colorAttachments:[{view:o._colorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]}).end(),Q._colorView&&g._currentEncoder.beginRenderPass({label:`${t}-clear-history`,colorAttachments:[{view:Q._colorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]}).end()},dispose(){r.dispose(),o._eager=!1,Q._eager=!1,Se(o),Se(Q),s=null,l=null,c=null,D?.destroy(),D=null,y=null,_=null,u=null}}}const g1=(A,g,I)=>Math.min(I,Math.max(g,A));function VrA(A){return{resolutionScale:g1(A.resolutionScale??1,.25,1),intensity:g1(A.intensity??.6,0,4),tint:A.tint??[.35,.38,.48],stepCount:Math.round(g1(A.stepCount??8,1,64)),maxDistance:g1(A.maxDistance??.3,.001,1e3),thickness:g1(A.thickness??.35,.001,1e3),bias:g1(A.bias??.03,0,100),normalBias:g1(A.normalBias??.035,.001,100),temporalWeight:g1(A.temporalWeight??1/32,0,1),temporalSamples:Math.round(g1(A.temporalSamples??32,1,256)),spatialRadius:g1(A.spatialRadius??1.5,0,4)}}const tH=48,WrA=tH*4,zrA="struct SsContactParams{invViewProj:mat4x4f,viewProj:mat4x4f,rayDir:vec3f,stepCount:f32,cameraPos:vec3f,maxDistance:f32,outputDims:vec2f,depthDims:vec2f,bias:f32,normalBias:f32,thickness:f32,phase:f32}",ZrA="@group(0)@binding(0)var ssDepth:texture_depth_2d;@group(0)@binding(1)var<uniform>ssContact:SsContactParams;",XrA="fn ssTangentPlaneClearance(candidateWorld:vec3f,receiverWorld:vec3f,receiverNormal:vec3f)->f32{return dot(candidateWorld-receiverWorld,receiverNormal);}",$rA="struct SsCVOut{@builtin(position)position:vec4f}@vertex fn ssContactVertex(@builtin(vertex_index)i:u32)->SsCVOut{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return SsCVOut(vec4f(p,0,1));}",AEA="@fragment fn ssContactFragment(v:SsCVOut)->@location(0)vec4f{let coord=vec2i(v.position.xy);let uv=ssTexelUv(coord,ssContact.outputDims);let depth=textureLoad(ssDepth,ssUvToCoord(uv,ssContact.depthDims),0);if(ssIsClearDepth(depth)){return vec4f(0.0,0.0,0.0,0.0);}let worldPos=ssWorldFromDepth(uv,depth,ssContact.invViewProj);let normal=ssNormalFromDepth(uv,ssContact.depthDims,ssContact.invViewProj,ssDepth);let originPos=worldPos+normal*ssContact.bias;let stepCount=max(1u,u32(ssContact.stepCount));let stepLen=ssContact.maxDistance/f32(stepCount);let jitter=ssPhaseAngle(vec2f(coord),ssContact.phase);var occlusion=0.0;for(var i:u32=0u;i<stepCount;i=i+1u){let t=(f32(i)+jitter)*stepLen;let samplePos=originPos+ssContact.rayDir*t;let hit=ssDualSurfaceHit(samplePos,ssContact.cameraPos,ssContact.viewProj,ssContact.invViewProj,ssContact.depthDims,ssDepth,ssContact.bias,ssContact.thickness);if(hit.hit){let hitDepth=textureLoad(ssDepth,ssUvToCoord(hit.uv,ssContact.depthDims),0);let hitWorld=ssWorldFromDepth(hit.uv,hitDepth,ssContact.invViewProj);let clearance=ssTangentPlaneClearance(hitWorld,worldPos,normal);let clearanceFoot=ssContact.normalBias*0.35;if(clearance>clearanceFoot){let distFactor=clamp(1.0-t/ssContact.maxDistance,0.0,1.0);let penetration=clamp(1.0-abs(hit.rayDist-hit.surfaceDist)/max(ssContact.thickness,1e-4),0.0,1.0);let clearanceWeight=smoothstep(clearanceFoot,ssContact.normalBias,clearance);occlusion=max(occlusion,distFactor*penetration*clearanceWeight);}}}return vec4f(occlusion,0.0,0.0,0.0);}";function gEA(){return`${$rA} ${zrA} ${ZrA} ${x3()} ${XrA} ${AEA}`}const IEA="@group(0)@binding(2)var ssShadowTex:texture_2d<f32>;",eEA="struct SsContactCompositeParams{intensity:f32,enabled:f32,tintR:f32,tintG:f32,tintB:f32,p0:f32,p1:f32,p2:f32}@group(0)@binding(3)var<uniform>ssContactComposite:SsContactCompositeParams;",tEA="fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{if(ssContactComposite.enabled<0.5){return color;}let shadow=textureSample(ssShadowTex,sourceSampler,uv).r;let amount=clamp(shadow*ssContactComposite.intensity,0.0,1.0);let tint=vec3f(ssContactComposite.tintR,ssContactComposite.tintG,ssContactComposite.tintB);return vec4f(color.rgb*mix(vec3f(1.0),tint,amount),color.a);}";function CEA(A,g,I){const e=A.name??"screen-space-contact-shadows",t=A.sourceTexture,i=A.depthTexture??t;(t._descriptor.samples??1)!==1&&U(440,e),(i._descriptor.samples??1)!==1&&U(441,e),i._descriptor.dFormat||U(442,e),gH(`ScreenSpaceContactShadowsPostProcessTask "${e}"`,A.targetTexture,t);const o=VrA(A),Q={camera:A.camera,lightDirection:A.lightDirection,composition:A.composition??"multiply",resetVersion:A.resetVersion??0,...o},r=wt({lbl:`${e}-raw`,format:"r8unorm",samples:1,size:{width:1,height:1}}),E=eH({name:e,kind:"scalar",engine:g,scene:I});let n=null,s=null,c=null,l=null;const D=new X(tH);let p=null;const y=Q.composition==="none"?null:Vt({name:`${e}-composite`,sourceTexture:t,sourceSamplingMode:"linear",targetTexture:A.targetTexture??null,_shader:{extraTextureWGSL:IEA,extraTextures:[E.stableTexture],uniformWGSL:eEA,uniformBinding:3,uniformByteLength:32,writeUniforms(k){k[0]=K.intensity,k[1]=K.enabled?1:0,k[2]=K.tint[0],k[3]=K.tint[1],k[4]=K.tint[2]},fragmentWGSL:tEA}},g,I);let _=0,u=0,f=!0,h=!1,w,M,S=null,R=1,N=0,F=!1;function G(){if(n)return;const k=g._device;s=k.createBindGroupLayout({label:`${e}-producer-bgl`,entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"depth"}},{binding:1,visibility:NA.FRAGMENT,buffer:{type:"uniform"}}]});const L=k.createShaderModule({label:`${e}-producer`,code:gEA()});n=k.createRenderPipeline({label:`${e}-producer-pipeline`,layout:k.createPipelineLayout({label:`${e}-producer-layout`,bindGroupLayouts:[s]}),vertex:{module:L,entryPoint:"ssContactVertex"},fragment:{module:L,entryPoint:"ssContactFragment",targets:[{format:"r8unorm"}]},primitive:{topology:"triangle-list"}}),l=k.createBuffer({label:`${e}-producer-uniforms`,size:WrA,usage:SA.UNIFORM|SA.COPY_DST})}function m(){const k=i._depthTexture.createView({aspect:"depth-only"});c=g._device.createBindGroup({label:`${e}-producer-bind-group`,layout:s,entries:[{binding:0,resource:k},{binding:1,resource:{buffer:l}}]}),p=i._depthTexture}const K={name:e,engine:g,scene:I,_passes:[],sourceTexture:t,depthTexture:i,targetTexture:A.targetTexture??null,outputTexture:y?y.outputTexture:E.stableTexture,shadowTexture:E.stableTexture,enabled:!0,intensity:Q.intensity,tint:Q.tint,stepCount:Q.stepCount,maxDistance:Q.maxDistance,thickness:Q.thickness,bias:Q.bias,normalBias:Q.normalBias,temporalWeight:Q.temporalWeight,spatialRadius:Q.spatialRadius,resetVersion:Q.resetVersion,lightDirection:Q.lightDirection,record(){G();const k=AH(i),L=$v(k.width,k.height,Q.resolutionScale);(L.width!==_||L.height!==u)&&(_=L.width,u=L.height,r._eager=!1,Se(r),r._descriptor.size={width:_,height:u},Kt(r,g),r._eager=!0,c=null,h=!0),E.record(_,u)&&(h=!0),y?.record(),K.outputTexture=y?y.outputTexture:E.stableTexture},execute(){if(!K.enabled)return w&&E.clearIdentity(),w=!1,M=K.resetVersion,f=!1,h=!1,y?.updateUniforms(),y?.execute?.()??0;const L=Q.camera,H=KC(L,i._width||1,i._height||1),q=x1(L,H),CA=lt(q),eA=l1(L),Z=jQ(L);if(T1(L),!CA)return F=!0,w=!0,M=K.resetVersion,f=!1,h=!1,E.clearIdentity(),y?.updateUniforms(),y?.execute?.()??0;const O=pi(S,i._depthTexture),P=Xv({firstAllocation:f,targetReallocated:h,sourceIdentityChanged:O||F,resetVersionChanged:K.resetVersion!==M,enabledTransitionedOn:!w,singularInverse:!1});F=!1,R=Wv(R,P.invalidateHistory,Q.temporalSamples);const gA=Vv(g1(K.temporalWeight,0,1),R);N=zv(N,P.restartPhase);const yA=Zv(N,Q.temporalSamples);(pi(p,i._depthTexture)||!c)&&m();const cA=K.lightDirection,RA=Math.hypot(cA.x,cA.y,cA.z)||1,YA=Math.round(g1(K.stepCount,1,64)),Ag=g1(K.maxDistance,.001,1e3),lg=g1(K.bias,0,100),mA=g1(K.normalBias,.001,100),HA=g1(K.thickness,.001,1e3);D.fill(0),et(D,CA,0),et(D,q,16),D[32]=-cA.x/RA,D[33]=-cA.y/RA,D[34]=-cA.z/RA,D[35]=YA,D[36]=Z.x,D[37]=Z.y,D[38]=Z.z,D[39]=Ag,D[40]=_,D[41]=u,D[42]=i._width,D[43]=i._height,D[44]=lg,D[45]=mA,D[46]=HA,D[47]=yA,g._device.queue.writeBuffer(l,0,D);const Qg=g._currentEncoder.beginRenderPass({label:`${e}-producer`,colorAttachments:[{view:r._colorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});Qg.setPipeline(n),Qg.setBindGroup(0,c),Qg.draw(3),Qg.end();const Eg=1+E.resolve({width:_,height:u,depthWidth:i._width,depthHeight:i._height,rawTexture:r,depthTexture:i,invViewProj:CA,viewMatrix:eA,viewProjMatrix:q,weight:gA,spatialRadius:g1(K.spatialRadius,0,4),spatialPhase:N%Math.max(1,Q.temporalSamples)});return w=!0,M=K.resetVersion,S=i._depthTexture,f=!1,h=!1,y?.updateUniforms(),Eg+(y?.execute?.()??0)},dispose(){K._passes.length=0,y?.dispose(),E.dispose(),r._eager=!1,Se(r),n=null,c=null,s=null,l?.destroy(),l=null,p=null}};return K}const St=(A,g,I)=>Math.min(I,Math.max(g,A));function iEA(A){const g=St(A.fadeStart??20,0,1e5),I=Math.max(A.fadeEnd??60,g+.001);return{resolutionScale:St(A.resolutionScale??.5,.25,1),intensity:St(A.intensity??1,0,4),stepCount:Math.round(St(A.stepCount??8,1,64)),rayCount:Math.round(St(A.rayCount??1,1,8)),rayLength:St(A.rayLength??2,.001,1e3),thickness:St(A.thickness??.45,.001,1e3),bias:St(A.bias??.05,0,100),fadeStart:g,fadeEnd:I,edgeFade:St(A.edgeFade??.1,.001,.5),temporalWeight:St(A.temporalWeight??1/64,0,1),temporalSamples:Math.round(St(A.temporalSamples??64,1,256)),colorBleedGain:St(A.colorBleedGain??1,0,16),colorBleedMax:St(A.colorBleedMax??.45,0,1)}}const CH=48,oEA=CH*4,BEA="struct SsGiParams{invViewProj:mat4x4f,viewProj:mat4x4f,cameraPos:vec3f,stepCount:f32,rayLength:f32,thickness:f32,bias:f32,fadeStart:f32,fadeEnd:f32,edgeFade:f32,phase:f32,rayCount:f32,outputDims:vec2f,depthDims:vec2f}",QEA="@group(0)@binding(0)var ssGiDepth:texture_depth_2d;@group(0)@binding(1)var ssGiColorSampler:sampler;@group(0)@binding(2)var ssGiColor:texture_2d<f32>;@group(0)@binding(3)var<uniform>ssGi:SsGiParams;",rEA="fn ssCosineHemisphere(n:vec3f,u1:f32,u2:f32)->vec3f{let r=sqrt(u1);let theta=6.2831853*u2;let x=r*cos(theta);let y=r*sin(theta);let z=sqrt(max(0.0,1.0-u1));var up=vec3f(0.0,1.0,0.0);if(abs(n.y)>0.999){up=vec3f(1.0,0.0,0.0);}let tangent=normalize(cross(up,n));let bitangent=cross(n,tangent);return normalize(tangent*x+bitangent*y+n*z);}",EEA="struct SsGVOut{@builtin(position)position:vec4f}@vertex fn ssGiVertex(@builtin(vertex_index)i:u32)->SsGVOut{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return SsGVOut(vec4f(p,0,1));}",nEA="@fragment fn ssGiFragment(v:SsGVOut)->@location(0)vec4f{let coord=vec2i(v.position.xy);let uv=ssTexelUv(coord,ssGi.outputDims);let depth=textureLoad(ssGiDepth,ssUvToCoord(uv,ssGi.depthDims),0);if(ssIsClearDepth(depth)){return vec4f(0.0,0.0,0.0,0.0);}let worldPos=ssWorldFromDepth(uv,depth,ssGi.invViewProj);let normal=ssNormalFromDepth(uv,ssGi.depthDims,ssGi.invViewProj,ssGiDepth);let originPos=worldPos+normal*ssGi.bias;let stepCount=max(1u,u32(ssGi.stepCount));let stepLen=ssGi.rayLength/f32(stepCount);let rayCount=max(1u,min(8u,u32(ssGi.rayCount)));var colorSum=vec3f(0.0);for(var rayIndex:u32=0u;rayIndex<8u;rayIndex=rayIndex+1u){if(rayIndex>=rayCount){break;}let raySeed=f32(rayIndex);let seedOffset=vec2f(raySeed*37.719,raySeed*17.173);let u1=fract(ssPhaseAngle(vec2f(coord)+seedOffset,ssGi.phase)+raySeed*0.754877666);let u2=fract(ssScreenSpaceNoise(vec2f(coord)*1.7+vec2f(23.11,9.07)+seedOffset)+ssGi.phase*0.61803399);let dither=fract(ssScreenSpaceNoise(vec2f(coord)*0.731+vec2f(11.317,31.179)+seedOffset)+ssGi.phase*0.38196601);let rayDir=ssCosineHemisphere(normal,u1,u2);var rayColor=vec3f(0.0);for(var i:u32=0u;i<stepCount;i=i+1u){let t=(f32(i)+0.35+0.65*dither)*stepLen;let samplePos=originPos+rayDir*t;let hit=ssDualSurfaceHit(samplePos,ssGi.cameraPos,ssGi.viewProj,ssGi.invViewProj,ssGi.depthDims,ssGiDepth,ssGi.bias,ssGi.thickness);if(hit.hit){let edge=min(min(hit.uv.x,1.0-hit.uv.x),min(hit.uv.y,1.0-hit.uv.y))/max(ssGi.edgeFade,1e-4);let edgeFactor=clamp(edge,0.0,1.0);let distFade=clamp(1.0-smoothstep(ssGi.fadeStart,ssGi.fadeEnd,hit.rayDist),0.0,1.0);let litColor=textureSampleLevel(ssGiColor,ssGiColorSampler,hit.uv,0.0).rgb;rayColor=litColor*edgeFactor*distFade;break;}}colorSum=colorSum+rayColor;}return vec4f(colorSum/f32(rayCount),1.0);}";function sEA(){return`${EEA} ${BEA} ${QEA} ${x3()} ${rEA} ${nEA}`}const aEA="@group(0)@binding(2)var ssGiTex:texture_2d<f32>;",cEA="struct SsGiCompositeParams{intensity:f32,enabled:f32,colorBleedGain:f32,colorBleedMax:f32}@group(0)@binding(3)var<uniform>ssGiComposite:SsGiCompositeParams;";function lEA(A){return A==="color-bleed"?"fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{if(ssGiComposite.enabled<0.5){return color;}let illum=textureSample(ssGiTex,sourceSampler,uv).rgb;let luminance=dot(illum,vec3f(0.2126,0.7152,0.0722));let amount=min(ssGiComposite.intensity*min(luminance*ssGiComposite.colorBleedGain,1.0),ssGiComposite.colorBleedMax);return vec4f(color.rgb*mix(vec3f(1.0),illum/max(luminance,1e-4),amount),color.a);}":"fn applyPostProcess(color:vec4f,uv:vec2f)->vec4f{if(ssGiComposite.enabled<0.5){return color;}let illum=textureSample(ssGiTex,sourceSampler,uv).rgb;return vec4f(color.rgb+illum*ssGiComposite.intensity,color.a);}"}function DEA(A,g,I){const e=A.name??"screen-space-global-illumination",t=A.sourceTexture,i=A.depthTexture??t;(t._descriptor.samples??1)!==1&&U(443,e),(i._descriptor.samples??1)!==1&&U(444,e),i._descriptor.dFormat||U(445,e),gH(`ScreenSpaceGlobalIlluminationPostProcessTask "${e}"`,A.targetTexture,t);const o=iEA(A),Q={camera:A.camera,composition:A.composition??"additive",resetVersion:A.resetVersion??0,...o},r=wt({lbl:`${e}-raw`,format:"rgba16float",samples:1,size:{width:1,height:1}}),E=eH({name:e,kind:"color",engine:g,scene:I});let n=null,s=null,c=null,l=null;const D=new X(CH);let p=null,y=null;const _=Q.composition==="none"?null:Vt({name:`${e}-composite`,sourceTexture:t,sourceSamplingMode:"linear",targetTexture:A.targetTexture??null,_shader:{extraTextureWGSL:aEA,extraTextures:[E.stableTexture],uniformWGSL:cEA,uniformBinding:3,uniformByteLength:16,writeUniforms(H){H[0]=L.intensity,H[1]=L.enabled?1:0,H[2]=L.colorBleedGain,H[3]=L.colorBleedMax},fragmentWGSL:lEA(Q.composition==="color-bleed"?"color-bleed":"additive")}},g,I);let u=0,f=0,h=!0,w=!1,M,S,R=null,N=null,F=1,G=0,m=!1;function K(){if(n)return;const H=g._device;s=H.createBindGroupLayout({label:`${e}-producer-bgl`,entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"depth"}},{binding:1,visibility:NA.FRAGMENT,sampler:{type:"filtering"}},{binding:2,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:3,visibility:NA.FRAGMENT,buffer:{type:"uniform"}}]});const q=H.createShaderModule({label:`${e}-producer`,code:sEA()});n=H.createRenderPipeline({label:`${e}-producer-pipeline`,layout:H.createPipelineLayout({label:`${e}-producer-layout`,bindGroupLayouts:[s]}),vertex:{module:q,entryPoint:"ssGiVertex"},fragment:{module:q,entryPoint:"ssGiFragment",targets:[{format:"rgba16float"}]},primitive:{topology:"triangle-list"}}),l=H.createBuffer({label:`${e}-producer-uniforms`,size:oEA,usage:SA.UNIFORM|SA.COPY_DST})}function k(){const H=i._depthTexture.createView({aspect:"depth-only"});c=g._device.createBindGroup({label:`${e}-producer-bind-group`,layout:s,entries:[{binding:0,resource:H},{binding:1,resource:m1(g)},{binding:2,resource:t._colorView},{binding:3,resource:{buffer:l}}]}),p=i._depthTexture,y=t._colorTexture}const L={name:e,engine:g,scene:I,_passes:[],sourceTexture:t,depthTexture:i,targetTexture:A.targetTexture??null,outputTexture:_?_.outputTexture:E.stableTexture,illuminationTexture:E.stableTexture,enabled:!0,intensity:Q.intensity,stepCount:Q.stepCount,rayCount:Q.rayCount,rayLength:Q.rayLength,thickness:Q.thickness,bias:Q.bias,fadeStart:Q.fadeStart,fadeEnd:Q.fadeEnd,edgeFade:Q.edgeFade,temporalWeight:Q.temporalWeight,colorBleedGain:Q.colorBleedGain,colorBleedMax:Q.colorBleedMax,resetVersion:Q.resetVersion,record(){K();const H=AH(i),q=$v(H.width,H.height,Q.resolutionScale);(q.width!==u||q.height!==f)&&(u=q.width,f=q.height,r._eager=!1,Se(r),r._descriptor.size={width:u,height:f},Kt(r,g),r._eager=!0,c=null,w=!0),E.record(u,f)&&(w=!0),_?.record(),L.outputTexture=_?_.outputTexture:E.stableTexture},execute(){if(!L.enabled)return M&&E.clearIdentity(),M=!1,S=L.resetVersion,h=!1,w=!1,_?.updateUniforms(),_?.execute?.()??0;const q=Q.camera,CA=KC(q,i._width||1,i._height||1),eA=x1(q,CA),Z=lt(eA),O=l1(q),P=jQ(q);if(T1(q),!Z)return m=!0,M=!0,S=L.resetVersion,h=!1,w=!1,E.clearIdentity(),_?.updateUniforms(),_?.execute?.()??0;const gA=pi(R,i._depthTexture),yA=pi(N,t._colorTexture),cA=Xv({firstAllocation:h,targetReallocated:w,sourceIdentityChanged:gA||yA||m,resetVersionChanged:L.resetVersion!==S,enabledTransitionedOn:!M,singularInverse:!1});m=!1,F=Wv(F,cA.invalidateHistory,Q.temporalSamples);const RA=Vv(St(L.temporalWeight,0,1),F);G=zv(G,cA.restartPhase);const YA=Zv(G,Q.temporalSamples);(pi(p,i._depthTexture)||pi(y,t._colorTexture)||!c)&&k();const Ag=Math.round(St(L.stepCount,1,64)),lg=Math.round(St(L.rayCount,1,8)),mA=St(L.rayLength,.001,1e3),HA=St(L.thickness,.001,1e3),Qg=St(L.bias,0,100),Eg=St(L.fadeStart,0,1e5),kA=Math.max(L.fadeEnd,Eg+.001),ug=St(L.edgeFade,.001,.5);D.fill(0),et(D,Z,0),et(D,eA,16),D[32]=P.x,D[33]=P.y,D[34]=P.z,D[35]=Ag,D[36]=mA,D[37]=HA,D[38]=Qg,D[39]=Eg,D[40]=kA,D[41]=ug,D[42]=YA,D[43]=lg,D[44]=u,D[45]=f,D[46]=i._width,D[47]=i._height,g._device.queue.writeBuffer(l,0,D);const fg=g._currentEncoder.beginRenderPass({label:`${e}-producer`,colorAttachments:[{view:r._colorView,loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});fg.setPipeline(n),fg.setBindGroup(0,c),fg.draw(3),fg.end();const rg=1+E.resolve({width:u,height:f,depthWidth:i._width,depthHeight:i._height,rawTexture:r,depthTexture:i,invViewProj:Z,viewMatrix:O,viewProjMatrix:eA,weight:RA});return M=!0,S=L.resetVersion,R=i._depthTexture,N=t._colorTexture,h=!1,w=!1,_?.updateUniforms(),rg+(_?.execute?.()??0)},dispose(){L._passes.length=0,_?.dispose(),E.dispose(),r._eager=!1,Se(r),n=null,c=null,s=null,l?.destroy(),l=null,p=null,y=null,N=null}};return L}function pEA(A){A.lowerRadiusLimit!==void 0&&A.radius<A.lowerRadiusLimit?(A.radius=A.lowerRadiusLimit,A.inertialRadiusOffset=0):A.upperRadiusLimit!==void 0&&A.radius>A.upperRadiusLimit&&(A.radius=A.upperRadiusLimit,A.inertialRadiusOffset=0),A.lowerBetaLimit!==void 0&&A.beta<A.lowerBetaLimit?(A.beta=A.lowerBetaLimit,A.inertialBetaOffset=0):A.upperBetaLimit!==void 0&&A.beta>A.upperBetaLimit&&(A.beta=A.upperBetaLimit,A.inertialBetaOffset=0),A.lowerAlphaLimit!==void 0&&A.alpha<A.lowerAlphaLimit?(A.alpha=A.lowerAlphaLimit,A.inertialAlphaOffset=0):A.upperAlphaLimit!==void 0&&A.alpha>A.upperAlphaLimit&&(A.alpha=A.upperAlphaLimit,A.inertialAlphaOffset=0)}function yEA(A,g,I){"lowerAlphaLimit"in g&&(A.lowerAlphaLimit=g.lowerAlphaLimit),"upperAlphaLimit"in g&&(A.upperAlphaLimit=g.upperAlphaLimit),"lowerBetaLimit"in g&&(A.lowerBetaLimit=g.lowerBetaLimit),"upperBetaLimit"in g&&(A.upperBetaLimit=g.upperBetaLimit),"lowerRadiusLimit"in g&&(A.lowerRadiusLimit=g.lowerRadiusLimit),"upperRadiusLimit"in g&&(A.upperRadiusLimit=g.upperRadiusLimit);const e=()=>pEA(A);return A._clampToLimits=e,e(),()=>{A._clampToLimits===e&&(A._clampToLimits=void 0)}}function _EA(A,g,I,e){let Q=!1,r=!1,E=0,n=0;const s=new Map;let c=0,l=0;function D(N){e?.shouldHandlePointerDown&&!e.shouldHandlePointerDown(N)||(g.setPointerCapture(N.pointerId),E=N.clientX,n=N.clientY,N.button===0?(Q=!0,r=!1):N.button===2&&(Q=!1,r=!0))}function p(N){const F=N.clientX-E,G=N.clientY-n;if(E=N.clientX,n=N.clientY,!(s.size>=2)&&!(!Q&&!r)){if(e?.isExternalDragActive?.()){Q=!1,r=!1,A.inertialAlphaOffset=0,A.inertialBetaOffset=0,A.inertialPanningX=0,A.inertialPanningY=0;return}if(!e?.isExternalPickPending?.()){if(Q){const m=A.angularSensibility;A.inertialAlphaOffset-=F/m,A.inertialBetaOffset-=G/m}if(r){const m=A.panningSensibility;A.inertialPanningX+=-F/m,A.inertialPanningY+=G/m}}}}function y(N){g.releasePointerCapture(N.pointerId),Q=!1,r=!1}function _(N){N.preventDefault(),A.inertialRadiusOffset-=N.deltaY*A.radius/(A.wheelPrecision*1e3)}function u(N){N.preventDefault()}function f(N){for(let F=0;F<N.changedTouches.length;F++){const G=N.changedTouches[F];s.set(G.identifier,{x:G.clientX,y:G.clientY})}if(s.size>=2){Q=!1,r=!1;const F=s.values(),G=F.next().value,m=F.next().value;c=Math.hypot(m.x-G.x,m.y-G.y),l=A.radius,N.preventDefault()}}function h(N){for(let F=0;F<N.changedTouches.length;F++){const G=N.changedTouches[F];s.set(G.identifier,{x:G.clientX,y:G.clientY})}if(s.size>=2){N.preventDefault();const F=s.values(),G=F.next().value,m=F.next().value,K=Math.hypot(m.x-G.x,m.y-G.y);c>0&&K>0&&(A.radius=l*(c/K),A.radius=Math.max(.01,A.radius))}}function w(N){for(let F=0;F<N.changedTouches.length;F++)s.delete(N.changedTouches[F].identifier);if(s.size===1){const F=s.values().next().value;E=F.x,n=F.y}s.size<2&&(c=0)}function M(N){N.preventDefault()}function S(){if(A.inertialAlphaOffset!==0||A.inertialBetaOffset!==0){A.alpha+=A.inertialAlphaOffset,A.beta+=A.inertialBetaOffset;const N=.01;A.beta=Math.max(N,Math.min(Math.PI-N,A.beta)),A.inertialAlphaOffset*=A.inertia,A.inertialBetaOffset*=A.inertia,Math.abs(A.inertialAlphaOffset)<.001&&(A.inertialAlphaOffset=0),Math.abs(A.inertialBetaOffset)<.001&&(A.inertialBetaOffset=0)}if(A.inertialRadiusOffset!==0&&(A.radius-=A.inertialRadiusOffset,A.radius=Math.max(.01,A.radius),A.inertialRadiusOffset*=A.inertia,Math.abs(A.inertialRadiusOffset)<.001&&(A.inertialRadiusOffset=0)),A.inertialPanningX!==0||A.inertialPanningY!==0){const N=Math.cos(A.alpha),G=-Math.sin(A.alpha),m=N,K=A.radius*.001;A.target.x+=G*A.inertialPanningX*K,A.target.y+=A.inertialPanningY*K,A.target.z+=m*A.inertialPanningX*K,A.inertialPanningX*=A.panningInertia,A.inertialPanningY*=A.panningInertia,Math.abs(A.inertialPanningX)<1e-4&&(A.inertialPanningX=0),Math.abs(A.inertialPanningY)<1e-4&&(A.inertialPanningY=0)}}I&&I._beforeRender.push(S);const R=[["pointerdown",D],["pointermove",p],["pointerup",y],["wheel",_,{passive:!1}],["contextmenu",u],["touchstart",f,{passive:!1}],["touchmove",h,{passive:!1}],["touchend",w],["gesturestart",M,{passive:!1}],["gesturechange",M,{passive:!1}],["gestureend",M,{passive:!1}]];for(const[N,F,G]of R)g.addEventListener(N,F,G);return()=>{if(I){const N=I._beforeRender.indexOf(S);N>=0&&I._beforeRender.splice(N,1)}for(const[N,F]of R)g.removeEventListener(N,F)}}function q3(A){return A instanceof Error?A:new Error(String(A))}const iH=()=>{};function oH(A,g,I){return new Promise((e,t)=>{if(I?.aborted){t(q3(I.reason));return}let i=!1,o;const Q=()=>{if(i)return;i=!0;const E=A._beforeRender,n=E.indexOf(r);if(n>=0)for(E[n]=iH;E.length>0&&E[E.length-1]===iH;)E.pop();o&&I&&I.removeEventListener("abort",o)},r=E=>{if(i)return;const n=(E>0?E:1e3/60)/1e3;let s;try{s=g(n)}catch(c){Q(),t(q3(c));return}s||(Q(),e())};I&&(o=()=>{Q(),t(q3(I.reason))},I.addEventListener("abort",o)),A._beforeRender.push(r)})}function BH(A,g){return g<=0?1:A<=0?0:1-Math.pow(2,-A/g)}function QH(A,g,I){return A+(g-A)*I}function $R(A,g,I){const e=Math.PI*2;let t=(g-A)%e;return t>Math.PI?t-=e:t<-Math.PI&&(t+=e),A+t*I}function rH(A,g,I){return I.x=A.x+g.x,I.y=A.y+g.y,I.z=A.z+g.z,I}function uEA(A,g){return rH(A,g,A)}function EH(A,g,I){return I.x=A.x-g.x,I.y=A.y-g.y,I.z=A.z-g.z,I}function hEA(A,g){return EH(A,g,A)}function nH(A,g,I){return I.x=A.x*g,I.y=A.y*g,I.z=A.z*g,I}function fEA(A,g){return nH(A,g,A)}function sH(A,g,I){const e=A.y*g.z-A.z*g.y,t=A.z*g.x-A.x*g.z,i=A.x*g.y-A.y*g.x;return I.x=e,I.y=t,I.z=i,I}function dEA(A,g){return sH(A,g,A)}function aH(A,g,I=1e-10){const e=Math.hypot(A.x,A.y,A.z);if(e<=I)return g.x=0,g.y=0,g.z=0,g;const t=1/e;return g.x=A.x*t,g.y=A.y*t,g.z=A.z*t,g}function wEA(A,g=1e-10){return aH(A,A,g)}function cH(A,g){return g.x=-A.x,g.y=-A.y,g.z=-A.z,g}function MEA(A){return cH(A,A)}function P3(A,g,I,e){return e.x=A.x+(g.x-A.x)*I,e.y=A.y+(g.y-A.y)*I,e.z=A.z+(g.z-A.z)*I,e}function SEA(A,g,I){return P3(A,g,I,A)}const REA=.1,bF=.001;function O3(A,g,I){return g!==void 0&&A<g?g:I!==void 0&&A>I?I:A}function NEA(A,g,I,e,t){const i=t?.interpolationFactor??REA,o=I.alpha!==void 0&&!isNaN(I.alpha),Q=I.beta!==void 0&&!isNaN(I.beta),r=I.radius!==void 0&&!isNaN(I.radius),E=I.target!==void 0;let n=0,s=0,c=0;const l={x:0,y:0,z:0};let D=0,p=0,y=0;const _={x:0,y:0,z:0};let u=!0;return oH(g,h=>{if(u)u=!1,A.inertialAlphaOffset=0,A.inertialBetaOffset=0,A.inertialRadiusOffset=0,A.inertialPanningX=0,A.inertialPanningY=0,n=o?I.alpha:A.alpha,s=Q?I.beta:A.beta,c=r?I.radius:A.radius,l.x=E?I.target.x:A.target.x,l.y=E?I.target.y:A.target.y,l.z=E?I.target.z:A.target.z;else if(A.alpha!==D||A.beta!==p||A.radius!==y||A.target.x!==_.x||A.target.y!==_.y||A.target.z!==_.z)throw new Error("ArcRotate camera interpolation was interrupted.");const w=O3(n,A.lowerAlphaLimit,A.upperAlphaLimit),M=O3(s,A.lowerBetaLimit,A.upperBetaLimit),S=O3(c,A.lowerRadiusLimit,A.upperRadiusLimit),R=BH(h,i);A.alpha=$R(A.alpha,w,R),A.beta=$R(A.beta,M,R),A.radius=QH(A.radius,S,R),P3(A.target,l,R,A.target);const N=Math.abs(S)>1e-6?Math.abs(S):1,F=Math.abs($R(A.alpha,w,1)-A.alpha),G=Math.abs($R(A.beta,M,1)-A.beta),m=Math.abs(S-A.radius)/N,K=l.x-A.target.x,k=l.y-A.target.y,L=l.z-A.target.z,H=Math.hypot(K,k,L)/N;return F<bF&&G<bF&&m<bF&&H<bF?(A.alpha=w,A.beta=M,A.radius=S,A.target.x=l.x,A.target.y=l.y,A.target.z=l.z,!1):(D=A.alpha,p=A.beta,y=A.radius,_.x=A.target.x,_.y=A.target.y,_.z=A.target.z,!0)},e)}function j3(A,g){return lH(A,g,R3)}function lH(A,g,I){const e=g.x-A.x,t=g.y-A.y,i=g.z-A.z,o=se();function Q(){return S3(o,c.position,c.target,I),o}const r=so(Q),E=()=>r.markLocalDirty();let n=Math.atan2(e,i),s=Math.atan2(t,Math.sqrt(e*e+i*i));const c={position:new Ht(A.x,A.y,A.z,E),target:new Ht(g.x,g.y,g.z,E),fov:.8,nearPlane:1,farPlane:1e4,speed:2,angularSensitivity:2e3,inertia:.9,children:[],_viewCache:se(),_projCache:se(),_vpCache:se(),get parent(){return r.parent},set parent(l){r.parent=l},get worldMatrix(){return r.getWorldMatrix()},get worldMatrixVersion(){return r.getWorldMatrixVersion()}};return Object.defineProperty(c,"_yaw",{get(){return n},set(l){n!==l&&(n=l,E())},configurable:!0,enumerable:!0}),Object.defineProperty(c,"_pitch",{get(){return s},set(l){s!==l&&(s=l,E())},configurable:!0,enumerable:!0}),tQ(c,r),c}function GEA(A,g,I={x:0,y:1,z:0}){const e=new Ht(I.x,I.y,I.z,()=>OR(t)),t=lH(A,g,e);return Object.defineProperty(t,"upVector",{value:e,enumerable:!0}),t}function FEA(A,g,I){let e=0,t=0,i=0,o=0,Q=0,r=!1,E=0,n=0;const s=new Set;function c(f){(f.button===0||f.button===1||f.button===2)&&(g.setPointerCapture(f.pointerId),r=!0,E=f.clientX,n=f.clientY)}function l(f){if(!r)return;const h=f.clientX-E,w=f.clientY-n;E=f.clientX,n=f.clientY,Q+=h/A.angularSensitivity,o+=w/A.angularSensitivity}function D(f){g.releasePointerCapture(f.pointerId),r=!1}function p(f){f.preventDefault()}function y(f){s.add(f.code)}function _(f){s.delete(f.code)}function u(f){const h=Math.max(f,1),w=A.speed*Math.sqrt(h*h/1e5);(s.has("KeyW")||s.has("ArrowUp"))&&(i+=w),(s.has("KeyS")||s.has("ArrowDown"))&&(i-=w),(s.has("KeyA")||s.has("ArrowLeft"))&&(e-=w),(s.has("KeyD")||s.has("ArrowRight"))&&(e+=w),(s.has("Space")||s.has("PageUp"))&&(t+=w),(s.has("ShiftLeft")||s.has("ShiftRight")||s.has("PageDown"))&&(t-=w);const M=e!==0||t!==0||i!==0,S=o!==0||Q!==0;if(S){A._yaw+=Q,A._pitch-=o;const G=Math.PI/2-.01;A._pitch=Math.max(-G,Math.min(G,A._pitch))}if(M){const G=Math.cos(A._yaw),m=Math.sin(A._yaw),K=Math.cos(A._pitch),k=Math.sin(A._pitch);A.position.x+=m*K*i+G*e,A.position.y+=k*i+t,A.position.z+=G*K*i-m*e}if(M||S){const G=Math.cos(A._yaw),m=Math.sin(A._yaw),K=Math.cos(A._pitch);A.target.set(A.position.x+m*K,A.position.y+Math.sin(A._pitch),A.position.z+G*K)}const R=A.inertia,N=A.speed*.001,F=A.speed*.001;e*=R,t*=R,i*=R,o*=R,Q*=R,Math.abs(e)<N&&(e=0),Math.abs(t)<N&&(t=0),Math.abs(i)<N&&(i=0),Math.abs(o)<F&&(o=0),Math.abs(Q)<F&&(Q=0)}return I&&I._beforeRender.push(u),g.addEventListener("pointerdown",c),g.addEventListener("pointermove",l),g.addEventListener("pointerup",D),g.addEventListener("contextmenu",p),g.addEventListener("keydown",y),g.addEventListener("keyup",_),g.hasAttribute("tabindex")||(g.tabIndex=0),()=>{if(I){const f=I._beforeRender.indexOf(u);f>=0&&I._beforeRender.splice(f,1)}g.removeEventListener("pointerdown",c),g.removeEventListener("pointermove",l),g.removeEventListener("pointerup",D),g.removeEventListener("contextmenu",p),g.removeEventListener("keydown",y),g.removeEventListener("keyup",_)}}function mEA(A,g,I,e,t,i,o){const Q=o-i;A[0]=2/(I-g),A[1]=0,A[2]=0,A[3]=0,A[4]=0,A[5]=2/(t-e),A[6]=0,A[7]=0,A[8]=0,A[9]=0,A[10]=-1/Q,A[11]=0,A[12]=(g+I)/(g-I),A[13]=(t+e)/(e-t),A[14]=o/Q,A[15]=1}const bEA=["left","right","bottom","top"];function KF(A){A._projRev=(A._projRev??0)+1}function KEA(A,g){let I=g.halfHeight??1;const e={left:g.left??null,right:g.right??null,bottom:g.bottom??null,top:g.top??null},t={};Object.defineProperty(t,"halfHeight",{get(){return I},set(i){I!==i&&(I=i,KF(A))},enumerable:!0,configurable:!0});for(const i of bEA)Object.defineProperty(t,i,{get(){return e[i]},set(o){e[i]!==o&&(e[i]=o,KF(A))},enumerable:!0,configurable:!0});return t}function kEA(A,g,I){const e=A.ortho,t=e.halfHeight,i=t*g;mEA(I,e.left??-i,e.right??i,e.bottom??-t,e.top??t,A.nearPlane,A.farPlane)}function DH(A,g){GiA(kEA);const I=KEA(A,g??{});return A.ortho=I,KF(A),I}function pH(A){A.ortho=null;const g=A._projCache;g[12]=0,g[13]=0,g[15]=0,KF(A)}const UEA=Object.freeze(Object.defineProperty({__proto__:null,disableOrthographicCamera:pH,enableOrthographicCamera:DH},Symbol.toStringTag,{value:"Module"})),UC=.001;function yH(A){return{planetRadius:A,radiusMin:10,radiusMax:A*4,pitchMin:UC,pitchMax:Math.PI/2-.01,pitchDisabledRadiusScale:{x:2,y:4},yawMin:-1/0,yawMax:1/0}}function _H(A,g){const I=A.pitchDisabledRadiusScale;if(!I)return A.pitchMax;const e=I.x*A.planetRadius,t=I.y*A.planetRadius;if(g<=e)return A.pitchMax;if(g>=t)return A.pitchMin;const i=(g-e)/(t-e),o=i<0?0:i>1?1:i;return A.pitchMax*(1-o)+A.pitchMin*o}function uH(A,g,I,e){if(g>0){const i=(e??I)-A.radiusMin;return Math.min(g,Math.max(0,i))}const t=A.radiusMax-I;return Math.max(g,-Math.max(0,t))}const hH=Math.PI*2,LEA={x:0,y:0,z:1},YEA={x:1,y:0,z:0},V3=.998749218;function $Q(A){return A-hH*Math.floor((A+Math.PI)/hH)}function AN(A,g,I){return A<g?g:A>I?I:A}function Ar(A,g,I,e){const t=Math.hypot(A.x,A.y,A.z)||1;e.x=A.x/t,e.y=A.y/t,e.z=A.z/t,gr(e,LEA,g),MH(g)<UC&&gr(e,YEA,g),gN(g),gr(g,e,I),gN(I)}function fH(A,g,I,e){const t={x:0,y:0,z:0},i={x:0,y:0,z:0},o={x:0,y:0,z:0};Ar(I,t,i,o);const Q=Math.sin(g),r=Math.cos(g),E=Math.cos(A),n=Math.sin(A),s=i.x*E+t.x*n,c=i.y*E+t.y*n,l=i.z*E+t.z*n;return e.x=s*Q-o.x*r,e.y=c*Q-o.y*r,e.z=l*Q-o.z*r,gN(e)}function dH(A,g,I,e){const t={x:0,y:0,z:0},i={x:0,y:0,z:0},o={x:0,y:0,z:0};Ar(g,t,i,o);const r=-(A.x*o.x+A.y*o.y+A.z*o.z),E=Math.acos(AN(r,-1,1)),n=A.x+o.x*r,s=A.y+o.y*r,c=A.z+o.z*r,l=Math.sin(E);if(Math.abs(l)<UC)return e.x=I,e.y=E,e;const D=1/l,p=n*D,y=s*D,_=c*D,u=p*i.x+y*i.y+_*i.z,f=p*t.x+y*t.y+_*t.z;return e.x=Math.atan2(f,u),e.y=E,e}function wH(A){const g=Math.hypot(A.x,A.y,A.z);if(g>UC){const I=A.z/g;if(Math.abs(I)>V3){const e=AN(I,-V3,V3),t=Math.sqrt(1-e*e),i=Math.atan2(A.y,A.x);A.x=g*Math.cos(i)*t,A.y=g*Math.sin(i)*t,A.z=g*e}}return A}function JEA(A,g){A._setOrientation(g.yaw??A.yaw,g.pitch??A.pitch,g.radius??A.radius,g.center??A.center)}function vEA(A){const g=yH(A.planetRadius),I={x:A.planetRadius,y:0,z:0},e={x:0,y:0,z:0},t={x:0,y:1,z:0},i={x:0,y:0,z:0},o={yaw:0,pitch:0,radius:0},Q=se();function r(){const l={x:e.x+i.x,y:e.y+i.y,z:e.z+i.z};return S3(Q,e,l,t),Q}const E=so(r);function n(l,D,p,y){o.yaw=$Q(l),o.pitch=$Q(D),o.radius=p,I.x=y.x,I.y=y.y,I.z=y.z,o.yaw=AN(o.yaw,g.yawMin,g.yawMax),o.pitch=AN(o.pitch,g.pitchMin,_H(g,o.radius)),o.radius=AN(o.radius,g.radiusMin,g.radiusMax),wH(I);const _={x:0,y:0,z:0},u={x:0,y:0,z:0},f={x:0,y:0,z:0};Ar(I,_,u,f),fH(o.yaw,o.pitch,I,i);const h={x:0,y:0,z:0};if(gr(f,i,h),MH(h)<UC){const w=Math.cos(o.yaw),M=Math.sin(o.yaw),S={x:u.x*w+_.x*M,y:u.y*w+_.y*M,z:u.z*w+_.z*M};gr(S,i,h)}gN(h),gr(i,h,t),gN(t),e.x=I.x-i.x*o.radius,e.y=I.y-i.y*o.radius,e.z=I.z-i.z*o.radius,E.markLocalDirty()}const s={fov:.8,nearPlane:1,farPlane:A.planetRadius*16,children:[],limits:g,position:e,upVector:t,_lookAt:i,_setOrientation:n,_viewCache:se(),_projCache:se(),_vpCache:se(),get parent(){return E.parent},set parent(l){E.parent=l},get worldMatrix(){return E.getWorldMatrix()},get worldMatrixVersion(){return E.getWorldMatrixVersion()},get center(){return I},set center(l){n(o.yaw,o.pitch,o.radius,l)},get yaw(){return o.yaw},set yaw(l){l!==o.yaw&&n(l,o.pitch,o.radius,I)},get pitch(){return o.pitch},set pitch(l){l!==o.pitch&&n(o.yaw,l,o.radius,I)},get radius(){return o.radius},set radius(l){l!==o.radius&&n(o.yaw,o.pitch,l,I)}};tQ(s,E);const c=g.radiusMax!==1/0?g.radiusMax:A.planetRadius*4;return n(0,0,c,I),s}function gr(A,g,I){const e=A.y*g.z-A.z*g.y,t=A.z*g.x-A.x*g.z,i=A.x*g.y-A.y*g.x;I.x=e,I.y=t,I.z=i}function MH(A){return A.x*A.x+A.y*A.y+A.z*A.z}function gN(A){const g=Math.hypot(A.x,A.y,A.z);if(g>1e-10){const I=1/g;A.x*=I,A.y*=I,A.z*=I}return A}function HEA(A){if(A>=.5){const I=2*(1-A);return(1-I*I*I)*.5+.5}const g=2*A;return g*g*g*.5}function TEA(A,g,I,e){const t=Math.hypot(A.x,A.y,A.z)||1,i=Math.hypot(g.x,g.y,g.z)||1,o=A.x/t,Q=A.y/t,r=A.z/t,E=g.x/i,n=g.y/i,s=g.z/i;let c=o*E+Q*n+r*s;c=c<-1?-1:c>1?1:c;const l=Math.acos(c)*I;let D=E-o*c,p=n-Q*c,y=s-r*c;const _=Math.hypot(D,p,y);_>1e-9&&(D/=_,p/=_,y/=_);const u=Math.cos(l),f=Math.sin(l),h=t+(i-t)*I;e.x=(o*u+D*f)*h,e.y=(Q*u+p*f)*h,e.z=(r*u+y*f)*h}function SH(A,g,I){A._cancelFly?.();const e=Math.max(1,I.durationMs??1e3),t=I.centerHopScale??0,i=I.ease??HEA,o=A.yaw,Q=A.pitch,r=A.radius,E={x:A.center.x,y:A.center.y,z:A.center.z},n=I.yaw!==void 0?o+$Q($Q(I.yaw)-o):o,s=I.pitch!==void 0?$Q(I.pitch):Q,c=I.radius??r,l=I.center!==void 0,D=l?{x:I.center.x,y:I.center.y,z:I.center.z}:E,p=Math.hypot(D.x-E.x,D.y-E.y,D.z-E.z),y={x:0,y:0,z:0};let _=0;return new Promise(u=>{const f=w=>{_+=w>0?w:16.666666666666668;const M=Math.min(1,_/e),S=M>=1?1:i(M),R=o+(n-o)*S,N=Q+(s-Q)*S,F=r+(c-r)*S;let G=E;if(l){if(TEA(E,D,S,y),t>0){const K=t*p*Math.max(0,(S*S-S)/-.25),k=Math.hypot(y.x,y.y,y.z)||1,L=1+K/k;y.x*=L,y.y*=L,y.z*=L}G=y}A._setOrientation(R,N,F,G),M>=1&&h()};function h(){const w=g._beforeRender.indexOf(f);w>=0&&g._beforeRender.splice(w,1),A._cancelFly===h&&(A._cancelFly=void 0),u()}A._cancelFly=h,g._beforeRender.push(f)})}function W3(A,g,I,e,t){const i=lt(I);if(!i)return null;const o=2*A/e-1,Q=1-2*g/t,r=RH(i,o,Q,1),E=RH(i,o,Q,0),n=E[0]-r[0],s=E[1]-r[1],c=E[2]-r[2],l=Math.sqrt(n*n+s*s+c*c);if(l<1e-10)return null;const D=1/l;return{origin:r,direction:[n*D,s*D,c*D],length:l}}function RH(A,g,I,e){const t=A[0]*g+A[4]*I+A[8]*e+A[12],i=A[1]*g+A[5]*I+A[9]*e+A[13],o=A[2]*g+A[6]*I+A[10]*e+A[14],r=1/(A[3]*g+A[7]*I+A[11]*e+A[15]);return[t*r,i*r,o*r]}const NH=60,xEA=1e3/NH;function qEA(A,g,I=xEA){return Math.pow(A,g/I)}function PEA(A,g,I,e,t){if(e===0)return A;const i=qEA(I,e);let o=A*i;if(g!==0||t){const Q=1-I,r=Q>0?(1-i)/Q:1;o+=g/e*r}else Math.abs(o)<1e-6&&(o=0);return o}function OEA(A){return A<0?0:A>1?1:A}function jEA(A,g){const I=Math.hypot(A.x,A.y,A.z),e=Math.hypot(g.x,g.y,g.z),t=I>0?A.z/I:0,i=Math.sqrt(1-Math.min(1,t*t)),o=Math.sqrt(Math.abs(i)),Q=Math.max(e-I,UC),r=Math.max(1,I/Q);return OEA(r*o)}function VEA(A){return A*.01}function WEA(A,g,I,e){const t=e?.zoomToCursor??!0,i=e?.checkCollisions??!1,o=e?.doubleTapAnimationDurationMs??1e3,Q=e?.doubleTapEasingFunction??null,r=1,E=1,n=Math.PI/500,s=Math.PI/500,c=2,l=0,D=0,p=.9,y={x:0,y:0,z:0},_={x:0,y:0};let u=0,f=!1;const h={x:0,y:0,z:0},w={x:0,y:0};let M=0,S=0,R=1,N=1;const F={x:0,y:0,z:0},G={x:0,y:0};let m=0,K=null,k;const L={x:0,y:0,z:0},H={x:0,y:0,z:0},q={x:0,y:0,z:0},CA={x:0,y:0,z:0};let eA=0,Z=0,O="none",P=0,gA=0;const yA=new Set,cA=new Map;let RA=0,YA=0,Ag=0,lg=!1;const mA=20,HA=.05;function Qg(){const vA=g.getBoundingClientRect();return{width:vA.width||g.width,height:vA.height||g.height}}function Eg(vA){const ng=g.getBoundingClientRect();eA=vA.clientX-ng.left,Z=vA.clientY-ng.top}function kA(vA,ng){const{width:qA,height:Tg}=Qg(),jI=x1(A,qA/Tg),MI=W3(vA,ng,jI,qA,Tg);return MI?{origin:{x:MI.origin[0],y:MI.origin[1],z:MI.origin[2]},direction:{x:MI.direction[0],y:MI.direction[1],z:MI.direction[2]}}:null}function ug(vA,ng){const qA=A.limits.planetRadius,Tg=2*(vA.x*ng.x+vA.y*ng.y+vA.z*ng.z),jI=vA.x*vA.x+vA.y*vA.y+vA.z*vA.z-qA*qA,MI=Tg*Tg-4*jI;if(MI<0)return null;const VI=Math.sqrt(MI);let ie=(-Tg-VI)/2;return ie<0&&(ie=(-Tg+VI)/2),ie<0?null:{x:vA.x+ng.x*ie,y:vA.y+ng.y*ie,z:vA.z+ng.z*ie}}function fg(vA,ng){const qA=kA(vA,ng);if(!qA)return{hit:!1,point:null,ray:null};const Tg=ug(qA.origin,qA.direction);return{hit:!!Tg,point:Tg,ray:qA}}function rg(vA){return ug(A.position,vA)}function ag(vA,ng,qA){const Tg=Math.max(1e-5,Math.hypot(A.position.x,A.position.y,A.position.z)),jI=vA/Tg;H.x=A.position.x*jI,H.y=A.position.y*jI,H.z=A.position.z*jI;const MI={x:0,y:0,z:0},VI={x:0,y:0,z:0};Ar(H,MI,VI,L),qA[0]=MI.x,qA[1]=MI.y,qA[2]=MI.z,qA[3]=0,qA[4]=VI.x,qA[5]=VI.y,qA[6]=VI.z,qA[7]=0,qA[8]=L.x,qA[9]=L.y,qA[10]=L.z,qA[11]=0,qA[12]=H.x,qA[13]=H.y,qA[14]=H.z,qA[15]=1;const ie=lt(qA);if(!ie)return;const Zg=-(L.x*H.x+L.y*H.y+L.z*H.z),WI=L.x*ng.direction.x+L.y*ng.direction.y+L.z*ng.direction.z;if(Math.abs(WI)>1e-9){const De=-(L.x*ng.origin.x+L.y*ng.origin.y+L.z*ng.origin.z+Zg)/WI;if(De>=0){const pe=ng.origin.x+ng.direction.x*De,oe=ng.origin.y+ng.direction.y*De,Xe=ng.origin.z+ng.direction.z*De;zEA(pe,oe,Xe,ie,q)}}}function Rg(vA,ng){const qA=fg(vA,ng);if(qA.point&&qA.ray){k=Math.hypot(qA.point.x,qA.point.y,qA.point.z);const Tg=vg;ag(k,qA.ray,Tg),CA.x=q.x,CA.y=q.y,CA.z=q.z}else k=void 0}function UA(vA,ng){if(k===void 0)return;const qA=kA(vA,ng);if(!qA)return;const Tg=vg;ag(k,qA,Tg);let jI=q.x-CA.x,MI=q.y-CA.y,VI=q.z-CA.z;const ie=k*.1,Zg=Math.hypot(jI,MI,VI);if(Zg>ie){const oe=ie/Zg;jI*=oe,MI*=oe,VI*=oe}CA.x=q.x,CA.y=q.y,CA.z=q.z;const WI=jI*Tg[0]+MI*Tg[4]+VI*Tg[8],De=jI*Tg[1]+MI*Tg[5]+VI*Tg[9],pe=jI*Tg[2]+MI*Tg[6]+VI*Tg[10];H.x+=WI,H.y+=De,H.z+=pe,y.x-=WI,y.y-=De,y.z-=pe}function $A(){k=void 0}const vg=new Float32Array(16);function Jg(vA,ng){if(vA===0)return;u+=vA;const qA=fg(eA,Z);qA.hit&&qA.point&&t?K=qA.point:K=rg(A._lookAt)}function nI(){const vA=A.center.x+F.x,ng=A.center.y+F.y,qA=A.center.z+F.z,Tg=Math.hypot(vA,ng,qA)||1,MI=Math.hypot(A.center.x,A.center.y,A.center.z)/Tg;A._setOrientation(A.yaw,A.pitch,A.radius,{x:vA*MI,y:ng*MI,z:qA*MI})}function qI(){if(G.x===0&&G.y===0)return;const vA=G.x!==0?kF(A.pitch+G.x,0,.5*Math.PI-UC):A.pitch,ng=G.y!==0?A.yaw+G.y:A.yaw;A._setOrientation(ng,vA,A.radius,A.center)}function kI(vA,ng,qA){const Tg=A.limits,jI=vA.x-A.position.x,MI=vA.y-A.position.y,VI=vA.z-A.position.z,ie=Math.hypot(jI,MI,VI);if(ie<Tg.radiusMin)return qA.x=A.center.x,qA.y=A.center.y,qA.z=A.center.z,kF(A.radius-ng,Tg.radiusMin,Tg.radiusMax);const Zg=ng/ie,WI=A.position.x+jI*Zg,De=A.position.y+MI*Zg,pe=A.position.z+VI*Zg,oe=jI*Zg*A._lookAt.x+MI*Zg*A._lookAt.y+VI*Zg*A._lookAt.z,Xe=kF(A.radius-oe,Tg.radiusMin,Tg.radiusMax);return qA.x=WI+A._lookAt.x*Xe,qA.y=De+A._lookAt.y*Xe,qA.z=pe+A._lookAt.z*Xe,Xe}const pI={x:0,y:0,z:0};function Ye(){const vA=A.limits,ng=K?UF(A.position,K):void 0,qA=uH(vA,m,A.radius,ng);if(!(Math.abs(qA)<UC))if(K){const Tg=kI(K,qA,pI);A._setOrientation(A.yaw,A.pitch,Tg,pI)}else{const Tg=kF(A.radius-qA,vA.radiusMin,vA.radiusMax);A._setOrientation(A.yaw,A.pitch,Tg,A.center)}}let vI=!1;function Je(vA){const ng=vI&&!vA;if(vI=vA,!ng)return;const qA=rg(A._lookAt);if(!qA)return;const Tg=1/(Math.hypot(qA.x,qA.y,qA.z)||1);if(A._lookAt.x*-qA.x*Tg+A._lookAt.y*-qA.y*Tg+A._lookAt.z*-qA.z*Tg<=0)return;const MI=UF(A.position,qA);if(MI<=UC)return;const VI={x:0,y:0};dH(A._lookAt,qA,A.yaw,VI),A._setOrientation(VI.x,VI.y,MI,qA)}function Wg(){if(!i)return;const vA=A.limits.planetRadius+A.limits.radiusMin,ng=Math.hypot(A.position.x,A.position.y,A.position.z);if(ng>=vA||ng<1e-6)return;const qA=vA-ng,Tg=1/ng,jI=A.position.x*Tg*qA,MI=A.position.y*Tg*qA,VI=A.position.z*Tg*qA;A._setOrientation(A.yaw,A.pitch,A.radius,{x:A.center.x+jI,y:A.center.y+MI,z:A.center.z+VI})}function PI(vA){return vA>0?vA:S>0?S:1e3/NH}function jA(vA,ng,qA,Tg){return PEA(vA,ng,qA,PI(Tg),f)}function kg(){return k!==void 0}function tI(vA){const ng=A.center;if(y.x!==0||y.y!==0||y.z!==0?R=jEA(ng,A.position):R=1,kg()||_.x!==0||_.y!==0)N=0,M=0;else{const jI=K?UF(A.position,K):UF(A.position,ng);N=VEA(jI)}const qA=PI(vA);h.x=jA(h.x,y.x,l,vA),h.y=jA(h.y,y.y,l,vA),h.z=jA(h.z,y.z,l,vA);const Tg=r*E*R*qA;F.x=h.x*Tg,F.y=h.y*Tg,F.z=h.z*Tg,w.x=jA(w.x,_.x,D,vA),w.y=jA(w.y,_.y,D,vA),G.x=w.x*r*n*qA,G.y=w.y*r*s*qA,M=jA(M,u,p,vA),m=M*(r*c*N)*qA,vA>0&&(S=vA),u=0,y.x=y.y=y.z=0,_.x=_.y=0,f=!1}function UI(vA){Ke(),(y.x!==0||y.y!==0||y.z!==0||_.x!==0||_.y!==0||u!==0)&&A._cancelFly&&A._cancelFly(),tI(vA);let qA=!1;(F.x!==0||F.y!==0||F.z!==0)&&(nI(),qA=!0),(G.x!==0||G.y!==0)&&qI(),Math.abs(m)>UC&&(Ye(),qA=!0),Je(qA),Wg()}function Ke(){if(yA.size===0)return;f=!0;const vA=6,ng=4,qA=A.radius*.0015,Tg=yA.has("ControlLeft")||yA.has("ControlRight");if((yA.has("Equal")||yA.has("NumpadAdd"))&&(u+=ng,K=null),(yA.has("Minus")||yA.has("NumpadSubtract"))&&(u-=ng,K=null),Tg){yA.has("ArrowLeft")&&(_.y-=vA),yA.has("ArrowRight")&&(_.y+=vA),yA.has("ArrowUp")&&(_.x+=vA),yA.has("ArrowDown")&&(_.x-=vA);return}const jI={x:0,y:0,z:0},MI={x:0,y:0,z:0},VI={x:0,y:0,z:0};let ie=0,Zg=0;if(yA.has("ArrowUp")&&(ie+=1),yA.has("ArrowDown")&&(ie-=1),yA.has("ArrowRight")&&(Zg+=1),yA.has("ArrowLeft")&&(Zg-=1),ie!==0||Zg!==0){const WI=1/Math.hypot(ie,Zg);ie*=WI,Zg*=WI,Ar(A.center,jI,MI,VI),y.x+=(MI.x*ie+jI.x*Zg)*qA,y.y+=(MI.y*ie+jI.y*Zg)*qA,y.z+=(MI.z*ie+jI.z*Zg)*qA}}function Ge(vA){g.setPointerCapture(vA.pointerId),Eg(vA),P=vA.clientX,gA=vA.clientY,vA.button===0?(O="pan",Rg(eA,Z)):O="rotate"}function Ze(vA){Eg(vA);const ng=vA.clientX-P,qA=vA.clientY-gA;P=vA.clientX,gA=vA.clientY,!(cA.size>=2)&&O!=="none"&&(f=!0,O==="pan"?UA(eA,Z):O==="rotate"&&(_.y+=ng,_.x+=qA))}function st(vA){g.releasePointerCapture(vA.pointerId),O==="pan"&&$A(),O="none"}function Q1(vA){vA.preventDefault(),Eg(vA),Jg(-Math.sign(vA.deltaY))}function r1(vA){vA.preventDefault()}function _t(vA){if(vA.button!==0||vA.buttons!==0)return;vA.preventDefault();const ng=g.getBoundingClientRect(),qA=fg(vA.clientX-ng.left,vA.clientY-ng.top);qA.hit&&qA.point&&SH(A,I,{center:{x:qA.point.x,y:qA.point.y,z:qA.point.z},durationMs:o,ease:Q??void 0})}function k1(vA){yA.add(vA.code)}function at(vA){yA.delete(vA.code)}function ut(){const vA=cA.values(),ng=vA.next().value,qA=vA.next().value;return[ng,qA]}function z1(vA){for(let ng=0;ng<vA.changedTouches.length;ng++){const qA=vA.changedTouches[ng];cA.set(qA.identifier,{x:qA.clientX,y:qA.clientY})}if(cA.size>=2){vA.preventDefault(),O==="pan"&&$A(),O="none";const[ng,qA]=ut();RA=Math.hypot(qA.x-ng.x,qA.y-ng.y),YA=(ng.x+qA.x)/2,Ag=(ng.y+qA.y)/2,lg=!1}}function E1(vA){for(let Zg=0;Zg<vA.changedTouches.length;Zg++){const WI=vA.changedTouches[Zg];cA.has(WI.identifier)&&cA.set(WI.identifier,{x:WI.clientX,y:WI.clientY})}if(cA.size<2)return;vA.preventDefault(),f=!0;const[ng,qA]=ut(),Tg=Math.hypot(qA.x-ng.x,qA.y-ng.y),jI=(ng.x+qA.x)/2,MI=(ng.y+qA.y)/2,VI=g.getBoundingClientRect();eA=jI-VI.left,Z=MI-VI.top;const ie=Math.hypot(jI-YA,MI-Ag);if(!lg&&ie>mA&&(lg=!0,Rg(eA,Z)),lg)UA(eA,Z);else if(RA>0){const Zg=Tg-RA;if(Zg!==0){u+=Zg*HA;const WI=fg(eA,Z);K=WI.hit&&WI.point&&t?WI.point:rg(A._lookAt)}}RA=Tg}function mt(vA){for(let ng=0;ng<vA.changedTouches.length;ng++)cA.delete(vA.changedTouches[ng].identifier);if(cA.size<2&&(lg&&($A(),lg=!1),RA=0),cA.size===1){const ng=cA.values().next().value;P=ng.x,gA=ng.y}}function f1(vA){vA.preventDefault()}I._beforeRender.push(UI);const Z1=[[g,"pointerdown",Ge],[g,"pointermove",Ze],[g,"pointerup",st],[g,"wheel",Q1,{passive:!1}],[g,"contextmenu",r1],[g,"dblclick",_t],[g,"touchstart",z1,{passive:!1}],[g,"touchmove",E1,{passive:!1}],[g,"touchend",mt],[g,"gesturestart",f1,{passive:!1}],[g,"gesturechange",f1,{passive:!1}],[g,"gestureend",f1,{passive:!1}],[window,"keydown",k1],[window,"keyup",at]];for(const[vA,ng,qA,Tg]of Z1)vA.addEventListener(ng,qA,Tg);return()=>{const vA=I._beforeRender.indexOf(UI);vA>=0&&I._beforeRender.splice(vA,1);for(const[ng,qA,Tg]of Z1)ng.removeEventListener(qA,Tg)}}function kF(A,g,I){return A<g?g:A>I?I:A}function UF(A,g){return Math.hypot(A.x-g.x,A.y-g.y,A.z-g.z)}function zEA(A,g,I,e,t){const i=A*e[0]+g*e[4]+I*e[8]+e[12],o=A*e[1]+g*e[5]+I*e[9]+e[13],Q=A*e[2]+g*e[6]+I*e[10]+e[14],r=A*e[3]+g*e[7]+I*e[11]+e[15],E=r!==0?1/r:1;t.x=i*E,t.y=o*E,t.z=Q*E}function z3(A,g){A[0]=g[0],A[1]=g[1],A[2]=-g[2],A[3]=g[3],A[4]=g[4],A[5]=g[5],A[6]=-g[6],A[7]=g[7],A[8]=-g[8],A[9]=-g[9],A[10]=g[10],A[11]=-g[11],A[12]=g[12],A[13]=g[13],A[14]=-g[14],A[15]=g[15]}function ZEA(A,g){for(let I=0;I<16;I++)A[I]=g[I];A[8]=-A[8],A[9]=-A[9],A[10]=-A[10],A[11]=-A[11]}function XEA(A,g){const I=g.position,e=g.orientation;A.position.set(I.x,I.y,-I.z),A.rotationQuaternion.set(e.x,e.y,-e.z,-e.w)}function GH(A){const g=se();return g[0]=g[5]=g[10]=g[15]=1,{eye:A,fov:1,nearPlane:.1,farPlane:1e3,viewport:void 0,children:[],_viewCache:se(),_projCache:se(),_vpCache:se(),_world:g,_wmv:1,get worldMatrix(){return this._world},get worldMatrixVersion(){return this._wmv}}}function FH(A,g,I,e,t){const i=g.transform.matrix,o=A._world;z3(o,i),A._wmv=A._wmv+1,A.viewport=t;const Q=I/e*(t.width/t.height),r=A._projCache,E=g.projectionMatrix;ZEA(r,E),r[2]=r[3]-r[2],r[6]=r[7]-r[6],r[10]=r[11]-r[10],r[14]=r[15]-r[14],A._projVer=T1(A),A._projAspect=Q,A._viewVer=-1,A._vpVer=-1}function $EA(A){return{source:A,handedness:A.handedness,targetRayMode:A.targetRayMode,targetRayMatrix:new Float32Array(16),targetRayTracked:!1,gripMatrix:new Float32Array(16),gripTracked:!1,selecting:!1,squeezing:!1,gamepad:A.gamepad??null}}function mH(A,g){const I=[],e=new Map,t={get inputSources(){return t._list},_list:I,_bySource:e,_session:A,_cbs:g,_handlers:[]},i=E=>{const n=[];for(let s=0;s<E.length;s++){const c=E[s];if(e.has(c))continue;const l=$EA(c);e.set(c,l),I.push(l),n.push(l)}return n},o=E=>{const n=[];for(let s=0;s<E.length;s++){const c=E[s],l=e.get(c);if(!l)continue;e.delete(c);const D=I.indexOf(l);D>=0&&I.splice(D,1),n.push(l)}return n},Q=(E,n)=>{A.addEventListener(E,n),t._handlers.push({type:E,fn:n})};Q("inputsourceschange",(E=>{const n=i(E.added),s=o(E.removed);g.onInputSourcesChange?.(n,s)}));const r=(E,n,s)=>{Q(E,(c=>{const l=e.get(c.inputSource);l&&(E.endsWith("start")?l[n]=!0:E.endsWith("end")&&(l[n]=!1),s?.(l))}))};return r("selectstart","selecting",g.onSelectStart),r("select","selecting",g.onSelect),r("selectend","selecting",g.onSelectEnd),r("squeezestart","squeezing",g.onSqueezeStart),r("squeeze","squeezing",g.onSqueeze),r("squeezeend","squeezing",g.onSqueezeEnd),i(A.inputSources),t}function bH(A,g,I){for(const e of A._list){const t=g.getPose(e.source.targetRaySpace,I);t?(z3(e.targetRayMatrix,t.transform.matrix),e.targetRayTracked=!0):e.targetRayTracked=!1;const i=e.source.gripSpace;if(i){const o=g.getPose(i,I);o?(z3(e.gripMatrix,o.transform.matrix),e.gripTracked=!0):e.gripTracked=!1}else e.gripTracked=!1}}function KH(A){for(const{type:g,fn:I}of A._handlers)A._session.removeEventListener(g,I);A._handlers.length=0,A._list.length=0,A._bySource.clear()}function Z3(){return typeof navigator<"u"&&"xr"in navigator&&!!navigator.xr}function X3(){return typeof XRGPUBinding<"u"}async function AnA(A){if(!Z3()||!X3())return!1;try{return await navigator.xr.isSessionSupported(A)===!0}catch{return!1}}async function gnA(A,g={}){Z3()||U(606),X3()||U(607);const I=g.mode??"immersive-vr",e=A.surface.engine,t=e._device,i=g.referenceSpaceType??"local-floor",o=["webgpu",...g.requiredFeatures??[]],Q=[...g.optionalFeatures??[]];i!=="viewer"&&i!=="local"&&!o.includes(i)&&!Q.includes(i)&&Q.push(i);for(const n of g.features??[])for(const s of n.sessionFeatures??[])!o.includes(s)&&!Q.includes(s)&&Q.push(s);const r=await navigator.xr.requestSession(I,{requiredFeatures:o,optionalFeatures:Q});let E=null;try{let n;try{n=new XRGPUBinding(r,t)}catch(_){const u=_ instanceof Error?_.message:String(_);throw new Error(`Failed to construct XRGPUBinding: ${u}. Call enableXrCompatibleAdapter() before createEngine so its GPU adapter is XR-compatible.`,{cause:_})}const s=g.colorFormat??n.getPreferredColorFormat(),c=g.depthStencilFormat===void 0?"depth24plus":g.depthStencilFormat,l=n.createProjectionLayer({colorFormat:s,depthStencilFormat:c??void 0});await r.updateRenderState({layers:[l],depthNear:g.depthNear??.02,...g.depthFar!==void 0?{depthFar:g.depthFar}:{}});let D;try{D=await r.requestReferenceSpace(i)}catch(_){if(i==="local")throw _;D=await r.requestReferenceSpace("local")}const p=g.input===!1?null:mH(r,g.input??{}),y={mode:I,session:r,binding:n,layer:l,get referenceSpace(){return y._referenceSpace},scene:A,engine:e,colorFormat:s,depthFormat:c,get cameras(){return y._units.map(_=>_.camera)},input:p,_features:[],_referenceSpace:D,_units:[],_options:g,_rafId:0,_lastTime:0,_ended:!1,_canvasStopped:!1,_recovery:null};if(E=y,I==="immersive-ar"){const _=A.clearColor;y._savedClear={r:_.r,g:_.g,b:_.b,a:_.a},_.a=0}for(const _ of g.features??[])y._features.push(_.create(y));return r.addEventListener("end",()=>$3(y),{once:!0}),tnA(y),eF(e),y._canvasStopped=!0,y._rafId=r.requestAnimationFrame((_,u)=>UH(y,_,u)),y}catch(n){const s=E?._canvasStopped??!1;E&&$3(E,!1,!1);let c=n;try{await r.end()}catch(l){c=new AggregateError([n,l],"WebXR initialization failed and the session could not be ended.",{cause:l})}throw s&&JR(e).catch(l=>LF("canvas restart after initialization failure",l)),c}}async function InA(A){A._ended||await A.session.end()}function enA(A,g,I){const e=A._units[g];if(e)return e;const t=A.layer,i=wt({lbl:`xr-eye-${g}`,format:A.colorFormat,dFormat:A.depthFormat??void 0,samples:1,size:{width:t.textureWidth,height:t.textureHeight}});i._eager=!0;const o=GH(I),Q=Eo({name:`xr-eye-${g}`,rt:i,clr:!0,cam:o},A.engine,A.scene),r={rt:i,camera:o,task:Q,recorded:!1};return A._units[g]=r,r}function kH(A,g,I){const e=I.baseArrayLayer??0,t=I.baseMipLevel??0,i=A.some(o=>o.texture===g&&o.arrayLayer===e&&o.mipLevel===t);return A.push({texture:g,arrayLayer:e,mipLevel:t}),i}function UH(A,g,I){if(A._ended)return;A._rafId=A.session.requestAnimationFrame((D,p)=>UH(A,D,p));const e=I.getViewerPose(A.referenceSpace);A.input&&bH(A.input,I,A.referenceSpace),A._options.onFrame?.(A,I,g);for(const D of A._features)D.update?.(I,g);if(!e)return;const t=A.engine,i=A._lastTime?g-A._lastTime:0;A._lastTime=g;const o=t._device.createCommandEncoder({label:"xr-frame"}),Q=t._currentEncoder,r=t._currentDelta;t._currentEncoder=o,t._currentDelta=A.scene.fixedDeltaMs>0?A.scene.fixedDeltaMs:i,A.scene._update();const E=e.views,n=A.layer.textureWidth,s=A.layer.textureHeight,c=[],l=[];for(let D=0;D<E.length;D++){const p=E[D],y=A.binding.getViewSubImage(A.layer,p),_=enA(A,D,p.eye),u=y.getViewDescriptor(),f=y.colorTexture.createView(u),h=y.depthStencilTexture,w=h?h.createView(u):null,M=_.rt;M._colorTexture=y.colorTexture,M._colorView=f,M._depthTexture=h,M._depthView=w,M._width=n,M._height=s,_.recorded||(_.task.record(),_.recorded=!0),_.task._colorAttachment.view=f,_.task._config.clr=!kH(c,y.colorTexture,u);const S=_.task._renderPassDescriptor.depthStencilAttachment;if(S&&w&&h){S.view=w;const F=kH(l,h,u);S.depthLoadOp=F?"load":"clear",S.stencilLoadOp!==void 0&&(S.stencilLoadOp=F?"load":"clear")}const R=y.viewport,N={x:R.x/n,y:R.y/s,width:R.width/n,height:R.height/s};FH(_.camera,p,n,s,N),_.task.execute?.()}t._device.queue.submit([o.finish()]),gF(t),t._currentEncoder=Q,t._currentDelta=r}function LF(A,g){console.error(`Babylon Lite WebXR ${A} failed:`,g)}function $3(A,g=!0,I=!0){if(A._ended)return;A._ended=!0;const e=(i,o)=>{try{o()}catch(Q){LF(i,Q)}};e("frame cancellation",()=>{A._rafId&&(A.session.cancelAnimationFrame(A._rafId),A._rafId=0)}),e("recovery detachment",()=>{A._recovery?.disable(),A._recovery=null});for(let i=A._features.length-1;i>=0;i--)e("feature disposal",()=>A._features[i].dispose?.());A._features.length=0,A.input&&e("input disposal",()=>KH(A.input));for(const i of A._units)e("render-task disposal",()=>i.task.dispose());if(A._units.length=0,A._savedClear){const i=A.scene.clearColor;i.r=A._savedClear.r,i.g=A._savedClear.g,i.b=A._savedClear.b,i.a=A._savedClear.a,A._savedClear=void 0}I&&e("onEnd callback",()=>A._options.onEnd?.());const t=g&&A._canvasStopped;A._canvasStopped=!1,t&&JR(A.engine).catch(i=>LF("canvas restart",i))}function tnA(A){if(!A.engine._deviceLostRecovery?._registrations.length)return;let g=!1;A._recovery=iF(A.engine,{_kind:"xr-session",_recoverOrder:Number.MAX_SAFE_INTEGER,_onLost(){g=A._canvasStopped,$3(A,!1),A.session.end().catch(I=>LF("session end after device loss",I))},async _recover(){g&&await JR(A.engine)}})}function CnA(){HCA(()=>({xrCompatible:!0}))}function inA(A,g){const I=g.create(A);return A._features.push(I),I}function A4(A,g,I,e,t,i,o,Q,r){const E=A+t+r;let n;return E>0?(n=.5/Math.sqrt(E+1),{x:(Q-i)*n,y:(I-o)*n,z:(e-g)*n,w:.25/n}):A>t&&A>r?(n=2*Math.sqrt(1+A-t-r),{x:.25*n,y:(g+e)/n,z:(I+o)/n,w:(Q-i)/n}):t>r?(n=2*Math.sqrt(1+t-A-r),{x:(g+e)/n,y:.25*n,z:(i+Q)/n,w:(I-o)/n}):(n=2*Math.sqrt(1+r-A-t),{x:(I+o)/n,y:(i+Q)/n,z:.25*n,w:(e-g)/n})}function LH(A){return A4(A[0],A[4],A[8],A[1],A[5],A[9],A[2],A[6],A[10])}function IN(A){return A[0]*(A[5]*A[10]-A[6]*A[9])+A[1]*(A[6]*A[8]-A[4]*A[10])+A[2]*(A[4]*A[9]-A[5]*A[8])}function LC(A){const g=Math.hypot(A[0],A[1],A[2]),I=Math.hypot(A[4],A[5],A[6]),e=Math.hypot(A[8],A[9],A[10]),t=IN(A)<0?-I:I,i=g>1e-8?1/g:0,o=I>1e-8?1/t:0,Q=e>1e-8?1/e:0,r=A4(A[0]*i,A[4]*o,A[8]*Q,A[1]*i,A[5]*o,A[9]*Q,A[2]*i,A[6]*o,A[10]*Q),E=1/Math.hypot(r.x,r.y,r.z,r.w);return{translation:{x:A[12],y:A[13],z:A[14]},rotation:{x:r.x*E,y:r.y*E,z:r.z*E,w:r.w*E},scale:{x:g,y:t,z:e}}}class eN{_x;_y;_z;_w;_onDirty;_version=0;constructor(g,I,e,t,i){this._x=g,this._y=I,this._z=e,this._w=t,this._onDirty=i}get version(){return this._version}get x(){return this._x}set x(g){this._x!==g&&(this._x=g,this._version++,this._onDirty())}get y(){return this._y}set y(g){this._y!==g&&(this._y=g,this._version++,this._onDirty())}get z(){return this._z}set z(g){this._z!==g&&(this._z=g,this._version++,this._onDirty())}get w(){return this._w}set w(g){this._w!==g&&(this._w=g,this._version++,this._onDirty())}set(g,I,e,t){this._x=g,this._y=I,this._z=e,this._w=t,this._version++,this._onDirty()}copyFrom(g){this.set(g.x,g.y,g.z,g.w)}toArray(g,I=0){g[I]=this._x,g[I+1]=this._y,g[I+2]=this._z,g[I+3]=this._w}}function YF(A,g,I){const e=Math.cos(A*.5),t=Math.sin(A*.5),i=Math.cos(g*.5),o=Math.sin(g*.5),Q=Math.cos(I*.5),r=Math.sin(I*.5);return[t*i*Q+e*o*r,e*o*Q-t*i*r,e*i*r+t*o*Q,e*i*Q-t*o*r]}function YH(A,g,I,e){const t=2*(A*I+e*g),i=Math.asin(Math.max(-1,Math.min(1,t))),o=Math.atan2(-(2*(g*I-e*A)),1-2*(A*A+g*g)),Q=Math.atan2(-(2*(A*g-e*I)),1-2*(g*g+I*I));return[o,i,Q]}function JF(A){let g=0,I=0,e=0,t=-1;const i=()=>{if(A.version!==t){const Q=YH(A.x,A.y,A.z,A.w);g=Q[0],I=Q[1],e=Q[2],t=A.version}},o=(Q,r,E)=>{g=Q,I=r,e=E;const[n,s,c,l]=YF(Q,r,E);A.set(n,s,c,l),t=A.version};return{get x(){return i(),g},set x(Q){i(),o(Q,I,e)},get y(){return i(),I},set y(Q){i(),o(g,Q,e)},get z(){return i(),e},set z(Q){i(),o(g,I,Q)},set:o}}function onA(A,g=0,I=0,e=0,t=0,i=0,o=0,Q=1,r=1,E=1,n=1){return JH(A,null,g,I,e,t,i,o,Q,r,E,n)}function g4(A,g){return JH(A,g)}function JH(A,g,I=0,e=0,t=0,i=0,o=0,Q=0,r=1,E=1,n=1,s=1){const c=so(()=>u._localMatrix??lF(u.position,u.rotationQuaternion,u.scaling)),l=()=>{u._localMatrix||c.markLocalDirty()},D=new Ht(I,e,t,l),p=new eN(i,o,Q,r,l),y=JF(p),_=new Ht(E,n,s,l),u={name:A,children:[],position:D,rotationQuaternion:p,rotation:y,scaling:_,get parent(){return c.parent},set parent(f){c.parent=f},get worldMatrix(){return c.getWorldMatrix()},get worldMatrixVersion(){return c.getWorldMatrixVersion()}};return g&&(u._localMatrix=g),tQ(u,c),u}function tN(A,g=0,I=0,e=0,t=0,i=0,o=0,Q=1,r=1,E=1){const n=so(()=>lF(w.position,w.rotationQuaternion,w.scaling)),s=()=>n.markLocalDirty(),[c,l,D,p]=YF(t,i,o),y=new eN(c,l,D,p,s),_=y,u=JF(y),f=new Ht(g,I,e,s),h=new Ht(Q,r,E,s),w={...A,position:f,rotationQuaternion:_,rotation:u,scaling:h};return w.children||(w.children=[]),Object.defineProperty(w,"parent",{get(){return n.parent},set(M){n.parent=M},configurable:!0,enumerable:!0}),Object.defineProperty(w,"worldMatrix",{get(){return n.getWorldMatrix()},configurable:!0,enumerable:!1}),Object.defineProperty(w,"worldMatrixVersion",{get(){return n.getWorldMatrixVersion()},configurable:!0,enumerable:!1}),tQ(w,n),w}function I4(A,g,I,e,t,i,o,Q){const r=A._device,E=wI(A,g,SA.VERTEX),n=wI(A,I,SA.VERTEX),s=wI(A,e,SA.INDEX);let c;t&&t.length>0?c=wI(A,t,SA.VERTEX):(c=r.createBuffer({size:g.length/3*8,usage:SA.VERTEX,mappedAtCreation:!0}),c.unmap());let l=null;i&&i.length>0&&(l=wI(A,i,SA.VERTEX));const D=o&&o.length>0?wI(A,o,SA.VERTEX):null,p=Q&&Q.length>0?wI(A,Q,SA.VERTEX):null;return{positionBuffer:E,normalBuffer:n,uvBuffer:c,uv2Buffer:l,tangentBuffer:D,colorBuffer:p,hasUv:!!t&&t.length>0,hasUv2:!!i&&i.length>0,hasTangent:!!o&&o.length>0,hasColor:!!Q&&Q.length>0,indexBuffer:s,indexCount:e.length,indexFormat:"uint32"}}function yi(A,g){let I=1/0,e=1/0,t=1/0,i=-1/0,o=-1/0,Q=-1/0;if(g){const r=g[0],E=g[1],n=g[2],s=g[4],c=g[5],l=g[6],D=g[8],p=g[9],y=g[10],_=g[12],u=g[13],f=g[14];for(let h=0;h<A.length;h+=3){const w=A[h],M=A[h+1],S=A[h+2],R=r*w+s*M+D*S+_,N=E*w+c*M+p*S+u,F=n*w+l*M+y*S+f;R<I&&(I=R),R>i&&(i=R),N<e&&(e=N),N>o&&(o=N),F<t&&(t=F),F>Q&&(Q=F)}}else for(let r=0;r<A.length;r+=3){const E=A[r],n=A[r+1],s=A[r+2];E<I&&(I=E),E>i&&(i=E),n<e&&(e=n),n>o&&(o=n),s<t&&(t=s),s>Q&&(Q=s)}return[[I,e,t],[i,o,Q]]}function vH(A={}){const g=Math.max(3,A.segments??32),I=A.diameter??1,e=(A.diameterX??I)/2,t=(A.diameterY??I)/2,i=(A.diameterZ??I)/2,o=2+g,Q=2*o,r=(o+1)*(Q+1),E=o*Q*6,n=new X(r*3),s=new X(r*3),c=new X(r*2),l=new Vg(E);let D=0;for(let y=0;y<=o;y++){const _=y/o,u=_*Math.PI;for(let f=0;f<=Q;f++){const h=f/Q,w=h*Math.PI*2,M=Math.sin(u)*Math.cos(w),S=Math.cos(u),R=-Math.sin(u)*Math.sin(w);n[D*3]=e*M,n[D*3+1]=t*S,n[D*3+2]=i*R,s[D*3]=M,s[D*3+1]=S,s[D*3+2]=R,c[D*2]=h,c[D*2+1]=_,D++}}let p=0;for(let y=0;y<o;y++)for(let _=0;_<Q;_++){const u=y*(Q+1)+_,f=u+Q+1;l[p++]=u,l[p++]=u+1,l[p++]=f,l[p++]=f,l[p++]=u+1,l[p++]=f+1}return{positions:n,normals:s,uvs:c,indices:l,vertexCount:r,indexCount:E}}const BnA=[1260470181,3738583663,128],QnA=new X([0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0]),rnA=new X([1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,0]),EnA=new Vg([0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]);function e4(A=1){let g;if(typeof A=="number")g=[A,A,A];else{const{size:e=1,width:t=e,height:i=e,depth:o=e}=A;g=[t,i,o]}const I=new X(72);for(let e=0;e<I.length;e++){const t=BnA[e>>5]>>>(e&31)&1;I[e]=(t-.5)*g[e%3]}return{positions:I,normals:QnA.slice(),uvs:rnA.slice(),indices:EnA.slice(),vertexCount:24,indexCount:36}}function nnA(A={}){const g=A.diameter??1,I=A.thickness??.5,e=A.tessellation??16,t=g/2,i=I/2,o=e+1,Q=o*o,r=o*o*6,E=new X(Q*3),n=new X(Q*3),s=new X(Q*2),c=new Vg(r),l=Math.PI*2;let D=0,p=0,y=0;for(let _=0;_<=e;_++){const u=_*l/e-Math.PI/2,f=Math.cos(u),h=Math.sin(u);for(let w=0;w<=e;w++){const M=w*l/e+Math.PI,S=Math.cos(M),R=Math.sin(M),N=S*i,F=(N+t)*f,G=R*i,m=-(N+t)*h;E[D]=F,E[D+1]=G,E[D+2]=m,n[D]=S*f,n[D+1]=R,n[D+2]=-S*h,D+=3,s[p]=_/e,s[p+1]=1-w/e,p+=2;const K=(_+1)%o,k=(w+1)%o;c[y++]=_*o+w,c[y++]=_*o+k,c[y++]=K*o+w,c[y++]=_*o+k,c[y++]=K*o+k,c[y++]=K*o+w}}return{positions:E,normals:n,uvs:s,indices:c}}function t4(A,g){const I=A.length,e=new S1(I);for(let E=0;E<I;E++)e[E]=A[E];const t=new Vg(g.length);for(let E=0;E<g.length;E++)t[E]=g[E];const i=new S1(I),o=g.length/3|0;for(let E=0;E<o;E++){const n=t[E*3]*3,s=t[E*3+1]*3,c=t[E*3+2]*3,l=e[n]-e[s],D=e[n+1]-e[s+1],p=e[n+2]-e[s+2],y=e[c]-e[s],_=e[c+1]-e[s+1],u=e[c+2]-e[s+2];let f=D*u-p*_,h=p*y-l*u,w=l*_-D*y,M=Math.sqrt(f*f+h*h+w*w);M===0&&(M=1),f/=M,h/=M,w/=M,i[n]=i[n]+f,i[n+1]=i[n+1]+h,i[n+2]=i[n+2]+w,i[s]=i[s]+f,i[s+1]=i[s+1]+h,i[s+2]=i[s+2]+w,i[c]=i[c]+f,i[c+1]=i[c+1]+h,i[c+2]=i[c+2]+w}const Q=I/3|0,r=new Array(I);for(let E=0;E<Q;E++){const n=i[E*3],s=i[E*3+1],c=i[E*3+2];let l=Math.sqrt(n*n+s*s+c*c);l===0&&(l=1),r[E*3]=n/l,r[E*3+1]=s/l,r[E*3+2]=c/l}return r}function HH(A={}){const g=A.radius??2,I=A.tube??.5,e=A.radialSegments??32,t=A.tubularSegments??32,i=A.p??2,o=A.q??3,Q=[],r=[],E=[],n=c=>{const l=Math.cos(c),D=Math.sin(c),p=o/i*c,y=Math.cos(p),_=g*(2+y)*.5*l,u=g*(2+y)*D*.5,f=g*Math.sin(p)*.5;return[_,u,f]};for(let c=0;c<=e;c++){const D=c%e/e*2*i*Math.PI,p=n(D),y=n(D+.01),_=y[0]-p[0],u=y[1]-p[1],f=y[2]-p[2];let h=y[0]+p[0],w=y[1]+p[1],M=y[2]+p[2],S=u*M-f*w,R=f*h-_*M,N=_*w-u*h;h=R*f-N*u,w=N*_-S*f,M=S*u-R*_;let F=Math.sqrt(S*S+R*R+N*N);F===0&&(F=1),S/=F,R/=F,N/=F;let G=Math.sqrt(h*h+w*w+M*M);G===0&&(G=1),h/=G,w/=G,M/=G;for(let m=0;m<t;m++){const k=m%t/t*2*Math.PI,L=-I*Math.cos(k),H=I*Math.sin(k);Q.push(p[0]+L*h+H*S),Q.push(p[1]+L*w+H*R),Q.push(p[2]+L*M+H*N),r.push(c/e),r.push(m/t)}}for(let c=0;c<e;c++)for(let l=0;l<t;l++){const D=(l+1)%t,p=c*t+l,y=(c+1)*t+l,_=(c+1)*t+D,u=c*t+D;E.push(u),E.push(y),E.push(p),E.push(u),E.push(_),E.push(y)}const s=t4(Q,E);return{positions:new Float32Array(Q),normals:new Float32Array(s),uvs:new Float32Array(r),indices:new Uint32Array(E)}}function TH(A={}){const g=A.width??1,I=A.height??1,e=A.subdivisions??1,t=e+1,i=t,o=t*i,Q=e*e*6,r=new X(o*3),E=new X(o*3),n=new X(o*2),s=new Vg(Q);let c=0,l=0;for(let _=0;_<i;_++)for(let u=0;u<t;u++){const f=-g/2+u/e*g,h=-I/2+(1-_/e)*I;r[c]=f,r[c+1]=0,r[c+2]=h,E[c]=0,E[c+1]=1,E[c+2]=0,c+=3,n[l]=u/e,n[l+1]=1-_/e,l+=2}const D=A.uvScale?.[0]??1,p=A.uvScale?.[1]??1;if(D!==1||p!==1)for(let _=0;_<n.length;_+=2)n[_]=n[_]*D,n[_+1]=n[_+1]*p;let y=0;for(let _=0;_<e;_++)for(let u=0;u<e;u++){const f=_*t+u,h=f+1,w=(_+1)*t+u,M=w+1;s[y++]=M,s[y++]=h,s[y++]=f,s[y++]=w,s[y++]=M,s[y++]=f}return{positions:r,normals:E,uvs:n,indices:s}}function snA(A,g,I,e,t,i,o){const Q=t+1,r=Q,E=o-i;for(let s=0;s<r;s++)for(let c=0;c<Q;c++){const l=s*Q+c,D=c/t,p=s/t,y=D*(I-1)|0,u=((p*(e-1)|0)*I+y)*4,f=g[u]/255,h=g[u+1]/255,w=g[u+2]/255,M=f*.3+h*.59+w*.11;A.positions[l*3+1]=i+M*E}A.normals.fill(0);for(let s=0;s<A.indices.length;s+=3){const c=A.indices[s],l=A.indices[s+1],D=A.indices[s+2],p=A.positions,y=p[c*3],_=p[c*3+1],u=p[c*3+2],f=p[l*3],h=p[l*3+1],w=p[l*3+2],M=p[D*3],S=p[D*3+1],R=p[D*3+2],N=f-y,F=h-_,G=w-u,m=M-y,K=S-_,k=R-u;let L=-(F*k-G*K),H=-(G*m-N*k),q=-(N*K-F*m);const CA=Math.sqrt(L*L+H*H+q*q)||1;L/=CA,H/=CA,q/=CA;const eA=A.normals;eA[c*3]=eA[c*3]+L,eA[c*3+1]=eA[c*3+1]+H,eA[c*3+2]=eA[c*3+2]+q,eA[l*3]=eA[l*3]+L,eA[l*3+1]=eA[l*3+1]+H,eA[l*3+2]=eA[l*3+2]+q,eA[D*3]=eA[D*3]+L,eA[D*3+1]=eA[D*3+1]+H,eA[D*3+2]=eA[D*3+2]+q}const n=A.positions.length/3;for(let s=0;s<n;s++){const c=A.normals[s*3],l=A.normals[s*3+1],D=A.normals[s*3+2],p=Math.sqrt(c*c+l*l+D*D)||1;A.normals[s*3]=c/p,A.normals[s*3+1]=l/p,A.normals[s*3+2]=D/p}}async function anA(A,g={}){const I=g.subdivisions??1,e=g.minHeight??0,t=g.maxHeight??1,i=TH(g),o=new Image;o.crossOrigin="anonymous",await new Promise((n,s)=>{o.onload=()=>n(),o.onerror=c=>s(c instanceof Error?c:new Error(String(c))),o.src=A});const Q=document.createElement("canvas");Q.width=o.width,Q.height=o.height;const r=Q.getContext("2d");r.drawImage(o,0,0);const E=r.getImageData(0,0,o.width,o.height);return snA(i,E.data,o.width,o.height,I,e,t),i}function xH(A={}){const g=A.height??2;let I=A.diameterTop===0?0:A.diameterTop??A.diameter??1,e=A.diameterBottom===0?0:A.diameterBottom??A.diameter??1;I===0&&(I=1e-5),e===0&&(e=1e-5);const t=Math.max(3,(A.tessellation??24)|0),i=Math.max(1,(A.subdivisions??1)|0),o=1,Q=[],r=[],E=[],n=[],s=Math.PI*2*o/t,c=(e-I)/2/g;for(let p=0;p<=i;p++){const y=p/i,_=(y*(I-e)+e)/2;for(let u=0;u<=t;u++){const f=u*s,h=Math.cos(-f)*_,w=-g/2+y*g,M=Math.sin(-f)*_;let S,R,N;if(A.diameterTop===0&&p===i){const F=r.length-(t+1)*3;S=r[F],R=r[F+1],N=r[F+2]}else{S=h,N=M,R=Math.sqrt(S*S+N*N)*c;const F=1/Math.sqrt(S*S+R*R+N*N);S*=F,R*=F,N*=F}Q.push(h,w,M),r.push(S,R,N),E.push(u/t,y)}}const l=t;for(let p=0;p<i;p++)for(let y=0;y<t;y++){const _=p*(l+1)+y,u=(p+1)*(l+1)+y,f=p*(l+1)+(y+1),h=(p+1)*(l+1)+(y+1);n.push(_,u,f),n.push(h,f,u)}const D=p=>{const y=p?I/2:e/2;if(y===0)return;const _=Q.length/3,u=p?g/2:-g/2;Q.push(0,u,0),r.push(0,p?1:-1,0),E.push(.5,.5);for(let f=0;f<=t;f++){const h=Math.PI*2*f*o/t,w=Math.cos(-h),M=Math.sin(-h);Q.push(w*y,u,M*y),r.push(0,p?1:-1,0),E.push(w*.5+.5,M*.5+.5)}for(let f=0;f<t;f++)p?n.push(_,_+(f+2),_+(f+1)):n.push(_,_+(f+1),_+(f+2))};return D(!1),D(!0),{positions:new X(Q),normals:new X(r),uvs:new X(E),indices:new Vg(n)}}function qH(A={}){const g=Math.max(A.subdivisions?A.subdivisions:2,1)|0,I=Math.max(A.tessellation?A.tessellation:16,3)|0,e=Math.max(A.height?A.height:1,0),t=Math.max(A.radius?A.radius:.25,0),i=Math.max(A.capSubdivisions?A.capSubdivisions:6,1)|0,o=I,Q=g,r=Math.max(A.radiusTop?A.radiusTop:t,0),E=Math.max(A.radiusBottom?A.radiusBottom:t,0),n=e-(r+E),s=0,c=2*Math.PI,l=Math.max(A.topCapSubdivisions?A.topCapSubdivisions:i,1),D=Math.max(A.bottomCapSubdivisions?A.bottomCapSubdivisions:i,1),p=Math.acos((E-r)/e);let y=[];const _=[],u=[],f=[];let h=0;const w=[],M=n*.5,S=Math.PI*.5;let R,N;const F=Math.cos(p),G=Math.sin(p),m=r*G-E*G,K=M+r*F-(-M+E*F),k=Math.sqrt(m*m+K*K),L=r*p+k+E*(S-p);let H=0;for(N=0;N<=l;N++){const eA=[],Z=S-p*(N/l);H+=r*p/l;const O=Math.cos(Z),P=Math.sin(Z),gA=O*r;for(R=0;R<=o;R++){const yA=R/o,cA=yA*c+s,RA=Math.sin(cA),YA=Math.cos(cA);_.push(gA*RA,M+P*r,gA*YA),u.push(O*RA,P,O*YA),f.push(yA,1-H/L),eA.push(h),h++}w.push(eA)}const q=e-r-E+F*r-F*E,CA=G*(E-r)/q;for(N=1;N<=Q;N++){const eA=[];H+=k/Q;const Z=G*(N*(E-r)/Q+r);for(R=0;R<=o;R++){const O=R/o,P=O*c+s,gA=Math.sin(P),yA=Math.cos(P);_.push(Z*gA,M+F*r-N*q/Q,Z*yA);const cA=1/Math.sqrt(gA*gA+CA*CA+yA*yA);u.push(gA*cA,CA*cA,yA*cA),f.push(O,1-H/L),eA.push(h),h++}w.push(eA)}for(N=1;N<=D;N++){const eA=[],Z=S-p-(Math.PI-p)*(N/D);H+=E*p/D;const O=Math.cos(Z),P=Math.sin(Z),gA=O*E;for(R=0;R<=o;R++){const yA=R/o,cA=yA*c+s,RA=Math.sin(cA),YA=Math.cos(cA);_.push(gA*RA,-M+P*E,gA*YA),u.push(O*RA,P,O*YA),f.push(yA,1-H/L),eA.push(h),h++}w.push(eA)}for(R=0;R<o;R++)for(N=0;N<l+Q+D;N++){const eA=w[N][R],Z=w[N+1][R],O=w[N+1][R+1],P=w[N][R+1];y.push(eA,Z,P),y.push(Z,O,P)}return y=y.reverse(),{positions:new X(_),normals:new X(u),uvs:new X(f),indices:new Vg(y)}}function cnA(A={}){const g=A.size??1,I=A.width??g,e=A.height??g,t=I/2,i=e/2,o=new X([-t,-i,0,t,-i,0,t,i,0,-t,i,0]),Q=new X([0,0,-1,0,0,-1,0,0,-1,0,0,-1]),r=new X([0,0,1,0,1,1,0,1]),E=new Vg([0,1,2,0,2,3]);return{positions:o,normals:Q,uvs:r,indices:E}}function lnA(A={}){const g=A.radius??.5,I=A.tessellation??64,e=A.arc&&(A.arc<=0||A.arc>1)?1:A.arc??1,t=[],i=[],o=[];t.push(0,0,0),i.push(.5,.5);const Q=Math.PI*2*e,r=e===1?Q/I:Q/(I-1);let E=0;for(let c=0;c<I;c++){const l=Math.cos(E),D=Math.sin(E);t.push(g*l,g*D,0),i.push((l+1)/2,(1-D)/2),E+=r}e===1&&(t.push(t[3],t[4],t[5]),i.push(i[2],i[3]));const n=t.length/3;for(let c=1;c<n-1;c++)o.push(c+1,0,c);const s=new X(n*3);for(let c=0;c<n;c++)s[c*3+2]=-1;return{positions:new X(t),normals:s,uvs:new X(i),indices:new Vg(o)}}const PH=[{vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},{vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},{vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},{vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},{vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},{vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},{vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},{vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},{vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},{vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},{vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},{vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},{vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},{vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},{vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]}];function DnA(A={}){const g=A.type!==void 0&&(A.type<0||A.type>=PH.length)?0:A.type??0,I=A.size,e=A.sizeX??I??1,t=A.sizeY??I??1,i=A.sizeZ??I??1,o=A.flat??!0,Q=PH[g],r=Q.face.length,E=[],n=[],s=[];if(o){let l=0,D=0;const p=[];for(let y=0;y<r;y++){const _=Q.face[y],u=_.length,f=2*Math.PI/u;let h=.5*Math.tan(f/2),w=.5;for(let M=0;M<u;M++){const S=Q.vertex[_[M]];E.push(S[0]*e,S[1]*t,S[2]*i),p.push(l),l++,n.push(.5+h,w-.5+.5);const R=h*Math.cos(f)-w*Math.sin(f);w=h*Math.sin(f)+w*Math.cos(f),h=R}for(let M=0;M<u-2;M++)s.push(p[0+D],p[M+2+D],p[M+1+D]);D+=u}}else{for(let l=0;l<Q.vertex.length;l++){const D=Q.vertex[l];E.push(D[0]*e,D[1]*t,D[2]*i),n.push(0,0)}for(let l=0;l<r;l++){const D=Q.face[l];for(let p=0;p<D.length-2;p++)s.push(D[0],D[p+2],D[p+1])}}const c=t4(E,s);return{positions:new X(E),normals:new X(c),uvs:new X(n),indices:new Vg(s)}}function C4(A){return Math.sqrt(A.x*A.x+A.y*A.y+A.z*A.z)}function i4(A,g){return{x:A.x-g.x,y:A.y-g.y,z:A.z-g.z}}function o4(A){let g=A.pathArray;const I=A.closeArray||!1,e=A.closePath||!1,t=Math.floor(g[0].length/2);let i=A.offset??t;if(i=i>t?t:Math.floor(i),g.length<2){const G=[],m=[],K=g[0];for(let k=0;k<K.length-i;k++)G.push(K[k]),m.push(K[k+i]);g=[G,m]}const o=[],Q=[],r=[],E=[],n=[],s=[],c=[],l=[],D=[],p=e?1:0,y=I?1:0;let _=g[0].length,u=0;for(let G=0;G<g.length+y;G++){s[G]=0,E[G]=[0];const m=G===g.length?g[0]:g[G],K=m.length;_=_<K?_:K;let k=0;for(;k<K;){const L=m[k];if(o.push(L.x,L.y,L.z),k>0){const q=C4(i4(m[k],m[k-1]))+s[G];E[G].push(q),s[G]=q}k++}if(e){k--,o.push(m[0].x,m[0].y,m[0].z);const H=C4(i4(m[k],m[0]))+s[G];E[G].push(H),s[G]=H}l[G]=K+p,D[G]=u,u+=K+p}for(let G=0;G<_+p;G++){c[G]=0,n[G]=[0];for(let m=0;m<g.length-1+y;m++){const K=g[m],k=m===g.length-1?g[0]:g[m+1];let L,H;G===_?(L=K[0],H=k[0]):(L=K[G],H=k[G]);const CA=C4(i4(H,L))+c[G];n[G].push(CA),c[G]=CA}}for(let G=0;G<g.length+y;G++)for(let m=0;m<_+p;m++){const K=s[G]!==0?E[G][m]/s[G]:0,k=c[m]!==0?n[m][G]/c[m]:0;r.push(K,k)}let f=0,h=0,w=l[f]-1,M=l[f+1]-1,S=w<M?w:M,R=D[1]-D[0];const N=l.length-1;for(;h<=S&&f<N;)Q.push(h,h+R,h+1),Q.push(h+R+1,h+1,h+R),h+=1,h===S&&(f++,R=D[f+1]-D[f],w=l[f]-1,M=l[f+1]-1,h=D[f],S=w<M?w+h:M+h);const F=t4(o,Q);if(e)for(let G=0;G<g.length;G++){const m=D[G]*3,K=G+1<g.length?(D[G+1]-1)*3:F.length-3;F[m]=(F[m]+F[K])*.5,F[m+1]=(F[m+1]+F[K+1])*.5,F[m+2]=(F[m+2]+F[K+2])*.5;const k=Math.sqrt(F[m]*F[m]+F[m+1]*F[m+1]+F[m+2]*F[m+2])||1;F[m]=F[m]/k,F[m+1]=F[m+1]/k,F[m+2]=F[m+2]/k,F[K]=F[m],F[K+1]=F[m+1],F[K+2]=F[m+2]}if(I){let G=D[0]*3,m=D[g.length]*3;for(let K=0;K<_+p;K++){F[G]=(F[G]+F[m])*.5,F[G+1]=(F[G+1]+F[m+1])*.5,F[G+2]=(F[G+2]+F[m+2])*.5;const k=Math.sqrt(F[G]*F[G]+F[G+1]*F[G+1]+F[G+2]*F[G+2])||1;F[G]=F[G]/k,F[G+1]=F[G+1]/k,F[G+2]=F[G+2]/k,F[m]=F[G],F[m+1]=F[G+1],F[m+2]=F[G+2],G+=3,m+=3}}return{positions:new X(o),normals:new X(F),uvs:new X(r),indices:new Vg(Q)}}function D1(A,g){return{x:A.y*g.z-A.z*g.y,y:A.z*g.x-A.x*g.z,z:A.x*g.y-A.y*g.x}}function ao(A){return Math.sqrt(A.x*A.x+A.y*A.y+A.z*A.z)}function pC(A){const g=ao(A);if(g<1e-10)return{x:0,y:0,z:0};const I=1/g;return{x:A.x*I,y:A.y*I,z:A.z*I}}function iQ(A,g){return{x:A.x-g.x,y:A.y-g.y,z:A.z-g.z}}const B4=.001;function Q4(A,g,I){return Math.abs(A-g)<=I}function OH(A,g){let I=1,e=iQ(A[g+I],A[g]);for(;ao(e)===0&&g+I+1<A.length;)I++,e=iQ(A[g+I],A[g]);return e}function pnA(A,g){let I=1,e=iQ(A[g],A[g-I]);for(;ao(e)===0&&g>I+1;)I++,e=iQ(A[g],A[g-I]);return e}function ynA(A,g){let I,e=ao(A);if(e===0&&(e=1),g===null){let t;Q4(Math.abs(A.y)/e,1,B4)?Q4(Math.abs(A.x)/e,1,B4)?Q4(Math.abs(A.z)/e,1,B4)?t=CQ(0,0,0):t=CQ(0,0,1):t=CQ(1,0,0):t=CQ(0,-1,0),I=D1(A,t)}else{const t=D1(A,g);I=D1(t,A)}return pC(I)}function jH(A,g=null){const I=A.length,e=new Array(I),t=new Array(I),i=new Array(I),o=new Array(I);if(I<2)return{tangents:e,normals:t,binormals:i,distances:o};e[0]=pC(OH(A,0)),e[I-1]=pC(iQ(A[I-1],A[I-2]));const Q=pC(ynA(e[0],g));t[0]=Q,i[0]=pC(D1(e[0],t[0])),o[0]=0;for(let r=1;r<I;r++){const E=pnA(A,r);if(r<I-1){const l=OH(A,r),D={x:E.x+l.x,y:E.y+l.y,z:E.z+l.z};e[r]=pC(D)}o[r]=o[r-1]+ao(iQ(A[r],A[r-1]));const n=e[r],s=i[r-1];let c=D1(s,n);if(ao(c)===0){const l=t[r-1];c={x:l.x,y:l.y,z:l.z}}else c=pC(c);t[r]=c,i[r]=pC(D1(n,c))}return{tangents:e,normals:t,binormals:i,distances:o}}const oQ=0,r4=1,CN=2,iN=3;function _nA(A,g,I){const e=Math.cos(I),t=Math.sin(I),i=g.x*A.x+g.y*A.y+g.z*A.z,o=g.y*A.z-g.z*A.y,Q=g.z*A.x-g.x*A.z,r=g.x*A.y-g.y*A.x;return{x:A.x*e+o*t+g.x*i*(1-e),y:A.y*e+Q*t+g.y*i*(1-e),z:A.z*e+r*t+g.z*i*(1-e)}}function unA(A){const g=A.path,I=A.radius??1,e=(A.tessellation??64)|0,t=A.radiusFunction??null;let i=A.cap??oQ;i=i<0||i>3?oQ:i;const o=A.arc&&(A.arc<=0||A.arc>1)?1:A.arc??1,Q=jH(g),{tangents:r,normals:E,distances:n}=Q,c=Math.PI*2/e*o,l=[];let D=i===oQ||i===CN?0:2;for(let y=0;y<g.length;y++){const _=t?t(y,n[y]):I,u=[],f=E[y],h=r[y];for(let w=0;w<e;w++){const M=_nA(f,h,c*w);u.push({x:M.x*_+g[y].x,y:M.y*_+g[y].y,z:M.z*_+g[y].z})}l[D]=u,D++}const p=(y,_)=>{const u=[];for(let f=0;f<y;f++)u.push(g[_]);return u};return(i===r4||i===iN)&&(l[0]=p(e,0),l[1]=l[2].slice(0)),(i===CN||i===iN)&&(l[D]=l[D-1].slice(0),l[D+1]=p(e,g.length-1)),o4({pathArray:l,closePath:!0,closeArray:!1})}function hnA(A,g,I){const e=Math.cos(I),t=Math.sin(I),i=g.x*A.x+g.y*A.y+g.z*A.z,o=g.y*A.z-g.z*A.y,Q=g.z*A.x-g.x*A.z,r=g.x*A.y-g.y*A.x;return{x:A.x*e+o*t+g.x*i*(1-e),y:A.y*e+Q*t+g.y*i*(1-e),z:A.z*e+r*t+g.z*i*(1-e)}}function fnA(A){const g=A.shape,I=A.path,e=A.scale??1,t=A.rotation??0;let i=A.cap??oQ;i=i<0||i>3?oQ:i;const o=jH(I),{tangents:Q,normals:r,binormals:E}=o,n=[];let s=i===oQ||i===CN?0:2,c=0;for(let D=0;D<I.length;D++){const p=[],y=Q[D],_=r[D],u=E[D];for(let f=0;f<g.length;f++){const h=g[f],w={x:y.x*h.z+_.x*h.x+u.x*h.y,y:y.y*h.z+_.y*h.x+u.y*h.y,z:y.z*h.z+_.z*h.x+u.z*h.y},M=hnA(w,y,c);p.push({x:M.x*e+I[D].x,y:M.y*e+I[D].y,z:M.z*e+I[D].z})}n[s]=p,c+=t,s++}const l=D=>{const p={x:0,y:0,z:0};for(const u of D)p.x+=u.x,p.y+=u.y,p.z+=u.z;const y=1/D.length;p.x*=y,p.y*=y,p.z*=y;const _=[];for(let u=0;u<D.length;u++)_.push(p);return _};return(i===r4||i===iN)&&(n[0]=l(n[2]),n[1]=n[2]),(i===CN||i===iN)&&(n[s]=n[s-1],n[s+1]=l(n[s-1])),o4({pathArray:n,closeArray:!1,closePath:!1})}function vF(A,g,I,e,t,i,o,Q,r){const[E,n]=yi(I);g.boundMin=isFinite(E[0])?E:void 0,g.boundMax=isFinite(n[0])?n:void 0,g._cpuPositions=I,g._cpuNormals=e,g._cpuUvs=i?.length?i:void 0,g._cpuUv2s=o?.length?o:null,g._cpuTangents=Q?.length?Q:null,g._cpuColors=r?.length?r:null,g._cpuIndices=t,g._cpuGpuIndices=t,g._cpuIndexFormat="uint32",A._dlr?.m(g,g._cpuUv2s,g._cpuTangents,g._cpuColors,t,"uint32")}function dnA(A,g,I,e,t,i,o,Q){const r=A._gpu,E=g.length/3;(r._vbLayout||(r._refCount??1)>1)&&U(357),(!Number.isInteger(E)||I.length!==g.length||e.length%3!==0||r.indexFormat!=="uint32")&&U(358);const n=!!t&&t.length>0,s=!!i&&i.length>0,c=!!o&&o.length>0,l=!!Q&&Q.length>0;return(n!==!!r.hasUv||n&&t.length!==E*2||s!==!!r.hasUv2||s&&i.length!==E*2||c!==!!r.hasTangent||c&&o.length!==E*4||l!==!!r.hasColor||l&&Q.length!==E*4)&&U(359),E}function Et(A,g,I,e,t,i,o,Q,r){const[E,n]=yi(I),s=tN({name:g,material:null,receiveShadows:!1,boundMin:isFinite(E[0])?E:void 0,boundMax:isFinite(n[0])?n:void 0,_gpu:I4(A,I,e,t,i,o,Q,r)});return s._cpuPositions=I,s._cpuNormals=e,s._cpuUvs=i,s._cpuIndices=t,A._dlr?.m(s,o??null,Q??null,r??null,t,"uint32"),s}function VH(A){cC();for(const g of A._renderingContexts){const I=g;I._renderableVersion!==void 0&&I._renderableVersion++}}function HF(A,g,I,e=0,t,i=0){Ir(A,g,g._gpu.positionBuffer,I,3,e,t,i)}function Ir(A,g,I,e,t,i,o,Q){(g._gpu._refCount??1)>1&&U(360,g.name);const r=e.length/t,E=o??r-Q;if((!Number.isInteger(r)||!Number.isInteger(i)||i<0||!Number.isInteger(Q)||Q<0||!Number.isInteger(E)||E<0||Q+E>r)&&U(361),E===0)return;const n=t*4,s=i*n,c=E*n;s+c>I.size&&U(362),A._device.queue.writeBuffer(I,s,e.buffer,e.byteOffset+Q*n,c),OR(g)}function wnA(A,g,I,e,t,i,o,Q,r){const E=g._gpu,n=I.length/3,s=!!i&&i.length>0,c=!!o&&o.length>0,l=!!Q&&Q.length>0,D=!!r&&r.length>0;(E._vbLayout||(E._refCount??1)>1)&&U(363),(!Number.isInteger(n)||g._cpuPositions?.length!==I.length||e.length!==I.length||g._cpuIndices?.length!==t.length||t.length>E.indexCount||E.indexFormat!=="uint32")&&U(364),(s!==!!E.hasUv||s&&i.length!==n*2||c!==!!E.hasUv2||c&&o.length!==n*2||l!==!!E.hasTangent||l&&Q.length!==n*4||D!==!!E.hasColor||D&&r.length!==n*4)&&U(365);const p=A._device.queue;p.writeBuffer(E.positionBuffer,0,I.buffer,I.byteOffset,I.byteLength),p.writeBuffer(E.normalBuffer,0,e.buffer,e.byteOffset,e.byteLength),p.writeBuffer(E.indexBuffer,0,t.buffer,t.byteOffset,t.byteLength),s&&p.writeBuffer(E.uvBuffer,0,i.buffer,i.byteOffset,i.byteLength),c&&p.writeBuffer(E.uv2Buffer,0,o.buffer,o.byteOffset,o.byteLength),l&&p.writeBuffer(E.tangentBuffer,0,Q.buffer,Q.byteOffset,Q.byteLength),D&&p.writeBuffer(E.colorBuffer,0,r.buffer,r.byteOffset,r.byteLength),vF(A,g,I,e,t,i,o,Q,r),OR(g)}function MnA(A,g,I,e,t,i,o,Q,r,E=1.25){(!Number.isFinite(E)||E<1)&&U(366);const n=dnA(g,I,e,t,i,o,Q,r),s=g._gpu,c=s._vertexCapacity??(g._cpuPositions?g._cpuPositions.length/3:n),l=s._indexCapacity??s.indexCount;if(n>c||t.length>l){const y=n>c?Math.ceil(n*E):c,_=t.length>l?Math.ceil(t.length*E):l,u=Math.ceil(_/3)*3,f=new Float32Array(y*3),h=new Float32Array(y*3),w=new Uint32Array(u);f.set(I),h.set(e),w.set(t);const M=i?.length?new Float32Array(y*2):void 0,S=o?.length?new Float32Array(y*2):void 0,R=Q?.length?new Float32Array(y*4):void 0,N=r?.length?new Float32Array(y*4):void 0;return M?.set(i),S?.set(o),R?.set(Q),N?.set(r),WH(A,g,f,h,w,M,S,R,N),g._gpu._vertexCapacity=y,g._gpu._indexCapacity=u,g._gpu._indexScratch=w,vF(A,g,I,e,t,i,o,Q,r),{stable:!1,vertexCapacity:y,indexCapacity:u}}s._vertexCapacity=c,s._indexCapacity=l;const D=s._indexScratch?.length===l?s._indexScratch:s._indexScratch=new Uint32Array(l);D.fill(0),D.set(t);const p=A._device.queue;return p.writeBuffer(s.positionBuffer,0,I.buffer,I.byteOffset,I.byteLength),p.writeBuffer(s.normalBuffer,0,e.buffer,e.byteOffset,e.byteLength),p.writeBuffer(s.indexBuffer,0,D.buffer,D.byteOffset,D.byteLength),i?.length&&p.writeBuffer(s.uvBuffer,0,i.buffer,i.byteOffset,i.byteLength),o?.length&&p.writeBuffer(s.uv2Buffer,0,o.buffer,o.byteOffset,o.byteLength),Q?.length&&p.writeBuffer(s.tangentBuffer,0,Q.buffer,Q.byteOffset,Q.byteLength),r?.length&&p.writeBuffer(s.colorBuffer,0,r.buffer,r.byteOffset,r.byteLength),vF(A,g,I,e,t,i,o,Q,r),OR(g),{stable:!0,vertexCapacity:c,indexCapacity:l}}function WH(A,g,I,e,t,i,o,Q,r){const E=g._gpu;VH(A),g._gpu=I4(A,I,e,t,i,o,Q,r),vF(A,g,I,e,t,i,o,Q,r),OR(g),DC(E)&&G1(A,()=>{E.positionBuffer.destroy(),E.normalBuffer.destroy(),E.indexBuffer.destroy(),E.uvBuffer.destroy(),E.uv2Buffer?.destroy(),E.tangentBuffer?.destroy(),E.colorBuffer?.destroy()})}function SnA(A,g,I,e=0,t,i=0){const o=g._gpu;o.normalBuffer&&Ir(A,g,o.normalBuffer,I,3,e,t,i)}function zH(A,g,I,e=0,t,i=0){const o=g._gpu;o.colorBuffer&&Ir(A,g,o.colorBuffer,I,4,e,t,i)}function RnA(A,g,I,e=0,t,i=0){const o=g._gpu;o.uvBuffer&&Ir(A,g,o.uvBuffer,I,2,e,t,i)}function NnA(A,g,I,e=0,t,i=0){const o=g._gpu;o.uv2Buffer&&Ir(A,g,o.uv2Buffer,I,2,e,t,i)}function GnA(A,g,I,e=0,t,i=0){const o=g._gpu;o.tangentBuffer&&Ir(A,g,o.tangentBuffer,I,4,e,t,i)}function oN(A,g){const I=vH(g);return Et(A,"sphere",I.positions,I.normals,I.indices,I.uvs)}function gC(A,g=1){const I=e4(g);return Et(A,"box",I.positions,I.normals,I.indices,I.uvs)}function BN(A,g){const I=nnA(g);return Et(A,"torus",I.positions,I.normals,I.indices,I.uvs)}function FnA(A,g){const I=HH(g);return Et(A,"torusKnot",I.positions,I.normals,I.indices,I.uvs)}async function mnA(A,g,I){const e=await anA(g,I);return Et(A,"ground",e.positions,e.normals,e.indices,e.uvs)}function bnA(A,g){const I=TH(g);return Et(A,"ground",I.positions,I.normals,I.indices,I.uvs)}function Wt(A,g){const I=xH(g);return Et(A,"cylinder",I.positions,I.normals,I.indices,I.uvs)}function KnA(A,g){const I=qH(g);return Et(A,"capsule",I.positions,I.normals,I.indices,I.uvs)}function E4(A,g){const I=cnA(g);return Et(A,"plane",I.positions,I.normals,I.indices,I.uvs)}function ZH(A,g){const I=lnA(g);return Et(A,"disc",I.positions,I.normals,I.indices,I.uvs)}function XH(A,g){const I=DnA(g);return Et(A,"polyhedron",I.positions,I.normals,I.indices,I.uvs)}function knA(A,g){const I=o4(g);return Et(A,"ribbon",I.positions,I.normals,I.indices,I.uvs)}function UnA(A,g){const I=unA(g);return Et(A,"tube",I.positions,I.normals,I.indices,I.uvs)}function LnA(A,g){const I=fnA(g);return Et(A,"extrude",I.positions,I.normals,I.indices,I.uvs)}const yC=1,TF=2,QN=4,rN=8,xF=16,qF=32,co=64,PF=128,OF=256,jF=512,VF=1024,EN=2048,$H=4096,AT=8192,gT=16384,lo=65536,IT=1<<17,WF=1<<18,eT=1<<19,er=1<<20,YnA=1<<21,tT=32768,CT=1<<22,n4=1<<24,zF=1<<26,s4=1<<27,JnA=1;let a4=null,ZF=null;function _C(A){(a4??=new Map).set(A._id,A),ZF=null}function iT(){return a4??=new Map}function XF(){if(!ZF){const A=a4;ZF=A?Array.from(A.values()).sort((g,I)=>g._id.localeCompare(I._id)):[]}return ZF}const BQ=yC|TF|QN|rN|xF|qF|co,c4=PF|OF|VF|EN;let l4=null;function D4(A,g){const I=A().then(e=>{_C(e[g])});return(l4??=[]).push(I),I}let p4=null;function $F(){if(p4)return p4;const A=async(g,I)=>{const e=I.some(u=>!!u.thinInstances),t=I.some(u=>!!u.thinInstances?._gpuCullingEnabled),i=I.some(u=>u.receiveShadows)&&g.lights.some(u=>!!u.shadowGenerator),o=I.some(u=>!!u.morphTargets);let Q,r,E,n,s,c,l=null;const D=[];if(e&&(D.push(Promise.resolve().then(()=>A5).then(u=>{Q=u.syncThinInstanceBuffers,r=u.syncThinInstanceForDraw}),Promise.resolve().then(()=>g5).then(u=>{E=u.createThinInstanceFragment})),t&&D.push(Promise.resolve().then(()=>o5).then(u=>{c=u}))),i&&D.push(Promise.resolve().then(()=>D5A).then(u=>{n=u.createStdShadowFragment})),o&&D.push(Promise.resolve().then(()=>_5A).then(u=>{s=u.createMorphFragment})),g.fog&&D.push(Promise.resolve().then(()=>h5A).then(u=>{l=u.createStandardFogFragment()})),l4)for(const u of l4)D.push(u);D.length>0&&await Promise.all(D);const p=await Promise.resolve().then(()=>d5A),y=g.fog?{_features:JnA,_fragments:[l]}:null,_=p.buildStandardMeshRenderables(g,I,{tiSync:Q,tiUpdate:r,tiFragment:E,shadowFragment:n,morphFragment:s,cull:c,sceneShader:y});return A._rebuildSingle=_.rebuildSingle,_};return A._materialFamily="standard",p4=A}function nt(){return{diffuseColor:[1,1,1],alpha:1,specularColor:[1,1,1],specularPower:64,emissiveColor:[0,0,0],ambientColor:[0,0,0],diffuseTexture:null,diffuseCoordIndex:0,bumpLevel:1,specularCoordIndex:0,ambientTexLevel:1,ambientCoordIndex:0,lightmapLevel:1,lightmapCoordIndex:1,useLightmapAsShadowmap:!1,opacityLevel:1,opacityFromRGB:!1,alphaCutOff:0,reflectionLevel:1,reflectionCoordMode:1,uvScale:[1,1],backFaceCulling:!0,disableLighting:!1,_buildGroup:$F(),_uboVersion:0}}function Do(){return{hit:!1,distance:0,pickedPoint:null,pickedNormal:null,pickedNormalWorld:null,pickedFaceNormal:null,pickedFaceNormalWorld:null,pickedMesh:null,faceId:-1,bu:0,bv:0,subMeshId:0,thinInstanceIndex:-1,ray:null,_normalsInvalid:!1}}function oT(A,g){const I=[],e=g?.predicate;for(const t of A){if(!g?.skipPickableCheck&&t.pickable===!1||e&&!e(t))continue;const i=TnA(t);if(!i)continue;const o=lt(t.worldMatrix);o&&I.push({mesh:t,aabb:i,invWorld:o})}return{candidates:I}}function BT(A,g){return oT(A.meshes,g)}let vnA=null;function HnA(){return vnA??=new WeakMap}function TnA(A){const g=A._cpuPositions;if(!g||g.length<3)return null;const I=HnA(),e=I.get(g);if(e)return e;let t=1/0,i=1/0,o=1/0,Q=-1/0,r=-1/0,E=-1/0;for(let s=0;s<g.length;s+=3){const c=g[s],l=g[s+1],D=g[s+2];c<t&&(t=c),l<i&&(i=l),D<o&&(o=D),c>Q&&(Q=c),l>r&&(r=l),D>E&&(E=D)}const n={min:[t,i,o],max:[Q,r,E]};return I.set(g,n),n}function xnA(A,g,I,e,t){const i=A[0]*g+A[4]*I+A[8]*e+A[12],o=A[1]*g+A[5]*I+A[9]*e+A[13],Q=A[2]*g+A[6]*I+A[10]*e+A[14],r=A[3]*g+A[7]*I+A[11]*e+A[15],E=r!==0?1/r:1;t[0]=i*E,t[1]=o*E,t[2]=Q*E}function qnA(A,g,I,e,t){t[0]=A[0]*g+A[4]*I+A[8]*e,t[1]=A[1]*g+A[5]*I+A[9]*e,t[2]=A[2]*g+A[6]*I+A[10]*e}function PnA(A,g,I,e,t,i,o,Q,r){let E=0,n=Q,s=-1;const c=[A,g,I],l=[e,t,i];for(let D=0;D<3;D++){const p=o.min[D],y=o.max[D],_=l[D],u=c[D];if(Math.abs(_)<1e-12){if(u<p||u>y)return-1}else{const f=1/_;let h=(p-u)*f,w=(y-u)*f;if(h>w){const M=h;h=w,w=M}if(h>E&&(E=h,s=D),w<n&&(n=w),E>n)return-1}}return r[0]=s,E}function Am(A,g,I){const e=Do();e.ray=g;const t=I?.predicate,[i,o,Q]=g.origin,[r,E,n]=g.direction,s=[0,0,0],c=[0,0,0],l=[-1];let D=g.length,p=null,y=-1,_=0,u=null;for(const f of A.candidates){const h=f.mesh;if(t&&!t(h))continue;const{aabb:w,invWorld:M}=f;xnA(M,i,o,Q,s),qnA(M,r,E,n,c),l[0]=-1;const S=PnA(s[0],s[1],s[2],c[0],c[1],c[2],w,D,l);S>=0&&S<D&&(D=S,p=h,y=l[0],_=y>=0?Math.sign(c[y]):0,u=M)}if(p&&(e.hit=!0,e.distance=D,e.pickedMesh=p,e.pickedPoint=[i+r*D,o+E*D,Q+n*D],y>=0&&u)){const f=[0,0,0];f[y]=-_,e.pickedNormal=[f[0],f[1],f[2]];const h=u;let w=h[0]*f[0]+h[1]*f[1]+h[2]*f[2],M=h[4]*f[0]+h[5]*f[1]+h[6]*f[2],S=h[8]*f[0]+h[9]*f[1]+h[10]*f[2];const R=Math.hypot(w,M,S)||1;w/=R,M/=R,S/=R,e.pickedNormalWorld=[w,M,S]}return e}function QT(A,g,I){return Am(BT(A,I),g)}function OnA(A,g,I){return Am(oT(A,I),g)}function _i(A){const g=AC(A);g._uboVersion++}const ui={maxLength:10,laserColor:[.7,.7,.7],laserPickedColor:[.9,.9,.9],cursorColor:[.8,.8,.8],cursorPickedColor:[.3,.3,1],laserThickness:.004,cursorSize:.03,enableOnAllControllers:!1,disableSwitchOnClick:!1},jnA=.02;function rT(A,g,I,e){const t=I>=0&&Number.isFinite(I),i=Math.max(1e-4,t?I:e),o=i*.5,Q=[A[0]+g[0]*o,A[1]+g[1]*o,A[2]+g[2]*o],r=t?[A[0]+g[0]*I,A[1]+g[1]*I,A[2]+g[2]*I]:[0,0,0];return{hit:t,beamLength:i,laserPosition:Q,cursorPosition:r}}function ET(A,g,I={}){return{_engine:A,_scene:g,_options:{maxLength:I.maxLength??ui.maxLength,laserColor:I.laserColor??ui.laserColor,laserPickedColor:I.laserPickedColor??ui.laserPickedColor,cursorColor:I.cursorColor??ui.cursorColor,cursorPickedColor:I.cursorPickedColor??ui.cursorPickedColor,laserThickness:I.laserThickness??ui.laserThickness,cursorSize:I.cursorSize??ui.cursorSize,enableOnAllControllers:I.enableOnAllControllers??ui.enableOnAllControllers,disableSwitchOnClick:I.disableSwitchOnClick??ui.disableSwitchOnClick,predicate:I.predicate,preferredHandedness:I.preferredHandedness,onHoverStart:I.onHoverStart,onHoverEnd:I.onHoverEnd,onSelect:I.onSelect},_units:new Map,_activeSource:null}}function nT(A,g=!1){const I=nt();return I.diffuseColor=[1,1,1],I.emissiveColor=[A[0],A[1],A[2]],I.disableLighting=!0,g&&(I.backFaceCulling=!1),I}function VnA(A,g){const I=g[1];if(I<-.999999){A.rotationQuaternion.set(1,0,0,0);return}const e=g[2],t=0,i=-g[0],o=1+I,Q=Math.hypot(e,t,i,o)||1;A.rotationQuaternion.set(e/Q,t/Q,i/Q,o/Q)}function WnA(A,g){const I=A._units.get(g);if(I)return I;const e=A._engine,t=A._options,i=gC(e,1);i.name="xr-pointer-laser";const o=nT(t.laserColor);i.material=o,i.pickable=!1,i.receiveShadows=!1,i.visible=!1;const Q=BN(e,{diameter:t.cursorSize,thickness:t.cursorSize*.12,tessellation:24});Q.name="xr-pointer-cursor";const r=nT(t.cursorColor,!0);Q.material=r,Q.pickable=!1,Q.receiveShadows=!1,Q.visible=!1,JI(A._scene,i),JI(A._scene,Q);const E={laser:i,cursor:Q,laserMat:o,cursorMat:r,hovered:null,lastInput:null,picked:!1,wasSelecting:!1};return A._units.set(g,E),E}function sT(A,g){g.hovered&&(g.lastInput&&A._options.onHoverEnd?.(g.hovered,g.lastInput),g.hovered=null),ct(A._scene,g.laser),ct(A._scene,g.cursor),X1(g.laser),X1(g.cursor)}function aT(A,g,I){const e=A._options,t=A._scene,i=new Set,o=!e.enableOnAllControllers;for(const r of g.inputSources)i.add(r.source),WnA(A,r.source);let Q=null;if(o&&!e.disableSwitchOnClick)for(const r of g.inputSources){const E=A._units.get(r.source);r.selecting&&!E.wasSelecting&&r.source!==A._activeSource&&(A._activeSource=r.source,Q=r.source)}if(o&&!(A._activeSource!==null&&i.has(A._activeSource))){A._activeSource=null;const E=e.preferredHandedness;let n=null;for(const s of g.inputSources)if(n??=s.source,E!==void 0&&s.handedness===E){A._activeSource=s.source;break}A._activeSource??=n}for(const r of g.inputSources){const E=A._units.get(r.source);if(E.lastInput=r,!(!o||r.source===A._activeSource)||!r.targetRayTracked){ke(E.laser,!1),ke(E.cursor,!1),E.hovered&&(e.onHoverEnd?.(E.hovered,r),E.hovered=null),E.wasSelecting=r.selecting;continue}const s=r.targetRayMatrix,c=[s[12],s[13],s[14]];let l=s[8],D=s[9],p=s[10];const y=Math.hypot(l,D,p)||1;l/=y,D/=y,p/=y;const _=[l,D,p],u=QT(t,{origin:c,direction:_,length:e.maxLength},{predicate:e.predicate}),f=u.hit&&u.distance>jnA,h=f?u.pickedMesh:null,w=rT(c,_,f?u.distance:-1,e.maxLength),M=LC(s).rotation;if(E.laser.rotationQuaternion.set(M.x,M.y,M.z,M.w),E.laser.position.set(w.laserPosition[0],w.laserPosition[1],w.laserPosition[2]),E.laser.scaling.set(e.laserThickness,e.laserThickness,w.beamLength),ke(E.laser,!0),w.hit){const R=w.cursorPosition,N=I&&Math.hypot(R[0]-I[0],R[1]-I[1],R[2]-I[2])||u.distance,F=.003*N,G=u.pickedNormalWorld??[-l,-D,-p];E.cursor.position.set(R[0]+G[0]*F,R[1]+G[1]*F,R[2]+G[2]*F),E.cursor.scaling.set(N,N,N),VnA(E.cursor,G),ke(E.cursor,!0)}else ke(E.cursor,!1);const S=h!==null;if(S!==E.picked){const R=S?e.laserPickedColor:e.laserColor,N=S?e.cursorPickedColor:e.cursorColor;E.laserMat.emissiveColor=[R[0],R[1],R[2]],E.cursorMat.emissiveColor=[N[0],N[1],N[2]],_i(E.laserMat),_i(E.cursorMat),E.picked=S}h!==E.hovered&&(E.hovered&&e.onHoverEnd?.(E.hovered,r),h&&e.onHoverStart?.(h,r),E.hovered=h),r.selecting&&!E.wasSelecting&&h&&r.source!==Q&&e.onSelect?.(h,u,r),E.wasSelecting=r.selecting}for(const[r,E]of A._units)i.has(r)||(sT(A,E),A._units.delete(r));A._activeSource!==null&&!i.has(A._activeSource)&&(A._activeSource=null)}function cT(A){for(const g of A._units.values())sT(A,g);A._units.clear()}function znA(A={}){return{create(g){g.input||U(605);const I=g.input,e=ET(g.engine,g.scene,A);return{update(t){const o=t.getViewerPose?.(g.referenceSpace)?.transform.position,Q=o?[o.x,o.y,-o.z]:null;aT(e,I,Q)},dispose(){cT(e)}}}}}function tr(A,g){const I=A[g];return I?{pressed:I.pressed,touched:I.touched,value:I.value}:null}function lT(A,g,I){const e=A[g],t=A[I];return e===void 0||t===void 0?null:[e,t]}function ZnA(A){const g=A.gamepad;if(!g)return null;const I=g.buttons,e=g.axes;return{handedness:A.handedness,trigger:tr(I,0),squeeze:tr(I,1),touchpad:tr(I,2),thumbstick:tr(I,3),buttonA:tr(I,4),buttonB:tr(I,5),touchpadAxes:lT(e,0,1),thumbstickAxes:lT(e,2,3)}}function gm(A){const g=[],I=new Set,e=t=>{if(I.has(t))return;I.add(t),t._gpu&&g.push(t);const i=t.children;if(i)for(const o of i)e(o)};for(const t of A.entities)"lightType"in t||e(t);return g}function XnA(A){return A==="left"?[.3,.5,.9]:A==="right"?[.9,.5,.3]:[.6,.6,.6]}function $nA(A,g,I){const e=gC(A,1);e.name=`xr-controller-${I}`;const t=nt();return t.diffuseColor=XnA(I),e.material=t,e.pickable=!1,e.receiveShadows=!1,e.scaling.set(.04,.04,.12),e.visible=!1,e}const Cr=[.55,.72,1];function AsA(A,g,I){const e=gC(A,1);e.name=`xr-controller-loading-${I}`;const t=nt();return t.diffuseColor=[1,1,1],t.emissiveColor=[Cr[0],Cr[1],Cr[2]],t.disableLighting=!0,t.alpha=.45,e.material=t,e.pickable=!1,e.receiveShadows=!1,e.scaling.set(.035,.035,.11),e.visible=!1,e}function DT(A,g,I={}){const e=I.profiles?I.profiles===!0?{}:I.profiles:null,t=!I.meshFactory&&e!==null;return{_engine:A,_scene:g,_factory:I.meshFactory??(t?AsA:$nA),_loadingStyle:t,_profiles:e,_mod:null,_units:new Map}}function gsA(A){A._mod||!A._profiles||Promise.resolve().then(()=>m0A).then(g=>{A._mod=g}).catch(()=>{A._profiles=null})}function y4(A,g){ct(A._scene,g.container);for(const I of gm(g.container))X1(I)}function IsA(A,g,I){const e=A._mod,t=A._profiles;!e||!t||I.loadStarted||(I.loadStarted=!0,(async()=>{try{const i=await e.loadMotionController(A._engine,g,I.handedness,t);if(!i)return;if(I.retired){y4(A,i);return}for(const Q of gm(i.container))Q.pickable=!1;const{enableMirroredMeshes:o}=await Promise.resolve().then(()=>Rq);if(await o(A._scene),I.retired){y4(A,i);return}JI(A._scene,i.container),ke(i.root,!1),I.model=i,I.active=i.root,I.visible=!1,I.mesh&&(ct(A._scene,I.mesh),X1(I.mesh),I.mesh=null)}catch{}})())}function esA(A,g,I){const e=A._units.get(g);if(e)return e;const t=A._factory(A._engine,A._scene,I);JI(A._scene,t);const i=A._loadingStyle?t.material:null,o={handedness:I,mesh:t,model:null,placeholderMat:i,active:t,loadStarted:!1,retired:!1,visible:null};return A._units.set(g,o),o}function pT(A,g){g.retired=!0,g.mesh&&(ct(A._scene,g.mesh),X1(g.mesh),g.mesh=null),g.model&&(y4(A,g.model),g.model=null)}function yT(A,g){A.visible!==g&&(A.model?ke(A.active,g):A.mesh&&ke(A.mesh,g),A.visible=g)}function _T(A,g){const I=new Set;gsA(A);for(const e of g.inputSources){if(e.source.hand)continue;I.add(e.source);const t=esA(A,e.source,e.handedness);if(IsA(A,e.source,t),!e.gripTracked){yT(t,!1);continue}const i=e.gripMatrix,o=LC(i).rotation;if(t.active.position.set(i[12],i[13],i[14]),t.model?t.active.rotationQuaternion.set(-o.z,o.w,o.x,-o.y):t.active.rotationQuaternion.set(o.x,o.y,o.z,o.w),yT(t,!0),t.placeholderMat&&t.mesh&&!t.model){const Q=.5+.5*Math.sin(performance.now()*.004);t.placeholderMat.alpha=.25+.35*Q;const r=.6+.4*Q;t.placeholderMat.emissiveColor=[Cr[0]*r,Cr[1]*r,Cr[2]*r],_i(t.placeholderMat)}t.model&&A._mod&&A._mod.updateMotionController(t.model,e.source.gamepad??null)}for(const[e,t]of A._units)I.has(e)||(pT(A,t),A._units.delete(e))}function uT(A){for(const g of A._units.values())pT(A,g);A._units.clear()}function tsA(A={}){return{create(g){g.input||U(603);const I=g.input,e=DT(g.engine,g.scene,A);return{update(){_T(e,I)},dispose(){uT(e)}}}}}const CsA=[.7,.78,.95],isA=[.455,.247,.796],osA=.008,BsA="https://assets.babylonjs.com/core/HandMeshes/",QsA="r_hand_rhs.glb",rsA="l_hand_rhs.glb";function EsA(A){return(g,I,e)=>{const t=oN(g,{diameter:1,segments:8});t.name=`xr-hand-${e}-joint`;const i=nt();return i.diffuseColor=[A[0],A[1],A[2]],t.material=i,t.pickable=!1,t.receiveShadows=!1,t.visible=!1,t}}function hT(A,g,I={}){return{_engine:A,_scene:g,_factory:I.jointMeshFactory??EsA(I.jointColor??CsA),_jointScale:I.jointScale??1,_handMeshes:I.handMeshes??!0,_handMeshOpts:{baseUrl:I.handMeshBaseUrl??BsA,leftFilename:I.handMeshLeftFilename??rsA,rightFilename:I.handMeshRightFilename??QsA,color:I.handColor??isA,alpha:I.handAlpha??1},_mod:null,_modLoading:!1,_units:new Map}}function nsA(A){A._mod||A._modLoading||!A._handMeshes||(A._modLoading=!0,Promise.resolve().then(()=>R5A).then(g=>{A._mod=g}).catch(()=>{A._handMeshes=!1}))}function ssA(A,g){const I=A._mod;!I||g.meshLoadStarted||(g.meshLoadStarted=!0,(async()=>{try{const e=await I.loadHandMesh(A._engine,A._scene,g.handedness,A._handMeshOpts);if(!e)return;if(g.retired){I.disposeHandMesh(A._scene,e);return}g.mesh=e,fT(A,g)}catch{}})())}function asA(A,g,I){const e=A._units.get(g);if(e)return e;const t={handedness:I,joints:new Map,mesh:null,meshLoadStarted:!1,retired:!1};return A._units.set(g,t),t}function csA(A,g,I){const e=g.joints.get(I);if(e)return e;const t=A._factory(A._engine,A._scene,g.handedness);return t.name=`xr-hand-${g.handedness}-${I}`,JI(A._scene,t),g.joints.set(I,t),t}function fT(A,g){for(const I of g.joints.values())ct(A._scene,I),X1(I);g.joints.clear()}function dT(A,g){g.retired=!0,fT(A,g),g.mesh&&A._mod&&(A._mod.disposeHandMesh(A._scene,g.mesh),g.mesh=null)}function wT(A,g,I,e){const t=new Set,i=I.getJointPose;A._handMeshes&&nsA(A);for(const o of g.inputSources){const Q=o.source.hand;if(!Q)continue;t.add(o.source);const r=asA(A,o.source,o.handedness);if(A._handMeshes&&(r.mesh||ssA(A,r),r.mesh)){A._mod.poseHandMesh(r.mesh,Q,I,e);continue}if(i)for(const[E,n]of Q){const s=csA(A,r,E),c=i.call(I,n,e);if(!c){ke(s,!1);continue}const l=(c.radius??osA)*2*A._jointScale;XEA(s,c.transform),s.scaling.set(l,l,l),ke(s,!0)}}for(const[o,Q]of A._units)t.has(o)||(dT(A,Q),A._units.delete(o))}function MT(A){for(const g of A._units.values())dT(A,g);A._units.clear()}function lsA(A={}){return{sessionFeatures:["hand-tracking"],create(g){g.input||U(604);const I=g.input,e=hT(g.engine,g.scene,A);return{update(t){wT(e,I,t,g.referenceSpace)},dispose(){MT(e)}}}}}const DsA=[.3,.6,1],psA=[1,.25,.25],_4=.4,ysA=.008,IC=32,_sA=.3,usA=.13,hsA=.05,fsA=.02,dsA=.6,wsA=.2,MsA=.35;function SsA(A){if(A.floorMeshes){const g=new Set(A.floorMeshes);return I=>g.has(I)}if(A.floorPredicate){const g=A.floorPredicate;return I=>g(I)}return(g,I)=>I!==null&&I[1]>=dsA}function RsA(A){const g=A.pickBlockerMeshes?new Set(A.pickBlockerMeshes):null,I=A.blockerPredicate;return!g&&!I?()=>!1:e=>g!==null&&g.has(e)||I!==void 0&&I(e)}function u4(A,g,I){const e=nt();return e.diffuseColor=[1,1,1],e.emissiveColor=[A[0],A[1],A[2]],e.disableLighting=!0,e.alpha=g,I&&(e.backFaceCulling=!1),e}function ST(A,g,I={}){const e=I.color??DsA,t=I.blockedColor??psA;return{_engine:A,_scene:g,_options:{color:[e[0],e[1],e[2]],blockedColor:[t[0],t[1],t[2]],blockAllPickableMeshes:I.blockAllPickableMeshes??!1,maxLength:I.maxLength??20,parabolic:I.parabolic??!0,parabolaSpeed:I.parabolaSpeed??7,gravity:I.gravity??9.8,rotateToDirection:I.rotateToDirection??!0,snapTurn:I.snapTurn??!0,rotationAngle:I.rotationAngle??Math.PI/4,thumbstickThreshold:I.thumbstickThreshold??.7},_isFloor:SsA(I),_isBlocker:RsA(I),_floorY:0,_units:new Map}}function NsA(){const A=new Uint32Array((IC-1)*6);for(let g=0;g<IC-1;g++){const I=2*g,e=2*g+1,t=2*g+2,i=2*g+3,o=g*6;A[o]=I,A[o+1]=e,A[o+2]=t,A[o+3]=e,A[o+4]=i,A[o+5]=t}return A}function GsA(A,g){const I=A._units.get(g);if(I)return I;const e=A._options.color,t=A._engine,i=new Float32Array(2*IC*3),o=new Float32Array(2*IC*3);for(let D=0;D<2*IC;D++)o[D*3+1]=1;const Q=Et(t,"xr-teleport-arc",i.slice(),o,NsA()),r=u4(e,.85,!0);Q.material=r,Q.pickable=!1,Q.receiveShadows=!1,Q.visible=!1;const E=BN(t,{diameter:_4,thickness:_4*.14,tessellation:40});E.name="xr-teleport-reticle",E.material=u4(e,1,!1),E.pickable=!1,E.receiveShadows=!1,E.visible=!1;const n=usA,s=_sA,c=Et(t,"xr-teleport-arrow",new Float32Array([-n,0,0,n,0,0,0,0,s]),new Float32Array([0,1,0,0,1,0,0,1,0]),new Uint32Array([0,1,2]));c.material=u4(e,1,!0),c.pickable=!1,c.receiveShadows=!1,c.visible=!1,JI(A._scene,Q),JI(A._scene,E),JI(A._scene,c);const l={arc:Q,arcMat:r,arcBlocked:!1,reticle:E,indicator:c,arcPath:new Float32Array(IC*3),arcVerts:i,aiming:!1,target:null,landingTurn:0,turnLatched:!1};return A._units.set(g,l),l}function RT(A,g){ct(A._scene,g.arc),ct(A._scene,g.reticle),ct(A._scene,g.indicator),X1(g.arc),X1(g.reticle),X1(g.indicator)}function FsA(A,g){const I=g[2],e=-g[0],t=g[1];if(t>.99999){A.rotationQuaternion.set(0,0,0,1);return}if(t<-.99999){A.rotationQuaternion.set(1,0,0,0);return}const i=Math.hypot(I,0,e)||1,Q=Math.atan2(i,t)/2,r=Math.sin(Q)/i;A.rotationQuaternion.set(I*r,0,e*r,Math.cos(Q))}function msA(A){const g=A.axes,I=(g.length>2?g[2]:g[0])??0,e=(g.length>3?g[3]:g[1])??0;return[I,e]}function bsA(A){const g=A.transform.orientation;if(!g)return null;const I=-2*(g.x*g.z+g.w*g.y),e=1-2*(g.x*g.x+g.y*g.y),t=Math.hypot(I,e)||1;return[I/t,0,e/t]}function KsA(A,g){const I=Math.cos(g),e=Math.sin(g);return[A[0]*I+A[2]*e,0,-A[0]*e+A[2]*I]}function ksA(A,g,I,e){const t=A._options,i=t.parabolaSpeed,o=t.parabolic?t.gravity:0,Q=BT(A._scene),r=t.maxLength/i;e[0]=g[0],e[1]=g[1],e[2]=g[2];let E=g[0],n=g[1],s=g[2];for(let c=1;c<IC;c++){const l=c/(IC-1),D=r*l*l,p=g[0]+I[0]*i*D,y=g[1]+I[1]*i*D-.5*o*D*D,_=g[2]+I[2]*i*D,u=p-E,f=y-n,h=_-s,w=Math.hypot(u,f,h)||1e-6,M={origin:[E,n,s],direction:[u/w,f/w,h/w],length:w};let S=Am(Q,M),R=null;for(;S.hit&&S.pickedMesh;){const N=S.pickedMesh;if(A._isBlocker(N)||A._isFloor(N,S.pickedNormalWorld)||t.blockAllPickableMeshes)break;if(R?.includes(N)){S.hit=!1;break}(R??=[]).push(N),S=Am(Q,M,{predicate:F=>!R.includes(F)})}if(S.hit&&S.pickedPoint){const N=S.pickedPoint;for(let F=c;F<IC;F++)e[F*3]=N[0],e[F*3+1]=N[1],e[F*3+2]=N[2];return{hit:!0,point:[N[0],N[1],N[2]],normal:S.pickedNormalWorld,mesh:S.pickedMesh}}e[c*3]=p,e[c*3+1]=y,e[c*3+2]=_,E=p,n=y,s=_}return{hit:!1,point:[E,n,s],normal:null,mesh:null}}function UsA(A,g,I){const e=g.arcPath,t=g.arcVerts,i=ysA;for(let o=0;o<IC;o++){const Q=e[o*3],r=e[o*3+1],E=e[o*3+2],n=o>0?o-1:0,s=o<IC-1?o+1:IC-1,c=e[s*3]-e[n*3],l=e[s*3+1]-e[n*3+1],D=e[s*3+2]-e[n*3+2],p=I[0]-Q,y=I[1]-r,_=I[2]-E;let u=l*_-D*y,f=D*p-c*_,h=c*y-l*p;const w=Math.hypot(u,f,h)||1;u=u/w*i,f=f/w*i,h=h/w*i;const M=o*6;t[M]=Q+u,t[M+1]=r+f,t[M+2]=E+h,t[M+3]=Q-u,t[M+4]=r-f,t[M+5]=E-h}HF(A._engine,g.arc,t)}function LsA(A,g,I){const e=_4/2+hsA;A.position.set(g[0]+I[0]*e,g[1]+fsA,g[2]+I[2]*e);const i=Math.atan2(I[0],I[2])/2;A.rotationQuaternion.set(0,Math.sin(i),0,Math.cos(i))}function YsA(A,g,I,e){const t={x:g[0]-I[0],y:e-I[1],z:-(g[2]-I[2])};return A.getOffsetReferenceSpace(new XRRigidTransform(t))}function NT(A,g,I){const e=Math.cos(I),t=Math.sin(I),i=g[0]*e-g[2]*t,o=g[0]*t+g[2]*e,Q=I/2,r={x:0,y:Math.sin(Q),z:0,w:Math.cos(Q)};return A.getOffsetReferenceSpace(new XRRigidTransform({x:g[0]-i,y:0,z:-(g[2]-o)},r))}function GT(A,g,I,e){const t=new Set,i=A._options;let o=e;for(const Q of g.inputSources){const r=Q.source.gamepad;if(!r)continue;t.add(Q.source);const E=GsA(A,Q.source),[n,s]=msA(r),c=Math.hypot(n,s),l=c<wsA;if(s<=-i.thumbstickThreshold&&(E.aiming=!0),!E.aiming)if(i.snapTurn&&Math.abs(n)>=i.thumbstickThreshold&&Math.abs(s)<i.thumbstickThreshold){if(!E.turnLatched){const D=I.getViewerPose(o);if(D){const p=D.transform.position;o=NT(o,[p.x,p.y,-p.z],n>0?i.rotationAngle:-i.rotationAngle)}E.turnLatched=!0}}else Math.abs(n)<i.thumbstickThreshold*.5&&(E.turnLatched=!1);if(E.aiming&&!l){if(Q.targetRayTracked){const D=Q.targetRayMatrix,p=[D[12],D[13],D[14]];let y=D[8],_=D[9],u=D[10];const f=Math.hypot(y,_,u)||1;y/=f,_/=f,u/=f;const w=ksA(A,p,[y,_,u],E.arcPath),M=I.getViewerPose(o),S=M?[M.transform.position.x,M.transform.position.y,-M.transform.position.z]:p;UsA(A,E,S),ke(E.arc,!0);const R=w.hit?w.mesh:null,N=R!==null&&A._isBlocker(R),F=!N&&w.hit&&A._isFloor(R,w.normal),G=w.hit&&!F&&(N||i.blockAllPickableMeshes&&R?.pickable!==!1);if(G!==E.arcBlocked){const m=G?i.blockedColor:i.color;E.arcMat.emissiveColor=[m[0],m[1],m[2]],_i(E.arcMat),E.arcBlocked=G}if(F)if(E.target=w.point,E.reticle.position.set(w.point[0],w.point[1],w.point[2]),FsA(E.reticle,w.normal??[0,1,0]),ke(E.reticle,!0),i.rotateToDirection){c>=MsA&&(E.landingTurn=Math.atan2(n,-s));const m=M?bsA(M):null;m?(LsA(E.indicator,w.point,KsA(m,E.landingTurn)),ke(E.indicator,!0)):ke(E.indicator,!1)}else E.landingTurn=0,ke(E.indicator,!1);else E.target=null,E.landingTurn=0,ke(E.reticle,!1),ke(E.indicator,!1)}}else if(E.aiming&&l){if(E.target){const D=I.getViewerPose(o);if(D){const p=D.transform.position,y=E.target;o=YsA(o,[p.x,p.y,-p.z],y,A._floorY),A._floorY=y[1],i.rotateToDirection&&Math.abs(E.landingTurn)>1e-4&&(o=NT(o,y,E.landingTurn))}}E.aiming=!1,E.turnLatched=!1,E.target=null,E.landingTurn=0,ke(E.arc,!1),ke(E.reticle,!1),ke(E.indicator,!1)}}for(const[Q,r]of A._units)t.has(Q)||(RT(A,r),A._units.delete(Q));return o}function FT(A){for(const g of A._units.values())RT(A,g);A._units.clear()}function JsA(A={}){return{create(g){g.input||U(608);const I=g.input,e=ST(g.engine,g.scene,A);return{update(t){g._referenceSpace=GT(e,I,t,g._referenceSpace)},dispose(){FT(e)}}}}}function b1(A,g=0,I=0,e=0,t=0,i=0,o=0,Q=1,r=1,E=1,n=1){return onA(A,g,I,e,t,i,o,Q,r,E,n)}function h4(A){if("_gpu"in A)return vsA(A);const g=A._localMatrix?g4(A.name+"_clone",A._localMatrix):b1(A.name+"_clone",A.position.x,A.position.y,A.position.z,A.rotationQuaternion.x,A.rotationQuaternion.y,A.rotationQuaternion.z,A.rotationQuaternion.w,A.scaling.x,A.scaling.y,A.scaling.z);for(const I of A.children)if("lightType"in I){const e={...I,name:I.name+"_clone",children:[]};e.parent=g,g.children.push(e)}else{const e=h4(I);e.parent=g,g.children.push(e)}return g}function vsA(A){if(A._clone)throw Error(A._clone);if(A._disposed)throw Error(`Mesh "${A.name}" cannot be cloned: it was disposed when it left its last scene.`);const g=tN({...A,name:A.name+"_clone",children:[],_gpu:A._gpu},A.position.x,A.position.y,A.position.z,0,0,0,A.scaling.x,A.scaling.y,A.scaling.z);for(const e of[A._gpu,A.skeleton,A.vat,A.morphTargets,A.thinInstances])e&&HR(e);const I=A.rotationQuaternion;g.rotationQuaternion.set(I.x,I.y,I.z,I.w);for(const e of A.children){const t=h4(e);t.parent=g,g.children.push(t)}return g}let HsA=null,TsA=null;function xsA(){return HsA??=se()}function qsA(){return TsA??=se()}const PsA=5126,OsA=5123,jsA=5125,VsA=5121,po={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};function p1(A,g,I){const e=A.accessors[I],t=po[e.type]??1,i=e.count,o=i*t;let Q;switch(e.componentType){case PsA:Q=X;break;case OsA:Q=N1;break;case jsA:Q=Vg;break;case VsA:Q=mg;break;case 5122:Q=B3;break;case 5120:Q=Q3;break;default:U(138,e.componentType)}return{_data:e.bufferView===void 0?new Q(o):new Q(g.buffer,g.byteOffset+(A.bufferViews[e.bufferView].byteOffset??0)+(e.byteOffset??0),o),_count:i,_componentCount:t}}function f4(A){return A.extensions?.EXT_texture_webp?.source??A.source}function QQ(A,g){for(const I of A.meshes??[])for(const e of I.primitives??[])if(g(e))return!0;return!1}function mT(A){const g=A.materials??[],I=A.textures??[];for(const e of g){const t=e.pbrMetallicRoughness?.metallicRoughnessTexture,i=e.occlusionTexture;if(t&&i&&I[t.index]&&I[i.index]&&f4(I[t.index])!==f4(I[i.index]))return!0}return!1}async function WsA(A,g,I,e){const t=A.images[I];if(t.bufferView!==void 0){const i=A.bufferViews[t.bufferView],o=g.byteOffset+(i.byteOffset??0),Q=g.buffer.slice(o,o+i.byteLength),r=new Blob([Q],{type:t.mimeType??"image/png"});return createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"})}if(t.uri)return(await Promise.resolve().then(()=>$gA)).resolveExternalImage(t.uri,e);U(139)}const zsA=new X([-1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ZsA(A){const g=new Map,I=A.nodes??[];for(let e=0;e<I.length;e++){const t=I[e].children;if(t)for(const i of t)g.set(i,e)}return g}function nN(A,g){return A.get(g)??-1}function rQ(A,g,I,e){const t=e.get(g);if(t)return t;const i=A.nodes[g],o=nN(I,g),Q=o!==-1?rQ(A,o,I,e):zsA;let r;if(i.matrix)r=new X(i.matrix);else{const n=i.translation??[0,0,0],s=i.rotation??[0,0,0,1],c=i.scale??[1,1,1],l=xsA();Di(l,0,n[0],n[1],n[2],s[0],s[1],s[2],s[3],c[0],c[1],c[2]),r=l}const E=new X(16);return Oe(E,0,Q,0,r,0),e.set(g,E),E}async function bT(A,g,I,e,t){const i=A.materials?.[I],o=i??{},Q=o.pbrMetallicRoughness??{},r=d4(A,g,e,t),[E,n,s,c,l]=await Promise.all([r(Q.baseColorTexture),r(Q.metallicRoughnessTexture),r(o.normalTexture),r(o.occlusionTexture),r(o.emissiveTexture)]);return{_baseColorFactor:Q.baseColorFactor??[1,1,1,1],_metallicFactor:Q.metallicFactor??1,_roughnessFactor:Q.roughnessFactor??1,_emissiveFactor:o.emissiveFactor??[0,0,0],_baseColorImage:E,_metallicRoughnessImage:n,_normalImage:s,_normalScale:typeof o.normalTexture?.scale=="number"?o.normalTexture.scale:1,_occlusionTexCoord:typeof o.occlusionTexture?.texCoord=="number"?o.occlusionTexture.texCoord:0,_occlusionImage:c,_emissiveImage:l,_doubleSided:!!o.doubleSided,_alphaMode:o.alphaMode??"OPAQUE",_alphaCutoff:o.alphaCutoff??.5,_rawMatDef:i}}function d4(A,g,I,e){return t=>{if(!t)return Promise.resolve(null);const i=f4(A.textures[t.index]);return e[i]??=WsA(A,g,i,I)}}function KT(A,g,I,e,t=1){const i=A._device,o=i.createTexture({size:{width:1,height:1},format:"rgba8unorm",usage:dA.TEXTURE_BINDING|dA.COPY_DST}),Q=new mg([Math.round(g*255),Math.round(I*255),Math.round(e*255),Math.round(t*255)]);i.queue.writeTexture({texture:o},Q,{bytesPerRow:4,rowsPerImage:1},{width:1,height:1});const r=m1(A),E={texture:o,view:o.createView(),sampler:r,width:1,height:1};return A._dlr?.s(E,g,I,e,t),E}const EQ=1,Im=2,em=4,kT=8,UT=16,w4=32,YC=64,tm=128,Cm=256,ir=1024,or=2048,LT=4096,YT=32768,JT=1<<17,vT=1<<20,M4=1<<21,S4=1<<22,R4=1<<23,N4=1<<25,HT=1<<26,G4=1<<27,Br=1<<28,F4=1<<29,TT=1<<30,sN=16,im=512,aN=1024,Qr=2048,xT=4096,rr=32768,yo=65536;let m4=null,om=null;function tt(A){(m4??=new Map).set(A.id,A),om=null}function nQ(){return m4??=new Map}function XsA(){if(!om){const A=m4;om=A?Array.from(A.values()).sort((g,I)=>g.id.localeCompare(I.id)):[]}return om}let qT=null;function PT(A){(qT??=new Set).add(A)}function $sA(){return qT??[]}const Er=1,Bm=2,cN=4,JC=8,eC=16,sQ=32,nr=64,sr=128,Qm=256,b4=512,OT=1024;let K4=null;function A0A(A){K4=A}function rm(A,g=!1){const I=A._gpu;let e=0;return I.tangentBuffer&&(e|=Er),A.vat?(e|=b4,A.vat.joints1Buffer&&(e|=cN)):A.skeleton&&(e|=Bm,A.skeleton.joints1Buffer&&(e|=cN)),A.morphTargets&&(e|=JC),A.thinInstances&&(e|=eC,A.thinInstances.colors&&(e|=sQ)),I.colorBuffer&&(e|=nr),I.uv2Buffer&&(e|=sr),A._flatNormal&&(e|=OT),g&&(e|=Qm),K4&&(e|=K4(A)),e}let jT=null;function g0A(A){jT=A}function aQ(){return jT}let Em=null;function I0A(A){Em=A}let k4=null;function e0A(A){k4=A}let VT=null;function t0A(A){VT=A}const nm=new Map;let U4=null;function WT(A){U4!==A._device&&(nm.clear(),U4=A._device)}function C0A(){nm.clear(),U4=null}function i0A(A,g,I,e,t,i,o="",Q=null){WT(A);const r=Q&&Em?Em(Q):null,E=`${g}:${I}:${e}:${t}:${o}${r?r._key:""}`,n=nm.get(E);if(n)return n;const s=A._device,c=s.createBindGroupLayout(i._meshBGLDescriptor);let l=null;i._shadowBGLDescriptor&&(l=s.createBindGroupLayout(i._shadowBGLDescriptor));const D={_features:g,_features2:I,_meshFeatures:e,_meshBGL:c,_shadowBGL:l,_composed:i,_pipelines:new Map};return r&&(D._stencil=r._desc),nm.set(E,D),D}function o0A(A,g,I,e){WT(A);const t=aQ(),i=g._sampleCount>1&&!!t?.(e),o=`${Ot(g)}${i?":a2c":""}`,Q=I._pipelines.get(o);if(Q)return Q;const r=A._device,{_features:E,_features2:n,_composed:s}=I,c=(n&yo)!==0,l=!c&&(E&YC)!==0,D=(E&Cm)!==0,p=Mt(A),y=I._shadowBGL?[p,I._meshBGL,I._shadowBGL]:[p,I._meshBGL],_=t?I._a2cVertModule??=r.createShaderModule({code:s._vertexWGSL}):r.createShaderModule({code:s._vertexWGSL}),u=(n&rr)!==0,f=!g._colorFormat&&!u?null:t?I._a2cFragModule??=r.createShaderModule({code:s._fragmentWGSL}):r.createShaderModule({code:s._fragmentWGSL}),h=u?null:{format:g._colorFormat,writeMask:ai.ALL};l&&h&&(h.blend={color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one",operation:"add"}});const w=r.createRenderPipeline({layout:r.createPipelineLayout({bindGroupLayouts:y}),vertex:{module:_,entryPoint:"main",buffers:s._vertexBufferLayouts},...f?{fragment:{module:f,entryPoint:"main",targets:h?[h]:[]}}:{},...g._depthStencilFormat?{depthStencil:{format:g._depthStencilFormat,depthCompare:g._depthCompare??HQ,depthWriteEnabled:u||c||!l,...Em&&I._stencil&&g._depthStencilFormat.includes("stencil")?I._stencil:{}}}:{},multisample:i?{count:g._sampleCount,alphaToCoverageEnabled:!0}:{count:g._sampleCount},primitive:{cullMode:D?"none":"back",...s._prim}});return I._pipelines.set(o,w),w}function L4(A,g,I,e,t,i,o,Q,r){const E=A._device,n=g._features,s=g._features2,c=g._meshFeatures,l=(n&EQ)!==0&&(c&Er)!==0,D=(n&EQ)!==0&&(c&Er)===0,p=l||D,y=(n&Im)!==0,_=(n&tm)!==0,u=(s&yo)!==0,f=[];let h=0;const w=F=>{f.push({binding:h++,resource:F.view}),f.push({binding:h++,resource:F.sampler})},M={_engine:A,_features:n,_features2:s,_meshFeatures:c,_material:i,_mesh:Q??void 0,_env:o??VT?.(i)??null,_refractionTexture:r},S=XsA(),R=I._fragmentKey?I._fragmentKey.split("|").filter(F=>F.length>0):[];f.push({binding:h++,resource:{buffer:e}}),f.push({binding:h++,resource:{buffer:t}});for(const F of S)F.phase==="vertex"&&F.bind&&(h=F.bind(M,f,h));w(i.baseColorTexture??k4?.(A)),p&&w(i.normalTexture),w(i.ormTexture??k4?.(A)),(s&Qr)!==0&&(c&sr)!==0&&i.occlusionTexture&&i.occlusionTexCoord===1&&w(i.occlusionTexture),y&&w(i.emissiveTexture),_&&w(i.specGlossTexture),u&&f.push({binding:h++,resource:{buffer:i._esmShadowParamsUBO}});const N=[];for(const F of R){const G=S.find(m=>m.id===F||F.startsWith(m.id+"-"));!G||G.phase==="vertex"||!G.bind||N.includes(G)||(N.push(G),h=G.bind(M,f,h))}return E.createBindGroup({layout:g._meshBGL,entries:f})}let Y4=null;function sm(){if(Y4)return Y4;const A=async(g,I)=>{const e=g._envTextures,i=await(await Promise.resolve().then(()=>QYA)).buildPbrRenderables(g,I,e);return A._rebuildSingle=i.rebuildSingle,i};return A._materialFamily="pbr",Y4=A}function J4(A){let g=(A.emissiveTexture?Im:0)|(A.normalTexture?EQ:0)|(A.alphaBlend===!0||(A._alphaCutOff??0)<=0&&A.alpha<1?YC:0)|(A.specGlossTexture?tm:0)|(A.doubleSided?Cm:0);(A.occlusionStrength??1)>0&&(g|=YT),A.enableSpecularAA&&(g|=JT);let I=0;for(const e of nQ().values())if(e.detect){const t=e.detect(A);g|=t.f,I|=t.f2}return A._uv2Mask&&(I|=Qr),A.baseColorFactor&&(I|=xT),{features:g,features2:I}}function zT(A){return e0A(g=>g._pbrFallbackTex??=KT(g,1,1,1)),{...A,_buildGroup:sm(),_uboVersion:0}}function lN(A){const g=[];for(const I of[A.baseColorTexture,A.normalTexture,A.ormTexture,A.occlusionTexture,A.emissiveTexture,A.specGlossTexture])I&&g.push(I);for(const I of nQ().values())I.textures?.(A,g);return g}const B0A=Object.freeze(Object.defineProperty({__proto__:null,_computePbrMaterialFeatures:J4,collectPbrBoundTextures:lN,createPbrMaterial:zT,getPbrGroupBuilder:sm},Symbol.toStringTag,{value:"Module"}));function am(A){const g=Math.max(0,Math.min(1,A));return Math.round((g<=.0031308?g*12.92:1.055*Math.pow(g,1/2.4)-.055)*255)}function cm(A){const g=Math.max(0,Math.min(255,A))/255;return g<=.04045?g/12.92:Math.pow((g+.055)/1.055,2.4)}function Q0A(A,g=1){return[cm(A>>16&255),cm(A>>8&255),cm(A&255),g]}const v4=A=>A;function _o(A,g,I,e,t,i){const o=A._device,Q=g?.width??1,r=g?.height??1,E=I?"rgba8unorm-srgb":"rgba8unorm",n=g?XQ(Q,r):1,s=o.createTexture({size:{width:Q,height:r},format:E,usage:dA.TEXTURE_BINDING|dA.COPY_DST|dA.COPY_SRC|dA.RENDER_ATTACHMENT,mipLevelCount:n});g?(o.queue.copyExternalImageToTexture({source:g},{texture:s,premultipliedAlpha:!1},{width:Q,height:r}),t(A,s)):o.queue.writeTexture({texture:s},i??new mg([255,255,255,255]),{bytesPerRow:4},{width:1,height:1});const c={texture:s,view:s.createView(),sampler:e,width:Q,height:r};return A._dlr?.b(c,g,I,!!g,i),c}function H4(A,g,I,e){return _o(A,null,!0,I,e,new mg([am(g[0]),am(g[1]),am(g[2]),Math.round(Math.max(0,Math.min(1,g[3]))*255)]))}function lm(A,g,I,e,t){const i=o=>Math.round(Math.max(0,Math.min(1,o))*255);return _o(A,null,!1,e,t,new mg([255,i(g),i(I),255]))}function r0A(A,g){const I=A._emissiveFactor;return!(I[0]===0&&I[1]===0&&I[2]===0||g&&I[0]===1&&I[1]===1&&I[2]===1)}async function ZT(A,g){if(!A._emissiveColor&&r0A(g,A.emissiveTexture)){const{setPbrEmissive:I}=await Promise.resolve().then(()=>$DA),e=g._emissiveFactor;I(A,[e[0],e[1],e[2]])}if(g._alphaMode==="MASK"){const{setPbrAlphaCutoff:I}=await Promise.resolve().then(()=>TDA);I(A,g._alphaCutoff)}}function E0A(A,g,I,e,t,i){return{baseColorTexture:g,normalTexture:e,ormTexture:I,emissiveTexture:t,...A._baseColorImage&&!n0A(A._baseColorFactor)?{baseColorFactor:A._baseColorFactor}:void 0,doubleSided:A._doubleSided,occlusionStrength:A._occlusionImage?1:0,...A._normalScale!==1?{normalTextureScale:A._normalScale}:void 0,...A._metallicRoughnessImage?{metallicFactor:A._metallicFactor,roughnessFactor:A._roughnessFactor}:void 0,enableSpecularAA:!0,...A._alphaMode==="BLEND"?{alphaBlend:!0,alpha:A._baseColorFactor[3]}:void 0,...A._alphaMode==="MASK"?{alpha:A._baseColorFactor[3]}:void 0,...A._rawMatDef?.name?{name:A._rawMatDef.name}:void 0,...i,_buildGroup:sm(),_uboVersion:0}}function n0A(A){return A[0]===1&&A[1]===1&&A[2]===1&&A[3]===1}function s0A(A,g,I,e,t){const i=g._baseColorImage?t(g._baseColorImage,!0):H4(A,g._baseColorFactor,I,e),o=g._normalImage?t(g._normalImage,!1):void 0,Q=g._emissiveImage?t(g._emissiveImage,!0):void 0,r=g._metallicRoughnessImage??g._occlusionImage;let E;return r&&(!g._metallicRoughnessImage||!g._occlusionImage||g._metallicRoughnessImage===g._occlusionImage)?E=t(r,!1):r?E=t(g._metallicRoughnessImage,!1):E=lm(A,g._roughnessFactor,g._metallicFactor,I,e),{baseColorTexture:i,ormTexture:E,normalTexture:o,emissiveTexture:Q}}let T4;function a0A(A,g){const I=T4;T4=(e,t)=>{I?.(e,t),A(e)&&t.push(g)}}function c0A(A,g){T4?.(A,g)}let l0A;function XT(){return l0A??=Promise.resolve().then(()=>CIA)}let D0A;function p0A(){return D0A??=Promise.resolve().then(()=>P5A)}let y0A;function x4(){return y0A??=Promise.resolve().then(()=>V5A)}function $T(A,g,I,e,t){const[i,o]=yi(g._positions),Q=g._indices,r=Q instanceof Vg,E=t?t._gpu:{positionBuffer:wI(A,g._positions,SA.VERTEX),normalBuffer:wI(A,g._normals,SA.VERTEX),tangentBuffer:g._tangents?wI(A,g._tangents,SA.VERTEX):null,uvBuffer:wI(A,g._uvs,SA.VERTEX),uv2Buffer:g._uv2s?wI(A,g._uv2s,SA.VERTEX):null,colorBuffer:g._colors?wI(A,g._colors,SA.VERTEX):null,indexBuffer:wI(A,Q,SA.INDEX),indexCount:g._indexCount,indexFormat:r?"uint32":"uint16"},n=tN({name:e,material:I,receiveShadows:!1,boundMin:i,boundMax:o,_gpu:E,_flatNormal:g._flatNormal});return n._cpuPositions=g._positions,n._cpuNormals=g._normals,n._cpuUvs=g._uvs,n._cpuIndices=t?t._cpuIndices:r?Q:new Vg(Q),A._dlr?.m(n,g._uv2s,g._tangents,g._colors,Q,E.indexFormat),n}async function q4(A,g){const{json:I,binChunk:e,baseUrl:t}=await _0A(g),i=ZsA(I),o=new Map,Q=u0A(I)?await p0A():void 0,r=Q?await Q.loadGltfFeatures(I):[];c0A(I,r);let E=e;for(const w of r)if(w.preParse){const M=await w.preParse(I,E);M&&(E=M)}const n=r.filter(w=>w.applyMaterial),s=r.filter(w=>w.wrapTexture).map(w=>w.wrapTexture),c=s.length?(w,M)=>s.reduce((S,R)=>R(S,M),w):v4,l=new Map;for(const w of await Promise.all(r.flatMap(M=>M.preMesh?[M.preMesh(I,E,t)]:[])))for(const[M,S]of w)l.set(M,S);const D=await f0A(I,E,t,i,o,l),p={_engine:A,_json:I,_binChunk:E,_baseUrl:t,_parentMap:i,_worldMatrixCache:o,_matExts:n,_runMatExts:Q?.runGltfMaterialFeatures,_wrapTex:c},y=await w0A(D,r,p),{root:_,nodeMap:u}=h0A(I,y,D);p._nodeMap=u;const f=await Promise.all(r.flatMap(w=>w.applyAsset?[w.applyAsset(y,_,p)]:[])),h={entities:[_]};for(const w of f){w.entities?.length&&h.entities.push(...w.entities);const{entities:M,_sceneSetup:S,...R}=w;if(Object.assign(h,R),S){const N=h._sceneSetup;h._sceneSetup=(F,G)=>{N?.(F,G),S(F,G)}}}return h}async function _0A(A){const g=typeof A=="string";let I="";if(g)try{I=new URL(".",new URL(A,globalThis.location?.href))+""}catch{}const e=g?await(await fetch(A)).arrayBuffer():A instanceof Blob?await A.arrayBuffer():A;return e.byteLength>=4&&new H1(e).getUint32(0,!0)===1179937895?{...(await Promise.resolve().then(()=>z5A)).parseGlbContainer(e),baseUrl:I}:(await Promise.resolve().then(()=>$gA)).parseGltfJsonAsset(e,I)}function u0A(A){return A.extensionsUsed?.length||A.animations?.length||/extras|sparse/.test(JSON.stringify(A))||A.skins?.length&&QQ(A,g=>g.attributes?.JOINTS_0!==void 0)||QQ(A,g=>!!g.targets?.length)||A.nodes?.some(g=>g.scale?g.scale[0]*g.scale[1]*g.scale[2]<0:g.matrix?IN(g.matrix)<0:!1)||QQ(A,g=>g.mode!==void 0&&g.mode!==4)||mT(A)}function h0A(A,g,I){const e=[];for(let E=0;E<I.length;E++){const n=I[E]._nodeIndex;(e[n]??=[]).push(g[E])}const t=new Array(A.nodes?.length??0);function i(E){const n=A.nodes[E],s=n.name??`node_${E}`;let c;if(n.matrix)c=g4(s,n.matrix);else{const D=n.translation??[0,0,0],p=n.rotation??[0,0,0,1],y=n.scale??[1,1,1];c=b1(s,D[0],D[1],D[2],p[0],p[1],p[2],p[3],y[0],y[1],y[2])}if(t[E]=c,n.children)for(const D of n.children)c.children.push(i(D));const l=e[E]??[];return c.children.push(...l),c}const Q=(A.scenes?.[A.scene??0]?.nodes??[]).map(E=>i(E)),r=b1("__root__",0,0,0,0,0,0,1,-1,1,1);return r.children.push(...Q),{root:r,nodeMap:t}}async function f0A(A,g,I,e,t,i){const o=[],Q=[],r=p=>{const y=(p??-1)+1;return Q[y]??=bT(A,g,y-1,I,o)},E=[],n=[],s=A.accessors,c=A.bufferViews,l=p=>{for(const y in p.attributes){const _=s[p.attributes[y]],u=c?.[_?.bufferView]?.byteStride;if(u!==void 0&&u!==(po[_.type]??1)*(_.componentType===5126||_.componentType===5125?4:_.componentType===5123||_.componentType===5122?2:1))return!0}return!1};for(let p=0;p<A.nodes.length;p++){const y=A.nodes[p];if(y.mesh===void 0)continue;const _=y.mesh,u=A.meshes[_],f=rQ(A,p,e,t);for(let h=0;h<u.primitives.length;h++){const w=u.primitives[h],M=w.attributes,S=i.get(w);if(!S&&l(w)){const P=await(await XT()).buildInterleavedPartial(A,g,w,f,p);if(P){n.push(r(w.material)),E.push(P);continue}}const R=P=>{if(S&&S._attributes.has(P)){const yA=S._attributes.get(P),cA=yA.length/S._vertexCount;return{_data:yA,_count:S._vertexCount,_componentCount:cA}}const gA=M[P];return gA!==void 0?p1(A,g,gA):null},N=R("POSITION"),F=R("NORMAL"),G=R("TEXCOORD_0"),m=R("TEXCOORD_1"),K=R("TANGENT"),k=R("COLOR_0"),L=S?S._indexCount>0?{_data:S._indices,_count:S._indexCount}:null:w.indices!==void 0?p1(A,g,w.indices):null,H=!L||!F?await Promise.resolve().then(()=>m5A):null,q=k?(await x4()).normalizeColorToVec4(k._data,k._count,k._componentCount):null,CA=G?G._data instanceof X?G._data:(await x4()).normalizeUvToVec2(G._data,G._count):new X(N._count*2),eA=m?m._data instanceof X?m._data:(await x4()).normalizeUvToVec2(m._data,m._count):null,Z=L?L._data instanceof Vg?new Vg(L._data):L._data instanceof mg?Uint16Array.from(L._data):new N1(L._data.buffer,L._data.byteOffset,L._count):H.createSequentialIndices(N._count);n.push(r(w.material));const O=F?F._data:H.computeSmoothNormals(N._data,Z,N._count);E.push({_positions:N._data,_normals:O,_tangents:K?K._data:null,_uvs:CA,_uv2s:eA,_colors:q,_flatNormal:!F,_indices:Z,_vertexCount:N._count,_indexCount:Z.length,_worldMatrix:f,_nodeIndex:p,_primitive:w,_decoded:S})}}const D=await Promise.all(n);return E.map((p,y)=>({...p,_material:D[y]}))}let cQ=null;async function d0A(){cQ||(cQ=(await Promise.resolve().then(()=>zR)).generateMipmaps)}async function w0A(A,g,I){const{_engine:e,_json:t,_binChunk:i,_baseUrl:o,_matExts:Q,_wrapTex:r}=I,E=Pe(e,{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat",maxAnisotropy:4});let n,s;if(t.samplers?.some(S=>S.wrapS>10497||S.wrapT>10497||S.magFilter===9728||S.minFilter!=null&&S.minFilter!==9729&&S.minFilter!==9987)){const S=await Promise.resolve().then(()=>AJA);n=S.makeSamplerFor(e,t,E),s=S.buildSampledPbrTextures}await d0A();const c=g.filter(S=>S.applyMesh),l=new Map,D=(S,R)=>{let N=l.get(S);N||l.set(S,N=[]);const F=+R;let G=N[F];return G||(G=_o(e,S,R,E,cQ),N[F]=G),G},p=Q.length?[]:null,y=p?d4(t,i,o,p):null,_={_engine:e,async _texture(S,R){if(!S||!y)return;const N=await y(S);return N?r(D(N,R),S):void 0},_uploadImage(S,R){return _o(e,S,R,E,cQ)}};let u=r!==v4;if(!u){const S=t.materials;S&&JSON.stringify(S).includes('"texCoord":1')&&(u=!0)}let f=null;const h=()=>f??=Promise.resolve().then(()=>CJA),w=new Map,M=S=>{let R=w.get(S);return R||(R=(async()=>{const N=Q.length?await I._runMatExts(S,Q,_):void 0;let F;if(u){const G=await h(),m=G.buildDefaultPbrTexturesExt(e,S,E,cQ,D,r,n);F=G.assemblePbrPropsExt(S,m,N),await G.applyGltfUvTransform(F,m)}else{const G=s?s(e,S,E,cQ,n,D):s0A(e,S,E,cQ,D);F=E0A(S,G.baseColorTexture,G.ormTexture,G.normalTexture,G.emissiveTexture,N)}return await ZT(F,S),F})(),w.set(S,R)),R};return new Set(A.map(S=>S._primitive)).size<A.length?Promise.resolve().then(()=>QJA).then(S=>S.share(A,M,$T,c,I)):Promise.all(A.map(async(S,R)=>{const N=await M(S._material),F=t.meshes[t.nodes[S._nodeIndex].mesh].name||`gltf_mesh_${R}`,G=S._vb?(await XT()).buildInterleavedMesh(e,S,R,N,F):$T(e,S,N,F);return G._authoredSign=-1,await Promise.all(c.map(m=>m.applyMesh(S,G,I))),G}))}function P4(A,g,I){return{x:A.x+(g.x-A.x)*I,y:A.y+(g.y-A.y)*I,z:A.z+(g.z-A.z)*I}}const O4="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets/dist/profiles/";async function Ax(A){const g=await fetch(A);if(!g.ok)throw new Error(`WebXR profiles: ${g.status} fetching ${A}`);return await g.json()}function M0A(A,g){for(const I of A){const e=g[I];if(e)return{id:I,path:e.path}}return null}function S0A(A,g){return A.layouts[g]??A.layouts.none??Object.values(A.layouts)[0]??null}function gx(A,g){A.name&&!g.has(A.name)&&g.set(A.name,A);for(const I of A.children)gx(I,g)}function R0A(A,g){const I=[];for(const e of Object.values(A.components)){const t=e.gamepadIndices,i=e.visualResponses;if(i)for(const o of Object.values(i)){const Q=g.get(o.valueNodeName);Q&&I.push({valueNode:Q,minNode:o.minNodeName?g.get(o.minNodeName)??null:null,maxNode:o.maxNodeName?g.get(o.maxNodeName)??null:null,property:o.valueNodeProperty,source:o.componentProperty,states:o.states,buttonIndex:t.button??-1,xAxisIndex:t.xAxis??-1,yAxisIndex:t.yAxis??-1})}}return I}async function Ix(A,g,I,e={}){try{const t=e.baseUrl??O4,i=await Ax(new URL("profilesList.json",t).href),o=M0A(g.profiles,i);if(!o)return null;const Q=new URL(o.path,t).href,r=await Ax(Q),E=S0A(r,I);if(!E?.assetPath)return null;const n=new URL(E.assetPath,Q).href,s=await q4(A,n),c=s.entities[0];if(!c)return null;const l=new Map;return gx(c,l),{container:s,root:c,profileId:r.profileId,_responses:R0A(E,l)}}catch{return null}}function N0A(A,g,I,e,t,i,o,Q,r,E){let n=A*t+g*i+I*o+e*Q;n<0&&(t=-t,i=-i,o=-o,Q=-Q,n=-n);let s,c;if(n>.9995)s=1-r,c=r;else{const u=Math.acos(n),f=Math.sin(u);s=Math.sin((1-r)*u)/f,c=Math.sin(r*u)/f}let l=s*A+c*t,D=s*g+c*i,p=s*I+c*o,y=s*e+c*Q;const _=Math.hypot(l,D,p,y)||1;l/=_,D/=_,p/=_,y/=_,E.x=l,E.y=D,E.z=p,E.w=y}function G0A(A){return A?A.pressed?"pressed":A.touched?"touched":"default":"default"}const DN={x:0,y:0,z:0,w:1};function F0A(A,g){if(!A.minNode||!A.maxNode)return;const I=A.minNode,e=A.maxNode,t=P4(I.position,e.position,g);A.valueNode.position.set(t.x,t.y,t.z);const i=P4(I.scaling,e.scaling,g);A.valueNode.scaling.set(i.x,i.y,i.z);const o=I.rotationQuaternion,Q=e.rotationQuaternion;N0A(o.x,o.y,o.z,o.w,Q.x,Q.y,Q.z,Q.w,g,DN),A.valueNode.rotationQuaternion.set(DN.x,DN.y,DN.z,DN.w)}function ex(A,g){if(!g)return;const I=g.buttons,e=g.axes;for(const t of A._responses){if(t.property==="visibility"){const o=G0A(I[t.buttonIndex]);ke(t.valueNode,t.states.includes(o));continue}let i;t.source==="xAxis"?i=(e[t.xAxisIndex]??0)*.5+.5:t.source==="yAxis"?i=(e[t.yAxisIndex]??0)*.5+.5:t.source==="button"?i=I[t.buttonIndex]?.value??0:i=I[t.buttonIndex]?.pressed?1:0,F0A(t,i)}}const m0A=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_PROFILES_BASE_URL:O4,loadMotionController:Ix,updateMotionController:ex},Symbol.toStringTag,{value:"Module"}));function Dm(A){const g=so(A),I={_lightVersion:0,b(){I._lightVersion++}};return{wm:g,onDirty:()=>{g.markLocalDirty(),I._lightVersion++},lvs:I}}function pm(A,g,I){return Object.defineProperties(A,{parent:{get(){return g.parent},set(e){g.parent=e},enumerable:!0,configurable:!0},worldMatrix:{get(){return g.getWorldMatrix()},enumerable:!0,configurable:!0},worldMatrixVersion:{get(){return g.getWorldMatrixVersion()},enumerable:!0,configurable:!0}}),I&&(Object.defineProperty(A,"_lightVersion",{get(){return I._lightVersion},enumerable:!1,configurable:!0}),A._bumpLightVersion=I.b),tQ(A,g),A}function j4(A,g,I,e=0,t=0,i=0,o){const Q=Math.sqrt(A*A+g*g+I*I)||1,r=A/Q,E=g/Q,n=I/Q;let s=-n,c=r;const l=0,D=Math.sqrt(s*s+l*l+c*c)||1;s/=D,c/=D;const p=E*c-n*l,y=n*s-r*c,_=r*l-E*s,u=o??new X(16),f=u;return f[0]=s,f[1]=l,f[2]=c,f[3]=0,f[4]=p,f[5]=y,f[6]=_,f[7]=0,f[8]=r,f[9]=E,f[10]=n,f[11]=0,f[12]=e,f[13]=t,f[14]=i,f[15]=1,u}function tx(A=[0,1,0],g=1){const I=se(),{wm:e,onDirty:t,lvs:i}=Dm(()=>j4(o.direction.x,o.direction.y,o.direction.z,0,0,0,I)),o=pm({lightType:"hemispheric",children:[],direction:new Ht(A[0],A[1],A[2],t),intensity:g,diffuseColor:[1,1,1],specularColor:[1,1,1],groundColor:[0,0,0],_writeLightUbo:(Q,r)=>{const E=r,n=o.worldMatrix;Q[E]=n[8],Q[E+1]=n[9],Q[E+2]=n[10],Q[E+3]=3,Q[E+4]=o.diffuseColor[0]*o.intensity,Q[E+5]=o.diffuseColor[1]*o.intensity,Q[E+6]=o.diffuseColor[2]*o.intensity,Q[E+8]=o.specularColor[0]*o.intensity,Q[E+9]=o.specularColor[1]*o.intensity,Q[E+10]=o.specularColor[2]*o.intensity,Q[E+12]=o.groundColor[0]*o.intensity,Q[E+13]=o.groundColor[1]*o.intensity,Q[E+14]=o.groundColor[2]*o.intensity}},e,i);return o}function Cx(A,g=1){const I=se();I[0]=1,I[5]=1,I[10]=1,I[15]=1;const e=I,{wm:t,onDirty:i,lvs:o}=Dm(()=>(I[12]=Q.position.x,I[13]=Q.position.y,I[14]=Q.position.z,e)),Q=pm({lightType:"point",children:[],position:new Ht(A[0],A[1],A[2],i),diffuse:[1,1,1],specular:[1,1,1],intensity:g,range:Number.MAX_VALUE,_writeLightUbo:(r,E)=>{const n=E,s=Q.worldMatrix;r[n]=s[12],r[n+1]=s[13],r[n+2]=s[14],r[n+3]=0,r[n+4]=Q.diffuse[0]*Q.intensity,r[n+5]=Q.diffuse[1]*Q.intensity,r[n+6]=Q.diffuse[2]*Q.intensity,r[n+7]=Q.range,r[n+8]=Q.specular[0]*Q.intensity,r[n+9]=Q.specular[1]*Q.intensity,r[n+10]=Q.specular[2]*Q.intensity}},t,o);return Q}const ix=Object.freeze(Object.defineProperty({__proto__:null,createPointLight:Cx},Symbol.toStringTag,{value:"Module"}));function ox(A,g=1){const I=se(),{wm:e,onDirty:t,lvs:i}=Dm(()=>j4(o.direction.x,o.direction.y,o.direction.z,o.position.x,o.position.y,o.position.z,I)),o=pm({lightType:"directional",children:[],direction:new Ht(A[0],A[1],A[2],t),position:new Ht(0,0,0,t),diffuse:[1,1,1],specular:[1,1,1],intensity:g,_writeLightUbo:(Q,r)=>{const E=r,n=o.worldMatrix;Q[E]=n[8],Q[E+1]=n[9],Q[E+2]=n[10],Q[E+3]=1,Q[E+4]=o.diffuse[0]*o.intensity,Q[E+5]=o.diffuse[1]*o.intensity,Q[E+6]=o.diffuse[2]*o.intensity,Q[E+7]=Number.MAX_VALUE,Q[E+8]=o.specular[0]*o.intensity,Q[E+9]=o.specular[1]*o.intensity,Q[E+10]=o.specular[2]*o.intensity}},e,i);return o}const b0A=Object.freeze(Object.defineProperty({__proto__:null,createDirectionalLight:ox},Symbol.toStringTag,{value:"Module"}));function Bx(A,g,I,e,t=1){const i=se(),{wm:o,onDirty:Q,lvs:r}=Dm(()=>j4(s.direction.x,s.direction.y,s.direction.z,s.position.x,s.position.y,s.position.z,i));let E=I,n=Math.cos(I*.5);const s=pm({lightType:"spot",children:[],position:new Ht(A[0],A[1],A[2],Q),direction:new Ht(g[0],g[1],g[2],Q),angle:0,exponent:e,diffuse:[1,1,1],specular:[1,1,1],intensity:t,range:Number.MAX_VALUE,_writeLightUbo:(c,l)=>{const D=l,p=s.worldMatrix;c[D]=p[12],c[D+1]=p[13],c[D+2]=p[14],c[D+3]=2,c[D+4]=s.diffuse[0]*s.intensity,c[D+5]=s.diffuse[1]*s.intensity,c[D+6]=s.diffuse[2]*s.intensity,c[D+7]=s.range,c[D+8]=s.specular[0]*s.intensity,c[D+9]=s.specular[1]*s.intensity,c[D+10]=s.specular[2]*s.intensity,c[D+11]=s.exponent,c[D+12]=p[8],c[D+13]=p[9],c[D+14]=p[10],c[D+15]=n}},o,r);return Object.defineProperty(s,"angle",{get(){return E},set(c){c!==E&&(E=c,n=Math.cos(c*.5),r.b())},configurable:!0,enumerable:!0}),s}const K0A=Object.freeze(Object.defineProperty({__proto__:null,createSpotLight:Bx},Symbol.toStringTag,{value:"Module"})),Qx="struct clusteredLightParamsUniforms{tileCountX:u32,tileCountY:u32,zSlices:u32,lightCount:u32,sliceScale:f32,sliceBias:f32,dataTextureWidth:u32,batchCount:u32,};fn clusteredTexel(index:u32)->vec2<u32>{return vec2<u32>(index%clusteredLightParams.dataTextureWidth,index/clusteredLightParams.dataTextureWidth);}";function rx(A,g){return`{let clip=scene.viewProjection*vec4<f32>(input.worldPos,1.0);let ndc=clip.xyz/clip.w;let tx=clamp(u32((ndc.x*0.5+0.5)*f32(clusteredLightParams.tileCountX)),0u,clusteredLightParams.tileCountX-1u);let ty=clamp(u32((0.5-ndc.y*0.5)*f32(clusteredLightParams.tileCountY)),0u,clusteredLightParams.tileCountY-1u);let viewPos=scene.view*vec4<f32>(input.worldPos,1.0);let tzi=clamp(i32(log(max(viewPos.z,0.0001))*clusteredLightParams.sliceScale+clusteredLightParams.sliceBias),0,i32(clusteredLightParams.zSlices)-1);let slice=textureLoad(clusteredCells,clusteredTexel(u32(tzi)),0);let directRoughnessCluster=max(roughness,AA_factor_x);let directAlphaGCluster=directRoughnessCluster*directRoughnessCluster+0.0005;if(slice.x<=slice.y){let firstLight=slice.x;let lastLight=min(slice.y,clusteredLightParams.lightCount-1u);let firstBatch=firstLight/32u;let lastBatch=lastLight/32u;for(var batch=firstBatch;batch<=lastBatch;batch++){let batchOffset=batch*32u;let tileMaskIndex=(tx*clusteredLightParams.tileCountY+ty)*clusteredLightParams.batchCount+batch;var mask=textureLoad(clusteredIndices,clusteredTexel(tileMaskIndex),0).x;let maskOffset=max(firstLight,batchOffset)-batchOffset;let maskWidth=min(lastLight-batchOffset+1u,32u);mask=extractBits(mask,maskOffset,maskWidth);while(mask!=0u){let trailing=firstTrailingBit(mask);mask^=1u<<trailing;let li=batchOffset+maskOffset+trailing;let lightTexel=li*${A};let positionRange=textureLoad(clusteredLights,clusteredTexel(lightTexel),0);let colorIntensity=textureLoad(clusteredLights,clusteredTexel(lightTexel+1u),0);let toLight=positionRange.xyz-input.worldPos;let d2=dot(toLight,toLight);let dist=sqrt(d2);let range=max(positionRange.w,0.0001);if(dist<range){let Lc=toLight/max(dist,0.0001);let NdotLc=max(dot(N,Lc),0.0);let range2=max(range*range,0.0000001);let falloffFactor=d2/range2;var rangeAtt=1.0/max(d2,0.0000001);var smoothRange=saturate(1.0-falloffFactor*falloffFactor);smoothRange*=smoothRange;rangeAtt*=smoothRange;${g}let lightRadiance=colorIntensity.rgb*colorIntensity.a*rangeAtt*material.directIntensity;directDiffuse+=surfaceAlbedo*(1.0/PI)*NdotLc*lightRadiance;if(NdotLc>0.0){let Hc=normalize(V+Lc);let NdotHc=clamp(dot(N,Hc),0.0000001,1.0);let VdotHc=saturate(dot(V,Hc));let Dc=distributionGGX(NdotHc,directAlphaGCluster);let Gc=geometrySmithGGX(NdotLc,NdotV,directAlphaGCluster);let Fc=fresnelSchlick(VdotHc,colorF0,colorF90);directSpecular+=Fc*Dc*Gc*NdotLc*lightRadiance;}}}}}}`}function k0A(){return rx("2u","")}function U0A(){return rx("3u","let dirCone=textureLoad(clusteredLights,clusteredTexel(lightTexel+2u),0);if(dirCone.w>=0.0){let cd=dot(-dirCone.xyz,Lc);let coneAtt=saturate((cd-dirCone.w)/max(1.0-dirCone.w,0.001));rangeAtt*=coneAtt*coneAtt;}")}const Ex=16384,L0A={id:"clustered-spot-lights",phase:"fragment",detect(A){return A._clusteredLightState?._hasSpots?{f:Ex,f2:0}:{f:0,f2:0}},frag(A){if((A._features&Ex)===0)return null;const g=U0A();return{_id:"clustered-spot-lights",_bindings:[{_name:"clusteredLightParams",_type:{_kind:"uniform-buffer"},_visibility:NA.FRAGMENT},{_name:"clusteredLights",_type:{_kind:"texture",_textureType:"texture_2d<f32>",_sampleType:"unfilterable-float"},_visibility:NA.FRAGMENT},{_name:"clusteredCells",_type:{_kind:"texture",_textureType:"texture_2d<u32>"},_visibility:NA.FRAGMENT},{_name:"clusteredIndices",_type:{_kind:"texture",_textureType:"texture_2d<u32>"},_visibility:NA.FRAGMENT}],_helperFunctions:Qx,_fragmentSlots:{AD:g,BL:g}}},bind(A,g,I){const e=A._material._clusteredLightState;return e&&(g.push({binding:I++,resource:{buffer:e.paramsBuffer}}),g.push({binding:I++,resource:e.lightsView}),g.push({binding:I++,resource:e.cellsView}),g.push({binding:I++,resource:e.indicesView})),I}};function Y0A(A){A._spotSupport||(A._spotSupport=J0A,tt(L0A))}const J0A={_create(A){const g=new X(A*4);return g.fill(Number.NaN),{_stride:3,_coneChanged(e,t){const i=e*4,o=g[i]!==t.direction[0]||g[i+1]!==t.direction[1]||g[i+2]!==t.direction[2]||g[i+3]!==t.angle;return g[i]=t.direction[0],g[i+1]=t.direction[1],g[i+2]=t.direction[2],g[i+3]=t.angle,o},_collect(e,t,i){for(const o of t)o.range>0&&o.intensity>0&&e.push({light:o,_spot:o,depth:i[2]*o.position[0]+i[6]*o.position[1]+i[10]*o.position[2]+i[14]})},_write(e,t,i){if(!i){e[t+8]=0,e[t+9]=0,e[t+10]=0,e[t+11]=-1;return}const o=i.direction[0],Q=i.direction[1],r=i.direction[2],E=Math.sqrt(o*o+Q*Q+r*r),n=E===0||E===1?1:1/E;e[t+8]=o*n,e[t+9]=Q*n,e[t+10]=r*n,e[t+11]=Math.cos(Math.min(Math.max(i.angle,0),Math.PI)*.5)},_markState(e){e._hasSpots=!0}}}},nx=8192,v0A=8192,pN=32,H0A=4294967295;function T0A(A){return{kind:"clusteredLightContainer",pointLights:[],spotLights:[],horizontalTiles:A?.horizontalTiles??64,verticalTiles:A?.verticalTiles??64,zSlices:A?.zSlices??16,_version:0}}function x0A(A,g){const I={position:g.position,diffuse:g.diffuse,range:g.range??1,intensity:g.intensity??1};return A.pointLights.push(I),A._version++,I}function q0A(A,g){Y0A(A);const I={position:g.position,direction:g.direction,diffuse:g.diffuse,range:g.range??1,intensity:g.intensity??1,angle:g.angle??Math.PI/2};return A.spotLights.push(I),A._version++,I}function P0A(A){A._version++}function O0A(A,g){const I=A;I._clusteredLightContainer=g,tt(j0A);const e=V0A(I.surface.engine,I,g);I._clusteredLightUpdater=(t,i,o)=>e.refresh(t,i,o),I._disposables.push(()=>e.dispose());for(const t of I.meshes)if(t.material){const i=t.material;i._clusteredLightState=e,i._renderFeatures=void 0}}const j0A={id:"clustered-lights",phase:"fragment",detect(A){const g=A._clusteredLightState;return g&&!g._hasSpots?{f:nx,f2:0}:{f:0,f2:0}},frag(A){if((A._features&nx)===0)return null;const g=k0A();return{_id:"clustered-lights",_bindings:[{_name:"clusteredLightParams",_type:{_kind:"uniform-buffer"},_visibility:NA.FRAGMENT},{_name:"clusteredLights",_type:{_kind:"texture",_textureType:"texture_2d<f32>",_sampleType:"unfilterable-float"},_visibility:NA.FRAGMENT},{_name:"clusteredCells",_type:{_kind:"texture",_textureType:"texture_2d<u32>"},_visibility:NA.FRAGMENT},{_name:"clusteredIndices",_type:{_kind:"texture",_textureType:"texture_2d<u32>"},_visibility:NA.FRAGMENT}],_helperFunctions:Qx,_fragmentSlots:{AD:g,BL:g}}},bind(A,g,I){const e=A._material._clusteredLightState;return e&&(g.push({binding:I++,resource:{buffer:e.paramsBuffer}}),g.push({binding:I++,resource:e.lightsView}),g.push({binding:I++,resource:e.cellsView}),g.push({binding:I++,resource:e.indicesView})),I}};function V0A(A,g,I){const e=g.camera;e||U(112);const t=Math.max(1,A.canvas.width),i=Math.max(1,A.canvas.height),o=Math.max(1,I.horizontalTiles|0),Q=Math.max(1,I.verticalTiles|0),r=Math.max(1,I.zSlices|0),E=Math.max(1,Math.min(v0A,A._device.limits.maxTextureDimension2D)),n=I.pointLights,s=I.spotLights,c=I._spotSupport?._create(s.length),l=n.length,D=c?s.length:0,p=l+D,y=c?._stride??2,_=Math.max(1,Math.ceil(p/pN)),u=Math.max(1,p*y),f=Math.max(1,o*Q*_),h=Math.min(E,Math.max(u,r,f)),w=new X(V4(u,4,h)),M=new Vg(V4(r,4,h)),S=new Vg(V4(f,1,h)),R=new X(p*8);R.fill(Number.NaN);const N=[],F=new ArrayBuffer(32),G=new Vg(F),m=new X(F);G[0]=o,G[1]=Q,G[2]=r,G[3]=p,m[4]=e.nearPlane,m[5]=e.farPlane,G[6]=h,G[7]=_;const K=Re(A,m,"clustered-light-params"),k=W4(A,"rgba32float",u,"clustered-light-data",h),L=W4(A,"rgba32uint",r,"clustered-slice-data",h),H=W4(A,"r32uint",f,"clustered-tile-mask-data",h);let q,CA=-1,eA=0,Z=0,O=-1,P=-1,gA=-1;const yA={paramsBuffer:K,lightsView:k.createView(),cellsView:L.createView(),indicesView:H.createView(),refresh(cA,RA,YA){if(!cA)return;const Ag=Math.max(1,RA),lg=Math.max(1,YA),mA=KC(cA,Ag,lg),HA=T1(cA),Qg=I.pointLights,Eg=I.spotLights,kA=I._version,ug=Qg.length+(c?Eg.length:0);if(cA===q&&HA===CA&&Ag===eA&&lg===Z&&mA===O&&kA===P&&ug===gA)return;(ug*y>u||Math.ceil(ug/pN)>_||!!I._spotSupport!=!!c)&&U(113);let fg=cA!==q||HA!==CA||Ag!==eA||lg!==Z||mA!==O||ug!==gA,rg=fg;if(kA!==P||ug!==gA){let ag=0;for(let Rg=0;Rg<Qg.length;Rg++){const UA=sx(R,ag++,Qg[Rg]);fg||=(UA&1)!==0,rg||=(UA&2)!==0}if(c)for(let Rg=0;Rg<Eg.length;Rg++){const UA=Eg[Rg],$A=sx(R,ag++,UA),vg=c._coneChanged(Rg,UA);fg||=($A&1)!==0,rg||=($A&2)!==0||vg}}if(!fg&&!rg){P=kA;return}if(fg){rg=!0,M.fill(0),N.length=0;const ag=l1(cA),Rg=li(cA,mA),UA=cA.nearPlane,$A=cA.farPlane,vg=Math.log($A/UA),Jg=r/vg,nI=-(r*Math.log(UA))/vg;for(const pI of Qg)pI.range>0&&pI.intensity>0&&N.push({light:pI,depth:z0A(pI.position,ag)});c?._collect(N,Eg,ag),N.sort((pI,Ye)=>pI.depth-Ye.depth);const qI=Math.max(1,Math.ceil(N.length/pN)),kI=o*Q*qI;S.fill(0,0,kI);for(let pI=0;pI<r;pI++){const Ye=pI*4;M[Ye]=H0A,M[Ye+1]=0}for(let pI=0;pI<N.length;pI++){const{light:Ye,depth:vI}=N[pI];W0A(M,S,Ye,vI,pI,ag,Rg,o,Q,r,Jg,nI,qI)}G[0]=o,G[1]=Q,G[2]=r,G[3]=N.length,m[4]=Jg,m[5]=nI,G[7]=qI,A._device.queue.writeBuffer(K,0,m),z4(A,L,M,4,r,h),N.length>0&&z4(A,H,S,1,kI,h)}if(rg){for(let ag=0;ag<N.length;ag++){const{light:Rg,_spot:UA}=N[ag],$A=ag*y*4;w.set(Rg.position,$A),w[$A+3]=Rg.range,w.set(Rg.diffuse,$A+4),w[$A+7]=Rg.intensity,c?._write(w,$A,UA)}N.length>0&&z4(A,k,w,4,N.length*y,h)}q=cA,CA=HA,eA=Ag,Z=lg,O=mA,P=kA,gA=ug},dispose(){K.destroy(),k.destroy(),L.destroy(),H.destroy()}};return c?._markState(yA),yA.refresh(e,t,i),yA}function V4(A,g,I){return I*Math.max(1,Math.ceil(A/I))*g}function sx(A,g,I){const e=g*8,t=I.position,i=I.diffuse,o=A[e+3]>0&&A[e+7]>0,Q=I.range>0&&I.intensity>0;let r=0;return(A[e]!==t[0]||A[e+1]!==t[1]||A[e+2]!==t[2]||A[e+3]!==I.range||o!==Q)&&(r|=1),(A[e+4]!==i[0]||A[e+5]!==i[1]||A[e+6]!==i[2]||A[e+7]!==I.intensity)&&(r|=2),A.set(t,e),A[e+3]=I.range,A.set(i,e+4),A[e+7]=I.intensity,r}function W4(A,g,I,e,t){const i=Math.max(1,Math.ceil(I/t));return A._device.createTexture({label:e,size:{width:t,height:i},format:g,usage:dA.TEXTURE_BINDING|dA.COPY_DST})}function z4(A,g,I,e,t,i){const o=Math.max(1,Math.ceil(t/i)),Q=o>1?i:Math.max(1,Math.min(t,i));A._device.queue.writeTexture({texture:g},I.buffer,{bytesPerRow:Q*e*4,rowsPerImage:o},{width:Q,height:o})}function W0A(A,g,I,e,t,i,o,Q,r,E,n,s,c){const l=i[0]*I.position[0]+i[4]*I.position[1]+i[8]*I.position[2]+i[12],D=i[1]*I.position[0]+i[5]*I.position[1]+i[9]*I.position[2]+i[13],p=e,y=Math.max(0,I.range),_=ax(p-y,n,s),u=ax(p+y,n,s);if(u<0||_>=E)return;const f=Z0A(l,D,p,y,o,Q,r),h=f[0],w=f[1],M=f[2],S=f[3],R=ar(_,0,E-1),N=ar(u,0,E-1);for(let m=R;m<=N;m++){const K=m*4;A[K]=Math.min(A[K],t),A[K+1]=Math.max(A[K+1],t)}const F=Math.floor(t/pN),G=1<<t%pN;for(let m=M;m<=S;m++)for(let K=h;K<=w;K++){const k=(K*r+m)*c+F;g[k]=g[k]|G}}function z0A(A,g){return g[2]*A[0]+g[6]*A[1]+g[10]*A[2]+g[14]}function ax(A,g,I){return A>0?Math.floor(Math.log(A)*g+I):-1}function ar(A,g,I){return A<g?g:A>I?I:A}function Z0A(A,g,I,e,t,i,o){const Q=e*e;let r=-1,E=1,n=-1,s=1;if(t[11]===0){const c=t[0],l=t[5],D=c*A+t[12],p=l*g+t[13],y=Math.abs(c*e),_=Math.abs(l*e);r=Math.max(D-y,-1),E=Math.min(D+y,1),n=Math.max(p-_,-1),s=Math.min(p+_,1)}else if(I>e){const c=ym(A,I,Q,t[0],-1),l=ym(A,I,Q,t[0],1);r=Math.min(c,l),E=Math.max(c,l);const D=ym(g,I,Q,t[5],-1),p=ym(g,I,Q,t[5],1);n=Math.min(D,p),s=Math.max(D,p)}return[ar(Math.floor((r*.5+.5)*i)-1,0,i-1),ar(Math.floor((E*.5+.5)*i)+1,0,i-1),ar(Math.floor((.5-s*.5)*o)-1,0,o-1),ar(Math.floor((.5-n*.5)*o)+1,0,o-1)]}function ym(A,g,I,e,t){const i=A*A+g*g;if(i<=I)return t;const o=I/i,Q=Math.max(1-o,.01),r=t*Math.sqrt(o*Q),E=Q*A+r*g,n=-r*A+Q*g;return e*E/Math.max(n,.01)}let Z4=null;function cx(){if(Z4)return Z4;const A=async(g,I)=>{const{buildShaderGroup:e}=await Promise.resolve().then(()=>tyA),t=await e(g,I);return A._rebuildSingle=t.rebuildSingle,t};return A._materialFamily="shader",Z4=A}function X0A(A){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(A)}function _m(A,g){X0A(g)||U(289,A,g)}function $0A(A){return A==="position"||A==="normal"||A==="uv"||A==="uv2"||A==="tangent"||A==="color"||A==="joints"||A==="weights"||A==="joints1"||A==="weights1"}function lx(A){return A==="world"||A==="view"||A==="projection"||A==="viewProjection"||A==="worldView"||A==="worldViewProjection"||A==="cameraPosition"||A==="screenSize"||A==="alphaCutoff"}function AaA(A){return A==="cameraPosition"?"vec3<f32>":A==="screenSize"?"vec2<f32>":A==="alphaCutoff"?"f32":"mat4x4<f32>"}function cr(A){return lx(A)}function yN(A){(!A.vertexSource||!A.fragmentSource)&&U(290);const g=[],I=new Set;for(const c of A.attributes)$0A(c)||U(291,String(c)),I.has(c)&&U(292,c),I.add(c),g.push(c);I.has("position")||U(293);const e=[],t=new Map,i=new Set;for(const c of A.uniforms??[]){const l=typeof c=="string"?gaA(c):IaA(c);_N(i,"uniform",l.name),e.push(l),t.set(l.name,{decl:l,value:CaA(l,l.defaultValue??taA(l)),_v:0})}const o=[],Q=new Map;for(const c of A.samplers??[]){const l=typeof c=="string"?{name:c,sampleType:"float"}:{name:c.name,sampleType:c.sampleType??(c.comparison?"depth":"float"),viewDimension:c.viewDimension??"2d",comparison:c.comparison??!1};_m("sampler",l.name),_N(i,"sampler",l.name),_N(i,"sampler",`${l.name}Sampler`),o.push(l),Q.set(l.name,{decl:l,current:null})}const r=[],E=new Map;for(const c of A.storageBuffers??[])_m("storage buffer",c.name),_N(i,"storage buffer",c.name),r.push(c),E.set(c.name,{decl:c,current:null});const n=[];for(const[c,l]of Object.entries(A.defines??{}))_m("define",c),_N(i,"define",c),typeof l!="boolean"&&typeof l!="number"&&U(294,c),n.push({name:c,value:l});n.sort((c,l)=>c.name.localeCompare(l.name));const s=A.needAlphaBlending??!!A.blend;return A.transmissive&&!s&&U(295),{name:A.name,vertexSource:A.vertexSource,fragmentSource:A.fragmentSource,attributes:g,uniformDecls:e,samplerDecls:o,storageBufferDecls:r,defines:n,_tic:A.useThinInstanceColors,needAlphaBlending:s,blendMode:A.blendMode??"alpha",...A.blend?{blend:A.blend}:{},transmissive:A.transmissive??!1,needAlphaTesting:A.needAlphaTesting??!1,backFaceCulling:A.backFaceCulling??!0,depthWrite:A.depthWrite??!s,depthCompare:A.depthCompare??"greater-equal",depthOnlyFragment:A.depthOnlyFragment??!1,depthBias:A.depthBias??0,depthBiasSlopeScale:A.depthBiasSlopeScale??0,_buildGroup:cx(),_uboVersion:0,_uniformValues:t,_textureSlots:Q,_storageBufferSlots:E,_uniformVersion:0,_resourceVersion:0}}function gaA(A){return lx(A)||U(296,A),{name:A,type:AaA(A)}}function IaA(A){return _m("uniform",A.name),eaA(A.type)||U(297,String(A.type),A.name),A}function eaA(A){return A==="f32"||A==="u32"||A==="i32"||A==="vec2<f32>"||A==="vec3<f32>"||A==="vec4<f32>"||A==="mat4x4<f32>"}function _N(A,g,I){A.has(I)&&U(298,I,g),A.add(I)}function Dx(A){switch(A){case"f32":case"u32":case"i32":return 1;case"vec2<f32>":return 2;case"vec3<f32>":return 3;case"vec4<f32>":return 4;case"mat4x4<f32>":return 16}}function taA(A){if(A.name==="alphaCutoff")return .4;const g=Dx(A.type);return g===1?0:new Array(g).fill(0)}function CaA(A,g){const I=Dx(A.type),e=typeof g=="number"?new X([g]):g instanceof X?new X(g):new X(g);return e.length!==I&&U(299,A.name,A.type,I,e.length),e}function px(A,g,I){const e=A._uniformValues.get(g);e||U(300,g);const t=e.value,i=t.length,o=typeof I=="number"?1:I.length;o!==i&&U(301,e.decl.name,e.decl.type,i,o);let Q=!1;if(typeof I=="number"){const r=Math.fround(I);t[0]!==r&&(t[0]=r,Q=!0)}else for(let r=0;r<i;r++){const E=Math.fround(I[r]);t[r]!==E&&(t[r]=E,Q=!0)}Q&&(e._v=(e._v|0)+1,A._uniformVersion++,A._uboVersion=A._uniformVersion)}function lQ(A,g,I){px(A,g,I)}function yx(A,g,I){const e=A._textureSlots.get(g);if(e||U(302,g),I){const t=e.decl.comparison||e.decl.sampleType==="depth",i=I._sampleType==="depth";t&&!i&&U(303,g),!t&&i&&U(304,g)}e.current!==I&&(e.current=I,A._resourceVersion++,cC())}function iaA(A,g,I){const e=A._storageBufferSlots.get(g);e||U(305,g),I&&!("_engine"in I)&&U(306),I?._destroyed&&U(307,g),I&&!I._engine._storageBuffers?.has(I)&&U(308),e.current!==I&&(e.current=I,A._resourceVersion++,cC())}function oaA(A,g,I){lQ(A,g,I)}function BaA(A,g,I){lQ(A,g,I)}function QaA(A,g,I){px(A,g,I)}let X4=null;function _x(A,g){g.useThinInstances&&!A.thinInstances&&U(177,g.name??"<unnamed>")}function raA(){if(X4)return X4;const A=cx(),g=async(I,e)=>{for(const Q of e)_x(Q,Q.material);const t=await A(I,e),i=t.rebuildSingle,o=(Q,r,E)=>(_x(r,E??r.material),i(Q,r,E));return g._rebuildSingle=o,{...t,rebuildSingle:o}};return g._materialFamily="shader",X4=g}function ux(A){return`struct VertexOutput{@builtin(position)position:vec4<f32>,${A?"@location(0) color:vec4<f32>,":""}};`}function EaA(A,g,I){const e=A||I,t=g?"let instanceWorld=mat4x4<f32>(input.world0,input.world1,input.world2,input.world3);let finalWorld=shaderSystem.world*instanceWorld;":"let finalWorld=shaderSystem.world;",i=A&&I?"out.color=input.color*input.instanceColor;":A?"out.color=input.color;":I?"out.color=input.instanceColor;":"";return`${ux(e)} @vertex fn mainVertex(input:VertexInput)->VertexOutput{var out:VertexOutput;${t}out.position=shaderSystem.viewProjection*finalWorld*vec4<f32>(input.position,1.0);${i}return out;}`}function naA(A){return`${ux(A)} @fragment fn mainFragment(input:VertexOutput)->@location(0)vec4<f32>{return ${A?"input.color":"shaderUniforms.lineColor"};}`}function hx(A={}){const g=A.useVertexColor??!1,I=A.useVertexAlpha??!0,e=A.useThinInstances??!1,t=A.useThinInstanceColors??!1;t&&!e&&U(178);const i=A.color??{r:1,g:1,b:1,a:1},o={r:i.r,g:i.g,b:i.b,a:i.a},Q=g||t,r=yN({name:A.name??"LineMaterial",vertexSource:EaA(g,e,t),fragmentSource:naA(Q),attributes:g?["position","color"]:["position"],uniforms:["world","viewProjection",...Q?[]:[{name:"lineColor",type:"vec4<f32>",defaultValue:[o.r,o.g,o.b,o.a]}]],useThinInstanceColors:t,needAlphaBlending:I,blendMode:"alpha",backFaceCulling:!1,depthWrite:A.depthWrite,depthCompare:A.depthCompare});return Object.assign(r,{useVertexColor:g,useVertexAlpha:I,useThinInstances:e,useThinInstanceColors:t,color:o,_topology:"line-list",_buildGroup:raA()}),r}function saA(A,g){A.color.r=g.r,A.color.g=g.g,A.color.b=g.b,A.color.a=g.a,!A.useVertexColor&&!A.useThinInstanceColors&&lQ(A,"lineColor",[g.r,g.g,g.b,g.a])}function DQ(A,g){Number.isFinite(g)||U(324,A)}function fx(A,g,I,e){const{lines:t,colors:i}=A;i&&i.length!==t.length&&U(325);const o=new Float32Array(g*3),Q=i?new Float32Array(g*4):void 0;let r=0,E=0;for(let n=0;n<t.length;n++){const s=t[n],c=i?.[n];c&&c.length!==s.length&&U(326),I&&(I[n]=s.length);for(let l=0;l<s.length;l++){const D=s[l];DQ("position",D.x),DQ("position",D.y),DQ("position",D.z);const p=r*3;if(o[p]=D.x,o[p+1]=D.y,o[p+2]=D.z,Q&&c){const y=c[l];DQ("color",y.r),DQ("color",y.g),DQ("color",y.b),DQ("color",y.a);const _=r*4;Q[_]=y.r,Q[_+1]=y.g,Q[_+2]=y.b,Q[_+3]=y.a}e&&l>0&&(e[E++]=r-1,e[E++]=r),r++}}return{positions:o,...Q?{colors:Q}:{}}}function dx(A){const{lines:g}=A;let I=0,e=0;for(let r=0;r<g.length;r++){const E=g[r];I+=E.length,e+=Math.max(0,E.length-1)*2}I===0&&U(327);const t=new Float32Array(I*3),i=new Uint32Array(e),o=new Uint32Array(g.length),Q=fx(A,I,o,i);return{positions:Q.positions,normals:t,indices:i,...Q.colors?{colors:Q.colors}:{},linePointCounts:o}}function $4(A,g){const I=dx(g),e=g.material??hx({color:g.color,useVertexColor:!!I.colors,useVertexAlpha:g.useVertexAlpha,useThinInstances:g.useThinInstances,useThinInstanceColors:g.useThinInstanceColors});e.useVertexColor!==!!I.colors&&U(328);const t=Et(A,g.name??"lineSystem",I.positions,I.normals,I.indices,void 0,void 0,void 0,I.colors);return t.material=e,t.hasVertexAlpha=!!I.colors&&e.useVertexAlpha,t._topology=2,t._linePointCounts=I.linePointCounts,t._cpuColors=I.colors??null,t}function aaA(A,g){return $4(A,{name:g.name??"lines",lines:[g.points],...g.colors?{colors:[g.colors]}:{},color:g.color,useVertexAlpha:g.useVertexAlpha,useThinInstances:g.useThinInstances,useThinInstanceColors:g.useThinInstanceColors,material:g.material})}function wx(A,g,I){const e=g._linePointCounts;e||U(329),I.lines.length!==e.length&&U(330);for(let r=0;r<e.length;r++)I.lines[r].length!==e[r]&&U(331);I.colors&&!g._gpu.colorBuffer&&U(332);let t=0;for(const r of e)t+=r;const i=fx(I,t);HF(A,g,i.positions),i.colors&&zH(A,g,i.colors);const[o,Q]=yi(i.positions);g.boundMin=o,g.boundMax=Q,g._cpuPositions=i.positions,i.colors&&(g._cpuColors=i.colors),A._dlr?.m(g,g._cpuUv2s??null,g._cpuTangents??null,g._cpuColors??null,g._cpuIndices,g._cpuIndexFormat??"uint32")}function Mx(A,g,I,e,t){A.length<2&&U(321);let i=0;for(let E=0;E<A.length-1;E++){const n=A[E],s=A[E+1];i+=Math.hypot(s.x-n.x,s.y-n.y,s.z-n.z)}const o=i/e,Q=g*o/(g+I),r=[];for(let E=0;E<A.length-1;E++){const n=A[E],s=A[E+1];let c=s.x-n.x,l=s.y-n.y,D=s.z-n.z;const p=Math.hypot(c,l,D),y=p>0?Math.floor(p/o):0;p>0&&(c/=p,l/=p,D/=p);for(let _=0;_<y&&(t===void 0||r.length<t);_++){const u=o*_;r.push([{x:n.x+u*c,y:n.y+u*l,z:n.z+u*D},{x:n.x+(u+Q)*c,y:n.y+(u+Q)*l,z:n.z+(u+Q)*D}])}}if(t!==void 0){const E=A[A.length-1];for(;r.length<t;)r.push([{x:E.x,y:E.y,z:E.z},{x:E.x,y:E.y,z:E.z}])}return r}function caA(A,g){const I=g.dashSize??3,e=g.gapSize??1,t=g.dashNb??200,i=Mx(g.points,I,e,t);i.length===0&&U(322);const o=$4(A,{name:g.name??"dashedLines",lines:i,color:g.color,useVertexAlpha:g.useVertexAlpha,material:g.material});return o._dashedLineOptions=[I,e],o}function laA(A,g,I){const e=g._dashedLineOptions,t=g._linePointCounts?.length;(!e||!t)&&U(323);const i=Mx(I.points,e[0],e[1],t,t);wx(A,g,{lines:i})}function DaA(A){const g=A._cpuPositions,I=A._cpuIndices;return!g||!I?null:{positions:g.slice(),indices:I.slice()}}function paA(A){const g=A._cpuPositions,I=A._cpuNormals,e=A._cpuIndices;if(!g||!I||!e)return null;const t=A._cpuUvs,i=A._cpuUv2s,o=A._cpuTangents,Q=A._cpuColors;return{positions:g.slice(),normals:I.slice(),indices:e.slice(),...t?{uvs:t.slice()}:{},...i?{uvs2:i.slice()}:{},...o?{tangents:o.slice()}:{},...Q?{colors:Q.slice()}:{}}}function tC(A,g,I,e=1e-10){const t=Math.hypot(A,g,I);return t<=e?[0,1,0]:[A/t,g/t,I/t]}class OJ{constructor(g,I,e,t){this.nx=g,this.ny=I,this.nz=e,this.w=t}clone(){return new OJ(this.nx,this.ny,this.nz,this.w)}flip(){this.nx=-this.nx,this.ny=-this.ny,this.nz=-this.nz,this.w=-this.w}}class WG{constructor(g,I=0){this.vertices=g,this.materialSlot=I,this.plane=_aA(g[0],g[1],g[2])}plane;clone(){return new WG(this.vertices.map(hm),this.materialSlot)}flip(){this.vertices.reverse(),this.vertices=this.vertices.map(g=>({...g,nx:-g.nx,ny:-g.ny,nz:-g.nz})),this.plane.flip()}}class ei{plane=null;polygons=[];front=null;back=null;constructor(g=[]){g.length>0&&this.build(g)}clone(){const g=new ei;return g.plane=this.plane?.clone()??null,g.polygons=this.polygons.map(I=>I.clone()),g.front=this.front?.clone()??null,g.back=this.back?.clone()??null,g}invert(){for(const I of this.polygons)I.flip();this.plane?.flip(),this.front?.invert(),this.back?.invert();const g=this.front;this.front=this.back,this.back=g}clipPolygons(g){if(!this.plane)return g.map(t=>t.clone());let I=[],e=[];for(const t of g)Rx(this.plane,t,I,e,I,e);return this.front&&(I=this.front.clipPolygons(I)),this.back?e=this.back.clipPolygons(e):e=[],I.concat(e)}clipTo(g){this.polygons=g.clipPolygons(this.polygons),this.front?.clipTo(g),this.back?.clipTo(g)}allPolygons(){let g=this.polygons.map(I=>I.clone());return this.front&&(g=g.concat(this.front.allPolygons())),this.back&&(g=g.concat(this.back.allPolygons())),g}build(g){if(g.length===0)return;this.plane||(this.plane=g[0].plane.clone());const I=[],e=[];for(const t of g)Rx(this.plane,t,this.polygons,this.polygons,I,e);I.length>0&&(this.front||(this.front=new ei),this.front.build(I)),e.length>0&&(this.back||(this.back=new ei),this.back.build(e))}}const um=1e-5,Sx=0,A9=1,g9=2,yaA=3;function hm(A){return{x:A.x,y:A.y,z:A.z,nx:A.nx,ny:A.ny,nz:A.nz,u:A.u,v:A.v}}function _aA(A,g,I){const e=g.x-A.x,t=g.y-A.y,i=g.z-A.z,o=I.x-A.x,Q=I.y-A.y,r=I.z-A.z,[E,n,s]=tC(Q*i-r*t,r*e-o*i,o*t-Q*e,1e-20);return new OJ(E,n,s,E*A.x+n*A.y+s*A.z)}function uaA(A,g,I){const e=g.x-A.x,t=g.y-A.y,i=g.z-A.z,o=I.x-A.x,Q=I.y-A.y,r=I.z-A.z,E=t*r-i*Q,n=i*o-e*r,s=e*Q-t*o;return E*E+n*n+s*s}function haA(A,g,I){const e=A.nx+(g.nx-A.nx)*I,t=A.ny+(g.ny-A.ny)*I,i=A.nz+(g.nz-A.nz)*I,[o,Q,r]=tC(e,t,i,1e-20);return{x:A.x+(g.x-A.x)*I,y:A.y+(g.y-A.y)*I,z:A.z+(g.z-A.z)*I,nx:o,ny:Q,nz:r,u:A.u+(g.u-A.u)*I,v:A.v+(g.v-A.v)*I}}function Rx(A,g,I,e,t,i){let o=0;const Q=[];for(const n of g.vertices){const s=A.nx*n.x+A.ny*n.y+A.nz*n.z-A.w,c=s<-um?g9:s>um?A9:Sx;o|=c,Q.push(c)}if(o===Sx){(A.nx*g.plane.nx+A.ny*g.plane.ny+A.nz*g.plane.nz>0?I:e).push(g);return}if(o===A9){t.push(g);return}if(o===g9){i.push(g);return}const r=[],E=[];for(let n=0;n<g.vertices.length;n++){const s=(n+1)%g.vertices.length,c=g.vertices[n],l=g.vertices[s],D=Q[n],p=Q[s];if(D!==g9&&r.push(hm(c)),D!==A9&&E.push(hm(c)),(D|p)===yaA){const y=A.nx*(l.x-c.x)+A.ny*(l.y-c.y)+A.nz*(l.z-c.z);if(Math.abs(y)>1e-20){const _=(A.w-A.nx*c.x-A.ny*c.y-A.nz*c.z)/y,u=haA(c,l,_);r.push(u),E.push(hm(u))}}}r.length>=3&&t.push(new WG(r,g.materialSlot)),E.length>=3&&i.push(new WG(E,g.materialSlot))}function fm(A){return{_polygons:A}}function lr(A){return A._polygons.map(g=>g.clone())}function faA(A,g,I,e){return[A[0]*g+A[4]*I+A[8]*e+A[12],A[1]*g+A[5]*I+A[9]*e+A[13],A[2]*g+A[6]*I+A[10]*e+A[14]]}function daA(A,g,I,e,t){return g?tC(g[0]*I+g[1]*e+g[2]*t,g[4]*I+g[5]*e+g[6]*t,g[8]*I+g[9]*e+g[10]*t,1e-20):tC(A[0]*I+A[4]*e+A[8]*t,A[1]*I+A[5]*e+A[9]*t,A[2]*I+A[6]*e+A[10]*t,1e-20)}function waA(A){return A._cpuPositions||U(333,A.name),A._cpuIndices||U(334,A.name),A._cpuNormals||U(335,A.name),A}function MaA(A,g=0){const I=waA(A),e=I._cpuPositions,t=I._cpuNormals,i=I._cpuIndices,o=I._cpuUvs,Q=A.worldMatrix,r=lt(Q),E=[];for(let n=0;n<i.length;n+=3){const s=[];for(let c=0;c<3;c++){const l=i[n+c],D=l*3,p=l*2,[y,_,u]=faA(Q,e[D],e[D+1],e[D+2]),[f,h,w]=daA(Q,r,t[D],t[D+1],t[D+2]);s.push({x:y,y:_,z:u,nx:f,ny:h,nz:w,u:o?.[p]??0,v:o?.[p+1]??0})}uaA(s[0],s[1],s[2])<=um*um||E.push(new WG(s,g))}return fm(E)}function SaA(A,g){const I=new ei(lr(A)),e=new ei(lr(g));return I.clipTo(e),e.clipTo(I),e.invert(),e.clipTo(I),e.invert(),I.build(e.allPolygons()),fm(I.allPolygons())}function RaA(A,g){const I=new ei(lr(A)),e=new ei(lr(g));return I.invert(),I.clipTo(e),e.clipTo(I),e.invert(),e.clipTo(I),e.invert(),I.build(e.allPolygons()),I.invert(),fm(I.allPolygons())}function NaA(A,g){const I=new ei(lr(A)),e=new ei(lr(g));return I.invert(),e.clipTo(I),e.invert(),I.clipTo(e),e.clipTo(I),I.build(e.allPolygons()),I.invert(),fm(I.allPolygons())}function GaA(A,g,I){const e=[],t=[],i=[],o=[];for(const Q of g){const r=e.length/3;for(const E of Q.vertices)e.push(E.x,E.y,E.z),t.push(E.nx,E.ny,E.nz),i.push(E.u,E.v);for(let E=2;E<Q.vertices.length;E++)o.push(r,r+E-1,r+E)}return Et(A,I,new X(e),new X(t),new Vg(o),new X(i))}function FaA(A,g,I="csg"){return GaA(A,g._polygons,I)}const dm=65536;let Dr=null,pr=null;function maA(){return Dr!==null}async function baA(){await KaA()}async function KaA(){return Dr||pr||(pr=(async()=>{const[A,g]=await Promise.all([Promise.resolve().then(()=>EJA),Promise.resolve().then(()=>sJA)]),I=import.meta.url,e=await A.default({locateFile:()=>new URL(g.default,I).href});e.setup();const t={Manifold:e.Manifold,Mesh:e.Mesh,firstMaterialId:e.Manifold.reserveIDs(dm)};return Dr=t,t})(),pr.catch(()=>{pr=null}),pr)}function wm(){return Dr||U(337),Dr}function Mm(A,g){const I=A._manifold;return I||U(338,g),I}function Nx(A,g){return{_manifold:A,_numProp:g}}function kaA(A,g,I,e){return[A[0]*g+A[4]*I+A[8]*e+A[12],A[1]*g+A[5]*I+A[9]*e+A[13],A[2]*g+A[6]*I+A[10]*e+A[14]]}function UaA(A,g,I,e,t){return g?tC(g[0]*I+g[1]*e+g[2]*t,g[4]*I+g[5]*e+g[6]*t,g[8]*I+g[9]*e+g[10]*t,1e-20):tC(A[0]*I+A[4]*e+A[8]*t,A[1]*I+A[5]*e+A[9]*t,A[2]*I+A[6]*e+A[10]*t,1e-20)}function LaA(A){return A._cpuPositions||U(339,A.name),A._cpuIndices||U(340,A.name),A._cpuNormals||U(341,A.name),{positions:A._cpuPositions,normals:A._cpuNormals,indices:A._cpuIndices,uvs:A._cpuUvs}}function YaA(A,g=0){const I=wm();(g<0||g>=dm||!Number.isInteger(g))&&U(342,A.name,dm-1);const e=LaA(A),t=e.positions.length/3,i=8,o=new X(t*i),Q=A.worldMatrix,r=lt(Q);for(let s=0;s<t;s++){const c=s*3,l=s*2,D=s*i,[p,y,_]=kaA(Q,e.positions[c],e.positions[c+1],e.positions[c+2]),[u,f,h]=UaA(Q,r,e.normals[c],e.normals[c+1],e.normals[c+2]);o[D]=p,o[D+1]=y,o[D+2]=_,o[D+3]=u,o[D+4]=f,o[D+5]=h,o[D+6]=e.uvs?.[l]??0,o[D+7]=e.uvs?.[l+1]??0}const E=new Vg(e.indices.length);for(let s=0;s<e.indices.length;s+=3)E[s]=e.indices[s+2],E[s+1]=e.indices[s+1],E[s+2]=e.indices[s];const n=new I.Mesh({numProp:i,vertProperties:o,triVerts:E,runIndex:new Vg([0]),runOriginalID:new Vg([I.firstMaterialId+g])});n.merge();try{const s=I.Manifold;return Nx(s(n),i)}catch(s){throw new Error(`Error while creating CSG2 from mesh "${A.name}".`,{cause:s})}}function I9(A,g,I){const e=wm();return g._numProp!==I._numProp&&U(343),Nx(e.Manifold[A](Mm(g,`csg2 ${A}`),Mm(I,`csg2 ${A}`)),g._numProp)}function JaA(A,g){return I9("difference",A,g)}function vaA(A,g){return I9("intersection",A,g)}function HaA(A,g){return I9("union",A,g)}function TaA(A){A._manifold&&(A._manifold.delete(),A._manifold=null)}function xaA(A,g,I){const e=g-A.firstMaterialId;return(e<0||e>=dm)&&U(344,I,g),e}function Gx(A,g,I,e,t){const i=A.positions.length/3;for(let o=2;o>=0;o--){const r=I[t+o]*e;A.positions.push(g.vertProperties[r],g.vertProperties[r+1],g.vertProperties[r+2]),A.normals.push(g.vertProperties[r+3],g.vertProperties[r+4],g.vertProperties[r+5]),A.uvs.push(g.vertProperties[r+6],g.vertProperties[r+7]),A.indices.push(i+(2-o))}}function Fx(A,g,I){return I.positions.length===0&&U(345,g),Et(A,g,new X(I.positions),new X(I.normals),new Vg(I.indices),new X(I.uvs))}function qaA(A,g,I="csg2"){wm();const e=Mm(g,`createMeshFromCsg2("${I}")`).getMesh(),t={positions:[],normals:[],uvs:[],indices:[]};for(let i=0;i<e.triVerts.length;i+=3)Gx(t,e,e.triVerts,g._numProp,i);return Fx(A,I,t)}function PaA(A,g,I,e="csg2"){const t=wm(),i=Mm(g,`createMeshesFromCsg2("${e}")`).getMesh(),o=[];for(let Q=0;Q<i.numRun;Q++){const r=i.runOriginalID[Q],E=xaA(t,r,e);let n=o.find(l=>l.materialSlot===E);n||(n={materialSlot:E,positions:[],normals:[],uvs:[],indices:[]},o.push(n));const s=i.runIndex[Q]??0,c=i.runIndex[Q+1]??i.triVerts.length;for(let l=s;l<c;l+=3)Gx(n,i,i.triVerts,g._numProp,l)}return o.sort((Q,r)=>Q.materialSlot-r.materialSlot),o.map(Q=>{const r=I[Q.materialSlot];r||U(346,e,Q.materialSlot);const E=Fx(A,`${e}_sub${Q.materialSlot}`,Q);return E.material=r,E})}function OaA(A,g,I){const e=EF(Math.max(g.byteLength,4),4),t=new Uint8Array(e);t.set(new Uint8Array(g.buffer,g.byteOffset,g.byteLength));const i={byteLength:e};if(Object.defineProperties(i,{_buffer:{value:wI(A,t,SA.STORAGE,I),writable:!0},_destroyed:{value:!1,writable:!0},_data:{value:t,writable:!0},_engine:{value:A},_label:{value:I}}),(A._storageBuffers??=new Set).add(i),!A._storageRequiredLimits){const o=A._device.limits;o&&(A._storageRequiredLimits={maxBufferSize:o.maxBufferSize,maxStorageBufferBindingSize:o.maxStorageBufferBindingSize,maxStorageBuffersPerShaderStage:o.maxStorageBuffersPerShaderStage})}return A._rebuildStorageBuffers??=()=>WaA(A),A._disposeStorageBuffers??=()=>zaA(A),i}function jaA(A,g){return(g._destroyed||!g._data)&&U(448),g._engine!==A&&U(449),A._storageBuffers?.has(g)||U(450),g._buffer}function VaA(A,g,I,e=0){if(g._destroyed&&U(451),"_engine"in g||U(452),g._engine!==A&&U(453),A._storageBuffers?.has(g)||U(454),(!Number.isInteger(e)||e<0||(e&3)!==0)&&U(455),(I.byteLength&3)!==0&&U(456),e+I.byteLength>g.byteLength&&U(457,g.byteLength),I.byteLength===0)return;A._device.queue.writeBuffer(g._buffer,e,I.buffer,I.byteOffset,I.byteLength);const t=I instanceof Uint8Array?I:new Uint8Array(I.buffer,I.byteOffset,I.byteLength);g._data.set(t,e)}function mx(A){A._destroyed||((!("_engine"in A)||!A._engine._storageBuffers?.has(A))&&U(458),A._buffer?.destroy(),A._buffer=null,A._engine._storageBuffers.delete(A),A._data=null,A._destroyed=!0,A._engine._storageBuffers.size===0&&(A._engine._storageBuffers=void 0,A._engine._storageRequiredLimits=void 0,A._engine._rebuildStorageBuffers=void 0,A._engine._disposeStorageBuffers=void 0))}function WaA(A){for(const g of A._storageBuffers??[])!g._destroyed&&g._data&&(g._buffer=wI(A,g._data,SA.STORAGE,g._label))}function zaA(A){for(const g of[...A._storageBuffers??[]])mx(g)}function bx(A,g,I,e,t={}){(I<1||e<1)&&U(564,I,e);const i=I*e*4;g.length<i&&U(565,i,I,e,g.length);const o=A._device,Q=t.srgb?"rgba8unorm-srgb":"rgba8unorm",r=o.createTexture({size:{width:I,height:e},format:Q,usage:dA.TEXTURE_BINDING|dA.COPY_DST});o.queue.writeTexture({texture:r},g,{bytesPerRow:I*4,rowsPerImage:e},{width:I,height:e});const E={addressModeU:t.addressModeU??"clamp-to-edge",addressModeV:t.addressModeV??"clamp-to-edge",minFilter:t.minFilter??"nearest",magFilter:t.magFilter??"nearest"},n=Pe(A,E),s={texture:r,view:r.createView(),sampler:n,width:I,height:e};return A._dlr?.p(s,g,t),rt(s),s}function ZaA(A,g,I,e={}){(g<1||I<1)&&U(566,g,I);const t=A._device,i=e.format??A.format,o=t.createTexture({size:{width:g,height:I},format:i,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST}),Q={addressModeU:e.addressModeU??"clamp-to-edge",addressModeV:e.addressModeV??"clamp-to-edge",minFilter:e.minFilter??"linear",magFilter:e.magFilter??"linear"},r=Pe(A,Q),E={texture:o,view:o.createView(),sampler:r,width:g,height:I};return A._dlr?.r(E,g,I,i,Q),rt(E),E}function XaA(A,g,I,e=0,t=0,i=g.width,o=g.height){(i<1||o<1)&&U(567,i,o);const Q=i*o*4;I.length<Q&&U(568,Q,i,o,I.length),A._device.queue.writeTexture({texture:g.texture,origin:{x:e,y:t}},I,{bytesPerRow:i*4,rowsPerImage:o},{width:i,height:o}),A._dlr?.w(g,I,e,t,i,o)}function $aA(A,g,I,e,t,i={}){(I<1||e<1||t<1)&&U(569,I,e,t);const o=I*e*t*4;g.length<o&&U(570,o,I,e,t,g.length);const Q=A._device,r=i.srgb?"rgba8unorm-srgb":"rgba8unorm",E=Q.createTexture({size:{width:I,height:e,depthOrArrayLayers:t},dimension:"3d",format:r,usage:dA.TEXTURE_BINDING|dA.COPY_DST});Q.queue.writeTexture({texture:E},g,{bytesPerRow:I*4,rowsPerImage:e},{width:I,height:e,depthOrArrayLayers:t});const n=i.addressMode??"clamp-to-edge",s=i.filter??"linear",c=Pe(A,{addressModeU:n,addressModeV:n,addressModeW:n,minFilter:s,magFilter:s}),l={texture:E,view:E.createView({dimension:"3d"}),sampler:c,width:I,height:e,depth:t};return rt(l),l}let e9=null;function AcA(){if(e9)return e9;const A=new Map;e9=A;function g(o,Q,r,E,n,s){A.set(o,{gpuFormat:Q,feature:r,blockW:E,blockH:n,blockBytes:s})}const I="texture-compression-bc",e="texture-compression-etc2",t="texture-compression-astc";g(33776,"bc1-rgba-unorm",I,4,4,8),g(33777,"bc1-rgba-unorm",I,4,4,8),g(33778,"bc2-rgba-unorm",I,4,4,16),g(33779,"bc3-rgba-unorm",I,4,4,16),g(36283,"bc4-r-unorm",I,4,4,8),g(36284,"bc4-r-snorm",I,4,4,8),g(36285,"bc5-rg-unorm",I,4,4,16),g(36286,"bc5-rg-snorm",I,4,4,16),g(36495,"bc6h-rgb-ufloat",I,4,4,16),g(36494,"bc6h-rgb-float",I,4,4,16),g(36492,"bc7-rgba-unorm",I,4,4,16),g(36493,"bc7-rgba-unorm-srgb",I,4,4,16),g(37488,"eac-r11unorm",e,4,4,8),g(37489,"eac-r11snorm",e,4,4,8),g(37490,"eac-rg11unorm",e,4,4,16),g(37491,"eac-rg11snorm",e,4,4,16),g(37492,"etc2-rgb8unorm",e,4,4,8),g(37493,"etc2-rgb8unorm-srgb",e,4,4,8),g(37494,"etc2-rgb8a1unorm",e,4,4,8),g(37495,"etc2-rgb8a1unorm-srgb",e,4,4,8),g(37496,"etc2-rgba8unorm",e,4,4,16),g(37497,"etc2-rgba8unorm-srgb",e,4,4,16);const i=[[4,4],[5,4],[5,5],[6,5],[6,6],[8,5],[8,6],[8,8],[10,5],[10,6],[10,8],[10,10],[12,10],[12,12]];for(let o=0;o<i.length;o++){const[Q,r]=i[o],E=`${Q}x${r}`;g(37808+o,`astc-${E}-unorm`,t,Q,r,16),g(37840+o,`astc-${E}-unorm-srgb`,t,Q,r,16)}return A}function t9(A){return AcA().get(A)}function gcA(A){const g=A.toLowerCase();if(g.includes("astc"))return"texture-compression-astc";if(g.includes("dxt")||g.includes("s3tc")||g.includes("bc"))return"texture-compression-bc";if(g.includes("etc"))return"texture-compression-etc2"}let Kx="https://cdn.babylonjs.com/babylon.ktx2Decoder.js",uN=null;function IcA(A,g){Kx=A,uN=g??null}let yr=null;const ecA=32856,tcA=33321,CcA=33323,kx={astc:!1,bptc:!1,s3tc:!1,pvrtc:!1,etc2:!1,etc1:!1};function icA(A){const g=A._device.features,I=g.has("texture-compression-bc"),e=g.has("texture-compression-etc2");return{astc:g.has("texture-compression-astc"),bptc:I,s3tc:I,pvrtc:!1,etc2:e,etc1:e}}function C9(){return yr||(yr=new Promise((A,g)=>{const I=globalThis,e=()=>{const i=I.KTX2DECODER;if(!i){g(new Error("KTX2: decoder global KTX2DECODER not found after script load"));return}if(i.MSCTranscoder.UseFromWorkerThread=!1,i.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,uN){const o=i;for(const Q of Object.keys(uN)){const r=o[Q];if(r)for(const E of Object.keys(uN[Q]))r[E]=uN[Q][E]}}A(new i.KTX2Decoder)};if(I.KTX2DECODER){e();return}const t=document.createElement("script");t.src=Kx,t.async=!0,t.onload=e,t.onerror=()=>g(new Error(`KTX2: failed to load ${t.src}`)),document.head.appendChild(t)}),yr.catch(()=>{yr=null}),yr)}function i9(A){switch(A){case"rgba8unorm":return"rgba8unorm-srgb";case"bc1-rgba-unorm":return"bc1-rgba-unorm-srgb";case"bc2-rgba-unorm":return"bc2-rgba-unorm-srgb";case"bc3-rgba-unorm":return"bc3-rgba-unorm-srgb";case"bc7-rgba-unorm":return"bc7-rgba-unorm-srgb";case"etc2-rgb8unorm":return"etc2-rgb8unorm-srgb";case"etc2-rgb8a1unorm":return"etc2-rgb8a1unorm-srgb";case"etc2-rgba8unorm":return"etc2-rgba8unorm-srgb";case"astc-4x4-unorm":return"astc-4x4-unorm-srgb";case"astc-5x4-unorm":return"astc-5x4-unorm-srgb";case"astc-5x5-unorm":return"astc-5x5-unorm-srgb";case"astc-6x5-unorm":return"astc-6x5-unorm-srgb";case"astc-6x6-unorm":return"astc-6x6-unorm-srgb";case"astc-8x5-unorm":return"astc-8x5-unorm-srgb";case"astc-8x6-unorm":return"astc-8x6-unorm-srgb";case"astc-8x8-unorm":return"astc-8x8-unorm-srgb";case"astc-10x5-unorm":return"astc-10x5-unorm-srgb";case"astc-10x6-unorm":return"astc-10x6-unorm-srgb";case"astc-10x8-unorm":return"astc-10x8-unorm-srgb";case"astc-10x10-unorm":return"astc-10x10-unorm-srgb";case"astc-12x10-unorm":return"astc-12x10-unorm-srgb";case"astc-12x12-unorm":return"astc-12x12-unorm-srgb";default:return A}}function Ux(A){switch(A){case ecA:return{format:"rgba8unorm",bytesPerPixel:4};case tcA:return{format:"r8unorm",bytesPerPixel:1};case CcA:return{format:"rg8unorm",bytesPerPixel:2};default:return null}}function Lx(A){A.errors&&U(552,A.errors),A.mipmaps.length||U(553);for(let g=0;g<A.mipmaps.length;g++)A.mipmaps[g]?.data||U(554,g);return A.mipmaps}function o9(A,g){return Pe(A,{addressModeU:"repeat",addressModeV:"repeat",minFilter:"linear",magFilter:"linear",mipmapFilter:g>1?"linear":"nearest",maxAnisotropy:g>1?4:1})}function ocA(A,g,I,e){A._device.features.has(I.feature)||U(555,I.feature);const t=g[0].width,i=g[0].height,o=A._device.createTexture({size:{width:t,height:i},format:e?i9(I.gpuFormat):I.gpuFormat,mipLevelCount:g.length,usage:dA.TEXTURE_BINDING|dA.COPY_DST});for(let r=0;r<g.length;r++){const E=g[r],n=Math.ceil(E.width/I.blockW),s=n*I.blockBytes,c=n*I.blockW,l=Math.ceil(E.height/I.blockH)*I.blockH;A._device.queue.writeTexture({texture:o,mipLevel:r},E.data,{bytesPerRow:s},{width:c,height:l})}const Q={texture:o,view:o.createView(),sampler:o9(A,g.length),width:t,height:i,invertY:!0};return rt(Q),Q}function BcA(A,g,I,e){const t=g[0].width,i=g[0].height,o=A._device.createTexture({size:{width:t,height:i},format:e?i9(I.format):I.format,mipLevelCount:g.length,usage:dA.TEXTURE_BINDING|dA.COPY_DST});for(let r=0;r<g.length;r++){const E=g[r],n=E.width*E.height*I.bytesPerPixel;E.data.length!==n&&U(556,r,E.data.length,n),A._device.queue.writeTexture({texture:o,mipLevel:r},E.data,{bytesPerRow:E.width*I.bytesPerPixel},{width:E.width,height:E.height})}const Q={texture:o,view:o.createView(),sampler:o9(A,g.length),width:t,height:i,invertY:!0};return rt(Q),Q}async function Yx(A,g){const e=await(await C9()).decode(new mg(g),icA(A));return Lx(e),e}async function Jx(A,g,I){const e=await Yx(A,g),t=e.mipmaps,i=t9(e.transcodedFormat);if(i)return ocA(A,t,i,I);const o=Ux(e.transcodedFormat);if(o)return BcA(A,t,o,I);U(557,e.transcodedFormat.toString(16))}async function QcA(A,g,I=!1){const e=await fetch(g);return e.ok||U(558,e.status,g),Jx(A,await e.arrayBuffer(),I)}async function rcA(A){const I=await(await C9()).decode(new mg(A),kx,{forceRGBA:!0}),e=Lx(I)[0];e.data.length!==e.width*e.height*4&&U(559);const t=new si(e.data.length);return t.set(e.data),createImageBitmap(new ImageData(t,e.width,e.height))}function B9(A,g,I,e,t={}){(g<1||I<1||e<1)&&U(573,g,I,e);const i=A._device,o=t.mipMaps??!0,Q=t.srgb?"rgba8unorm-srgb":"rgba8unorm",r=i.createTexture({size:{width:g,height:I,depthOrArrayLayers:e},dimension:"2d",format:Q,mipLevelCount:o?XQ(g,I):1,usage:dA.TEXTURE_BINDING|dA.COPY_DST|dA.RENDER_ATTACHMENT}),E=Pe(A,{addressModeU:t.addressModeU??"repeat",addressModeV:t.addressModeV??"repeat",minFilter:t.minFilter??"linear",magFilter:t.magFilter??"linear",mipmapFilter:o?"linear":"nearest"}),n={texture:r,view:r.createView({dimension:"2d-array"}),sampler:E,width:g,height:I,layers:e};return rt(n),n}function Q9(A,g,I,e,t={}){(I<0||I>=g.layers||(I|0)!==I)&&U(574,g.layers,I);const i=t.invertY??!0,o=t.premultiplyAlpha??!1;A._device.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:g.texture,origin:[0,0,I],premultipliedAlpha:o},[g.width,g.height,1]),g.texture.mipLevelCount>1&&ZQ(A,g.texture,I)}async function EcA(A,g,I,e,t={}){const i=await fetch(e);i.ok||U(575,e,i.status);const o=await createImageBitmap(await i.blob(),{premultiplyAlpha:t.premultiplyAlpha?"premultiply":"none",colorSpaceConversion:"none"});try{Q9(A,g,I,o,t)}finally{o.close()}}async function ncA(A,g,I={}){const e=await Promise.allSettled(g.map(async E=>{const n=await fetch(E);return n.ok||U(576,E,n.status),createImageBitmap(await n.blob(),{premultiplyAlpha:I.premultiplyAlpha?"premultiply":"none",colorSpaceConversion:"none"})})),t=e.find(E=>E.status==="rejected");if(t){for(const E of e)E.status==="fulfilled"&&E.value.close();throw t.reason}const i=e.filter(E=>E.status==="fulfilled").map(E=>E.value),o=i[0].width,Q=i[0].height;for(const[E,n]of i.entries())if(n.width!==o||n.height!==Q){for(const s of i)s.close();U(577,o,Q,E,n.width,n.height)}const r=B9(A,o,Q,i.length,I);for(const[E,n]of i.entries())Q9(A,r,E,n,I),n.close();return r}function vx(A,g,I,e,t,i={}){const o=B9(A,I,e,t,i);return Hx(A,o,g),o}function Hx(A,g,I,e=0){(e<0||e>=g.texture.mipLevelCount||(e|0)!==e)&&U(578,g.texture.mipLevelCount,e);const t=Math.max(1,g.width>>e),i=Math.max(1,g.height>>e),o=t*i*g.layers*4;if(I.length<o&&U(579,o,t,i,g.layers,e,I.length),A._device.queue.writeTexture({texture:g.texture,mipLevel:e},I,{bytesPerRow:t*4,rowsPerImage:i},{width:t,height:i,depthOrArrayLayers:g.layers}),e===0&&g.texture.mipLevelCount>1){const Q=A._device.createCommandEncoder();for(let r=0;r<g.layers;r++)wF(A,g.texture,Q,r);A._device.queue.submit([Q.finish()])}}function Tx(A){const g=A.mipmaps,I=A.layerCount;I===void 0&&U(580),(I<1||g.length%I!==0)&&U(581,g.length,I);const e=[];for(let t=0;t<g.length;t+=I){const i=g.slice(t,t+I);for(let o=0;o<I;o++){const Q=i[o];Q.layerIndex!==o&&U(582,o,t+o,Q.layerIndex),(Q.width!==i[0].width||Q.height!==i[0].height)&&U(583,e.length,o)}e.push(i)}return{layers:I,levels:e}}function xx(A,g,I,e,t,i,o){const Q=A._device.createTexture({size:{width:g,height:I,depthOrArrayLayers:e},dimension:"2d",format:o?i9(i):i,mipLevelCount:t,usage:dA.TEXTURE_BINDING|dA.COPY_DST}),r={texture:Q,view:Q.createView({dimension:"2d-array"}),sampler:o9(A,t),width:g,height:I,layers:e,invertY:!0};return rt(r),r}function scA(A,g,I,e){A._device.features.has(I.feature)||U(584,I.feature);const{layers:t,levels:i}=Tx(g),o=i[0][0].width,Q=i[0][0].height,r=xx(A,o,Q,t,i.length,I.gpuFormat,e);for(let E=0;E<i.length;E++){const n=Math.ceil(i[E][0].width/I.blockW),s=n*I.blockBytes,c=n*I.blockW,l=Math.ceil(i[E][0].height/I.blockH)*I.blockH;for(let D=0;D<t;D++){const p=i[E][D];A._device.queue.writeTexture({texture:r.texture,mipLevel:E,origin:{x:0,y:0,z:D}},p.data,{bytesPerRow:s},{width:c,height:l,depthOrArrayLayers:1})}}return r}function acA(A,g,I,e){const t=I.bytesPerPixel,{layers:i,levels:o}=Tx(g),Q=o[0][0].width,r=o[0][0].height,E=xx(A,Q,r,i,o.length,I.format,e);for(let n=0;n<o.length;n++){const s=o[n][0].width,c=o[n][0].height;for(let l=0;l<i;l++){const D=o[n][l],p=s*c*t;D.data.length!==p&&U(585,n,l,D.data.length,p),A._device.queue.writeTexture({texture:E.texture,mipLevel:n,origin:{x:0,y:0,z:l}},D.data,{bytesPerRow:s*t},{width:s,height:c,depthOrArrayLayers:1})}}return E}async function qx(A,g,I=!1){const e=await Yx(A,g),t=t9(e.transcodedFormat);if(t)return scA(A,e,t,I);const i=Ux(e.transcodedFormat);if(i)return acA(A,e,i,I);U(586,e.transcodedFormat.toString(16))}async function ccA(A,g,I=!1){const e=await fetch(g);return e.ok||U(587,e.status,g),qx(A,await e.arrayBuffer(),I)}function Px(A,g,I,e={}){(g<1||I<1)&&U(536,g,I);const t=A._device,i=e.mipMaps??!1,o=e.srgb?"rgba8unorm-srgb":"rgba8unorm",Q=i?XQ(g,I):1,r=t.createTexture({size:{width:g,height:I},format:o,mipLevelCount:Q,usage:dA.TEXTURE_BINDING|dA.COPY_DST|dA.RENDER_ATTACHMENT}),E={addressModeU:e.addressModeU??"clamp-to-edge",addressModeV:e.addressModeV??"clamp-to-edge",minFilter:e.minFilter??"linear",magFilter:e.magFilter??"linear",mipmapFilter:i?"linear":"nearest"},n=Pe(A,E),s={texture:r,view:r.createView(),sampler:n,width:g,height:I};return rt(s),A._dlr&&A._dlr.t(s,{kind:"dynamic",width:g,height:I,format:o,levels:Q,samplerDesc:E,source:null,flipY:!0,premultipliedAlpha:!1}),s}function Ox(A,g,I,e={}){const t=e.invertY??!0,i=e.premultiplyAlpha??!1;A._device.queue.copyExternalImageToTexture({source:I,flipY:t},{texture:g.texture,premultipliedAlpha:i},[g.width,g.height]);const o=g._recoverySource;o&&o.kind==="dynamic"&&(o.source=I,o.flipY=t,o.premultipliedAlpha=i),g.texture.mipLevelCount>1&&ZQ(A,g.texture)}function r9(A){return typeof A._device.queue.copyElementImageToTexture=="function"}function lcA(A,g,I={}){const e=A.surfaces[0].canvas;XG(e)||U(537);const t=r9(A),i=I.width??(g.offsetWidth||256),o=I.height??(g.offsetHeight||256),Q=Px(A,i,o,{srgb:I.srgb,mipMaps:I.mipMaps,addressModeU:I.addressModeU,addressModeV:I.addressModeV,minFilter:I.minFilter,magFilter:I.magFilter});if(Q._element=g,Q._host=e,Q._prevParent=g.parentNode,Q._prevNextSibling=g.nextSibling,Q._prevInert=g.inert,Q._paint=null,Q._invertY=I.invertY??!0,Q._autoUpdate=I.autoUpdate??!0,Q._useSvgFallback=I.useSvgFallback??!0,Q._forceNext=!1,Q._hosted=!1,Q._disposed=!1,Q._flipSrc=null,Q._flipDevice=null,(t||Q._useSvgFallback)&&(pcA(e),g.inert=!0,e.appendChild(g),Q._hosted=!0),t){const r=E=>{if(Q._disposed)return;const n=Q._forceNext;if(Q._forceNext=!1,!n){if(!Q._autoUpdate)return;const s=E.changedElements;if(s&&!s.some(c=>c===g||g.contains(c)))return}Sm(A,Q)};Q._paint=r,e.addEventListener("paint",r),jx(A,Q)}else Q._useSvgFallback&&Sm(A,Q);return Q}function Sm(A,g,I=g._invertY){if(g._disposed)return;const e=A._device.queue;if(typeof e.copyElementImageToTexture=="function"){if(I){const t=dcA(A,g);e.copyElementImageToTexture({source:g._element},{destination:{texture:t},width:g.width,height:g.height}),wcA(A,t,g.texture)}else e.copyElementImageToTexture({source:g._element},{destination:{texture:g.texture},width:g.width,height:g.height});g.texture.mipLevelCount>1&&ZQ(A,g.texture);return}g._useSvgFallback&&_cA(A,g,I)}function jx(A,g){if(g._disposed)return;const I=g._host,e=r9(A);e&&typeof I.requestPaint=="function"?(g._forceNext=!0,I.requestPaint()):!e&&g._useSvgFallback&&Sm(A,g)}function DcA(A){if(!A._disposed){if(A._disposed=!0,A._paint&&(A._host.removeEventListener("paint",A._paint),A._paint=null),A._hosted){const g=A._element;g.parentNode===A._host&&(A._prevParent?A._prevParent.insertBefore(g,A._prevNextSibling):A._host.removeChild(g)),g.inert=A._prevInert,ycA(A._host),A._hosted=!1}A._flipSrc?.destroy(),A._flipSrc=null,A._flipDevice=null,lC(A)}}let E9=null;function pcA(A){const g=E9??=new WeakMap;let I=g.get(A);I||(I={count:0,previousLayoutSubtree:A.layoutSubtree},g.set(A,I)),I.count++,A.layoutSubtree=!0}function ycA(A){const g=E9?.get(A);g&&(g.count--,!(g.count>0)&&(g.previousLayoutSubtree===void 0?delete A.layoutSubtree:A.layoutSubtree=g.previousLayoutSubtree,E9?.delete(A)))}async function _cA(A,g,I){try{const e=await ucA(g._element,g.width,g.height);g._disposed||Ox(A,g,e,{invertY:I})}catch{}}function ucA(A,g,I){const e=new XMLSerializer().serializeToString(A),t=`<svg xmlns="http://www.w3.org/2000/svg" width="${g}" height="${I}"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml">${e}</div></foreignObject></svg>`,i="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(t);return new Promise((o,Q)=>{const r=new Image(g,I);r.decoding="async",r.onload=()=>{const E=document.createElement("canvas");E.width=g,E.height=I;const n=E.getContext("2d");if(!n){Q(new Error("createHtmlTexture: SVG fallback could not acquire a 2D canvas context."));return}n.drawImage(r,0,0,g,I),o(E)},r.onerror=()=>Q(new Error("createHtmlTexture: SVG fallback failed to rasterise the element.")),r.src=i})}const hcA="@group(0)@binding(0)var t:texture_2d<f32>;@group(0)@binding(1)var s:sampler;struct V{@builtin(position)p:vec4f,@location(0)u:vec2f};@vertex fn vs(@builtin(vertex_index)i:u32)->V{let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i];return V(vec4f(p,0,1),p*vec2f(.5,.5)+.5);}@fragment fn fs(v:V)->@location(0)vec4f{return textureSample(t,s,v.u);}";let Vx=null,Rm=null,Nm=null,Gm=null;function fcA(A,g){const I=A._device;I!==Vx&&(Vx=I,Rm=null,Nm=null,Gm=null),Rm??=I.createShaderModule({code:hcA}),Nm??=I.createBindGroupLayout({entries:[{binding:0,visibility:NA.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:NA.FRAGMENT,sampler:{}}]}),Gm??=new Map;let e=Gm.get(g);return e||(e=I.createRenderPipeline({layout:I.createPipelineLayout({bindGroupLayouts:[Nm]}),vertex:{module:Rm,entryPoint:"vs"},fragment:{module:Rm,entryPoint:"fs",targets:[{format:g}]},primitive:{topology:"triangle-list"}}),Gm.set(g,e)),e}function dcA(A,g){const I=A._device;let e=g._flipSrc;return(!e||g._flipDevice!==I||e.width!==g.width||e.height!==g.height)&&(e?.destroy(),e=I.createTexture({size:{width:g.width,height:g.height},format:g.texture.format,usage:dA.TEXTURE_BINDING|dA.COPY_DST|dA.RENDER_ATTACHMENT}),g._flipSrc=e,g._flipDevice=I),e}function wcA(A,g,I){const e=A._device,t=fcA(A,I.format),i=e.createBindGroup({layout:Nm,entries:[{binding:0,resource:g.createView()},{binding:1,resource:m1(A)}]}),o=e.createCommandEncoder(),Q=o.beginRenderPass({colorAttachments:[{view:I.createView({baseMipLevel:0,mipLevelCount:1}),loadOp:"clear",storeOp:"store",clearValue:{r:0,g:0,b:0,a:0}}]});Q.setPipeline(t),Q.setBindGroup(0,i),Q.draw(3),Q.end(),e.queue.submit([o.finish()])}const McA=new mg([171,75,84,88,32,49,49,187,13,10,26,10]);function ScA(A){const g=new mg(A);A.byteLength<64&&U(538);for(let y=0;y<12;y++)g[y]!==McA[y]&&U(539);const I=new H1(A);I.getUint32(12,!0)!==67305985&&U(540),I.getUint32(16,!0)!==0&&U(541),I.getUint32(24,!0)!==0&&U(542);const e=I.getUint32(28,!0),t=t9(e);t||U(543,e.toString(16));const i=I.getUint32(36,!0),o=I.getUint32(40,!0),Q=I.getUint32(44,!0),r=I.getUint32(48,!0),E=I.getUint32(52,!0),n=Math.max(I.getUint32(56,!0),1),s=I.getUint32(60,!0);Q>0&&U(544),r>0&&U(545),E!==1&&U(546);let c=64+s;c>A.byteLength&&U(547);const l=[];let D=i,p=o;for(let y=0;y<n;y++){c+4>A.byteLength&&U(548,y);const _=I.getUint32(c,!0);c+=4,c+_>A.byteLength&&U(549,y),l.push({data:new mg(A,c,_),width:D,height:p}),c+=_,c=c+3&-4,D=Math.max(1,D>>1),p=Math.max(1,p>>1)}return l.length===0&&U(550),{format:t,width:i,height:o,mips:l}}function RcA(A,g,I){const e=A._device,t=g.format,i=e.createTexture({size:{width:g.width,height:g.height},format:t.gpuFormat,mipLevelCount:g.mips.length,usage:dA.TEXTURE_BINDING|dA.COPY_DST});for(let c=0;c<g.mips.length;c++){const l=g.mips[c],D=Math.ceil(l.width/t.blockW),p=D*t.blockBytes,y=D*t.blockW,_=Math.ceil(l.height/t.blockH)*t.blockH;e.queue.writeTexture({texture:i,mipLevel:c},l.data,{bytesPerRow:p},{width:y,height:_})}const o=I.minFilter??"linear",Q=I.magFilter??"linear",r=g.mips.length>1?"linear":"nearest",E=o==="linear"&&Q==="linear"&&r==="linear",n=Pe(A,{addressModeU:I.addressModeU??"repeat",addressModeV:I.addressModeV??"repeat",minFilter:o,magFilter:Q,mipmapFilter:r,maxAnisotropy:E?4:1}),s={texture:i,view:i.createView(),sampler:n,width:g.width,height:g.height};return rt(s),s}function NcA(A,g){const I=A.indexOf("?"),e=I>=0?A.substring(0,I):A,t=I>=0?A.substring(I):"",i=e.lastIndexOf(".");return i<0?e+g+t:e.substring(0,i)+g+t}async function GcA(A,g,I,e={}){const t=A._device,i=[];for(const o of I){const Q=gcA(o);Q&&t.features.has(Q)&&i.push(o)}for(const o of i)try{const Q=NcA(g,o),r=await fetch(Q);r.ok||U(551,r.status);const E=ScA(await r.arrayBuffer());return RcA(A,E,e)}catch(Q){console.warn(`KTX load failed for suffix "${o}":`,Q)}return OQ(A,g,e)}const FcA=0,mcA=1,bcA=2,KcA=3,kcA=6,UcA=10,LcA=13,Wx="https://cdn.babylonjs.com/basisTranscoder/1";let _r=null;function YcA(){return _r||(_r=new Promise((A,g)=>{const I=globalThis,e=()=>{const i=I.BASIS;if(!i){g(new Error("Basis: transcoder global BASIS not found after script load"));return}i({locateFile:o=>`${Wx}/${o}`}).then(o=>{o.initializeBasis(),A(o)}).catch(g)};if(I.BASIS){e();return}const t=document.createElement("script");t.src=`${Wx}/basis_transcoder.js`,t.async=!0,t.onload=e,t.onerror=()=>g(new Error(`Basis: failed to load ${t.src}`)),document.head.appendChild(t)}),_r.catch(()=>{_r=null}),_r)}const n9=[{basisFormat:kcA,gpuFormat:"bc7-rgba-unorm",gpuFormatSrgb:"bc7-rgba-unorm-srgb",feature:"texture-compression-bc",blockW:4,blockH:4,blockBytes:16,hasAlpha:!0},{basisFormat:UcA,gpuFormat:"astc-4x4-unorm",gpuFormatSrgb:"astc-4x4-unorm-srgb",feature:"texture-compression-astc",blockW:4,blockH:4,blockBytes:16,hasAlpha:!0},{basisFormat:mcA,gpuFormat:"etc2-rgba8unorm",gpuFormatSrgb:"etc2-rgba8unorm-srgb",feature:"texture-compression-etc2",blockW:4,blockH:4,blockBytes:16,hasAlpha:!0},{basisFormat:KcA,gpuFormat:"bc3-rgba-unorm",gpuFormatSrgb:"bc3-rgba-unorm-srgb",feature:"texture-compression-bc",blockW:4,blockH:4,blockBytes:16,hasAlpha:!0},{basisFormat:bcA,gpuFormat:"bc1-rgba-unorm",gpuFormatSrgb:"bc1-rgba-unorm-srgb",feature:"texture-compression-bc",blockW:4,blockH:4,blockBytes:8,hasAlpha:!1},{basisFormat:LcA,gpuFormat:"rgba8unorm",gpuFormatSrgb:"rgba8unorm-srgb",blockW:1,blockH:1,blockBytes:4,hasAlpha:!0},{basisFormat:FcA,gpuFormat:"etc2-rgb8unorm",gpuFormatSrgb:"etc2-rgb8unorm-srgb",feature:"texture-compression-etc2",blockW:4,blockH:4,blockBytes:8,hasAlpha:!1}];function JcA(A,g){for(const I of n9)if(!(!I.hasAlpha&&g)&&!(I.feature&&!A.features.has(I.feature)))return I;return n9[n9.length-2]}async function vcA(A,g,I={}){const e=A._device,[t,i]=await Promise.all([YcA(),fetch(g).then(r=>r.arrayBuffer())]),o=new mg(i),Q=new t.BasisFile(o);try{Q.getNumImages()===0&&U(532),Q.startTranscoding()===0&&U(533);const r=Q.getHasAlpha()!==0,E=JcA(e,r),n=Q.getImageWidth(0,0),s=Q.getImageHeight(0,0),c=Q.getNumLevels(0),D=(I.srgb??!1)&&E.gpuFormatSrgb?E.gpuFormatSrgb:E.gpuFormat,p=[];for(let S=0;S<c;S++){const R=Q.getImageWidth(0,S),N=Q.getImageHeight(0,S),F=Q.getImageTranscodedSizeInBytes(0,S,E.basisFormat);F===0&&U(534,S);const G=new mg(F);Q.transcodeImage(G,0,S,E.basisFormat,0,r?1:0)===0&&U(535,S),p.push({data:G,width:R,height:N})}const y=e.createTexture({size:{width:n,height:s},format:D,mipLevelCount:p.length,usage:dA.TEXTURE_BINDING|dA.COPY_DST});for(let S=0;S<p.length;S++){const R=p[S],N=Math.ceil(R.width/E.blockW),F=E.blockW===1?R.width*E.blockBytes:N*E.blockBytes;e.queue.writeTexture({texture:y,mipLevel:S},R.data,{bytesPerRow:F},{width:R.width,height:R.height})}const _=I.minFilter??"linear",u=I.magFilter??"linear",f=p.length>1?"linear":"nearest",h=_==="linear"&&u==="linear"&&f==="linear",w=Pe(A,{addressModeU:I.addressModeU??"repeat",addressModeV:I.addressModeV??"repeat",minFilter:_,magFilter:u,mipmapFilter:f,maxAnisotropy:h?4:1}),M={texture:y,view:y.createView(),sampler:w,width:n,height:s,invertY:!0};return rt(M),M}finally{Q.close(),Q.delete()}}async function HcA(A,g,I={}){const e=g instanceof ArrayBuffer?new mg(g):new mg(g.buffer,g.byteOffset,g.byteLength),i=await(await C9()).decode(e,kx,{forceRGBA:!0});i.errors&&U(560,i.errors),i.mipmaps.length||U(561);const o=Math.max(i.layerCount??1,1),Q=i.mipmaps.slice(0,o);Q.length!==o&&U(562,o,Q.length);const{width:r,height:E}=Q[0],n=r*E*4,s=new mg(n*o);for(let l=0;l<o;l++){const D=Q[l];(!D.data||D.width!==r||D.height!==E||D.data.byteLength!==n)&&U(563,l,r,E,n),s.set(D.data,l*n)}const c=vx(A,s,r,E,o,{mipMaps:I.generateMipMaps??!0,srgb:I.srgb??!1,minFilter:I.minFilter??"linear",magFilter:I.magFilter??"linear"});return I.mipmapFilter&&(c.sampler=Pe(A,{addressModeU:"repeat",addressModeV:"repeat",minFilter:I.minFilter??"linear",magFilter:I.magFilter??"linear",mipmapFilter:I.mipmapFilter})),c.invertY=I.invertY??!1,c}function zx(A){const g=A._renderFeatures??{features:0};return $1(A,{features:g.features|WF})}const TcA=Object.freeze(Object.defineProperty({__proto__:null,createStandardNoColorMaterialView:zx},Symbol.toStringTag,{value:"Module"}));let Zx=null;function xcA(A){Zx=A}function qcA(){return Zx}function Fm(A){const g=[];A.diffuseTexture&&g.push(A.diffuseTexture);for(const I of iT().values())I._textures?.(A,g);return g}function s9(A){let g=0;A.diffuseTexture&&(g|=yC,A.diffuseCoordIndex===1&&(g|=VF)),A.backFaceCulling||(g|=jF),A.disableLighting&&(g|=gT),A.alpha<1&&(g|=lo);for(const I of iT().values())I._detect&&(g|=I._detect(A));return g}function Xx(A,g,I,e=""){return e?`${A}:${g}:${I}:${e}`:`${A}:${g}:${I}`}function $x(A){return A.length===0?"":A.map(g=>`${g.lightIndex}${g.shadowType==="pcf"?"p":"e"}`).join(",")}const PcA=Object.freeze(Object.defineProperty({__proto__:null,_computeStandardMaterialFeatures:s9,_standardFeatureKey:Xx,_standardShaderVariantKey:$x,collectStdBoundTextures:Fm,createStandardMaterial:nt,getStandardGroupBuilder:$F},Symbol.toStringTag,{value:"Module"})),OcA=1,mm=2,jcA="fn computeLighting(viewDir:vec3<f32>,N:vec3<f32>,L:LightEntry,g:f32,P:vec3<f32>)->array<vec3<f32>,2>{var lv:vec3<f32>;var a:f32=1.0;let t=u32(L.vLightData.w);if(t==3u){let nl=0.5+0.5*dot(N,normalize(L.vLightData.xyz));let diff=mix(L.vLightDirection.xyz,L.vLightDiffuse.rgb,nl);let h=normalize(viewDir+normalize(L.vLightData.xyz));var s=pow(max(0.0,dot(N,h)),max(1.0,g));return array<vec3<f32>,2>(diff,s*L.vLightSpecular.rgb);}if(t==1u){lv=normalize(-L.vLightData.xyz);}else{let d=L.vLightData.xyz-P;a=max(0.0,1.0-length(d)/L.vLightDiffuse.a);lv=normalize(d);if(t==2u){let c=max(0.0,dot(L.vLightDirection.xyz,-lv));if(c>=L.vLightDirection.w){a*=max(0.0,pow(c,L.vLightSpecular.a));}else{a=0.0;}}}let nl=max(0.0,dot(N,lv));let diff=nl*L.vLightDiffuse.rgb*a;let h=normalize(viewDir+lv);var s=max(0.0,dot(N,h));s=pow(s,max(1.0,g));return array<vec3<f32>,2>(diff,s*L.vLightSpecular.rgb*a);}";function VcA(A,g=""){const{_diffuse:I,_needsUV:e,_needsUV2:t,_diffuseUsesUV2:i,_disableLighting:o,_noColorOutput:Q,_esmShadowOutput:r,_hasMorph:E}=A,n=[{_name:"position",_type:"vec3<f32>",_gpuFormat:"float32x3",_arrayStride:12},{_name:"normal",_type:"vec3<f32>",_gpuFormat:"float32x3",_arrayStride:12}];e&&n.push({_name:"uv",_type:"vec2<f32>",_gpuFormat:"float32x2",_arrayStride:8}),t&&n.push({_name:"uv2",_type:"vec2<f32>",_gpuFormat:"float32x2",_arrayStride:8});const s=[{_name:"vp",_type:"vec3<f32>"},{_name:"vn",_type:"vec3<f32>"}];e&&s.push({_name:"vu",_type:"vec2<f32>"}),t&&s.push({_name:"vv",_type:"vec2<f32>"});const c=[{_name:"world",_type:"mat4x4<f32>"}];d6(c);const l=[{_name:"mat",_type:{_kind:"uniform-buffer"},_visibility:mm}];I&&l.push({_name:"dT",_type:{_kind:"texture",_textureType:"texture_2d<f32>"},_visibility:mm},{_name:"dS",_type:{_kind:"sampler",_samplerType:"sampler"},_visibility:mm}),e&&l.push({_name:"up",_type:{_kind:"uniform-buffer"},_visibility:OcA}),r&&l.push({_name:"shadowParams",_type:{_kind:"uniform-buffer"},_visibility:mm});const f=`/*SU*/ /*MU*/@group(1)@binding(0)var<uniform>mesh:MeshUniforms;${e?"struct upUniforms{u:vec4<f32>,}":""} /*VH*/ /*VD*/ /*VO*/@vertex fn main( /*VP*/)->VertexOutput{var out:VertexOutput; /*VR*/var finalWorld=mesh.world; /*VW*/let worldPos4=finalWorld*vec4<f32>(${E?"morphedPos":"position"},1.0);out.vp=worldPos4.xyz;let normalWorld=mat3x3<f32>(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);out.vn=normalize(normalWorld* ${E?"morphedNorm":"normal"});out.clipPos=scene.viewProjection*worldPos4;${e?"out.vu=uv*up.u.xy+up.u.zw;":""} ${t?"out.vv=uv2;":""} /*VB*/return out;}`,h=`struct LightEntry{vLightData:vec4<f32>,vLightDiffuse:vec4<f32>,vLightSpecular:vec4<f32>,vLightDirection:vec4<f32>};struct lightsUniforms{count:u32,_p0:u32,_p1:u32,_p2:u32,lights:array<LightEntry,${HI}>};@group(0)@binding(1)var<uniform>lights:lightsUniforms;`,w="struct matUniforms{dc:vec4<f32>,sc:vec4<f32>,ec:vec3<f32>,bs:f32,ac:vec3<f32>,tl:f32,ambTexLvl:f32,lmLvl:f32,opLvl:f32,aCut:f32,rLvl:f32,rCm:f32,_0:f32,_1:f32,};",M=o?"":jcA,S=`@fragment fn main(input:FragmentInput)${Q?"":" -> @location(0) vec4<f32>"}{`,R=o?"":"let viewDirectionW=normalize(scene.vEyePosition.xyz-input.vp);",N=o?"":"var normalW=normalize(input.vn);",F="var alpha=mat.dc.a;",G=I?`let _ds=textureSample(dT,dS,${i?"input.vv":"input.vu"});if(_ds.a<mat.aCut){discard;}var baseColor=_ds.rgb*mat.tl;`:"var baseColor=vec3<f32>(1.0,1.0,1.0);",m="let diffuseColor=mat.dc.rgb;",K="var emissiveContrib=mat.ec;",k=o?"":"var specularColor=mat.sc.rgb;";let L;o?L="var color=vec4<f32>(clamp(emissiveContrib*diffuseColor,vec3<f32>(0.0),vec3<f32>(1.0))*baseColor,alpha);":L=`var glossiness=mat.sc.a;var diffuseBase=vec3<f32>(0.0);var specularBase=vec3<f32>(0.0);var shadowFactors=array<f32,${HI}>(${new Array(HI).fill("1.0").join(", ")});var baseAmbientColor=vec3<f32>(1.0,1.0,1.0);var reflectionColor=vec3<f32>(0.0);let lc=min(mesh.lc,${HI}u); /*AD*/for(var li=0u;li<lc;li++){let lightIndex=mli(li);let r=computeLighting(viewDirectionW,normalW,lights.lights[lightIndex],glossiness,input.vp);let sf=shadowFactors[lightIndex];diffuseBase+=r[0]*sf;specularBase+=r[1]*sf;}let finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveContrib+mat.ac,vec3<f32>(0.0),vec3<f32>(1.0))*baseColor;let finalSpecular=specularBase*specularColor;var color=vec4<f32>(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);`;const H=`/*SU*/ ${h} ${w} ${r?"struct shadowParamsUniforms { biasAndScale: vec4<f32>, depthValues: vec4<f32>, }":""} /*MU*/@group(1)@binding(0)var<uniform>mesh:MeshUniforms;${o?"":w6("mesh")} ${M} /*HF*/ /*FB*/ /*FI*/ ${S} /*SV*/ ${R} ${N} /*AC*/ ${F} ${G} ${m} ${K} ${k} /*AT*/ ${Q?"return;":`${r?g:""} ${L} /*BC*/color=vec4<f32>(max(color.rgb,vec3<f32>(0.0)),color.a); /*BA*/return color;`}}`;return{_vertexTemplate:f,_fragmentTemplate:H,_baseMeshUboFields:c,_baseVertexAttributes:n,_baseVaryings:s,_baseBindings:l}}const WcA={f32:{align:4,size:4},u32:{align:4,size:4},i32:{align:4,size:4},"vec2<f32>":{align:8,size:8},"vec3<f32>":{align:16,size:12},"vec4<f32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"mat4x4<f32>":{align:16,size:64}};function Aq(A,g){return A+g-1&~(g-1)}function zcA(A){const g=WcA[A];if(g)return g;const I=/^array<vec4<u32>,\s*(\d+)>$/.exec(A);if(I)return{align:16,size:Number(I[1])*16};throw new Error(`Unknown UBO field type: ${A}`)}function ur(A){const g=new Map,I=[];let e=0;for(const o of A){const Q=zcA(o._type);e=Aq(e,Q.align),g.set(o._name,e),I.push(`${o._name}: ${o._type},`),e+=Q.size}const t=A.length>0?Aq(e,16):0,i=I.join(`
|
|
2
2
|
`);return{_totalBytes:t,_offsets:g,_structBody:i}}const gq=1,a9=2;function ZcA(A){const g=new Map;for(const Q of A){if(g.has(Q._id))throw Error();g.set(Q._id,Q)}const I=new Map,e=new Map;for(const Q of A){I.has(Q._id)||I.set(Q._id,0);for(const r of Q._dependencies??[]){if(!g.has(r))throw Error();I.set(Q._id,(I.get(Q._id)??0)+1);let E=e.get(r);E||(E=[],e.set(r,E)),E.push(Q._id)}}const t=[];for(const[Q,r]of I)r===0&&t.push(Q);t.sort();const i=[];let o=0;for(;o<t.length;){const Q=t[o++];i.push(g.get(Q));for(const r of e.get(Q)??[]){const E=(I.get(r)??1)-1;if(I.set(r,E),E===0){let n=o;for(;n<t.length&&t[n]<r;)n++;t.splice(n,0,r)}}}if(i.length!==A.length)throw Error();return i}function Iq(A,g){const I=new Set,e=[];for(const t of A)I.has(t._name)||(I.add(t._name),e.push(t));for(const t of g)I.has(t._name)||(I.add(t._name),e.push(t));return e}function XcA(A,g){const I={binding:A,visibility:g._visibility};switch(g._type._kind){case"uniform-buffer":I.buffer={type:"uniform"};break;case"texture":{const e=g._type._textureType==="texture_depth_2d"?"depth":g._type._textureType==="texture_2d<u32>"?"uint":"float";I.texture={sampleType:g._type._sampleType??e,viewDimension:g._type._textureType.includes("array")?"2d-array":g._type._textureType.includes("cube")?"cube":"2d"};break}case"sampler":I.sampler={type:g._type._samplerType==="sampler_comparison"?"comparison":g._type._samplerType==="sampler_non_filtering"?"non-filtering":"filtering"};break;case"storage-texture":I.storageTexture={access:g._type._access,format:g._type._format};break}return I}function $cA(A,g,I){switch(I._type._kind){case"uniform-buffer":return`@group(${A})@binding(${g})var<uniform> ${I._name}:${I._name}Uniforms;`;case"texture":return`@group(${A})@binding(${g})var ${I._name}:${I._type._textureType};`;case"sampler":return`@group(${A})@binding(${g})var ${I._name}:${I._type._samplerType==="sampler_non_filtering"?"sampler":I._type._samplerType};`;case"storage-texture":return`@group(${A})@binding(${g})var ${I._name}:texture_storage_2d<${I._type._format},${I._type._access}>;`}}const AlA=/\/\*([A-Z_0-9]+)\*\//g;function eq(A,g,I){return A.replace(AlA,(e,t)=>{const i=[];for(const o of g){const Q=o[I];Q?.[t]&&i.push(Q[t])}return i.join(`
|
|
3
3
|
`)})}function tq(A,g){const I=ZcA(g),e=[],t=[],i=[],o=[],Q=[];for(const Z of I){Z._vertexAttributes&&e.push(...Z._vertexAttributes),Z._varyings&&t.push(...Z._varyings),Z._helperFunctions&&i.push(Z._helperFunctions),Z._vertexHelperFunctions&&o.push(Z._vertexHelperFunctions);for(const O of Z._vertexBuiltins??[])Q.push(`@builtin(${O._builtin})${O._name}:${O._type},`)}const r=Iq(A._baseVertexAttributes,e),E=[],n=[],s=new Map,c=new Map;for(let Z=0;Z<r.length;Z++){const O=r[Z];E.push(`@location(${Z})${O._name}:${O._type},`),O._bufferGroup?(s.has(O._bufferGroup)||(s.set(O._bufferGroup,[]),c.set(O._bufferGroup,O)),s.get(O._bufferGroup).push({loc:Z,off:O._offset??0,fmt:O._gpuFormat})):n.push({arrayStride:O._arrayStride,stepMode:O._stepMode??"vertex",attributes:[{shaderLocation:Z,offset:O._offset??0,format:O._gpuFormat}]})}for(const[Z,O]of s){const P=c.get(Z);n.push({arrayStride:P._arrayStride,stepMode:P._stepMode??"vertex",attributes:O.map(gA=>({shaderLocation:gA.loc,offset:gA.off,format:gA.fmt}))})}let l=r.length;for(const Z of I)if(Z._pipelineVertexBuffers){const O=Z._pipelineVertexBuffers(l);n.push(...O._buffers),l=O._nextLoc}const p="@builtin(position)clipPos:vec4f,"+Iq(A._baseVaryings,t).map((Z,O)=>`@location(${O})${Z._name}:${Z._type},`).join(`
|
|
4
4
|
`),y=!!(A._baseMaterialUboFields&&A._baseMaterialUboFields.length>0),_=[...A._baseMeshUboFields],u=y?[...A._baseMaterialUboFields]:[];for(const Z of I)Z._uboFields?.length&&(y?u:_).push(...Z._uboFields);const f=ur(_),h=y?ur(u):void 0,w=[{binding:0,visibility:gq|a9,buffer:{type:"uniform"}}];y&&w.push({binding:1,visibility:a9,buffer:{type:"uniform"}});const M=[],S=[],R=[];let N=y?2:1,F=0;function G(Z,O){const P=Z._group==="shadow",gA=P?F++:N++,yA=P?2:1;(P?M:w).push(XcA(gA,Z));const cA=$cA(yA,gA,Z);Z._visibility&gq&&S.push(cA),Z._visibility&a9&&R.push(cA)}for(const Z of A._baseVertexBindings??[])G(Z);for(const Z of I)for(const O of Z._vertexBindings??[])G(O);for(const Z of A._baseBindings??[])G(Z);for(const Z of I)for(const O of(Z._bindings??[]).filter(P=>(P._group??"mesh")==="mesh"))G(O);for(const Z of I)for(const O of(Z._bindings??[]).filter(P=>P._group==="shadow"))G(O);const m=I.map(Z=>Z._id).join("|"),K=(Q.length?Q.join(`
|