@quake2ts/engine 0.0.772 → 0.0.774
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.global.js +1 -1
- package/dist/browser/index.global.js.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/render/shaderProgram.d.ts.map +1 -1
- package/package.json +6 -5
|
@@ -138,7 +138,7 @@ KÙ:KµºKí{K]ûK£[KÚKóKÓ½R׿ÿ'P^j9TîçmóþL¿_o©×hÙtÙ
|
|
|
138
138
|
Ái;ªäÀ%n= =M+W= ÓÖc[aS
|
|
139
139
|
FÁð]NôÝ'= qr(¶ù¤nü«òÿ¿d&ÿÈõT4Þ=}z|ö ¿OW×SMtdH.ÏãRX&§o3ØÜXÍ^ÊMí£W´iâ]NüOå£S£Å·ç÷ݧ½GÑUy¹¦ß§/6P0(Cúýb"þ¥°VÙÄá£ÓÙ@¾YýòD{òÃv?EP©=MBé\ĽYäýRò øfâëEEf¼D+gC×úDZGÅÿ±Ç?TzÙ¡±ÏÁÕ¯¦ðvZmT}3xËz×cºrÑM=Mc-É©Ô7½wæc§Î»cû¾yfÙWòÆÝÔc¥³ôØf«Äñ·9ø%g:y^+{U]¤þ
[&fÓÏYë«Gªõ¹¦Öðþ¬moÛø?/ÛS.[S9ÛùC
/û2²Y£ÎÑ%/sy¢×ÌùJW6Oí\g0^JùêßÏ0í[Ü'ÏÔ>À-¿[ÔW?Y]±ØÙÃî<~ÎëR~Ìf¾Z/×¼_á¾Þê+îoÐñ{Þ\e3K%©¹§íB¹§(c=}ËÈ·SzÔnf§èx}o\9öf|%Ýå¥~©IÇüñY8}Ffú@Rú1éþ3÷ËótQøvû|³Îaá,Óé>BG6Òê}ÃJ|¶=}°öf6õk¶ÌºHgNjÒ{æ¾M;9·é§WèO±Ä3ÒËÒyt ;ù´à©a|Ó^!ÝøûÂÄ
|
|
140
140
|
(VV¸ÇÙcÏ>yoçzÃvòG{3Þ£½c×ôíÅé;°OÛGØ<wÜW> rU]q{û'ùÝír{*øï?t-ígùWÿ
&§]m}×ût¥Ë~ß&>&Õv!b#ÅÌq¢µ|jÍüùÉ^Æ&ôþ~sIµ"]d)uâ´ºvk Å\<Íÿöê½Â
|
|
141
|
-
ïBçϧmÙIólÜoëVb¦¯éWÇû3`});var rm={a:$r};this.setModule=R=>{t.setModule(cr,R)},this.getModule=()=>t.getModule(cr),this.instantiate=()=>(this.getModule().then(R=>WebAssembly.instantiate(R,rm)).then(R=>{let dt=R.exports;oa(dt),m=dt.l,g(),tm(dt),r()}),this.ready=new Promise(R=>{r=R}).then(()=>{this.HEAP=m.buffer,this.malloc=nd,this.free=ld,this.create_decoder=vi,this.send_setup=id,this.init_dsp=od,this.decode_packets=ad,this.destroy_decoder=sd}),this)}function gn(){return this._init=()=>new this._WASMAudioDecoderCommon().instantiate(this._EmscriptenWASM,this._module).then(t=>{this._common=t,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._firstPage=!0,this._inputLen=this._common.allocateTypedArray(1,Uint32Array),this._outputBufferPtr=this._common.allocateTypedArray(1,Uint32Array),this._channels=this._common.allocateTypedArray(1,Uint32Array),this._sampleRate=this._common.allocateTypedArray(1,Uint32Array),this._samplesDecoded=this._common.allocateTypedArray(1,Uint32Array);let e=256;this._errors=this._common.allocateTypedArray(e,Uint32Array),this._errorsLength=this._common.allocateTypedArray(1,Int32Array),this._frameNumber=0,this._inputBytes=0,this._outputSamples=0,this._decoder=this._common.wasm.create_decoder(this._input.ptr,this._inputLen.ptr,this._outputBufferPtr.ptr,this._channels.ptr,this._sampleRate.ptr,this._samplesDecoded.ptr,this._errors.ptr,this._errorsLength.ptr,e)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.wasm.destroy_decoder(this._decoder),this._common.free()},this.sendSetupHeader=t=>{this._input.buf.set(t),this._inputLen.buf[0]=t.length,this._common.wasm.send_setup(this._decoder,this._firstPage),this._firstPage=!1},this.initDsp=()=>{this._common.wasm.init_dsp(this._decoder)},this.decodePackets=t=>{let e=[],r=0,n=[];for(let i=0;i<t.length;i++){let o=t[i];this._input.buf.set(o),this._inputLen.buf[0]=o.length,this._common.wasm.decode_packets(this._decoder);let a=this._samplesDecoded.buf[0],s=[],d=new Uint32Array(this._common.wasm.HEAP,this._outputBufferPtr.buf[0],this._channels.buf[0]);for(let l=0;l<this._channels.buf[0];l++){let c=new Float32Array(a);a&&c.set(new Float32Array(this._common.wasm.HEAP,d[l],a)),s.push(c)}e.push(s),r+=a,this._frameNumber++,this._inputBytes+=o.length,this._outputSamples+=a;for(let l=0;l<this._errorsLength.buf;l+=2){let c=this._common.codeToString(this._errors.buf[l]),f=this._common.codeToString(this._errors.buf[l+1]);n.push({message:c+" vorbis_synthesis"+f,frameLength:o.length,frameNumber:this._frameNumber,inputBytes:this._inputBytes,outputSamples:this._outputSamples})}this._errorsLength.buf[0]=0}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,e,this._channels.buf[0],r,this._sampleRate.buf[0],16)},this._isWebWorker=gn.isWebWorker,this._WASMAudioDecoderCommon=gn.WASMAudioDecoderCommon||re,this._EmscriptenWASM=gn.EmscriptenWASM||cr,this._module=gn.module,this._inputSize=128*1024,this._ready=this._init(),this}var is=Symbol(),dr=class{constructor(){this._onCodec=e=>{if(e!=="vorbis")throw new Error("@wasm-audio-decoders/ogg-vorbis does not support this codec "+e)},new re,this._init(),this._ready=this[is](gn)}_init(){this._vorbisSetupInProgress=!0,this._totalSamplesDecoded=0,this._codecParser=new Su("audio/ogg",{onCodec:this._onCodec,enableFrameCRC32:!1})}async[is](e){if(this._decoder){let r=this._decoder;await r.ready.then(()=>r.free())}return this._decoder=new e,this._decoder.ready}get ready(){return this._ready}async reset(){return this._init(),this._decoder.reset()}free(){this._decoder.free()}async decodeOggPages(e){let r=[];for(let o=0;o<e.length;o++){let a=e[o];if(this._vorbisSetupInProgress&&(a[ns][0]===1&&this._decoder.sendSetupHeader(a[ns]),a[rs].length)){let s=a[rs][0][wu];this._decoder.sendSetupHeader(s[Mu]),this._decoder.initDsp(),this._vorbisSetupInProgress=!1}r.push(...a[rs].map(s=>s[ns]))}let n=await this._decoder.decodePackets(r);this._totalSamplesDecoded+=n.samplesDecoded;let i=e[e.length-1];if(i&&i[Au]){let o=this._totalSamplesDecoded-i[Eu];if(o>0){for(let a=0;a<n.channelData.length;a++)n.channelData[a]=n.channelData[a].subarray(0,n.samplesDecoded-o);n.samplesDecoded-=o,this._totalSamplesDecoded-=o}}return n}async decode(e){return this.decodeOggPages([...this._codecParser.parseChunk(e)])}async flush(){let e=await this.decodeOggPages([...this._codecParser.flush()]);return await this.reset(),e}async decodeFile(e){let r=await this.decodeOggPages([...this._codecParser.parseAll(e)]);return await this.reset(),r}};var Wl=class extends Vn{constructor(e){super(e,"ogg-vorbis-decoder",gn,cr)}async sendSetupHeader(e){return this.postToDecoder("sendSetupHeader",e)}async initDsp(){return this.postToDecoder("initDsp")}async decodePackets(e){return this.postToDecoder("decodePackets",e)}},To=class extends dr{constructor(){super(),this._ready=super[is](Wl)}async free(){await this._decoder.free()}terminate(){this._decoder.terminate()}};Ca(dr,"OggVorbisDecoder");Ca(To,"OggVorbisDecoderWebWorker");var Xl=class extends Error{constructor(e){super(e),this.name="OggDecodeError"}};async function os(t,e=new dr){await e.ready;let r=await e.decode(new Uint8Array(t)),n=r.errors;if(n&&n.length>0)throw new Xl(n.map(i=>i.message).join("; "));return{sampleRate:r.sampleRate,channels:r.channelData.length,bitDepth:r.bitDepth,channelData:r.channelData}}var Co=class extends Error{constructor(e){super(e),this.name="AudioRegistryError"}},oi=class{constructor(e,r={}){this.vfs=e;this.refCounts=new Map;this.nextRequestId=0;this.cache=new _r(r.cacheSize??64),r.workerPath&&(this.worker=new Worker(r.workerPath,{type:"module"}))}get size(){return this.cache.size}get capacity(){return this.cache.capacity}async load(e){let r=e.toLowerCase(),n=this.cache.get(r);if(n)return this.refCounts.set(r,(this.refCounts.get(r)??0)+1),n;let o=(await this.vfs.readFile(e)).slice().buffer,a=await this.decodeByExtension(e,o);return this.cache.set(r,a),this.refCounts.set(r,1),a}release(e){let r=e.toLowerCase(),n=this.refCounts.get(r)??0;n<=1?(this.cache.delete(r),this.refCounts.delete(r)):this.refCounts.set(r,n-1)}clearAll(){this.cache.clear(),this.refCounts.clear()}set capacity(e){this.cache.capacity=e}async decodeByExtension(e,r){let n=e.toLowerCase();if(n.endsWith(".wav")){if(this.worker)return this.decodeWavInWorker(r);let i=Ta(r),o=i.channels,a=Array.from({length:o},()=>new Float32Array(i.samples.length/o));for(let s=0;s<i.samples.length;s+=1)a[s%o][Math.floor(s/o)]=i.samples[s];return{sampleRate:i.sampleRate,channels:o,bitDepth:i.bitsPerSample,channelData:a}}if(n.endsWith(".ogg")||n.endsWith(".oga"))return os(r);throw new Co(`Unsupported audio format: ${e}`)}decodeWavInWorker(e){return new Promise((r,n)=>{if(!this.worker){n(new Error("Worker not initialized"));return}let i=this.nextRequestId++,o=a=>{if(a.data.id===i)if(this.worker.removeEventListener("message",o),a.data.type==="success"){let s=a.data.data,d=s.channels,l=Array.from({length:d},()=>new Float32Array(s.samples.length/d));for(let c=0;c<s.samples.length;c+=1)l[c%d][Math.floor(c/d)]=s.samples[c];r({sampleRate:s.sampleRate,channels:d,bitDepth:s.bitsPerSample,channelData:l})}else n(new Error(a.data.message))};this.worker.addEventListener("message",o),this.worker.postMessage({id:i,buffer:e,type:"wav"},[e])})}};var lp="quake2ts-pak-indexes",cp="pak-indexes";function Lu(){if(typeof indexedDB<"u")return indexedDB;if(typeof window<"u"&&"indexedDB"in window)return window.indexedDB;if(typeof globalThis<"u"&&"indexedDB"in globalThis)return globalThis.indexedDB}function Io(t,e){let r=Lu();return r?new Promise((n,i)=>{let o=r.open(t,1);o.onupgradeneeded=()=>{let{result:a}=o;a.objectStoreNames.contains(e)||a.createObjectStore(e,{keyPath:"key"})},o.onerror=()=>i(o.error??new Error("Unknown IndexedDB error")),o.onsuccess=()=>n(o.result)}):Promise.reject(new Error("IndexedDB is not available in this environment"))}function Ro(t,e,r,n){return new Promise((i,o)=>{let s=t.transaction(e,r).objectStore(e),d=n(s);d.onsuccess=()=>i(d.result),d.onerror=()=>o(d.error??new Error("IndexedDB transaction error"))})}function Kl(t,e){return`${ae(t)}:${e.toString(16)}`}function dp(t){return t.map(e=>({...e}))}var as=class{constructor(e=lp,r=cp){this.dbName=e;this.storeName=r}get isSupported(){return!!Lu()}async persist(e){if(!this.isSupported)return;let r=e.validate(),n={...r,key:Kl(e.name,r.checksum),name:e.name,size:e.size,persistedAt:Date.now(),entries:dp(r.entries)},i=await Io(this.dbName,this.storeName);return await Ro(i,this.storeName,"readwrite",o=>o.put(n)),i.close(),n}async find(e,r){if(!this.isSupported)return;let n=await Io(this.dbName,this.storeName),i=r!==void 0?Kl(e,r):void 0,o=await Ro(n,this.storeName,"readonly",a=>i?a.get(i):a.getAll());if(n.close(),!!o){if(Array.isArray(o)){let a=ae(e),s=o.filter(d=>ae(d.name)===a);return s.length===0?void 0:s.sort((d,l)=>l.persistedAt-d.persistedAt)[0]}return o}}async remove(e,r){if(!this.isSupported)return!1;let n=await Io(this.dbName,this.storeName),i=r!==void 0?Kl(e,r):void 0,o=await Ro(n,this.storeName,"readwrite",a=>{if(i)return a.delete(i);let s=`${ae(e)}:`;return a.delete(IDBKeyRange.bound(s,`${s}\uFFFF`,!1,!0))});return n.close(),typeof o=="number"?o>0:!0}async clear(){if(!this.isSupported)return;let e=await Io(this.dbName,this.storeName);await Ro(e,this.storeName,"readwrite",r=>r.clear()),e.close()}async list(){if(!this.isSupported)return[];let e=await Io(this.dbName,this.storeName),r=await Ro(e,this.storeName,"readonly",n=>n.getAll());return e.close(),r.sort((n,i)=>i.persistedAt-n.persistedAt)}};var yn=class extends Error{constructor(r,n){super(n??`Missing dependencies: ${r.join(", ")}`);this.missing=r;this.name="AssetDependencyError"}},ko=class{constructor(){this.nodes=new Map}register(e,r=[]){let n=this.nodes.get(e)??{dependencies:new Set,loaded:!1};r.forEach(i=>n.dependencies.add(i)),this.nodes.set(e,n),r.forEach(i=>{this.nodes.has(i)||this.nodes.set(i,{dependencies:new Set,loaded:!1})})}markLoaded(e){let r=this.nodes.get(e)??{dependencies:new Set,loaded:!1},n=this.getMissingDependencies(e,r);if(n.length>0)throw new yn(n,`Asset ${e} is missing dependencies: ${n.join(", ")}`);r.loaded=!0,this.nodes.set(e,r)}markUnloaded(e){let r=this.nodes.get(e);r&&(r.loaded=!1)}isLoaded(e){return this.nodes.get(e)?.loaded??!1}missingDependencies(e){let r=this.nodes.get(e);return r?this.getMissingDependencies(e,r):[]}reset(){this.nodes.clear()}getMissingDependencies(e,r){let n=[];for(let i of r.dependencies)this.nodes.get(i)?.loaded||n.push(i);return n}},ss=class{constructor(e,r={}){this.vfs=e;this.maps=new Map;this.loadQueue=[];this.activeLoads=0;this.textures=new Hn({capacity:r.textureCacheCapacity??128,maxMemory:r.textureMemoryLimit}),this.audio=new oi(e,{cacheSize:r.audioCacheSize??64,workerPath:r.audioWorkerPath}),this.dependencyTracker=r.dependencyTracker??new ko,this.resourceTracker=r.resourceTracker,this.md2=new zn(e),this.md3=new Un(e),this.sprite=new Nn(e),this.bsp=new On(e,{useWorker:!!r.bspWorkerPath,workerPath:r.bspWorkerPath}),this.maxConcurrentLoads=r.maxConcurrentLoads??4,this.palette=new Uint8Array(768);for(let n=0;n<256;n++)this.palette[n*3]=n,this.palette[n*3+1]=n,this.palette[n*3+2]=n}async loadPalette(e="pics/colormap.pcx"){try{let r=await this.vfs.readFile(e),n=Di(r);n.palette&&(this.palette=n.palette)}catch(r){console.warn(`Failed to load palette from ${e}:`,r)}}isAssetLoaded(e,r){return this.dependencyTracker.isLoaded(this.makeKey(e,r))}registerTexture(e,r){this.textures.set(e,r);let n=this.makeKey("texture",e);this.dependencyTracker.register(n),this.dependencyTracker.markLoaded(n)}async loadTexture(e){if(this.resourceTracker){let a=this.vfs.stat(e);this.resourceTracker.recordLoad("texture",e,a?.size,a?.sourcePak)}let r=this.textures.get(e);if(r)return r;let n=await this.vfs.readFile(e),i=e.split(".").pop()?.toLowerCase(),o;if(i==="wal")o=La(n,this.palette);else if(i==="pcx")o=Ea(Di(n));else if(i==="tga")o=jd(Al(n));else throw new Error(`Unsupported texture format for loadTexture: ${i}`);return this.registerTexture(e,o),o}async loadSound(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("sound",e,i?.size,i?.sourcePak)}let r=await this.audio.load(e),n=this.makeKey("sound",e);return this.dependencyTracker.register(n),this.dependencyTracker.markLoaded(n),r}async loadMd2Model(e,r=[]){if(this.resourceTracker){let s=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,s?.size,s?.sourcePak)}let n=this.makeKey("model",e),i=r.map(s=>this.makeKey("texture",s));this.dependencyTracker.register(n,i);let o=this.dependencyTracker.missingDependencies(n);if(o.length>0)throw new yn(o,`Asset ${n} is missing dependencies: ${o.join(", ")}`);let a=await this.md2.load(e);return this.dependencyTracker.markLoaded(n),a}getMd2Model(e){if(this.resourceTracker){let r=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,r?.size,r?.sourcePak)}return this.md2.get(e)}async loadMd3Model(e,r=[]){if(this.resourceTracker){let s=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,s?.size,s?.sourcePak)}let n=this.makeKey("model",e),i=r.map(s=>this.makeKey("texture",s));this.dependencyTracker.register(n,i);let o=this.dependencyTracker.missingDependencies(n);if(o.length>0)throw new yn(o,`Asset ${n} is missing dependencies: ${o.join(", ")}`);let a=await this.md3.load(e);return this.dependencyTracker.markLoaded(n),a}getMd3Model(e){if(this.resourceTracker){let r=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,r?.size,r?.sourcePak)}return this.md3.get(e)}async loadSprite(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("sprite",e,i?.size,i?.sourcePak)}let r=this.makeKey("sprite",e);this.dependencyTracker.register(r);let n=await this.sprite.load(e);return this.dependencyTracker.markLoaded(r),n}async loadMap(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("map",e,i?.size,i?.sourcePak)}let r=this.makeKey("map",e);if(this.maps.has(e))return this.maps.get(e);this.dependencyTracker.register(r);let n=await this.bsp.load(e);return this.maps.set(e,n),this.dependencyTracker.markLoaded(r),n}getMap(e){return this.maps.get(e)}listFiles(e){return this.vfs.findByExtension(e)}resetForLevelChange(){this.textures.clear(),this.audio.clearAll(),this.dependencyTracker.reset(),this.maps.clear(),this.loadQueue.length=0}getMemoryUsage(){let e=0,r=0;if(typeof process<"u"&&process.memoryUsage){let n=process.memoryUsage();e=n.heapTotal,r=n.heapUsed}return{textures:this.textures.memoryUsage,audio:this.audio.size,heapTotal:e,heapUsed:r}}enforceMemoryBudget(e){e.textureMemoryLimit!==void 0&&(this.textures.maxMemory=e.textureMemoryLimit),e.textureCacheCapacity!==void 0&&(this.textures.capacity=e.textureCacheCapacity),e.audioCacheSize!==void 0&&(this.audio.capacity=e.audioCacheSize)}clearCache(e){switch(e){case"texture":this.textures.clear();break;case"sound":this.audio.clearAll();break;case"map":this.maps.clear();break}}async preloadAssets(e){let r=e.map(n=>{let i=this.detectAssetType(n);return i?this.queueLoad(n,i,0):Promise.resolve()});await Promise.all(r)}queueLoad(e,r,n=1){return r==="texture"&&this.textures.get(e)?Promise.resolve(this.textures.get(e)):new Promise((i,o)=>{this.loadQueue.push({path:e,type:r,priority:n,resolve:i,reject:o}),this.loadQueue.sort((a,s)=>s.priority-a.priority),this.processQueue()})}async processQueue(){if(this.activeLoads>=this.maxConcurrentLoads||this.loadQueue.length===0)return;let e=this.loadQueue.shift();this.activeLoads++;try{let r;switch(e.type){case"texture":r=await this.loadTexture(e.path);break;case"sound":r=await this.loadSound(e.path);break;case"model":e.path.endsWith(".md2")?r=await this.loadMd2Model(e.path):e.path.endsWith(".md3")&&(r=await this.loadMd3Model(e.path));break;case"sprite":r=await this.loadSprite(e.path);break;case"map":r=await this.loadMap(e.path);break;default:throw new Error(`Unknown asset type ${e.type}`)}e.resolve(r)}catch(r){e.reject(r)}finally{this.activeLoads--,this.processQueue()}}detectAssetType(e){let r=e.split(".").pop()?.toLowerCase();return r?["wal","pcx","tga","png","jpg"].includes(r)?"texture":["wav","ogg"].includes(r)?"sound":["md2","md3"].includes(r)?"model":["sp2"].includes(r)?"sprite":["bsp"].includes(r)?"map":null:null}makeKey(e,r){return`${e}:${ae(r)}`}};var ls=class{constructor(e){this.factory=e}getContext(){return this.context||(this.context=this.factory()),this.context}async resume(){let e=this.getContext();e.state==="suspended"&&await e.resume()}getState(){return this.context?.state??"suspended"}};function cs(t){let e=t.getContext(),r=e.createGain();r.gain.value=1;let n=e.createDynamicsCompressor(),i=e.createBiquadFilter?.(),o;if(e.createConvolver&&e.createGain){let a=e.createConvolver(),s=e.createGain(),d=e.createGain();s.connect(a),a.connect(d),o={convolver:a,input:s,output:d}}return i?(i.type="lowpass",i.frequency.value=2e4,i.Q.value=.707,r.connect(i),i.connect(n),o&&o.output.connect(i)):(r.connect(n),o&&o.output.connect(n)),n.connect(e.destination),{context:e,master:r,compressor:n,filter:i,reverb:o}}var ds=class{constructor(e=new Fn){this.configStrings=e;this.buffers=new Map}registerName(e){return this.configStrings.soundIndex(e)}register(e,r){let n=this.registerName(e);return this.buffers.set(n,r),n}find(e){return this.configStrings.findSoundIndex(e)}get(e){return this.buffers.get(e)}has(e){return this.buffers.has(e)}getName(e){return this.configStrings.getName(e)}};var us=class{constructor(e){this.vfs=e.vfs,this.registry=e.registry,this.contextController=e.context,this.soundRoot=e.soundRoot??"sound/",this.decodeAudio=e.decodeAudio??((r,n)=>{if(!r.decodeAudioData)throw new Error("decodeAudioData is not available on the provided audio context");return r.decodeAudioData(n)})}async precache(e){let r=[...new Set(e.map(o=>this.normalize(o)))],n={loaded:[],skipped:[],missing:[],errors:{}},i=this.contextController.getContext();for(let o of r)try{let a=this.registry.find(o);if(a!==void 0&&this.registry.has(a)){n.skipped.push(o);continue}if(!this.vfs.stat(o)){n.missing.push(o);continue}let l=(await this.vfs.readFile(o)).slice().buffer,c=await this.decodeAudio(i,l);this.registry.register(o,c),n.loaded.push(o)}catch(a){let s=a instanceof Error?a:new Error(String(a));n.errors[o]=s}return n}normalize(e){let r=ae(e.replace(/^\//,""));return r.startsWith(this.soundRoot)?r:ae(`${this.soundRoot}${r}`)}};var up=7,Po=t=>t&up;function fs(t){return Array.from({length:Ti},()=>({entnum:0,entchannel:Ot.Auto,endTimeMs:0,isPlayer:!1,active:!1})).map(e=>({...e,isPlayer:e.entnum===t}))}function hs(t,e,r,n){if(r<0)throw new Error("pickChannel: entchannel must be non-negative");let i=Po(r),o=-1,a=Number.POSITIVE_INFINITY;for(let s=0;s<t.length;s+=1){let d=t[s],l=Po(d.entchannel);if(i!==Ot.Auto&&d.entnum===e&&l===i){o=s;break}if(d.active&&d.entnum===n.playerEntity&&e!==n.playerEntity)continue;let c=d.endTimeMs-n.nowMs;(o===-1||c<a)&&(a=c,o=s)}return o===-1?void 0:o}var ms=class{constructor(e){this.activePreset=null;this.enabled=!0;this.node=e,this.node.input.gain.value=.5,this.node.output.gain.value=1}setPreset(e){this.activePreset=e,this.node.convolver.buffer!==(e?.buffer??null)&&(this.node.convolver.buffer=e?.buffer??null),e&&e.gain!==void 0?this.node.output.gain.value=e.gain:this.node.output.gain.value=1}setEnabled(e){this.enabled=e,e?this.node.input.gain.value=.5:this.node.input.gain.value=0}getOutputNode(){return this.node.output}getInputNode(){return this.node.input}};var ps=class{constructor(e){this.activeSources=new Map;this.playbackRate=1;this.contextController=e.context,this.registry=e.registry,this.playerEntity=e.playerEntity,this.channels=fs(e.playerEntity),this.listener=e.listener??{origin:ud,right:{x:1,y:0,z:0}},this.sfxVolume=e.sfxVolume??1,this.masterVolume=e.masterVolume??1,this.resolveOcclusion=e.resolveOcclusion,this.graph=cs(this.contextController),this.graph.master.gain.value=this.masterVolume,this.graph.reverb&&(this.reverb=new ms(this.graph.reverb))}setListener(e){this.listener=e}setMasterVolume(e){this.masterVolume=e,this.graph.master.gain.value=e}setSfxVolume(e){this.sfxVolume=e}setPlaybackRate(e){this.playbackRate=e;for(let r of this.activeSources.values())r.source.playbackRate&&(r.source.playbackRate.value=e),this.updateSourceGain(r)}async ensureRunning(){await this.contextController.resume()}setReverbPreset(e){this.reverb?.setPreset(e)}play(e){let r=this.registry.get(e.soundIndex);if(!r)return;let n=this.graph.context,i=n.currentTime*1e3,o=hs(this.channels,e.entity,e.channel,{nowMs:i,playerEntity:this.playerEntity});if(o===void 0)return;let a=this.activeSources.get(o);a&&(a.source.onended=null,a.source.stop(),this.activeSources.delete(o));let s=n.createBufferSource();s.buffer=r,s.loop=e.looping??!1,s.playbackRate&&(s.playbackRate.value=this.playbackRate);let d=e.origin??this.listener.origin,l=n.createGain(),c=this.createPanner(n,e.attenuation),f=this.resolveOcclusion?.(this.listener,d,e.attenuation),u=Tu(f?.gainScale??1),h=this.resolveOcclusion?this.createOcclusionFilter(n,f?.lowpassHz??2e4):void 0;this.applyOriginToPanner(c,d);let g=e.volume/255*this.sfxVolume,p=Math.abs(this.playbackRate-1)<.001?1:0;l.gain.value=g*u*p;let y=n.currentTime+(e.timeOffsetMs??0)/1e3,_=(e.looping?Number.POSITIVE_INFINITY:r.duration*1e3)+y*1e3;s.connect(c);let x=c;h?(c.connect(h),h.connect(l),x=l):(c.connect(l),x=l),l.connect(this.graph.master),this.reverb&&l.connect(this.reverb.getInputNode()),s.start(y),s.onended=()=>{this.channels[o].active=!1,this.activeSources.delete(o)};let b={channelIndex:o,entnum:e.entity,entchannel:Po(e.channel),endTimeMs:_,source:s,panner:c,gain:l,baseGain:g,origin:d,attenuation:e.attenuation,occlusion:h?{scale:u,lowpassHz:f?.lowpassHz,filter:h}:f?{scale:u,lowpassHz:f.lowpassHz}:void 0};return this.channels[o]={entnum:e.entity,entchannel:Po(e.channel),endTimeMs:_,isPlayer:e.entity===this.playerEntity,active:!0},this.activeSources.set(o,b),b}stop(e){let r=this.activeSources.get(e);r&&(r.source.stop(),this.channels[e].active=!1,this.activeSources.delete(e))}stopEntitySounds(e){for(let[r,n]of[...this.activeSources.entries()])n.entnum===e&&(n.source.stop(),this.channels[r].active=!1,this.activeSources.delete(r))}updateEntityPosition(e,r){for(let n of this.activeSources.values())if(n.entnum===e&&(this.applyOriginToPanner(n.panner,r),n.origin=r,this.resolveOcclusion)){let i=this.resolveOcclusion(this.listener,r,n.attenuation);this.applyOcclusion(n,i)}}positionedSound(e,r,n,i){return this.play({entity:0,channel:Ot.Auto,soundIndex:r,volume:n,attenuation:i,origin:e})}ambientSound(e,r,n){return this.play({entity:0,channel:Ot.Auto,soundIndex:r,volume:n,attenuation:Ci,origin:e,looping:!0})}getChannelState(e){return this.channels[e]}getDiagnostics(){return{activeChannels:this.activeSources.size,masterVolume:this.masterVolume,sfxVolume:this.sfxVolume,channels:[...this.channels],activeSounds:[...this.activeSources.values()].map(e=>({entnum:e.entnum,entchannel:e.entchannel,channelIndex:e.channelIndex,origin:e.origin,gain:e.gain.gain.value,baseGain:e.baseGain,attenuation:e.attenuation,maxDistance:e.panner.maxDistance,distanceModel:e.panner.distanceModel,occlusion:e.occlusion?{scale:e.occlusion.scale,lowpassHz:e.occlusion.lowpassHz}:void 0}))}}setUnderwater(e,r=400){let n=this.graph.filter;n&&(n.type="lowpass",n.Q.value=.707,n.frequency.value=e?r:2e4)}createPanner(e,r){let n=e.createPanner?e.createPanner():Object.assign(e.createGain(),{positionX:{value:this.listener.origin.x},positionY:{value:this.listener.origin.y},positionZ:{value:this.listener.origin.z}});return this.configurePanner(n,r)}configurePanner(e,r){let n=Rn(r);return e.refDistance=In,e.maxDistance=Jr(r),e.rolloffFactor=n,e.distanceModel="linear",e.positionX.value=this.listener.origin.x,e.positionY.value=this.listener.origin.y,e.positionZ.value=this.listener.origin.z,e}applyOriginToPanner(e,r){e.positionX.value=r.x,e.positionY.value=r.y,e.positionZ.value=r.z}createOcclusionFilter(e,r){if(!e.createBiquadFilter)return;let n=e.createBiquadFilter();return n.type="lowpass",n.Q.value=.707,n.frequency.value=$l(r,10,2e4),n}updateSourceGain(e){let r=e.occlusion?.scale??1,n=Math.abs(this.playbackRate-1)<.001?1:0;e.gain.gain.value=e.baseGain*r*n}applyOcclusion(e,r){let n=Tu(r?.gainScale??1),i=Math.abs(this.playbackRate-1)<.001?1:0;if(e.gain.gain.value=e.baseGain*n*i,e.occlusion?.filter){let o=r?.lowpassHz??2e4;e.occlusion.filter.frequency.value=$l(o,10,2e4)}e.occlusion?(e.occlusion.scale=n,e.occlusion.lowpassHz=r?.lowpassHz):r&&(e.occlusion={scale:n,lowpassHz:r.lowpassHz})}},$l=(t,e,r)=>Math.min(r,Math.max(e,t)),Tu=t=>$l(t,0,1);var Bo=class{constructor(e){this.trace=e;this.resolve=(e,r,n)=>{let i=tl(fd(r,e.origin)),o=Jr(n),d=2e4*(1-Math.min(i,o)/Math.max(1,o)*.9),l=this.trace(e.origin,r,void 0,void 0),c=1,f=2e4;l.fraction<1&&(c=.3,f=400);let u=Math.min(d,f);if(c<1||u<2e4)return{gainScale:c,lowpassHz:u}}}};function Cu(t){return new Bo(t).resolve}var gs=class{constructor(e){this.createElement=e.createElement,this.resolveSource=e.resolveSource??(async r=>r),this.volume=e.volume??1,this.crossfadeDuration=e.crossfadeDuration??1}async playTrack(e){let r=`music/track${e.toString().padStart(2,"0")}.ogg`;return this.play(r)}async play(e,{loop:r=!0,restart:n=!1}={}){if(this.track===e&&this.currentElement){this.currentElement.loop=r,this.cancelFade(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.currentElement.volume=this.volume,n&&(this.currentElement.currentTime=0),(this.currentElement.paused||n)&&await this.currentElement.play();return}let i=await this.resolveSource(e);this.cancelFade(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.currentElement&&(this.fadingElement=this.currentElement,this.currentElement=void 0);let o=this.createElement();o.src=i,o.loop=r,o.volume=0,o.currentTime=0,o.load();try{await o.play()}catch(a){console.warn(`MusicSystem: Failed to play ${e}`,a),this.fadingElement}this.currentElement=o,this.track=e,this.startCrossfade()}pause(){this.cancelFade(),this.currentElement&&!this.currentElement.paused&&this.currentElement.pause(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0)}async resume(){!this.currentElement||!this.currentElement.paused||(await this.currentElement.play(),this.currentElement.volume=this.volume)}stop(){this.cancelFade(),this.currentElement&&(this.currentElement.pause(),this.currentElement.currentTime=0,this.currentElement=void 0),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.track=void 0}setVolume(e){this.volume=e,this.currentElement&&!this.fadeInterval&&(this.currentElement.volume=e)}getState(){let e=!!(this.currentElement&&!this.currentElement.paused&&!this.currentElement.ended),r=!!this.currentElement?.paused;return{track:this.track,paused:r,playing:e,volume:this.volume}}startCrossfade(){let r=this.crossfadeDuration*1e3/50,n=this.volume/r,i=0,o=this.fadingElement?this.fadingElement.volume:0,a=()=>{let s=!1;this.currentElement&&(i=Math.min(this.volume,i+n),this.currentElement.volume=i,i<this.volume&&(s=!0)),this.fadingElement&&(o=Math.max(0,o-n),this.fadingElement.volume=o,o>0?s=!0:(this.fadingElement.pause(),this.fadingElement=void 0)),s||this.cancelFade()};a(),(this.currentElement&&this.currentElement.volume<this.volume||this.fadingElement)&&(this.fadeInterval=setInterval(a,50))}cancelFade(){this.fadeInterval&&(clearInterval(this.fadeInterval),this.fadeInterval=void 0)}};function fp(t){t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.enable(t.CULL_FACE),t.cullFace(t.BACK),t.enable(t.BLEND),t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA)}function hp(t,e,r,n){for(let i of e){let o=t.getExtension(i);if(!o)throw new Error(`Missing required WebGL extension: ${i}`);n.set(i,o)}for(let i of r){let o=t.getExtension(i);o&&n.set(i,o)}}function Iu(t,e={}){let{contextAttributes:r,requiredExtensions:n=[],optionalExtensions:i=[]}=e,o=t.getContext("webgl2",r??{antialias:!0});if(!o)throw new Error("WebGL2 not supported or failed to initialize");fp(o);let a=new Map;hp(o,n,i,a);let s=!1,d=new Set,l=new Set,c=u=>{s=!0,u.preventDefault();for(let h of d)h()},f=()=>{s=!1;for(let u of l)u()};return t.addEventListener("webglcontextlost",c),t.addEventListener("webglcontextrestored",f),{gl:o,extensions:a,isLost:()=>s,onLost(u){return d.add(u),()=>d.delete(u)},onRestored(u){return l.add(u),()=>l.delete(u)},dispose(){t.removeEventListener("webglcontextlost",c),t.removeEventListener("webglcontextrestored",f),d.clear(),l.clear(),a.clear()}}}function Ru(t,e,r){let n=t.createShader(e);if(!n)throw new Error("Failed to allocate shader");if(t.shaderSource(n,r),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){let o=t.getShaderInfoLog(n)??"Unknown shader compile failure";throw t.deleteShader(n),new Error(o)}return n}function mp(t,e,r,n){let i=t.createProgram();if(!i)throw new Error("Failed to allocate shader program");if(t.attachShader(i,e),t.attachShader(i,r),n)for(let[a,s]of Object.entries(n))t.bindAttribLocation(i,s,a);if(t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){let a=t.getProgramInfoLog(i)??"Unknown shader link failure";throw t.deleteProgram(i),new Error(a)}return i}var ve=class t{constructor(e,r,n){this.uniformLocations=new Map;this.attributeLocations=new Map;this.gl=e,this.program=r,this.sourceSize=n}static create(e,r,n){let i=Ru(e,e.VERTEX_SHADER,r.vertex),o=Ru(e,e.FRAGMENT_SHADER,r.fragment);try{let a=mp(e,i,o,n),s=r.vertex.length+r.fragment.length;return new t(e,a,s)}finally{e.deleteShader(i),e.deleteShader(o)}}use(){this.gl.useProgram(this.program)}getUniformLocation(e){if(!this.uniformLocations.has(e)){let r=this.gl.getUniformLocation(this.program,e);this.uniformLocations.set(e,r)}return this.uniformLocations.get(e)??null}getAttributeLocation(e){if(!this.attributeLocations.has(e)){let r=this.gl.getAttribLocation(this.program,e);this.attributeLocations.set(e,r)}return this.attributeLocations.get(e)??-1}dispose(){this.gl.deleteProgram(this.program),this.uniformLocations.clear(),this.attributeLocations.clear()}};function ku(t,e,r){return ve.create(t,e,r)}var Se=class{constructor(e,r=e.STATIC_DRAW,n){this.gl=e,this.target=n??e.ARRAY_BUFFER;let i=e.createBuffer();if(!i)throw new Error("Failed to allocate buffer");this.buffer=i,e.bindBuffer(this.target,this.buffer),e.bufferData(this.target,0,r)}bind(){this.gl.bindBuffer(this.target,this.buffer)}upload(e,r=this.gl.STATIC_DRAW){this.bind(),this.gl.bufferData(this.target,e,r)}update(e,r=0){this.bind(),this.gl.bufferSubData(this.target,r,e)}dispose(){this.gl.deleteBuffer(this.buffer)}},Te=class extends Se{constructor(e,r=e.STATIC_DRAW){super(e,r,e.ELEMENT_ARRAY_BUFFER)}},Ce=class{constructor(e){this.gl=e;let r=e.createVertexArray();if(!r)throw new Error("Failed to allocate vertex array object");this.vao=r}bind(){this.gl.bindVertexArray(this.vao)}configureAttributes(e,r){this.bind(),r&&r.bind();for(let n of e)this.gl.enableVertexAttribArray(n.index),this.gl.vertexAttribPointer(n.index,n.size,n.type,n.normalized??!1,n.stride??0,n.offset??0),n.divisor!==void 0&&this.gl.vertexAttribDivisor(n.index,n.divisor)}dispose(){this.gl.deleteVertexArray(this.vao)}},Ur=class{constructor(e,r=e.TEXTURE_2D){this.width=0;this.height=0;this.gl=e,this.target=r;let n=e.createTexture();if(!n)throw new Error("Failed to allocate texture");this.texture=n}bind(e=0){this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.target,this.texture)}setParameters(e){this.bind(),e.wrapS!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_S,e.wrapS),e.wrapT!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_T,e.wrapT),e.minFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MIN_FILTER,e.minFilter),e.magFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MAG_FILTER,e.magFilter)}upload(e,r,n){this.width=e,this.height=r,this.uploadImage(0,this.gl.RGBA,e,r,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n)}uploadImage(e,r,n,i,o,a,s,d){this.bind(),this.gl.texImage2D(this.target,e,r,n,i,o,a,s,d)}dispose(){this.gl.deleteTexture(this.texture)}},ai=class{constructor(e){this.gl=e,this.target=e.TEXTURE_CUBE_MAP;let r=e.createTexture();if(!r)throw new Error("Failed to allocate cubemap texture");this.texture=r}bind(e=0){this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.target,this.texture)}setParameters(e){this.bind(),e.wrapS!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_S,e.wrapS),e.wrapT!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_T,e.wrapT),e.minFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MIN_FILTER,e.minFilter),e.magFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MAG_FILTER,e.magFilter)}uploadFace(e,r,n,i,o,a,s,d,l){this.bind(),this.gl.texImage2D(e,r,n,i,o,a,s,d,l)}dispose(){this.gl.deleteTexture(this.texture)}},ys=class{constructor(e){this.gl=e;let r=e.createFramebuffer();if(!r)throw new Error("Failed to allocate framebuffer");this.framebuffer=r}bind(e=this.gl.FRAMEBUFFER){this.gl.bindFramebuffer(e,this.framebuffer)}attachTexture2D(e,r,n=0){this.bind(),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,e,r.target,r.texture,n)}dispose(){this.gl.deleteFramebuffer(this.framebuffer)}};var Yl=4,Zl=7*Yl,ql=[{index:0,size:3,type:5126,stride:Zl,offset:0},{index:1,size:2,type:5126,stride:Zl,offset:3*Yl},{index:2,size:2,type:5126,stride:Zl,offset:5*Yl}];function pp(t,e){return{width:t,height:t,padding:e,data:new Uint8Array(t*t*4),cursorX:0,cursorY:0,rowHeight:0}}function gp(t){let e=t.width*t.height;if(e===0)throw new Error("Invalid lightmap with zero area");let r=t.samples.byteLength/e;if(!Number.isInteger(r)||r<3||r>4)throw new Error("Unsupported lightmap channel count");return r}function yp(t,e,r){let n=gp(r),i=t.width*4,o=e.x+t.padding,a=e.y+t.padding,s=0;for(let d=0;d<r.height;d++){let l=(a+d)*i+o*4;for(let c=0;c<r.width;c++){let f=l+c*4;t.data[f]=r.samples[s],t.data[f+1]=r.samples[s+1],t.data[f+2]=r.samples[s+2],t.data[f+3]=n===4?r.samples[s+3]:255,s+=n}}}function bp(t,e,r){let n=e.width+r.lightmapPadding*2,i=e.height+r.lightmapPadding*2;if(n>r.atlasSize||i>r.atlasSize)throw new Error("Lightmap too large for atlas");for(let s of t){if(s.cursorX+n>s.width&&(s.cursorX=0,s.cursorY+=s.rowHeight+r.lightmapPadding,s.rowHeight=0),s.cursorY+i>s.height)continue;let d={atlasIndex:t.indexOf(s),x:s.cursorX,y:s.cursorY,width:e.width,height:e.height};return s.cursorX+=n+r.lightmapPadding,s.rowHeight=Math.max(s.rowHeight,i),{placement:d,atlas:s}}let o=pp(r.atlasSize,r.lightmapPadding);t.push(o);let a={atlasIndex:t.length-1,x:0,y:0,width:e.width,height:e.height};return o.cursorX=n+r.lightmapPadding,o.rowHeight=i,{placement:a,atlas:o}}function bs(t){return t instanceof Float32Array?t:new Float32Array(t)}function xp(t,e){if(!t){let n=new Uint16Array(e);for(let i=0;i<e;i++)n[i]=i;return n}return t instanceof Uint16Array?t:new Uint16Array(t)}function _p(t,e){let r=new Float32Array(t.length);for(let n=0;n<t.length;n+=2)r[n]=e.offset[0]+t[n]*e.scale[0],r[n+1]=e.offset[1]+t[n+1]*e.scale[1];return r}function vp(t,e){let r=bs(t.vertices),n=bs(t.textureCoords),i=e?_p(bs(t.lightmapCoords??t.textureCoords),e):bs(t.lightmapCoords??new Float32Array(n.length)),o=r.length/3;if(n.length/2!==o)throw new Error("Texture coordinates count mismatch");if(i.length/2!==o)throw new Error("Lightmap coordinates count mismatch");let a=new Float32Array(o*7);for(let s=0;s<o;s++){let d=s*3,l=s*2,c=s*7;a[c]=r[d],a[c+1]=r[d+1],a[c+2]=r[d+2],a[c+3]=n[l],a[c+4]=n[l+1],a[c+5]=i[l],a[c+6]=i[l+1]}return a}function Pu(t){let e=[];for(let r=0;r<t.faces.length;r++){let n=t.faces[r];if(n.texInfo<0)continue;let i=t.texInfo[n.texInfo],o=[],a=[],s=[];for(let u=0;u<n.numEdges;u++){let h=t.surfEdges[n.firstEdge+u],m=t.edges[Math.abs(h)],g=h>=0?m.vertices[0]:m.vertices[1],p=t.vertices[g];o.push(p[0],p[1],p[2]);let y=p[0]*i.s[0]+p[1]*i.s[1]+p[2]*i.s[2]+i.sOffset,_=p[0]*i.t[0]+p[1]*i.t[1]+p[2]*i.t[2]+i.tOffset;a.push(y,_),s.push(y,_)}let d=[],l=o.length/3;for(let u=1;u<l-1;u++)d.push(0,u,u+1);let c,f=t.lightMapInfo[r];if(f){let u=1/0,h=-1/0,m=1/0,g=-1/0;for(let v=0;v<a.length;v+=2){let w=a[v],S=a[v+1];w<u&&(u=w),w>h&&(h=w),S<m&&(m=S),S>g&&(g=S)}let p=Math.floor(u/16),y=Math.floor(m/16),_=Math.ceil(h/16)-p+1,x=Math.ceil(g/16)-y+1,b=Sa(n,t.lightMaps,f);if(b&&b.length===_*x*3){c={width:_,height:x,samples:b};for(let v=0;v<s.length;v+=2)s[v]=a[v]/16-p+.5,s[v+1]=a[v+1]/16-y+.5}}e.push({vertices:new Float32Array(o),textureCoords:new Float32Array(a),lightmapCoords:new Float32Array(s),indices:new Uint16Array(d),texture:i.texture,surfaceFlags:i.flags,lightmap:c,faceIndex:r})}return e}function Bu(t,e,r,n={}){let i=e;if(r&&n.hiddenClassnames&&n.hiddenClassnames.size>0){let c=new Set;for(let f of r.entities.entities)if(f.classname&&n.hiddenClassnames.has(f.classname)){let u=f.properties.model;if(u&&u.startsWith("*")){let h=parseInt(u.substring(1),10);if(!isNaN(h)&&h>=0&&h<r.models.length){let m=r.models[h];for(let g=0;g<m.numFaces;g++)c.add(m.firstFace+g)}}}c.size>0&&(i=e.filter(f=>!c.has(f.faceIndex)))}let o={atlasSize:n.atlasSize??1024,lightmapPadding:n.lightmapPadding??1,hiddenClassnames:n.hiddenClassnames??new Set},a=[],s=new Map;i.forEach((c,f)=>{if(!c.lightmap)return;let{placement:u,atlas:h}=bp(a,c.lightmap,o);yp(h,u,c.lightmap),s.set(f,{atlasIndex:u.atlasIndex,offset:[(u.x+o.lightmapPadding)/o.atlasSize,(u.y+o.lightmapPadding)/o.atlasSize],scale:[u.width/o.atlasSize,u.height/o.atlasSize]})});let d=a.map(c=>{let f=new Ur(t);return f.setParameters({wrapS:t.CLAMP_TO_EDGE,wrapT:t.CLAMP_TO_EDGE,minFilter:t.LINEAR,magFilter:t.LINEAR}),f.uploadImage(0,t.RGBA,c.width,c.height,0,t.RGBA,t.UNSIGNED_BYTE,c.data),{texture:f,width:c.width,height:c.height,pixels:c.data}});return{surfaces:i.map((c,f)=>{let u=s.get(f),h=vp(c,u),m=xp(c.indices,h.length/7),g=new Se(t,t.STATIC_DRAW,t.ARRAY_BUFFER);g.upload(h);let p=new Te(t,t.STATIC_DRAW);p.upload(m);let y=new Ce(t);return y.configureAttributes(ql,g),{vao:y,vertexBuffer:g,indexBuffer:p,indexCount:m.length,vertexCount:h.length/7,texture:c.texture,surfaceFlags:c.surfaceFlags??Mi,lightmap:u,vertexData:h,indexData:m}}),lightmaps:d}}function si(t){let{normal:e,distance:r}=t,n=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);if(n===0)return t;let i=1/n;return{normal:{x:e.x*i,y:e.y*i,z:e.z*i},distance:r*i}}function Fu(t){if(t.length!==16)throw new Error("View-projection matrix must contain 16 elements");let e=t[0],r=t[4],n=t[8],i=t[12],o=t[1],a=t[5],s=t[9],d=t[13],l=t[2],c=t[6],f=t[10],u=t[14],h=t[3],m=t[7],g=t[11],p=t[15];return[si({normal:{x:h+e,y:m+r,z:g+n},distance:p+i}),si({normal:{x:h-e,y:m-r,z:g-n},distance:p-i}),si({normal:{x:h+o,y:m+a,z:g+s},distance:p+d}),si({normal:{x:h-o,y:m-a,z:g-s},distance:p-d}),si({normal:{x:h+l,y:m+c,z:g+f},distance:p+u}),si({normal:{x:h-l,y:m-c,z:g-f},distance:p-u})]}function Sp(t,e){return t.normal.x*e.x+t.normal.y*e.y+t.normal.z*e.z+t.distance}function Fo(t,e,r){for(let n of r){let i=n.normal.x>=0?e.x:t.x,o=n.normal.y>=0?e.y:t.y,a=n.normal.z>=0?e.z:t.z;if(Sp(n,{x:i,y:o,z:a})<0)return!1}return!0}function Du(t){return t<0}function Ou(t){return-t-1}function zu(t,e){return t.normal[0]*e.x+t.normal[1]*e.y+t.normal[2]*e.z-t.dist}function wp(t,e,r){if(!t||e<0||r<0)return!0;let n=Math.ceil(t.numClusters/8),i=t.clusters[e].pvs,o=Math.floor(r/8),a=1<<r%8;return o<0||o>=n?!1:(i[o]&a)!==0}function Ap(t,e){let r={x:t.mins[0],y:t.mins[1],z:t.mins[2]},n={x:t.maxs[0],y:t.maxs[1],z:t.maxs[2]};return Fo(r,n,e)}function Ql(t,e){let r=0;for(;r>=0;){let n=t.nodes[r],i=t.planes[n.planeIndex],a=zu(i,e)>=0?0:1,s=n.children[a];if(Du(s))return Ou(s);r=s}return-1}function Mp(t,e){let r=t.leafs[e],n=[];for(let i=0;i<r.numLeafFaces;i+=1)n.push(t.leafLists.leafFaces[e][i]);return n}function jl(t,e,r,n,i,o,a,s){if(Du(e)){let h=Ou(e),m=t.leafs[h];if(s&&m.area>=0&&!s.has(m.area)||!wp(t.visibility,i,m.cluster)||!Ap(m,n))return;let g={x:(m.mins[0]+m.maxs[0])*.5,y:(m.mins[1]+m.maxs[1])*.5,z:(m.mins[2]+m.maxs[2])*.5},p=g.x-r.x,y=g.y-r.y,_=g.z-r.z,x=-(p*p+y*y+_*_);for(let b of Mp(t,h))a.has(b)||(a.add(b),o.push({faceIndex:b,leafIndex:h,sortKey:x}));return}let d=t.nodes[e],l=t.planes[d.planeIndex],c=zu(l,r),f=c>=0?d.children[0]:d.children[1],u=c>=0?d.children[1]:d.children[0];Fo({x:d.mins[0],y:d.mins[1],z:d.mins[2]},{x:d.maxs[0],y:d.maxs[1],z:d.maxs[2]},n)&&(jl(t,f,r,n,i,o,a,s),jl(t,u,r,n,i,o,a,s))}function Ep(t,e,r){let n=new Set;if(e<0||e>=t.areas.length)return n;let i=[e];for(n.add(e);i.length>0;){let o=i.pop(),a=t.areas[o];for(let s=0;s<a.numAreaPortals;s++){let d=a.firstAreaPortal+s,l=t.areaPortals[d],c=l.otherArea;(l.portalNumber<=0||r[l.portalNumber])&&!n.has(c)&&(n.add(c),i.push(c))}}return n}function Uu(t,e,r,n){let i=Ql(t,e),o=i>=0?t.leafs[i]:null,a=o?o.cluster:-1,s=o?o.area:-1,d=null;n&&s>=0&&t.areas&&t.areas.length>0&&(d=Ep(t,s,n));let l=[];return jl(t,0,e,r,a,l,new Set,d),l}var Nr=32,xs=class{constructor(){this.lights=[]}addLight(e,r){if(e.key!==void 0){let n=this.lights.findIndex(i=>i.key===e.key);if(n!==-1){this.lights[n]=e;return}}this.lights.push(e)}clear(){this.lights=[]}update(e,r=0){if(this.lights=this.lights.filter(n=>n.die>e),r>0)for(let n of this.lights)n.radiusSpeed!==void 0&&n.radiusSpeed!==0&&(n.intensity+=n.radiusSpeed*r,n.intensity<0&&(n.intensity=0))}getActiveLights(){return this.lights}};function li(t){let e=[];for(let r=0;r<t.length;r+=3){let n=t[r],i=t[r+1],o=t[r+2];e.push(n,i,i,o,o,n)}return t instanceof Uint32Array||Math.max(...e)>65535?new Uint32Array(e):new Uint16Array(e)}var Jl=`#version 300 es
|
|
141
|
+
ïBçϧmÙIólÜoëVb¦¯éWÇû3`});var rm={a:$r};this.setModule=R=>{t.setModule(cr,R)},this.getModule=()=>t.getModule(cr),this.instantiate=()=>(this.getModule().then(R=>WebAssembly.instantiate(R,rm)).then(R=>{let dt=R.exports;oa(dt),m=dt.l,g(),tm(dt),r()}),this.ready=new Promise(R=>{r=R}).then(()=>{this.HEAP=m.buffer,this.malloc=nd,this.free=ld,this.create_decoder=vi,this.send_setup=id,this.init_dsp=od,this.decode_packets=ad,this.destroy_decoder=sd}),this)}function gn(){return this._init=()=>new this._WASMAudioDecoderCommon().instantiate(this._EmscriptenWASM,this._module).then(t=>{this._common=t,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._firstPage=!0,this._inputLen=this._common.allocateTypedArray(1,Uint32Array),this._outputBufferPtr=this._common.allocateTypedArray(1,Uint32Array),this._channels=this._common.allocateTypedArray(1,Uint32Array),this._sampleRate=this._common.allocateTypedArray(1,Uint32Array),this._samplesDecoded=this._common.allocateTypedArray(1,Uint32Array);let e=256;this._errors=this._common.allocateTypedArray(e,Uint32Array),this._errorsLength=this._common.allocateTypedArray(1,Int32Array),this._frameNumber=0,this._inputBytes=0,this._outputSamples=0,this._decoder=this._common.wasm.create_decoder(this._input.ptr,this._inputLen.ptr,this._outputBufferPtr.ptr,this._channels.ptr,this._sampleRate.ptr,this._samplesDecoded.ptr,this._errors.ptr,this._errorsLength.ptr,e)}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.wasm.destroy_decoder(this._decoder),this._common.free()},this.sendSetupHeader=t=>{this._input.buf.set(t),this._inputLen.buf[0]=t.length,this._common.wasm.send_setup(this._decoder,this._firstPage),this._firstPage=!1},this.initDsp=()=>{this._common.wasm.init_dsp(this._decoder)},this.decodePackets=t=>{let e=[],r=0,n=[];for(let i=0;i<t.length;i++){let o=t[i];this._input.buf.set(o),this._inputLen.buf[0]=o.length,this._common.wasm.decode_packets(this._decoder);let a=this._samplesDecoded.buf[0],s=[],d=new Uint32Array(this._common.wasm.HEAP,this._outputBufferPtr.buf[0],this._channels.buf[0]);for(let l=0;l<this._channels.buf[0];l++){let c=new Float32Array(a);a&&c.set(new Float32Array(this._common.wasm.HEAP,d[l],a)),s.push(c)}e.push(s),r+=a,this._frameNumber++,this._inputBytes+=o.length,this._outputSamples+=a;for(let l=0;l<this._errorsLength.buf;l+=2){let c=this._common.codeToString(this._errors.buf[l]),f=this._common.codeToString(this._errors.buf[l+1]);n.push({message:c+" vorbis_synthesis"+f,frameLength:o.length,frameNumber:this._frameNumber,inputBytes:this._inputBytes,outputSamples:this._outputSamples})}this._errorsLength.buf[0]=0}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,e,this._channels.buf[0],r,this._sampleRate.buf[0],16)},this._isWebWorker=gn.isWebWorker,this._WASMAudioDecoderCommon=gn.WASMAudioDecoderCommon||re,this._EmscriptenWASM=gn.EmscriptenWASM||cr,this._module=gn.module,this._inputSize=128*1024,this._ready=this._init(),this}var is=Symbol(),dr=class{constructor(){this._onCodec=e=>{if(e!=="vorbis")throw new Error("@wasm-audio-decoders/ogg-vorbis does not support this codec "+e)},new re,this._init(),this._ready=this[is](gn)}_init(){this._vorbisSetupInProgress=!0,this._totalSamplesDecoded=0,this._codecParser=new Su("audio/ogg",{onCodec:this._onCodec,enableFrameCRC32:!1})}async[is](e){if(this._decoder){let r=this._decoder;await r.ready.then(()=>r.free())}return this._decoder=new e,this._decoder.ready}get ready(){return this._ready}async reset(){return this._init(),this._decoder.reset()}free(){this._decoder.free()}async decodeOggPages(e){let r=[];for(let o=0;o<e.length;o++){let a=e[o];if(this._vorbisSetupInProgress&&(a[ns][0]===1&&this._decoder.sendSetupHeader(a[ns]),a[rs].length)){let s=a[rs][0][wu];this._decoder.sendSetupHeader(s[Mu]),this._decoder.initDsp(),this._vorbisSetupInProgress=!1}r.push(...a[rs].map(s=>s[ns]))}let n=await this._decoder.decodePackets(r);this._totalSamplesDecoded+=n.samplesDecoded;let i=e[e.length-1];if(i&&i[Au]){let o=this._totalSamplesDecoded-i[Eu];if(o>0){for(let a=0;a<n.channelData.length;a++)n.channelData[a]=n.channelData[a].subarray(0,n.samplesDecoded-o);n.samplesDecoded-=o,this._totalSamplesDecoded-=o}}return n}async decode(e){return this.decodeOggPages([...this._codecParser.parseChunk(e)])}async flush(){let e=await this.decodeOggPages([...this._codecParser.flush()]);return await this.reset(),e}async decodeFile(e){let r=await this.decodeOggPages([...this._codecParser.parseAll(e)]);return await this.reset(),r}};var Wl=class extends Vn{constructor(e){super(e,"ogg-vorbis-decoder",gn,cr)}async sendSetupHeader(e){return this.postToDecoder("sendSetupHeader",e)}async initDsp(){return this.postToDecoder("initDsp")}async decodePackets(e){return this.postToDecoder("decodePackets",e)}},To=class extends dr{constructor(){super(),this._ready=super[is](Wl)}async free(){await this._decoder.free()}terminate(){this._decoder.terminate()}};Ca(dr,"OggVorbisDecoder");Ca(To,"OggVorbisDecoderWebWorker");var Xl=class extends Error{constructor(e){super(e),this.name="OggDecodeError"}};async function os(t,e=new dr){await e.ready;let r=await e.decode(new Uint8Array(t)),n=r.errors;if(n&&n.length>0)throw new Xl(n.map(i=>i.message).join("; "));return{sampleRate:r.sampleRate,channels:r.channelData.length,bitDepth:r.bitDepth,channelData:r.channelData}}var Co=class extends Error{constructor(e){super(e),this.name="AudioRegistryError"}},oi=class{constructor(e,r={}){this.vfs=e;this.refCounts=new Map;this.nextRequestId=0;this.cache=new _r(r.cacheSize??64),r.workerPath&&(this.worker=new Worker(r.workerPath,{type:"module"}))}get size(){return this.cache.size}get capacity(){return this.cache.capacity}async load(e){let r=e.toLowerCase(),n=this.cache.get(r);if(n)return this.refCounts.set(r,(this.refCounts.get(r)??0)+1),n;let o=(await this.vfs.readFile(e)).slice().buffer,a=await this.decodeByExtension(e,o);return this.cache.set(r,a),this.refCounts.set(r,1),a}release(e){let r=e.toLowerCase(),n=this.refCounts.get(r)??0;n<=1?(this.cache.delete(r),this.refCounts.delete(r)):this.refCounts.set(r,n-1)}clearAll(){this.cache.clear(),this.refCounts.clear()}set capacity(e){this.cache.capacity=e}async decodeByExtension(e,r){let n=e.toLowerCase();if(n.endsWith(".wav")){if(this.worker)return this.decodeWavInWorker(r);let i=Ta(r),o=i.channels,a=Array.from({length:o},()=>new Float32Array(i.samples.length/o));for(let s=0;s<i.samples.length;s+=1)a[s%o][Math.floor(s/o)]=i.samples[s];return{sampleRate:i.sampleRate,channels:o,bitDepth:i.bitsPerSample,channelData:a}}if(n.endsWith(".ogg")||n.endsWith(".oga"))return os(r);throw new Co(`Unsupported audio format: ${e}`)}decodeWavInWorker(e){return new Promise((r,n)=>{if(!this.worker){n(new Error("Worker not initialized"));return}let i=this.nextRequestId++,o=a=>{if(a.data.id===i)if(this.worker.removeEventListener("message",o),a.data.type==="success"){let s=a.data.data,d=s.channels,l=Array.from({length:d},()=>new Float32Array(s.samples.length/d));for(let c=0;c<s.samples.length;c+=1)l[c%d][Math.floor(c/d)]=s.samples[c];r({sampleRate:s.sampleRate,channels:d,bitDepth:s.bitsPerSample,channelData:l})}else n(new Error(a.data.message))};this.worker.addEventListener("message",o),this.worker.postMessage({id:i,buffer:e,type:"wav"},[e])})}};var lp="quake2ts-pak-indexes",cp="pak-indexes";function Lu(){if(typeof indexedDB<"u")return indexedDB;if(typeof window<"u"&&"indexedDB"in window)return window.indexedDB;if(typeof globalThis<"u"&&"indexedDB"in globalThis)return globalThis.indexedDB}function Io(t,e){let r=Lu();return r?new Promise((n,i)=>{let o=r.open(t,1);o.onupgradeneeded=()=>{let{result:a}=o;a.objectStoreNames.contains(e)||a.createObjectStore(e,{keyPath:"key"})},o.onerror=()=>i(o.error??new Error("Unknown IndexedDB error")),o.onsuccess=()=>n(o.result)}):Promise.reject(new Error("IndexedDB is not available in this environment"))}function Ro(t,e,r,n){return new Promise((i,o)=>{let s=t.transaction(e,r).objectStore(e),d=n(s);d.onsuccess=()=>i(d.result),d.onerror=()=>o(d.error??new Error("IndexedDB transaction error"))})}function Kl(t,e){return`${ae(t)}:${e.toString(16)}`}function dp(t){return t.map(e=>({...e}))}var as=class{constructor(e=lp,r=cp){this.dbName=e;this.storeName=r}get isSupported(){return!!Lu()}async persist(e){if(!this.isSupported)return;let r=e.validate(),n={...r,key:Kl(e.name,r.checksum),name:e.name,size:e.size,persistedAt:Date.now(),entries:dp(r.entries)},i=await Io(this.dbName,this.storeName);return await Ro(i,this.storeName,"readwrite",o=>o.put(n)),i.close(),n}async find(e,r){if(!this.isSupported)return;let n=await Io(this.dbName,this.storeName),i=r!==void 0?Kl(e,r):void 0,o=await Ro(n,this.storeName,"readonly",a=>i?a.get(i):a.getAll());if(n.close(),!!o){if(Array.isArray(o)){let a=ae(e),s=o.filter(d=>ae(d.name)===a);return s.length===0?void 0:s.sort((d,l)=>l.persistedAt-d.persistedAt)[0]}return o}}async remove(e,r){if(!this.isSupported)return!1;let n=await Io(this.dbName,this.storeName),i=r!==void 0?Kl(e,r):void 0,o=await Ro(n,this.storeName,"readwrite",a=>{if(i)return a.delete(i);let s=`${ae(e)}:`;return a.delete(IDBKeyRange.bound(s,`${s}\uFFFF`,!1,!0))});return n.close(),typeof o=="number"?o>0:!0}async clear(){if(!this.isSupported)return;let e=await Io(this.dbName,this.storeName);await Ro(e,this.storeName,"readwrite",r=>r.clear()),e.close()}async list(){if(!this.isSupported)return[];let e=await Io(this.dbName,this.storeName),r=await Ro(e,this.storeName,"readonly",n=>n.getAll());return e.close(),r.sort((n,i)=>i.persistedAt-n.persistedAt)}};var yn=class extends Error{constructor(r,n){super(n??`Missing dependencies: ${r.join(", ")}`);this.missing=r;this.name="AssetDependencyError"}},ko=class{constructor(){this.nodes=new Map}register(e,r=[]){let n=this.nodes.get(e)??{dependencies:new Set,loaded:!1};r.forEach(i=>n.dependencies.add(i)),this.nodes.set(e,n),r.forEach(i=>{this.nodes.has(i)||this.nodes.set(i,{dependencies:new Set,loaded:!1})})}markLoaded(e){let r=this.nodes.get(e)??{dependencies:new Set,loaded:!1},n=this.getMissingDependencies(e,r);if(n.length>0)throw new yn(n,`Asset ${e} is missing dependencies: ${n.join(", ")}`);r.loaded=!0,this.nodes.set(e,r)}markUnloaded(e){let r=this.nodes.get(e);r&&(r.loaded=!1)}isLoaded(e){return this.nodes.get(e)?.loaded??!1}missingDependencies(e){let r=this.nodes.get(e);return r?this.getMissingDependencies(e,r):[]}reset(){this.nodes.clear()}getMissingDependencies(e,r){let n=[];for(let i of r.dependencies)this.nodes.get(i)?.loaded||n.push(i);return n}},ss=class{constructor(e,r={}){this.vfs=e;this.maps=new Map;this.loadQueue=[];this.activeLoads=0;this.textures=new Hn({capacity:r.textureCacheCapacity??128,maxMemory:r.textureMemoryLimit}),this.audio=new oi(e,{cacheSize:r.audioCacheSize??64,workerPath:r.audioWorkerPath}),this.dependencyTracker=r.dependencyTracker??new ko,this.resourceTracker=r.resourceTracker,this.md2=new zn(e),this.md3=new Un(e),this.sprite=new Nn(e),this.bsp=new On(e,{useWorker:!!r.bspWorkerPath,workerPath:r.bspWorkerPath}),this.maxConcurrentLoads=r.maxConcurrentLoads??4,this.palette=new Uint8Array(768);for(let n=0;n<256;n++)this.palette[n*3]=n,this.palette[n*3+1]=n,this.palette[n*3+2]=n}async loadPalette(e="pics/colormap.pcx"){try{let r=await this.vfs.readFile(e),n=Di(r);n.palette&&(this.palette=n.palette)}catch(r){console.warn(`Failed to load palette from ${e}:`,r)}}isAssetLoaded(e,r){return this.dependencyTracker.isLoaded(this.makeKey(e,r))}registerTexture(e,r){this.textures.set(e,r);let n=this.makeKey("texture",e);this.dependencyTracker.register(n),this.dependencyTracker.markLoaded(n)}async loadTexture(e){if(this.resourceTracker){let a=this.vfs.stat(e);this.resourceTracker.recordLoad("texture",e,a?.size,a?.sourcePak)}let r=this.textures.get(e);if(r)return r;let n=await this.vfs.readFile(e),i=e.split(".").pop()?.toLowerCase(),o;if(i==="wal")o=La(n,this.palette);else if(i==="pcx")o=Ea(Di(n));else if(i==="tga")o=jd(Al(n));else throw new Error(`Unsupported texture format for loadTexture: ${i}`);return this.registerTexture(e,o),o}async loadSound(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("sound",e,i?.size,i?.sourcePak)}let r=await this.audio.load(e),n=this.makeKey("sound",e);return this.dependencyTracker.register(n),this.dependencyTracker.markLoaded(n),r}async loadMd2Model(e,r=[]){if(this.resourceTracker){let s=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,s?.size,s?.sourcePak)}let n=this.makeKey("model",e),i=r.map(s=>this.makeKey("texture",s));this.dependencyTracker.register(n,i);let o=this.dependencyTracker.missingDependencies(n);if(o.length>0)throw new yn(o,`Asset ${n} is missing dependencies: ${o.join(", ")}`);let a=await this.md2.load(e);return this.dependencyTracker.markLoaded(n),a}getMd2Model(e){if(this.resourceTracker){let r=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,r?.size,r?.sourcePak)}return this.md2.get(e)}async loadMd3Model(e,r=[]){if(this.resourceTracker){let s=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,s?.size,s?.sourcePak)}let n=this.makeKey("model",e),i=r.map(s=>this.makeKey("texture",s));this.dependencyTracker.register(n,i);let o=this.dependencyTracker.missingDependencies(n);if(o.length>0)throw new yn(o,`Asset ${n} is missing dependencies: ${o.join(", ")}`);let a=await this.md3.load(e);return this.dependencyTracker.markLoaded(n),a}getMd3Model(e){if(this.resourceTracker){let r=this.vfs.stat(e);this.resourceTracker.recordLoad("model",e,r?.size,r?.sourcePak)}return this.md3.get(e)}async loadSprite(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("sprite",e,i?.size,i?.sourcePak)}let r=this.makeKey("sprite",e);this.dependencyTracker.register(r);let n=await this.sprite.load(e);return this.dependencyTracker.markLoaded(r),n}async loadMap(e){if(this.resourceTracker){let i=this.vfs.stat(e);this.resourceTracker.recordLoad("map",e,i?.size,i?.sourcePak)}let r=this.makeKey("map",e);if(this.maps.has(e))return this.maps.get(e);this.dependencyTracker.register(r);let n=await this.bsp.load(e);return this.maps.set(e,n),this.dependencyTracker.markLoaded(r),n}getMap(e){return this.maps.get(e)}listFiles(e){return this.vfs.findByExtension(e)}resetForLevelChange(){this.textures.clear(),this.audio.clearAll(),this.dependencyTracker.reset(),this.maps.clear(),this.loadQueue.length=0}getMemoryUsage(){let e=0,r=0;if(typeof process<"u"&&process.memoryUsage){let n=process.memoryUsage();e=n.heapTotal,r=n.heapUsed}return{textures:this.textures.memoryUsage,audio:this.audio.size,heapTotal:e,heapUsed:r}}enforceMemoryBudget(e){e.textureMemoryLimit!==void 0&&(this.textures.maxMemory=e.textureMemoryLimit),e.textureCacheCapacity!==void 0&&(this.textures.capacity=e.textureCacheCapacity),e.audioCacheSize!==void 0&&(this.audio.capacity=e.audioCacheSize)}clearCache(e){switch(e){case"texture":this.textures.clear();break;case"sound":this.audio.clearAll();break;case"map":this.maps.clear();break}}async preloadAssets(e){let r=e.map(n=>{let i=this.detectAssetType(n);return i?this.queueLoad(n,i,0):Promise.resolve()});await Promise.all(r)}queueLoad(e,r,n=1){return r==="texture"&&this.textures.get(e)?Promise.resolve(this.textures.get(e)):new Promise((i,o)=>{this.loadQueue.push({path:e,type:r,priority:n,resolve:i,reject:o}),this.loadQueue.sort((a,s)=>s.priority-a.priority),this.processQueue()})}async processQueue(){if(this.activeLoads>=this.maxConcurrentLoads||this.loadQueue.length===0)return;let e=this.loadQueue.shift();this.activeLoads++;try{let r;switch(e.type){case"texture":r=await this.loadTexture(e.path);break;case"sound":r=await this.loadSound(e.path);break;case"model":e.path.endsWith(".md2")?r=await this.loadMd2Model(e.path):e.path.endsWith(".md3")&&(r=await this.loadMd3Model(e.path));break;case"sprite":r=await this.loadSprite(e.path);break;case"map":r=await this.loadMap(e.path);break;default:throw new Error(`Unknown asset type ${e.type}`)}e.resolve(r)}catch(r){e.reject(r)}finally{this.activeLoads--,this.processQueue()}}detectAssetType(e){let r=e.split(".").pop()?.toLowerCase();return r?["wal","pcx","tga","png","jpg"].includes(r)?"texture":["wav","ogg"].includes(r)?"sound":["md2","md3"].includes(r)?"model":["sp2"].includes(r)?"sprite":["bsp"].includes(r)?"map":null:null}makeKey(e,r){return`${e}:${ae(r)}`}};var ls=class{constructor(e){this.factory=e}getContext(){return this.context||(this.context=this.factory()),this.context}async resume(){let e=this.getContext();e.state==="suspended"&&await e.resume()}getState(){return this.context?.state??"suspended"}};function cs(t){let e=t.getContext(),r=e.createGain();r.gain.value=1;let n=e.createDynamicsCompressor(),i=e.createBiquadFilter?.(),o;if(e.createConvolver&&e.createGain){let a=e.createConvolver(),s=e.createGain(),d=e.createGain();s.connect(a),a.connect(d),o={convolver:a,input:s,output:d}}return i?(i.type="lowpass",i.frequency.value=2e4,i.Q.value=.707,r.connect(i),i.connect(n),o&&o.output.connect(i)):(r.connect(n),o&&o.output.connect(n)),n.connect(e.destination),{context:e,master:r,compressor:n,filter:i,reverb:o}}var ds=class{constructor(e=new Fn){this.configStrings=e;this.buffers=new Map}registerName(e){return this.configStrings.soundIndex(e)}register(e,r){let n=this.registerName(e);return this.buffers.set(n,r),n}find(e){return this.configStrings.findSoundIndex(e)}get(e){return this.buffers.get(e)}has(e){return this.buffers.has(e)}getName(e){return this.configStrings.getName(e)}};var us=class{constructor(e){this.vfs=e.vfs,this.registry=e.registry,this.contextController=e.context,this.soundRoot=e.soundRoot??"sound/",this.decodeAudio=e.decodeAudio??((r,n)=>{if(!r.decodeAudioData)throw new Error("decodeAudioData is not available on the provided audio context");return r.decodeAudioData(n)})}async precache(e){let r=[...new Set(e.map(o=>this.normalize(o)))],n={loaded:[],skipped:[],missing:[],errors:{}},i=this.contextController.getContext();for(let o of r)try{let a=this.registry.find(o);if(a!==void 0&&this.registry.has(a)){n.skipped.push(o);continue}if(!this.vfs.stat(o)){n.missing.push(o);continue}let l=(await this.vfs.readFile(o)).slice().buffer,c=await this.decodeAudio(i,l);this.registry.register(o,c),n.loaded.push(o)}catch(a){let s=a instanceof Error?a:new Error(String(a));n.errors[o]=s}return n}normalize(e){let r=ae(e.replace(/^\//,""));return r.startsWith(this.soundRoot)?r:ae(`${this.soundRoot}${r}`)}};var up=7,Po=t=>t&up;function fs(t){return Array.from({length:Ti},()=>({entnum:0,entchannel:Ot.Auto,endTimeMs:0,isPlayer:!1,active:!1})).map(e=>({...e,isPlayer:e.entnum===t}))}function hs(t,e,r,n){if(r<0)throw new Error("pickChannel: entchannel must be non-negative");let i=Po(r),o=-1,a=Number.POSITIVE_INFINITY;for(let s=0;s<t.length;s+=1){let d=t[s],l=Po(d.entchannel);if(i!==Ot.Auto&&d.entnum===e&&l===i){o=s;break}if(d.active&&d.entnum===n.playerEntity&&e!==n.playerEntity)continue;let c=d.endTimeMs-n.nowMs;(o===-1||c<a)&&(a=c,o=s)}return o===-1?void 0:o}var ms=class{constructor(e){this.activePreset=null;this.enabled=!0;this.node=e,this.node.input.gain.value=.5,this.node.output.gain.value=1}setPreset(e){this.activePreset=e,this.node.convolver.buffer!==(e?.buffer??null)&&(this.node.convolver.buffer=e?.buffer??null),e&&e.gain!==void 0?this.node.output.gain.value=e.gain:this.node.output.gain.value=1}setEnabled(e){this.enabled=e,e?this.node.input.gain.value=.5:this.node.input.gain.value=0}getOutputNode(){return this.node.output}getInputNode(){return this.node.input}};var ps=class{constructor(e){this.activeSources=new Map;this.playbackRate=1;this.contextController=e.context,this.registry=e.registry,this.playerEntity=e.playerEntity,this.channels=fs(e.playerEntity),this.listener=e.listener??{origin:ud,right:{x:1,y:0,z:0}},this.sfxVolume=e.sfxVolume??1,this.masterVolume=e.masterVolume??1,this.resolveOcclusion=e.resolveOcclusion,this.graph=cs(this.contextController),this.graph.master.gain.value=this.masterVolume,this.graph.reverb&&(this.reverb=new ms(this.graph.reverb))}setListener(e){this.listener=e}setMasterVolume(e){this.masterVolume=e,this.graph.master.gain.value=e}setSfxVolume(e){this.sfxVolume=e}setPlaybackRate(e){this.playbackRate=e;for(let r of this.activeSources.values())r.source.playbackRate&&(r.source.playbackRate.value=e),this.updateSourceGain(r)}async ensureRunning(){await this.contextController.resume()}setReverbPreset(e){this.reverb?.setPreset(e)}play(e){let r=this.registry.get(e.soundIndex);if(!r)return;let n=this.graph.context,i=n.currentTime*1e3,o=hs(this.channels,e.entity,e.channel,{nowMs:i,playerEntity:this.playerEntity});if(o===void 0)return;let a=this.activeSources.get(o);a&&(a.source.onended=null,a.source.stop(),this.activeSources.delete(o));let s=n.createBufferSource();s.buffer=r,s.loop=e.looping??!1,s.playbackRate&&(s.playbackRate.value=this.playbackRate);let d=e.origin??this.listener.origin,l=n.createGain(),c=this.createPanner(n,e.attenuation),f=this.resolveOcclusion?.(this.listener,d,e.attenuation),u=Tu(f?.gainScale??1),h=this.resolveOcclusion?this.createOcclusionFilter(n,f?.lowpassHz??2e4):void 0;this.applyOriginToPanner(c,d);let g=e.volume/255*this.sfxVolume,p=Math.abs(this.playbackRate-1)<.001?1:0;l.gain.value=g*u*p;let y=n.currentTime+(e.timeOffsetMs??0)/1e3,_=(e.looping?Number.POSITIVE_INFINITY:r.duration*1e3)+y*1e3;s.connect(c);let x=c;h?(c.connect(h),h.connect(l),x=l):(c.connect(l),x=l),l.connect(this.graph.master),this.reverb&&l.connect(this.reverb.getInputNode()),s.start(y),s.onended=()=>{this.channels[o].active=!1,this.activeSources.delete(o)};let b={channelIndex:o,entnum:e.entity,entchannel:Po(e.channel),endTimeMs:_,source:s,panner:c,gain:l,baseGain:g,origin:d,attenuation:e.attenuation,occlusion:h?{scale:u,lowpassHz:f?.lowpassHz,filter:h}:f?{scale:u,lowpassHz:f.lowpassHz}:void 0};return this.channels[o]={entnum:e.entity,entchannel:Po(e.channel),endTimeMs:_,isPlayer:e.entity===this.playerEntity,active:!0},this.activeSources.set(o,b),b}stop(e){let r=this.activeSources.get(e);r&&(r.source.stop(),this.channels[e].active=!1,this.activeSources.delete(e))}stopEntitySounds(e){for(let[r,n]of[...this.activeSources.entries()])n.entnum===e&&(n.source.stop(),this.channels[r].active=!1,this.activeSources.delete(r))}updateEntityPosition(e,r){for(let n of this.activeSources.values())if(n.entnum===e&&(this.applyOriginToPanner(n.panner,r),n.origin=r,this.resolveOcclusion)){let i=this.resolveOcclusion(this.listener,r,n.attenuation);this.applyOcclusion(n,i)}}positionedSound(e,r,n,i){return this.play({entity:0,channel:Ot.Auto,soundIndex:r,volume:n,attenuation:i,origin:e})}ambientSound(e,r,n){return this.play({entity:0,channel:Ot.Auto,soundIndex:r,volume:n,attenuation:Ci,origin:e,looping:!0})}getChannelState(e){return this.channels[e]}getDiagnostics(){return{activeChannels:this.activeSources.size,masterVolume:this.masterVolume,sfxVolume:this.sfxVolume,channels:[...this.channels],activeSounds:[...this.activeSources.values()].map(e=>({entnum:e.entnum,entchannel:e.entchannel,channelIndex:e.channelIndex,origin:e.origin,gain:e.gain.gain.value,baseGain:e.baseGain,attenuation:e.attenuation,maxDistance:e.panner.maxDistance,distanceModel:e.panner.distanceModel,occlusion:e.occlusion?{scale:e.occlusion.scale,lowpassHz:e.occlusion.lowpassHz}:void 0}))}}setUnderwater(e,r=400){let n=this.graph.filter;n&&(n.type="lowpass",n.Q.value=.707,n.frequency.value=e?r:2e4)}createPanner(e,r){let n=e.createPanner?e.createPanner():Object.assign(e.createGain(),{positionX:{value:this.listener.origin.x},positionY:{value:this.listener.origin.y},positionZ:{value:this.listener.origin.z}});return this.configurePanner(n,r)}configurePanner(e,r){let n=Rn(r);return e.refDistance=In,e.maxDistance=Jr(r),e.rolloffFactor=n,e.distanceModel="linear",e.positionX.value=this.listener.origin.x,e.positionY.value=this.listener.origin.y,e.positionZ.value=this.listener.origin.z,e}applyOriginToPanner(e,r){e.positionX.value=r.x,e.positionY.value=r.y,e.positionZ.value=r.z}createOcclusionFilter(e,r){if(!e.createBiquadFilter)return;let n=e.createBiquadFilter();return n.type="lowpass",n.Q.value=.707,n.frequency.value=$l(r,10,2e4),n}updateSourceGain(e){let r=e.occlusion?.scale??1,n=Math.abs(this.playbackRate-1)<.001?1:0;e.gain.gain.value=e.baseGain*r*n}applyOcclusion(e,r){let n=Tu(r?.gainScale??1),i=Math.abs(this.playbackRate-1)<.001?1:0;if(e.gain.gain.value=e.baseGain*n*i,e.occlusion?.filter){let o=r?.lowpassHz??2e4;e.occlusion.filter.frequency.value=$l(o,10,2e4)}e.occlusion?(e.occlusion.scale=n,e.occlusion.lowpassHz=r?.lowpassHz):r&&(e.occlusion={scale:n,lowpassHz:r.lowpassHz})}},$l=(t,e,r)=>Math.min(r,Math.max(e,t)),Tu=t=>$l(t,0,1);var Bo=class{constructor(e){this.trace=e;this.resolve=(e,r,n)=>{let i=tl(fd(r,e.origin)),o=Jr(n),d=2e4*(1-Math.min(i,o)/Math.max(1,o)*.9),l=this.trace(e.origin,r,void 0,void 0),c=1,f=2e4;l.fraction<1&&(c=.3,f=400);let u=Math.min(d,f);if(c<1||u<2e4)return{gainScale:c,lowpassHz:u}}}};function Cu(t){return new Bo(t).resolve}var gs=class{constructor(e){this.createElement=e.createElement,this.resolveSource=e.resolveSource??(async r=>r),this.volume=e.volume??1,this.crossfadeDuration=e.crossfadeDuration??1}async playTrack(e){let r=`music/track${e.toString().padStart(2,"0")}.ogg`;return this.play(r)}async play(e,{loop:r=!0,restart:n=!1}={}){if(this.track===e&&this.currentElement){this.currentElement.loop=r,this.cancelFade(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.currentElement.volume=this.volume,n&&(this.currentElement.currentTime=0),(this.currentElement.paused||n)&&await this.currentElement.play();return}let i=await this.resolveSource(e);this.cancelFade(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.currentElement&&(this.fadingElement=this.currentElement,this.currentElement=void 0);let o=this.createElement();o.src=i,o.loop=r,o.volume=0,o.currentTime=0,o.load();try{await o.play()}catch(a){console.warn(`MusicSystem: Failed to play ${e}`,a),this.fadingElement}this.currentElement=o,this.track=e,this.startCrossfade()}pause(){this.cancelFade(),this.currentElement&&!this.currentElement.paused&&this.currentElement.pause(),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0)}async resume(){!this.currentElement||!this.currentElement.paused||(await this.currentElement.play(),this.currentElement.volume=this.volume)}stop(){this.cancelFade(),this.currentElement&&(this.currentElement.pause(),this.currentElement.currentTime=0,this.currentElement=void 0),this.fadingElement&&(this.fadingElement.pause(),this.fadingElement=void 0),this.track=void 0}setVolume(e){this.volume=e,this.currentElement&&!this.fadeInterval&&(this.currentElement.volume=e)}getState(){let e=!!(this.currentElement&&!this.currentElement.paused&&!this.currentElement.ended),r=!!this.currentElement?.paused;return{track:this.track,paused:r,playing:e,volume:this.volume}}startCrossfade(){let r=this.crossfadeDuration*1e3/50,n=this.volume/r,i=0,o=this.fadingElement?this.fadingElement.volume:0,a=()=>{let s=!1;this.currentElement&&(i=Math.min(this.volume,i+n),this.currentElement.volume=i,i<this.volume&&(s=!0)),this.fadingElement&&(o=Math.max(0,o-n),this.fadingElement.volume=o,o>0?s=!0:(this.fadingElement.pause(),this.fadingElement=void 0)),s||this.cancelFade()};a(),(this.currentElement&&this.currentElement.volume<this.volume||this.fadingElement)&&(this.fadeInterval=setInterval(a,50))}cancelFade(){this.fadeInterval&&(clearInterval(this.fadeInterval),this.fadeInterval=void 0)}};function fp(t){t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.enable(t.CULL_FACE),t.cullFace(t.BACK),t.enable(t.BLEND),t.blendFuncSeparate(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA)}function hp(t,e,r,n){for(let i of e){let o=t.getExtension(i);if(!o)throw new Error(`Missing required WebGL extension: ${i}`);n.set(i,o)}for(let i of r){let o=t.getExtension(i);o&&n.set(i,o)}}function Iu(t,e={}){let{contextAttributes:r,requiredExtensions:n=[],optionalExtensions:i=[]}=e,o=t.getContext("webgl2",r??{antialias:!0});if(!o)throw new Error("WebGL2 not supported or failed to initialize");fp(o);let a=new Map;hp(o,n,i,a);let s=!1,d=new Set,l=new Set,c=u=>{s=!0,u.preventDefault();for(let h of d)h()},f=()=>{s=!1;for(let u of l)u()};return t.addEventListener("webglcontextlost",c),t.addEventListener("webglcontextrestored",f),{gl:o,extensions:a,isLost:()=>s,onLost(u){return d.add(u),()=>d.delete(u)},onRestored(u){return l.add(u),()=>l.delete(u)},dispose(){t.removeEventListener("webglcontextlost",c),t.removeEventListener("webglcontextrestored",f),d.clear(),l.clear(),a.clear()}}}function Ru(t,e,r){let n=t.createShader(e);if(!n)throw new Error("Failed to allocate shader");if(t.shaderSource(n,r.trim()),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){let o=t.getShaderInfoLog(n)??"Unknown shader compile failure";throw t.deleteShader(n),new Error(o)}return n}function mp(t,e,r,n){let i=t.createProgram();if(!i)throw new Error("Failed to allocate shader program");if(t.attachShader(i,e),t.attachShader(i,r),n)for(let[a,s]of Object.entries(n))t.bindAttribLocation(i,s,a);if(t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){let a=t.getProgramInfoLog(i)??"Unknown shader link failure";throw t.deleteProgram(i),new Error(a)}return i}var ve=class t{constructor(e,r,n){this.uniformLocations=new Map;this.attributeLocations=new Map;this.gl=e,this.program=r,this.sourceSize=n}static create(e,r,n){let i=Ru(e,e.VERTEX_SHADER,r.vertex),o=Ru(e,e.FRAGMENT_SHADER,r.fragment);try{let a=mp(e,i,o,n),s=r.vertex.length+r.fragment.length;return new t(e,a,s)}finally{e.deleteShader(i),e.deleteShader(o)}}use(){this.gl.useProgram(this.program)}getUniformLocation(e){if(!this.uniformLocations.has(e)){let r=this.gl.getUniformLocation(this.program,e);this.uniformLocations.set(e,r)}return this.uniformLocations.get(e)??null}getAttributeLocation(e){if(!this.attributeLocations.has(e)){let r=this.gl.getAttribLocation(this.program,e);this.attributeLocations.set(e,r)}return this.attributeLocations.get(e)??-1}dispose(){this.gl.deleteProgram(this.program),this.uniformLocations.clear(),this.attributeLocations.clear()}};function ku(t,e,r){return ve.create(t,e,r)}var Se=class{constructor(e,r=e.STATIC_DRAW,n){this.gl=e,this.target=n??e.ARRAY_BUFFER;let i=e.createBuffer();if(!i)throw new Error("Failed to allocate buffer");this.buffer=i,e.bindBuffer(this.target,this.buffer),e.bufferData(this.target,0,r)}bind(){this.gl.bindBuffer(this.target,this.buffer)}upload(e,r=this.gl.STATIC_DRAW){this.bind(),this.gl.bufferData(this.target,e,r)}update(e,r=0){this.bind(),this.gl.bufferSubData(this.target,r,e)}dispose(){this.gl.deleteBuffer(this.buffer)}},Te=class extends Se{constructor(e,r=e.STATIC_DRAW){super(e,r,e.ELEMENT_ARRAY_BUFFER)}},Ce=class{constructor(e){this.gl=e;let r=e.createVertexArray();if(!r)throw new Error("Failed to allocate vertex array object");this.vao=r}bind(){this.gl.bindVertexArray(this.vao)}configureAttributes(e,r){this.bind(),r&&r.bind();for(let n of e)this.gl.enableVertexAttribArray(n.index),this.gl.vertexAttribPointer(n.index,n.size,n.type,n.normalized??!1,n.stride??0,n.offset??0),n.divisor!==void 0&&this.gl.vertexAttribDivisor(n.index,n.divisor)}dispose(){this.gl.deleteVertexArray(this.vao)}},Ur=class{constructor(e,r=e.TEXTURE_2D){this.width=0;this.height=0;this.gl=e,this.target=r;let n=e.createTexture();if(!n)throw new Error("Failed to allocate texture");this.texture=n}bind(e=0){this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.target,this.texture)}setParameters(e){this.bind(),e.wrapS!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_S,e.wrapS),e.wrapT!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_T,e.wrapT),e.minFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MIN_FILTER,e.minFilter),e.magFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MAG_FILTER,e.magFilter)}upload(e,r,n){this.width=e,this.height=r,this.uploadImage(0,this.gl.RGBA,e,r,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n)}uploadImage(e,r,n,i,o,a,s,d){this.bind(),this.gl.texImage2D(this.target,e,r,n,i,o,a,s,d)}dispose(){this.gl.deleteTexture(this.texture)}},ai=class{constructor(e){this.gl=e,this.target=e.TEXTURE_CUBE_MAP;let r=e.createTexture();if(!r)throw new Error("Failed to allocate cubemap texture");this.texture=r}bind(e=0){this.gl.activeTexture(this.gl.TEXTURE0+e),this.gl.bindTexture(this.target,this.texture)}setParameters(e){this.bind(),e.wrapS!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_S,e.wrapS),e.wrapT!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_WRAP_T,e.wrapT),e.minFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MIN_FILTER,e.minFilter),e.magFilter!==void 0&&this.gl.texParameteri(this.target,this.gl.TEXTURE_MAG_FILTER,e.magFilter)}uploadFace(e,r,n,i,o,a,s,d,l){this.bind(),this.gl.texImage2D(e,r,n,i,o,a,s,d,l)}dispose(){this.gl.deleteTexture(this.texture)}},ys=class{constructor(e){this.gl=e;let r=e.createFramebuffer();if(!r)throw new Error("Failed to allocate framebuffer");this.framebuffer=r}bind(e=this.gl.FRAMEBUFFER){this.gl.bindFramebuffer(e,this.framebuffer)}attachTexture2D(e,r,n=0){this.bind(),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,e,r.target,r.texture,n)}dispose(){this.gl.deleteFramebuffer(this.framebuffer)}};var Yl=4,Zl=7*Yl,ql=[{index:0,size:3,type:5126,stride:Zl,offset:0},{index:1,size:2,type:5126,stride:Zl,offset:3*Yl},{index:2,size:2,type:5126,stride:Zl,offset:5*Yl}];function pp(t,e){return{width:t,height:t,padding:e,data:new Uint8Array(t*t*4),cursorX:0,cursorY:0,rowHeight:0}}function gp(t){let e=t.width*t.height;if(e===0)throw new Error("Invalid lightmap with zero area");let r=t.samples.byteLength/e;if(!Number.isInteger(r)||r<3||r>4)throw new Error("Unsupported lightmap channel count");return r}function yp(t,e,r){let n=gp(r),i=t.width*4,o=e.x+t.padding,a=e.y+t.padding,s=0;for(let d=0;d<r.height;d++){let l=(a+d)*i+o*4;for(let c=0;c<r.width;c++){let f=l+c*4;t.data[f]=r.samples[s],t.data[f+1]=r.samples[s+1],t.data[f+2]=r.samples[s+2],t.data[f+3]=n===4?r.samples[s+3]:255,s+=n}}}function bp(t,e,r){let n=e.width+r.lightmapPadding*2,i=e.height+r.lightmapPadding*2;if(n>r.atlasSize||i>r.atlasSize)throw new Error("Lightmap too large for atlas");for(let s of t){if(s.cursorX+n>s.width&&(s.cursorX=0,s.cursorY+=s.rowHeight+r.lightmapPadding,s.rowHeight=0),s.cursorY+i>s.height)continue;let d={atlasIndex:t.indexOf(s),x:s.cursorX,y:s.cursorY,width:e.width,height:e.height};return s.cursorX+=n+r.lightmapPadding,s.rowHeight=Math.max(s.rowHeight,i),{placement:d,atlas:s}}let o=pp(r.atlasSize,r.lightmapPadding);t.push(o);let a={atlasIndex:t.length-1,x:0,y:0,width:e.width,height:e.height};return o.cursorX=n+r.lightmapPadding,o.rowHeight=i,{placement:a,atlas:o}}function bs(t){return t instanceof Float32Array?t:new Float32Array(t)}function xp(t,e){if(!t){let n=new Uint16Array(e);for(let i=0;i<e;i++)n[i]=i;return n}return t instanceof Uint16Array?t:new Uint16Array(t)}function _p(t,e){let r=new Float32Array(t.length);for(let n=0;n<t.length;n+=2)r[n]=e.offset[0]+t[n]*e.scale[0],r[n+1]=e.offset[1]+t[n+1]*e.scale[1];return r}function vp(t,e){let r=bs(t.vertices),n=bs(t.textureCoords),i=e?_p(bs(t.lightmapCoords??t.textureCoords),e):bs(t.lightmapCoords??new Float32Array(n.length)),o=r.length/3;if(n.length/2!==o)throw new Error("Texture coordinates count mismatch");if(i.length/2!==o)throw new Error("Lightmap coordinates count mismatch");let a=new Float32Array(o*7);for(let s=0;s<o;s++){let d=s*3,l=s*2,c=s*7;a[c]=r[d],a[c+1]=r[d+1],a[c+2]=r[d+2],a[c+3]=n[l],a[c+4]=n[l+1],a[c+5]=i[l],a[c+6]=i[l+1]}return a}function Pu(t){let e=[];for(let r=0;r<t.faces.length;r++){let n=t.faces[r];if(n.texInfo<0)continue;let i=t.texInfo[n.texInfo],o=[],a=[],s=[];for(let u=0;u<n.numEdges;u++){let h=t.surfEdges[n.firstEdge+u],m=t.edges[Math.abs(h)],g=h>=0?m.vertices[0]:m.vertices[1],p=t.vertices[g];o.push(p[0],p[1],p[2]);let y=p[0]*i.s[0]+p[1]*i.s[1]+p[2]*i.s[2]+i.sOffset,_=p[0]*i.t[0]+p[1]*i.t[1]+p[2]*i.t[2]+i.tOffset;a.push(y,_),s.push(y,_)}let d=[],l=o.length/3;for(let u=1;u<l-1;u++)d.push(0,u,u+1);let c,f=t.lightMapInfo[r];if(f){let u=1/0,h=-1/0,m=1/0,g=-1/0;for(let v=0;v<a.length;v+=2){let w=a[v],S=a[v+1];w<u&&(u=w),w>h&&(h=w),S<m&&(m=S),S>g&&(g=S)}let p=Math.floor(u/16),y=Math.floor(m/16),_=Math.ceil(h/16)-p+1,x=Math.ceil(g/16)-y+1,b=Sa(n,t.lightMaps,f);if(b&&b.length===_*x*3){c={width:_,height:x,samples:b};for(let v=0;v<s.length;v+=2)s[v]=a[v]/16-p+.5,s[v+1]=a[v+1]/16-y+.5}}e.push({vertices:new Float32Array(o),textureCoords:new Float32Array(a),lightmapCoords:new Float32Array(s),indices:new Uint16Array(d),texture:i.texture,surfaceFlags:i.flags,lightmap:c,faceIndex:r})}return e}function Bu(t,e,r,n={}){let i=e;if(r&&n.hiddenClassnames&&n.hiddenClassnames.size>0){let c=new Set;for(let f of r.entities.entities)if(f.classname&&n.hiddenClassnames.has(f.classname)){let u=f.properties.model;if(u&&u.startsWith("*")){let h=parseInt(u.substring(1),10);if(!isNaN(h)&&h>=0&&h<r.models.length){let m=r.models[h];for(let g=0;g<m.numFaces;g++)c.add(m.firstFace+g)}}}c.size>0&&(i=e.filter(f=>!c.has(f.faceIndex)))}let o={atlasSize:n.atlasSize??1024,lightmapPadding:n.lightmapPadding??1,hiddenClassnames:n.hiddenClassnames??new Set},a=[],s=new Map;i.forEach((c,f)=>{if(!c.lightmap)return;let{placement:u,atlas:h}=bp(a,c.lightmap,o);yp(h,u,c.lightmap),s.set(f,{atlasIndex:u.atlasIndex,offset:[(u.x+o.lightmapPadding)/o.atlasSize,(u.y+o.lightmapPadding)/o.atlasSize],scale:[u.width/o.atlasSize,u.height/o.atlasSize]})});let d=a.map(c=>{let f=new Ur(t);return f.setParameters({wrapS:t.CLAMP_TO_EDGE,wrapT:t.CLAMP_TO_EDGE,minFilter:t.LINEAR,magFilter:t.LINEAR}),f.uploadImage(0,t.RGBA,c.width,c.height,0,t.RGBA,t.UNSIGNED_BYTE,c.data),{texture:f,width:c.width,height:c.height,pixels:c.data}});return{surfaces:i.map((c,f)=>{let u=s.get(f),h=vp(c,u),m=xp(c.indices,h.length/7),g=new Se(t,t.STATIC_DRAW,t.ARRAY_BUFFER);g.upload(h);let p=new Te(t,t.STATIC_DRAW);p.upload(m);let y=new Ce(t);return y.configureAttributes(ql,g),{vao:y,vertexBuffer:g,indexBuffer:p,indexCount:m.length,vertexCount:h.length/7,texture:c.texture,surfaceFlags:c.surfaceFlags??Mi,lightmap:u,vertexData:h,indexData:m}}),lightmaps:d}}function si(t){let{normal:e,distance:r}=t,n=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);if(n===0)return t;let i=1/n;return{normal:{x:e.x*i,y:e.y*i,z:e.z*i},distance:r*i}}function Fu(t){if(t.length!==16)throw new Error("View-projection matrix must contain 16 elements");let e=t[0],r=t[4],n=t[8],i=t[12],o=t[1],a=t[5],s=t[9],d=t[13],l=t[2],c=t[6],f=t[10],u=t[14],h=t[3],m=t[7],g=t[11],p=t[15];return[si({normal:{x:h+e,y:m+r,z:g+n},distance:p+i}),si({normal:{x:h-e,y:m-r,z:g-n},distance:p-i}),si({normal:{x:h+o,y:m+a,z:g+s},distance:p+d}),si({normal:{x:h-o,y:m-a,z:g-s},distance:p-d}),si({normal:{x:h+l,y:m+c,z:g+f},distance:p+u}),si({normal:{x:h-l,y:m-c,z:g-f},distance:p-u})]}function Sp(t,e){return t.normal.x*e.x+t.normal.y*e.y+t.normal.z*e.z+t.distance}function Fo(t,e,r){for(let n of r){let i=n.normal.x>=0?e.x:t.x,o=n.normal.y>=0?e.y:t.y,a=n.normal.z>=0?e.z:t.z;if(Sp(n,{x:i,y:o,z:a})<0)return!1}return!0}function Du(t){return t<0}function Ou(t){return-t-1}function zu(t,e){return t.normal[0]*e.x+t.normal[1]*e.y+t.normal[2]*e.z-t.dist}function wp(t,e,r){if(!t||e<0||r<0)return!0;let n=Math.ceil(t.numClusters/8),i=t.clusters[e].pvs,o=Math.floor(r/8),a=1<<r%8;return o<0||o>=n?!1:(i[o]&a)!==0}function Ap(t,e){let r={x:t.mins[0],y:t.mins[1],z:t.mins[2]},n={x:t.maxs[0],y:t.maxs[1],z:t.maxs[2]};return Fo(r,n,e)}function Ql(t,e){let r=0;for(;r>=0;){let n=t.nodes[r],i=t.planes[n.planeIndex],a=zu(i,e)>=0?0:1,s=n.children[a];if(Du(s))return Ou(s);r=s}return-1}function Mp(t,e){let r=t.leafs[e],n=[];for(let i=0;i<r.numLeafFaces;i+=1)n.push(t.leafLists.leafFaces[e][i]);return n}function jl(t,e,r,n,i,o,a,s){if(Du(e)){let h=Ou(e),m=t.leafs[h];if(s&&m.area>=0&&!s.has(m.area)||!wp(t.visibility,i,m.cluster)||!Ap(m,n))return;let g={x:(m.mins[0]+m.maxs[0])*.5,y:(m.mins[1]+m.maxs[1])*.5,z:(m.mins[2]+m.maxs[2])*.5},p=g.x-r.x,y=g.y-r.y,_=g.z-r.z,x=-(p*p+y*y+_*_);for(let b of Mp(t,h))a.has(b)||(a.add(b),o.push({faceIndex:b,leafIndex:h,sortKey:x}));return}let d=t.nodes[e],l=t.planes[d.planeIndex],c=zu(l,r),f=c>=0?d.children[0]:d.children[1],u=c>=0?d.children[1]:d.children[0];Fo({x:d.mins[0],y:d.mins[1],z:d.mins[2]},{x:d.maxs[0],y:d.maxs[1],z:d.maxs[2]},n)&&(jl(t,f,r,n,i,o,a,s),jl(t,u,r,n,i,o,a,s))}function Ep(t,e,r){let n=new Set;if(e<0||e>=t.areas.length)return n;let i=[e];for(n.add(e);i.length>0;){let o=i.pop(),a=t.areas[o];for(let s=0;s<a.numAreaPortals;s++){let d=a.firstAreaPortal+s,l=t.areaPortals[d],c=l.otherArea;(l.portalNumber<=0||r[l.portalNumber])&&!n.has(c)&&(n.add(c),i.push(c))}}return n}function Uu(t,e,r,n){let i=Ql(t,e),o=i>=0?t.leafs[i]:null,a=o?o.cluster:-1,s=o?o.area:-1,d=null;n&&s>=0&&t.areas&&t.areas.length>0&&(d=Ep(t,s,n));let l=[];return jl(t,0,e,r,a,l,new Set,d),l}var Nr=32,xs=class{constructor(){this.lights=[]}addLight(e,r){if(e.key!==void 0){let n=this.lights.findIndex(i=>i.key===e.key);if(n!==-1){this.lights[n]=e;return}}this.lights.push(e)}clear(){this.lights=[]}update(e,r=0){if(this.lights=this.lights.filter(n=>n.die>e),r>0)for(let n of this.lights)n.radiusSpeed!==void 0&&n.radiusSpeed!==0&&(n.intensity+=n.radiusSpeed*r,n.intensity<0&&(n.intensity=0))}getActiveLights(){return this.lights}};function li(t){let e=[];for(let r=0;r<t.length;r+=3){let n=t[r],i=t[r+1],o=t[r+2];e.push(n,i,i,o,o,n)}return t instanceof Uint32Array||Math.max(...e)>65535?new Uint32Array(e):new Uint16Array(e)}var Jl=`#version 300 es
|
|
142
142
|
precision highp float;
|
|
143
143
|
|
|
144
144
|
layout(location = 0) in vec3 a_position;
|