(function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define([], factory); else if (typeof exports === 'object') exports['luma'] = factory(); else root['luma'] = factory();})(globalThis, function () { "use strict";var __exports__=(()=>{var Sr=Object.create;var Vt=Object.defineProperty;var Ar=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var Tr=Object.getPrototypeOf,Or=Object.prototype.hasOwnProperty;var Lr=(s,t,e)=>t in s?Vt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Ir=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports),Nr=(s,t)=>{for(var e in t)Vt(s,e,{get:t[e],enumerable:!0})},ae=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Er(t))!Or.call(s,r)&&r!==e&&Vt(s,r,{get:()=>t[r],enumerable:!(n=Ar(t,r))||n.enumerable});return s},ce=(s,t,e)=>(ae(s,t,"default"),e&&ae(e,t,"default")),C=(s,t,e)=>(e=s!=null?Sr(Tr(s)):{},ae(t||!s||!s.__esModule?Vt(e,"default",{value:s,enumerable:!0}):e,s)),Pr=s=>ae(Vt({},"__esModule",{value:!0}),s);var st=(s,t,e)=>(Lr(s,typeof t!="symbol"?t+"":t,e),e);var z=Ir(($i,en)=>{en.exports=globalThis.luma});var se={};Nr(se,{AnimationLoop:()=>St,AnimationLoopTemplate:()=>ue,BufferTransform:()=>Ut,ClipSpace:()=>Be,Computation:()=>ee,ConeGeometry:()=>je,CubeGeometry:()=>Ge,CylinderGeometry:()=>We,GPUGeometry:()=>Ct,Geometry:()=>j,GroupNode:()=>$t,IcoSphereGeometry:()=>He,KeyFrames:()=>le,Model:()=>K,ModelNode:()=>Ve,PipelineFactory:()=>lt,PlaneGeometry:()=>Ye,ScenegraphNode:()=>dt,ShaderFactory:()=>ut,SphereGeometry:()=>Xe,TextureTransform:()=>$e,Timeline:()=>he,TruncatedConeGeometry:()=>yt,_ShaderInputs:()=>xt,makeAnimationLoop:()=>rn});ce(se,C(z(),1));var Rr=1,zr=1,he=class{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(t){let{delay:e=0,duration:n=Number.POSITIVE_INFINITY,rate:r=1,repeat:i=1}=t,o=Rr++,c={time:0,delay:e,duration:n,rate:r,repeat:i};return this._setChannelTime(c,this.time),this.channels.set(o,c),o}removeChannel(t){this.channels.delete(t);for(let[e,n]of this.animations)n.channel===t&&this.detachAnimation(e)}isFinished(t){let e=this.channels.get(t);return e===void 0?!1:this.time>=e.delay+e.duration*e.repeat}getTime(t){if(t===void 0)return this.time;let e=this.channels.get(t);return e===void 0?-1:e.time}setTime(t){this.time=Math.max(0,t);let e=this.channels.values();for(let r of e)this._setChannelTime(r,this.time);let n=this.animations.values();for(let r of n){let{animation:i,channel:o}=r;i.setTime(this.getTime(o))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(t,e){let n=zr++;return this.animations.set(n,{animation:t,channel:e}),t.setTime(this.getTime(e)),n}detachAnimation(t){this.animations.delete(t)}update(t){this.playing&&(this.lastEngineTime===-1&&(this.lastEngineTime=t),this.setTime(this.time+(t-this.lastEngineTime)),this.lastEngineTime=t)}_setChannelTime(t,e){let n=e-t.delay,r=t.duration*t.repeat;n>=r?t.time=t.duration*t.rate:(t.time=Math.max(0,n)%t.duration,t.time*=t.rate)}};var le=class{startIndex=-1;endIndex=-1;factor=0;times=[];values=[];_lastTime=-1;constructor(t){this.setKeyFrames(t),this.setTime(0)}setKeyFrames(t){let e=t.length;this.times.length=e,this.values.length=e;for(let n=0;nt);++e);this.startIndex=e,this.endIndex=e+1;let r=this.times[this.startIndex],i=this.times[this.endIndex];this.factor=Math.min(Math.max(0,(t-r)/(i-r)),1)}};var ue=class{constructor(t){}async onInitialize(t){return null}};var sn=C(z(),1),fe=C(z(),1);function jt(){let s;if(typeof window<"u"&&window.performance)s=window.performance.now();else if(typeof process<"u"&&process.hrtime){let t=process.hrtime();s=t[0]*1e3+t[1]/1e6}else s=Date.now();return s}var wt=class{constructor(t,e){this.sampleSize=1,this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this.name=t,this.type=e,this.reset()}reset(){return this.time=0,this.count=0,this.samples=0,this.lastTiming=0,this.lastSampleTime=0,this.lastSampleCount=0,this._count=0,this._time=0,this._samples=0,this._startTime=0,this._timerPending=!1,this}setSampleSize(t){return this.sampleSize=t,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(t){return this._count+=t,this._samples++,this._checkSampling(),this}subtractCount(t){return this._count-=t,this._samples++,this._checkSampling(),this}addTime(t){return this._time+=t,this.lastTiming=t,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=jt(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(jt()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}};var Mt=class{constructor(t){this.stats={},this.id=t.id,this.stats={},this._initializeStats(t.stats),Object.seal(this)}get(t,e="count"){return this._getOrCreate({name:t,type:e})}get size(){return Object.keys(this.stats).length}reset(){for(let t of Object.values(this.stats))t.reset();return this}forEach(t){for(let e of Object.values(this.stats))t(e)}getTable(){let t={};return this.forEach(e=>{t[e.name]={time:e.time||0,count:e.count||0,average:e.getAverageTime()||0,hz:e.getHz()||0}}),t}_initializeStats(t=[]){t.forEach(e=>this._getOrCreate(e))}_getOrCreate(t){let{name:e,type:n}=t,r=this.stats[e];return r||(t instanceof wt?r=t:r=new wt(e,n),this.stats[e]=r),r}};var Cr=0,Fr={device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:s=>console.error(s),stats:sn.luma.stats.get(`animation-loop-${Cr++}`),useDevicePixels:!0,autoResizeViewport:!1,autoResizeDrawingBuffer:!1},St=class{device=null;canvas=null;props;animationProps=null;timeline=null;stats;cpuTime;gpuTime;frameRate;display;needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;constructor(t){if(this.props={...Fr,...t},t=this.props,!t.device)throw new Error("No device provided");let{useDevicePixels:e=!0}=this.props;this.stats=t.stats||new Mt({id:"animation-loop-stats"}),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.frameRate=this.stats.get("Frame Rate"),this.setProps({autoResizeViewport:t.autoResizeViewport,autoResizeDrawingBuffer:t.autoResizeDrawingBuffer,useDevicePixels:e}),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this._onMousemove=this._onMousemove.bind(this),this._onMouseleave=this._onMouseleave.bind(this)}destroy(){this.stop(),this._setDisplay(null)}delete(){this.destroy()}setNeedsRedraw(t){return this.needsRedraw=this.needsRedraw||t,this}setProps(t){return"autoResizeViewport"in t&&(this.props.autoResizeViewport=t.autoResizeViewport||!1),"autoResizeDrawingBuffer"in t&&(this.props.autoResizeDrawingBuffer=t.autoResizeDrawingBuffer||!1),"useDevicePixels"in t&&(this.props.useDevicePixels=t.useDevicePixels||!1),this}async start(){if(this._running)return this;this._running=!0;try{let t;return this._initialized||(this._initialized=!0,await this._initDevice(),this._initialize(),await this.props.onInitialize(this._getAnimationProps())),this._running?(t!==!1&&(this._cancelAnimationFrame(),this._requestAnimationFrame()),this):null}catch(t){let e=t instanceof Error?t:new Error("Unknown error");throw this.props.onError(e),e}}stop(){return this._running&&(this.animationProps&&this.props.onFinalize(this.animationProps),this._cancelAnimationFrame(),this._nextFramePromise=null,this._resolveNextFrame=null,this._running=!1),this}redraw(){return this.device?.isLost?this:(this._beginFrameTimers(),this._setupFrame(),this._updateAnimationProps(),this._renderFrame(this._getAnimationProps()),this._clearNeedsRedraw(),this._resolveNextFrame&&(this._resolveNextFrame(this),this._nextFramePromise=null,this._resolveNextFrame=null),this._endFrameTimers(),this)}attachTimeline(t){return this.timeline=t,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise(t=>{this._resolveNextFrame=t})),this._nextFramePromise}async toDataURL(){if(this.setNeedsRedraw("toDataURL"),await this.waitForRender(),this.canvas instanceof HTMLCanvasElement)return this.canvas.toDataURL();throw new Error("OffscreenCanvas")}_initialize(){this._startEventHandling(),this._initializeAnimationProps(),this._updateAnimationProps(),this._resizeCanvasDrawingBuffer(),this._resizeViewport()}_setDisplay(t){this.display&&(this.display.destroy(),this.display.animationLoop=null),t&&(t.animationLoop=this),this.display=t}_requestAnimationFrame(){this._running&&(this._animationFrameId=(0,fe.requestAnimationFrame)(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&((0,fe.cancelAnimationFrame)(this._animationFrameId),this._animationFrameId=null)}_animationFrame(){this._running&&(this.redraw(),this._requestAnimationFrame())}_renderFrame(t){if(this.display){this.display._renderFrame(t);return}this.props.onRender(this._getAnimationProps()),this.device.submit()}_clearNeedsRedraw(){this.needsRedraw=!1}_setupFrame(){this._resizeCanvasDrawingBuffer(),this._resizeViewport()}_initializeAnimationProps(){if(!this.device)throw new Error("loop");this.animationProps={animationLoop:this,device:this.device,canvas:this.device?.canvasContext?.canvas,timeline:this.timeline,useDevicePixels:this.props.useDevicePixels,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,_mousePosition:null}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:t,height:e,aspect:n}=this._getSizeAndAspect();(t!==this.animationProps.width||e!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),n!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=t,this.animationProps.height=e,this.animationProps.aspect=n,this.animationProps.needsRedraw=this.needsRedraw,this.animationProps.engineTime=Date.now()-this.animationProps.startTime,this.timeline&&this.timeline.update(this.animationProps.engineTime),this.animationProps.tick=Math.floor(this.animationProps.time/1e3*60),this.animationProps.tock++,this.animationProps.time=this.timeline?this.timeline.getTime():this.animationProps.engineTime}async _initDevice(){if(this.device=await this.props.device,!this.device)throw new Error("No device provided");this.canvas=this.device.canvasContext?.canvas||null}_createInfoDiv(){if(this.canvas&&this.props.onAddHTML){let t=document.createElement("div");document.body.appendChild(t),t.style.position="relative";let e=document.createElement("div");e.style.position="absolute",e.style.left="10px",e.style.bottom="10px",e.style.width="300px",e.style.background="white",this.canvas instanceof HTMLCanvasElement&&t.appendChild(this.canvas),t.appendChild(e);let n=this.props.onAddHTML(e);n&&(e.innerHTML=n)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[t,e]=this.device?.canvasContext?.getPixelSize()||[1,1],n=1,r=this.device?.canvasContext?.canvas;return r&&r.clientHeight?n=r.clientWidth/r.clientHeight:t>0&&e>0&&(n=t/e),{width:t,height:e,aspect:n}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_resizeCanvasDrawingBuffer(){this.props.autoResizeDrawingBuffer&&this.device?.canvasContext?.resize({useDevicePixels:this.props.useDevicePixels})}_beginFrameTimers(){this.frameRate.timeEnd(),this.frameRate.timeStart(),this.cpuTime.timeStart()}_endFrameTimers(){this.cpuTime.timeEnd()}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove.bind(this)),this.canvas.addEventListener("mouseleave",this._onMouseleave.bind(this)))}_onMousemove(t){t instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[t.offsetX,t.offsetY])}_onMouseleave(t){this._getAnimationProps()._mousePosition=null}};var nn=C(z(),1);function rn(s,t){let e=null,n=t?.device||nn.luma.createDevice(),r=new St({...t,device:n,async onInitialize(i){return e=new s(i),await e?.onInitialize(i)},onRender:i=>e?.onRender(i),onFinalize:i=>e?.onFinalize(i)});return r.getInfo=()=>this.AnimationLoopTemplateCtor.info,r}var ft=C(z(),1),De=C(z(),1),D=C(z(),1),Ue=C(z(),1);function nt(s,t){if(!s)throw new Error(t||"shadertools: assertion failed.")}var Ke={number:{type:"number",validate(s,t){return Number.isFinite(s)&&typeof t=="object"&&(t.max===void 0||s<=t.max)&&(t.min===void 0||s>=t.min)}},array:{type:"array",validate(s,t){return Array.isArray(s)||ArrayBuffer.isView(s)}}};function an(s){let t={};for(let[e,n]of Object.entries(s))t[e]=Dr(n);return t}function cn(s,t,e){let n={};for(let[r,i]of Object.entries(t))s&&r in s&&!i.private?(i.validate&&nt(i.validate(s[r],i),`${e}: invalid ${r}`),n[r]=s[r]):n[r]=i.value;return n}function Dr(s){let t=on(s);if(t!=="object")return{value:s,...Ke[t],type:t};if(typeof s=="object")return s?s.type!==void 0?{...s,...Ke[s.type],type:s.type}:s.value===void 0?{type:"object",value:s}:(t=on(s.value),{...s,...Ke[t],type:t}):{type:"object",value:null};throw new Error("props")}function on(s){return Array.isArray(s)||ArrayBuffer.isView(s)?"array":typeof s}var hn=`#ifdef MODULE_LOGDEPTH logdepth_adjustPosition(gl_Position); #endif `,ln=`#ifdef MODULE_MATERIAL gl_FragColor = material_filterColor(gl_FragColor); #endif #ifdef MODULE_LIGHTING gl_FragColor = lighting_filterColor(gl_FragColor); #endif #ifdef MODULE_FOG gl_FragColor = fog_filterColor(gl_FragColor); #endif #ifdef MODULE_PICKING gl_FragColor = picking_filterHighlightColor(gl_FragColor); gl_FragColor = picking_filterPickingColor(gl_FragColor); #endif #ifdef MODULE_LOGDEPTH logdepth_setFragDepth(); #endif `;var Ur={vertex:hn,fragment:ln},un=/void\s+main\s*\([^)]*\)\s*\{\n?/,fn=/}\n?[^{}]*$/,Ze=[],Gt="__LUMA_INJECT_DECLARATIONS__";function dn(s){let t={vertex:{},fragment:{}};for(let e in s){let n=s[e],r=qr(e);typeof n=="string"&&(n={order:0,injection:n}),t[r][e]=n}return t}function qr(s){let t=s.slice(0,2);switch(t){case"vs":return"vertex";case"fs":return"fragment";default:throw new Error(t)}}function Wt(s,t,e,n=!1){let r=t==="vertex";for(let i in e){let o=e[i];o.sort((h,f)=>h.order-f.order),Ze.length=o.length;for(let h=0,f=o.length;hh+c));break;case"vs:#main-end":r&&(s=s.replace(fn,h=>c+h));break;case"fs:#decl":r||(s=s.replace(Gt,c));break;case"fs:#main-start":r||(s=s.replace(un,h=>h+c));break;case"fs:#main-end":r||(s=s.replace(fn,h=>c+h));break;default:s=s.replace(i,h=>h+c)}}return s=s.replace(Gt,""),n&&(s=s.replace(/\}\s*$/,i=>i+Ur[t])),s}var $r=1,Q=class{name;vs;fs;getModuleUniforms;dependencies;deprecations;defines;injections;uniforms={};uniformTypes={};static instantiateModules(t){return t.map(e=>{if(e instanceof Q)return e;nt(typeof e!="string",`Shader module use by name is deprecated. Import shader module '${JSON.stringify(e)}' and use it directly.`),e.name||(console.warn("shader module has no name"),e.name=`shader-module-${$r++}`);let n=new Q(e);return n.dependencies=Q.instantiateModules(e.dependencies||[]),n})}constructor(t){let{name:e,vs:n,fs:r,dependencies:i=[],uniformTypes:o={},uniformPropTypes:c={},getUniforms:h,deprecations:f=[],defines:m={},inject:p={}}=t;nt(typeof e=="string"),this.name=e,this.vs=n,this.fs=r,this.getModuleUniforms=h,this.dependencies=Q.instantiateModules(i),this.deprecations=this._parseDeprecationDefinitions(f),this.defines=m,this.injections=dn(p),this.uniformTypes=o,c&&(this.uniforms=an(c))}getModuleSource(t){let e;switch(t){case"vertex":e=this.vs||"";break;case"fragment":e=this.fs||"";break;default:nt(!1)}let n=this.name.toUpperCase().replace(/[^0-9a-z]/gi,"_");return`// ----- MODULE ${this.name} --------------- #define MODULE_${n} ${e} `}getUniforms(t,e){return this.getModuleUniforms?this.getModuleUniforms(t,e):cn(t,this.uniforms,this.name)}getDefines(){return this.defines}checkDeprecations(t,e){this.deprecations.forEach(n=>{n.regex?.test(t)&&(n.deprecated?e.deprecated(n.old,n.new)():e.removed(n.old,n.new)())})}_parseDeprecationDefinitions(t){return t.forEach(e=>{switch(e.type){case"function":e.regex=new RegExp(`\\b${e.old}\\(`);break;default:e.regex=new RegExp(`${e.type} ${e.old};`)}}),t}_defaultGetUniforms(t={}){let e={},n=this.uniforms;for(let r in n){let i=n[r];r in t&&!i.private?(i.validate&&nt(i.validate(t[r],i),`${this.name}: invalid ${r}`),e[r]=t[r]):e[r]=i.value}return e}};function Je(s){if(s.source&&s.platformInfo.type==="webgpu")return{...s,vs:void 0,fs:void 0};if(!s.vs)throw new Error("no vertex shader");let t=mn(s.platformInfo,s.vs),e;return s.fs&&(e=mn(s.platformInfo,s.fs)),{...s,vs:t,fs:e}}function mn(s,t){if(typeof t=="string")return t;switch(s.type){case"webgpu":if(t?.wgsl)return t.wgsl;throw new Error("WebGPU does not support GLSL shaders");default:if(t?.glsl)return t.glsl;throw new Error("WebGL does not support WGSL shaders")}}function kt(s){let t=Q.instantiateModules(s);return Br(t)}function Br(s){let t={},e={};return pn({modules:s,level:0,moduleMap:t,moduleDepth:e}),Object.keys(e).sort((n,r)=>e[r]-e[n]).map(n=>t[n])}function pn(s){let{modules:t,level:e,moduleMap:n,moduleDepth:r}=s;if(e>=5)throw new Error("Possible loop in shader dependency graph");for(let i of t)n[i.name]=i,(r[i.name]===void 0||r[i.name]o.order-c.order);for(let o of i)e+=` ${o.injection} `}r.footer&&(e+=` ${r.footer}`),e+=`} `}return e}function es(s){let t={vertex:{},fragment:{}};for(let e of s){let n,r;typeof e!="string"?(n=e,r=n.hook):(n={},r=e),r=r.trim();let[i,o]=r.split(":"),c=r.replace(/\(.+/,""),h=Object.assign(n,{signature:o});switch(i){case"vs":t.vertex[c]=h;break;case"fs":t.fragment[c]=h;break;default:throw new Error(i)}}return t}function wn(s,t){return{name:Gr(s,t),language:"glsl",version:Wr(s)}}function Gr(s,t="unnamed"){let n=/#define[^\S\r\n]*SHADER_NAME[^\S\r\n]*([A-Za-z0-9_-]+)\s*/.exec(s);return n?n[1]:t}function Wr(s){let t=100,e=s.match(/[^\s]+/g);if(e&&e.length>=2&&e[0]==="#version"){let n=parseInt(e[1],10);Number.isFinite(n)&&(t=n)}if(t!==100&&t!==300)throw new Error(`Invalid GLSL version ${t}`);return t}var vn=` ${Gt} `,Hr=`precision highp float; `;function bn(s){let t=kt(s.modules||[]);return{source:ss(s.platformInfo,{...s,source:s.source,stage:"vertex",modules:t}),getUniforms:ns(t)}}function Mn(s){let t=kt(s.modules||[]);return{vs:ss(s.platformInfo,{...s,source:s.vs,stage:"vertex",modules:t}),fs:ss(s.platformInfo,{...s,source:s.fs,stage:"fragment",modules:t}),getUniforms:ns(t)}}function Sn(s){let{vs:t,fs:e}=s,n=kt(s.modules||[]);return{vs:kn(s.platformInfo,{...s,source:t,stage:"vertex",modules:n}),fs:kn(s.platformInfo,{...s,source:e,stage:"fragment",modules:n}),getUniforms:ns(n)}}function ss(s,t){let{source:e,stage:n,modules:r,hookFunctions:i=[],inject:o={},log:c}=t;nt(typeof e=="string","shader source must be a string");let h=e,f="",m=es(i),p={},_={},y={};for(let g in o){let w=typeof o[g]=="string"?{injection:o[g],order:0}:o[g],M=/^(v|f)s:(#)?([\w-]+)$/.exec(g);if(M){let b=M[2],x=M[3];b?x==="decl"?_[g]=[w]:y[g]=[w]:p[g]=[w]}else y[g]=[w]}let S=s.type!=="webgpu"?r:[];for(let g of S){c&&g.checkDeprecations(h,c);let w=g.getModuleSource(n,"wgsl");f+=w;let M=g.injections[n];for(let b in M){let x=/^(v|f)s:#([\w-]+)$/.exec(b);if(x){let v=x[2]==="decl"?_:y;v[b]=v[b]||[],v[b].push(M[b])}else p[b]=p[b]||[],p[b].push(M[b])}}return f+=vn,f=Wt(f,n,_),f+=ts(m[n],p),f+=h,f=Wt(f,n,y),f}function kn(s,t){let{id:e,source:n,stage:r,language:i="glsl",modules:o,defines:c={},hookFunctions:h=[],inject:f={},prologue:m=!0,log:p}=t;nt(typeof n=="string","shader source must be a string");let _=i==="glsl"?wn(n).version:-1,y=s.shaderLanguageVersion,S=_===100?"#version 100":"#version 300 es",w=n.split(` `).slice(1).join(` `),M={};o.forEach(T=>{Object.assign(M,T.getDefines())}),Object.assign(M,c);let b="";switch(i){case"wgsl":break;case"glsl":b=m?`${S} // ----- PROLOGUE ------------------------- ${Yr({id:e,source:n,stage:r})} ${`#define SHADER_TYPE_${r.toUpperCase()}`} ${_n(s)} ${r==="fragment"?Hr:""} // ----- APPLICATION DEFINES ------------------------- ${Xr(M)} `:`${S} `;break}let x=es(h),k={},v={},A={};for(let T in f){let R=typeof f[T]=="string"?{injection:f[T],order:0}:f[T],O=/^(v|f)s:(#)?([\w-]+)$/.exec(T);if(O){let N=O[2],E=O[3];N?E==="decl"?v[T]=[R]:A[T]=[R]:k[T]=[R]}else A[T]=[R]}for(let T of o){p&&T.checkDeprecations(w,p);let R=T.getModuleSource(r);b+=R;let O=T.injections[r];for(let N in O){let E=/^(v|f)s:#([\w-]+)$/.exec(N);if(E){let P=E[2]==="decl"?v:A;P[N]=P[N]||[],P[N].push(O[N])}else k[N]=k[N]||[],k[N].push(O[N])}}return b+="// ----- MAIN SHADER SOURCE -------------------------",b+=vn,b=Wt(b,r,v),b+=ts(x[r],k),b+=w,b=Wt(b,r,A),i==="glsl"&&_!==y&&(b=xn(b,r)),b.trim()}function ns(s){return function(e){let n={};for(let r of s){let i=r.getUniforms(e,n);Object.assign(n,i)}return n}}function Yr(s){let{id:t,source:e,stage:n}=s;return t&&e.indexOf("SHADER_NAME")===-1?` #define SHADER_NAME ${t}_${n} `:""}function Xr(s={}){let t="";for(let e in s){let n=s[e];(n||Number.isFinite(n))&&(t+=`#define ${e.toUpperCase()} ${s[e]} `)}return t}var At=class{_hookFunctions=[];_defaultModules=[];static getDefaultShaderAssembler(){return At.defaultShaderAssembler=At.defaultShaderAssembler||new At,At.defaultShaderAssembler}addDefaultModule(t){this._defaultModules.find(e=>e.name===(typeof t=="string"?t:t.name))||this._defaultModules.push(t)}removeDefaultModule(t){let e=typeof t=="string"?t:t.name;this._defaultModules=this._defaultModules.filter(n=>n.name!==e)}addShaderHook(t,e){e&&(t=Object.assign(e,{hook:t})),this._hookFunctions.push(t)}assembleShader(t){let e=this._getModuleList(t.modules),n=this._hookFunctions,r=Je(t);return{...bn({platformInfo:t.platformInfo,...r,modules:e,hookFunctions:n}),modules:e}}assembleShaderPair(t){let e=Je(t),n=this._getModuleList(t.modules),r=this._hookFunctions,{platformInfo:i}=t;return{...t.platformInfo.shaderLanguage==="wgsl"?Mn({platformInfo:i,...e,modules:n,hookFunctions:r}):Sn({platformInfo:i,...e,modules:n,hookFunctions:r}),modules:n}}_getModuleList(t=[]){let e=new Array(this._defaultModules.length+t.length),n={},r=0;for(let i=0,o=this._defaultModules.length;i":return this.left.evaluate(t)>this.right.evaluate(t)?1:0;case"<=":return this.left.evaluate(t)<=this.right.evaluate(t)?1:0;case">=":return this.left.evaluate(t)>=this.right.evaluate(t)?1:0;case"&&":return this.left.evaluate(t)&&this.right.evaluate(t)?1:0;case"||":return this.left.evaluate(t)||this.right.evaluate(t)?1:0;default:throw new Error(`Unknown operator ${this.operator}`)}}search(t){this.left.search(t),this.right.search(t)}},Se=class extends tt{constructor(){super()}},As=class extends Se{constructor(t,e){super(),this.selector=t,this.body=e}get astNodeType(){return"case"}search(t){this.searchBlock(this.body,t)}},Es=class extends Se{constructor(t){super(),this.body=t}get astNodeType(){return"default"}search(t){this.searchBlock(this.body,t)}},Ts=class extends tt{constructor(t,e,n){super(),this.name=t,this.type=e,this.attributes=n}get astNodeType(){return"argument"}},Os=class extends tt{constructor(t,e){super(),this.condition=t,this.body=e}get astNodeType(){return"elseif"}search(t){this.condition.search(t),this.searchBlock(this.body,t)}},Ls=class extends tt{constructor(t,e,n){super(),this.name=t,this.type=e,this.attributes=n}get astNodeType(){return"member"}},Is=class extends tt{constructor(t,e){super(),this.name=t,this.value=e}get astNodeType(){return"attribute"}},d,u;(function(s){s[s.token=0]="token",s[s.keyword=1]="keyword",s[s.reserved=2]="reserved"})(u||(u={}));var l=class{constructor(t,e,n){this.name=t,this.type=e,this.rule=n}toString(){return this.name}},a=class{};d=a;a.none=new l("",u.reserved,"");a.eof=new l("EOF",u.token,"");a.reserved={asm:new l("asm",u.reserved,"asm"),bf16:new l("bf16",u.reserved,"bf16"),do:new l("do",u.reserved,"do"),enum:new l("enum",u.reserved,"enum"),f16:new l("f16",u.reserved,"f16"),f64:new l("f64",u.reserved,"f64"),handle:new l("handle",u.reserved,"handle"),i8:new l("i8",u.reserved,"i8"),i16:new l("i16",u.reserved,"i16"),i64:new l("i64",u.reserved,"i64"),mat:new l("mat",u.reserved,"mat"),premerge:new l("premerge",u.reserved,"premerge"),regardless:new l("regardless",u.reserved,"regardless"),typedef:new l("typedef",u.reserved,"typedef"),u8:new l("u8",u.reserved,"u8"),u16:new l("u16",u.reserved,"u16"),u64:new l("u64",u.reserved,"u64"),unless:new l("unless",u.reserved,"unless"),using:new l("using",u.reserved,"using"),vec:new l("vec",u.reserved,"vec"),void:new l("void",u.reserved,"void")};a.keywords={array:new l("array",u.keyword,"array"),atomic:new l("atomic",u.keyword,"atomic"),bool:new l("bool",u.keyword,"bool"),f32:new l("f32",u.keyword,"f32"),i32:new l("i32",u.keyword,"i32"),mat2x2:new l("mat2x2",u.keyword,"mat2x2"),mat2x3:new l("mat2x3",u.keyword,"mat2x3"),mat2x4:new l("mat2x4",u.keyword,"mat2x4"),mat3x2:new l("mat3x2",u.keyword,"mat3x2"),mat3x3:new l("mat3x3",u.keyword,"mat3x3"),mat3x4:new l("mat3x4",u.keyword,"mat3x4"),mat4x2:new l("mat4x2",u.keyword,"mat4x2"),mat4x3:new l("mat4x3",u.keyword,"mat4x3"),mat4x4:new l("mat4x4",u.keyword,"mat4x4"),ptr:new l("ptr",u.keyword,"ptr"),sampler:new l("sampler",u.keyword,"sampler"),sampler_comparison:new l("sampler_comparison",u.keyword,"sampler_comparison"),struct:new l("struct",u.keyword,"struct"),texture_1d:new l("texture_1d",u.keyword,"texture_1d"),texture_2d:new l("texture_2d",u.keyword,"texture_2d"),texture_2d_array:new l("texture_2d_array",u.keyword,"texture_2d_array"),texture_3d:new l("texture_3d",u.keyword,"texture_3d"),texture_cube:new l("texture_cube",u.keyword,"texture_cube"),texture_cube_array:new l("texture_cube_array",u.keyword,"texture_cube_array"),texture_multisampled_2d:new l("texture_multisampled_2d",u.keyword,"texture_multisampled_2d"),texture_storage_1d:new l("texture_storage_1d",u.keyword,"texture_storage_1d"),texture_storage_2d:new l("texture_storage_2d",u.keyword,"texture_storage_2d"),texture_storage_2d_array:new l("texture_storage_2d_array",u.keyword,"texture_storage_2d_array"),texture_storage_3d:new l("texture_storage_3d",u.keyword,"texture_storage_3d"),texture_depth_2d:new l("texture_depth_2d",u.keyword,"texture_depth_2d"),texture_depth_2d_array:new l("texture_depth_2d_array",u.keyword,"texture_depth_2d_array"),texture_depth_cube:new l("texture_depth_cube",u.keyword,"texture_depth_cube"),texture_depth_cube_array:new l("texture_depth_cube_array",u.keyword,"texture_depth_cube_array"),texture_depth_multisampled_2d:new l("texture_depth_multisampled_2d",u.keyword,"texture_depth_multisampled_2d"),texture_external:new l("texture_external",u.keyword,"texture_external"),u32:new l("u32",u.keyword,"u32"),vec2:new l("vec2",u.keyword,"vec2"),vec3:new l("vec3",u.keyword,"vec3"),vec4:new l("vec4",u.keyword,"vec4"),bitcast:new l("bitcast",u.keyword,"bitcast"),block:new l("block",u.keyword,"block"),break:new l("break",u.keyword,"break"),case:new l("case",u.keyword,"case"),continue:new l("continue",u.keyword,"continue"),continuing:new l("continuing",u.keyword,"continuing"),default:new l("default",u.keyword,"default"),diagnostic:new l("diagnostic",u.keyword,"diagnostic"),discard:new l("discard",u.keyword,"discard"),else:new l("else",u.keyword,"else"),enable:new l("enable",u.keyword,"enable"),fallthrough:new l("fallthrough",u.keyword,"fallthrough"),false:new l("false",u.keyword,"false"),fn:new l("fn",u.keyword,"fn"),for:new l("for",u.keyword,"for"),function:new l("function",u.keyword,"function"),if:new l("if",u.keyword,"if"),let:new l("let",u.keyword,"let"),const:new l("const",u.keyword,"const"),loop:new l("loop",u.keyword,"loop"),while:new l("while",u.keyword,"while"),private:new l("private",u.keyword,"private"),read:new l("read",u.keyword,"read"),read_write:new l("read_write",u.keyword,"read_write"),return:new l("return",u.keyword,"return"),requires:new l("requires",u.keyword,"requires"),storage:new l("storage",u.keyword,"storage"),switch:new l("switch",u.keyword,"switch"),true:new l("true",u.keyword,"true"),alias:new l("alias",u.keyword,"alias"),type:new l("type",u.keyword,"type"),uniform:new l("uniform",u.keyword,"uniform"),var:new l("var",u.keyword,"var"),override:new l("override",u.keyword,"override"),workgroup:new l("workgroup",u.keyword,"workgroup"),write:new l("write",u.keyword,"write"),r8unorm:new l("r8unorm",u.keyword,"r8unorm"),r8snorm:new l("r8snorm",u.keyword,"r8snorm"),r8uint:new l("r8uint",u.keyword,"r8uint"),r8sint:new l("r8sint",u.keyword,"r8sint"),r16uint:new l("r16uint",u.keyword,"r16uint"),r16sint:new l("r16sint",u.keyword,"r16sint"),r16float:new l("r16float",u.keyword,"r16float"),rg8unorm:new l("rg8unorm",u.keyword,"rg8unorm"),rg8snorm:new l("rg8snorm",u.keyword,"rg8snorm"),rg8uint:new l("rg8uint",u.keyword,"rg8uint"),rg8sint:new l("rg8sint",u.keyword,"rg8sint"),r32uint:new l("r32uint",u.keyword,"r32uint"),r32sint:new l("r32sint",u.keyword,"r32sint"),r32float:new l("r32float",u.keyword,"r32float"),rg16uint:new l("rg16uint",u.keyword,"rg16uint"),rg16sint:new l("rg16sint",u.keyword,"rg16sint"),rg16float:new l("rg16float",u.keyword,"rg16float"),rgba8unorm:new l("rgba8unorm",u.keyword,"rgba8unorm"),rgba8unorm_srgb:new l("rgba8unorm_srgb",u.keyword,"rgba8unorm_srgb"),rgba8snorm:new l("rgba8snorm",u.keyword,"rgba8snorm"),rgba8uint:new l("rgba8uint",u.keyword,"rgba8uint"),rgba8sint:new l("rgba8sint",u.keyword,"rgba8sint"),bgra8unorm:new l("bgra8unorm",u.keyword,"bgra8unorm"),bgra8unorm_srgb:new l("bgra8unorm_srgb",u.keyword,"bgra8unorm_srgb"),rgb10a2unorm:new l("rgb10a2unorm",u.keyword,"rgb10a2unorm"),rg11b10float:new l("rg11b10float",u.keyword,"rg11b10float"),rg32uint:new l("rg32uint",u.keyword,"rg32uint"),rg32sint:new l("rg32sint",u.keyword,"rg32sint"),rg32float:new l("rg32float",u.keyword,"rg32float"),rgba16uint:new l("rgba16uint",u.keyword,"rgba16uint"),rgba16sint:new l("rgba16sint",u.keyword,"rgba16sint"),rgba16float:new l("rgba16float",u.keyword,"rgba16float"),rgba32uint:new l("rgba32uint",u.keyword,"rgba32uint"),rgba32sint:new l("rgba32sint",u.keyword,"rgba32sint"),rgba32float:new l("rgba32float",u.keyword,"rgba32float"),static_assert:new l("static_assert",u.keyword,"static_assert")};a.tokens={decimal_float_literal:new l("decimal_float_literal",u.token,/((-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?f?)|(-?[0-9]+(e|E)(\+|-)?[0-9]+f?)|([0-9]+f)/),hex_float_literal:new l("hex_float_literal",u.token,/-?0x((([0-9a-fA-F]*\.[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)((p|P)(\+|-)?[0-9]+f?)?)|([0-9a-fA-F]+(p|P)(\+|-)?[0-9]+f?))/),int_literal:new l("int_literal",u.token,/-?0x[0-9a-fA-F]+|0i?|-?[1-9][0-9]*i?/),uint_literal:new l("uint_literal",u.token,/0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u/),ident:new l("ident",u.token,/[_a-zA-Z][0-9a-zA-Z_]*/),and:new l("and",u.token,"&"),and_and:new l("and_and",u.token,"&&"),arrow:new l("arrow ",u.token,"->"),attr:new l("attr",u.token,"@"),forward_slash:new l("forward_slash",u.token,"/"),bang:new l("bang",u.token,"!"),bracket_left:new l("bracket_left",u.token,"["),bracket_right:new l("bracket_right",u.token,"]"),brace_left:new l("brace_left",u.token,"{"),brace_right:new l("brace_right",u.token,"}"),colon:new l("colon",u.token,":"),comma:new l("comma",u.token,","),equal:new l("equal",u.token,"="),equal_equal:new l("equal_equal",u.token,"=="),not_equal:new l("not_equal",u.token,"!="),greater_than:new l("greater_than",u.token,">"),greater_than_equal:new l("greater_than_equal",u.token,">="),shift_right:new l("shift_right",u.token,">>"),less_than:new l("less_than",u.token,"<"),less_than_equal:new l("less_than_equal",u.token,"<="),shift_left:new l("shift_left",u.token,"<<"),modulo:new l("modulo",u.token,"%"),minus:new l("minus",u.token,"-"),minus_minus:new l("minus_minus",u.token,"--"),period:new l("period",u.token,"."),plus:new l("plus",u.token,"+"),plus_plus:new l("plus_plus",u.token,"++"),or:new l("or",u.token,"|"),or_or:new l("or_or",u.token,"||"),paren_left:new l("paren_left",u.token,"("),paren_right:new l("paren_right",u.token,")"),semicolon:new l("semicolon",u.token,";"),star:new l("star",u.token,"*"),tilde:new l("tilde",u.token,"~"),underscore:new l("underscore",u.token,"_"),xor:new l("xor",u.token,"^"),plus_equal:new l("plus_equal",u.token,"+="),minus_equal:new l("minus_equal",u.token,"-="),times_equal:new l("times_equal",u.token,"*="),division_equal:new l("division_equal",u.token,"/="),modulo_equal:new l("modulo_equal",u.token,"%="),and_equal:new l("and_equal",u.token,"&="),or_equal:new l("or_equal",u.token,"|="),xor_equal:new l("xor_equal",u.token,"^="),shift_right_equal:new l("shift_right_equal",u.token,">>="),shift_left_equal:new l("shift_left_equal",u.token,"<<=")};a.simpleTokens={"@":d.tokens.attr,"{":d.tokens.brace_left,"}":d.tokens.brace_right,":":d.tokens.colon,",":d.tokens.comma,"(":d.tokens.paren_left,")":d.tokens.paren_right,";":d.tokens.semicolon};a.literalTokens={"&":d.tokens.and,"&&":d.tokens.and_and,"->":d.tokens.arrow,"/":d.tokens.forward_slash,"!":d.tokens.bang,"[":d.tokens.bracket_left,"]":d.tokens.bracket_right,"=":d.tokens.equal,"==":d.tokens.equal_equal,"!=":d.tokens.not_equal,">":d.tokens.greater_than,">=":d.tokens.greater_than_equal,">>":d.tokens.shift_right,"<":d.tokens.less_than,"<=":d.tokens.less_than_equal,"<<":d.tokens.shift_left,"%":d.tokens.modulo,"-":d.tokens.minus,"--":d.tokens.minus_minus,".":d.tokens.period,"+":d.tokens.plus,"++":d.tokens.plus_plus,"|":d.tokens.or,"||":d.tokens.or_or,"*":d.tokens.star,"~":d.tokens.tilde,_:d.tokens.underscore,"^":d.tokens.xor,"+=":d.tokens.plus_equal,"-=":d.tokens.minus_equal,"*=":d.tokens.times_equal,"/=":d.tokens.division_equal,"%=":d.tokens.modulo_equal,"&=":d.tokens.and_equal,"|=":d.tokens.or_equal,"^=":d.tokens.xor_equal,">>=":d.tokens.shift_right_equal,"<<=":d.tokens.shift_left_equal};a.regexTokens={decimal_float_literal:d.tokens.decimal_float_literal,hex_float_literal:d.tokens.hex_float_literal,int_literal:d.tokens.int_literal,uint_literal:d.tokens.uint_literal,ident:d.tokens.ident};a.storage_class=[d.keywords.function,d.keywords.private,d.keywords.workgroup,d.keywords.uniform,d.keywords.storage];a.access_mode=[d.keywords.read,d.keywords.write,d.keywords.read_write];a.sampler_type=[d.keywords.sampler,d.keywords.sampler_comparison];a.sampled_texture_type=[d.keywords.texture_1d,d.keywords.texture_2d,d.keywords.texture_2d_array,d.keywords.texture_3d,d.keywords.texture_cube,d.keywords.texture_cube_array];a.multisampled_texture_type=[d.keywords.texture_multisampled_2d];a.storage_texture_type=[d.keywords.texture_storage_1d,d.keywords.texture_storage_2d,d.keywords.texture_storage_2d_array,d.keywords.texture_storage_3d];a.depth_texture_type=[d.keywords.texture_depth_2d,d.keywords.texture_depth_2d_array,d.keywords.texture_depth_cube,d.keywords.texture_depth_cube_array,d.keywords.texture_depth_multisampled_2d];a.texture_external_type=[d.keywords.texture_external];a.any_texture_type=[...d.sampled_texture_type,...d.multisampled_texture_type,...d.storage_texture_type,...d.depth_texture_type,...d.texture_external_type];a.texel_format=[d.keywords.r8unorm,d.keywords.r8snorm,d.keywords.r8uint,d.keywords.r8sint,d.keywords.r16uint,d.keywords.r16sint,d.keywords.r16float,d.keywords.rg8unorm,d.keywords.rg8snorm,d.keywords.rg8uint,d.keywords.rg8sint,d.keywords.r32uint,d.keywords.r32sint,d.keywords.r32float,d.keywords.rg16uint,d.keywords.rg16sint,d.keywords.rg16float,d.keywords.rgba8unorm,d.keywords.rgba8unorm_srgb,d.keywords.rgba8snorm,d.keywords.rgba8uint,d.keywords.rgba8sint,d.keywords.bgra8unorm,d.keywords.bgra8unorm_srgb,d.keywords.rgb10a2unorm,d.keywords.rg11b10float,d.keywords.rg32uint,d.keywords.rg32sint,d.keywords.rg32float,d.keywords.rgba16uint,d.keywords.rgba16sint,d.keywords.rgba16float,d.keywords.rgba32uint,d.keywords.rgba32sint,d.keywords.rgba32float];a.const_literal=[d.tokens.int_literal,d.tokens.uint_literal,d.tokens.decimal_float_literal,d.tokens.hex_float_literal,d.keywords.true,d.keywords.false];a.literal_or_ident=[d.tokens.ident,d.tokens.int_literal,d.tokens.uint_literal,d.tokens.decimal_float_literal,d.tokens.hex_float_literal];a.element_count_expression=[d.tokens.int_literal,d.tokens.uint_literal,d.tokens.ident];a.template_types=[d.keywords.vec2,d.keywords.vec3,d.keywords.vec4,d.keywords.mat2x2,d.keywords.mat2x3,d.keywords.mat2x4,d.keywords.mat3x2,d.keywords.mat3x3,d.keywords.mat3x4,d.keywords.mat4x2,d.keywords.mat4x3,d.keywords.mat4x4,d.keywords.atomic,d.keywords.bitcast,...d.any_texture_type];a.attribute_name=[d.tokens.ident,d.keywords.block,d.keywords.diagnostic];a.assignment_operators=[d.tokens.equal,d.tokens.plus_equal,d.tokens.minus_equal,d.tokens.times_equal,d.tokens.division_equal,d.tokens.modulo_equal,d.tokens.and_equal,d.tokens.or_equal,d.tokens.xor_equal,d.tokens.shift_right_equal,d.tokens.shift_left_equal];a.increment_operators=[d.tokens.plus_plus,d.tokens.minus_minus];var Ae=class{constructor(t,e,n){this.type=t,this.lexeme=e,this.line=n}toString(){return this.lexeme}isTemplateType(){return a.template_types.indexOf(this.type)!=-1}isArrayType(){return this.type==a.keywords.array}isArrayOrTemplateType(){return this.isArrayType()||this.isTemplateType()}},Ns=class{constructor(t){this._tokens=[],this._start=0,this._current=0,this._line=1,this._source=t??""}scanTokens(){for(;!this._isAtEnd();)if(this._start=this._current,!this.scanToken())throw`Invalid syntax at line ${this._line}`;return this._tokens.push(new Ae(a.eof,"",this._line)),this._tokens}scanToken(){let t=this._advance();if(t==` `)return this._line++,!0;if(this._isWhitespace(t))return!0;if(t=="/"){if(this._peekAhead()=="/"){for(;t!=` `;){if(this._isAtEnd())return!0;t=this._advance()}return this._line++,!0}else if(this._peekAhead()=="*"){this._advance();let o=1;for(;o>0;){if(this._isAtEnd())return!0;if(t=this._advance(),t==` `)this._line++;else if(t=="*"){if(this._peekAhead()=="/"&&(this._advance(),o--,o==0))return!0}else t=="/"&&this._peekAhead()=="*"&&(this._advance(),o++)}return!0}}let e=a.simpleTokens[t];if(e)return this._addToken(e),!0;let n=a.none,r=this._isAlpha(t),i=t==="_";if(this._isAlphaNumeric(t)){let o=this._peekAhead();for(;this._isAlphaNumeric(o);)t+=this._advance(),o=this._peekAhead()}if(r){let o=a.keywords[t];if(o)return this._addToken(o),!0}if(r||i)return this._addToken(a.tokens.ident),!0;for(;;){let o=this._findType(t),c=this._peekAhead();if(t==">"&&(c==">"||c=="=")){let h=!1,f=this._tokens.length-1;for(let m=0;m<5&&f>=0;++m,--f)if(this._tokens[f].type===a.tokens.less_than){f>0&&this._tokens[f-1].isArrayOrTemplateType()&&(h=!0);break}if(h)return this._addToken(o),!0}if(o===a.none){let h=t,f=0,m=2;for(let p=0;p=this._source.length}_isAlpha(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"}_isAlphaNumeric(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t=="_"||t>="0"&&t<="9"}_isWhitespace(t){return t==" "||t==" "||t=="\r"}_advance(t=0){let e=this._source[this._current];return t=t||0,t++,this._current+=t,e}_peekAhead(t=0){return t=t||0,this._current+t>=this._source.length?"\0":this._source[this._current+t]}_addToken(t){let e=this._source.substring(this._start,this._current);this._tokens.push(new Ae(t,e,this._line))}},Ps=class{constructor(){this._tokens=[],this._current=0,this._currentLine=0,this._context=new rs,this._deferArrayCountEval=[]}parse(t){this._initialize(t),this._deferArrayCountEval.length=0;let e=[];for(;!this._isAtEnd();){let n=this._global_decl_or_directive();if(!n)break;e.push(n)}if(this._deferArrayCountEval.length>0){for(let n of this._deferArrayCountEval){let r=n.arrayType,i=n.countNode;if(i instanceof Jt){let c=i.name,h=this._context.constants.get(c);if(h)try{let f=h.evaluate(this._context);r.count=f}catch{}}}this._deferArrayCountEval.length=0}return e}_initialize(t){if(t)if(typeof t=="string"){let e=new Ns(t);this._tokens=e.scanTokens()}else this._tokens=t;else this._tokens=[];this._current=0}_error(t,e){return{token:t,message:e,toString:function(){return`${e}`}}}_isAtEnd(){return this._current>=this._tokens.length||this._peek().type==a.eof}_match(t){if(t instanceof l)return this._check(t)?(this._advance(),!0):!1;for(let e=0,n=t.length;e'.");let r=this._paren_expression();return new vs(n,r)}let t=this._type_decl(),e=this._argument_expression_list();return new bs(t,e)}_argument_expression_list(){if(!this._match(a.tokens.paren_left))return null;let t=[];do{if(this._check(a.tokens.paren_right))break;let e=this._short_circuit_or_expression();t.push(e)}while(this._match(a.tokens.comma));return this._consume(a.tokens.paren_right,"Expected ')' for agument list"),t}_optional_paren_expression(){this._match(a.tokens.paren_left);let t=this._short_circuit_or_expression();return this._match(a.tokens.paren_right),new be([t])}_paren_expression(){this._consume(a.tokens.paren_left,"Expected '('.");let t=this._short_circuit_or_expression();return this._consume(a.tokens.paren_right,"Expected ')'."),new be([t])}_struct_decl(){if(!this._match(a.keywords.struct))return null;let t=this._currentLine,e=this._consume(a.tokens.ident,"Expected name for struct.").toString();this._consume(a.tokens.brace_left,"Expected '{' for struct body.");let n=[];for(;!this._check(a.tokens.brace_right);){let o=this._attribute(),c=this._consume(a.tokens.ident,"Expected variable name.").toString();this._consume(a.tokens.colon,"Expected ':' for struct member type.");let h=this._attribute(),f=this._type_decl();f!=null&&(f.attributes=h),this._check(a.tokens.brace_right)?this._match(a.tokens.comma):this._consume(a.tokens.comma,"Expected ',' for struct member."),n.push(new Ls(c,f,o))}this._consume(a.tokens.brace_right,"Expected '}' after struct body.");let r=this._currentLine,i=new it(e,n,t,r);return this._context.structs.set(e,i),i}_global_variable_decl(){let t=this._variable_decl();return t&&this._match(a.tokens.equal)&&(t.value=this._const_expression()),t}_override_variable_decl(){let t=this._override_decl();return t&&this._match(a.tokens.equal)&&(t.value=this._const_expression()),t}_global_const_decl(){if(!this._match(a.keywords.const))return null;let t=this._consume(a.tokens.ident,"Expected variable name"),e=null;if(this._match(a.tokens.colon)){let i=this._attribute();e=this._type_decl(),e!=null&&(e.attributes=i)}let n=null;if(this._match(a.tokens.equal)){let i=this._short_circuit_or_expression();if(i instanceof _t)n=i;else if(i instanceof ke&&i.initializer instanceof _t)n=i.initializer;else try{let o=i.evaluate(this._context);n=new ve(o)}catch{n=i}}let r=new me(t.toString(),e,"","",n);return this._context.constants.set(r.name,r),r}_global_let_decl(){if(!this._match(a.keywords.let))return null;let t=this._consume(a.tokens.ident,"Expected variable name"),e=null;if(this._match(a.tokens.colon)){let r=this._attribute();e=this._type_decl(),e!=null&&(e.attributes=r)}let n=null;return this._match(a.tokens.equal)&&(n=this._const_expression()),new Kt(t.toString(),e,"","",n)}_const_expression(){if(this._match(a.const_literal))return new ye(this._previous().toString());let t=this._type_decl();this._consume(a.tokens.paren_left,"Expected '('.");let e=[];for(;!this._check(a.tokens.paren_right)&&(e.push(this._const_expression()),!!this._check(a.tokens.comma));)this._advance();return this._consume(a.tokens.paren_right,"Expected ')'."),new _t(t,e)}_variable_decl(){if(!this._match(a.keywords.var))return null;let t="",e="";this._match(a.tokens.less_than)&&(t=this._consume(a.storage_class,"Expected storage_class.").toString(),this._match(a.tokens.comma)&&(e=this._consume(a.access_mode,"Expected access_mode.").toString()),this._consume(a.tokens.greater_than,"Expected '>'."));let n=this._consume(a.tokens.ident,"Expected variable name"),r=null;if(this._match(a.tokens.colon)){let i=this._attribute();r=this._type_decl(),r!=null&&(r.attributes=i)}return new ot(n.toString(),r,t,e,null)}_override_decl(){if(!this._match(a.keywords.override))return null;let t=this._consume(a.tokens.ident,"Expected variable name"),e=null;if(this._match(a.tokens.colon)){let n=this._attribute();e=this._type_decl(),e!=null&&(e.attributes=n)}return new de(t.toString(),e,null)}_diagnostic(){this._consume(a.tokens.paren_left,"Expected '('");let t=this._consume(a.tokens.ident,"Expected severity control name.");this._consume(a.tokens.comma,"Expected ','");let e=this._consume(a.tokens.ident,"Expected diagnostic rule name.");return this._consume(a.tokens.paren_right,"Expected ')'"),new gs(t.toString(),e.toString())}_enable_directive(){let t=this._consume(a.tokens.ident,"identity expected.");return new ps(t.toString())}_requires_directive(){let t=[this._consume(a.tokens.ident,"identity expected.").toString()];for(;this._match(a.tokens.comma);){let e=this._consume(a.tokens.ident,"identity expected.");t.push(e.toString())}return new _s(t)}_type_alias(){let t=this._consume(a.tokens.ident,"identity expected.");this._consume(a.tokens.equal,"Expected '=' for type alias.");let e=this._type_decl();if(e===null)throw this._error(this._peek(),"Expected Type for Alias.");this._context.aliases.has(e.name)&&(e=this._context.aliases.get(e.name).type);let n=new _e(t.toString(),e);return this._context.aliases.set(n.name,n),n}_type_decl(){if(this._check([a.tokens.ident,...a.texel_format,a.keywords.bool,a.keywords.f32,a.keywords.i32,a.keywords.u32])){let n=this._advance(),r=n.toString();return this._context.structs.has(r)?this._context.structs.get(r):this._context.aliases.has(r)?this._context.aliases.get(r).type:new at(n.toString())}let t=this._texture_sampler_types();if(t)return t;if(this._check(a.template_types)){let n=this._advance().toString(),r=null,i=null;return this._match(a.tokens.less_than)&&(r=this._type_decl(),i=null,this._match(a.tokens.comma)&&(i=this._consume(a.access_mode,"Expected access_mode for pointer").toString()),this._consume(a.tokens.greater_than,"Expected '>' for type.")),new ge(n,r,i)}if(this._match(a.keywords.ptr)){let n=this._previous().toString();this._consume(a.tokens.less_than,"Expected '<' for pointer.");let r=this._consume(a.storage_class,"Expected storage_class for pointer");this._consume(a.tokens.comma,"Expected ',' for pointer.");let i=this._type_decl(),o=null;return this._match(a.tokens.comma)&&(o=this._consume(a.access_mode,"Expected access_mode for pointer").toString()),this._consume(a.tokens.greater_than,"Expected '>' for pointer."),new ks(n,r.toString(),i,o)}let e=this._attribute();if(this._match(a.keywords.array)){let n=null,r=-1,i=this._previous(),o=null;if(this._match(a.tokens.less_than)){n=this._type_decl(),this._context.aliases.has(n.name)&&(n=this._context.aliases.get(n.name).type);let h="";if(this._match(a.tokens.comma)){o=this._shift_expression();try{h=o.evaluate(this._context).toString(),o=null}catch{h="1"}}this._consume(a.tokens.greater_than,"Expected '>' for array."),r=h?parseInt(h):0}let c=new xe(i.toString(),e,n,r);return o&&this._deferArrayCountEval.push({arrayType:c,countNode:o}),c}return null}_texture_sampler_types(){if(this._match(a.sampler_type))return new vt(this._previous().toString(),null,null);if(this._match(a.depth_texture_type))return new vt(this._previous().toString(),null,null);if(this._match(a.sampled_texture_type)||this._match(a.multisampled_texture_type)){let t=this._previous();this._consume(a.tokens.less_than,"Expected '<' for sampler type.");let e=this._type_decl();return this._consume(a.tokens.greater_than,"Expected '>' for sampler type."),new vt(t.toString(),e,null)}if(this._match(a.storage_texture_type)){let t=this._previous();this._consume(a.tokens.less_than,"Expected '<' for sampler type.");let e=this._consume(a.texel_format,"Invalid texel format.").toString();this._consume(a.tokens.comma,"Expected ',' after texel format.");let n=this._consume(a.access_mode,"Expected access mode for storage texture type.").toString();return this._consume(a.tokens.greater_than,"Expected '>' for sampler type."),new vt(t.toString(),e,n)}return null}_attribute(){let t=[];for(;this._match(a.tokens.attr);){let e=this._consume(a.attribute_name,"Expected attribute name"),n=new Is(e.toString(),null);if(this._match(a.tokens.paren_left)){if(n.value=this._consume(a.literal_or_ident,"Expected attribute value").toString(),this._check(a.tokens.comma)){this._advance();do{let r=this._consume(a.literal_or_ident,"Expected attribute value").toString();n.value instanceof Array||(n.value=[n.value]),n.value.push(r)}while(this._match(a.tokens.comma))}this._consume(a.tokens.paren_right,"Expected ')'")}t.push(n)}return t.length==0?null:t}},gt=class{constructor(t,e){this.name=t,this.attributes=e,this.size=0}get isArray(){return!1}get isStruct(){return!1}get isTemplate(){return!1}},Ee=class{constructor(t,e,n){this.name=t,this.type=e,this.attributes=n,this.offset=0,this.size=0}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray?this.type.format:this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}},Et=class extends gt{constructor(t,e){super(t,e),this.members=[],this.align=0,this.startLine=-1,this.endLine=-1,this.inUse=!1}get isStruct(){return!0}},Yt=class extends gt{constructor(t,e){super(t,e),this.count=0,this.stride=0}get isArray(){return!0}},Te=class extends gt{constructor(t,e,n,r){super(t,n),this.format=e,this.access=r}get isTemplate(){return!0}},pt;(function(s){s[s.Uniform=0]="Uniform",s[s.Storage=1]="Storage",s[s.Texture=2]="Texture",s[s.Sampler=3]="Sampler",s[s.StorageTexture=4]="StorageTexture"})(pt||(pt={}));var Tt=class{constructor(t,e,n,r,i,o,c){this.name=t,this.type=e,this.group=n,this.binding=r,this.attributes=i,this.resourceType=o,this.access=c}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get size(){return this.type.size}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray?this.type.format:this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}},Rs=class{constructor(t,e){this.name=t,this.type=e}},Ot=class{constructor(t,e){this.align=t,this.size=e}},zs=class{constructor(t,e,n,r){this.name=t,this.type=e,this.locationType=n,this.location=r,this.interpolation=null}},Oe=class{constructor(t,e,n,r){this.name=t,this.type=e,this.locationType=n,this.location=r}},Cs=class{constructor(t,e=null){this.stage=null,this.inputs=[],this.outputs=[],this.resources=[],this.startLine=-1,this.endLine=-1,this.inUse=!1,this.calls=new Set,this.name=t,this.stage=e}},Fs=class{constructor(){this.vertex=[],this.fragment=[],this.compute=[]}},Ds=class{constructor(t,e,n,r){this.name=t,this.type=e,this.attributes=n,this.id=r}},Us=class{constructor(t){this.resources=null,this.inUse=!1,this.info=null,this.node=t}},X=class{constructor(t){this.uniforms=[],this.storage=[],this.textures=[],this.samplers=[],this.aliases=[],this.overrides=[],this.structs=[],this.entry=new Fs,this.functions=[],this._types=new Map,this._functions=new Map,t&&this.update(t)}_isStorageTexture(t){return t.name=="texture_storage_1d"||t.name=="texture_storage_2d"||t.name=="texture_storage_2d_array"||t.name=="texture_storage_3d"}update(t){let n=new Ps().parse(t);for(let r of n)r instanceof Xt&&this._functions.set(r.name,new Us(r));for(let r of n)if(r instanceof it){let i=this._getTypeInfo(r,null);i instanceof Et&&this.structs.push(i)}for(let r of n){if(r instanceof _e){this.aliases.push(this._getAliasInfo(r));continue}if(r instanceof de){let i=r,o=this._getAttributeNum(i.attributes,"id",0),c=i.type!=null?this._getTypeInfo(i.type,i.attributes):null;this.overrides.push(new Ds(i.name,c,i.attributes,o));continue}if(this._isUniformVar(r)){let i=r,o=this._getAttributeNum(i.attributes,"group",0),c=this._getAttributeNum(i.attributes,"binding",0),h=this._getTypeInfo(i.type,i.attributes),f=new Tt(i.name,h,o,c,i.attributes,pt.Uniform,i.access);this.uniforms.push(f);continue}if(this._isStorageVar(r)){let i=r,o=this._getAttributeNum(i.attributes,"group",0),c=this._getAttributeNum(i.attributes,"binding",0),h=this._getTypeInfo(i.type,i.attributes),f=this._isStorageTexture(h),m=new Tt(i.name,h,o,c,i.attributes,f?pt.StorageTexture:pt.Storage,i.access);this.storage.push(m);continue}if(this._isTextureVar(r)){let i=r,o=this._getAttributeNum(i.attributes,"group",0),c=this._getAttributeNum(i.attributes,"binding",0),h=this._getTypeInfo(i.type,i.attributes),f=this._isStorageTexture(h),m=new Tt(i.name,h,o,c,i.attributes,f?pt.StorageTexture:pt.Texture,i.access);f?this.storage.push(m):this.textures.push(m);continue}if(this._isSamplerVar(r)){let i=r,o=this._getAttributeNum(i.attributes,"group",0),c=this._getAttributeNum(i.attributes,"binding",0),h=this._getTypeInfo(i.type,i.attributes),f=new Tt(i.name,h,o,c,i.attributes,pt.Sampler,i.access);this.samplers.push(f);continue}if(r instanceof Xt){let i=this._getAttribute(r,"vertex"),o=this._getAttribute(r,"fragment"),c=this._getAttribute(r,"compute"),h=i||o||c,f=new Cs(r.name,h?.name);f.startLine=r.startLine,f.endLine=r.endLine,this.functions.push(f),this._functions.get(r.name).info=f,h&&(this._functions.get(r.name).inUse=!0,f.inUse=!0,f.resources=this._findResources(r,!!h),f.inputs=this._getInputs(r.args),f.outputs=this._getOutputs(r.returnType),this.entry[h.name].push(f));continue}}for(let r of this._functions.values())r.info&&(r.info.inUse=r.inUse,this._addCalls(r.node,r.info.calls));for(let r of this.uniforms)this._markStructsInUse(r.type);for(let r of this.storage)this._markStructsInUse(r.type)}_markStructsInUse(t){if(t.isStruct){t.inUse=!0;for(let e of t.members)this._markStructsInUse(e.type)}else if(t.isArray)this._markStructsInUse(t.format);else if(t.isTemplate)this._markStructsInUse(t.format);else{let e=this._getAlias(t.name);e&&this._markStructsInUse(e)}}_addCalls(t,e){var n;for(let r of t.calls){let i=(n=this._functions.get(r.name))===null||n===void 0?void 0:n.info;i&&e.add(i)}}findResource(t,e){for(let n of this.uniforms)if(n.group==t&&n.binding==e)return n;for(let n of this.storage)if(n.group==t&&n.binding==e)return n;for(let n of this.textures)if(n.group==t&&n.binding==e)return n;for(let n of this.samplers)if(n.group==t&&n.binding==e)return n;return null}_findResource(t){for(let e of this.uniforms)if(e.name==t)return e;for(let e of this.storage)if(e.name==t)return e;for(let e of this.textures)if(e.name==t)return e;for(let e of this.samplers)if(e.name==t)return e;return null}_markStructsFromAST(t){let e=this._getTypeInfo(t,null);this._markStructsInUse(e)}_findResources(t,e){let n=[],r=this,i=[];return t.search(o=>{if(o instanceof Lt)i.push({});else if(o instanceof It)i.pop();else if(o instanceof ot){let c=o;e&&c.type!==null&&this._markStructsFromAST(c.type),i.length>0&&(i[i.length-1][c.name]=c)}else if(o instanceof _t){let c=o;e&&c.type!==null&&this._markStructsFromAST(c.type)}else if(o instanceof Kt){let c=o;e&&c.type!==null&&this._markStructsFromAST(c.type),i.length>0&&(i[i.length-1][c.name]=c)}else if(o instanceof Jt){let c=o;if(i.length>0&&i[i.length-1][c.name])return;let h=r._findResource(c.name);h&&n.push(h)}else if(o instanceof we){let c=o,h=r._functions.get(c.name);h&&(e&&(h.inUse=!0),t.calls.add(h.node),h.resources===null&&(h.resources=r._findResources(h.node,e)),n.push(...h.resources))}else if(o instanceof pe){let c=o,h=r._functions.get(c.name);h&&(e&&(h.inUse=!0),t.calls.add(h.node),h.resources===null&&(h.resources=r._findResources(h.node,e)),n.push(...h.resources))}}),[...new Map(n.map(o=>[o.name,o])).values()]}getBindGroups(){let t=[];function e(n,r){n>=t.length&&(t.length=n+1),t[n]===void 0&&(t[n]=[]),r>=t[n].length&&(t[n].length=r+1)}for(let n of this.uniforms){e(n.group,n.binding);let r=t[n.group];r[n.binding]=n}for(let n of this.storage){e(n.group,n.binding);let r=t[n.group];r[n.binding]=n}for(let n of this.textures){e(n.group,n.binding);let r=t[n.group];r[n.binding]=n}for(let n of this.samplers){e(n.group,n.binding);let r=t[n.group];r[n.binding]=n}return t}_getOutputs(t,e=void 0){if(e===void 0&&(e=[]),t instanceof it)this._getStructOutputs(t,e);else{let n=this._getOutputInfo(t);n!==null&&e.push(n)}return e}_getStructOutputs(t,e){for(let n of t.members)if(n.type instanceof it)this._getStructOutputs(n.type,e);else{let r=this._getAttribute(n,"location")||this._getAttribute(n,"builtin");if(r!==null){let i=this._getTypeInfo(n.type,n.type.attributes),o=this._parseInt(r.value),c=new Oe(n.name,i,r.name,o);e.push(c)}}}_getOutputInfo(t){let e=this._getAttribute(t,"location")||this._getAttribute(t,"builtin");if(e!==null){let n=this._getTypeInfo(t,t.attributes),r=this._parseInt(e.value);return new Oe("",n,e.name,r)}return null}_getInputs(t,e=void 0){e===void 0&&(e=[]);for(let n of t)if(n.type instanceof it)this._getStructInputs(n.type,e);else{let r=this._getInputInfo(n);r!==null&&e.push(r)}return e}_getStructInputs(t,e){for(let n of t.members)if(n.type instanceof it)this._getStructInputs(n.type,e);else{let r=this._getInputInfo(n);r!==null&&e.push(r)}}_getInputInfo(t){let e=this._getAttribute(t,"location")||this._getAttribute(t,"builtin");if(e!==null){let n=this._getAttribute(t,"interpolation"),r=this._getTypeInfo(t.type,t.attributes),i=this._parseInt(e.value),o=new zs(t.name,r,e.name,i);return n!==null&&(o.interpolation=this._parseString(n.value)),o}return null}_parseString(t){return t instanceof Array&&(t=t[0]),t}_parseInt(t){t instanceof Array&&(t=t[0]);let e=parseInt(t);return isNaN(e)?t:e}_getAlias(t){for(let e of this.aliases)if(e.name==t)return e.type;return null}_getAliasInfo(t){return new Rs(t.name,this._getTypeInfo(t.type,null))}_getTypeInfo(t,e){if(this._types.has(t))return this._types.get(t);if(t instanceof xe){let r=t,i=this._getTypeInfo(r.format,r.attributes),o=new Yt(r.name,e);return o.format=i,o.count=r.count,this._types.set(t,o),this._updateTypeInfo(o),o}if(t instanceof it){let r=t,i=new Et(r.name,e);i.startLine=r.startLine,i.endLine=r.endLine;for(let o of r.members){let c=this._getTypeInfo(o.type,o.attributes);i.members.push(new Ee(o.name,c,o.attributes))}return this._types.set(t,i),this._updateTypeInfo(i),i}if(t instanceof vt){let r=t,i=r.format instanceof at,o=r.format?i?this._getTypeInfo(r.format,null):new gt(r.format,null):null,c=new Te(r.name,o,e,r.access);return this._types.set(t,c),this._updateTypeInfo(c),c}if(t instanceof ge){let r=t,i=r.format?this._getTypeInfo(r.format,null):null,o=new Te(r.name,i,e,r.access);return this._types.set(t,o),this._updateTypeInfo(o),o}let n=new gt(t.name,e);return this._types.set(t,n),this._updateTypeInfo(n),n}_updateTypeInfo(t){var e,n;let r=this._getTypeSize(t);if(t.size=(e=r?.size)!==null&&e!==void 0?e:0,t instanceof Yt){let i=this._getTypeSize(t.format);t.stride=(n=i?.size)!==null&&n!==void 0?n:0,this._updateTypeInfo(t.format)}t instanceof Et&&this._updateStructInfo(t)}_updateStructInfo(t){var e;let n=0,r=0,i=0,o=0;for(let c=0,h=t.members.length;cs.name);X._samplerTypes=a.sampler_type.map(s=>s.name);function Qt(s){let t={attributes:[],bindings:[]},e;try{e=Qr(s)}catch(i){return Tn.log.error(i.message)(),t}for(let i of e.uniforms){let o=[];for(let c of i.type?.members||[])o.push({name:c.name,type:En(c.type)});t.bindings.push({type:"uniform",name:i.name,location:i.binding,group:i.group,members:o})}let n=e.entry.vertex[0],r=n?.inputs.length||0;for(let i=0;i`:s.name}function Qr(s){try{return new X(s)}catch(t){if(t instanceof Error)throw t;let e="WGSL parse error";throw typeof t=="object"&&t?.message&&(e+=`: ${t.message} `),typeof t=="object"&&t?.token&&(e+=t.token.line||""),new Error(e,{cause:t})}}var Uo=1/Math.PI*180,qo=1/180*Math.PI,ti={EPSILON:1e-12,debug:!1,precision:4,printTypes:!1,printDegrees:!1,printRowMajor:!0,_cartographicRadians:!1};globalThis.mathgl=globalThis.mathgl||{config:{...ti}};var B=globalThis.mathgl.config;function On(s,{precision:t=B.precision}={}){return s=ei(s),`${parseFloat(s.toPrecision(t))}`}function Pt(s){return Array.isArray(s)||ArrayBuffer.isView(s)&&!(s instanceof DataView)}function qs(s,t,e){let n=B.EPSILON;e&&(B.EPSILON=e);try{if(s===t)return!0;if(Pt(s)&&Pt(t)){if(s.length!==t.length)return!1;for(let r=0;r0?", ":"")+On(this[n],t);return`${t.printTypes?this.constructor.name:""}[${e}]`}equals(t){if(!t||this.length!==t.length)return!1;for(let e=0;e=0&&t=0&&tMath.PI*2)throw Error("expected radians")}function pi(s,t,e,n,r,i){let o=2*i/(e-t),c=2*i/(r-n),h=(e+t)/(e-t),f=(r+n)/(r-n),m=-1,p=-1,_=-2*i;return s[0]=o,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=c,s[6]=0,s[7]=0,s[8]=h,s[9]=f,s[10]=m,s[11]=p,s[12]=0,s[13]=0,s[14]=_,s[15]=0,s}var ht=C(z(),1),Ct=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(t){this.id=t.id||(0,ht.uid)("geometry"),this.topology=t.topology,this.indices=t.indices||null,this.attributes=t.attributes,this.vertexCount=t.vertexCount,this.bufferLayout=t.bufferLayout||[],this.indices&&(0,ht.assert)(this.indices.usage===ht.Buffer.INDEX)}destroy(){this.indices?.destroy();for(let t of Object.values(this.attributes))t.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices}_calculateVertexCount(t){return t.byteLength/12}};function rr(s,t){if(t instanceof Ct)return t;let e=_i(s,t),{attributes:n,bufferLayout:r}=gi(s,t);return new Ct({topology:t.topology||"triangle-list",bufferLayout:r,vertexCount:t.vertexCount,indices:e,attributes:n})}function _i(s,t){if(!t.indices)return;let e=t.indices.value;return s.createBuffer({usage:ht.Buffer.INDEX,data:e})}function gi(s,t){let e=[],n={};for(let[i,o]of Object.entries(t.attributes)){let c=i;switch(i){case"POSITION":c="positions";break;case"NORMAL":c="normals";break;case"TEXCOORD_0":c="texCoords";break;case"COLOR_0":c="colors";break}n[c]=s.createBuffer({data:o.value,id:`${i}-buffer`});let{value:h,size:f,normalized:m}=o;e.push({name:c,format:(0,ht.getVertexFormatFromAttribute)(h,f,m)})}let r=t._calculateVertexCount(t.attributes,t.indices);return{attributes:n,bufferLayout:e,vertexCount:r}}var te=C(z(),1);var xt=class{modules;moduleUniforms;moduleBindings;moduleUniformsChanged;constructor(t){let e=kt(Object.values(t).filter(n=>n.dependencies));for(let n of e)t[n.name]=n;te.log.log(1,"Creating ShaderInputs with modules",Object.keys(t))(),this.modules=t,this.moduleUniforms={},this.moduleBindings={};for(let[n,r]of Object.entries(t)){let i=n;this.moduleUniforms[i]=r.defaultUniforms||{},this.moduleBindings[i]={}}}destroy(){}setProps(t){for(let e of Object.keys(t)){let n=e,r=t[n],i=this.modules[n];if(!i){te.log.warn(`Module ${e} not found`)();continue}let o=this.moduleUniforms[n],c=this.moduleBindings[n],h=i.getUniforms?.(r,o)||r,{uniforms:f,bindings:m}=(0,te.splitUniformsAndBindings)(h);this.moduleUniforms[n]={...o,...f},this.moduleBindings[n]={...c,...m}}}getModules(){return Object.values(this.modules)}getUniformValues(){return this.moduleUniforms}getBindings(){let t={};for(let e of Object.values(this.moduleBindings))Object.assign(t,e);return t}getDebugTable(){let t={};for(let[e,n]of Object.entries(this.moduleUniforms))for(let[r,i]of Object.entries(n))t[`${e}.${r}`]={type:this.modules[e].uniformTypes?.[r],value:String(i)};return t}};var Ft=C(z(),1);var Ys=class{device;_hashCounter=0;_hashes={};_renderPipelineCache={};_computePipelineCache={};static getDefaultPipelineFactory(t){return t._lumaData.defaultPipelineFactory=t._lumaData.defaultPipelineFactory||new Ys(t),t._lumaData.defaultPipelineFactory}constructor(t){this.device=t}createRenderPipeline(t){let e={...Ft.RenderPipeline.defaultProps,...t},n=this._hashRenderPipeline(e);if(!this._renderPipelineCache[n]){let r=this.device.createRenderPipeline({...e,id:e.id?`${e.id}-cached`:void 0});r.hash=n,this._renderPipelineCache[n]={pipeline:r,useCount:0}}return this._renderPipelineCache[n].useCount++,this._renderPipelineCache[n].pipeline}createComputePipeline(t){let e={...Ft.ComputePipeline.defaultProps,...t},n=this._hashComputePipeline(e);if(!this._computePipelineCache[n]){let r=this.device.createComputePipeline({...e,id:e.id?`${e.id}-cached`:void 0});r.hash=n,this._computePipelineCache[n]={pipeline:r,useCount:0}}return this._computePipelineCache[n].useCount++,this._computePipelineCache[n].pipeline}release(t){let e=t.hash,n=t instanceof Ft.ComputePipeline?this._computePipelineCache:this._renderPipelineCache;n[e].useCount--,n[e].useCount===0&&(n[e].pipeline.destroy(),delete n[e])}_hashComputePipeline(t){return`${this._getHash(t.shader.source)}`}_hashRenderPipeline(t){let e=this._getHash(t.vs.source),n=t.fs?this._getHash(t.fs.source):0,r="-",i=this._getHash(JSON.stringify(t.bufferLayout));switch(this.device.type){case"webgl":return`${e}/${n}V${r}BL${i}`;default:let o=this._getHash(JSON.stringify(t.parameters));return`${e}/${n}V${r}T${t.topology}P${o}BL${i}`}}_getHash(t){return this._hashes[t]===void 0&&(this._hashes[t]=this._hashCounter++),this._hashes[t]}},lt=Ys;st(lt,"defaultProps",{...Ft.RenderPipeline.defaultProps});var ir=C(z(),1);var Xs=class{device;_cache={};static getDefaultShaderFactory(t){return t._lumaData.defaultShaderFactory||=new Xs(t),t._lumaData.defaultShaderFactory}constructor(t){this.device=t}createShader(t){let e=this._hashShader(t),n=this._cache[e];if(!n){let r=this.device.createShader({...t,id:t.id?`${t.id}-cached`:void 0});this._cache[e]=n={shader:r,useCount:0}}return n.useCount++,n.shader}release(t){let e=this._hashShader(t),n=this._cache[e];n&&(n.useCount--,n.useCount===0&&(delete this._cache[e],n.shader.destroy()))}_hashShader(t){return`${t.stage}:${t.source}`}},ut=Xs;st(ut,"defaultProps",{...ir.Shader.defaultProps});function or(s,t){let e={},n="Values";if(s.attributes.length===0&&!s.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(let r of s.attributes)if(r){let i=`${r.location} ${r.name}: ${r.type}`;e[`in ${i}`]={[n]:r.stepMode||"vertex"}}for(let r of s.varyings||[]){let i=`${r.location} ${r.name}`;e[`out ${i}`]={[n]:JSON.stringify(r.accessor)}}return e}var q=null,Ks=null;function ar(s,{id:t,minimap:e,opaque:n,top:r="0",left:i="0",rgbaScale:o=1}){q||(q=document.createElement("canvas"),q.id=t,q.title=t,q.style.zIndex="100",q.style.position="absolute",q.style.top=r,q.style.left=i,q.style.border="blue 1px solid",q.style.transform="scaleY(-1)",document.body.appendChild(q),Ks=q.getContext("2d")),(q.width!==s.width||q.height!==s.height)&&(q.width=s.width/2,q.height=s.height/2,q.style.width="400px",q.style.height="400px");let c=s.device.readPixelsToArrayWebGL(s),h=Ks.createImageData(s.width,s.height),f=0;for(let m=0;m[c.name,c])||[]);this.setShaderInputs(e.shaderInputs||new xt(n));let r=yi(t),i=(this.props.modules?.length>0?this.props.modules:this.shaderInputs?.getModules())||[];if(this.device.type==="webgpu"&&this.props.source){this.props.shaderLayout||=Qt(this.props.source);let{source:c,getUniforms:h}=this.props.shaderAssembler.assembleShader({platformInfo:r,...this.props,modules:i});this.source=c,this._getModuleUniforms=h}else{let{vs:c,fs:h,getUniforms:f}=this.props.shaderAssembler.assembleShaderPair({platformInfo:r,...this.props,modules:i});this.vs=c,this.fs=h,this._getModuleUniforms=f}this.vertexCount=this.props.vertexCount,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,e.geometry&&this.setGeometry(e.geometry),this.pipelineFactory=e.pipelineFactory||lt.getDefaultPipelineFactory(this.device),this.shaderFactory=e.shaderFactory||ut.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=t.createVertexArray({renderPipeline:this.pipeline}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in e&&(this.isInstanced=e.isInstanced),e.instanceCount&&this.setInstanceCount(e.instanceCount),e.vertexCount&&this.setVertexCount(e.vertexCount),e.indexBuffer&&this.setIndexBuffer(e.indexBuffer),e.attributes&&this.setAttributes(e.attributes),e.constantAttributes&&this.setConstantAttributes(e.constantAttributes),e.bindings&&this.setBindings(e.bindings),e.uniforms&&this.setUniforms(e.uniforms),e.moduleSettings&&this.updateModuleSettings(e.moduleSettings),e.transformFeedback&&(this.transformFeedback=e.transformFeedback),Object.seal(this)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.shaderFactory.release(this.pipeline.fs),this._uniformStore.destroy(),this._gpuGeometry?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");let t=this._needsRedraw;return this._needsRedraw=!1,t}setNeedsRedraw(t){this._needsRedraw||=t}predraw(){this.updateShaderInputs(),this.pipeline=this._updatePipeline()}draw(t){this.predraw();let e;try{this._logDrawCallStart(),this.pipeline=this._updatePipeline(),this.pipeline.setBindings(this.bindings,{disableWarnings:this.props.disableWarnings}),(0,D.isObjectEmpty)(this.uniforms)||this.pipeline.setUniformsWebGL(this.uniforms);let{indexBuffer:n}=this.vertexArray,r=n?n.byteLength/(n.indexType==="uint32"?4:2):void 0;e=this.pipeline.draw({renderPass:t,vertexArray:this.vertexArray,isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.instanceCount,indexCount:r,transformFeedback:this.transformFeedback||void 0,parameters:this.parameters,topology:this.topology})}finally{this._logDrawCallEnd()}return this._logFramebuffer(t),e?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):this._needsRedraw="waiting for resource initialization",e}setGeometry(t){this._gpuGeometry?.destroy();let e=t&&rr(this.device,t);e&&(this.setTopology(e.topology||"triangle-list"),this.bufferLayout=cr(e.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(e)),this._gpuGeometry=e}setTopology(t){t!==this.topology&&(this.topology=t,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(t){this.bufferLayout=this._gpuGeometry?cr(t,this._gpuGeometry.bufferLayout):t,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({renderPipeline:this.pipeline}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry)}setParameters(t){(0,D.deepEqual)(t,this.parameters,2)||(this.parameters=t,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(t){this.instanceCount=t,this.isInstanced===void 0&&t>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(t){this.vertexCount=t,this.setNeedsRedraw("vertexCount")}setShaderInputs(t){this.shaderInputs=t,this._uniformStore=new De.UniformStore(this.shaderInputs.modules);for(let e of Object.keys(this.shaderInputs.modules)){let n=this._uniformStore.getManagedUniformBuffer(this.device,e);this.bindings[`${e}Uniforms`]=n}this.setNeedsRedraw("shaderInputs")}updateShaderInputs(){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues()),this.setBindings(this.shaderInputs.getBindings()),this.setNeedsRedraw("shaderInputs")}setBindings(t){Object.assign(this.bindings,t),this.setNeedsRedraw("bindings")}setTransformFeedback(t){this.transformFeedback=t,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(t){this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(t,e){t.indices&&D.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)();for(let[n,r]of Object.entries(t)){let i=this.bufferLayout.find(h=>hr(h).includes(n));if(!i){D.log.warn(`Model(${this.id}): Missing layout for buffer "${n}".`)();continue}let o=hr(i),c=!1;for(let h of o){let f=this._attributeInfos[h];f&&(this.vertexArray.setBuffer(f.location,r),c=!0)}!c&&!(e?.disableWarnings??this.props.disableWarnings)&&D.log.warn(`Model(${this.id}): Ignoring buffer "${r.id}" for unknown attribute "${n}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(t,e){for(let[n,r]of Object.entries(t)){let i=this._attributeInfos[n];i?this.vertexArray.setConstantWebGL(i.location,r):(e?.disableWarnings??this.props.disableWarnings)||D.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}setUniforms(t){(0,D.isObjectEmpty)(t)||(this.pipeline.setUniformsWebGL(t),Object.assign(this.uniforms,t)),this.setNeedsRedraw("uniforms")}updateModuleSettings(t){let{bindings:e,uniforms:n}=(0,D.splitUniformsAndBindings)(this._getModuleUniforms(t));Object.assign(this.bindings,e),Object.assign(this.uniforms,n),this.setNeedsRedraw("moduleSettings")}_getBindingsUpdateTimestamp(){let t=0;for(let e of Object.values(this.bindings))e instanceof ft.TextureView?t=Math.max(t,e.texture.updateTimestamp):e instanceof ft.Buffer||e instanceof ft.Texture?t=Math.max(t,e.updateTimestamp):e instanceof ft.Sampler||(t=Math.max(t,e.buffer.updateTimestamp));return t}_setGeometryAttributes(t){let e={...t.attributes};for(let[n]of Object.entries(e))!this.pipeline.shaderLayout.attributes.find(r=>r.name===n)&&n!=="positions"&&delete e[n];this.vertexCount=t.vertexCount,this.setIndexBuffer(t.indices||null),this.setAttributes(t.attributes,{disableWarnings:!0}),this.setAttributes(e,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(t){this._pipelineNeedsUpdate||=t,this.setNeedsRedraw(t)}_updatePipeline(){if(this._pipelineNeedsUpdate){let t=null,e=null;this.pipeline&&(D.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),t=this.pipeline.vs,e=this.pipeline.fs),this._pipelineNeedsUpdate=!1;let n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debug:this.props.debugShaders}),r=null;this.source?r=n:this.fs&&(r=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debug:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bufferLayout:this.bufferLayout,topology:this.topology,parameters:this.parameters,vs:n,fs:r}),this._attributeInfos=(0,Ue.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),t&&this.shaderFactory.release(t),e&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let t=D.log.level>3?0:xi;D.log.level<2||Date.now()-this._lastLogTime>> DRAWING MODEL ${this.id}`,{collapsed:D.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let t=or(this.pipeline.shaderLayout,this.id);D.log.table(Dt,t)();let e=this.shaderInputs.getDebugTable();for(let[r,i]of Object.entries(this.uniforms))e[r]={value:i};D.log.table(Dt,e)();let n=this._getAttributeDebugTable();D.log.table(Dt,this._attributeInfos)(),D.log.table(Dt,n)(),D.log.groupEnd(Dt)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(t){let e=D.log.get("framebuffer");if(this._drawCount++,!e||this._drawCount++>3&&this._drawCount%60)return;let n=t.props.framebuffer;n&&ar(n,{id:n.id,minimap:!0})}_getAttributeDebugTable(){let t={};for(let[e,n]of Object.entries(this._attributeInfos))t[n.location]={name:e,type:n.shaderType,values:this._getBufferOrConstantValues(this.vertexArray.attributes[n.location],n.bufferDataType)};if(this.vertexArray.indexBuffer){let{indexBuffer:e}=this.vertexArray,n=e.indexType==="uint32"?new Uint32Array(e.debugData):new Uint16Array(e.debugData);t.indices={name:"indices",type:e.indexType,values:n.toString()}}return t}_getBufferOrConstantValues(t,e){let n=(0,Ue.getTypedArrayFromDataType)(e);return(t instanceof ft.Buffer?new n(t.debugData):t).toString()}},K=Zs;st(K,"defaultProps",{...De.RenderPipeline.defaultProps,source:null,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],moduleSettings:void 0,geometry:null,indexBuffer:null,attributes:{},constantAttributes:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:mt.getDefaultShaderAssembler(),debugShaders:void 0,disableWarnings:void 0});function cr(s,t){let e=[...s];for(let n of t){let r=e.findIndex(i=>i.name===n.name);r<0?e.push(n):e[r]=n}return e}function yi(s){return{type:s.type,shaderLanguage:s.info.shadingLanguage,shaderLanguageVersion:s.info.shadingLanguageVersion,gpu:s.info.gpu,features:s.features}}function hr(s){return s.attributes?s.attributes?.map(t=>t.attribute):[s.name]}var qe=C(z(),1);var Ut=class{device;model;transformFeedback;static isSupported(t){return t?.info?.type==="webgl"}constructor(t,e=K.defaultProps){(0,qe.assert)(Ut.isSupported(t),"BufferTransform not yet implemented on WebGPU"),this.device=t,this.model=new K(this.device,{id:e.id||"buffer-transform-model",fs:e.fs||Ht(),topology:e.topology||"point-list",...e}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:e.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback),Object.seal(this)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(t){let e=this.device.beginRenderPass(t);this.model.draw(e),e.end()}update(...t){console.warn("TextureTransform#update() not implemented")}getBuffer(t){return this.transformFeedback.getBuffer(t)}readAsync(t){let e=this.getBuffer(t);if(e instanceof qe.Buffer)return e.readAsync();let{buffer:n,byteOffset:r=0,byteLength:i=n.byteLength}=e;return n.readAsync(r,i)}};var wi="transform_output",$e=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(t,e){this.device=t,this.sampler=t.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new K(this.device,{id:e.id||"texture-transform-model",fs:e.fs||Ht({input:e.targetTextureVarying,inputChannels:e.targetTextureChannels,output:wi}),vertexCount:e.vertexCount,...e}),this._initialize(e),Object.seal(this)}destroy(){}delete(){this.destroy()}run(t){let{framebuffer:e}=this.bindings[this.currentIndex],n=this.device.beginRenderPass({framebuffer:e,...t});this.model.draw(n),n.end()}update(...t){console.warn("TextureTransform#update() not implemented")}getData({packed:t=!1}={}){throw new Error("getData() not implemented")}getTargetTexture(){let{targetTexture:t}=this.bindings[this.currentIndex];return t}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(t){this._updateBindings(t)}_updateBindings(t){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],t)}_updateBinding(t,{sourceBuffers:e,sourceTextures:n,targetTexture:r}){if(t||(t={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(t.sourceTextures,n),Object.assign(t.sourceBuffers,e),r){t.targetTexture=r;let{width:i,height:o}=r;t.framebuffer&&t.framebuffer.destroy(),t.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:i,height:o,colorAttachments:[r]}),t.framebuffer.resize({width:i,height:o})}return t}_setSourceTextureParameters(){let t=this.currentIndex,{sourceTextures:e}=this.bindings[t];for(let n in e)e[n].sampler=this.sampler}};var oc=C(z(),1);var qt=C(z(),1),j=class{id;topology;vertexCount;indices;attributes;userData={};constructor(t){let{attributes:e={},indices:n=null,vertexCount:r=null}=t;this.id=t.id||(0,qt.uid)("geometry"),this.topology=t.topology,n&&(this.indices=ArrayBuffer.isView(n)?{value:n,size:1}:n),this.attributes={};for(let[i,o]of Object.entries(e)){let c=ArrayBuffer.isView(o)?{value:o}:o;(0,qt.assert)(ArrayBuffer.isView(c.value),`${this._print(i)}: must be typed array or object with value as typed array`),(i==="POSITION"||i==="positions")&&!c.size&&(c.size=3),i==="indices"?((0,qt.assert)(!this.indices),this.indices=c):this.attributes[i]=c}this.indices&&this.indices.isIndexed!==void 0&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this.vertexCount=r||this._calculateVertexCount(this.attributes,this.indices)}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}_print(t){return`Geometry ${this.id} attribute ${t}`}_setAttributes(t,e){return this}_calculateVertexCount(t,e){if(e)return e.value.length;let n=1/0;for(let r of Object.values(t)){let{value:i,size:o,constant:c}=r;!c&&i&&o>=1&&(n=Math.min(n,i.length/o))}return(0,qt.assert)(Number.isFinite(n)),n}};var ki=`#version 300 es in vec2 aClipSpacePosition; in vec2 aTexCoord; in vec2 aCoordinate; out vec2 position; out vec2 coordinate; out vec2 uv; void main(void) { gl_Position = vec4(aClipSpacePosition, 0., 1.); position = aClipSpacePosition; coordinate = aCoordinate; uv = aTexCoord; } `,lr=[-1,-1,1,-1,-1,1,1,1],Be=class extends K{constructor(t,e){let n=lr.map(r=>r===-1?0:r);super(t,{...e,vs:ki,vertexCount:4,geometry:new j({topology:"triangle-strip",vertexCount:4,attributes:{aClipSpacePosition:{size:2,value:new Float32Array(lr)},aTexCoord:{size:2,value:new Float32Array(n)},aCoordinate:{size:2,value:new Float32Array(n)}}})})}};var bt=C(z(),1);var dt=class{id;matrix=new et;display=!0;position=new G;rotation=new G;scale=new G(1,1,1);userData={};props={};constructor(t={}){let{id:e}=t;this.id=e||(0,bt.uid)(this.constructor.name),this._setScenegraphNodeProps(t)}getBounds(){return null}destroy(){}delete(){this.destroy()}setProps(t){return this._setScenegraphNodeProps(t),this}toString(){return`{type: ScenegraphNode, id: ${this.id})}`}setPosition(t){return(0,bt.assert)(t.length===3,"setPosition requires vector argument"),this.position=t,this}setRotation(t){return(0,bt.assert)(t.length===3,"setRotation requires vector argument"),this.rotation=t,this}setScale(t){return(0,bt.assert)(t.length===3,"setScale requires vector argument"),this.scale=t,this}setMatrix(t,e=!0){e?this.matrix.copy(t):this.matrix=t}setMatrixComponents(t){let{position:e,rotation:n,scale:r,update:i=!0}=t;return e&&this.setPosition(e),n&&this.setRotation(n),r&&this.setScale(r),i&&this.updateMatrix(),this}updateMatrix(){let t=this.position,e=this.rotation,n=this.scale;return this.matrix.identity(),this.matrix.translate(t),this.matrix.rotateXYZ(e),this.matrix.scale(n),this}update(t={}){let{position:e,rotation:n,scale:r}=t;return e&&this.setPosition(e),n&&this.setRotation(n),r&&this.setScale(r),this.updateMatrix(),this}getCoordinateUniforms(t,e){(0,bt.assert)(t),e=e||this.matrix;let n=new et(t).multiplyRight(e),r=n.invert(),i=r.transpose();return{viewMatrix:t,modelMatrix:e,objectMatrix:e,worldMatrix:n,worldInverseMatrix:r,worldInverseTransposeMatrix:i}}_setScenegraphNodeProps(t){"display"in t&&(this.display=t.display),"position"in t&&this.setPosition(t.position),"rotation"in t&&this.setRotation(t.rotation),"scale"in t&&this.setScale(t.scale),"matrix"in t&&this.setMatrix(t.matrix),Object.assign(this.props,t)}};var ur=C(z(),1);var $t=class extends dt{children;constructor(t={}){t=Array.isArray(t)?{children:t}:t;let{children:e=[]}=t;ur.log.assert(e.every(n=>n instanceof dt),"every child must an instance of ScenegraphNode"),super(t),this.children=e}getBounds(){let t=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]];return this.traverse((e,{worldMatrix:n})=>{let r=e.getBounds();if(!r)return;let[i,o]=r,c=new G(i).add(o).divide([2,2,2]);n.transformAsPoint(c,c);let h=new G(o).subtract(i).divide([2,2,2]);n.transformAsVector(h,h);for(let f=0;f<8;f++){let m=new G(f&1?-1:1,f&2?-1:1,f&4?-1:1).multiply(h).add(c);for(let p=0;p<3;p++)t[0][p]=Math.min(t[0][p],m[p]),t[1][p]=Math.max(t[1][p],m[p])}}),Number.isFinite(t[0][0])?t:null}destroy(){this.children.forEach(t=>t.destroy()),this.removeAll(),super.destroy()}add(...t){for(let e of t)Array.isArray(e)?this.add(...e):this.children.push(e);return this}remove(t){let e=this.children,n=e.indexOf(t);return n>-1&&e.splice(n,1),this}removeAll(){return this.children=[],this}traverse(t,{worldMatrix:e=new et}={}){let n=new et(e).multiplyRight(this.matrix);for(let r of this.children)r instanceof $t?r.traverse(t,{worldMatrix:n}):t(r,{worldMatrix:n})}};var Ve=class extends dt{model;bounds=null;managedResources;constructor(t){super(t),this.model=t.model,this.managedResources=t.managedResources||[],this.bounds=t.bounds||null,this.setProps(t)}getBounds(){return this.bounds}destroy(){this.model&&(this.model.destroy(),this.model=null),this.managedResources.forEach(t=>t.destroy()),this.managedResources=[]}draw(t){return this.model.draw(t)}};var dr=C(z(),1);var fr=C(z(),1);var vi={x:[2,0,1],y:[0,1,2],z:[1,2,0]},yt=class extends j{constructor(t={}){let{id:e=(0,fr.uid)("truncated-code-geometry")}=t,{indices:n,attributes:r}=bi(t);super({...t,id:e,topology:"triangle-list",indices:n,attributes:{POSITION:{size:3,value:r.POSITION},NORMAL:{size:3,value:r.NORMAL},TEXCOORD_0:{size:2,value:r.TEXCOORD_0},...t.attributes}})}};function bi(s={}){let{bottomRadius:t=0,topRadius:e=0,height:n=1,nradial:r=10,nvertical:i=10,verticalAxis:o="y",topCap:c=!1,bottomCap:h=!1}=s,f=(c?2:0)+(h?2:0),m=(r+1)*(i+1+f),p=Math.atan2(t-e,n),_=Math.sin,y=Math.cos,S=Math.PI,g=y(p),w=_(p),M=c?-2:0,b=i+(h?2:0),x=r+1,k=new Uint16Array(r*(i+f)*6),v=vi[o],A=new Float32Array(m*3),T=new Float32Array(m*3),R=new Float32Array(m*2),O=0,N=0;for(let E=M;E<=b;E++){let I=E/i,P=n*I,L;E<0?(P=0,I=1,L=t):E>i?(P=n,I=1,L=e):L=t+(e-t)*(E/i),(E===-2||E===i+2)&&(L=0,I=0),P-=n/2;for(let $=0;$i?0:rt*g,T[O+v[1]]=E<0?-1:E>i?1:w,T[O+v[2]]=E<0||E>i?0:J*g,R[N+0]=$/r,R[N+1]=I,N+=2,O+=3}}for(let E=0;E{let m={};return(p,_)=>{p*=3,_*=3;let y=p<_?p:_,S=p>_?p:_,g=`${y}|${S}`;if(g in m)return m[g];let w=r[p],M=r[p+1],b=r[p+2],x=r[_],k=r[_+1],v=r[_+2],A=(w+x)/2,T=(M+k)/2,R=(b+v)/2,O=Math.sqrt(A*A+T*T+R*R);return A/=O,T/=O,R/=O,r.push(A,T,R),m[g]=r.length/3-1}})();for(let m=0;m=0;m-=3){let p=i[m+0],_=i[m+1],y=i[m+2],S=p*3,g=_*3,w=y*3,M=p*2,b=_*2,x=y*2,k=r[S+0],v=r[S+1],A=r[S+2],T=Math.acos(A/Math.sqrt(k*k+v*v+A*A)),R=Math.atan2(v,k)+e,O=T/e,N=1-R/n,E=r[g+0],I=r[g+1],P=r[g+2],L=Math.acos(P/Math.sqrt(E*E+I*I+P*P)),$=Math.atan2(I,E)+e,rt=L/e,J=1-$/n,ne=r[w+0],re=r[w+1],ie=r[w+2],kr=Math.acos(ie/Math.sqrt(ne*ne+re*re+ie*ie)),vr=Math.atan2(re,ne)+e,tn=kr/e,oe=1-vr/n,br=[ne-E,re-I,ie-P],Mr=[k-E,v-I,A-P],H=new G(br).cross(Mr).normalize(),U;(N===0||J===0||oe===0)&&(N===0||N>.5)&&(J===0||J>.5)&&(oe===0||oe>.5)&&(r.push(r[S+0],r[S+1],r[S+2]),U=r.length/3-1,i.push(U),h[U*2+0]=1,h[U*2+1]=O,c[U*3+0]=H.x,c[U*3+1]=H.y,c[U*3+2]=H.z,r.push(r[g+0],r[g+1],r[g+2]),U=r.length/3-1,i.push(U),h[U*2+0]=1,h[U*2+1]=rt,c[U*3+0]=H.x,c[U*3+1]=H.y,c[U*3+2]=H.z,r.push(r[w+0],r[w+1],r[w+2]),U=r.length/3-1,i.push(U),h[U*2+0]=1,h[U*2+1]=tn,c[U*3+0]=H.x,c[U*3+1]=H.y,c[U*3+2]=H.z),c[S+0]=c[g+0]=c[w+0]=H.x,c[S+1]=c[g+1]=c[w+1]=H.y,c[S+2]=c[g+2]=c[w+2]=H.z,h[M+0]=N,h[M+1]=O,h[b+0]=J,h[b+1]=rt,h[x+0]=oe,h[x+1]=tn}return{indices:{size:1,value:new Uint16Array(i)},attributes:{POSITION:{size:3,value:new Float32Array(r)},NORMAL:{size:3,value:new Float32Array(c)},TEXCOORD_0:{size:2,value:new Float32Array(h)}}}}var xr=C(z(),1);function gr(s){let{indices:t,attributes:e}=s;if(!t)return s;let n=t.value.length,r={};for(let i in e){let o=e[i],{constant:c,value:h,size:f}=o;if(c||!f)continue;let m=new h.constructor(n*f);for(let p=0;ps.radius||1,p=new Float32Array(f*3),_=new Float32Array(f*3),y=new Float32Array(f*2),S=f>65535?Uint32Array:Uint16Array,g=new S(t*e*6);for(let M=0;M<=t;M++)for(let b=0;b<=e;b++){let x=b/e,k=M/t,v=b+M*(e+1),A=v*2,T=v*3,R=h*x,O=i*k,N=Math.sin(R),E=Math.cos(R),I=Math.sin(O),P=Math.cos(O),L=E*I,$=P,rt=N*I,J=m(L,$,rt,x,k);p[T+0]=J*L,p[T+1]=J*$,p[T+2]=J*rt,_[T+0]=L,_[T+1]=$,_[T+2]=rt,y[A+0]=x,y[A+1]=1-k}let w=e+1;for(let M=0;M[h.name,h])||[]);this.setShaderInputs(e.shaderInputs||new xt(n)),this.props.shaderLayout||=Qt(this.props.source);let r=Ui(t),i=(this.props.modules?.length>0?this.props.modules:this.shaderInputs?.getModules())||[];this.pipelineFactory=e.pipelineFactory||lt.getDefaultPipelineFactory(this.device),this.shaderFactory=e.shaderFactory||ut.getDefaultShaderFactory(this.device);let{source:o,getUniforms:c}=this.props.shaderAssembler.assembleShader({platformInfo:r,...this.props,modules:i});this.source=o,this._getModuleUniforms=c,this.pipeline=this._updatePipeline(),e.bindings&&this.setBindings(e.bindings),Object.seal(this)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._uniformStore.destroy(),this._destroyed=!0)}predraw(){this.updateShaderInputs()}dispatch(t,e,n,r){try{this._logDrawCallStart(),this.pipeline=this._updatePipeline(),this.pipeline.setBindings(this.bindings),t.setPipeline(this.pipeline),t.setBindings([]),t.dispatch(e,n,r)}finally{this._logDrawCallEnd()}}setVertexCount(t){}setInstanceCount(t){}setShaderInputs(t){this.shaderInputs=t,this._uniformStore=new Bt.UniformStore(this.shaderInputs.modules);for(let e of Object.keys(this.shaderInputs.modules)){let n=this._uniformStore.getManagedUniformBuffer(this.device,e);this.bindings[`${e}Uniforms`]=n}}setShaderModuleProps(t){let e=this._getModuleUniforms(t),n=Object.keys(e).filter(i=>{let o=e[i];return!(0,Z.isNumberArray)(o)&&typeof o!="number"&&typeof o!="boolean"}),r={};for(let i of n)r[i]=e[i],delete e[i]}updateShaderInputs(){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues())}setBindings(t){Object.assign(this.bindings,t)}_setPipelineNeedsUpdate(t){this._pipelineNeedsUpdate=this._pipelineNeedsUpdate||t}_updatePipeline(){if(this._pipelineNeedsUpdate){let t=null;this.pipeline&&(Z.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),t=this.shader),this._pipelineNeedsUpdate=!1,this.shader=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"compute",source:this.source,debug:this.props.debugShaders}),this.pipeline=this.pipelineFactory.createComputePipeline({...this.props,shader:this.shader}),t&&this.shaderFactory.release(t)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let t=Z.log.level>3?0:Di;Z.log.level<2||Date.now()-this._lastLogTime>> DRAWING MODEL ${this.id}`,{collapsed:Z.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let t=this.shaderInputs.getDebugTable();Z.log.table(Js,t)(),Z.log.groupEnd(Js)(),this._logOpen=!1}}_drawCount=0;_getBufferOrConstantValues(t,e){let n=(0,wr.getTypedArrayFromDataType)(e);return(t instanceof Bt.Buffer?new n(t.debugData):t).toString()}},ee=Qs;st(ee,"defaultProps",{...Bt.ComputePipeline.defaultProps,id:"unnamed",handle:void 0,userData:{},source:"",modules:[],defines:{},bindings:void 0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,shaderAssembler:mt.getDefaultShaderAssembler(),debugShaders:void 0});function Ui(s){return{type:s.type,shaderLanguage:s.info.shadingLanguage,shaderLanguageVersion:s.info.shadingLanguageVersion,gpu:s.info.gpu,features:s.features}}return Pr(se);})(); return __exports__; });