(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function i(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(r){if(r.ep)return;r.ep=!0;const s=i(r);fetch(r.href,s)}})();function vr(t,e){if(!t)throw new Error(e||"loader assertion failed.")}const ga=!!(typeof process!="object"||String(process)!=="[object process]"||process.browser),_c=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version);_c&&parseFloat(_c[1]);const Ac=globalThis,yc=globalThis.process||{},kp=globalThis.navigator||{};function Eu(t){if(typeof window<"u"&&window.process?.type==="renderer"||typeof process<"u"&&process.versions?.electron)return!0;const i=typeof navigator<"u"&&navigator.userAgent;return!!(i&&i.indexOf("Electron")>=0)}function ei(){return!(typeof process=="object"&&String(process)==="[object process]"&&!process?.browser)||Eu()}function Lp(t){return ei()?Eu()?"Electron":(kp.userAgent||"").indexOf("Edge")>-1?"Edge":globalThis.chrome?"Chrome":globalThis.safari?"Safari":globalThis.mozInnerScreenX?"Firefox":"Unknown":"Node"}const Su="4.1.1";function ma(t,e){if(!t)throw new Error("Assertion failed")}function Ru(t){if(!t)return 0;let e;switch(typeof t){case"number":e=t;break;case"object":e=t.logLevel||t.priority||0;break;default:return 0}return ma(Number.isFinite(e)&&e>=0),e}function Wp(t){const{logLevel:e,message:i}=t;t.logLevel=Ru(e);const n=t.args?Array.from(t.args):[];for(;n.length&&n.shift()!==i;);switch(typeof e){case"string":case"function":i!==void 0&&n.unshift(i),t.message=e;break;case"object":Object.assign(t,e);break}typeof t.message=="function"&&(t.message=t.message());const r=typeof t.message;return ma(r==="string"||r==="object"),Object.assign(t,{args:n},t.opts)}const gi=()=>{};class Vp{constructor({level:e=0}={}){this.userData={},this._onceCache=new Set,this._level=e}set level(e){this.setLevel(e)}get level(){return this.getLevel()}setLevel(e){return this._level=e,this}getLevel(){return this._level}warn(e,...i){return this._log("warn",0,e,i,{once:!0})}error(e,...i){return this._log("error",0,e,i)}log(e,i,...n){return this._log("log",e,i,n)}info(e,i,...n){return this._log("info",e,i,n)}once(e,i,...n){return this._log("once",e,i,n,{once:!0})}_log(e,i,n,r,s={}){const o=Wp({logLevel:i,message:n,args:this._buildArgs(i,n,r),opts:s});return this._createLogFunction(e,o,s)}_buildArgs(e,i,n){return[e,i,...n]}_createLogFunction(e,i,n){if(!this._shouldLog(i.logLevel))return gi;const r=this._getOnceTag(n.tag??i.tag??i.message);if((n.once||i.once)&&r!==void 0){if(this._onceCache.has(r))return gi;this._onceCache.add(r)}return this._emit(e,i)}_shouldLog(e){return this.getLevel()>=Ru(e)}_getOnceTag(e){if(e!==void 0)try{return typeof e=="string"?e:String(e)}catch{return}}}function zp(t){try{const e=window[t],i="__storage_test__";return e.setItem(i,i),e.removeItem(i),e}catch{return null}}class jp{constructor(e,i,n="sessionStorage"){this.storage=zp(n),this.id=e,this.config=i,this._loadConfiguration()}getConfiguration(){return this.config}setConfiguration(e){if(Object.assign(this.config,e),this.storage){const i=JSON.stringify(this.config);this.storage.setItem(this.id,i)}}_loadConfiguration(){let e={};if(this.storage){const i=this.storage.getItem(this.id);e=i?JSON.parse(i):{}}return Object.assign(this.config,e),this}}function Hp(t){let e;return t<10?e=`${t.toFixed(2)}ms`:t<100?e=`${t.toFixed(1)}ms`:t<1e3?e=`${t.toFixed(0)}ms`:e=`${(t/1e3).toFixed(2)}s`,e}function Yp(t,e=8){const i=Math.max(e-t.length,0);return`${" ".repeat(i)}${t}`}var Cr;(function(t){t[t.BLACK=30]="BLACK",t[t.RED=31]="RED",t[t.GREEN=32]="GREEN",t[t.YELLOW=33]="YELLOW",t[t.BLUE=34]="BLUE",t[t.MAGENTA=35]="MAGENTA",t[t.CYAN=36]="CYAN",t[t.WHITE=37]="WHITE",t[t.BRIGHT_BLACK=90]="BRIGHT_BLACK",t[t.BRIGHT_RED=91]="BRIGHT_RED",t[t.BRIGHT_GREEN=92]="BRIGHT_GREEN",t[t.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",t[t.BRIGHT_BLUE=94]="BRIGHT_BLUE",t[t.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",t[t.BRIGHT_CYAN=96]="BRIGHT_CYAN",t[t.BRIGHT_WHITE=97]="BRIGHT_WHITE"})(Cr||(Cr={}));const Xp=10;function bc(t){return typeof t!="string"?t:(t=t.toUpperCase(),Cr[t]||Cr.WHITE)}function Qp(t,e,i){return!ei&&typeof t=="string"&&(e&&(t=`\x1B[${bc(e)}m${t}\x1B[39m`),i&&(t=`\x1B[${bc(i)+Xp}m${t}\x1B[49m`)),t}function Kp(t,e=["constructor"]){const i=Object.getPrototypeOf(t),n=Object.getOwnPropertyNames(i),r=t;for(const s of n){const o=r[s];typeof o=="function"&&(e.find(a=>s===a)||(r[s]=o.bind(t)))}}function Vi(){let t;if(ei()&&Ac.performance)t=Ac?.performance?.now?.();else if("hrtime"in yc){const e=yc?.hrtime?.();t=e[0]*1e3+e[1]/1e6}else t=Date.now();return t}const li={debug:ei()&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},ps={enabled:!0,level:0};class Sn extends Vp{constructor({id:e}={id:""}){super({level:0}),this.VERSION=Su,this._startTs=Vi(),this._deltaTs=Vi(),this.userData={},this.LOG_THROTTLE_TIMEOUT=0,this.id=e,this.userData={},this._storage=new jp(`__probe-${this.id}__`,{[this.id]:ps}),this.timeStamp(`${this.id} started`),Kp(this),Object.seal(this)}isEnabled(){return this._getConfiguration().enabled}getLevel(){return this._getConfiguration().level}getTotal(){return Number((Vi()-this._startTs).toPrecision(10))}getDelta(){return Number((Vi()-this._deltaTs).toPrecision(10))}set priority(e){this.level=e}get priority(){return this.level}getPriority(){return this.level}enable(e=!0){return this._updateConfiguration({enabled:e}),this}setLevel(e){return this._updateConfiguration({level:e}),this}get(e){return this._getConfiguration()[e]}set(e,i){this._updateConfiguration({[e]:i})}settings(){console.table?console.table(this._storage.config):console.log(this._storage.config)}assert(e,i){if(!e)throw new Error(i||"Assertion failed")}warn(e,...i){return this._log("warn",0,e,i,{method:li.warn,once:!0})}error(e,...i){return this._log("error",0,e,i,{method:li.error})}deprecated(e,i){return this.warn(`\`${e}\` is deprecated and will be removed in a later version. Use \`${i}\` instead`)}removed(e,i){return this.error(`\`${e}\` has been removed. Use \`${i}\` instead`)}probe(e,i,...n){return this._log("log",e,i,n,{method:li.log,time:!0,once:!0})}log(e,i,...n){return this._log("log",e,i,n,{method:li.debug})}info(e,i,...n){return this._log("info",e,i,n,{method:console.info})}once(e,i,...n){return this._log("once",e,i,n,{method:li.debug||li.info,once:!0})}table(e,i,n){return i?this._log("table",e,i,n&&[n]||[],{method:console.table||gi,tag:Zp(i)}):gi}time(e,i){return this._log("time",e,i,[],{method:console.time?console.time:console.info})}timeEnd(e,i){return this._log("time",e,i,[],{method:console.timeEnd?console.timeEnd:console.info})}timeStamp(e,i){return this._log("time",e,i,[],{method:console.timeStamp||gi})}group(e,i,n={collapsed:!1}){const r=(n.collapsed?console.groupCollapsed:console.group)||console.info;return this._log("group",e,i,[],{method:r})}groupCollapsed(e,i,n={}){return this.group(e,i,Object.assign({},n,{collapsed:!0}))}groupEnd(e){return this._log("groupEnd",e,"",[],{method:console.groupEnd||gi})}withGroup(e,i,n){this.group(e,i)();try{n()}finally{this.groupEnd(e)()}}trace(){console.trace&&console.trace()}_shouldLog(e){return this.isEnabled()&&super._shouldLog(e)}_emit(e,i){const n=i.method;ma(n),i.total=this.getTotal(),i.delta=this.getDelta(),this._deltaTs=Vi();const r=qp(this.id,i.message,i);return n.bind(console,r,...i.args)}_getConfiguration(){return this._storage.config[this.id]||this._updateConfiguration(ps),this._storage.config[this.id]}_updateConfiguration(e){const i=this._storage.config[this.id]||{...ps};this._storage.setConfiguration({[this.id]:{...i,...e}})}}Sn.VERSION=Su;function qp(t,e,i){if(typeof e=="string"){const n=i.time?Yp(Hp(i.total)):"";e=i.time?`${t}: ${n} ${e}`:`${t}: ${e}`,e=Qp(e,i.color,i.background)}return e}function Zp(t){for(const e in t)for(const i in t[e])return i||"untitled";return"empty"}const gs="4.4.2",Gp=gs[0]>="0"&&gs[0]<="9"?`v${gs}`:"";function Jp(){const t=new Sn({id:"loaders.gl"});return globalThis.loaders||={},globalThis.loaders.log=t,globalThis.loaders.version=Gp,globalThis.probe||={},globalThis.probe.loaders=t,t}const $p=Jp(),eg=t=>typeof t=="boolean",tt=t=>typeof t=="function",ti=t=>t!==null&&typeof t=="object",wc=t=>ti(t)&&t.constructor==={}.constructor,vu=t=>typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer,_a=t=>ti(t)&&typeof t.byteLength=="number"&&typeof t.slice=="function",tg=t=>!!t&&tt(t[Symbol.iterator]),ig=t=>!!t&&tt(t[Symbol.asyncIterator]),ii=t=>typeof Response<"u"&&t instanceof Response||ti(t)&&tt(t.arrayBuffer)&&tt(t.text)&&tt(t.json),ni=t=>typeof Blob<"u"&&t instanceof Blob,ng=t=>typeof ReadableStream<"u"&&t instanceof ReadableStream||ti(t)&&tt(t.tee)&&tt(t.cancel)&&tt(t.getReader),rg=t=>ti(t)&&tt(t.read)&&tt(t.pipe)&&eg(t.readable),Cu=t=>ng(t)||rg(t);function sg(t,e){return Pu(t||{},e)}function Pu(t,e,i=0){if(i>3)return e;const n={...t};for(const[r,s]of Object.entries(e))s&&typeof s=="object"&&!Array.isArray(s)?n[r]=Pu(n[r]||{},e[r],i+1):n[r]=e[r];return n}const og="latest";function ag(){return globalThis._loadersgl_?.version||(globalThis._loadersgl_=globalThis._loadersgl_||{},globalThis._loadersgl_.version="4.4.2"),globalThis._loadersgl_.version}const cg=ag();function Rt(t,e){if(!t)throw new Error(e||"loaders.gl assertion failed.")}const Wt=typeof process!="object"||String(process)!=="[object process]"||process.browser,lg=typeof window<"u"&&typeof window.orientation<"u",Tc=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version);Tc&&parseFloat(Tc[1]);class fg{name;workerThread;isRunning=!0;result;_resolve=()=>{};_reject=()=>{};constructor(e,i){this.name=e,this.workerThread=i,this.result=new Promise((n,r)=>{this._resolve=n,this._reject=r})}postMessage(e,i){this.workerThread.postMessage({source:"loaders.gl",type:e,payload:i})}done(e){Rt(this.isRunning),this.isRunning=!1,this._resolve(e)}error(e){Rt(this.isRunning),this.isRunning=!1,this._reject(e)}}class ms{terminate(){}}const _s=new Map;function ug(t){Rt(t.source&&!t.url||!t.source&&t.url);let e=_s.get(t.source||t.url);return e||(t.url&&(e=hg(t.url),_s.set(t.url,e)),t.source&&(e=Iu(t.source),_s.set(t.source,e))),Rt(e),e}function hg(t){if(!t.startsWith("http"))return t;const e=dg(t);return Iu(e)}function Iu(t){const e=new Blob([t],{type:"application/javascript"});return URL.createObjectURL(e)}function dg(t){return`try { importScripts('${t}'); } catch (error) { console.error(error); throw error; }`}function xu(t,e=!0,i){const n=i||new Set;if(t){if(Ec(t))n.add(t);else if(Ec(t.buffer))n.add(t.buffer);else if(!ArrayBuffer.isView(t)){if(e&&typeof t=="object")for(const r in t)xu(t[r],e,n)}}return i===void 0?Array.from(n):[]}function Ec(t){return t?t instanceof ArrayBuffer||typeof MessagePort<"u"&&t instanceof MessagePort||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas:!1}const As=()=>{};class lo{name;source;url;terminated=!1;worker;onMessage;onError;_loadableURL="";static isSupported(){return typeof Worker<"u"&&Wt||typeof ms<"u"&&!Wt}constructor(e){const{name:i,source:n,url:r}=e;Rt(n||r),this.name=i,this.source=n,this.url=r,this.onMessage=As,this.onError=s=>console.log(s),this.worker=Wt?this._createBrowserWorker():this._createNodeWorker()}destroy(){this.onMessage=As,this.onError=As,this.worker.terminate(),this.terminated=!0}get isRunning(){return!!this.onMessage}postMessage(e,i){i=i||xu(e),this.worker.postMessage(e,i)}_getErrorFromErrorEvent(e){let i="Failed to load ";return i+=`worker ${this.name} from ${this.url}. `,e.message&&(i+=`${e.message} in `),e.lineno&&(i+=`:${e.lineno}:${e.colno}`),new Error(i)}_createBrowserWorker(){this._loadableURL=ug({source:this.source,url:this.url});const e=new Worker(this._loadableURL,{name:this.name});return e.onmessage=i=>{i.data?this.onMessage(i.data):this.onError(new Error("No data received"))},e.onerror=i=>{this.onError(this._getErrorFromErrorEvent(i)),this.terminated=!0},e.onmessageerror=i=>console.error(i),e}_createNodeWorker(){let e;if(this.url){const n=this.url.includes(":/")||this.url.startsWith("/")?this.url:`./${this.url}`,r=this.url.endsWith(".ts")||this.url.endsWith(".mjs")?"module":"commonjs";e=new ms(n,{eval:!1,type:r})}else if(this.source)e=new ms(this.source,{eval:!0});else throw new Error("no worker");return e.on("message",i=>{this.onMessage(i)}),e.on("error",i=>{this.onError(i)}),e.on("exit",i=>{}),e}}class pg{name="unnamed";source;url;maxConcurrency=1;maxMobileConcurrency=1;onDebug=()=>{};reuseWorkers=!0;props={};jobQueue=[];idleQueue=[];count=0;isDestroyed=!1;static isSupported(){return lo.isSupported()}constructor(e){this.source=e.source,this.url=e.url,this.setProps(e)}destroy(){this.idleQueue.forEach(e=>e.destroy()),this.isDestroyed=!0}setProps(e){this.props={...this.props,...e},e.name!==void 0&&(this.name=e.name),e.maxConcurrency!==void 0&&(this.maxConcurrency=e.maxConcurrency),e.maxMobileConcurrency!==void 0&&(this.maxMobileConcurrency=e.maxMobileConcurrency),e.reuseWorkers!==void 0&&(this.reuseWorkers=e.reuseWorkers),e.onDebug!==void 0&&(this.onDebug=e.onDebug)}async startJob(e,i=(r,s,o)=>r.done(o),n=(r,s)=>r.error(s)){const r=new Promise(s=>(this.jobQueue.push({name:e,onMessage:i,onError:n,onStart:s}),this));return this._startQueuedJob(),await r}async _startQueuedJob(){if(!this.jobQueue.length)return;const e=this._getAvailableWorker();if(!e)return;const i=this.jobQueue.shift();if(i){this.onDebug({message:"Starting job",name:i.name,workerThread:e,backlog:this.jobQueue.length});const n=new fg(i.name,e);e.onMessage=r=>i.onMessage(n,r.type,r.payload),e.onError=r=>i.onError(n,r),i.onStart(n);try{await n.result}catch(r){console.error(`Worker exception: ${r}`)}finally{this.returnWorkerToQueue(e)}}}returnWorkerToQueue(e){!Wt||this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}_getAvailableWorker(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count{}};class yt{props;workerPools=new Map;static _workerFarm;static isSupported(){return lo.isSupported()}static getWorkerFarm(e={}){return yt._workerFarm=yt._workerFarm||new yt({}),yt._workerFarm.setProps(e),yt._workerFarm}constructor(e){this.props={...gg},this.setProps(e),this.workerPools=new Map}destroy(){for(const e of this.workerPools.values())e.destroy();this.workerPools=new Map}setProps(e){this.props={...this.props,...e};for(const i of this.workerPools.values())i.setProps(this._getWorkerPoolProps())}getWorkerPool(e){const{name:i,source:n,url:r}=e;let s=this.workerPools.get(i);return s||(s=new pg({name:i,source:n,url:r}),s.setProps(this._getWorkerPoolProps()),this.workerPools.set(i,s)),s}_getWorkerPoolProps(){return{maxConcurrency:this.props.maxConcurrency,maxMobileConcurrency:this.props.maxMobileConcurrency,reuseWorkers:this.props.reuseWorkers,onDebug:this.props.onDebug}}}function mg(t,e={}){const i=e[t.id]||{},n=Wt?`${t.id}-worker.js`:`${t.id}-worker-node.js`;let r=i.workerUrl;if(!r&&t.id==="compression"&&(r=e.workerUrl),(e._workerType||e?.core?._workerType)==="test"&&(Wt?r=`modules/${t.module}/dist/${n}`:r=`modules/${t.module}/src/workers/${t.id}-worker-node.ts`),!r){let o=t.version;o==="latest"&&(o=og);const a=o?`@${o}`:"";r=`https://unpkg.com/@loaders.gl/${t.module}${a}/dist/${n}`}return Rt(r),r}function _g(t,e=cg){Rt(t,"no worker provided");const i=t.version;return!(!e||!i)}function Ag(t,e){if(!yt.isSupported())return!1;const i=e?._nodeWorkers??e?.core?._nodeWorkers;if(!Wt&&!i)return!1;const n=e?.worker??e?.core?.worker;return!!(t.worker&&n)}async function yg(t,e,i,n,r){const s=t.id,o=mg(t,i),c=yt.getWorkerFarm(i?.core).getWorkerPool({name:s,url:o});i=JSON.parse(JSON.stringify(i)),n=JSON.parse(JSON.stringify(n||{}));const l=await c.startJob("process-on-worker",bg.bind(null,r));return l.postMessage("process",{input:e,options:i,context:n}),await(await l.result).result}async function bg(t,e,i,n){switch(i){case"done":e.done(n);break;case"error":e.error(new Error(n.error));break;case"process":const{id:r,input:s,options:o}=n;try{const a=await t(s,o);e.postMessage("done",{id:r,result:a})}catch(a){const c=a instanceof Error?a.message:"unknown error";e.postMessage("error",{id:r,error:c})}break;default:console.warn(`parse-with-worker unknown message ${i}`)}}function wg(t,e,i){if(i=i||t.byteLength,t.byteLengths instanceof ArrayBuffer?new Uint8Array(s):s),i=e.reduce((s,o)=>s+o.byteLength,0),n=new Uint8Array(i);let r=0;for(const s of e)n.set(s,r),r+=s.byteLength;return n.buffer}async function Sg(t){const e=[];for await(const i of t)e.push(Rg(i));return Tg(...e)}function Rg(t){if(t instanceof ArrayBuffer)return t;if(ArrayBuffer.isView(t)){const{buffer:e,byteOffset:i,byteLength:n}=t;return Sc(e,i,n)}return Sc(t)}function Sc(t,e=0,i=t.byteLength-e){const n=new Uint8Array(t,e,i),r=new Uint8Array(n.length);return r.set(n),r.buffer}function Rc(){let t;if(typeof window<"u"&&window.performance)t=window.performance.now();else if(typeof process<"u"&&process.hrtime){const e=process.hrtime();t=e[0]*1e3+e[1]/1e6}else t=Date.now();return t}class vc{constructor(e,i){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=e,this.type=i,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(e){return this.sampleSize=e,this}incrementCount(){return this.addCount(1),this}decrementCount(){return this.subtractCount(1),this}addCount(e){return this._count+=e,this._samples++,this._checkSampling(),this}subtractCount(e){return this._count-=e,this._samples++,this._checkSampling(),this}addTime(e){return this._time+=e,this.lastTiming=e,this._samples++,this._checkSampling(),this}timeStart(){return this._startTime=Rc(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(Rc()-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)}}class Xr{constructor(e){this.stats={},this.id=e.id,this.stats={},this._initializeStats(e.stats),Object.seal(this)}get(e,i="count"){return this._getOrCreate({name:e,type:i})}get size(){return Object.keys(this.stats).length}reset(){for(const e of Object.values(this.stats))e.reset();return this}forEach(e){for(const i of Object.values(this.stats))e(i)}getTable(){const e={};return this.forEach(i=>{e[i.name]={time:i.time||0,count:i.count||0,average:i.getAverageTime()||0,hz:i.getHz()||0}}),e}_initializeStats(e=[]){e.forEach(i=>this._getOrCreate(i))}_getOrCreate(e){const{name:i,type:n}=e;let r=this.stats[i];return r||(e instanceof vc?r=e:r=new vc(i,n),this.stats[i]=r),r}}let vg="";const Cc={};function Cg(t){for(const e in Cc)if(t.startsWith(e)){const i=Cc[e];t=t.replace(e,i)}return!t.startsWith("http://")&&!t.startsWith("https://")&&(t=`${vg}${t}`),t}function Mu(t){return t&&typeof t=="object"&&t.isBuffer}function Aa(t){if(Mu(t))return t;if(t instanceof ArrayBuffer)return t;if(vu(t))return fo(t);if(ArrayBuffer.isView(t)){const e=t.buffer;return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?e:e.slice(t.byteOffset,t.byteOffset+t.byteLength)}if(typeof t=="string"){const e=t;return new TextEncoder().encode(e).buffer}if(t&&typeof t=="object"&&t._toArrayBuffer)return t._toArrayBuffer();throw new Error("toArrayBuffer")}function Ou(t){if(t instanceof ArrayBuffer)return t;if(vu(t))return fo(t);const{buffer:e,byteOffset:i,byteLength:n}=t;return e instanceof ArrayBuffer&&i===0&&n===e.byteLength?e:fo(e,i,n)}function fo(t,e=0,i=t.byteLength-e){const n=new Uint8Array(t,e,i),r=new Uint8Array(n.length);return r.set(n),r.buffer}function Pg(t){return ArrayBuffer.isView(t)?t:new Uint8Array(t)}function Bu(t){const e=t?t.lastIndexOf("/"):-1;return e>=0?t.substr(e+1):t}function Nu(t){const e=t?t.lastIndexOf("/"):-1;return e>=0?t.substr(0,e):""}class Ig extends Error{constructor(e,i){super(e),this.reason=i.reason,this.url=i.url,this.response=i.response}reason;url;response}const xg=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,Mg=/^([-\w.]+\/[-\w.+]+)/;function Pc(t,e){return t.toLowerCase()===e.toLowerCase()}function Og(t){const e=Mg.exec(t);return e?e[1]:t}function Ic(t){const e=xg.exec(t);return e?e[1]:""}const Du=/\?.*/;function Bg(t){const e=t.match(Du);return e&&e[0]}function Qr(t){return t.replace(Du,"")}function Ng(t){if(t.length<50)return t;const e=t.slice(t.length-15);return`${t.substr(0,32)}...${e}`}function Kr(t){return ii(t)?t.url:ni(t)?("name"in t?t.name:"")||"":typeof t=="string"?t:""}function qr(t){if(ii(t)){const e=t.headers.get("content-type")||"",i=Qr(t.url);return Og(e)||Ic(i)}return ni(t)?t.type||"":typeof t=="string"?Ic(t):""}function Dg(t){return ii(t)?t.headers["content-length"]||-1:ni(t)?t.size:typeof t=="string"?t.length:t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:-1}async function Fu(t){if(ii(t))return t;const e={},i=Dg(t);i>=0&&(e["content-length"]=String(i));const n=Kr(t),r=qr(t);r&&(e["content-type"]=r);const s=await kg(t);s&&(e["x-first-bytes"]=s),typeof t=="string"&&(t=new TextEncoder().encode(t));const o=new Response(t,{headers:e});return Object.defineProperty(o,"url",{value:n}),o}async function Fg(t){if(!t.ok)throw await Ug(t)}async function Ug(t){const e=Ng(t.url);let i=`Failed to fetch resource (${t.status}) ${t.statusText}: ${e}`;i=i.length>100?`${i.slice(0,100)}...`:i;const n={reason:t.statusText,url:t.url,response:t};try{const r=t.headers.get("Content-Type");n.reason=!t.bodyUsed&&r?.includes("application/json")?await t.json():await t.text()}catch{}return new Ig(i,n)}async function kg(t){if(typeof t=="string")return`data:,${t.slice(0,5)}`;if(t instanceof Blob){const i=t.slice(0,5);return await new Promise(n=>{const r=new FileReader;r.onload=s=>n(s?.target?.result),r.readAsDataURL(i)})}if(t instanceof ArrayBuffer){const i=t.slice(0,5);return`data:base64,${Lg(i)}`}return null}function Lg(t){let e="";const i=new Uint8Array(t);for(let n=0;n{}}info(){return()=>{}}warn(){return()=>{}}error(){return()=>{}}}class Hg{console;constructor(){this.console=console}log(...e){return this.console.log.bind(this.console,...e)}info(...e){return this.console.info.bind(this.console,...e)}warn(...e){return this.console.warn.bind(this.console,...e)}error(...e){return this.console.error.bind(this.console,...e)}}const uo={core:{baseUrl:void 0,fetch:null,mimeType:void 0,fallbackMimeType:void 0,ignoreRegisteredLoaders:void 0,nothrow:!1,log:new Hg,useLocalLibraries:!1,CDN:"https://unpkg.com/@loaders.gl",worker:!0,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:ga,_nodeWorkers:!1,_workerType:"",limit:0,_limitMB:0,batchSize:"auto",batchDebounceMs:0,metadata:!1,transforms:[]}},Yg={baseUri:"core.baseUrl",fetch:"core.fetch",mimeType:"core.mimeType",fallbackMimeType:"core.fallbackMimeType",ignoreRegisteredLoaders:"core.ignoreRegisteredLoaders",nothrow:"core.nothrow",log:"core.log",useLocalLibraries:"core.useLocalLibraries",CDN:"core.CDN",worker:"core.worker",maxConcurrency:"core.maxConcurrency",maxMobileConcurrency:"core.maxMobileConcurrency",reuseWorkers:"core.reuseWorkers",_nodeWorkers:"core.nodeWorkers",_workerType:"core._workerType",_worker:"core._workerType",limit:"core.limit",_limitMB:"core._limitMB",batchSize:"core.batchSize",batchDebounceMs:"core.batchDebounceMs",metadata:"core.metadata",transforms:"core.transforms",throws:"nothrow",dataType:"(no longer used)",uri:"core.baseUrl",method:"core.fetch.method",headers:"core.fetch.headers",body:"core.fetch.body",mode:"core.fetch.mode",credentials:"core.fetch.credentials",cache:"core.fetch.cache",redirect:"core.fetch.redirect",referrer:"core.fetch.referrer",referrerPolicy:"core.fetch.referrerPolicy",integrity:"core.fetch.integrity",keepalive:"core.fetch.keepalive",signal:"core.fetch.signal"},ya=["baseUrl","fetch","mimeType","fallbackMimeType","ignoreRegisteredLoaders","nothrow","log","useLocalLibraries","CDN","worker","maxConcurrency","maxMobileConcurrency","reuseWorkers","_nodeWorkers","_workerType","limit","_limitMB","batchSize","batchDebounceMs","metadata","transforms"];function Uu(){globalThis.loaders=globalThis.loaders||{};const{loaders:t}=globalThis;return t._state||(t._state={}),t._state}function ku(){const t=Uu();return t.globalOptions=t.globalOptions||{...uo,core:{...uo.core}},qt(t.globalOptions)}function Xg(t,e,i,n){return i=i||[],i=Array.isArray(i)?i:[i],Qg(t,i),qt(qg(e,t,n))}function qt(t){const e=Gg(t);Lu(e);for(const i of ya)e.core&&e.core[i]!==void 0&&delete e[i];return e.core&&e.core._workerType!==void 0&&delete e._worker,e}function Qg(t,e){Mc(t,null,uo,Yg,e);for(const i of e){const n=t&&t[i.id]||{},r=i.options&&i.options[i.id]||{},s=i.deprecatedOptions&&i.deprecatedOptions[i.id]||{};Mc(n,i.id,r,s,e)}}function Mc(t,e,i,n,r){const s=e||"Top level",o=e?`${e}.`:"";for(const a in t){const c=!e&&ti(t[a]),l=a==="baseUri"&&!e,f=a==="workerUrl"&&e;if(!(a in i)&&!l&&!f){if(a in n)Ln.level>0&&Ln.warn(`${s} loader option '${o}${a}' no longer supported, use '${n[a]}'`)();else if(!c&&Ln.level>0){const u=Kg(a,r);Ln.warn(`${s} loader option '${o}${a}' not recognized. ${u}`)()}}}}function Kg(t,e){const i=t.toLowerCase();let n="";for(const r of e)for(const s in r.options){if(t===s)return`Did you mean '${r.id}.${s}'?`;const o=s.toLowerCase();(i.startsWith(o)||o.startsWith(i))&&(n=n||`Did you mean '${r.id}.${s}'?`)}return n}function qg(t,e,i){const n=t.options||{},r={...n};n.core&&(r.core={...n.core}),Lu(r),r.core?.log===null&&(r.core={...r.core,log:new jg}),Oc(r,qt(ku()));const s=qt(e);return Oc(r,s),Zg(r,i),Jg(r),r}function Oc(t,e){for(const i in e)if(i in e){const n=e[i];wc(n)&&wc(t[i])?t[i]={...t[i],...e[i]}:t[i]=e[i]}}function Zg(t,e){if(!e)return;t.core?.baseUrl!==void 0||(t.core||={},t.core.baseUrl=Nu(Qr(e)))}function Gg(t){const e={...t};return t.core&&(e.core={...t.core}),e}function Lu(t){t.baseUri!==void 0&&(t.core||={},t.core.baseUrl===void 0&&(t.core.baseUrl=t.baseUri));for(const i of ya)if(t[i]!==void 0){const r=t.core=t.core||{};r[i]===void 0&&(r[i]=t[i])}const e=t._worker;e!==void 0&&(t.core||={},t.core._workerType===void 0&&(t.core._workerType=e))}function Jg(t){const e=t.core;if(e)for(const i of ya)e[i]!==void 0&&(t[i]=e[i])}function ba(t){return t?(Array.isArray(t)&&(t=t[0]),Array.isArray(t?.extensions)):!1}function wa(t){vr(t,"null loader"),vr(ba(t),"invalid loader");let e;return Array.isArray(t)&&(e=t[1],t=t[0],t={...t,options:{...t.options,...e}}),(t?.parseTextSync||t?.parseText)&&(t.text=!0),t.text||(t.binary=!0),t}const Wu=()=>{const t=Uu();return t.loaderRegistry=t.loaderRegistry||[],t.loaderRegistry};function $g(t){const e=Wu();t=Array.isArray(t)?t:[t];for(const i of t){const n=wa(i);e.find(r=>n===r)||e.unshift(n)}}function em(){return Wu()}const tm=/\.([^.]+)$/;async function im(t,e=[],i,n){if(!Vu(t))return null;const r=qt(i||{});if(r.core||={},t instanceof Response&&Bc(t)){const o=await t.clone().text(),a=Wn(o,e,{...r,core:{...r.core,nothrow:!0}},n);if(a)return a}let s=Wn(t,e,{...r,core:{...r.core,nothrow:!0}},n);if(s)return s;if(ni(t)&&(t=await t.slice(0,10).arrayBuffer(),s=Wn(t,e,r,n)),!s&&t instanceof Response&&Bc(t)){const o=await t.clone().text();s=Wn(o,e,r,n)}if(!s&&!r.core.nothrow)throw new Error(zu(t));return s}function Bc(t){const e=qr(t);return!!(e&&(e.startsWith("text/")||e==="application/json"||e.endsWith("+json")))}function Wn(t,e=[],i,n){if(!Vu(t))return null;const r=qt(i||{});if(r.core||={},e&&!Array.isArray(e))return wa(e);let s=[];e&&(s=s.concat(e)),r.core.ignoreRegisteredLoaders||s.push(...em()),rm(s);const o=nm(t,s,r,n);if(!o&&!r.core.nothrow)throw new Error(zu(t));return o}function nm(t,e,i,n){const r=Kr(t),s=qr(t),o=Qr(r)||n?.url;let a=null,c="";return i?.core?.mimeType&&(a=ys(e,i?.core?.mimeType),c=`match forced by supplied MIME type ${i?.core?.mimeType}`),a=a||sm(e,o),c=c||(a?`matched url ${o}`:""),a=a||ys(e,s),c=c||(a?`matched MIME type ${s}`:""),a=a||am(e,t),c=c||(a?`matched initial data ${ju(t)}`:""),i?.core?.fallbackMimeType&&(a=a||ys(e,i?.core?.fallbackMimeType),c=c||(a?`matched fallback MIME type ${s}`:"")),c&&$p.log(1,`selectLoader selected ${a?.name}: ${c}.`),a}function Vu(t){return!(t instanceof Response&&t.status===204)}function zu(t){const e=Kr(t),i=qr(t);let n="No valid loader found (";n+=e?`${Bu(e)}, `:"no url provided, ",n+=`MIME type: ${i?`"${i}"`:"not provided"}, `;const r=t?ju(t):"";return n+=r?` first bytes: "${r}"`:"first bytes: not available",n+=")",n}function rm(t){for(const e of t)wa(e)}function sm(t,e){const i=e&&tm.exec(e),n=i&&i[1];return n?om(t,n):null}function om(t,e){e=e.toLowerCase();for(const i of t)for(const n of i.extensions)if(n.toLowerCase()===e)return i;return null}function ys(t,e){for(const i of t)if(i.mimeTypes?.some(n=>Pc(e,n))||Pc(e,`application/x.${i.id}`))return i;return null}function am(t,e){if(!e)return null;for(const i of t)if(typeof e=="string"){if(cm(e,i))return i}else if(ArrayBuffer.isView(e)){if(Nc(e.buffer,e.byteOffset,i))return i}else if(e instanceof ArrayBuffer&&Nc(e,0,i))return i;return null}function cm(t,e){return e.testText?e.testText(t):(Array.isArray(e.tests)?e.tests:[e.tests]).some(n=>t.startsWith(n))}function Nc(t,e,i){return(Array.isArray(i.tests)?i.tests:[i.tests]).some(r=>lm(t,e,i,r))}function lm(t,e,i,n){if(_a(n))return wg(n,t,n.byteLength);switch(typeof n){case"function":return n(Ou(t));case"string":const r=ho(t,e,n.length);return n===r;default:return!1}}function ju(t,e=5){return typeof t=="string"?t.slice(0,e):ArrayBuffer.isView(t)?ho(t.buffer,t.byteOffset,e):t instanceof ArrayBuffer?ho(t,0,e):""}function ho(t,e,i){if(t.byteLengthxc(s,r):e?.fetch?e?.fetch:xc}function wm(t,e,i){if(i)return i;const n={fetch:Yu(e,t),...t};if(n.url){const r=Qr(n.url);n.baseUrl=r,n.queryString=Bg(n.url),n.filename=Bu(r),n.baseUrl=Nu(r)}return Array.isArray(n.loaders)||(n.loaders=null),n}function Tm(t,e){if(t&&!Array.isArray(t))return t;let i;if(t&&(i=Array.isArray(t)?t:[t]),e&&e.loaders){const n=Array.isArray(e.loaders)?e.loaders:[e.loaders];i=i?[...i,...n]:n}return i&&i.length?i:void 0}async function Pr(t,e,i,n){e&&!Array.isArray(e)&&!ba(e)&&(n=void 0,i=e,e=void 0),t=await t,i=i||{};const r=Kr(t),o=Tm(e,n),a=await im(t,o,i);if(!a)return null;const c=Xg(i,a,o,r);return n=wm({url:r,_parse:Pr,loaders:o},c,n||null),await Em(a,t,c,n)}async function Em(t,e,i,n){if(_g(t),i=sg(t.options,i),ii(e)){const{ok:s,redirected:o,status:a,statusText:c,type:l,url:f}=e,u=Object.fromEntries(e.headers.entries());n.response={headers:u,ok:s,redirected:o,status:a,statusText:c,type:l,url:f}}e=await bm(e,t,i);const r=t;if(r.parseTextSync&&typeof e=="string")return r.parseTextSync(e,i,n);if(Ag(t,i))return await yg(t,e,i,n,Pr);if(r.parseText&&typeof e=="string")return await r.parseText(e,i,n);if(r.parse)return await r.parse(e,i,n);throw Rt(!r.parseSync),new Error(`${t.id} loader - no parser found and worker is disabled`)}function Sm(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Rm(t){return Array.isArray(t)?t.length===0||typeof t[0]=="number":!1}function vm(t){return Sm(t)||Rm(t)}async function po(t,e,i,n){let r,s;!Array.isArray(e)&&!ba(e)?(r=[],s=e):(r=e,s=i);const o=Yu(s);let a=t;return typeof t=="string"&&(a=await o(t)),ni(t)&&(a=await o(t)),typeof t=="string"&&(qt(s||{}).core?.baseUrl||(s={...s,core:{...s?.core,baseUrl:t}})),Array.isArray(r)?await Pr(a,r,s):await Pr(a,r,s)}const Cm="4.4.2",Pm=globalThis.loaders?.parseImageNode,go=typeof Image<"u",mo=typeof ImageBitmap<"u",Im=!!Pm,_o=ga?!0:Im;function xm(t){switch(t){case"auto":return mo||go||_o;case"imagebitmap":return mo;case"image":return go;case"data":return _o;default:throw new Error(`@loaders.gl/images: image ${t} not supported in this environment`)}}function Mm(){if(mo)return"imagebitmap";if(go)return"image";if(_o)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}function Om(t){const e=Nm(t);if(!e)throw new Error("Not an image");return e}function Bm(t){switch(Om(t)){case"data":return t;case"image":case"imagebitmap":const e=document.createElement("canvas"),i=e.getContext("2d");if(!i)throw new Error("getImageData");return e.width=t.width,e.height=t.height,i.drawImage(t,0,0),i.getImageData(0,0,t.width,t.height);default:throw new Error("getImageData")}}function Nm(t){return typeof ImageBitmap<"u"&&t instanceof ImageBitmap?"imagebitmap":typeof Image<"u"&&t instanceof Image?"image":t&&typeof t=="object"&&t.data&&t.width&&t.height?"data":null}const Dm=/^data:image\/svg\+xml/,Fm=/\.svg((\?|#).*)?$/;function Ta(t){return t&&(Dm.test(t)||Fm.test(t))}function Um(t,e){if(Ta(e)){let n=new TextDecoder().decode(t);try{typeof unescape=="function"&&typeof encodeURIComponent=="function"&&(n=unescape(encodeURIComponent(n)))}catch(s){throw new Error(s.message)}return`data:image/svg+xml;base64,${btoa(n)}`}return Xu(t,e)}function Xu(t,e){if(Ta(e))throw new Error("SVG cannot be parsed directly to imagebitmap");return new Blob([new Uint8Array(t)])}async function Qu(t,e,i){const n=Um(t,i),r=self.URL||self.webkitURL,s=typeof n!="string"&&r.createObjectURL(n);try{return await km(s||n,e)}finally{s&&r.revokeObjectURL(s)}}async function km(t,e){const i=new Image;return i.src=t,e.image&&e.image.decode&&i.decode?(await i.decode(),i):await new Promise((n,r)=>{try{i.onload=()=>n(i),i.onerror=s=>{const o=s instanceof Error?s.message:"error";r(new Error(o))}}catch(s){r(s)}})}let Fc=!0;async function Lm(t,e,i){let n;Ta(i)?n=await Qu(t,e,i):n=Xu(t,i);const r=e&&e.imagebitmap;return await Wm(n,r)}async function Wm(t,e=null){if((Vm(e)||!Fc)&&(e=null),e)try{return await createImageBitmap(t,e)}catch(i){console.warn(i),Fc=!1}return await createImageBitmap(t)}function Vm(t){if(!t)return!0;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!1;return!0}function zm(t){return!Xm(t,"ftyp",4)||!(t[8]&96)?null:jm(t)}function jm(t){switch(Hm(t,8,12).replace("\0"," ").trim()){case"avif":case"avis":return{extension:"avif",mimeType:"image/avif"};default:return null}}function Hm(t,e,i){return String.fromCharCode(...t.slice(e,i))}function Ym(t){return[...t].map(e=>e.charCodeAt(0))}function Xm(t,e,i=0){const n=Ym(e);for(let r=0;r=24&&e.getUint32(0,et)===2303741511?{mimeType:"image/png",width:e.getUint32(16,et),height:e.getUint32(20,et)}:null}function qm(t){const e=Rn(t);return e.byteLength>=10&&e.getUint32(0,et)===1195984440?{mimeType:"image/gif",width:e.getUint16(6,sn),height:e.getUint16(8,sn)}:null}function Zm(t){const e=Rn(t);return e.byteLength>=14&&e.getUint16(0,et)===16973&&e.getUint32(2,sn)===e.byteLength?{mimeType:"image/bmp",width:e.getUint32(18,sn),height:e.getUint32(22,sn)}:null}function Gm(t){const e=Rn(t);if(!(e.byteLength>=3&&e.getUint16(0,et)===65496&&e.getUint8(2)===255))return null;const{tableMarkers:n,sofMarkers:r}=Jm();let s=2;for(;s+9!!Ku(new DataView(t))],options:r_},J=new Sn({id:"deck"});let Ao={};function o_(t){Ao=t}function be(t,e,i,n){J.level>0&&Ao[t]&&Ao[t].call(null,e,i,n)}function a_(t){const e=t[0],i=t[t.length-1];return e==="{"&&i==="}"||e==="["&&i==="]"}const c_={dataType:null,batchType:null,id:"JSON",name:"JSON",module:"",version:"",options:{},extensions:["json","geojson"],mimeTypes:["application/json","application/geo+json"],testText:a_,parseTextSync:JSON.parse};function l_(){const t="9.3.2",e=globalThis.deck&&globalThis.deck.VERSION;if(e&&e!==t)throw new Error(`deck.gl - multiple versions detected: ${e} vs ${t}`);return e||(J.log(1,`deck.gl ${t}`)(),globalThis.deck={...globalThis.deck,VERSION:t,version:t,log:J,_registerLoggers:o_},$g([c_,[s_,{imagebitmap:{premultiplyAlpha:"none"}}]])),t}const f_=l_();function vn(t,e){if(!t){const i=new Error(e||"shadertools: assertion failed.");throw Error.captureStackTrace?.(i,vn),i}}const bs={number:{type:"number",validate(t,e){return Number.isFinite(t)&&typeof e=="object"&&(e.max===void 0||t<=e.max)&&(e.min===void 0||t>=e.min)}},array:{type:"array",validate(t,e){return Array.isArray(t)||ArrayBuffer.isView(t)}}};function u_(t){const e={};for(const[i,n]of Object.entries(t))e[i]=h_(n);return e}function h_(t){let e=Uc(t);if(e!=="object")return{value:t,...bs[e],type:e};if(typeof t=="object")return t?t.type!==void 0?{...t,...bs[t.type],type:t.type}:t.value===void 0?{type:"object",value:t}:(e=Uc(t.value),{...t,...bs[e],type:e}):{type:"object",value:null};throw new Error("props")}function Uc(t){return Array.isArray(t)||ArrayBuffer.isView(t)?"array":typeof t}const d_=`#ifdef MODULE_LOGDEPTH logdepth_adjustPosition(gl_Position); #endif `,p_=`#ifdef MODULE_MATERIAL fragColor = material_filterColor(fragColor); #endif #ifdef MODULE_LIGHTING fragColor = lighting_filterColor(fragColor); #endif #ifdef MODULE_FOG fragColor = fog_filterColor(fragColor); #endif #ifdef MODULE_PICKING fragColor = picking_filterHighlightColor(fragColor); fragColor = picking_filterPickingColor(fragColor); #endif #ifdef MODULE_LOGDEPTH logdepth_setFragDepth(); #endif `,g_={vertex:d_,fragment:p_},kc=/void\s+main\s*\([^)]*\)\s*\{\n?/,Lc=/}\n?[^{}]*$/,ws=[],dr="__LUMA_INJECT_DECLARATIONS__";function m_(t){const e={vertex:{},fragment:{}};for(const i in t){let n=t[i];const r=__(i);typeof n=="string"&&(n={order:0,injection:n}),e[r][i]=n}return e}function __(t){const e=t.slice(0,2);switch(e){case"vs":return"vertex";case"fs":return"fragment";default:throw new Error(e)}}function Ir(t,e,i,n=!1){const r=e==="vertex";for(const s in i){const o=i[s];o.sort((c,l)=>c.order-l.order),ws.length=o.length;for(let c=0,l=o.length;cc+a));break;case"vs:#main-end":r&&(t=t.replace(Lc,c=>a+c));break;case"fs:#decl":r||(t=t.replace(dr,a));break;case"fs:#main-start":r||(t=t.replace(kc,c=>c+a));break;case"fs:#main-end":r||(t=t.replace(Lc,c=>a+c));break;default:t=t.replace(s,c=>c+a)}}return t=t.replace(dr,""),n&&(t=t.replace(/\}\s*$/,s=>s+g_[e])),t}function xr(t){t.map(e=>A_(e))}function A_(t){if(t.instance)return;xr(t.dependencies||[]);const{propTypes:e={},deprecations:i=[],inject:n={}}=t,r={normalizedInjections:m_(n),parsedDeprecations:y_(i)};e&&(r.propValidators=u_(e)),t.instance=r;let s={};e&&(s=Object.entries(e).reduce((o,[a,c])=>{const l=c?.value;return l&&(o[a]=l),o},{})),t.defaultUniforms={...t.defaultUniforms,...s}}function qu(t,e,i){t.deprecations?.forEach(n=>{n.regex?.test(e)&&(n.deprecated?i.deprecated(n.old,n.new)():i.removed(n.old,n.new)())})}function y_(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}function Ea(t){xr(t);const e={},i={};Zu({modules:t,level:0,moduleMap:e,moduleDepth:i});const n=Object.keys(i).sort((r,s)=>i[s]-i[r]).map(r=>e[r]);return xr(n),n}function Zu(t){const{modules:e,level:i,moduleMap:n,moduleDepth:r}=t;if(i>=5)throw new Error("Possible loop in shader dependency graph");for(const s of e)n[s.name]=s,(r[s.name]===void 0||r[s.name]]+>)?\s+([A-Za-z0-9_]+)(?:\s*\[[^\]]+\])?\s*;/,w_=/((?:layout\s*\([^)]*\)\s*)*)uniform\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{([\s\S]*?)\}\s*([A-Za-z_][A-Za-z0-9_]*)?\s*;/g;function Gu(t){return`${t.name}Uniforms`}function T_(t,e){const i=e==="wgsl"?t.source:e==="vertex"?t.vs:t.fs;if(!i)return null;const n=Gu(t);return v_(i,e==="wgsl"?"wgsl":"glsl",n)}function E_(t,e){const i=Object.keys(t.uniformTypes||{});if(!i.length)return null;const n=T_(t,e);return n?{moduleName:t.name,uniformBlockName:Gu(t),stage:e,expectedUniformNames:i,actualUniformNames:n,matches:I_(i,n)}:null}function S_(t,e,i={}){const n=E_(t,e);if(!n||n.matches)return n;const r=x_(n);return i.log?.error?.(r,n)(),i.throwOnError!==!1&&vn(!1,r),n}function Ju(t){const e=[],i=M_(t);for(const n of i.matchAll(w_)){const r=n[1]?.trim()||null;e.push({blockName:n[2],body:n[3],instanceName:n[4]||null,layoutQualifier:r,hasLayoutQualifier:!!r,isStd140:!!(r&&/\blayout\s*\([^)]*\bstd140\b[^)]*\)/.exec(r))})}return e}function R_(t,e,i,n){const r=Ju(t).filter(o=>!o.isStd140),s=new Set;for(const o of r){if(s.has(o.blockName))continue;s.add(o.blockName);const a="",c=o.hasLayoutQualifier?`declares ${O_(o.layoutQualifier)} instead of layout(std140)`:"does not declare layout(std140)",l=`${a}${e} shader uniform block ${o.blockName} ${c}. luma.gl host-side shader block packing assumes explicit layout(std140) for GLSL uniform blocks. Add \`layout(std140)\` to the block declaration.`;i?.warn?.(l,o)()}return r}function v_(t,e,i){const n=e==="wgsl"?C_(t,i):P_(t,i);if(!n)return null;const r=[];for(const s of n.split(` `)){const o=s.replace(/\/\/.*$/,"").trim();if(!o||o.startsWith("#"))continue;const a=e==="wgsl"?o.match(/^([A-Za-z0-9_]+)\s*:/):o.match(b_);a&&r.push(a[1])}return r}function C_(t,e){const i=new RegExp(`\\bstruct\\s+${e}\\b`,"m").exec(t);if(!i)return null;const n=t.indexOf("{",i.index);if(n<0)return null;let r=0;for(let s=n;sn.blockName===e)?.body||null}function I_(t,e){if(t.length!==e.length)return!1;for(let i=0;i!i.includes(a)),r=i.filter(a=>!e.includes(a)),s=[`Expected ${e.length} fields, found ${i.length}.`],o=B_(e,i);return o&&s.push(o),n.length&&s.push(`Missing from shader block (${n.length}): ${Wc(n)}.`),r.length&&s.push(`Unexpected in shader block (${r.length}): ${Wc(r)}.`),e.length<=12&&i.length<=12&&(n.length||r.length)&&(s.push(`Expected: ${e.join(", ")}.`),s.push(`Actual: ${i.join(", ")}.`)),`${t.moduleName}: ${t.stage} shader uniform block ${t.uniformBlockName} does not match module.uniformTypes. ${s.join(" ")}`}function M_(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}function O_(t){return t.replace(/\s+/g," ").trim()}function B_(t,e){const i=Math.min(t.length,e.length);for(let n=0;ne.length?`Shader block ends after field ${e.length}; expected next field ${t[e.length]}.`:e.length>t.length?`Shader block has extra field ${e.length}: ${e[t.length]}.`:null}function Wc(t,e=8){if(t.length<=e)return t.join(", ");const i=t.length-e;return`${t.slice(0,e).join(", ")}, ... (${i} more)`}function N_(t){switch(t?.gpu.toLowerCase()){case"apple":return`#define APPLE_GPU // Apple optimizes away the calculation necessary for emulated fp64 #define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 #define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 // Intel GPU doesn't have full 32 bits precision in same cases, causes overflow #define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 `;case"nvidia":return`#define NVIDIA_GPU // Nvidia optimizes away the calculation necessary for emulated fp64 #define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 `;case"intel":return`#define INTEL_GPU // Intel optimizes away the calculation necessary for emulated fp64 #define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 // Intel's built-in 'tan' function doesn't have acceptable precision #define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 // Intel GPU doesn't have full 32 bits precision in same cases, causes overflow #define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 `;case"amd":return`#define AMD_GPU `;default:return`#define DEFAULT_GPU // Prevent driver from optimizing away the calculation necessary for emulated fp64 #define LUMA_FP64_CODE_ELIMINATION_WORKAROUND 1 // Headless Chrome's software shader 'tan' function doesn't have acceptable precision #define LUMA_FP32_TAN_PRECISION_WORKAROUND 1 // If the GPU doesn't have full 32 bits precision, will causes overflow #define LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND 1 `}}function D_(t,e){if(Number(t.match(/^#version[ \t]+(\d+)/m)?.[1]||100)!==300)throw new Error("luma.gl v9 only supports GLSL 3.00 shader sources");switch(e){case"vertex":return t=Vc(t,F_),t;case"fragment":return t=Vc(t,U_),t;default:throw new Error(e)}}const $u=[[/^(#version[ \t]+(100|300[ \t]+es))?[ \t]*\n/,`#version 300 es `],[/\btexture(2D|2DProj|Cube)Lod(EXT)?\(/g,"textureLod("],[/\btexture(2D|2DProj|Cube)(EXT)?\(/g,"texture("]],F_=[...$u,[yo("attribute"),"in $1"],[yo("varying"),"out $1"]],U_=[...$u,[yo("varying"),"in $1"]];function Vc(t,e){for(const[i,n]of e)t=t.replace(i,n);return t}function yo(t){return new RegExp(`\\b${t}[ \\t]+(\\w+[ \\t]+\\w+(\\[\\w+\\])?;)`,"g")}function eh(t,e){let i="";for(const n in t){const r=t[n];if(i+=`void ${r.signature} { `,r.header&&(i+=` ${r.header}`),e[n]){const s=e[n];s.sort((o,a)=>o.order-a.order);for(const o of s)i+=` ${o.injection} `}r.footer&&(i+=` ${r.footer}`),i+=`} `}return i}function th(t){const e={vertex:{},fragment:{}};for(const i of t){let n,r;typeof i!="string"?(n=i,r=n.hook):(n={},r=i),r=r.trim();const[s,o]=r.split(":"),a=r.replace(/\(.+/,""),c=Object.assign(n,{signature:o});switch(s){case"vs":e.vertex[a]=c;break;case"fs":e.fragment[a]=c;break;default:throw new Error(s)}}return e}function k_(t,e){return{name:L_(t,e),language:"glsl",version:W_(t)}}function L_(t,e="unnamed"){const n=/#define[^\S\r\n]*SHADER_NAME[^\S\r\n]*([A-Za-z0-9_-]+)\s*/.exec(t);return n?n[1]:e}function W_(t){let e=100;const i=t.match(/[^\s]+/g);if(i&&i.length>=2&&i[0]==="#version"){const n=parseInt(i[1],10);Number.isFinite(n)&&(e=n)}if(e!==100&&e!==300)throw new Error(`Invalid GLSL version ${e}`);return e}const Fe="(?:var<\\s*(uniform|storage(?:\\s*,\\s*[A-Za-z_][A-Za-z0-9_]*)?)\\s*>|var)\\s+([A-Za-z_][A-Za-z0-9_]*)",Ue="\\s*",dn=[new RegExp(`@binding\\(\\s*(auto|\\d+)\\s*\\)${Ue}@group\\(\\s*(\\d+)\\s*\\)${Ue}${Fe}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)${Ue}@binding\\(\\s*(auto|\\d+)\\s*\\)${Ue}${Fe}`,"g")],bo=[new RegExp(`@binding\\(\\s*(auto|\\d+)\\s*\\)${Ue}@group\\(\\s*(\\d+)\\s*\\)${Ue}${Fe}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)${Ue}@binding\\(\\s*(auto|\\d+)\\s*\\)${Ue}${Fe}`,"g")],V_=[new RegExp(`@binding\\(\\s*(\\d+)\\s*\\)${Ue}@group\\(\\s*(\\d+)\\s*\\)${Ue}${Fe}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)${Ue}@binding\\(\\s*(\\d+)\\s*\\)${Ue}${Fe}`,"g")],z_=[new RegExp(`@binding\\(\\s*(auto)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Fe}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto)\\s*\\)\\s*${Fe}`,"g"),new RegExp(`@binding\\(\\s*(auto)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)(?:[\\s\\n\\r]*@[A-Za-z_][^\\n\\r]*)*[\\s\\n\\r]*${Fe}`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(auto)\\s*\\)(?:[\\s\\n\\r]*@[A-Za-z_][^\\n\\r]*)*[\\s\\n\\r]*${Fe}`,"g")];function Sa(t){const e=t.split("");let i=0,n=0,r=!1,s=!1,o=!1;for(;i0){if(a==="/"&&c==="*"){e[i]=" ",e[i+1]=" ",n++,i+=2;continue}if(a==="*"&&c==="/"){e[i]=" ",e[i+1]=" ",n--,i+=2;continue}a!==` `&&a!=="\r"&&(e[i]=" "),i++;continue}if(a==='"'){s=!0,i++;continue}if(a==="/"&&c==="/"){e[i]=" ",e[i+1]=" ",r=!0,i+=2;continue}if(a==="/"&&c==="*"){e[i]=" ",e[i+1]=" ",n=1,i+=2;continue}i++}return e.join("")}function Di(t,e){const i=Sa(t),n=[];for(const r of e){r.lastIndex=0;let s;for(s=r.exec(i);s;){const o=r===e[0],a=s.index,c=s[0].length;n.push({match:t.slice(a,a+c),index:a,length:c,bindingToken:s[o?1:2],groupToken:s[o?2:1],accessDeclaration:s[3]?.trim(),name:s[4]}),s=r.exec(i)}}return n.sort((r,s)=>r.index-s.index)}function ih(t,e,i){const n=Di(t,e);if(!n.length)return t;let r="",s=0;for(const o of n)r+=t.slice(s,o.index),r+=i(o),s=o.index+o.length;return r+=t.slice(s),r}function nh(t){return/@binding\(\s*auto\s*\)/.test(Sa(t))}function j_(t,e){return Di(t,e===dn||e===bo?z_:e).find(n=>n.bindingToken==="auto")}const zc=[new RegExp(`@binding\\(\\s*(\\d+)\\s*\\)\\s*@group\\(\\s*(\\d+)\\s*\\)\\s*${Fe}\\s*:\\s*([^;]+);`,"g"),new RegExp(`@group\\(\\s*(\\d+)\\s*\\)\\s*@binding\\(\\s*(\\d+)\\s*\\)\\s*${Fe}\\s*:\\s*([^;]+);`,"g")];function rh(t,e=[]){const i=Sa(t),n=new Map;for(const s of e)n.set(jc(s.name,s.group,s.location),s.moduleName);const r=[];for(const s of zc){s.lastIndex=0;let o;for(o=s.exec(i);o;){const a=s===zc[0],c=Number(o[a?1:2]),l=Number(o[a?2:1]),f=o[3]?.trim(),u=o[4],h=o[5].trim(),p=n.get(jc(u,l,c));r.push(H_({name:u,group:l,binding:c,owner:p?"module":"application",moduleName:p,accessDeclaration:f,resourceType:h})),o=s.exec(i)}}return r.sort((s,o)=>s.group!==o.group?s.group-o.group:s.binding!==o.binding?s.binding-o.binding:s.name.localeCompare(o.name))}function H_(t){const e={name:t.name,group:t.group,binding:t.binding,owner:t.owner,kind:"unknown",moduleName:t.moduleName,resourceType:t.resourceType};if(t.accessDeclaration){const i=t.accessDeclaration.split(",").map(n=>n.trim());if(i[0]==="uniform")return{...e,kind:"uniform",access:"uniform"};if(i[0]==="storage"){const n=i[1]||"read_write";return{...e,kind:n==="read"?"read-only-storage":"storage",access:n}}}return t.resourceType==="sampler"||t.resourceType==="sampler_comparison"?{...e,kind:"sampler",samplerKind:t.resourceType==="sampler_comparison"?"comparison":"filtering"}:t.resourceType.startsWith("texture_storage_")?{...e,kind:"storage-texture",access:X_(t.resourceType),viewDimension:Hc(t.resourceType)}:t.resourceType.startsWith("texture_")?{...e,kind:"texture",viewDimension:Hc(t.resourceType),sampleType:Y_(t.resourceType),multisampled:t.resourceType.startsWith("texture_multisampled_")}:e}function jc(t,e,i){return`${e}:${i}:${t}`}function Hc(t){if(t.includes("cube_array"))return"cube-array";if(t.includes("2d_array"))return"2d-array";if(t.includes("cube"))return"cube";if(t.includes("3d"))return"3d";if(t.includes("2d"))return"2d";if(t.includes("1d"))return"1d"}function Y_(t){if(t.startsWith("texture_depth_"))return"depth";if(t.includes(""))return"sint";if(t.includes(""))return"uint";if(t.includes(""))return"float"}function X_(t){return/,\s*([A-Za-z_][A-Za-z0-9_]*)\s*>$/.exec(t)?.[1]}const Ra=` ${dr} `,pn=100,Q_=`precision highp float; `;function K_(t){const e=Ea(t.modules||[]),{source:i,bindingAssignments:n}=Z_(t.platformInfo,{...t,source:t.source,stage:"vertex",modules:e});return{source:i,getUniforms:sh(e),bindingAssignments:n,bindingTable:rh(i,n)}}function q_(t){const{vs:e,fs:i}=t,n=Ea(t.modules||[]);return{vs:Yc(t.platformInfo,{...t,source:e,stage:"vertex",modules:n}),fs:Yc(t.platformInfo,{...t,source:i,stage:"fragment",modules:n}),getUniforms:sh(n)}}function Z_(t,e){const{source:i,stage:n,modules:r,hookFunctions:s=[],inject:o={},log:a}=e;vn(typeof i=="string","shader source must be a string");const c=i;let l="";const f=th(s),u={},h={},p={};for(const A in o){const b=typeof o[A]=="string"?{injection:o[A],order:0}:o[A],T=/^(v|f)s:(#)?([\w-]+)$/.exec(A);if(T){const w=T[2],v=T[3];w?v==="decl"?h[A]=[b]:p[A]=[b]:u[A]=[b]}else p[A]=[b]}const d=r,m=$_(c),g=J_(m.source),_=nA(d,e._bindingRegistry,g),y=[];for(const A of d){a&&qu(A,c,a);const b=eA(oh(A,"wgsl",a),A,{usedBindingsByGroup:g,bindingRegistry:e._bindingRegistry,reservedBindingKeysByGroup:_});y.push(...b.bindingAssignments);const T=b.source;l+=T;const w=A.injections?.[n]||{};for(const v in w){const M=/^(v|f)s:#([\w-]+)$/.exec(v);if(M){const P=M[2]==="decl"?h:p;P[v]=P[v]||[],P[v].push(w[v])}else u[v]=u[v]||[],u[v].push(w[v])}}return l+=Ra,l=Ir(l,n,h),l+=eh(f[n],u),l+=cA(y),l+=m.source,l=Ir(l,n,p),aA(l),{source:l,bindingAssignments:y}}function Yc(t,e){const{source:i,stage:n,language:r="glsl",modules:s,defines:o={},hookFunctions:a=[],inject:c={},prologue:l=!0,log:f}=e;vn(typeof i=="string","shader source must be a string");const u=r==="glsl"?k_(i).version:-1,h=t.shaderLanguageVersion,p=u===100?"#version 100":"#version 300 es",m=i.split(` `).slice(1).join(` `),g={};s.forEach(w=>{Object.assign(g,w.defines)}),Object.assign(g,o);let _="";switch(r){case"wgsl":break;case"glsl":_=l?`${p} // ----- PROLOGUE ------------------------- ${`#define SHADER_TYPE_${n.toUpperCase()}`} ${N_(t)} ${n==="fragment"?Q_:""} // ----- APPLICATION DEFINES ------------------------- ${G_(g)} `:`${p} `;break}const y=th(a),A={},b={},T={};for(const w in c){const v=typeof c[w]=="string"?{injection:c[w],order:0}:c[w],M=/^(v|f)s:(#)?([\w-]+)$/.exec(w);if(M){const x=M[2],P=M[3];x?P==="decl"?b[w]=[v]:T[w]=[v]:A[w]=[v]}else T[w]=[v]}for(const w of s){f&&qu(w,m,f);const v=oh(w,n,f);_+=v;const M=w.instance?.normalizedInjections[n]||{};for(const x in M){const P=/^(v|f)s:#([\w-]+)$/.exec(x);if(P){const I=P[2]==="decl"?b:T;I[x]=I[x]||[],I[x].push(M[x])}else A[x]=A[x]||[],A[x].push(M[x])}}return _+="// ----- MAIN SHADER SOURCE -------------------------",_+=Ra,_=Ir(_,n,b),_+=eh(y[n],A),_+=m,_=Ir(_,n,T),r==="glsl"&&u!==h&&(_=D_(_,n)),r==="glsl"&&R_(_,n,f),_.trim()}function sh(t){return function(i){const n={};for(const r of t){const s=r.getUniforms?.(i,n);Object.assign(n,s)}return n}}function G_(t={}){let e="";for(const i in t){const n=t[i];(n||Number.isFinite(n))&&(e+=`#define ${i.toUpperCase()} ${t[i]} `)}return e}function oh(t,e,i){let n;switch(e){case"vertex":n=t.vs||"";break;case"fragment":n=t.fs||"";break;case"wgsl":n=t.source||"";break;default:vn(!1)}if(!t.name)throw new Error("Shader module must have a name");S_(t,e,{log:i});const r=t.name.toUpperCase().replace(/[^0-9a-z]/gi,"_");let s=`// ----- MODULE ${t.name} --------------- `;return e!=="wgsl"&&(s+=`#define MODULE_${r} `),s+=`${n} `,s}function J_(t){const e=new Map;for(const i of Di(t,V_)){const n=Number(i.bindingToken),r=Number(i.groupToken);va(r,n,i.name),vi(e,r,n,`application binding "${i.name}"`)}return e}function $_(t){const e=Di(t,bo),i=new Map;for(const s of e){if(s.bindingToken==="auto")continue;const o=Number(s.bindingToken),a=Number(s.groupToken);va(a,o,s.name),vi(i,a,o,`application binding "${s.name}"`)}const n={sawSupportedBindingDeclaration:e.length>0},r=ih(t,bo,s=>iA(s,i,n));if(nh(t)&&!n.sawSupportedBindingDeclaration)throw new Error('Unsupported @binding(auto) declaration form in application WGSL. Use adjacent "@group(N)" and "@binding(auto)" decorators followed by a bindable "var" declaration.');return{source:r}}function eA(t,e,i){const n=[],s={sawSupportedBindingDeclaration:Di(t,dn).length>0,nextHintedBindingLocation:typeof e.firstBindingSlot=="number"?e.firstBindingSlot:null},o=ih(t,dn,a=>tA(a,{module:e,context:i,bindingAssignments:n,relocationState:s}));if(nh(t)&&!s.sawSupportedBindingDeclaration)throw new Error(`Unsupported @binding(auto) declaration form in module "${e.name}". Use adjacent "@group(N)" and "@binding(auto)" decorators followed by a bindable "var" declaration.`);return{source:o,bindingAssignments:n}}function tA(t,e){const{module:i,context:n,bindingAssignments:r,relocationState:s}=e,{match:o,bindingToken:a,groupToken:c,name:l}=t,f=Number(c);if(a==="auto"){const h=ah(f,i.name,l),p=n.bindingRegistry?.get(h),d=p!==void 0?p:s.nextHintedBindingLocation===null?Qc(f,n.usedBindingsByGroup):Qc(f,n.usedBindingsByGroup,s.nextHintedBindingLocation);return Xc(i.name,f,d,l),p!==void 0&&rA(n.reservedBindingKeysByGroup,f,d,h)?(r.push({moduleName:i.name,name:l,group:f,location:d}),o.replace(/@binding\(\s*auto\s*\)/,`@binding(${d})`)):(vi(n.usedBindingsByGroup,f,d,`module "${i.name}" binding "${l}"`),n.bindingRegistry?.set(h,d),r.push({moduleName:i.name,name:l,group:f,location:d}),s.nextHintedBindingLocation!==null&&p===void 0&&(s.nextHintedBindingLocation=d+1),o.replace(/@binding\(\s*auto\s*\)/,`@binding(${d})`))}const u=Number(a);return Xc(i.name,f,u,l),vi(n.usedBindingsByGroup,f,u,`module "${i.name}" binding "${l}"`),r.push({moduleName:i.name,name:l,group:f,location:u}),o}function iA(t,e,i){const{match:n,bindingToken:r,groupToken:s,name:o}=t,a=Number(s);if(r==="auto"){const c=oA(a,e);return va(a,c,o),vi(e,a,c,`application binding "${o}"`),n.replace(/@binding\(\s*auto\s*\)/,`@binding(${c})`)}return i.sawSupportedBindingDeclaration=!0,n}function nA(t,e,i){const n=new Map;if(!e)return n;for(const r of t)for(const s of sA(r)){const o=ah(s.group,r.name,s.name),a=e.get(o);if(a!==void 0){const c=n.get(s.group)||new Map,l=c.get(a);if(l&&l!==o)throw new Error(`Duplicate WGSL binding reservation for modules "${l}" and "${o}": group ${s.group}, binding ${a}.`);vi(i,s.group,a,`registered module binding "${o}"`),c.set(a,o),n.set(s.group,c)}}return n}function rA(t,e,i,n){const r=t.get(e);if(!r)return!1;const s=r.get(i);if(!s)return!1;if(s!==n)throw new Error(`Registered module binding "${n}" collided with "${s}": group ${e}, binding ${i}.`);return!0}function sA(t){const e=[],i=t.source||"";for(const n of Di(i,dn))e.push({name:n.name,group:Number(n.groupToken)});return e}function va(t,e,i){if(t===0&&e>=pn)throw new Error(`Application binding "${i}" in group 0 uses reserved binding ${e}. Application-owned explicit group-0 bindings must stay below ${pn}.`)}function Xc(t,e,i,n){if(e===0&&i0?Math.max(...n)+1:0);for(;n.has(r);)r++;return r}function oA(t,e){const i=e.get(t)||new Set;let n=0;for(;i.has(n);)n++;return n}function aA(t){const e=j_(t,dn);if(!e)return;const i=lA(t,e.index);throw i?new Error(`Unresolved @binding(auto) for module "${i}" binding "${e.name}" remained in assembled WGSL source.`):fA(t,e.index)?new Error(`Unresolved @binding(auto) for application binding "${e.name}" remained in assembled WGSL source.`):new Error(`Unresolved @binding(auto) remained in assembled WGSL source near "${uA(e.match)}".`)}function cA(t){if(t.length===0)return"";let e=`// ----- MODULE WGSL BINDING ASSIGNMENTS --------------- `;for(const i of t)e+=`// ${i.moduleName}.${i.name} -> @group(${i.group}) @binding(${i.location}) `;return e+=` `,e}function ah(t,e,i){return`${t}:${e}:${i}`}function lA(t,e){const i=/^\/\/ ----- MODULE ([^\n]+) ---------------$/gm;let n,r;for(r=i.exec(t);r&&r.index<=e;)n=r[1],r=i.exec(t);return n}function fA(t,e){const i=t.indexOf(Ra);return i>=0?e>i:!0}function uA(t){return t.replace(/\s+/g," ").trim()}const Ca="([a-zA-Z_][a-zA-Z0-9_]*)",hA=new RegExp(`^\\s*\\#\\s*ifdef\\s*${Ca}\\s*$`),dA=new RegExp(`^\\s*\\#\\s*ifndef\\s*${Ca}\\s*(?:\\/\\/.*)?$`),pA=/^\s*\#\s*else\s*(?:\/\/.*)?$/,gA=/^\s*\#\s*endif\s*$/,mA=new RegExp(`^\\s*\\#\\s*ifdef\\s*${Ca}\\s*(?:\\/\\/.*)?$`),_A=/^\s*\#\s*endif\s*(?:\/\/.*)?$/;function AA(t,e){const i=t.split(` `),n=[],r=[];let s=!0;for(const o of i){const a=o.match(mA)||o.match(hA),c=o.match(dA),l=o.match(pA),f=o.match(_A)||o.match(gA);if(a||c){const u=(a||c)?.[1],h=!!e?.defines?.[u],p=a?h:!h,d=s&&p;r.push({parentActive:s,branchTaken:p,active:d}),s=d}else if(l){const u=r[r.length-1];if(!u)throw new Error("Encountered #else without matching #ifdef or #ifndef");u.active=u.parentActive&&!u.branchTaken,u.branchTaken=!0,s=u.active}else f?(r.pop(),s=r.length?r[r.length-1].active:!0):s&&n.push(o)}if(r.length>0)throw new Error("Unterminated conditional block in shader source");return n.join(` `)}class Dt{static defaultShaderAssembler;_hookFunctions=[];_defaultModules=[];_wgslBindingRegistry=new Map;static getDefaultShaderAssembler(){return Dt.defaultShaderAssembler=Dt.defaultShaderAssembler||new Dt,Dt.defaultShaderAssembler}addDefaultModule(e){this._defaultModules.find(i=>i.name===(typeof e=="string"?e:e.name))||this._defaultModules.push(e)}removeDefaultModule(e){const i=typeof e=="string"?e:e.name;this._defaultModules=this._defaultModules.filter(n=>n.name!==i)}addShaderHook(e,i){i&&(e=Object.assign(i,{hook:e})),this._hookFunctions.push(e)}assembleWGSLShader(e){const i=this._getModuleList(e.modules),n=this._hookFunctions,{source:r,getUniforms:s,bindingAssignments:o}=K_({...e,source:e.source,_bindingRegistry:this._wgslBindingRegistry,modules:i,hookFunctions:n}),a={...i.reduce((l,f)=>(Object.assign(l,f.defines),l),{}),...e.defines},c=e.platformInfo.shaderLanguage==="wgsl"?AA(r,{defines:a}):r;return{source:c,getUniforms:s,modules:i,bindingAssignments:o,bindingTable:rh(c,o)}}assembleGLSLShaderPair(e){const i=this._getModuleList(e.modules),n=this._hookFunctions;return{...q_({...e,vs:e.vs,fs:e.fs,modules:i,hookFunctions:n}),modules:i}}_getModuleList(e=[]){const i=new Array(this._defaultModules.length+e.length),n={};let r=0;for(let s=0,o=this._defaultModules.length;sMath.max(e,Math.min(i,n)))}function Mr(t,e,i){return Ci(t)?t.map((n,r)=>Mr(n,e[r],i)):i*e+(1-i)*t}function gn(t,e,i){const n=ke.EPSILON;try{if(t===e)return!0;if(Ci(t)&&Ci(e)){if(t.length!==e.length)return!1;for(let r=0;r0?", ":"")+RA(this[n],e);return`${e.printTypes?this.constructor.name:""}[${i}]`}equals(e){if(!e||this.length!==e.length)return!1;for(let i=0;i=0&&e=0&&eMath.PI*2)throw Error("expected radians")}function _y(t,e,i,n,r,s){const o=2*s/(i-e),a=2*s/(r-n),c=(i+e)/(i-e),l=(r+n)/(r-n),f=-1,u=-1,h=-2*s;return t[0]=o,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=c,t[9]=l,t[10]=f,t[11]=u,t[12]=0,t[13]=0,t[14]=h,t[15]=0,t}function _h(t,e=[],i=0){const n=Math.fround(t),r=t-n;return e[i]=n,e[i+1]=r,e}function Ay(t){return t-Math.fround(t)}function yy(t){const e=new Float32Array(32);for(let i=0;i<4;++i)for(let n=0;n<4;++n){const r=i*4+n;_h(t[n*4+i],e,r*2)}return e}function by(t,e=!0){return t??e}function wy(t=[0,0,0],e=!0){return e?t.map(i=>i/255):[...t]}function Ty(t,e=!0){const i=wy(t.slice(0,3),e),n=Number.isFinite(t[3]),r=n?t[3]:1;return[i[0],i[1],i[2],e&&n?r/255:r]}const Ey=`#ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND // All these functions are for substituting tan() function from Intel GPU only const float TWO_PI = 6.2831854820251465; const float PI_2 = 1.5707963705062866; const float PI_16 = 0.1963495463132858; const float SIN_TABLE_0 = 0.19509032368659973; const float SIN_TABLE_1 = 0.3826834261417389; const float SIN_TABLE_2 = 0.5555702447891235; const float SIN_TABLE_3 = 0.7071067690849304; const float COS_TABLE_0 = 0.9807852506637573; const float COS_TABLE_1 = 0.9238795042037964; const float COS_TABLE_2 = 0.8314695954322815; const float COS_TABLE_3 = 0.7071067690849304; const float INVERSE_FACTORIAL_3 = 1.666666716337204e-01; // 1/3! const float INVERSE_FACTORIAL_5 = 8.333333767950535e-03; // 1/5! const float INVERSE_FACTORIAL_7 = 1.9841270113829523e-04; // 1/7! const float INVERSE_FACTORIAL_9 = 2.75573188446287533e-06; // 1/9! float sin_taylor_fp32(float a) { float r, s, t, x; if (a == 0.0) { return 0.0; } x = -a * a; s = a; r = a; r = r * x; t = r * INVERSE_FACTORIAL_3; s = s + t; r = r * x; t = r * INVERSE_FACTORIAL_5; s = s + t; r = r * x; t = r * INVERSE_FACTORIAL_7; s = s + t; r = r * x; t = r * INVERSE_FACTORIAL_9; s = s + t; return s; } void sincos_taylor_fp32(float a, out float sin_t, out float cos_t) { if (a == 0.0) { sin_t = 0.0; cos_t = 1.0; } sin_t = sin_taylor_fp32(a); cos_t = sqrt(1.0 - sin_t * sin_t); } float tan_taylor_fp32(float a) { float sin_a; float cos_a; if (a == 0.0) { return 0.0; } // 2pi range reduction float z = floor(a / TWO_PI); float r = a - TWO_PI * z; float t; float q = floor(r / PI_2 + 0.5); int j = int(q); if (j < -2 || j > 2) { return 1.0 / 0.0; } t = r - PI_2 * q; q = floor(t / PI_16 + 0.5); int k = int(q); int abs_k = int(abs(float(k))); if (abs_k > 4) { return 1.0 / 0.0; } else { t = t - PI_16 * q; } float u = 0.0; float v = 0.0; float sin_t, cos_t; float s, c; sincos_taylor_fp32(t, sin_t, cos_t); if (k == 0) { s = sin_t; c = cos_t; } else { if (abs(float(abs_k) - 1.0) < 0.5) { u = COS_TABLE_0; v = SIN_TABLE_0; } else if (abs(float(abs_k) - 2.0) < 0.5) { u = COS_TABLE_1; v = SIN_TABLE_1; } else if (abs(float(abs_k) - 3.0) < 0.5) { u = COS_TABLE_2; v = SIN_TABLE_2; } else if (abs(float(abs_k) - 4.0) < 0.5) { u = COS_TABLE_3; v = SIN_TABLE_3; } if (k > 0) { s = u * sin_t + v * cos_t; c = u * cos_t - v * sin_t; } else { s = u * sin_t - v * cos_t; c = u * cos_t + v * sin_t; } } if (j == 0) { sin_a = s; cos_a = c; } else if (j == 1) { sin_a = c; cos_a = -s; } else if (j == -1) { sin_a = -c; cos_a = s; } else { sin_a = -s; cos_a = -c; } return sin_a / cos_a; } #endif float tan_fp32(float a) { #ifdef LUMA_FP32_TAN_PRECISION_WORKAROUND return tan_taylor_fp32(a); #else return tan(a); #endif } `,Sy={name:"fp32",vs:Ey},Zc=` layout(std140) uniform fp64arithmeticUniforms { uniform float ONE; uniform float SPLIT; } fp64; /* About LUMA_FP64_CODE_ELIMINATION_WORKAROUND The purpose of this workaround is to prevent shader compilers from optimizing away necessary arithmetic operations by swapping their sequences or transform the equation to some 'equivalent' form. These helpers implement Dekker/Veltkamp-style error tracking. If the compiler folds constants or reassociates the arithmetic, the high/low split can stop tracking the rounding error correctly. That failure mode tends to look fine in simple coordinate setup, but then breaks down inside iterative arithmetic such as fp64 Mandelbrot loops. The method is to multiply an artifical variable, ONE, which will be known to the compiler to be 1 only at runtime. The whole expression is then represented as a polynomial with respective to ONE. In the coefficients of all terms, only one a and one b should appear err = (a + b) * ONE^6 - a * ONE^5 - (a + b) * ONE^4 + a * ONE^3 - b - (a + b) * ONE^2 + a * ONE */ float prevent_fp64_optimization(float value) { #if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) return value + fp64.ONE * 0.0; #else return value; #endif } // Divide float number to high and low floats to extend fraction bits vec2 split(float a) { // Keep SPLIT as a runtime uniform so the compiler cannot fold the Dekker // split into a constant expression and reassociate the recovery steps. float split = prevent_fp64_optimization(fp64.SPLIT); float t = prevent_fp64_optimization(a * split); float temp = t - a; float a_hi = t - temp; float a_lo = a - a_hi; return vec2(a_hi, a_lo); } // Divide float number again when high float uses too many fraction bits vec2 split2(vec2 a) { vec2 b = split(a.x); b.y += a.y; return b; } // Special sum operation when a > b vec2 quickTwoSum(float a, float b) { #if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) float sum = (a + b) * fp64.ONE; float err = b - (sum - a) * fp64.ONE; #else float sum = a + b; float err = b - (sum - a); #endif return vec2(sum, err); } // General sum operation vec2 twoSum(float a, float b) { float s = (a + b); #if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) float v = (s * fp64.ONE - a) * fp64.ONE; float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE + (b - v); #else float v = s - a; float err = (a - (s - v)) + (b - v); #endif return vec2(s, err); } vec2 twoSub(float a, float b) { float s = (a - b); #if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) float v = (s * fp64.ONE - a) * fp64.ONE; float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE - (b + v); #else float v = s - a; float err = (a - (s - v)) - (b + v); #endif return vec2(s, err); } vec2 twoSqr(float a) { float prod = a * a; vec2 a_fp64 = split(a); #if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) float err = ((a_fp64.x * a_fp64.x - prod) * fp64.ONE + 2.0 * a_fp64.x * a_fp64.y * fp64.ONE * fp64.ONE) + a_fp64.y * a_fp64.y * fp64.ONE * fp64.ONE * fp64.ONE; #else float err = ((a_fp64.x * a_fp64.x - prod) + 2.0 * a_fp64.x * a_fp64.y) + a_fp64.y * a_fp64.y; #endif return vec2(prod, err); } vec2 twoProd(float a, float b) { float prod = a * b; vec2 a_fp64 = split(a); vec2 b_fp64 = split(b); // twoProd is especially sensitive because mul_fp64 and div_fp64 both depend // on the split terms and cross terms staying in the original evaluation // order. If the compiler folds or reassociates them, the low part tends to // collapse to zero or NaN on some drivers. float highProduct = prevent_fp64_optimization(a_fp64.x * b_fp64.x); float crossProduct1 = prevent_fp64_optimization(a_fp64.x * b_fp64.y); float crossProduct2 = prevent_fp64_optimization(a_fp64.y * b_fp64.x); float lowProduct = prevent_fp64_optimization(a_fp64.y * b_fp64.y); #if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) float err1 = (highProduct - prod) * fp64.ONE; float err2 = crossProduct1 * fp64.ONE * fp64.ONE; float err3 = crossProduct2 * fp64.ONE * fp64.ONE * fp64.ONE; float err4 = lowProduct * fp64.ONE * fp64.ONE * fp64.ONE * fp64.ONE; #else float err1 = highProduct - prod; float err2 = crossProduct1; float err3 = crossProduct2; float err4 = lowProduct; #endif float err = ((err1 + err2) + err3) + err4; return vec2(prod, err); } vec2 sum_fp64(vec2 a, vec2 b) { vec2 s, t; s = twoSum(a.x, b.x); t = twoSum(a.y, b.y); s.y += t.x; s = quickTwoSum(s.x, s.y); s.y += t.y; s = quickTwoSum(s.x, s.y); return s; } vec2 sub_fp64(vec2 a, vec2 b) { vec2 s, t; s = twoSub(a.x, b.x); t = twoSub(a.y, b.y); s.y += t.x; s = quickTwoSum(s.x, s.y); s.y += t.y; s = quickTwoSum(s.x, s.y); return s; } vec2 mul_fp64(vec2 a, vec2 b) { vec2 prod = twoProd(a.x, b.x); // y component is for the error prod.y += a.x * b.y; #if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) prod = split2(prod); #endif prod = quickTwoSum(prod.x, prod.y); prod.y += a.y * b.x; #if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) prod = split2(prod); #endif prod = quickTwoSum(prod.x, prod.y); return prod; } vec2 div_fp64(vec2 a, vec2 b) { float xn = 1.0 / b.x; #if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) vec2 yn = mul_fp64(a, vec2(xn, 0)); #else vec2 yn = a * xn; #endif float diff = (sub_fp64(a, mul_fp64(b, yn))).x; vec2 prod = twoProd(xn, diff); return sum_fp64(yn, prod); } vec2 sqrt_fp64(vec2 a) { if (a.x == 0.0 && a.y == 0.0) return vec2(0.0, 0.0); if (a.x < 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0); float x = 1.0 / sqrt(a.x); float yn = a.x * x; #if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND) vec2 yn_sqr = twoSqr(yn) * fp64.ONE; #else vec2 yn_sqr = twoSqr(yn); #endif float diff = sub_fp64(a, yn_sqr).x; vec2 prod = twoProd(x * 0.5, diff); #if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND) return sum_fp64(split(yn), prod); #else return sum_fp64(vec2(yn, 0.0), prod); #endif } `,Ry=`struct Fp64ArithmeticUniforms { ONE: f32, SPLIT: f32, }; @group(0) @binding(auto) var fp64arithmetic : Fp64ArithmeticUniforms; fn fp64_nan(seed: f32) -> f32 { let nanBits = 0x7fc00000u | select(0u, 1u, seed < 0.0); return bitcast(nanBits); } fn fp64_runtime_zero() -> f32 { return fp64arithmetic.ONE * 0.0; } fn prevent_fp64_optimization(value: f32) -> f32 { #ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND return value + fp64_runtime_zero(); #else return value; #endif } fn split(a: f32) -> vec2f { let splitValue = prevent_fp64_optimization(fp64arithmetic.SPLIT + fp64_runtime_zero()); let t = prevent_fp64_optimization(a * splitValue); let temp = prevent_fp64_optimization(t - a); let aHi = prevent_fp64_optimization(t - temp); let aLo = prevent_fp64_optimization(a - aHi); return vec2f(aHi, aLo); } fn split2(a: vec2f) -> vec2f { var b = split(a.x); b.y = b.y + a.y; return b; } fn quickTwoSum(a: f32, b: f32) -> vec2f { #ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND let sum = prevent_fp64_optimization((a + b) * fp64arithmetic.ONE); let err = prevent_fp64_optimization(b - (sum - a) * fp64arithmetic.ONE); #else let sum = prevent_fp64_optimization(a + b); let err = prevent_fp64_optimization(b - (sum - a)); #endif return vec2f(sum, err); } fn twoSum(a: f32, b: f32) -> vec2f { let s = prevent_fp64_optimization(a + b); #ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE); let err = prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE) + prevent_fp64_optimization(b - v); #else let v = prevent_fp64_optimization(s - a); let err = prevent_fp64_optimization(a - (s - v)) + prevent_fp64_optimization(b - v); #endif return vec2f(s, err); } fn twoSub(a: f32, b: f32) -> vec2f { let s = prevent_fp64_optimization(a - b); #ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE); let err = prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE) - prevent_fp64_optimization(b + v); #else let v = prevent_fp64_optimization(s - a); let err = prevent_fp64_optimization(a - (s - v)) - prevent_fp64_optimization(b + v); #endif return vec2f(s, err); } fn twoSqr(a: f32) -> vec2f { let prod = prevent_fp64_optimization(a * a); let aFp64 = split(a); let highProduct = prevent_fp64_optimization(aFp64.x * aFp64.x); let crossProduct = prevent_fp64_optimization(2.0 * aFp64.x * aFp64.y); let lowProduct = prevent_fp64_optimization(aFp64.y * aFp64.y); #ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND let err = (prevent_fp64_optimization(highProduct - prod) * fp64arithmetic.ONE + crossProduct * fp64arithmetic.ONE * fp64arithmetic.ONE) + lowProduct * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE; #else let err = ((prevent_fp64_optimization(highProduct - prod) + crossProduct) + lowProduct); #endif return vec2f(prod, err); } fn twoProd(a: f32, b: f32) -> vec2f { let prod = prevent_fp64_optimization(a * b); let aFp64 = split(a); let bFp64 = split(b); let highProduct = prevent_fp64_optimization(aFp64.x * bFp64.x); let crossProduct1 = prevent_fp64_optimization(aFp64.x * bFp64.y); let crossProduct2 = prevent_fp64_optimization(aFp64.y * bFp64.x); let lowProduct = prevent_fp64_optimization(aFp64.y * bFp64.y); #ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND let err1 = (highProduct - prod) * fp64arithmetic.ONE; let err2 = crossProduct1 * fp64arithmetic.ONE * fp64arithmetic.ONE; let err3 = crossProduct2 * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE; let err4 = lowProduct * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE; #else let err1 = highProduct - prod; let err2 = crossProduct1; let err3 = crossProduct2; let err4 = lowProduct; #endif let err12InputA = prevent_fp64_optimization(err1); let err12InputB = prevent_fp64_optimization(err2); let err12 = prevent_fp64_optimization(err12InputA + err12InputB); let err123InputA = prevent_fp64_optimization(err12); let err123InputB = prevent_fp64_optimization(err3); let err123 = prevent_fp64_optimization(err123InputA + err123InputB); let err1234InputA = prevent_fp64_optimization(err123); let err1234InputB = prevent_fp64_optimization(err4); let err = prevent_fp64_optimization(err1234InputA + err1234InputB); return vec2f(prod, err); } fn sum_fp64(a: vec2f, b: vec2f) -> vec2f { var s = twoSum(a.x, b.x); let t = twoSum(a.y, b.y); s.y = prevent_fp64_optimization(s.y + t.x); s = quickTwoSum(s.x, s.y); s.y = prevent_fp64_optimization(s.y + t.y); s = quickTwoSum(s.x, s.y); return s; } fn sub_fp64(a: vec2f, b: vec2f) -> vec2f { var s = twoSub(a.x, b.x); let t = twoSub(a.y, b.y); s.y = prevent_fp64_optimization(s.y + t.x); s = quickTwoSum(s.x, s.y); s.y = prevent_fp64_optimization(s.y + t.y); s = quickTwoSum(s.x, s.y); return s; } fn mul_fp64(a: vec2f, b: vec2f) -> vec2f { var prod = twoProd(a.x, b.x); let crossProduct1 = prevent_fp64_optimization(a.x * b.y); prod.y = prevent_fp64_optimization(prod.y + crossProduct1); #ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND prod = split2(prod); #endif prod = quickTwoSum(prod.x, prod.y); let crossProduct2 = prevent_fp64_optimization(a.y * b.x); prod.y = prevent_fp64_optimization(prod.y + crossProduct2); #ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND prod = split2(prod); #endif prod = quickTwoSum(prod.x, prod.y); return prod; } fn div_fp64(a: vec2f, b: vec2f) -> vec2f { let xn = prevent_fp64_optimization(1.0 / b.x); let yn = mul_fp64(a, vec2f(xn, fp64_runtime_zero())); let diff = prevent_fp64_optimization(sub_fp64(a, mul_fp64(b, yn)).x); let prod = twoProd(xn, diff); return sum_fp64(yn, prod); } fn sqrt_fp64(a: vec2f) -> vec2f { if (a.x == 0.0 && a.y == 0.0) { return vec2f(0.0, 0.0); } if (a.x < 0.0) { let nanValue = fp64_nan(a.x); return vec2f(nanValue, nanValue); } let x = prevent_fp64_optimization(1.0 / sqrt(a.x)); let yn = prevent_fp64_optimization(a.x * x); #ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND let ynSqr = twoSqr(yn) * fp64arithmetic.ONE; #else let ynSqr = twoSqr(yn); #endif let diff = prevent_fp64_optimization(sub_fp64(a, ynSqr).x); let prod = twoProd(prevent_fp64_optimization(x * 0.5), diff); #ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND return sum_fp64(split(yn), prod); #else return sum_fp64(vec2f(yn, 0.0), prod); #endif } `,vy={ONE:1,SPLIT:4097},Cy={name:"fp64arithmetic",source:Ry,fs:Zc,vs:Zc,defaultUniforms:vy,uniformTypes:{ONE:"f32",SPLIT:"f32"},fp64ify:_h,fp64LowPart:Ay,fp64ifyMatrix4:yy},Py=[0,1,1,1],Iy=`layout(std140) uniform pickingUniforms { float isActive; float isAttribute; float isHighlightActive; float useByteColors; vec3 highlightedObjectColor; vec4 highlightColor; } picking; out vec4 picking_vRGBcolor_Avalid; // Normalize unsigned byte color to 0-1 range vec3 picking_normalizeColor(vec3 color) { return picking.useByteColors > 0.5 ? color / 255.0 : color; } // Normalize unsigned byte color to 0-1 range vec4 picking_normalizeColor(vec4 color) { return picking.useByteColors > 0.5 ? color / 255.0 : color; } bool picking_isColorZero(vec3 color) { return dot(color, vec3(1.0)) < 0.00001; } bool picking_isColorValid(vec3 color) { return dot(color, vec3(1.0)) > 0.00001; } // Check if this vertex is highlighted bool isVertexHighlighted(vec3 vertexColor) { vec3 highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); return bool(picking.isHighlightActive) && picking_isColorZero(abs(vertexColor - highlightedObjectColor)); } // Set the current picking color void picking_setPickingColor(vec3 pickingColor) { pickingColor = picking_normalizeColor(pickingColor); if (bool(picking.isActive)) { // Use alpha as the validity flag. If pickingColor is [0, 0, 0] fragment is non-pickable picking_vRGBcolor_Avalid.a = float(picking_isColorValid(pickingColor)); if (!bool(picking.isAttribute)) { // Stores the picking color so that the fragment shader can render it during picking picking_vRGBcolor_Avalid.rgb = pickingColor; } } else { // Do the comparison with selected item color in vertex shader as it should mean fewer compares picking_vRGBcolor_Avalid.a = float(isVertexHighlighted(pickingColor)); } } void picking_setPickingAttribute(float value) { if (bool(picking.isAttribute)) { picking_vRGBcolor_Avalid.r = value; } } void picking_setPickingAttribute(vec2 value) { if (bool(picking.isAttribute)) { picking_vRGBcolor_Avalid.rg = value; } } void picking_setPickingAttribute(vec3 value) { if (bool(picking.isAttribute)) { picking_vRGBcolor_Avalid.rgb = value; } } `,xy=`layout(std140) uniform pickingUniforms { float isActive; float isAttribute; float isHighlightActive; float useByteColors; vec3 highlightedObjectColor; vec4 highlightColor; } picking; in vec4 picking_vRGBcolor_Avalid; /* * Returns highlight color if this item is selected. */ vec4 picking_filterHighlightColor(vec4 color) { // If we are still picking, we don't highlight if (picking.isActive > 0.5) { return color; } bool selected = bool(picking_vRGBcolor_Avalid.a); if (selected) { // Blend in highlight color based on its alpha value float highLightAlpha = picking.highlightColor.a; float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha); float highLightRatio = highLightAlpha / blendedAlpha; vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio); return vec4(blendedRGB, blendedAlpha); } else { return color; } } /* * Returns picking color if picking enabled else unmodified argument. */ vec4 picking_filterPickingColor(vec4 color) { if (bool(picking.isActive)) { if (picking_vRGBcolor_Avalid.a == 0.0) { discard; } return picking_vRGBcolor_Avalid; } return color; } /* * Returns picking color if picking is enabled if not * highlight color if this item is selected, otherwise unmodified argument. */ vec4 picking_filterColor(vec4 color) { vec4 highlightColor = picking_filterHighlightColor(color); return picking_filterPickingColor(highlightColor); } `,Gc={props:{},uniforms:{},name:"picking",uniformTypes:{isActive:"f32",isAttribute:"f32",isHighlightActive:"f32",useByteColors:"f32",highlightedObjectColor:"vec3",highlightColor:"vec4"},defaultUniforms:{isActive:!1,isAttribute:!1,isHighlightActive:!1,useByteColors:!0,highlightedObjectColor:[0,0,0],highlightColor:Py},vs:Iy,fs:xy,getUniforms:My};function My(t={},e){const i={},n=by(t.useByteColors,!0);if(t.highlightedObjectColor!==void 0)if(t.highlightedObjectColor===null)i.isHighlightActive=!1;else{i.isHighlightActive=!0;const r=t.highlightedObjectColor.slice(0,3);i.highlightedObjectColor=r}return t.highlightColor&&(i.highlightColor=Ty(t.highlightColor,n)),t.isActive!==void 0&&(i.isActive=!!t.isActive,i.isAttribute=!!t.isAttribute),t.useByteColors!==void 0&&(i.useByteColors=!!t.useByteColors),i}const Oy="GPU Time and Memory",By=["Adapter","GPU","GPU Type","GPU Backend","Frame Rate","CPU Time","GPU Time","GPU Memory","Buffer Memory","Texture Memory","Referenced Buffer Memory","Referenced Texture Memory","Swap Chain Texture"],Jc=new WeakMap,$c=new WeakMap;class Ny{stats=new Map;getStats(e){return this.get(e)}get(e){this.stats.has(e)||this.stats.set(e,new Xr({id:e}));const i=this.stats.get(e);return e===Oy&&Dy(i,By),i}}const Ah=new Ny;function Dy(t,e){const i=t.stats;let n=!1;for(const c of e)i[c]||(t.get(c),n=!0);const r=Object.keys(i).length,s=Jc.get(t);if(!n&&s?.orderedStatNames===e&&s.statCount===r)return;const o={};let a=$c.get(e);a||(a=new Set(e),$c.set(e,a));for(const c of e)i[c]&&(o[c]=i[c]);for(const[c,l]of Object.entries(i))a.has(c)||(o[c]=l);for(const c of Object.keys(i))delete i[c];Object.assign(i,o),Jc.set(t,{orderedStatNames:e,statCount:r})}const C=new Sn({id:"luma.gl"}),Cs={};function Cn(t="id"){Cs[t]=Cs[t]||1;const e=Cs[t]++;return`${t}-${e}`}const Fy="cpu-hotspot-profiler",el="GPU Resource Counts",tl="Resource Counts",il="GPU Time and Memory",Uy=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","ComputePasss","CommandEncoders","CommandBuffers"],ky=["Resources","Buffers","Textures","Samplers","TextureViews","Framebuffers","QuerySets","Shaders","RenderPipelines","SharedRenderPipelines","ComputePipelines","PipelineLayouts","VertexArrays","RenderPasss","ComputePasss","CommandEncoders","CommandBuffers"],Ly=Uy.flatMap(t=>[`${t} Created`,`${t} Active`]),Wy=ky.flatMap(t=>[`${t} Created`,`${t} Active`]),nl=new WeakMap,rl=new WeakMap;let Q=class{static defaultProps={id:"undefined",handle:void 0,userData:void 0};toString(){return`${this[Symbol.toStringTag]||this.constructor.name}:"${this.id}"`}id;props;userData={};_device;destroyed=!1;allocatedBytes=0;allocatedBytesName=null;_attachedResources=new Set;constructor(e,i,n){if(!e)throw new Error("no device");this._device=e,this.props=Vy(i,n);const r=this.props.id!=="undefined"?this.props.id:Cn(this[Symbol.toStringTag]);this.props.id=r,this.id=r,this.userData=this.props.userData||{},this.addStats()}destroy(){this.destroyed||this.destroyResource()}delete(){return this.destroy(),this}getProps(){return this.props}attachResource(e){this._attachedResources.add(e)}detachResource(e){this._attachedResources.delete(e)}destroyAttachedResource(e){this._attachedResources.delete(e)&&e.destroy()}destroyAttachedResources(){for(const e of this._attachedResources)e.destroy();this._attachedResources=new Set}destroyResource(){this.destroyed||(this.destroyAttachedResources(),this.removeStats(),this.destroyed=!0)}removeStats(){const e=qi(this._device),i=e?ht():0,n=[this._device.statsManager.getStats(el),this._device.statsManager.getStats(tl)],r=ol(this._device);for(const o of n)sl(o,r);const s=this.getStatsName();for(const o of n)o.get("Resources Active").decrementCount(),o.get(`${s}s Active`).decrementCount();e&&(e.statsBookkeepingCalls=(e.statsBookkeepingCalls||0)+1,e.statsBookkeepingTimeMs=(e.statsBookkeepingTimeMs||0)+(ht()-i))}trackAllocatedMemory(e,i=this.getStatsName()){const n=qi(this._device),r=n?ht():0,s=this._device.statsManager.getStats(il);this.allocatedBytes>0&&this.allocatedBytesName&&(s.get("GPU Memory").subtractCount(this.allocatedBytes),s.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes)),s.get("GPU Memory").addCount(e),s.get(`${i} Memory`).addCount(e),n&&(n.statsBookkeepingCalls=(n.statsBookkeepingCalls||0)+1,n.statsBookkeepingTimeMs=(n.statsBookkeepingTimeMs||0)+(ht()-r)),this.allocatedBytes=e,this.allocatedBytesName=i}trackReferencedMemory(e,i=this.getStatsName()){this.trackAllocatedMemory(e,`Referenced ${i}`)}trackDeallocatedMemory(e=this.getStatsName()){if(this.allocatedBytes===0){this.allocatedBytesName=null;return}const i=qi(this._device),n=i?ht():0,r=this._device.statsManager.getStats(il);r.get("GPU Memory").subtractCount(this.allocatedBytes),r.get(`${this.allocatedBytesName||e} Memory`).subtractCount(this.allocatedBytes),i&&(i.statsBookkeepingCalls=(i.statsBookkeepingCalls||0)+1,i.statsBookkeepingTimeMs=(i.statsBookkeepingTimeMs||0)+(ht()-n)),this.allocatedBytes=0,this.allocatedBytesName=null}trackDeallocatedReferencedMemory(e=this.getStatsName()){this.trackDeallocatedMemory(`Referenced ${e}`)}addStats(){const e=this.getStatsName(),i=qi(this._device),n=i?ht():0,r=[this._device.statsManager.getStats(el),this._device.statsManager.getStats(tl)],s=ol(this._device);for(const o of r)sl(o,s);for(const o of r)o.get("Resources Created").incrementCount(),o.get("Resources Active").incrementCount(),o.get(`${e}s Created`).incrementCount(),o.get(`${e}s Active`).incrementCount();i&&(i.statsBookkeepingCalls=(i.statsBookkeepingCalls||0)+1,i.statsBookkeepingTimeMs=(i.statsBookkeepingTimeMs||0)+(ht()-n)),zy(this._device,e)}getStatsName(){return jy(this)}};function Vy(t,e){const i={...e};for(const n in t)t[n]!==void 0&&(i[n]=t[n]);return i}function sl(t,e){const i=t.stats;let n=!1;for(const c of e)i[c]||(t.get(c),n=!0);const r=Object.keys(i).length,s=nl.get(t);if(!n&&s?.orderedStatNames===e&&s.statCount===r)return;const o={};let a=rl.get(e);a||(a=new Set(e),rl.set(e,a));for(const c of e)i[c]&&(o[c]=i[c]);for(const[c,l]of Object.entries(i))a.has(c)||(o[c]=l);for(const c of Object.keys(i))delete i[c];Object.assign(i,o),nl.set(t,{orderedStatNames:e,statCount:r})}function ol(t){return t.type==="webgl"?Wy:Ly}function qi(t){const e=t.userData[Fy];return e?.enabled?e:null}function ht(){return globalThis.performance?.now?.()??Date.now()}function zy(t,e){const i=qi(t);if(!(!i||!i.activeDefaultFramebufferAcquireDepth))switch(i.transientCanvasResourceCreates=(i.transientCanvasResourceCreates||0)+1,e){case"Texture":i.transientCanvasTextureCreates=(i.transientCanvasTextureCreates||0)+1;break;case"TextureView":i.transientCanvasTextureViewCreates=(i.transientCanvasTextureViewCreates||0)+1;break;case"Sampler":i.transientCanvasSamplerCreates=(i.transientCanvasSamplerCreates||0)+1;break;case"Framebuffer":i.transientCanvasFramebufferCreates=(i.transientCanvasFramebufferCreates||0)+1;break}}function jy(t){let e=Object.getPrototypeOf(t);for(;e;){const i=Object.getPrototypeOf(e);if(!i||i===Q.prototype)return Hy(e)||t[Symbol.toStringTag]||t.constructor.name;e=i}return t[Symbol.toStringTag]||t.constructor.name}function Hy(t){const e=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);return typeof e?.get=="function"?e.get.call(t):typeof e?.value=="string"?e.value:null}class q extends Q{static INDEX=16;static VERTEX=32;static UNIFORM=64;static STORAGE=128;static INDIRECT=256;static QUERY_RESOLVE=512;static MAP_READ=1;static MAP_WRITE=2;static COPY_SRC=4;static COPY_DST=8;get[Symbol.toStringTag](){return"Buffer"}usage;indexType;updateTimestamp;constructor(e,i){const n={...i};(i.usage||0)&q.INDEX&&!i.indexType&&(i.data instanceof Uint32Array?n.indexType="uint32":i.data instanceof Uint16Array?n.indexType="uint16":i.data instanceof Uint8Array&&(n.indexType="uint8")),delete n.data,super(e,n,q.defaultProps),this.usage=n.usage||0,this.indexType=n.indexType,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createBuffer({...this.props,...e})}static DEBUG_DATA_MAX_LENGTH=32;debugData=new ArrayBuffer(0);_setDebugData(e,i,n){let r=null,s;ArrayBuffer.isView(e)?(r=e,s=e.buffer):s=e;const o=Math.min(e?e.byteLength:n,q.DEBUG_DATA_MAX_LENGTH);if(s===null)this.debugData=new ArrayBuffer(o);else{const a=Math.min(r?.byteOffset||0,s.byteLength),c=Math.max(0,s.byteLength-a),l=Math.min(o,c);this.debugData=new Uint8Array(s,a,l).slice().buffer}}static defaultProps={...Q.defaultProps,usage:0,byteLength:0,byteOffset:0,data:null,indexType:"uint16",onMapped:void 0}}class Yy{getDataTypeInfo(e){const[i,n,r]=Ps[e],s=e.includes("norm"),o=!s&&!e.startsWith("float"),a=e.startsWith("s");return{signedType:i,primitiveType:n,byteLength:r,normalized:s,integer:o,signed:a}}getNormalizedDataType(e){const i=e;switch(i){case"uint8":return"unorm8";case"sint8":return"snorm8";case"uint16":return"unorm16";case"sint16":return"snorm16";default:return i}}alignTo(e,i){switch(i){case 1:return e;case 2:return e+e%2;default:return e+(4-e%4)%4}}getDataType(e){const i=ArrayBuffer.isView(e)?e.constructor:e;if(i===Uint8ClampedArray)return"uint8";const n=Object.values(Ps).find(r=>i===r[4]);if(!n)throw new Error(i.name);return n[0]}getTypedArrayConstructor(e){const[,,,,i]=Ps[e];return i}}const ot=new Yy,Ps={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]};class Xy{getVertexFormatInfo(e){let i;e.endsWith("-webgl")&&(e.replace("-webgl",""),i=!0);const[n,r]=e.split("x"),s=n,o=r?parseInt(r):1,a=ot.getDataTypeInfo(s),c={type:s,components:o,byteLength:a.byteLength*o,integer:a.integer,signed:a.signed,normalized:a.normalized};return i&&(c.webglOnly=!0),c}makeVertexFormat(e,i,n){const r=n?ot.getNormalizedDataType(e):e;switch(r){case"unorm8":return i===1?"unorm8":i===3?"unorm8x3-webgl":`${r}x${i}`;case"snorm8":return i===1?"snorm8":i===3?"snorm8x3-webgl":`${r}x${i}`;case"uint8":case"sint8":if(i===1||i===3)throw new Error(`size: ${i}`);return`${r}x${i}`;case"uint16":return i===1?"uint16":i===3?"uint16x3-webgl":`${r}x${i}`;case"sint16":return i===1?"sint16":i===3?"sint16x3-webgl":`${r}x${i}`;case"unorm16":return i===1?"unorm16":i===3?"unorm16x3-webgl":`${r}x${i}`;case"snorm16":return i===1?"snorm16":i===3?"snorm16x3-webgl":`${r}x${i}`;case"float16":if(i===1||i===3)throw new Error(`size: ${i}`);return`${r}x${i}`;default:return i===1?r:`${r}x${i}`}}getVertexFormatFromAttribute(e,i,n){if(!i||i>4)throw new Error(`size ${i}`);const r=i,s=ot.getDataType(e);return this.makeVertexFormat(s,r,n)}getCompatibleVertexFormat(e){let i;switch(e.primitiveType){case"f32":i="float32";break;case"i32":i="sint32";break;case"u32":i="uint32";break;case"f16":return e.components<=2?"float16x2":"float16x4"}return e.components===1?i:`${i}x${e.components}`}}const mn=new Xy,_e="texture-compression-bc",G="texture-compression-astc",Ge="texture-compression-etc2",Qy="texture-compression-etc1-webgl",Hn="texture-compression-pvrtc-webgl",Is="texture-compression-atc-webgl",Yn="float32-renderable-webgl",xs="float16-renderable-webgl",Ky="rgb9e5ufloat-renderable-webgl",Ms="snorm8-renderable-webgl",dt="norm16-webgl",Os="norm16-renderable-webgl",Bs="snorm16-renderable-webgl",Xn="float32-filterable",al="float16-filterable-webgl";function yh(t){const e=bh[t];if(!e)throw new Error(`Unsupported texture format ${t}`);return e}function qy(){return bh}const Zy={r8unorm:{},rg8unorm:{},"rgb8unorm-webgl":{},rgba8unorm:{},"rgba8unorm-srgb":{},r8snorm:{render:Ms},rg8snorm:{render:Ms},"rgb8snorm-webgl":{},rgba8snorm:{render:Ms},r8uint:{},rg8uint:{},rgba8uint:{},r8sint:{},rg8sint:{},rgba8sint:{},bgra8unorm:{},"bgra8unorm-srgb":{},r16unorm:{f:dt,render:Os},rg16unorm:{f:dt,render:Os},"rgb16unorm-webgl":{f:dt,render:!1},rgba16unorm:{f:dt,render:Os},r16snorm:{f:dt,render:Bs},rg16snorm:{f:dt,render:Bs},"rgb16snorm-webgl":{f:dt,render:!1},rgba16snorm:{f:dt,render:Bs},r16uint:{},rg16uint:{},rgba16uint:{},r16sint:{},rg16sint:{},rgba16sint:{},r16float:{render:xs,filter:"float16-filterable-webgl"},rg16float:{render:xs,filter:al},rgba16float:{render:xs,filter:al},r32uint:{},rg32uint:{},rgba32uint:{},r32sint:{},rg32sint:{},rgba32sint:{},r32float:{render:Yn,filter:Xn},rg32float:{render:!1,filter:Xn},"rgb32float-webgl":{render:Yn,filter:Xn},rgba32float:{render:Yn,filter:Xn},"rgba4unorm-webgl":{channels:"rgba",bitsPerChannel:[4,4,4,4],packed:!0},"rgb565unorm-webgl":{channels:"rgb",bitsPerChannel:[5,6,5,0],packed:!0},"rgb5a1unorm-webgl":{channels:"rgba",bitsPerChannel:[5,5,5,1],packed:!0},rgb9e5ufloat:{channels:"rgb",packed:!0,render:Ky},rg11b10ufloat:{channels:"rgb",bitsPerChannel:[11,11,10,0],packed:!0,p:1,render:Yn},rgb10a2unorm:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1},rgb10a2uint:{channels:"rgba",bitsPerChannel:[10,10,10,2],packed:!0,p:1},stencil8:{attachment:"stencil",bitsPerChannel:[8,0,0,0],dataType:"uint8"},depth16unorm:{attachment:"depth",bitsPerChannel:[16,0,0,0],dataType:"uint16"},depth24plus:{attachment:"depth",bitsPerChannel:[24,0,0,0],dataType:"uint32"},depth32float:{attachment:"depth",bitsPerChannel:[32,0,0,0],dataType:"float32"},"depth24plus-stencil8":{attachment:"depth-stencil",bitsPerChannel:[24,8,0,0],packed:!0},"depth32float-stencil8":{attachment:"depth-stencil",bitsPerChannel:[32,8,0,0],packed:!0}},Gy={"bc1-rgb-unorm-webgl":{f:_e},"bc1-rgb-unorm-srgb-webgl":{f:_e},"bc1-rgba-unorm":{f:_e},"bc1-rgba-unorm-srgb":{f:_e},"bc2-rgba-unorm":{f:_e},"bc2-rgba-unorm-srgb":{f:_e},"bc3-rgba-unorm":{f:_e},"bc3-rgba-unorm-srgb":{f:_e},"bc4-r-unorm":{f:_e},"bc4-r-snorm":{f:_e},"bc5-rg-unorm":{f:_e},"bc5-rg-snorm":{f:_e},"bc6h-rgb-ufloat":{f:_e},"bc6h-rgb-float":{f:_e},"bc7-rgba-unorm":{f:_e},"bc7-rgba-unorm-srgb":{f:_e},"etc2-rgb8unorm":{f:Ge},"etc2-rgb8unorm-srgb":{f:Ge},"etc2-rgb8a1unorm":{f:Ge},"etc2-rgb8a1unorm-srgb":{f:Ge},"etc2-rgba8unorm":{f:Ge},"etc2-rgba8unorm-srgb":{f:Ge},"eac-r11unorm":{f:Ge},"eac-r11snorm":{f:Ge},"eac-rg11unorm":{f:Ge},"eac-rg11snorm":{f:Ge},"astc-4x4-unorm":{f:G},"astc-4x4-unorm-srgb":{f:G},"astc-5x4-unorm":{f:G},"astc-5x4-unorm-srgb":{f:G},"astc-5x5-unorm":{f:G},"astc-5x5-unorm-srgb":{f:G},"astc-6x5-unorm":{f:G},"astc-6x5-unorm-srgb":{f:G},"astc-6x6-unorm":{f:G},"astc-6x6-unorm-srgb":{f:G},"astc-8x5-unorm":{f:G},"astc-8x5-unorm-srgb":{f:G},"astc-8x6-unorm":{f:G},"astc-8x6-unorm-srgb":{f:G},"astc-8x8-unorm":{f:G},"astc-8x8-unorm-srgb":{f:G},"astc-10x5-unorm":{f:G},"astc-10x5-unorm-srgb":{f:G},"astc-10x6-unorm":{f:G},"astc-10x6-unorm-srgb":{f:G},"astc-10x8-unorm":{f:G},"astc-10x8-unorm-srgb":{f:G},"astc-10x10-unorm":{f:G},"astc-10x10-unorm-srgb":{f:G},"astc-12x10-unorm":{f:G},"astc-12x10-unorm-srgb":{f:G},"astc-12x12-unorm":{f:G},"astc-12x12-unorm-srgb":{f:G},"pvrtc-rgb4unorm-webgl":{f:Hn},"pvrtc-rgba4unorm-webgl":{f:Hn},"pvrtc-rgb2unorm-webgl":{f:Hn},"pvrtc-rgba2unorm-webgl":{f:Hn},"etc1-rbg-unorm-webgl":{f:Qy},"atc-rgb-unorm-webgl":{f:Is},"atc-rgba-unorm-webgl":{f:Is},"atc-rgbai-unorm-webgl":{f:Is}},bh={...Zy,...Gy},Jy=/^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/,$y=["rgb","rgba","bgra"],e0=["depth","stencil"],t0=["bc1","bc2","bc3","bc4","bc5","bc6","bc7","etc1","etc2","eac","atc","astc","pvrtc"];class i0{isColor(e){return $y.some(i=>e.startsWith(i))}isDepthStencil(e){return e0.some(i=>e.startsWith(i))}isCompressed(e){return t0.some(i=>e.startsWith(i))}getInfo(e){return wh(e)}getCapabilities(e){return r0(e)}computeMemoryLayout(e){return n0(e)}}const He=new i0;function n0({format:t,width:e,height:i,depth:n,byteAlignment:r}){const s=He.getInfo(t),{bytesPerPixel:o,bytesPerBlock:a=o,blockWidth:c=1,blockHeight:l=1,compressed:f=!1}=s,u=f?Math.ceil(e/c):e,h=f?Math.ceil(i/l):i,p=u*a,d=Math.ceil(p/r)*r,m=h,g=d*m*n;return{bytesPerPixel:o,bytesPerRow:d,rowsPerImage:m,depthOrArrayLayers:n,bytesPerImage:d*m,byteLength:g}}function r0(t){const e=yh(t),i={format:t,create:e.f??!0,render:e.render??!0,filter:e.filter??!0,blend:e.blend??!0,store:e.store??!0},n=wh(t),r=t.startsWith("depth")||t.startsWith("stencil"),s=n?.signed,o=n?.integer,a=n?.webgl,c=!!n?.compressed;return i.render&&=!r&&!c,i.filter&&=!r&&!s&&!o&&!a,i}function wh(t){let e=s0(t);if(He.isCompressed(t)){e.channels="rgb",e.components=3,e.bytesPerPixel=1,e.srgb=!1,e.compressed=!0,e.bytesPerBlock=a0(t);const n=o0(t);n&&(e.blockWidth=n.blockWidth,e.blockHeight=n.blockHeight)}const i=e.packed?null:Jy.exec(t);if(i){const[,n,r,s,o,a]=i,c=`${s}${r}`,l=ot.getDataTypeInfo(c),f=l.byteLength*8,u=n?.length??1,h=[f,u>=2?f:0,u>=3?f:0,u>=4?f:0];e={format:t,attachment:e.attachment,dataType:l.signedType,components:u,channels:n,integer:l.integer,signed:l.signed,normalized:l.normalized,bitsPerChannel:h,bytesPerPixel:l.byteLength*u,packed:e.packed,srgb:e.srgb},a==="-webgl"&&(e.webgl=!0),o==="-srgb"&&(e.srgb=!0)}return t.endsWith("-webgl")&&(e.webgl=!0),t.endsWith("-srgb")&&(e.srgb=!0),e}function s0(t){const e=yh(t),i=e.bytesPerPixel||1,n=e.bitsPerChannel||[8,8,8,8];return delete e.bitsPerChannel,delete e.bytesPerPixel,delete e.f,delete e.render,delete e.filter,delete e.blend,delete e.store,{...e,format:t,attachment:e.attachment||"color",channels:e.channels||"r",components:e.components||e.channels?.length||1,bytesPerPixel:i,bitsPerChannel:n,dataType:e.dataType||"uint8",srgb:e.srgb??!1,packed:e.packed??!1,webgl:e.webgl??!1,integer:e.integer??!1,signed:e.signed??!1,normalized:e.normalized??!1,compressed:e.compressed??!1}}function o0(t){const i=/.*-(\d+)x(\d+)-.*/.exec(t);if(i){const[,n,r]=i;return{blockWidth:Number(n),blockHeight:Number(r)}}return t.startsWith("bc")||t.startsWith("etc1")||t.startsWith("etc2")||t.startsWith("eac")||t.startsWith("atc")?{blockWidth:4,blockHeight:4}:t.startsWith("pvrtc-rgb4")||t.startsWith("pvrtc-rgba4")?{blockWidth:4,blockHeight:4}:t.startsWith("pvrtc-rgb2")||t.startsWith("pvrtc-rgba2")?{blockWidth:8,blockHeight:4}:null}function a0(t){return t.startsWith("bc1")||t.startsWith("bc4")||t.startsWith("etc1")||t.startsWith("etc2-rgb8")||t.startsWith("etc2-rgb8a1")||t.startsWith("eac-r11")||t==="atc-rgb-unorm-webgl"?8:t.startsWith("bc2")||t.startsWith("bc3")||t.startsWith("bc5")||t.startsWith("bc6h")||t.startsWith("bc7")||t.startsWith("etc2-rgba8")||t.startsWith("eac-rg11")||t.startsWith("astc")||t==="atc-rgba-unorm-webgl"||t==="atc-rgbai-unorm-webgl"?16:t.startsWith("pvrtc")?8:16}function Ia(t){return typeof ImageData<"u"&&t instanceof ImageData||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement||typeof VideoFrame<"u"&&t instanceof VideoFrame||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas}function Th(t){if(typeof ImageData<"u"&&t instanceof ImageData||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return{width:t.width,height:t.height};if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement)return{width:t.naturalWidth,height:t.naturalHeight};if(typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement)return{width:t.videoWidth,height:t.videoHeight};if(typeof VideoFrame<"u"&&t instanceof VideoFrame)return{width:t.displayWidth,height:t.displayHeight};throw new Error("Unknown image type")}class c0{}function l0(t,e){const i=Eo(t),n=e.map(Eo).filter(r=>r!==void 0);return[i,...n].filter(r=>r!==void 0)}function Eo(t){if(t!==void 0){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(t instanceof Error)return t.message;if(Array.isArray(t))return t.map(Eo);if(typeof t=="object"){if(f0(t)){const e=String(t);if(e!=="[object Object]")return e}return u0(t)?h0(t):t.constructor?.name||"Object"}return String(t)}}function f0(t){return"toString"in t&&typeof t.toString=="function"&&t.toString!==Object.prototype.toString}function u0(t){return"message"in t&&"type"in t}function h0(t){const e=typeof t.type=="string"?t.type:"message",i=typeof t.message=="string"?t.message:"",n=typeof t.lineNum=="number"?t.lineNum:null,r=typeof t.linePos=="number"?t.linePos:null,s=n!==null&&r!==null?` @ ${n}:${r}`:n!==null?` @ ${n}`:"";return`${e}${s}: ${i}`.trim()}class d0{features;disabledFeatures;constructor(e=[],i){this.features=new Set(e),this.disabledFeatures=i||{}}*[Symbol.iterator](){yield*this.features}has(e){return!this.disabledFeatures?.[e]&&this.features.has(e)}}class Zt{static defaultProps={id:null,powerPreference:"high-performance",failIfMajorPerformanceCaveat:!1,createCanvasContext:void 0,webgl:{},onError:(e,i)=>{},onResize:(e,i)=>{const[n,r]=e.getDevicePixelSize();C.log(1,`${e} resized => ${n}x${r}px`)()},onPositionChange:(e,i)=>{const[n,r]=e.getPosition();C.log(1,`${e} repositioned => ${n},${r}`)()},onVisibilityChange:e=>C.log(1,`${e} Visibility changed ${e.isVisible}`)(),onDevicePixelRatioChange:(e,i)=>C.log(1,`${e} DPR changed ${i.oldRatio} => ${e.devicePixelRatio}`)(),debug:g0(),debugGPUTime:!1,debugShaders:C.get("debug-shaders")||void 0,debugFramebuffers:!!C.get("debug-framebuffers"),debugFactories:!!C.get("debug-factories"),debugWebGL:!!C.get("debug-webgl"),debugSpectorJS:void 0,debugSpectorJSUrl:void 0,_reuseDevices:!1,_requestMaxLimits:!0,_cacheShaders:!0,_destroyShaders:!1,_cachePipelines:!0,_sharePipelines:!0,_destroyPipelines:!1,_initializeFeatures:!0,_disabledFeatures:{"compilation-status-async-webgl":!0},_handle:void 0};get[Symbol.toStringTag](){return"Device"}toString(){return`Device(${this.id})`}id;props;userData={};statsManager=Ah;_factories={};timestamp=0;_reused=!1;_moduleData={};_textureCaps={};_debugGPUTimeQuery=null;constructor(e){this.props={...Zt.defaultProps,...e},this.id=this.props.id||Cn(this[Symbol.toStringTag].toLowerCase())}getVertexFormatInfo(e){return mn.getVertexFormatInfo(e)}isVertexFormatSupported(e){return!0}getTextureFormatInfo(e){return He.getInfo(e)}getTextureFormatCapabilities(e){let i=this._textureCaps[e];if(!i){const n=this._getDeviceTextureFormatCapabilities(e);i=this._getDeviceSpecificTextureFormatCapabilities(n),this._textureCaps[e]=i}return i}getMipLevelCount(e,i,n=1){const r=Math.max(e,i,n);return 1+Math.floor(Math.log2(r))}isExternalImage(e){return Ia(e)}getExternalImageSize(e){return Th(e)}isTextureFormatSupported(e){return this.getTextureFormatCapabilities(e).create}isTextureFormatFilterable(e){return this.getTextureFormatCapabilities(e).filter}isTextureFormatRenderable(e){return this.getTextureFormatCapabilities(e).render}isTextureFormatCompressed(e){return He.isCompressed(e)}getSupportedCompressedTextureFormats(){const e=[];for(const i of Object.keys(qy()))this.isTextureFormatCompressed(i)&&this.isTextureFormatSupported(i)&&e.push(i);return e}pushDebugGroup(e){this.commandEncoder.pushDebugGroup(e)}popDebugGroup(){this.commandEncoder?.popDebugGroup()}insertDebugMarker(e){this.commandEncoder?.insertDebugMarker(e)}loseDevice(){return!1}incrementTimestamp(){return this.timestamp++}reportError(e,i,...n){if(!this.props.onError(e,i)){const s=l0(i,n);return C.error(this.type==="webgl"?"%cWebGL":"%cWebGPU","color: white; background: red; padding: 2px 6px; border-radius: 3px;",e.message,...s)}return()=>{}}debug(){if(this.props.debug)debugger;else C.once(0,`'Type luma.log.set({debug: true}) in console to enable debug breakpoints', or create a device with the 'debug: true' prop.`)()}getDefaultCanvasContext(){if(!this.canvasContext)throw new Error("Device has no default CanvasContext. See props.createCanvasContext");return this.canvasContext}createFence(){throw new Error("createFence() not implemented")}beginRenderPass(e){return this.commandEncoder.beginRenderPass(e)}beginComputePass(e){return this.commandEncoder.beginComputePass(e)}generateMipmapsWebGPU(e){throw new Error("not implemented")}_createSharedRenderPipelineWebGL(e){throw new Error("_createSharedRenderPipelineWebGL() not implemented")}_createBindGroupLayoutWebGPU(e,i){throw new Error("_createBindGroupLayoutWebGPU() not implemented")}_createBindGroupWebGPU(e,i,n,r,s){throw new Error("_createBindGroupWebGPU() not implemented")}_supportsDebugGPUTime(){return this.features.has("timestamp-query")&&!!(this.props.debug||this.props.debugGPUTime)}_enableDebugGPUTime(e=256){if(!this._supportsDebugGPUTime())return null;if(this._debugGPUTimeQuery)return this._debugGPUTimeQuery;try{this._debugGPUTimeQuery=this.createQuerySet({type:"timestamp",count:e}),this.commandEncoder=this.createCommandEncoder({id:this.commandEncoder.props.id,timeProfilingQuerySet:this._debugGPUTimeQuery})}catch{this._debugGPUTimeQuery=null}return this._debugGPUTimeQuery}_disableDebugGPUTime(){this._debugGPUTimeQuery&&(this.commandEncoder.getTimeProfilingQuerySet()===this._debugGPUTimeQuery&&(this.commandEncoder=this.createCommandEncoder({id:this.commandEncoder.props.id})),this._debugGPUTimeQuery.destroy(),this._debugGPUTimeQuery=null)}_isDebugGPUTimeEnabled(){return this._debugGPUTimeQuery!==null}getCanvasContext(){return this.getDefaultCanvasContext()}readPixelsToArrayWebGL(e,i){throw new Error("not implemented")}readPixelsToBufferWebGL(e,i){throw new Error("not implemented")}setParametersWebGL(e){throw new Error("not implemented")}getParametersWebGL(e){throw new Error("not implemented")}withParametersWebGL(e,i){throw new Error("not implemented")}clearWebGL(e){throw new Error("not implemented")}resetWebGL(){throw new Error("not implemented")}getModuleData(e){return this._moduleData[e]||={},this._moduleData[e]}static _getCanvasContextProps(e){return e.createCanvasContext===!0?{}:e.createCanvasContext}_getDeviceTextureFormatCapabilities(e){const i=He.getCapabilities(e),n=s=>(typeof s=="string"?this.features.has(s):s)??!0,r=n(i.create);return{format:e,create:r,render:r&&n(i.render),filter:r&&n(i.filter),blend:r&&n(i.blend),store:r&&n(i.store)}}_normalizeBufferProps(e){(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e={data:e});const i={...e};if((e.usage||0)&q.INDEX&&(e.indexType||(e.data instanceof Uint32Array?i.indexType="uint32":e.data instanceof Uint16Array?i.indexType="uint16":e.data instanceof Uint8Array&&(i.data=new Uint16Array(e.data),i.indexType="uint16")),!i.indexType))throw new Error("indices buffer content must be of type uint16 or uint32");return i}}function p0(t,e){return t!=null?!!t:e!==void 0?e!=="production":!1}function g0(){return p0(C.get("debug"),m0())}function m0(){const t=globalThis.process;if(t?.env)return t.env.NODE_ENV}const _0="set luma.log.level=1 (or higher) to trace rendering",cl="No matching device found. Ensure `@luma.gl/webgl` and/or `@luma.gl/webgpu` modules are imported.";class Nr{static defaultProps={...Zt.defaultProps,type:"best-available",adapters:void 0,waitForPageLoad:!0};stats=Ah;log=C;VERSION="9.3.3";spector;preregisteredAdapters=new Map;constructor(){if(globalThis.luma){if(globalThis.luma.VERSION!==this.VERSION)throw C.error(`Found luma.gl ${globalThis.luma.VERSION} while initialzing ${this.VERSION}`)(),C.error("'yarn why @luma.gl/core' can help identify the source of the conflict")(),new Error("luma.gl - multiple versions detected: see console log");C.error("This version of luma.gl has already been initialized")()}C.log(1,`${this.VERSION} - ${_0}`)(),globalThis.luma=this}async createDevice(e={}){const i={...Nr.defaultProps,...e},n=this.selectAdapter(i.type,i.adapters);if(!n)throw new Error(cl);return i.waitForPageLoad&&await n.pageLoaded,await n.create(i)}async attachDevice(e,i){const n=this._getTypeFromHandle(e,i.adapters),r=n&&this.selectAdapter(n,i.adapters);if(!r)throw new Error(cl);return await r?.attach?.(e,i)}registerAdapters(e){for(const i of e)this.preregisteredAdapters.set(i.type,i)}getSupportedAdapters(e=[]){const i=this._getAdapterMap(e);return Array.from(i).map(([,n])=>n).filter(n=>n.isSupported?.()).map(n=>n.type)}getBestAvailableAdapterType(e=[]){const i=["webgpu","webgl","null"],n=this._getAdapterMap(e);for(const r of i)if(n.get(r)?.isSupported?.())return r;return null}selectAdapter(e,i=[]){let n=e;e==="best-available"&&(n=this.getBestAvailableAdapterType(i));const r=this._getAdapterMap(i);return n&&r.get(n)||null}enforceWebGL2(e=!0,i=[]){const r=this._getAdapterMap(i).get("webgl");r||C.warn("enforceWebGL2: webgl adapter not found")(),r?.enforceWebGL2?.(e)}setDefaultDeviceProps(e){Object.assign(Nr.defaultProps,e)}_getAdapterMap(e=[]){const i=new Map(this.preregisteredAdapters);for(const n of e)i.set(n.type,n);return i}_getTypeFromHandle(e,i=[]){return e instanceof WebGL2RenderingContext?"webgl":typeof GPUDevice<"u"&&e instanceof GPUDevice||e?.queue?"webgpu":e===null?"null":(e instanceof WebGLRenderingContext?C.warn("WebGL1 is not supported",e)():C.warn("Unknown handle type",e)(),null)}}const So=new Nr;class A0{get pageLoaded(){return w0()}}const y0=ei()&&typeof document<"u",b0=()=>y0&&document.readyState==="complete";let Qn=null;function w0(){return Qn||(b0()||typeof window>"u"?Qn=Promise.resolve():Qn=new Promise(t=>window.addEventListener("load",()=>t()))),Qn}class T0{props;_resizeObserver;_intersectionObserver;_observeDevicePixelRatioTimeout=null;_observeDevicePixelRatioMediaQuery=null;_handleDevicePixelRatioChange=()=>this._refreshDevicePixelRatio();_trackPositionInterval=null;_started=!1;get started(){return this._started}constructor(e){this.props=e}start(){if(!(this._started||!this.props.canvas)){this._started=!0,this._intersectionObserver||=new IntersectionObserver(e=>this.props.onIntersection(e)),this._resizeObserver||=new ResizeObserver(e=>this.props.onResize(e)),this._intersectionObserver.observe(this.props.canvas);try{this._resizeObserver.observe(this.props.canvas,{box:"device-pixel-content-box"})}catch{this._resizeObserver.observe(this.props.canvas,{box:"content-box"})}this._observeDevicePixelRatioTimeout=setTimeout(()=>this._refreshDevicePixelRatio(),0),this.props.trackPosition&&this._trackPosition()}}stop(){this._started&&(this._started=!1,this._observeDevicePixelRatioTimeout&&(clearTimeout(this._observeDevicePixelRatioTimeout),this._observeDevicePixelRatioTimeout=null),this._observeDevicePixelRatioMediaQuery&&(this._observeDevicePixelRatioMediaQuery.removeEventListener("change",this._handleDevicePixelRatioChange),this._observeDevicePixelRatioMediaQuery=null),this._trackPositionInterval&&(clearInterval(this._trackPositionInterval),this._trackPositionInterval=null),this._resizeObserver?.disconnect(),this._intersectionObserver?.disconnect())}_refreshDevicePixelRatio(){this._started&&(this.props.onDevicePixelRatioChange(),this._observeDevicePixelRatioMediaQuery?.removeEventListener("change",this._handleDevicePixelRatioChange),this._observeDevicePixelRatioMediaQuery=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._observeDevicePixelRatioMediaQuery.addEventListener("change",this._handleDevicePixelRatioChange,{once:!0}))}_trackPosition(e=100){this._trackPositionInterval||(this._trackPositionInterval=setInterval(()=>{this._started?this.props.onPositionChange():this._trackPositionInterval&&(clearInterval(this._trackPositionInterval),this._trackPositionInterval=null)},e))}}function E0(){let t,e;return{promise:new Promise((n,r)=>{t=n,e=r}),resolve:t,reject:e}}function Eh(t,e){if(!t){const i=new Error(e??"luma.gl assertion failed.");throw Error.captureStackTrace?.(i,Eh),i}}function xa(t,e){return Eh(t,e),t}class Et{static isHTMLCanvas(e){return typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement}static isOffscreenCanvas(e){return typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas}static defaultProps={id:void 0,canvas:null,width:800,height:600,useDevicePixels:!0,autoResize:!0,container:null,visible:!0,alphaMode:"opaque",colorSpace:"srgb",trackPosition:!1};id;props;canvas;htmlCanvas;offscreenCanvas;type;initialized;isInitialized=!1;isVisible=!0;cssWidth;cssHeight;devicePixelRatio;devicePixelWidth;devicePixelHeight;drawingBufferWidth;drawingBufferHeight;_initializedResolvers=E0();_canvasObserver;_position=[0,0];destroyed=!1;_needsDrawingBufferResize=!0;toString(){return`${this[Symbol.toStringTag]}(${this.id})`}constructor(e){this.props={...Et.defaultProps,...e},e=this.props,this.initialized=this._initializedResolvers.promise,ei()?e.canvas?typeof e.canvas=="string"?this.canvas=R0(e.canvas):this.canvas=e.canvas:this.canvas=v0(e):this.canvas={width:e.width||1,height:e.height||1},Et.isHTMLCanvas(this.canvas)?(this.id=e.id||this.canvas.id,this.type="html-canvas",this.htmlCanvas=this.canvas):Et.isOffscreenCanvas(this.canvas)?(this.id=e.id||"offscreen-canvas",this.type="offscreen-canvas",this.offscreenCanvas=this.canvas):(this.id=e.id||"node-canvas-context",this.type="node"),this.cssWidth=this.htmlCanvas?.clientWidth||this.canvas.width,this.cssHeight=this.htmlCanvas?.clientHeight||this.canvas.height,this.devicePixelWidth=this.canvas.width,this.devicePixelHeight=this.canvas.height,this.drawingBufferWidth=this.canvas.width,this.drawingBufferHeight=this.canvas.height,this.devicePixelRatio=globalThis.devicePixelRatio||1,this._position=[0,0],this._canvasObserver=new T0({canvas:this.htmlCanvas,trackPosition:this.props.trackPosition,onResize:i=>this._handleResize(i),onIntersection:i=>this._handleIntersection(i),onDevicePixelRatioChange:()=>this._observeDevicePixelRatio(),onPositionChange:()=>this.updatePosition()})}destroy(){this.destroyed||(this.destroyed=!0,this._stopObservers(),this.device=null)}setProps(e){return"useDevicePixels"in e&&(this.props.useDevicePixels=e.useDevicePixels||!1,this._updateDrawingBufferSize()),this}getCurrentFramebuffer(e){return this._resizeDrawingBufferIfNeeded(),this._getCurrentFramebuffer(e)}getCSSSize(){return[this.cssWidth,this.cssHeight]}getPosition(){return this._position}getDevicePixelSize(){return[this.devicePixelWidth,this.devicePixelHeight]}getDrawingBufferSize(){return[this.drawingBufferWidth,this.drawingBufferHeight]}getMaxDrawingBufferSize(){const e=this.device.limits.maxTextureDimension2D;return[e,e]}setDrawingBufferSize(e,i){e=Math.floor(e),i=Math.floor(i),!(this.drawingBufferWidth===e&&this.drawingBufferHeight===i)&&(this.drawingBufferWidth=e,this.drawingBufferHeight=i,this._needsDrawingBufferResize=!0)}getDevicePixelRatio(){return typeof window<"u"&&window.devicePixelRatio||1}cssToDevicePixels(e,i=!0){const n=this.cssToDeviceRatio(),[r,s]=this.getDrawingBufferSize();return C0(e,n,r,s,i)}getPixelSize(){return this.getDevicePixelSize()}getAspect(){const[e,i]=this.getDrawingBufferSize();return e>0&&i>0?e/i:1}cssToDeviceRatio(){try{const[e]=this.getDrawingBufferSize(),[i]=this.getCSSSize();return i?e/i:1}catch{return 1}}resize(e){this.setDrawingBufferSize(e.width,e.height)}_setAutoCreatedCanvasId(e){this.htmlCanvas?.id==="lumagl-auto-created-canvas"&&(this.htmlCanvas.id=e)}_startObservers(){this.destroyed||this._canvasObserver.start()}_stopObservers(){this._canvasObserver.stop()}_handleIntersection(e){if(this.destroyed)return;const i=e.find(r=>r.target===this.canvas);if(!i)return;const n=i.isIntersecting;this.isVisible!==n&&(this.isVisible=n,this.device.props.onVisibilityChange(this))}_handleResize(e){if(this.destroyed)return;const i=e.find(l=>l.target===this.canvas);if(!i)return;const n=xa(i.contentBoxSize?.[0]);this.cssWidth=n.inlineSize,this.cssHeight=n.blockSize;const r=this.getDevicePixelSize(),s=i.devicePixelContentBoxSize?.[0]?.inlineSize||n.inlineSize*devicePixelRatio,o=i.devicePixelContentBoxSize?.[0]?.blockSize||n.blockSize*devicePixelRatio,[a,c]=this.getMaxDrawingBufferSize();this.devicePixelWidth=Math.max(1,Math.min(s,a)),this.devicePixelHeight=Math.max(1,Math.min(o,c)),this._updateDrawingBufferSize(),this.device.props.onResize(this,{oldPixelSize:r})}_updateDrawingBufferSize(){if(this.props.autoResize)if(typeof this.props.useDevicePixels=="number"){const e=this.props.useDevicePixels;this.setDrawingBufferSize(this.cssWidth*e,this.cssHeight*e)}else this.props.useDevicePixels?this.setDrawingBufferSize(this.devicePixelWidth,this.devicePixelHeight):this.setDrawingBufferSize(this.cssWidth,this.cssHeight);this._initializedResolvers.resolve(),this.isInitialized=!0,this.updatePosition()}_resizeDrawingBufferIfNeeded(){this._needsDrawingBufferResize&&(this._needsDrawingBufferResize=!1,(this.drawingBufferWidth!==this.canvas.width||this.drawingBufferHeight!==this.canvas.height)&&(this.canvas.width=this.drawingBufferWidth,this.canvas.height=this.drawingBufferHeight,this._configureDevice()))}_observeDevicePixelRatio(){if(this.destroyed||!this._canvasObserver.started)return;const e=this.devicePixelRatio;this.devicePixelRatio=window.devicePixelRatio,this.updatePosition(),this.device.props.onDevicePixelRatioChange?.(this,{oldRatio:e})}updatePosition(){if(this.destroyed)return;const e=this.htmlCanvas?.getBoundingClientRect();if(e){const i=[e.left,e.top];if(this._position??=i,i[0]!==this._position[0]||i[1]!==this._position[1]){const r=this._position;this._position=i,this.device.props.onPositionChange?.(this,{oldPosition:r})}}}}function S0(t){if(typeof t=="string"){const e=document.getElementById(t);if(!e)throw new Error(`${t} is not an HTML element`);return e}return t||document.body}function R0(t){const e=document.getElementById(t);if(!Et.isHTMLCanvas(e))throw new Error("Object is not a canvas element");return e}function v0(t){const{width:e,height:i}=t,n=document.createElement("canvas");n.id=Cn("lumagl-auto-created-canvas"),n.width=e||1,n.height=i||1,n.style.width=Number.isFinite(e)?`${e}px`:"100%",n.style.height=Number.isFinite(i)?`${i}px`:"100%",t?.visible||(n.style.visibility="hidden");const r=S0(t?.container||null);return r.insertBefore(n,r.firstChild),n}function C0(t,e,i,n,r){const s=t,o=ll(s[0],e,i);let a=fl(s[1],e,n,r),c=ll(s[0]+1,e,i);const l=c===i-1?c:c-1;c=fl(s[1]+1,e,n,r);let f;return r?(c=c===0?c:c+1,f=a,a=c):f=c===n-1?c:c-1,{x:o,y:a,width:Math.max(l-o+1,1),height:Math.max(f-a+1,1)}}function ll(t,e,i){return Math.min(Math.round(t*e),i-1)}function fl(t,e,i,n){return n?Math.max(0,i-1-Math.round(t*e)):Math.min(Math.round(t*e),i-1)}class P0 extends Et{static defaultProps=Et.defaultProps}class I0 extends Et{}class Gt extends Q{static defaultProps={...Q.defaultProps,type:"color-sampler",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge",magFilter:"nearest",minFilter:"nearest",mipmapFilter:"none",lodMinClamp:0,lodMaxClamp:32,compare:"less-equal",maxAnisotropy:1};get[Symbol.toStringTag](){return"Sampler"}constructor(e,i){i=Gt.normalizeProps(e,i),super(e,i,Gt.defaultProps)}static normalizeProps(e,i){return i}}const x0={"1d":"1d","2d":"2d","2d-array":"2d",cube:"2d","cube-array":"2d","3d":"3d"};class Y extends Q{static SAMPLE=4;static STORAGE=8;static RENDER=16;static COPY_SRC=1;static COPY_DST=2;static TEXTURE=4;static RENDER_ATTACHMENT=16;dimension;baseDimension;format;width;height;depth;mipLevels;samples;byteAlignment;ready=Promise.resolve(this);isReady=!0;updateTimestamp;get[Symbol.toStringTag](){return"Texture"}toString(){return`Texture(${this.id},${this.format},${this.width}x${this.height})`}constructor(e,i,n){if(i=Y.normalizeProps(e,i),super(e,i,Y.defaultProps),this.dimension=this.props.dimension,this.baseDimension=x0[this.dimension],this.format=this.props.format,this.width=this.props.width,this.height=this.props.height,this.depth=this.props.depth,this.mipLevels=this.props.mipLevels,this.samples=this.props.samples||1,this.dimension==="cube"&&(this.depth=6),this.props.width===void 0||this.props.height===void 0)if(e.isExternalImage(i.data)){const r=e.getExternalImageSize(i.data);this.width=r?.width||1,this.height=r?.height||1}else this.width=1,this.height=1,(this.props.width===void 0||this.props.height===void 0)&&C.warn(`${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`)();this.byteAlignment=n?.byteAlignment||1,this.updateTimestamp=e.incrementTimestamp()}clone(e){return this.device.createTexture({...this.props,...e})}setSampler(e){this.sampler=e instanceof Gt?e:this.device.createSampler(e)}copyImageData(e){const{data:i,depth:n,...r}=e;this.writeData(i,{...r,depthOrArrayLayers:r.depthOrArrayLayers??n})}computeMemoryLayout(e={}){const i=this._normalizeTextureReadOptions(e),{width:n=this.width,height:r=this.height,depthOrArrayLayers:s=this.depth}=i,{format:o,byteAlignment:a}=this;return He.computeMemoryLayout({format:o,width:n,height:r,depth:s,byteAlignment:a})}readBuffer(e,i){throw new Error("readBuffer not implemented")}readDataAsync(e){throw new Error("readBuffer not implemented")}writeBuffer(e,i){throw new Error("readBuffer not implemented")}writeData(e,i){throw new Error("readBuffer not implemented")}readDataSyncWebGL(e){throw new Error("readDataSyncWebGL not available")}generateMipmapsWebGL(){throw new Error("generateMipmapsWebGL not available")}static normalizeProps(e,i){const n={...i},{width:r,height:s}=n;return typeof r=="number"&&(n.width=Math.max(1,Math.ceil(r))),typeof s=="number"&&(n.height=Math.max(1,Math.ceil(s))),n}_initializeData(e){this.device.isExternalImage(e)?this.copyExternalImage({image:e,width:this.width,height:this.height,depth:this.depth,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1}):e&&this.copyImageData({data:e,mipLevel:0,x:0,y:0,z:0,aspect:"all"})}_normalizeCopyImageDataOptions(e){const{data:i,depth:n,...r}=e,s=this._normalizeTextureWriteOptions({...r,depthOrArrayLayers:r.depthOrArrayLayers??n});return{data:i,depth:s.depthOrArrayLayers,...s}}_normalizeCopyExternalImageOptions(e){const i=Y._omitUndefined(e),n=i.mipLevel??0,r=this._getMipLevelSize(n),s=this.device.getExternalImageSize(e.image),o={...Y.defaultCopyExternalImageOptions,...r,...s,...i};return o.width=Math.min(o.width,r.width-o.x),o.height=Math.min(o.height,r.height-o.y),o.depth=Math.min(o.depth,r.depthOrArrayLayers-o.z),o}_normalizeTextureReadOptions(e){const i=Y._omitUndefined(e),n=i.mipLevel??0,r=this._getMipLevelSize(n),s={...Y.defaultTextureReadOptions,...r,...i};return s.width=Math.min(s.width,r.width-s.x),s.height=Math.min(s.height,r.height-s.y),s.depthOrArrayLayers=Math.min(s.depthOrArrayLayers,r.depthOrArrayLayers-s.z),s}_getSupportedColorReadOptions(e){const i=this._normalizeTextureReadOptions(e),n=He.getInfo(this.format);switch(this._validateColorReadAspect(i),this._validateColorReadFormat(n),this.dimension){case"2d":case"cube":case"cube-array":case"2d-array":case"3d":return i;default:throw new Error(`${this} color readback does not support ${this.dimension} textures`)}}_validateColorReadAspect(e){if(e.aspect!=="all")throw new Error(`${this} color readback only supports aspect 'all'`)}_validateColorReadFormat(e){if(e.compressed)throw new Error(`${this} color readback does not support compressed formats (${this.format})`);switch(e.attachment){case"color":return;case"depth":throw new Error(`${this} color readback does not support depth formats (${this.format})`);case"stencil":throw new Error(`${this} color readback does not support stencil formats (${this.format})`);case"depth-stencil":throw new Error(`${this} color readback does not support depth-stencil formats (${this.format})`);default:throw new Error(`${this} color readback does not support format ${this.format}`)}}_normalizeTextureWriteOptions(e){const i=Y._omitUndefined(e),n=i.mipLevel??0,r=this._getMipLevelSize(n),s={...Y.defaultTextureWriteOptions,...r,...i};s.width=Math.min(s.width,r.width-s.x),s.height=Math.min(s.height,r.height-s.y),s.depthOrArrayLayers=Math.min(s.depthOrArrayLayers,r.depthOrArrayLayers-s.z);const o=He.computeMemoryLayout({format:this.format,width:s.width,height:s.height,depth:s.depthOrArrayLayers,byteAlignment:this.byteAlignment}),a=o.bytesPerPixel*s.width;if(s.bytesPerRow=i.bytesPerRow??o.bytesPerRow,s.rowsPerImage=i.rowsPerImage??s.height,s.bytesPerRow>e),n=this.baseDimension==="1d"?1:Math.max(1,this.height>>e),r=this.dimension==="3d"?Math.max(1,this.depth>>e):this.depth;return{width:i,height:n,depthOrArrayLayers:r}}getAllocatedByteLength(){let e=0;for(let i=0;ii!==void 0))}static defaultProps={...Q.defaultProps,data:null,dimension:"2d",format:"rgba8unorm",usage:Y.SAMPLE|Y.RENDER|Y.COPY_DST,width:void 0,height:void 0,depth:1,mipLevels:1,samples:void 0,sampler:{},view:void 0};static defaultCopyDataOptions={data:void 0,byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,width:void 0,height:void 0,depthOrArrayLayers:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all"};static defaultCopyExternalImageOptions={image:void 0,sourceX:0,sourceY:0,width:void 0,height:void 0,depth:1,mipLevel:0,x:0,y:0,z:0,aspect:"all",colorSpace:"srgb",premultipliedAlpha:!1,flipY:!1};static defaultTextureReadOptions={x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"};static defaultTextureWriteOptions={byteOffset:0,bytesPerRow:void 0,rowsPerImage:void 0,x:0,y:0,z:0,width:void 0,height:void 0,depthOrArrayLayers:1,mipLevel:0,aspect:"all"}}class Zr extends Q{get[Symbol.toStringTag](){return"TextureView"}constructor(e,i){super(e,i,Zr.defaultProps)}static defaultProps={...Q.defaultProps,format:void 0,dimension:void 0,aspect:"all",baseMipLevel:0,mipLevelCount:void 0,baseArrayLayer:0,arrayLayerCount:void 0}}function M0(t,e,i){let n="";const r=e.split(/\r?\n/),s=t.slice().sort((o,a)=>o.lineNum-a.lineNum);switch(i?.showSourceCode||"no"){case"all":let o=0;for(let a=1;a<=r.length;a++){const c=r[a-1],l=s[o];for(c&&l&&(n+=Sh(c,a,i));s.length>o&&l.lineNum===a;){const f=s[o++];f&&(n+=Ns(f,r,f.lineNum,{...i,inlineSource:!1}))}}for(;s.length>o;){const a=s[o++];a&&(n+=Ns(a,[],0,{...i,inlineSource:!1}))}return n;case"issues":case"no":for(const a of t)n+=Ns(a,r,a.lineNum,{inlineSource:i?.showSourceCode!=="no"});return n}}function Ns(t,e,i,n){if(n?.inlineSource){const s=O0(e,i),o=t.linePos>0?`${" ".repeat(t.linePos+5)}^^^ `:"";return` ${s}${o}${t.type.toUpperCase()}: ${t.message} `}const r=t.type==="error"?"red":"orange";return n?.html?`
${t.type.toUpperCase()}: ${t.message}
`:`${t.type.toUpperCase()}: ${t.message}`}function O0(t,e,i){let n="";for(let r=e-2;r<=e;r++){const s=t[r-1];s!==void 0&&(n+=Sh(s,e,i))}return n}function Sh(t,e,i){const n=i?.html?N0(t):t;return`${B0(String(e),4)}: ${n}${i?.html?"
":` `}`}function B0(t,e){let i="";for(let n=t.length;n",">").replaceAll('"',""").replaceAll("'","'")}class Gr extends Q{get[Symbol.toStringTag](){return"Shader"}stage;source;compilationStatus="pending";constructor(e,i){i={...i,debugShaders:i.debugShaders||e.props.debugShaders||"errors"},super(e,{id:D0(i),...i},Gr.defaultProps),this.stage=this.props.stage,this.source=this.props.source}getCompilationInfoSync(){return null}getTranslatedSource(){return null}async debugShader(){const e=this.props.debugShaders;switch(e){case"never":return;case"errors":if(this.compilationStatus==="success")return;break}const i=await this.getCompilationInfo();e==="warnings"&&i?.length===0||this._displayShaderLog(i,this.id)}_displayShaderLog(e,i){if(typeof document>"u"||!document?.createElement)return;const n=i,r=`${this.stage} shader "${n}"`,s=M0(e,this.source,{showSourceCode:"all",html:!0}),o=this.getTranslatedSource(),a=document.createElement("div");a.innerHTML=`

Compilation error in ${r}


${s}
`,o&&(a.innerHTML+=`

Translated Source



${o}
`),a.style.top="0",a.style.left="0",a.style.background="white",a.style.position="fixed",a.style.zIndex="9999",a.style.maxWidth="100vw",a.style.maxHeight="100vh",a.style.overflowY="auto",document.body.appendChild(a),a.querySelector(".luma-compiler-log-error")?.scrollIntoView(),a.querySelector("button#close").onclick=()=>{a.remove()},a.querySelector("button#copy").onclick=()=>{navigator.clipboard.writeText(this.source)}}static defaultProps={...Q.defaultProps,language:"auto",stage:void 0,source:"",sourceMap:null,entryPoint:"main",debugShaders:void 0}}function D0(t){return F0(t.source)||t.id||Cn(`unnamed ${t.stage}-shader`)}function F0(t,e="unnamed"){return/#define[\s*]SHADER_NAME[\s*]([A-Za-z0-9_-]+)[\s*]/.exec(t)?.[1]??e}class Jr extends Q{get[Symbol.toStringTag](){return"Framebuffer"}width;height;constructor(e,i={}){super(e,i,Jr.defaultProps),this.width=this.props.width,this.height=this.props.height}clone(e){const i=this.colorAttachments.map(r=>r.texture.clone(e)),n=this.depthStencilAttachment&&this.depthStencilAttachment.texture.clone(e);return this.device.createFramebuffer({...this.props,...e,colorAttachments:i,depthStencilAttachment:n})}resize(e){let i=!e;if(e){const[n,r]=Array.isArray(e)?e:[e.width,e.height];i=i||r!==this.height||n!==this.width,this.width=n,this.height=r}i&&(C.log(2,`Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)(),this.resizeAttachments(this.width,this.height))}autoCreateAttachmentTextures(){if(this.props.colorAttachments.length===0&&!this.props.depthStencilAttachment)throw new Error("Framebuffer has noattachments");this.colorAttachments=this.props.colorAttachments.map((i,n)=>{if(typeof i=="string"){const r=this.createColorTexture(i,n);return this.attachResource(r),r.view}return i instanceof Y?i.view:i});const e=this.props.depthStencilAttachment;if(e)if(typeof e=="string"){const i=this.createDepthStencilTexture(e);this.attachResource(i),this.depthStencilAttachment=i.view}else e instanceof Y?this.depthStencilAttachment=e.view:this.depthStencilAttachment=e}createColorTexture(e,i){return this.device.createTexture({id:`${this.id}-color-attachment-${i}`,usage:Y.RENDER_ATTACHMENT,format:e,width:this.width,height:this.height,sampler:{magFilter:"linear",minFilter:"linear"}})}createDepthStencilTexture(e){return this.device.createTexture({id:`${this.id}-depth-stencil-attachment`,usage:Y.RENDER_ATTACHMENT,format:e,width:this.width,height:this.height})}resizeAttachments(e,i){if(this.colorAttachments.forEach((n,r)=>{const s=n.texture.clone({width:e,height:i});this.destroyAttachedResource(n),this.colorAttachments[r]=s.view,this.attachResource(s.view)}),this.depthStencilAttachment){const n=this.depthStencilAttachment.texture.clone({width:e,height:i});this.destroyAttachedResource(this.depthStencilAttachment),this.depthStencilAttachment=n.view,this.attachResource(n)}this.updateAttachments()}static defaultProps={...Q.defaultProps,width:1,height:1,colorAttachments:[],depthStencilAttachment:null}}class bt extends Q{get[Symbol.toStringTag](){return"RenderPipeline"}shaderLayout;bufferLayout;linkStatus="pending";hash="";sharedRenderPipeline=null;get isPending(){return this.linkStatus==="pending"||this.vs.compilationStatus==="pending"||this.fs?.compilationStatus==="pending"}get isErrored(){return this.linkStatus==="error"||this.vs.compilationStatus==="error"||this.fs?.compilationStatus==="error"}constructor(e,i){super(e,i,bt.defaultProps),this.shaderLayout=this.props.shaderLayout,this.bufferLayout=this.props.bufferLayout||[],this.sharedRenderPipeline=this.props._sharedRenderPipeline||null}static defaultProps={...Q.defaultProps,vs:null,vertexEntryPoint:"vertexMain",vsConstants:{},fs:null,fragmentEntryPoint:"fragmentMain",fsConstants:{},shaderLayout:null,bufferLayout:[],topology:"triangle-list",colorAttachmentFormats:void 0,depthStencilAttachmentFormat:void 0,parameters:{},varyings:void 0,bufferMode:void 0,disableWarnings:!1,_sharedRenderPipeline:void 0,bindings:void 0,bindGroups:void 0}}class U0 extends Q{get[Symbol.toStringTag](){return"SharedRenderPipeline"}constructor(e,i){super(e,i,{...Q.defaultProps,handle:void 0,vs:void 0,fs:void 0,varyings:void 0,bufferMode:void 0})}}class Dr extends Q{get[Symbol.toStringTag](){return"ComputePipeline"}hash="";shaderLayout;constructor(e,i){super(e,i,Dr.defaultProps),this.shaderLayout=i.shaderLayout}static defaultProps={...Q.defaultProps,shader:void 0,entryPoint:void 0,constants:{},shaderLayout:void 0}}class Ma{static defaultProps={...bt.defaultProps};static getDefaultPipelineFactory(e){const i=e.getModuleData("@luma.gl/core");return i.defaultPipelineFactory||=new Ma(e),i.defaultPipelineFactory}device;_hashCounter=0;_hashes={};_renderPipelineCache={};_computePipelineCache={};_sharedRenderPipelineCache={};get[Symbol.toStringTag](){return"PipelineFactory"}toString(){return`PipelineFactory(${this.device.id})`}constructor(e){this.device=e}createRenderPipeline(e){if(!this.device.props._cachePipelines)return this.device.createRenderPipeline(e);const i={...bt.defaultProps,...e},n=this._renderPipelineCache,r=this._hashRenderPipeline(i);let s=n[r]?.resource;if(s)n[r].useCount++,this.device.props.debugFactories&&C.log(3,`${this}: ${n[r].resource} reused, count=${n[r].useCount}, (id=${e.id})`)();else{const o=this.device.type==="webgl"&&this.device.props._sharePipelines?this.createSharedRenderPipeline(i):void 0;s=this.device.createRenderPipeline({...i,id:i.id?`${i.id}-cached`:Cn("unnamed-cached"),_sharedRenderPipeline:o}),s.hash=r,n[r]={resource:s,useCount:1},this.device.props.debugFactories&&C.log(3,`${this}: ${s} created, count=${n[r].useCount}`)()}return s}createComputePipeline(e){if(!this.device.props._cachePipelines)return this.device.createComputePipeline(e);const i={...Dr.defaultProps,...e},n=this._computePipelineCache,r=this._hashComputePipeline(i);let s=n[r]?.resource;return s?(n[r].useCount++,this.device.props.debugFactories&&C.log(3,`${this}: ${n[r].resource} reused, count=${n[r].useCount}, (id=${e.id})`)()):(s=this.device.createComputePipeline({...i,id:i.id?`${i.id}-cached`:void 0}),s.hash=r,n[r]={resource:s,useCount:1},this.device.props.debugFactories&&C.log(3,`${this}: ${s} created, count=${n[r].useCount}`)()),s}release(e){if(!this.device.props._cachePipelines){e.destroy();return}const i=this._getCache(e),n=e.hash;i[n].useCount--,i[n].useCount===0?(this._destroyPipeline(e),this.device.props.debugFactories&&C.log(3,`${this}: ${e} released and destroyed`)()):i[n].useCount<0?(C.error(`${this}: ${e} released, useCount < 0, resetting`)(),i[n].useCount=0):this.device.props.debugFactories&&C.log(3,`${this}: ${e} released, count=${i[n].useCount}`)()}createSharedRenderPipeline(e){const i=this._hashSharedRenderPipeline(e);let n=this._sharedRenderPipelineCache[i];return n||(n={resource:this.device._createSharedRenderPipelineWebGL(e),useCount:0},this._sharedRenderPipelineCache[i]=n),n.useCount++,n.resource}releaseSharedRenderPipeline(e){if(!e.sharedRenderPipeline)return;const i=this._hashSharedRenderPipeline(e.sharedRenderPipeline.props),n=this._sharedRenderPipelineCache[i];n&&(n.useCount--,n.useCount===0&&(n.resource.destroy(),delete this._sharedRenderPipelineCache[i]))}_destroyPipeline(e){const i=this._getCache(e);return this.device.props._destroyPipelines?(delete i[e.hash],e.destroy(),e instanceof bt&&this.releaseSharedRenderPipeline(e),!0):!1}_getCache(e){let i;if(e instanceof Dr&&(i=this._computePipelineCache),e instanceof bt&&(i=this._renderPipelineCache),!i)throw new Error(`${this}`);if(!i[e.hash])throw new Error(`${this}: ${e} matched incorrect entry`);return i}_hashComputePipeline(e){const{type:i}=this.device,n=this._getHash(e.shader.source),r=this._getHash(JSON.stringify(e.shaderLayout));return`${i}/C/${n}SL${r}`}_hashRenderPipeline(e){const i=e.vs?this._getHash(e.vs.source):0,n=e.fs?this._getHash(e.fs.source):0,r=this._getWebGLVaryingHash(e),s=this._getHash(JSON.stringify(e.shaderLayout)),o=this._getHash(JSON.stringify(e.bufferLayout)),{type:a}=this.device;switch(a){case"webgl":const c=this._getHash(JSON.stringify(e.parameters));return`${a}/R/${i}/${n}V${r}T${e.topology}P${c}SL${s}BL${o}`;case"webgpu":default:const l=this._getHash(JSON.stringify({vertexEntryPoint:e.vertexEntryPoint,fragmentEntryPoint:e.fragmentEntryPoint})),f=this._getHash(JSON.stringify(e.parameters)),u=this._getWebGPUAttachmentHash(e);return`${a}/R/${i}/${n}V${r}T${e.topology}EP${l}P${f}SL${s}BL${o}A${u}`}}_hashSharedRenderPipeline(e){const i=e.vs?this._getHash(e.vs.source):0,n=e.fs?this._getHash(e.fs.source):0,r=this._getWebGLVaryingHash(e);return`webgl/S/${i}/${n}V${r}`}_getHash(e){return this._hashes[e]===void 0&&(this._hashes[e]=this._hashCounter++),this._hashes[e]}_getWebGLVaryingHash(e){const{varyings:i=[],bufferMode:n=null}=e;return this._getHash(JSON.stringify({varyings:i,bufferMode:n}))}_getWebGPUAttachmentHash(e){const i=e.colorAttachmentFormats??[this.device.preferredColorFormat],n=e.parameters?.depthWriteEnabled?e.depthStencilAttachmentFormat||this.device.preferredDepthFormat:null;return this._getHash(JSON.stringify({colorAttachmentFormats:i,depthStencilAttachmentFormat:n}))}}class Oa{static defaultProps={...Gr.defaultProps};static getDefaultShaderFactory(e){const i=e.getModuleData("@luma.gl/core");return i.defaultShaderFactory||=new Oa(e),i.defaultShaderFactory}device;_cache={};get[Symbol.toStringTag](){return"ShaderFactory"}toString(){return`${this[Symbol.toStringTag]}(${this.device.id})`}constructor(e){this.device=e}createShader(e){if(!this.device.props._cacheShaders)return this.device.createShader(e);const i=this._hashShader(e);let n=this._cache[i];if(n)n.useCount++,this.device.props.debugFactories&&C.log(3,`${this}: Reusing shader ${n.resource.id} count=${n.useCount}`)();else{const r=this.device.createShader({...e,id:e.id?`${e.id}-cached`:void 0});this._cache[i]=n={resource:r,useCount:1},this.device.props.debugFactories&&C.log(3,`${this}: Created new shader ${r.id}`)()}return n.resource}release(e){if(!this.device.props._cacheShaders){e.destroy();return}const i=this._hashShader(e),n=this._cache[i];if(n)if(n.useCount--,n.useCount===0)this.device.props._destroyShaders&&(delete this._cache[i],n.resource.destroy(),this.device.props.debugFactories&&C.log(3,`${this}: Releasing shader ${e.id}, destroyed`)());else{if(n.useCount<0)throw new Error(`ShaderFactory: Shader ${e.id} released too many times`);this.device.props.debugFactories&&C.log(3,`${this}: Releasing shader ${e.id} count=${n.useCount}`)()}}_hashShader(e){return`${e.stage}:${e.source}`}}function k0(t,e,i){const n=t.bindings.find(r=>r.name===e||`${r.name.toLocaleLowerCase()}uniforms`===e.toLocaleLowerCase());return n||C.warn(`Binding ${e} not set: Not found in shader layout.`)(),n||null}function Rh(t,e){if(!e)return{};if(L0(e))return Object.fromEntries(Object.entries(e).map(([r,s])=>[Number(r),{...s}]));const i={};for(const[n,r]of Object.entries(e)){const o=k0(t,n)?.group??0;i[o]||={},i[o][n]=r}return i}function ul(t){const e={};for(const i of Object.values(t))Object.assign(e,i);return e}function L0(t){const e=Object.keys(t);return e.length>0&&e.every(i=>/^\d+$/.test(i))}class Bt extends Q{static defaultClearColor=[0,0,0,1];static defaultClearDepth=1;static defaultClearStencil=0;get[Symbol.toStringTag](){return"RenderPass"}constructor(e,i){i=Bt.normalizeProps(e,i),super(e,i,Bt.defaultProps)}static normalizeProps(e,i){return i}static defaultProps={...Q.defaultProps,framebuffer:null,parameters:void 0,clearColor:Bt.defaultClearColor,clearColors:void 0,clearDepth:Bt.defaultClearDepth,clearStencil:Bt.defaultClearStencil,depthReadOnly:!1,stencilReadOnly:!1,discard:!1,occlusionQuerySet:void 0,timestampQuerySet:void 0,beginTimestampIndex:void 0,endTimestampIndex:void 0}}class Ba extends Q{get[Symbol.toStringTag](){return"CommandEncoder"}_timeProfilingQuerySet=null;_timeProfilingSlotCount=0;_gpuTimeMs;constructor(e,i){super(e,i,Ba.defaultProps),this._timeProfilingQuerySet=i.timeProfilingQuerySet??null,this._timeProfilingSlotCount=0,this._gpuTimeMs=void 0}async resolveTimeProfilingQuerySet(){if(this._gpuTimeMs=void 0,!this._timeProfilingQuerySet)return;const e=Math.floor(this._timeProfilingSlotCount/2);if(e<=0)return;const i=e*2,n=await this._timeProfilingQuerySet.readResults({firstQuery:0,queryCount:i});let r=0n;for(let s=0;s=this._timeProfilingQuerySet.props.count?i:(this._timeProfilingSlotCount+=2,{...i,timestampQuerySet:this._timeProfilingQuerySet,beginTimestampIndex:n,endTimestampIndex:n+1})}_supportsTimestampQueries(){return this.device.features.has("timestamp-query")}static defaultProps={...Q.defaultProps,measureExecutionTime:void 0,timeProfilingQuerySet:void 0}}class Na extends Q{get[Symbol.toStringTag](){return"CommandBuffer"}constructor(e,i){super(e,i,Na.defaultProps)}static defaultProps={...Q.defaultProps}}function Da(t){const e=Fa(t),i=X0[e];if(!i)throw new Error(`Unsupported variable shader type: ${t}`);return i}function W0(t){const e=vh(t),i=Y0[e];if(!i)throw new Error(`Unsupported attribute shader type: ${t}`);const[n,r]=i,s=n==="i32"||n==="u32",o=n!=="u32",a=H0[n]*r;return{primitiveType:n,components:r,byteLength:a,integer:s,signed:o}}class V0{getVariableShaderTypeInfo(e){return Da(e)}getAttributeShaderTypeInfo(e){return W0(e)}makeShaderAttributeType(e,i){return z0(e,i)}resolveAttributeShaderTypeAlias(e){return vh(e)}resolveVariableShaderTypeAlias(e){return Fa(e)}}function z0(t,e){return e===1?t:`vec${e}<${t}>`}function vh(t){return Q0[t]||t}function Fa(t){return K0[t]||t}const j0=new V0,H0={f32:4,f16:2,i32:4,u32:4},Y0={f32:["f32",1],"vec2":["f32",2],"vec3":["f32",3],"vec4":["f32",4],f16:["f16",1],"vec2":["f16",2],"vec3":["f16",3],"vec4":["f16",4],i32:["i32",1],"vec2":["i32",2],"vec3":["i32",3],"vec4":["i32",4],u32:["u32",1],"vec2":["u32",2],"vec3":["u32",3],"vec4":["u32",4]},X0={f32:{type:"f32",components:1},f16:{type:"f16",components:1},i32:{type:"i32",components:1},u32:{type:"u32",components:1},"vec2":{type:"f32",components:2},"vec3":{type:"f32",components:3},"vec4":{type:"f32",components:4},"vec2":{type:"f16",components:2},"vec3":{type:"f16",components:3},"vec4":{type:"f16",components:4},"vec2":{type:"i32",components:2},"vec3":{type:"i32",components:3},"vec4":{type:"i32",components:4},"vec2":{type:"u32",components:2},"vec3":{type:"u32",components:3},"vec4":{type:"u32",components:4},"mat2x2":{type:"f32",components:4},"mat2x3":{type:"f32",components:6},"mat2x4":{type:"f32",components:8},"mat3x2":{type:"f32",components:6},"mat3x3":{type:"f32",components:9},"mat3x4":{type:"f32",components:12},"mat4x2":{type:"f32",components:8},"mat4x3":{type:"f32",components:12},"mat4x4":{type:"f32",components:16},"mat2x2":{type:"f16",components:4},"mat2x3":{type:"f16",components:6},"mat2x4":{type:"f16",components:8},"mat3x2":{type:"f16",components:6},"mat3x3":{type:"f16",components:9},"mat3x4":{type:"f16",components:12},"mat4x2":{type:"f16",components:8},"mat4x3":{type:"f16",components:12},"mat4x4":{type:"f16",components:16},"mat2x2":{type:"i32",components:4},"mat2x3":{type:"i32",components:6},"mat2x4":{type:"i32",components:8},"mat3x2":{type:"i32",components:6},"mat3x3":{type:"i32",components:9},"mat3x4":{type:"i32",components:12},"mat4x2":{type:"i32",components:8},"mat4x3":{type:"i32",components:12},"mat4x4":{type:"i32",components:16},"mat2x2":{type:"u32",components:4},"mat2x3":{type:"u32",components:6},"mat2x4":{type:"u32",components:8},"mat3x2":{type:"u32",components:6},"mat3x3":{type:"u32",components:9},"mat3x4":{type:"u32",components:12},"mat4x2":{type:"u32",components:8},"mat4x3":{type:"u32",components:12},"mat4x4":{type:"u32",components:16}},Q0={vec2i:"vec2",vec3i:"vec3",vec4i:"vec4",vec2u:"vec2",vec3u:"vec3",vec4u:"vec4",vec2f:"vec2",vec3f:"vec3",vec4f:"vec4",vec2h:"vec2",vec3h:"vec3",vec4h:"vec4"},K0={vec2i:"vec2",vec3i:"vec3",vec4i:"vec4",vec2u:"vec2",vec3u:"vec3",vec4u:"vec4",vec2f:"vec2",vec3f:"vec3",vec4f:"vec4",vec2h:"vec2",vec3h:"vec3",vec4h:"vec4",mat2x2f:"mat2x2",mat2x3f:"mat2x3",mat2x4f:"mat2x4",mat3x2f:"mat3x2",mat3x3f:"mat3x3",mat3x4f:"mat3x4",mat4x2f:"mat4x2",mat4x3f:"mat4x3",mat4x4f:"mat4x4",mat2x2i:"mat2x2",mat2x3i:"mat2x3",mat2x4i:"mat2x4",mat3x2i:"mat3x2",mat3x3i:"mat3x3",mat3x4i:"mat3x4",mat4x2i:"mat4x2",mat4x3i:"mat4x3",mat4x4i:"mat4x4",mat2x2u:"mat2x2",mat2x3u:"mat2x3",mat2x4u:"mat2x4",mat3x2u:"mat3x2",mat3x3u:"mat3x3",mat3x4u:"mat3x4",mat4x2u:"mat4x2",mat4x3u:"mat4x3",mat4x4u:"mat4x4",mat2x2h:"mat2x2",mat2x3h:"mat2x3",mat2x4h:"mat2x4",mat3x2h:"mat3x2",mat3x3h:"mat3x3",mat3x4h:"mat3x4",mat4x2h:"mat4x2",mat4x3h:"mat4x3",mat4x4h:"mat4x4"};function Ch(t,e){const i={};for(const n of t.attributes){const r=Z0(t,e,n.name);r&&(i[n.name]=r)}return i}function q0(t,e,i=16){const n=Ch(t,e),r=new Array(i).fill(null);for(const s of Object.values(n))r[s.location]=s;return r}function Z0(t,e,i){const n=G0(t,i),r=J0(e,i);if(!n)return null;const s=j0.getAttributeShaderTypeInfo(n.type),o=mn.getCompatibleVertexFormat(s),a=r?.vertexFormat||o,c=mn.getVertexFormatInfo(a);return{attributeName:r?.attributeName||n.name,bufferName:r?.bufferName||n.name,location:n.location,shaderType:n.type,primitiveType:s.primitiveType,shaderComponents:s.components,vertexFormat:a,bufferDataType:c.type,bufferComponents:c.components,normalized:c.normalized,integer:s.integer,stepMode:r?.stepMode||n.stepMode||"vertex",byteOffset:r?.byteOffset||0,byteStride:r?.byteStride||0}}function G0(t,e){const i=t.attributes.find(n=>n.name===e);return i||C.warn(`shader layout attribute "${e}" not present in shader`),i||null}function J0(t,e){$0(t);let i=eb(t,e);return i||(i=tb(t,e),i)?i:(C.warn(`layout for attribute "${e}" not present in buffer layout`),null)}function $0(t){for(const e of t)(e.attributes&&e.format||!e.attributes&&!e.format)&&C.warn(`BufferLayout ${name} must have either 'attributes' or 'format' field`)}function eb(t,e){for(const i of t)if(i.format&&i.name===e)return{attributeName:i.name,bufferName:e,stepMode:i.stepMode,vertexFormat:i.format,byteOffset:0,byteStride:i.byteStride||0};return null}function tb(t,e){for(const i of t){let n=i.byteStride;if(typeof i.byteStride!="number")for(const s of i.attributes||[]){const o=mn.getVertexFormatInfo(s.format);n+=o.byteLength}const r=i.attributes?.find(s=>s.attribute===e);if(r)return{attributeName:r.attribute,bufferName:i.name,stepMode:i.stepMode,vertexFormat:r.format,byteOffset:r.byteOffset,byteStride:n}}return null}class Ua extends Q{static defaultProps={...Q.defaultProps,shaderLayout:void 0,bufferLayout:[]};get[Symbol.toStringTag](){return"VertexArray"}maxVertexAttributes;attributeInfos;indexBuffer=null;attributes;constructor(e,i){super(e,i,Ua.defaultProps),this.maxVertexAttributes=e.limits.maxVertexAttributes,this.attributes=new Array(this.maxVertexAttributes).fill(null),this.attributeInfos=q0(i.shaderLayout,i.bufferLayout,this.maxVertexAttributes)}setConstantWebGL(e,i){this.device.reportError(new Error("constant attributes not supported"),this)()}}class ka extends Q{static defaultProps={...Q.defaultProps,layout:void 0,buffers:{}};get[Symbol.toStringTag](){return"TransformFeedback"}constructor(e,i){super(e,i,ka.defaultProps)}}class La extends Q{get[Symbol.toStringTag](){return"QuerySet"}constructor(e,i){super(e,i,La.defaultProps)}static defaultProps={...Q.defaultProps,type:void 0,count:void 0}}class Wa extends Q{static defaultProps={...Q.defaultProps};get[Symbol.toStringTag](){return"Fence"}constructor(e,i={}){super(e,i,Wa.defaultProps)}}function st(t,e){switch(e){case 1:return t;case 2:return t+t%2;default:return t+(4-t%4)%4}}function Ph(t){const[,,,,e]=ib[t];return e}const ib={uint8:["uint8","u32",1,!1,Uint8Array],sint8:["sint8","i32",1,!1,Int8Array],unorm8:["uint8","f32",1,!0,Uint8Array],snorm8:["sint8","f32",1,!0,Int8Array],uint16:["uint16","u32",2,!1,Uint16Array],sint16:["sint16","i32",2,!1,Int16Array],unorm16:["uint16","u32",2,!0,Uint16Array],snorm16:["sint16","i32",2,!0,Int16Array],float16:["float16","f16",2,!1,Uint16Array],float32:["float32","f32",4,!1,Float32Array],uint32:["uint32","u32",4,!1,Uint32Array],sint32:["sint32","i32",4,!1,Int32Array]};function nb(t,e={}){const i={...t},n=e.layout??"std140",r={};let s=0;for(const[o,a]of Object.entries(i))s=Ro(r,o,a,s,n);return s=st(s,vt(i,n)),{layout:n,byteLength:s*4,uniformTypes:i,fields:r}}function $r(t,e){const i=Fa(t),n=Da(i),r=/^mat(\d)x(\d)<.+>$/.exec(i);if(r){const o=Number(r[1]),a=Number(r[2]),c=hl(a,i,n.type),l=sb(c.size,c.alignment,e);return{alignment:c.alignment,size:o*l,components:o*a,columns:o,rows:a,columnStride:l,shaderType:i,type:n.type}}const s=/^vec(\d)<.+>$/.exec(i);return s?hl(Number(s[1]),i,n.type):{alignment:1,size:1,components:1,columns:1,rows:1,columnStride:1,shaderType:i,type:n.type}}function Ih(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Ro(t,e,i,n,r){if(typeof i=="string"){const s=$r(i,r),o=st(n,s.alignment);return t[e]={offset:o,...s},o+s.size}if(Array.isArray(i)){if(Array.isArray(i[0]))throw new Error(`Nested arrays are not supported for ${e}`);const s=i[0],o=i[1],a=Mh(s,r),c=st(n,vt(i,r));for(let l=0;l=o.length)break;c===1?e[`${i}[${l}]`]=Number(o[f]):e[`${i}[${l}]`]=ub(s,f,f+c)}}_writeLeafValue(e,i,n){const r=this.layout.fields[i];if(!r){C.warn(`Uniform ${i} not found in layout`)();return}const{type:s,components:o,columns:a,rows:c,offset:l,columnStride:f}=r,u=e[s];if(o===1){u[l]=Number(n);return}const h=n;if(a===1){for(let d=0;ds)return!1;for(let o=0;or.type==="uniform"&&r.name===e?.name);if(!i)throw new Error(e?.name);const n=i;for(const r of n.uniforms||[])this.bindingLayout[r.name]=r}}setUniforms(e){for(const[i,n]of Object.entries(e))this._setUniform(i,n),this.needsRedraw||this.setNeedsRedraw(`${this.name}.${i}=${n}`)}setNeedsRedraw(e){this.needsRedraw=this.needsRedraw||e}getAllUniforms(){return this.modifiedUniforms={},this.needsRedraw=!1,this.uniforms||{}}_setUniform(e,i){db(this.uniforms[e],i)||(this.uniforms[e]=pb(i),this.modifiedUniforms[e]=!0,this.modified=!0)}}const mb=1024;class _b{device;uniformBlocks=new Map;shaderBlockLayouts=new Map;shaderBlockWriters=new Map;uniformBuffers=new Map;constructor(e,i){this.device=e;for(const[n,r]of Object.entries(i)){const s=n,o=nb(r.uniformTypes??{},{layout:r.layout??Ab(e)}),a=new lb(o);this.shaderBlockLayouts.set(s,o),this.shaderBlockWriters.set(s,a);const c=new gb({name:n});c.setUniforms(a.getFlatUniformValues(r.defaultUniforms||{})),this.uniformBlocks.set(s,c)}}destroy(){for(const e of this.uniformBuffers.values())e.destroy()}setUniforms(e){for(const[i,n]of Object.entries(e)){const r=i,o=this.shaderBlockWriters.get(r)?.getFlatUniformValues(n||{});this.uniformBlocks.get(r)?.setUniforms(o||{})}this.updateUniformBuffers()}getUniformBufferByteLength(e){const i=this.shaderBlockLayouts.get(e)?.byteLength||0;return Math.max(i,mb)}getUniformBufferData(e){const i=this.uniformBlocks.get(e)?.getAllUniforms()||{};return this.shaderBlockWriters.get(e)?.getData(i)||new Uint8Array(0)}createUniformBuffer(e,i){i&&this.setUniforms(i);const n=this.getUniformBufferByteLength(e),r=this.device.createBuffer({usage:q.UNIFORM|q.COPY_DST,byteLength:n}),s=this.getUniformBufferData(e);return r.write(s),r}getManagedUniformBuffer(e){if(!this.uniformBuffers.get(e)){const i=this.getUniformBufferByteLength(e),n=this.device.createBuffer({usage:q.UNIFORM|q.COPY_DST,byteLength:i});this.uniformBuffers.set(e,n)}return this.uniformBuffers.get(e)}updateUniformBuffers(){let e=!1;for(const i of this.uniformBlocks.keys()){const n=this.updateUniformBuffer(i);e||=n}return e&&C.log(3,`UniformStore.updateUniformBuffers(): ${e}`)(),e}updateUniformBuffer(e){const i=this.uniformBlocks.get(e);let n=this.uniformBuffers.get(e),r=!1;if(n&&i?.needsRedraw){r||=i.needsRedraw;const s=this.getUniformBufferData(e);n=this.uniformBuffers.get(e),n?.write(s);const o=this.uniformBlocks.get(e)?.getAllUniforms();C.log(4,`Writing to uniform buffer ${String(e)}`,s,o)()}return r}}function Ab(t){return t.type==="webgpu"?"wgsl-uniform":"std140"}const yb=`struct LayerUniforms { opacity: f32, }; @group(0) @binding(auto) var layer: LayerUniforms; `,dl=`layout(std140) uniform layerUniforms { uniform float opacity; } layer; `,bb={name:"layer",source:yb,vs:dl,fs:dl,getUniforms:t=>({opacity:Math.pow(t.opacity,1/2.2)}),uniformTypes:{opacity:"f32"}},wb=` @must_use fn deckgl_premultiplied_alpha(fragColor: vec4) -> vec4 { return vec4(fragColor.rgb * fragColor.a, fragColor.a); }; `,Tb={name:"color",dependencies:[],source:wb,getUniforms:t=>({})},Eb=`const SMOOTH_EDGE_RADIUS: f32 = 0.5; struct VertexGeometry { position: vec4, worldPosition: vec3, worldPositionAlt: vec3, normal: vec3, uv: vec2, pickingColor: vec3, }; var geometry_: VertexGeometry = VertexGeometry( vec4(0.0, 0.0, 1.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.0), vec2(0.0, 0.0), vec3(0.0, 0.0, 0.0) ); struct FragmentGeometry { uv: vec2, }; var fragmentGeometry: FragmentGeometry; fn smoothedge(edge: f32, x: f32) -> f32 { return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x); } `,Nh="#define SMOOTH_EDGE_RADIUS 0.5",Sb=`${Nh} struct VertexGeometry { vec4 position; vec3 worldPosition; vec3 worldPositionAlt; vec3 normal; vec2 uv; vec3 pickingColor; } geometry = VertexGeometry( vec4(0.0, 0.0, 1.0, 0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec2(0.0), vec3(0.0) ); `,Rb=`${Nh} struct FragmentGeometry { vec2 uv; } geometry; float smoothedge(float edge, float x) { return smoothstep(edge - SMOOTH_EDGE_RADIUS, edge + SMOOTH_EDGE_RADIUS, x); } `,Dh={name:"geometry",source:Eb,vs:Sb,fs:Rb},vb=25;var fe;(function(t){t[t.Start=1]="Start",t[t.Move=2]="Move",t[t.End=4]="End",t[t.Cancel=8]="Cancel"})(fe||(fe={}));var de;(function(t){t[t.None=0]="None",t[t.Left=1]="Left",t[t.Right=2]="Right",t[t.Up=4]="Up",t[t.Down=8]="Down",t[t.Horizontal=3]="Horizontal",t[t.Vertical=12]="Vertical",t[t.All=15]="All"})(de||(de={}));var j;(function(t){t[t.Possible=1]="Possible",t[t.Began=2]="Began",t[t.Changed=4]="Changed",t[t.Ended=8]="Ended",t[t.Recognized=8]="Recognized",t[t.Cancelled=16]="Cancelled",t[t.Failed=32]="Failed"})(j||(j={}));const Cb="compute",Pb="auto",vo="manipulation",gr="none",Co="pan-x",Po="pan-y";function Ib(t){if(t.includes(gr))return gr;const e=t.includes(Co),i=t.includes(Po);return e&&i?gr:e||i?e?Co:Po:t.includes(vo)?vo:Pb}class xb{constructor(e,i){this.actions="",this.manager=e,this.set(i)}set(e){e===Cb&&(e=this.compute()),this.manager.element&&(this.manager.element.style.touchAction=e,this.actions=e)}update(){this.set(this.manager.options.touchAction)}compute(){let e=[];for(const i of this.manager.recognizers)i.options.enable&&(e=e.concat(i.getTouchAction()));return Ib(e.join(" "))}}function Ur(t){return t.trim().split(/\s+/g)}function Ds(t,e,i){if(t)for(const n of Ur(e))t.addEventListener(n,i,!1)}function Fs(t,e,i){if(t)for(const n of Ur(e))t.removeEventListener(n,i,!1)}function pl(t){return(t.ownerDocument||t).defaultView}function Mb(t,e){let i=t;for(;i;){if(i===e)return!0;i=i.parentNode}return!1}function Fh(t){const e=t.length;if(e===1)return{x:Math.round(t[0].clientX),y:Math.round(t[0].clientY)};let i=0,n=0,r=0;for(;r=Math.abs(e)?t<0?de.Left:de.Right:e<0?de.Up:de.Down}function Bb(t,e){const i=e.center;let n=t.offsetDelta,r=t.prevDelta;const s=t.prevInput;return(e.eventType===fe.Start||s?.eventType===fe.End)&&(r=t.prevDelta={x:s?.deltaX||0,y:s?.deltaY||0},n=t.offsetDelta={x:i.x,y:i.y}),{deltaX:r.x+(i.x-n.x),deltaY:r.y+(i.y-n.y)}}function Lh(t,e,i){return{x:e/t||0,y:i/t||0}}function Nb(t,e){return ml(e[0],e[1])/ml(t[0],t[1])}function Db(t,e){return _l(e[1],e[0])-_l(t[1],t[0])}function Fb(t,e){const i=t.lastInterval||e,n=e.timeStamp-i.timeStamp;let r,s,o,a;if(e.eventType!==fe.Cancel&&(n>vb||i.velocity===void 0)){const c=e.deltaX-i.deltaX,l=e.deltaY-i.deltaY,f=Lh(n,c,l);s=f.x,o=f.y,r=Math.abs(f.x)>Math.abs(f.y)?f.x:f.y,a=kh(c,l),t.lastInterval=e}else r=i.velocity,s=i.velocityX,o=i.velocityY,a=i.direction;e.velocity=r,e.velocityX=s,e.velocityY=o,e.direction=a}function Ub(t,e){const{session:i}=t,{pointers:n}=e,{length:r}=n;i.firstInput||(i.firstInput=gl(e)),r>1&&!i.firstMultiple?i.firstMultiple=gl(e):r===1&&(i.firstMultiple=!1);const{firstInput:s,firstMultiple:o}=i,a=o?o.center:s.center,c=e.center=Fh(n);e.timeStamp=Date.now(),e.deltaTime=e.timeStamp-s.timeStamp,e.angle=Ob(a,c),e.distance=Uh(a,c);const{deltaX:l,deltaY:f}=Bb(i,e);e.deltaX=l,e.deltaY=f,e.offsetDirection=kh(e.deltaX,e.deltaY);const u=Lh(e.deltaTime,e.deltaX,e.deltaY);e.overallVelocityX=u.x,e.overallVelocityY=u.y,e.overallVelocity=Math.abs(u.x)>Math.abs(u.y)?u.x:u.y,e.scale=o?Nb(o.pointers,n):1,e.rotation=o?Db(o.pointers,n):0,e.maxPointers=i.prevInput?e.pointers.length>i.prevInput.maxPointers?e.pointers.length:i.prevInput.maxPointers:e.pointers.length;let h=t.element;return Mb(e.srcEvent.target,h)&&(h=e.srcEvent.target),e.target=h,Fb(i,e),e}function kb(t,e,i){const n=i.pointers.length,r=i.changedPointers.length,s=e&fe.Start&&n-r===0,o=e&(fe.End|fe.Cancel)&&n-r===0;i.isFirst=!!s,i.isFinal=!!o,s&&(t.session={}),i.eventType=e;const a=Ub(t,i);t.emit("hammer.input",a),t.recognize(a),t.session.prevInput=a}let Lb=class{constructor(e){this.evEl="",this.evWin="",this.evTarget="",this.domHandler=i=>{this.manager.options.enable&&this.handler(i)},this.manager=e,this.element=e.element,this.target=e.options.inputTarget||e.element}callback(e,i){kb(this.manager,e,i)}init(){Ds(this.element,this.evEl,this.domHandler),Ds(this.target,this.evTarget,this.domHandler),Ds(pl(this.element),this.evWin,this.domHandler)}destroy(){Fs(this.element,this.evEl,this.domHandler),Fs(this.target,this.evTarget,this.domHandler),Fs(pl(this.element),this.evWin,this.domHandler)}};const Wb={pointerdown:fe.Start,pointermove:fe.Move,pointerup:fe.End,pointercancel:fe.Cancel,pointerout:fe.Cancel},Vb="pointerdown",zb="pointermove pointerup pointercancel";class jb extends Lb{constructor(e){super(e),this.evEl=Vb,this.evWin=zb,this.store=this.manager.session.pointerEvents=[],this.init()}handler(e){const{store:i}=this;let n=!1;const r=Wb[e.type],s=e.pointerType,o=s==="touch";let a=i.findIndex(c=>c.pointerId===e.pointerId);r&fe.Start&&(e.buttons||o)?a<0&&(i.push(e),a=i.length-1):r&(fe.End|fe.Cancel)&&(n=!0),!(a<0)&&(i[a]=e,this.callback(r,{pointers:i,changedPointers:[e],eventType:r,pointerType:s,srcEvent:e}),n&&i.splice(a,1))}}const Hb=["","webkit","Moz","MS","ms","o"];function Yb(t,e){const i=e[0].toUpperCase()+e.slice(1);for(const n of Hb){const r=n?n+i:e;if(r in t)return r}}const Xb=1,Al=2,yl={touchAction:"compute",enable:!0,inputTarget:null,cssProps:{userSelect:"none",userDrag:"none",touchCallout:"none",tapHighlightColor:"rgba(0,0,0,0)"}};class Qb{constructor(e,i){this.options={...yl,...i,cssProps:{...yl.cssProps,...i.cssProps},inputTarget:i.inputTarget||e},this.handlers={},this.session={},this.recognizers=[],this.oldCssProps={},this.element=e,this.input=new jb(this),this.touchAction=new xb(this,this.options.touchAction),this.toggleCssProps(!0)}set(e){return Object.assign(this.options,e),e.touchAction&&this.touchAction.update(),e.inputTarget&&(this.input.destroy(),this.input.target=e.inputTarget,this.input.init()),this}stop(e){this.session.stopped=e?Al:Xb}recognize(e){const{session:i}=this;if(i.stopped)return;this.session.prevented&&e.srcEvent.preventDefault();let n;const{recognizers:r}=this;let{curRecognizer:s}=i;(!s||s&&s.state&j.Recognized)&&(s=i.curRecognizer=null);let o=0;for(;o-1&&this.requireFail.splice(n,1)}return this}hasRequireFailures(){return!!this.requireFail.find(e=>e.options.enable)}canRecognizeWith(e){return!!this.simultaneous[e.id]}emit(e){if(!e)return;const{state:i}=this;i=j.Ended&&this.manager.emit(this.options.event+bl(i),e)}tryEmit(e){this.canEmit()?this.emit(e):this.state=j.Failed}canEmit(){let e=0;for(;e{this.state=j.Recognized,this.tryEmit(this._input)},i.interval),j.Began):j.Recognized}return j.Failed}failTimeout(){return this._timer=setTimeout(()=>{this.state=j.Failed},this.options.interval),j.Failed}reset(){clearTimeout(this._timer)}emit(e){this.state===j.Recognized&&(e.tapCount=this.count,this.manager.emit(this.options.event,e))}}const Zb=["","start","move","end","cancel","up","down","left","right"];class Tl extends Vh{constructor(e={}){super({enable:!0,pointers:1,event:"pan",threshold:10,direction:de.All,...e}),this.pX=null,this.pY=null}getTouchAction(){const{options:{direction:e}}=this,i=[];return e&de.Horizontal&&i.push(Po),e&de.Vertical&&i.push(Co),i}getEventNames(){return Zb.map(e=>this.options.event+e)}directionTest(e){const{options:i}=this;let n=!0,{distance:r}=e,{direction:s}=e;const o=e.deltaX,a=e.deltaY;return s&i.direction||(i.direction&de.Horizontal?(s=o===0?de.None:o<0?de.Left:de.Right,n=o!==this.pX,r=Math.abs(e.deltaX)):(s=a===0?de.None:a<0?de.Up:de.Down,n=a!==this.pY,r=Math.abs(e.deltaY))),e.direction=s,n&&r>i.threshold&&!!(s&i.direction)}attrTest(e){return super.attrTest(e)&&(!!(this.state&j.Began)||!(this.state&j.Began)&&this.directionTest(e))}emit(e){this.pX=e.deltaX,this.pY=e.deltaY;const i=de[e.direction].toLowerCase();i&&(e.additionalEvent=this.options.event+i),super.emit(e)}}const Gb=["","start","move","end","cancel","in","out"];class Jb extends Vh{constructor(e={}){super({enable:!0,event:"pinch",threshold:0,pointers:2,...e})}getTouchAction(){return[gr]}getEventNames(){return Gb.map(e=>this.options.event+e)}attrTest(e){return super.attrTest(e)&&(Math.abs(e.scale-1)>this.options.threshold||!!(this.state&j.Began))}emit(e){if(e.scale!==1){const i=e.scale<1?"in":"out";e.additionalEvent=this.options.event+i}super.emit(e)}}class es{constructor(e,i,n){this.element=e,this.callback=i,this.options=n}}const $b=typeof navigator<"u"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",ew=$b.indexOf("firefox")!==-1,El=4.000244140625,tw=40,iw=.25;class nw extends es{constructor(e,i,n){super(e,i,{enable:!0,...n}),this.handleEvent=r=>{if(!this.options.enable)return;let s=r.deltaY;globalThis.WheelEvent&&(ew&&r.deltaMode===globalThis.WheelEvent.DOM_DELTA_PIXEL&&(s/=globalThis.devicePixelRatio),r.deltaMode===globalThis.WheelEvent.DOM_DELTA_LINE&&(s*=tw)),s!==0&&s%El===0&&(s=Math.floor(s/El)),r.shiftKey&&s&&(s=s*iw),this.callback({type:"wheel",center:{x:r.clientX,y:r.clientY},delta:-s,srcEvent:r,pointerType:"mouse",target:r.target})},e.addEventListener("wheel",this.handleEvent,{passive:!1})}destroy(){this.element.removeEventListener("wheel",this.handleEvent)}enableEventType(e,i){e==="wheel"&&(this.options.enable=i)}}const Sl=["mousedown","mousemove","mouseup","mouseover","mouseout","mouseleave"];class rw extends es{constructor(e,i,n){super(e,i,{enable:!0,...n}),this.handleEvent=s=>{this.handleOverEvent(s),this.handleOutEvent(s),this.handleEnterEvent(s),this.handleLeaveEvent(s),this.handleMoveEvent(s)},this.pressed=!1;const{enable:r}=this.options;this.enableMoveEvent=r,this.enableLeaveEvent=r,this.enableEnterEvent=r,this.enableOutEvent=r,this.enableOverEvent=r,Sl.forEach(s=>e.addEventListener(s,this.handleEvent))}destroy(){Sl.forEach(e=>this.element.removeEventListener(e,this.handleEvent))}enableEventType(e,i){switch(e){case"pointermove":this.enableMoveEvent=i;break;case"pointerover":this.enableOverEvent=i;break;case"pointerout":this.enableOutEvent=i;break;case"pointerenter":this.enableEnterEvent=i;break;case"pointerleave":this.enableLeaveEvent=i;break}}handleOverEvent(e){this.enableOverEvent&&e.type==="mouseover"&&this._emit("pointerover",e)}handleOutEvent(e){this.enableOutEvent&&e.type==="mouseout"&&this._emit("pointerout",e)}handleEnterEvent(e){this.enableEnterEvent&&e.type==="mouseenter"&&this._emit("pointerenter",e)}handleLeaveEvent(e){this.enableLeaveEvent&&e.type==="mouseleave"&&this._emit("pointerleave",e)}handleMoveEvent(e){if(this.enableMoveEvent)switch(e.type){case"mousedown":e.button>=0&&(this.pressed=!0);break;case"mousemove":e.buttons===0&&(this.pressed=!1),this.pressed||this._emit("pointermove",e);break;case"mouseup":this.pressed=!1;break}}_emit(e,i){this.callback({type:e,center:{x:i.clientX,y:i.clientY},srcEvent:i,pointerType:"mouse",target:i.target})}}const Rl=["keydown","keyup"];class sw extends es{constructor(e,i,n){super(e,i,{enable:!0,tabIndex:0,...n}),this.handleEvent=r=>{const s=r.target||r.srcElement;s.tagName==="INPUT"&&s.type==="text"||s.tagName==="TEXTAREA"||(this.enableDownEvent&&r.type==="keydown"&&this.callback({type:"keydown",srcEvent:r,key:r.key,target:r.target}),this.enableUpEvent&&r.type==="keyup"&&this.callback({type:"keyup",srcEvent:r,key:r.key,target:r.target}))},this.enableDownEvent=this.options.enable,this.enableUpEvent=this.options.enable,e.tabIndex=this.options.tabIndex,e.style.outline="none",Rl.forEach(r=>e.addEventListener(r,this.handleEvent))}destroy(){Rl.forEach(e=>this.element.removeEventListener(e,this.handleEvent))}enableEventType(e,i){e==="keydown"&&(this.enableDownEvent=i),e==="keyup"&&(this.enableUpEvent=i)}}class ow extends es{constructor(e,i,n){super(e,i,n),this.handleEvent=r=>{this.options.enable&&this.callback({type:"contextmenu",center:{x:r.clientX,y:r.clientY},srcEvent:r,pointerType:"mouse",target:r.target})},e.addEventListener("contextmenu",this.handleEvent)}destroy(){this.element.removeEventListener("contextmenu",this.handleEvent)}enableEventType(e,i){e==="contextmenu"&&(this.options.enable=i)}}const vl=1,Io=2,Cl=4,aw={pointerdown:vl,pointermove:Io,pointerup:Cl,mousedown:vl,mousemove:Io,mouseup:Cl},cw=0,lw=1,fw=2,uw=1,hw=2,dw=4;function pw(t){const e=aw[t.srcEvent.type];if(!e)return null;const{buttons:i,button:n}=t.srcEvent;let r=!1,s=!1,o=!1;return e===Io?(r=!!(i&uw),s=!!(i&dw),o=!!(i&hw)):(r=n===cw,s=n===lw,o=n===fw),{leftButton:r,middleButton:s,rightButton:o}}function gw(t,e){const i=t.center;if(!i)return null;const n=e.getBoundingClientRect(),r=n.width/e.offsetWidth||1,s=n.height/e.offsetHeight||1,o={x:(i.x-n.left-e.clientLeft)/r,y:(i.y-n.top-e.clientTop)/s};return{center:i,offsetCenter:o}}const mw={srcElement:"root",priority:0};class _w{constructor(e,i){this.handleEvent=n=>{if(this.isEmpty())return;const r=this._normalizeEvent(n);let s=n.srcEvent.target;for(;s&&s!==r.rootElement;){if(this._emit(r,s),r.handled)return;s=s.parentNode}this._emit(r,"root")},this.eventManager=e,this.recognizerName=i,this.handlers=[],this.handlersByElement=new Map,this._active=!1}isEmpty(){return!this._active}add(e,i,n,r=!1,s=!1){const{handlers:o,handlersByElement:a}=this,c={...mw,...n};let l=a.get(c.srcElement);l||(l=[],a.set(c.srcElement,l));const f={type:e,handler:i,srcElement:c.srcElement,priority:c.priority};r&&(f.once=!0),s&&(f.passive=!0),o.push(f),this._active=this._active||!f.passive;let u=l.length-1;for(;u>=0&&!(l[u].priority>=f.priority);)u--;l.splice(u+1,0,f)}remove(e,i){const{handlers:n,handlersByElement:r}=this;for(let s=n.length-1;s>=0;s--){const o=n[s];if(o.type===e&&o.handler===i){n.splice(s,1);const a=r.get(o.srcElement);a.splice(a.indexOf(o),1),a.length===0&&r.delete(o.srcElement)}}this._active=n.some(s=>!s.passive)}_emit(e,i){const n=this.handlersByElement.get(i);if(n){let r=!1;const s=()=>{e.handled=!0},o=()=>{e.handled=!0,r=!0},a=[];for(let c=0;c{e.srcEvent.preventDefault()},stopImmediatePropagation:null,stopPropagation:null,handled:!1,rootElement:i}}}function Aw(t){if("recognizer"in t)return t;let e;const i=Array.isArray(t)?[...t]:[t];if(typeof i[0]=="function"){const n=i.shift(),r=i.shift()||{};e=new n(r)}else e=i.shift();return{recognizer:e,recognizeWith:typeof i[0]=="string"?[i[0]]:i[0],requireFailure:typeof i[1]=="string"?[i[1]]:i[1]}}class yw{constructor(e=null,i={}){if(this._onBasicInput=n=>{this.manager.emit(n.srcEvent.type,n)},this._onOtherEvent=n=>{this.manager.emit(n.type,n)},this.options={recognizers:[],events:{},touchAction:"compute",tabIndex:0,cssProps:{},...i},this.events=new Map,this.element=e,!!e){this.manager=new Qb(e,this.options);for(const n of this.options.recognizers){const{recognizer:r,recognizeWith:s,requireFailure:o}=Aw(n);this.manager.add(r),s&&r.recognizeWith(s),o&&r.requireFailure(o)}this.manager.on("hammer.input",this._onBasicInput),this.wheelInput=new nw(e,this._onOtherEvent,{enable:!1}),this.moveInput=new rw(e,this._onOtherEvent,{enable:!1}),this.keyInput=new sw(e,this._onOtherEvent,{enable:!1,tabIndex:i.tabIndex}),this.contextmenuInput=new ow(e,this._onOtherEvent,{enable:!1}),this.on(this.options.events)}}getElement(){return this.element}destroy(){this.element&&(this.wheelInput.destroy(),this.moveInput.destroy(),this.keyInput.destroy(),this.contextmenuInput.destroy(),this.manager.destroy())}on(e,i,n){this._addEventHandler(e,i,n,!1)}once(e,i,n){this._addEventHandler(e,i,n,!0)}watch(e,i,n){this._addEventHandler(e,i,n,!1,!0)}off(e,i){this._removeEventHandler(e,i)}_toggleRecognizer(e,i){const{manager:n}=this;if(!n)return;const r=n.get(e);r&&(r.set({enable:i}),n.touchAction.update()),this.wheelInput?.enableEventType(e,i),this.moveInput?.enableEventType(e,i),this.keyInput?.enableEventType(e,i),this.contextmenuInput?.enableEventType(e,i)}_addEventHandler(e,i,n,r,s){if(typeof e!="string"){n=i;for(const[l,f]of Object.entries(e))this._addEventHandler(l,f,n,r,s);return}const{manager:o,events:a}=this;if(!o)return;let c=a.get(e);if(!c){const l=this._getRecognizerName(e)||e;c=new _w(this,l),a.set(e,c),o&&o.on(e,c.handleEvent)}c.add(e,i,n,r,s),c.isEmpty()||this._toggleRecognizer(c.recognizerName,!0)}_removeEventHandler(e,i){if(typeof e!="string"){for(const[s,o]of Object.entries(e))this._removeEventHandler(s,o);return}const{events:n}=this,r=n.get(e);if(r&&(r.remove(e,i),r.isEmpty())){const{recognizerName:s}=r;let o=!1;for(const a of n.values())if(a.recognizerName===s&&!a.isEmpty()){o=!0;break}o||this._toggleRecognizer(s,!1)}}_getRecognizerName(e){return this.manager.recognizers.find(i=>i.getEventNames().includes(e))?.options.event}}const xe={WEB_MERCATOR:1,GLOBE:2,WEB_MERCATOR_AUTO_OFFSET:4,IDENTITY:0},Ii={common:0,meters:1,pixels:2},mr={click:"onClick",dblclick:"onClick",panstart:"onDragStart",panmove:"onDrag",panend:"onDragEnd"},Pl={multipan:[Tl,{threshold:10,direction:de.Vertical,pointers:2}],pinch:[Jb,{},null,["multipan"]],pan:[Tl,{threshold:1},["pinch"],["multipan"]],dblclick:[wl,{event:"dblclick",taps:2}],click:[wl,{event:"click"},null,["dblclick"]]};function bw(t,e){if(t===e)return!0;if(Array.isArray(t)){const i=t.length;if(!e||e.length!==i)return!1;for(let n=0;n{for(const r in n)if(!bw(n[r],e[r])){i=t(n),e=n;break}return i}}const Il=[0,0,0,0],ww=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0],zh=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],Tw=[0,0,0],jh=[0,0,0],Ew={default:-1,cartesian:0,lnglat:1,"meter-offsets":2,"lnglat-offsets":3};function ts(t){const e=Ew[t];if(e===void 0)throw new Error(`Invalid coordinateSystem: ${t}`);return e}const Sw=Pn(Cw);function Hh(t,e,i=jh){i.length<3&&(i=[i[0],i[1],0]);let n=i,r,s=!0;switch(e==="lnglat-offsets"||e==="meter-offsets"?r=i:r=t.isGeospatial?[Math.fround(t.longitude),Math.fround(t.latitude),0]:null,t.projectionMode){case xe.WEB_MERCATOR:(e==="lnglat"||e==="cartesian")&&(r=[0,0,0],s=!1);break;case xe.WEB_MERCATOR_AUTO_OFFSET:e==="lnglat"?n=r:e==="cartesian"&&(n=[Math.fround(t.center[0]),Math.fround(t.center[1]),0],r=t.unprojectPosition(n),n[0]-=i[0],n[1]-=i[1],n[2]-=i[2]);break;case xe.IDENTITY:n=t.position.map(Math.fround),n[2]=n[2]||0;break;case xe.GLOBE:s=!1,r=null;break;default:s=!1}return{geospatialOrigin:r,shaderCoordinateOrigin:n,offsetMode:s}}function Rw(t,e,i){const{viewMatrixUncentered:n,projectionMatrix:r}=t;let{viewMatrix:s,viewProjectionMatrix:o}=t,a=Il,c=Il,l=t.cameraPosition;const{geospatialOrigin:f,shaderCoordinateOrigin:u,offsetMode:h}=Hh(t,e,i);return h&&(c=t.projectPosition(f||u),l=[l[0]-c[0],l[1]-c[1],l[2]-c[2]],c[3]=1,a=Fi([],c,o),s=n||s,o=Vt([],r,s),o=Vt([],o,ww)),{viewMatrix:s,viewProjectionMatrix:o,projectionCenter:a,originCommon:c,cameraPosCommon:l,shaderCoordinateOrigin:u,geospatialOrigin:f}}function vw({viewport:t,devicePixelRatio:e=1,modelMatrix:i=null,coordinateSystem:n="default",coordinateOrigin:r=jh,autoWrapLongitude:s=!1}){n==="default"&&(n=t.isGeospatial?"lnglat":"cartesian");const o=Sw({viewport:t,devicePixelRatio:e,coordinateSystem:n,coordinateOrigin:r});return o.wrapLongitude=s,o.modelMatrix=i||zh,o}function Cw({viewport:t,devicePixelRatio:e,coordinateSystem:i,coordinateOrigin:n}){const{projectionCenter:r,viewProjectionMatrix:s,originCommon:o,cameraPosCommon:a,shaderCoordinateOrigin:c,geospatialOrigin:l}=Rw(t,i,n),f=t.getDistanceScales(),u=[t.width*e,t.height*e],h=Fi([],[0,0,-t.focalDistance,1],t.projectionMatrix)[3]||1,p={coordinateSystem:ts(i),projectionMode:t.projectionMode,coordinateOrigin:c,commonOrigin:o.slice(0,3),center:r,pseudoMeters:!!t._pseudoMeters,viewportSize:u,devicePixelRatio:e,focalDistance:h,commonUnitsPerMeter:f.unitsPerMeter,commonUnitsPerWorldUnit:f.unitsPerMeter,commonUnitsPerWorldUnit2:Tw,scale:t.scale,wrapLongitude:!1,viewProjectionMatrix:s,modelMatrix:zh,cameraPosition:a};if(l){const d=t.getDistanceScales(l);switch(i){case"meter-offsets":p.commonUnitsPerWorldUnit=d.unitsPerMeter,p.commonUnitsPerWorldUnit2=d.unitsPerMeter2;break;case"lnglat":case"lnglat-offsets":t._pseudoMeters||(p.commonUnitsPerMeter=d.unitsPerMeter),p.commonUnitsPerWorldUnit=d.unitsPerDegree,p.commonUnitsPerWorldUnit2=d.unitsPerDegree2;break;case"cartesian":p.commonUnitsPerWorldUnit=[1,1,d.unitsPerMeter[2]],p.commonUnitsPerWorldUnit2=[0,0,d.unitsPerMeter2[2]];break}}return p}const Pw=["default","lnglat","meter-offsets","lnglat-offsets","cartesian"],Iw=Pw.map(t=>`const COORDINATE_SYSTEM_${t.toUpperCase().replaceAll("-","_")}: i32 = ${ts(t)};`).join(""),xw=Object.keys(xe).map(t=>`const PROJECTION_MODE_${t}: i32 = ${xe[t]};`).join(""),Mw=Object.keys(Ii).map(t=>`const UNIT_${t.toUpperCase()}: i32 = ${Ii[t]};`).join(""),Ow=`${Iw} ${xw} ${Mw} const TILE_SIZE: f32 = 512.0; const PI: f32 = 3.1415926536; const WORLD_SCALE: f32 = TILE_SIZE / (PI * 2.0); const ZERO_64_LOW: vec3 = vec3(0.0, 0.0, 0.0); const EARTH_RADIUS: f32 = 6370972.0; // meters const GLOBE_RADIUS: f32 = 256.0; // ----------------------------------------------------------------------------- // Uniform block (converted from GLSL uniform block) // ----------------------------------------------------------------------------- struct ProjectUniforms { wrapLongitude: i32, coordinateSystem: i32, commonUnitsPerMeter: vec3, projectionMode: i32, scale: f32, commonUnitsPerWorldUnit: vec3, commonUnitsPerWorldUnit2: vec3, center: vec4, modelMatrix: mat4x4, viewProjectionMatrix: mat4x4, viewportSize: vec2, devicePixelRatio: f32, focalDistance: f32, cameraPosition: vec3, coordinateOrigin: vec3, commonOrigin: vec3, pseudoMeters: i32, }; @group(0) @binding(auto) var project: ProjectUniforms; // ----------------------------------------------------------------------------- // Geometry data shared across the project helpers. // The active layer shader is responsible for populating this private module // state before calling the project functions below. // ----------------------------------------------------------------------------- // Structure to carry additional geometry data used by deck.gl filters. struct Geometry { worldPosition: vec3, worldPositionAlt: vec3, position: vec4, normal: vec3, uv: vec2, pickingColor: vec3, }; var geometry: Geometry; `,Bw=`${Ow} // ----------------------------------------------------------------------------- // Functions // ----------------------------------------------------------------------------- // Returns an adjustment factor for commonUnitsPerMeter fn _project_size_at_latitude(lat: f32) -> f32 { let y = clamp(lat, -89.9, 89.9); return 1.0 / cos(radians(y)); } // Overloaded version: scales a value in meters at a given latitude. fn _project_size_at_latitude_m(meters: f32, lat: f32) -> f32 { return meters * project.commonUnitsPerMeter.z * _project_size_at_latitude(lat); } // Computes a non-linear scale factor based on geometry. // (Note: This function relies on "geometry" being provided.) fn project_size() -> f32 { if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR && project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT && project.pseudoMeters == 0) { if (geometry.position.w == 0.0) { return _project_size_at_latitude(geometry.worldPosition.y); } let y: f32 = geometry.position.y / TILE_SIZE * 2.0 - 1.0; let y2 = y * y; let y4 = y2 * y2; let y6 = y4 * y2; return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6; } return 1.0; } // Overloads to scale offsets (meters to world units) fn project_size_float(meters: f32) -> f32 { return meters * project.commonUnitsPerMeter.z * project_size(); } fn project_size_vec2(meters: vec2) -> vec2 { return meters * project.commonUnitsPerMeter.xy * project_size(); } fn project_size_vec3(meters: vec3) -> vec3 { return meters * project.commonUnitsPerMeter * project_size(); } fn project_size_vec4(meters: vec4) -> vec4 { return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w); } // Returns a rotation matrix aligning the z‑axis with the given up vector. fn project_get_orientation_matrix(up: vec3) -> mat3x3 { let uz = normalize(up); let ux = select( vec3(1.0, 0.0, 0.0), normalize(vec3(uz.y, -uz.x, 0.0)), abs(uz.z) == 1.0 ); let uy = cross(uz, ux); return mat3x3(ux, uy, uz); } // Since WGSL does not support "out" parameters, we return a struct. struct RotationResult { needsRotation: bool, transform: mat3x3, }; fn project_needs_rotation(commonPosition: vec3) -> RotationResult { if (project.projectionMode == PROJECTION_MODE_GLOBE) { return RotationResult(true, project_get_orientation_matrix(commonPosition)); } else { return RotationResult(false, mat3x3()); // identity alternative if needed }; } // Projects a normal vector from the current coordinate system to world space. fn project_normal(vector: vec3) -> vec3 { let normal_modelspace = project.modelMatrix * vec4(vector, 0.0); var n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter); let rotResult = project_needs_rotation(geometry.position.xyz); if (rotResult.needsRotation) { n = rotResult.transform * n; } return n; } // Applies a scale offset based on y-offset (dy) fn project_offset_(offset: vec4) -> vec4 { let dy: f32 = offset.y; let commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy; return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w); } // Projects lng/lat coordinates to a unit tile [0,1] fn project_mercator_(lnglat: vec2) -> vec2 { var x = lnglat.x; if (project.wrapLongitude != 0) { x = ((x + 180.0) % 360.0) - 180.0; } let y = clamp(lnglat.y, -89.9, 89.9); return vec2( radians(x) + PI, PI + log(tan(PI * 0.25 + radians(y) * 0.5)) ) * WORLD_SCALE; } // Projects lng/lat/z coordinates for a globe projection. fn project_globe_(lnglatz: vec3) -> vec3 { let lambda = radians(lnglatz.x); let phi = radians(lnglatz.y); let cosPhi = cos(phi); let D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS; return vec3( sin(lambda) * cosPhi, -cos(lambda) * cosPhi, sin(phi) ) * D; } // Projects positions (with an optional 64-bit low part) from the input // coordinate system to the common space. fn project_position_vec4_f64(position: vec4, position64Low: vec3) -> vec4 { var position_world = project.modelMatrix * position; // Work around for a Mac+NVIDIA bug: if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) { if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { return vec4( project_mercator_(position_world.xy), _project_size_at_latitude_m(position_world.z, position_world.y), position_world.w ); } if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) { position_world = vec4f(position_world.xyz + project.coordinateOrigin, position_world.w); } } if (project.projectionMode == PROJECTION_MODE_GLOBE) { if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { return vec4( project_globe_(position_world.xyz), position_world.w ); } } if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) { if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) { return vec4( project_mercator_(position_world.xy) - project.commonOrigin.xy, project_size_float(position_world.z), position_world.w ); } } } if (project.projectionMode == PROJECTION_MODE_IDENTITY || (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET && (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT || project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) { position_world = vec4f(position_world.xyz - project.coordinateOrigin, position_world.w); } return project_offset_(position_world) + project_offset_(project.modelMatrix * vec4(position64Low, 0.0)); } // Overloaded versions for different input types. fn project_position_vec4_f32(position: vec4) -> vec4 { return project_position_vec4_f64(position, ZERO_64_LOW); } fn project_position_vec3_f64(position: vec3, position64Low: vec3) -> vec3 { let projected_position = project_position_vec4_f64(vec4(position, 1.0), position64Low); return projected_position.xyz; } fn project_position_vec3_f32(position: vec3) -> vec3 { let projected_position = project_position_vec4_f64(vec4(position, 1.0), ZERO_64_LOW); return projected_position.xyz; } fn project_position_vec2_f32(position: vec2) -> vec2 { let projected_position = project_position_vec4_f64(vec4(position, 0.0, 1.0), ZERO_64_LOW); return projected_position.xy; } // Transforms a common space position to clip space. fn project_common_position_to_clipspace_with_projection(position: vec4, viewProjectionMatrix: mat4x4, center: vec4) -> vec4 { return viewProjectionMatrix * position + center; } // Uses the project viewProjectionMatrix and center. fn project_common_position_to_clipspace(position: vec4) -> vec4 { return project_common_position_to_clipspace_with_projection(position, project.viewProjectionMatrix, project.center); } // Returns a clip space offset corresponding to a given number of screen pixels. fn project_pixel_size_to_clipspace(pixels: vec2) -> vec2 { let offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0; return offset * project.focalDistance; } fn project_meter_size_to_pixel(meters: f32) -> f32 { return project_size_float(meters) * project.scale; } fn project_unit_size_to_pixel(size: f32, unit: i32) -> f32 { if (unit == UNIT_METERS) { return project_meter_size_to_pixel(size); } else if (unit == UNIT_COMMON) { return size * project.scale; } // UNIT_PIXELS: no scaling applied. return size; } fn project_pixel_size_float(pixels: f32) -> f32 { return pixels / project.scale; } fn project_pixel_size_vec2(pixels: vec2) -> vec2 { return pixels / project.scale; } `,Nw=["default","lnglat","meter-offsets","lnglat-offsets","cartesian"],Dw=Nw.map(t=>`const int COORDINATE_SYSTEM_${t.toUpperCase().replaceAll("-","_")} = ${ts(t)};`).join(""),Fw=Object.keys(xe).map(t=>`const int PROJECTION_MODE_${t} = ${xe[t]};`).join(""),Uw=Object.keys(Ii).map(t=>`const int UNIT_${t.toUpperCase()} = ${Ii[t]};`).join(""),kw=`${Dw} ${Fw} ${Uw} layout(std140) uniform projectUniforms { bool wrapLongitude; int coordinateSystem; vec3 commonUnitsPerMeter; int projectionMode; float scale; vec3 commonUnitsPerWorldUnit; vec3 commonUnitsPerWorldUnit2; vec4 center; mat4 modelMatrix; mat4 viewProjectionMatrix; vec2 viewportSize; float devicePixelRatio; float focalDistance; vec3 cameraPosition; vec3 coordinateOrigin; vec3 commonOrigin; bool pseudoMeters; } project; const float TILE_SIZE = 512.0; const float PI = 3.1415926536; const float WORLD_SCALE = TILE_SIZE / (PI * 2.0); const vec3 ZERO_64_LOW = vec3(0.0); const float EARTH_RADIUS = 6370972.0; const float GLOBE_RADIUS = 256.0; float project_size_at_latitude(float lat) { float y = clamp(lat, -89.9, 89.9); return 1.0 / cos(radians(y)); } float project_size() { if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR && project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT && project.pseudoMeters == false) { if (geometry.position.w == 0.0) { return project_size_at_latitude(geometry.worldPosition.y); } float y = geometry.position.y / TILE_SIZE * 2.0 - 1.0; float y2 = y * y; float y4 = y2 * y2; float y6 = y4 * y2; return 1.0 + 4.9348 * y2 + 4.0587 * y4 + 1.5642 * y6; } return 1.0; } float project_size_at_latitude(float meters, float lat) { return meters * project.commonUnitsPerMeter.z * project_size_at_latitude(lat); } float project_size(float meters) { return meters * project.commonUnitsPerMeter.z * project_size(); } vec2 project_size(vec2 meters) { return meters * project.commonUnitsPerMeter.xy * project_size(); } vec3 project_size(vec3 meters) { return meters * project.commonUnitsPerMeter * project_size(); } vec4 project_size(vec4 meters) { return vec4(meters.xyz * project.commonUnitsPerMeter, meters.w); } mat3 project_get_orientation_matrix(vec3 up) { vec3 uz = normalize(up); vec3 ux = abs(uz.z) == 1.0 ? vec3(1.0, 0.0, 0.0) : normalize(vec3(uz.y, -uz.x, 0)); vec3 uy = cross(uz, ux); return mat3(ux, uy, uz); } bool project_needs_rotation(vec3 commonPosition, out mat3 transform) { if (project.projectionMode == PROJECTION_MODE_GLOBE) { transform = project_get_orientation_matrix(commonPosition); return true; } return false; } vec3 project_normal(vec3 vector) { vec4 normal_modelspace = project.modelMatrix * vec4(vector, 0.0); vec3 n = normalize(normal_modelspace.xyz * project.commonUnitsPerMeter); mat3 rotation; if (project_needs_rotation(geometry.position.xyz, rotation)) { n = rotation * n; } return n; } vec4 project_offset_(vec4 offset) { float dy = offset.y; vec3 commonUnitsPerWorldUnit = project.commonUnitsPerWorldUnit + project.commonUnitsPerWorldUnit2 * dy; return vec4(offset.xyz * commonUnitsPerWorldUnit, offset.w); } vec2 project_mercator_(vec2 lnglat) { float x = lnglat.x; if (project.wrapLongitude) { x = mod(x + 180., 360.0) - 180.; } float y = clamp(lnglat.y, -89.9, 89.9); return vec2( radians(x) + PI, PI + log(tan_fp32(PI * 0.25 + radians(y) * 0.5)) ) * WORLD_SCALE; } vec3 project_globe_(vec3 lnglatz) { float lambda = radians(lnglatz.x); float phi = radians(lnglatz.y); float cosPhi = cos(phi); float D = (lnglatz.z / EARTH_RADIUS + 1.0) * GLOBE_RADIUS; return vec3( sin(lambda) * cosPhi, -cos(lambda) * cosPhi, sin(phi) ) * D; } vec4 project_position(vec4 position, vec3 position64Low) { vec4 position_world = project.modelMatrix * position; if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR) { if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { return vec4( project_mercator_(position_world.xy), project_size_at_latitude(position_world.z, position_world.y), position_world.w ); } if (project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN) { position_world.xyz += project.coordinateOrigin; } } if (project.projectionMode == PROJECTION_MODE_GLOBE) { if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { return vec4( project_globe_(position_world.xyz), position_world.w ); } } if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) { if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) { if (abs(position_world.y - project.coordinateOrigin.y) > 0.25) { return vec4( project_mercator_(position_world.xy) - project.commonOrigin.xy, project_size(position_world.z), position_world.w ); } } } if (project.projectionMode == PROJECTION_MODE_IDENTITY || (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET && (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT || project.coordinateSystem == COORDINATE_SYSTEM_CARTESIAN))) { position_world.xyz -= project.coordinateOrigin; } return project_offset_(position_world) + project_offset_(project.modelMatrix * vec4(position64Low, 0.0)); } vec4 project_position(vec4 position) { return project_position(position, ZERO_64_LOW); } vec3 project_position(vec3 position, vec3 position64Low) { vec4 projected_position = project_position(vec4(position, 1.0), position64Low); return projected_position.xyz; } vec3 project_position(vec3 position) { vec4 projected_position = project_position(vec4(position, 1.0), ZERO_64_LOW); return projected_position.xyz; } vec2 project_position(vec2 position) { vec4 projected_position = project_position(vec4(position, 0.0, 1.0), ZERO_64_LOW); return projected_position.xy; } vec4 project_common_position_to_clipspace(vec4 position, mat4 viewProjectionMatrix, vec4 center) { return viewProjectionMatrix * position + center; } vec4 project_common_position_to_clipspace(vec4 position) { return project_common_position_to_clipspace(position, project.viewProjectionMatrix, project.center); } vec2 project_pixel_size_to_clipspace(vec2 pixels) { vec2 offset = pixels / project.viewportSize * project.devicePixelRatio * 2.0; return offset * project.focalDistance; } float project_size_to_pixel(float meters) { return project_size(meters) * project.scale; } vec2 project_size_to_pixel(vec2 meters) { return project_size(meters) * project.scale; } float project_size_to_pixel(float size, int unit) { if (unit == UNIT_METERS) return project_size_to_pixel(size); if (unit == UNIT_COMMON) return size * project.scale; return size; } float project_pixel_size(float pixels) { return pixels / project.scale; } vec2 project_pixel_size(vec2 pixels) { return pixels / project.scale; } `,Lw={};function Ww(t=Lw){return"viewport"in t?vw(t):{}}const Va={name:"project",dependencies:[Sy,Dh],source:Bw,vs:kw,getUniforms:Ww,uniformTypes:{wrapLongitude:"f32",coordinateSystem:"i32",commonUnitsPerMeter:"vec3",projectionMode:"i32",scale:"f32",commonUnitsPerWorldUnit:"vec3",commonUnitsPerWorldUnit2:"vec3",center:"vec4",modelMatrix:"mat4x4",viewProjectionMatrix:"mat4x4",viewportSize:"vec2",devicePixelRatio:"f32",focalDistance:"f32",cameraPosition:"vec3",coordinateOrigin:"vec3",commonOrigin:"vec3",pseudoMeters:"f32"}},Vw=`// Define a structure to hold both the clip-space position and the common position. struct ProjectResult { clipPosition: vec4, commonPosition: vec4, }; // This function mimics the GLSL version with the 'out' parameter by returning both values. fn project_position_to_clipspace_and_commonspace( position: vec3, position64Low: vec3, offset: vec3 ) -> ProjectResult { // Compute the projected position. let projectedPosition: vec3 = project_position_vec3_f64(position, position64Low); // Start with the provided offset. var finalOffset: vec3 = offset; // Get whether a rotation is needed and the rotation matrix. let rotationResult = project_needs_rotation(projectedPosition); // If rotation is needed, update the offset. if (rotationResult.needsRotation) { finalOffset = rotationResult.transform * offset; } // Compute the common position. let commonPosition: vec4 = vec4(projectedPosition + finalOffset, 1.0); // Convert to clip-space. let clipPosition: vec4 = project_common_position_to_clipspace(commonPosition); return ProjectResult(clipPosition, commonPosition); } // A convenience overload that returns only the clip-space position. fn project_position_to_clipspace( position: vec3, position64Low: vec3, offset: vec3 ) -> vec4 { return project_position_to_clipspace_and_commonspace(position, position64Low, offset).clipPosition; } `,zw=`vec4 project_position_to_clipspace( vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition ) { vec3 projectedPosition = project_position(position, position64Low); mat3 rotation; if (project_needs_rotation(projectedPosition, rotation)) { // offset is specified as ENU // when in globe projection, rotate offset so that the ground alighs with the surface of the globe offset = rotation * offset; } commonPosition = vec4(projectedPosition + offset, 1.0); return project_common_position_to_clipspace(commonPosition); } vec4 project_position_to_clipspace( vec3 position, vec3 position64Low, vec3 offset ) { vec4 commonPosition; return project_position_to_clipspace(position, position64Low, offset, commonPosition); } `,jw={name:"project32",dependencies:[Va],source:Vw,vs:zw};function Hw(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function Ei(t,e){const i=Fi([],e,t);return mh(i,i,1/i[3]),i}function xo(t,e,i){return ti?i:t}function Yw(t){return Math.log(t)*Math.LOG2E}const Yh=Math.log2||Yw;function at(t,e){if(!t)throw new Error(e||"@math.gl/web-mercator: assertion failed.")}const Ye=Math.PI,Xh=Ye/4,Le=Ye/180,Mo=180/Ye,xi=512,kr=4003e4,wt=85.051129,Xw=1.5;function Qw(t){return Yh(t)}function Mi(t){const[e,i]=t;at(Number.isFinite(e)),at(Number.isFinite(i)&&i>=-90&&i<=90,"invalid latitude");const n=e*Le,r=i*Le,s=xi*(n+Ye)/(2*Ye),o=xi*(Ye+Math.log(Math.tan(Xh+r*.5)))/(2*Ye);return[s,o]}function Oi(t){const[e,i]=t,n=e/xi*(2*Ye)-Ye,r=2*(Math.atan(Math.exp(i/xi*(2*Ye)-Ye))-Xh);return[n*Mo,r*Mo]}function Kw(t){const{latitude:e}=t;at(Number.isFinite(e));const i=Math.cos(e*Le);return Qw(kr*i)-9}function Us(t){const e=Math.cos(t*Le);return xi/kr/e}function Oo(t){const{latitude:e,longitude:i,highPrecision:n=!1}=t;at(Number.isFinite(e)&&Number.isFinite(i));const r=xi,s=Math.cos(e*Le),o=r/360,a=o/s,c=r/kr/s,l={unitsPerMeter:[c,c,c],metersPerUnit:[1/c,1/c,1/c],unitsPerDegree:[o,a,c],degreesPerUnit:[1/o,1/a,1/c]};if(n){const f=Le*Math.tan(e*Le)/s,u=o*f/2,h=r/kr*f,p=h/a*c;l.unitsPerDegree2=[0,u,h],l.unitsPerMeter2=[p,0,p]}return l}function Qh(t,e){const[i,n,r]=t,[s,o,a]=e,{unitsPerMeter:c,unitsPerMeter2:l}=Oo({longitude:i,latitude:n,highPrecision:!0}),f=Mi(t);f[0]+=s*(c[0]+l[0]*o),f[1]+=o*(c[1]+l[1]*o);const u=Oi(f),h=(r||0)+(a||0);return Number.isFinite(r)||Number.isFinite(a)?[u[0],u[1],h]:u}function qw(t){const{height:e,pitch:i,bearing:n,altitude:r,scale:s,center:o}=t,a=Hw();Br(a,a,[0,0,-r]),ph(a,a,-i*Le),gh(a,a,n*Le);const c=s/e;return Pa(a,a,[c,c,c]),o&&Br(a,a,VA([],o)),a}function Zw(t){const{width:e,height:i,altitude:n,pitch:r=0,offset:s,center:o,scale:a,nearZMultiplier:c=1,farZMultiplier:l=1}=t;let{fovy:f=_n(Xw)}=t;n!==void 0&&(f=_n(n));const u=f*Le,h=r*Le,p=za(f);let d=p;o&&(d+=o[2]*a/Math.cos(h)/i);const m=u*(.5+(s?s[1]:0)/i),g=Math.sin(m)*d/Math.sin(xo(Math.PI/2-h-m,.01,Math.PI-.01)),_=Math.sin(h)*g+d,y=d*10,A=Math.min(_*l,y);return{fov:u,aspect:e/i,focalDistance:p,near:c,far:A}}function _n(t){return 2*Math.atan(.5/t)*Mo}function za(t){return .5/Math.tan(.5*t*Le)}function Kh(t,e){const[i,n,r=0]=t;return at(Number.isFinite(i)&&Number.isFinite(n)&&Number.isFinite(r)),Ei(e,[i,n,r,1])}function is(t,e,i=0){const[n,r,s]=t;if(at(Number.isFinite(n)&&Number.isFinite(r),"invalid pixel coordinate"),Number.isFinite(s))return Ei(e,[n,r,s,1]);const o=Ei(e,[n,r,0,1]),a=Ei(e,[n,r,1,1]),c=o[2],l=a[2],f=c===l?0:((i||0)-c)/(l-c);return fh([],o,a,f)}function Gw(t){const{width:e,height:i,bounds:n,minExtent:r=0,maxZoom:s=24,offset:o=[0,0]}=t,[[a,c],[l,f]]=n,u=Jw(t.padding),h=Mi([a,xo(f,-wt,wt)]),p=Mi([l,xo(c,-wt,wt)]),d=[Math.max(Math.abs(p[0]-h[0]),r),Math.max(Math.abs(p[1]-h[1]),r)],m=[e-u.left-u.right-Math.abs(o[0])*2,i-u.top-u.bottom-Math.abs(o[1])*2];at(m[0]>0&&m[1]>0);const g=m[0]/d[0],_=m[1]/d[1],y=(u.right-u.left)/2/g,A=(u.top-u.bottom)/2/_,b=[(p[0]+h[0])/2+y,(p[1]+h[1])/2+A],T=Oi(b),w=Math.min(s,Yh(Math.abs(Math.min(g,_))));return at(Number.isFinite(w)),{longitude:T[0],latitude:T[1],zoom:w}}function Jw(t=0){return typeof t=="number"?{top:t,bottom:t,left:t,right:t}:(at(Number.isFinite(t.top)&&Number.isFinite(t.bottom)&&Number.isFinite(t.left)&&Number.isFinite(t.right)),t)}const xl=Math.PI/180;function $w(t,e=0){const{width:i,height:n,unproject:r}=t,s={targetZ:e},o=r([0,n],s),a=r([i,n],s);let c,l;const f=t.fovy?.5*t.fovy*xl:Math.atan(.5/t.altitude),u=(90-t.pitch)*xl;return f>u-.01?(c=Ml(t,0,e),l=Ml(t,i,e)):(c=r([0,0],s),l=r([i,0],s)),[o,a,l,c]}function Ml(t,e,i){const{pixelUnprojectionMatrix:n}=t,r=Ei(n,[e,0,1,1]),s=Ei(n,[e,t.height,1,1]),a=(i*t.distanceScales.unitsPerMeter[2]-r[2])/(s[2]-r[2]),c=fh([],r,s,a),l=Oi(c);return l.push(i),l}const qh=` layout(std140) uniform shadowUniforms { bool drawShadowMap; bool useShadowMap; vec4 color; highp int lightId; float lightCount; mat4 viewProjectionMatrix0; mat4 viewProjectionMatrix1; vec4 projectCenter0; vec4 projectCenter1; } shadow; `,eT=` const int max_lights = 2; out vec3 shadow_vPosition[max_lights]; vec4 shadow_setVertexPosition(vec4 position_commonspace) { mat4 viewProjectionMatrices[max_lights]; viewProjectionMatrices[0] = shadow.viewProjectionMatrix0; viewProjectionMatrices[1] = shadow.viewProjectionMatrix1; vec4 projectCenters[max_lights]; projectCenters[0] = shadow.projectCenter0; projectCenters[1] = shadow.projectCenter1; if (shadow.drawShadowMap) { return project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[shadow.lightId], projectCenters[shadow.lightId]); } if (shadow.useShadowMap) { for (int i = 0; i < max_lights; i++) { if(i < int(shadow.lightCount)) { vec4 shadowMap_position = project_common_position_to_clipspace(position_commonspace, viewProjectionMatrices[i], projectCenters[i]); shadow_vPosition[i] = (shadowMap_position.xyz / shadowMap_position.w + 1.0) / 2.0; } } } return gl_Position; } `,tT=` ${qh} ${eT} `,iT=` const int max_lights = 2; uniform sampler2D shadow_uShadowMap0; uniform sampler2D shadow_uShadowMap1; in vec3 shadow_vPosition[max_lights]; const vec4 bitPackShift = vec4(1.0, 255.0, 65025.0, 16581375.0); const vec4 bitUnpackShift = 1.0 / bitPackShift; const vec4 bitMask = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0); float shadow_getShadowWeight(vec3 position, sampler2D shadowMap) { vec4 rgbaDepth = texture(shadowMap, position.xy); float z = dot(rgbaDepth, bitUnpackShift); return smoothstep(0.001, 0.01, position.z - z); } vec4 shadow_filterShadowColor(vec4 color) { if (shadow.drawShadowMap) { vec4 rgbaDepth = fract(gl_FragCoord.z * bitPackShift); rgbaDepth -= rgbaDepth.gbaa * bitMask; return rgbaDepth; } if (shadow.useShadowMap) { float shadowAlpha = 0.0; shadowAlpha += shadow_getShadowWeight(shadow_vPosition[0], shadow_uShadowMap0); if(shadow.lightCount > 1.0) { shadowAlpha += shadow_getShadowWeight(shadow_vPosition[1], shadow_uShadowMap1); } shadowAlpha *= shadow.color.a / shadow.lightCount; float blendedAlpha = shadowAlpha + color.a * (1.0 - shadowAlpha); return vec4( mix(color.rgb, shadow.color.rgb, shadowAlpha / blendedAlpha), blendedAlpha ); } return color; } `,nT=` ${qh} ${iT} `,rT=Pn(lT),sT=Pn(fT),oT=[0,0,0,1],aT=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0];function cT(t,e){const[i,n,r]=t,s=is([i,n,r],e);return Number.isFinite(r)?s:[s[0],s[1],0]}function lT({viewport:t,center:e}){return new Oe(t.viewProjectionMatrix).invert().transform(e)}function fT({viewport:t,shadowMatrices:e}){const i=[],n=t.pixelUnprojectionMatrix,r=t.isGeospatial?void 0:1,s=[[0,0,r],[t.width,0,r],[0,t.height,r],[t.width,t.height,r],[0,0,-1],[t.width,0,-1],[0,t.height,-1],[t.width,t.height,-1]].map(o=>cT(o,n));for(const o of e){const a=o.clone().translate(new it(t.center).negate()),c=s.map(f=>a.transform(f)),l=new Oe().ortho({left:Math.min(...c.map(f=>f[0])),right:Math.max(...c.map(f=>f[0])),bottom:Math.min(...c.map(f=>f[1])),top:Math.max(...c.map(f=>f[1])),near:Math.min(...c.map(f=>-f[2])),far:Math.max(...c.map(f=>-f[2]))});i.push(l.multiplyRight(o))}return i}function uT(t){const{shadowEnabled:e=!0,project:i}=t;if(!e||!i||!t.shadowMatrices||!t.shadowMatrices.length)return{drawShadowMap:!1,useShadowMap:!1,shadow_uShadowMap0:t.dummyShadowMap,shadow_uShadowMap1:t.dummyShadowMap};const n=Va.getUniforms(i),r=rT({viewport:i.viewport,center:n.center}),s=[],o=sT({shadowMatrices:t.shadowMatrices,viewport:i.viewport}).slice();for(let c=0;c0:!1,color:t.shadowColor||oT,lightId:t.shadowLightId||0,lightCount:t.shadowMatrices.length,shadow_uShadowMap0:t.dummyShadowMap,shadow_uShadowMap1:t.dummyShadowMap};for(let c=0;c",lightId:"i32",lightCount:"f32",viewProjectionMatrix0:"mat4x4",viewProjectionMatrix1:"mat4x4",projectCenter0:"vec4",projectCenter1:"vec4"}},hT=`struct pickingUniforms { isActive: f32, isAttribute: f32, isHighlightActive: f32, useByteColors: f32, highlightedObjectColor: vec3, highlightColor: vec4, }; @group(0) @binding(auto) var picking: pickingUniforms; fn picking_normalizeColor(color: vec3) -> vec3 { return select(color, color / 255.0, picking.useByteColors > 0.5); } fn picking_normalizeColor4(color: vec4) -> vec4 { return select(color, color / 255.0, picking.useByteColors > 0.5); } fn picking_isColorZero(color: vec3) -> bool { return dot(color, vec3(1.0)) < 0.00001; } fn picking_isColorValid(color: vec3) -> bool { return dot(color, vec3(1.0)) > 0.00001; } `,dT={...Gc,source:hT,defaultUniforms:{...Gc.defaultUniforms,useByteColors:!0},inject:{"vs:DECKGL_FILTER_GL_POSITION":` // for picking depth values picking_setPickingAttribute(position.z / position.w); `,"vs:DECKGL_FILTER_COLOR":` picking_setPickingColor(geometry.pickingColor); `,"fs:DECKGL_FILTER_COLOR":{order:99,injection:` // use highlight color if this fragment belongs to the selected object. color = picking_filterHighlightColor(color); // use picking color if rendering to picking FBO. color = picking_filterPickingColor(color); `}}},pT=[Dh],gT=["vs:DECKGL_FILTER_SIZE(inout vec3 size, VertexGeometry geometry)","vs:DECKGL_FILTER_GL_POSITION(inout vec4 position, VertexGeometry geometry)","vs:DECKGL_FILTER_COLOR(inout vec4 color, VertexGeometry geometry)","fs:DECKGL_FILTER_COLOR(inout vec4 color, FragmentGeometry geometry)"],mT=[];function _T(t){const e=Dt.getDefaultShaderAssembler();for(const n of pT)e.addDefaultModule(n);e._hookFunctions.length=0;const i=t==="glsl"?gT:mT;for(const n of i)e.addShaderHook(n);return e}const AT=[255,255,255],yT=1;let bT=0;class wT{constructor(e={}){this.type="ambient";const{color:i=AT}=e,{intensity:n=yT}=e;this.id=e.id||`ambient-${bT++}`,this.color=i,this.intensity=n}}const TT=[255,255,255],ET=1,ST=[0,0,-1];let RT=0;class Bl{constructor(e={}){this.type="directional";const{color:i=TT}=e,{intensity:n=ET}=e,{direction:r=ST}=e,{_shadow:s=!1}=e;this.id=e.id||`directional-${RT++}`,this.color=i,this.intensity=n,this.type="directional",this.direction=new it(r).normalize().toArray(),this.shadow=s}getProjectedLight(e){return this}}class vT{constructor(e,i={id:"pass"}){const{id:n}=i;this.id=n,this.device=e,this.props={...i}}setProps(e){Object.assign(this.props,e)}render(e){}cleanup(){}}const CT={depthWriteEnabled:!0,depthCompare:"less-equal",blendColorOperation:"add",blendColorSrcFactor:"src-alpha",blendColorDstFactor:"one",blendAlphaOperation:"add",blendAlphaSrcFactor:"one-minus-dst-alpha",blendAlphaDstFactor:"one"};class ja extends vT{constructor(){super(...arguments),this._lastRenderIndex=-1}render(e){this._render(e)}_render(e){const i=this.device.canvasContext,n=e.target??i.getCurrentFramebuffer(),[r,s]=i.getDrawingBufferSize(),o=e.clearCanvas??!0,a=e.clearColor??(o?[0,0,0,0]:!1),c=o?1:!1,l=o?0:!1,f=e.colorMask??15,u={viewport:[0,0,r,s]};e.colorMask&&(u.colorMask=f),e.scissorRect&&(u.scissorRect=e.scissorRect);const h=this.device.beginRenderPass({framebuffer:n,parameters:u,clearColor:a,clearDepth:c,clearStencil:l});try{return this._drawLayers(h,e)}finally{h.end(),this.device.submit()}}_drawLayers(e,i){const{target:n,shaderModuleProps:r,viewports:s,views:o,onViewportActive:a,clearStack:c=!0}=i;i.pass=i.pass||"unknown",c&&(this._lastRenderIndex=-1);const l=[];for(const f of s){const u=o&&o[f.id];a?.(f);const h=this._getDrawLayerParams(f,i),p=f.subViewports||[f];for(const d of p){const m=this._drawLayersInViewport(e,{target:n,shaderModuleProps:r,viewport:d,view:u,pass:i.pass,layers:i.layers},h);l.push(m)}}return l}_getDrawLayerParams(e,{layers:i,pass:n,isPicking:r=!1,layerFilter:s,cullRect:o,effects:a,shaderModuleProps:c},l=!1){const f=[],u=Zh(this._lastRenderIndex+1),h={layer:i[0],viewport:e,isPicking:r,renderPass:n,cullRect:o},p={};for(let d=0;dA/255):h===!1&&(m=!1),p!==void 0&&(g=p),d!==void 0&&(_=d),this.device.beginRenderPass({framebuffer:s,parameters:{viewport:l,scissorRect:l},clearColor:m,clearDepth:g,clearStencil:_}).end()}}const f={totalCount:i.length,visibleCount:0,compositeCount:0,pickableCount:0};e.setParameters({viewport:l});for(let u=0;u{const o=r.props._offset,a=r.id,c=r.parent&&r.parent.id;let l;if(c&&!(c in e)&&n(r.parent,!1),c in i){const f=i[c]=i[c]||Zh(e[c],e);l=f(r,s),i[a]=f}else Number.isFinite(o)?(l=o+(e[c]||0),i[a]=null):l=t;return s&&l>=t&&(t=l+1),e[a]=l,l};return n}function PT(t,{shaderModuleProps:e,target:i,viewport:n}){const r=e?.project?.devicePixelRatio??t.canvasContext.cssToDeviceRatio(),[,s]=t.canvasContext.getDrawingBufferSize(),o=i?i.height:s,a=n;return[a.x*r,o-(a.y+a.height)*r,a.width*r,a.height*r]}function Nl(t,...e){for(const i of e)if(i)for(const n in i)t[n]?Object.assign(t[n],i[n]):t[n]=i[n];return t}class IT extends ja{constructor(e,i){super(e,i);const n=e.createTexture({format:"rgba8unorm",width:1,height:1,sampler:{minFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}}),r=e.createTexture({format:"depth16unorm",width:1,height:1});this.fbo=e.createFramebuffer({id:"shadowmap",width:1,height:1,colorAttachments:[n],depthStencilAttachment:r})}delete(){this.fbo&&(this.fbo.destroy(),this.fbo=null)}getShadowMap(){return this.fbo.colorAttachments[0].texture}render(e){const i=this.fbo,n=this.device.canvasContext.cssToDeviceRatio(),r=e.viewports[0],s=r.width*n,o=r.height*n,a=[1,1,1,1];(s!==i.width||o!==i.height)&&i.resize({width:s,height:o}),super.render({...e,clearColor:a,target:i,pass:"shadow"})}getLayerParameters(e,i,n){return{...e.props.parameters,blend:!1,depthWriteEnabled:!0,depthCompare:"less-equal"}}shouldDrawLayer(e){return e.props.shadowEnabled!==!1}getShaderModuleProps(e,i,n){return{shadow:{project:n.project,drawToShadowMap:!0}}}}const xT={color:[255,255,255],intensity:1},Dl=[{color:[255,255,255],intensity:1,direction:[-1,3,-1]},{color:[255,255,255],intensity:.9,direction:[1,-8,-2.5]}],MT=[0,0,0,200/255];class Gh{constructor(e={}){this.id="lighting-effect",this.shadowColor=MT,this.shadow=!1,this.directionalLights=[],this.pointLights=[],this.shadowPasses=[],this.dummyShadowMap=null,this.setProps(e)}setup(e){this.context=e;const{device:i,deck:n}=e;this.shadow&&!this.dummyShadowMap&&(this._createShadowPasses(i),n._addDefaultShaderModule(Ol),this.dummyShadowMap=i.createTexture({width:1,height:1}))}setProps(e){this.ambientLight=void 0,this.directionalLights=[],this.pointLights=[];for(const i in e){const n=e[i];switch(n.type){case"ambient":this.ambientLight=n;break;case"directional":this.directionalLights.push(n);break;case"point":this.pointLights.push(n);break}}this._applyDefaultLights(),this.shadow=this.directionalLights.some(i=>i.shadow),this.context&&this.setup(this.context),this.props=e}preRender({layers:e,layerFilter:i,viewports:n,onViewportActive:r,views:s}){if(this.shadow){this.shadowMatrices=this._calculateMatrices();for(let o=0;oo.getShadowMap()),dummyShadowMap:this.dummyShadowMap,shadowColor:this.shadowColor,shadowMatrices:this.shadowMatrices}:{},r={enabled:!0,lights:this._getLights(e)},s=e.props.material;return{shadow:n,lighting:r,phongMaterial:s,gouraudMaterial:s}}cleanup(e){for(const i of this.shadowPasses)i.delete();this.shadowPasses.length=0,this.dummyShadowMap&&(this.dummyShadowMap.destroy(),this.dummyShadowMap=null,e.deck._removeDefaultShaderModule(Ol))}_calculateMatrices(){const e=[];for(const i of this.directionalLights){const n=new Oe().lookAt({eye:new it(i.direction).negate()});e.push(n)}return e}_createShadowPasses(e){for(let i=0;ir&&(s=r);const o=this._pool,a=e.BYTES_PER_ELEMENT*s,c=o.findIndex(l=>l.byteLength>=a);if(c>=0){const l=new e(o.splice(c,1)[0],0,s);return n&&l.fill(0),l}return new e(s)}_release(e){if(!ArrayBuffer.isView(e))return;const i=this._pool,{buffer:n}=e,{byteLength:r}=n,s=i.findIndex(o=>o.byteLength>=r);s<0?i.push(n):(s>0||i.lengththis.opts.poolSize&&i.shift()}}const An=new OT;function Zi(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function Fl(t,e){const i=t%e;return i<0?e+i:i}function BT(t){return[t[12],t[13],t[14]]}function NT(t){return{left:fi(t[3]+t[0],t[7]+t[4],t[11]+t[8],t[15]+t[12]),right:fi(t[3]-t[0],t[7]-t[4],t[11]-t[8],t[15]-t[12]),bottom:fi(t[3]+t[1],t[7]+t[5],t[11]+t[9],t[15]+t[13]),top:fi(t[3]-t[1],t[7]-t[5],t[11]-t[9],t[15]-t[13]),near:fi(t[3]+t[2],t[7]+t[6],t[11]+t[10],t[15]+t[14]),far:fi(t[3]-t[2],t[7]-t[6],t[11]-t[10],t[15]-t[14])}}const Ul=new it;function fi(t,e,i,n){Ul.set(t,e,i);const r=Ul.len();return{distance:n/r,normal:new it(-t/r,-e/r,-i/r)}}function DT(t){return t-Math.fround(t)}let zi;function ks(t,e){const{size:i=1,startIndex:n=0}=e,r=e.endIndex!==void 0?e.endIndex:t.length,s=(r-n)/i;zi=An.allocate(zi,s,{type:Float32Array,size:i*2});let o=n,a=0;for(;o=i.delay+i.duration*i.repeat}getTime(e){if(e===void 0)return this.time;const i=this.channels.get(e);return i===void 0?-1:i.time}setTime(e){this.time=Math.max(0,e);const i=this.channels.values();for(const r of i)this._setChannelTime(r,this.time);const n=this.animations.values();for(const r of n){const{animation:s,channel:o}=r;s.setTime(this.getTime(o))}}play(){this.playing=!0}pause(){this.playing=!1,this.lastEngineTime=-1}reset(){this.setTime(0)}attachAnimation(e,i){const n=HT++;return this.animations.set(n,{animation:e,channel:i}),e.setTime(this.getTime(i)),n}detachAnimation(e){this.animations.delete(e)}update(e){this.playing&&(this.lastEngineTime===-1&&(this.lastEngineTime=e),this.setTime(this.time+(e-this.lastEngineTime)),this.lastEngineTime=e)}_setChannelTime(e,i){const n=i-e.delay,r=e.duration*e.repeat;n>=r?e.time=e.duration*e.rate:(e.time=Math.max(0,n)%e.duration,e.time*=e.rate)}}function YT(t){const e=typeof window<"u"?window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame:null;return e?e.call(window,t):setTimeout(()=>t(typeof performance<"u"?performance.now():Date.now()),1e3/60)}function XT(t){const e=typeof window<"u"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame:null;if(e){e.call(window,t);return}clearTimeout(t)}let QT=0;const KT="Animation Loop";class Ya{static defaultAnimationLoopProps={device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:e=>console.error(e),stats:void 0,autoResizeViewport:!1};device=null;canvas=null;props;animationProps=null;timeline=null;stats;sharedStats;cpuTime;gpuTime;frameRate;display;_needsRedraw="initialized";_initialized=!1;_running=!1;_animationFrameId=null;_nextFramePromise=null;_resolveNextFrame=null;_cpuStartTime=0;_error=null;_lastFrameTime=0;constructor(e){if(this.props={...Ya.defaultAnimationLoopProps,...e},e=this.props,!e.device)throw new Error("No device provided");this.stats=e.stats||new Xr({id:`animation-loop-${QT++}`}),this.sharedStats=So.stats.get(KT),this.frameRate=this.stats.get("Frame Rate"),this.frameRate.setSampleSize(1),this.cpuTime=this.stats.get("CPU Time"),this.gpuTime=this.stats.get("GPU Time"),this.setProps({autoResizeViewport:e.autoResizeViewport}),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),this.device?._disableDebugGPUTime()}delete(){this.destroy()}reportError(e){this.props.onError(e),this._error=e}setNeedsRedraw(e){return this._needsRedraw=this._needsRedraw||e,this}needsRedraw(){const e=this._needsRedraw;return this._needsRedraw=!1,e}setProps(e){return"autoResizeViewport"in e&&(this.props.autoResizeViewport=e.autoResizeViewport||!1),this}async start(){if(this._running)return this;this._running=!0;try{let e;if(!this._initialized){if(this._initialized=!0,await this._initDevice(),this._initialize(),!this._running)return null;await this.props.onInitialize(this._getAnimationProps())}return this._running?(e!==!1&&(this._cancelAnimationFrame(),this._requestAnimationFrame()),this):null}catch(e){const i=e instanceof Error?e:new Error("Unknown error");throw this.props.onError(i),i}}stop(){return this._running&&(this.animationProps&&!this._error&&this.props.onFinalize(this.animationProps),this._cancelAnimationFrame(),this._nextFramePromise=null,this._resolveNextFrame=null,this._running=!1,this._lastFrameTime=0),this}redraw(e){return this.device?.isLost||this._error?this:(this._beginFrameTimers(e),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(e){return this.timeline=e,this.timeline}detachTimeline(){this.timeline=null}waitForRender(){return this.setNeedsRedraw("waitForRender"),this._nextFramePromise||(this._nextFramePromise=new Promise(e=>{this._resolveNextFrame=e})),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._resizeViewport(),this.device?._enableDebugGPUTime()}_setDisplay(e){this.display&&(this.display.destroy(),this.display.animationLoop=null),e&&(e.animationLoop=this),this.display=e}_requestAnimationFrame(){this._running&&(this._animationFrameId=YT(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(XT(this._animationFrameId),this._animationFrameId=null)}_animationFrame(e){this._running&&(this.redraw(e),this._requestAnimationFrame())}_renderFrame(e){if(this.display){this.display._renderFrame(e);return}this.props.onRender(this._getAnimationProps()),this.device?.submit()}_clearNeedsRedraw(){this._needsRedraw=!1}_setupFrame(){this._resizeViewport()}_initializeAnimationProps(){const e=this.device?.getDefaultCanvasContext();if(!this.device||!e)throw new Error("loop");const i=e?.canvas,n=e.props.useDevicePixels;this.animationProps={animationLoop:this,device:this.device,canvasContext:e,canvas:i,useDevicePixels:n,timeline:this.timeline,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;const{width:e,height:i,aspect:n}=this._getSizeAndAspect();(e!==this.animationProps.width||i!==this.animationProps.height)&&this.setNeedsRedraw("drawing buffer resized"),n!==this.animationProps.aspect&&this.setNeedsRedraw("drawing buffer aspect changed"),this.animationProps.width=e,this.animationProps.height=i,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.getDefaultCanvasContext().canvas||null}_createInfoDiv(){if(this.canvas&&this.props.onAddHTML){const e=document.createElement("div");document.body.appendChild(e),e.style.position="relative";const i=document.createElement("div");i.style.position="absolute",i.style.left="10px",i.style.bottom="10px",i.style.width="300px",i.style.background="white",this.canvas instanceof HTMLCanvasElement&&e.appendChild(this.canvas),e.appendChild(i);const n=this.props.onAddHTML(i);n&&(i.innerHTML=n)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};const[e,i]=this.device.getDefaultCanvasContext().getDrawingBufferSize(),n=e>0&&i>0?e/i:1;return{width:e,height:i,aspect:n}}_resizeViewport(){this.props.autoResizeViewport&&this.device.gl&&this.device.gl.viewport(0,0,this.device.gl.drawingBufferWidth,this.device.gl.drawingBufferHeight)}_beginFrameTimers(e){const i=e??(typeof performance<"u"?performance.now():Date.now());if(this._lastFrameTime){const n=i-this._lastFrameTime;n>0&&this.frameRate.addTime(n)}this._lastFrameTime=i,this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeStart()}_endFrameTimers(){this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeEnd(),this._updateSharedStats()}_consumeEncodedGpuTime(){if(!this.device)return;const e=this.device.commandEncoder._gpuTimeMs;e!==void 0&&(this.gpuTime.addTime(e),this.device.commandEncoder._gpuTimeMs=void 0)}_updateSharedStats(){if(this.stats!==this.sharedStats){for(const e of Object.keys(this.sharedStats.stats))this.stats.stats[e]||delete this.sharedStats.stats[e];this.stats.forEach(e=>{const i=this.sharedStats.get(e.name,e.type);i.sampleSize=e.sampleSize,i.time=e.time,i.count=e.count,i.samples=e.samples,i.lastTiming=e.lastTiming,i.lastSampleTime=e.lastSampleTime,i.lastSampleCount=e.lastSampleCount,i._count=e._count,i._time=e._time,i._samples=e._samples,i._startTime=e._startTime,i._timerPending=e._timerPending})}}_startEventHandling(){this.canvas&&(this.canvas.addEventListener("mousemove",this._onMousemove.bind(this)),this.canvas.addEventListener("mouseleave",this._onMouseleave.bind(this)))}_onMousemove(e){e instanceof MouseEvent&&(this._getAnimationProps()._mousePosition=[e.offsetX,e.offsetY])}_onMouseleave(e){this._getAnimationProps()._mousePosition=null}}const Ws={};function ns(t="id"){Ws[t]=Ws[t]||1;const e=Ws[t]++;return`${t}-${e}`}class Wl{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||ns("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&q.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(const e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}}function qT(t,e){if(e instanceof Wl)return e;const i=ZT(t,e),{attributes:n,bufferLayout:r}=GT(t,e);return new Wl({topology:e.topology||"triangle-list",bufferLayout:r,vertexCount:e.vertexCount,indices:i,attributes:n})}function ZT(t,e){if(!e.indices)return;const i=e.indices.value;return t.createBuffer({usage:q.INDEX,data:i})}function GT(t,e){const i=[],n={};for(const[s,o]of Object.entries(e.attributes)){let a=s;switch(s){case"POSITION":a="positions";break;case"NORMAL":a="normals";break;case"TEXCOORD_0":a="texCoords";break;case"TEXCOORD_1":a="texCoords1";break;case"COLOR_0":a="colors";break}if(o){n[a]=t.createBuffer({data:o.value,id:`${s}-buffer`});const{value:c,size:l,normalized:f}=o;if(l===void 0)throw new Error(`Attribute ${s} is missing a size`);i.push({name:a,format:mn.getVertexFormatFromAttribute(c,l,f)})}}const r=e._calculateVertexCount(e.attributes,e.indices);return{attributes:n,bufferLayout:i,vertexCount:r}}function JT(t,e){const i={},n="Values";if(t.attributes.length===0&&!t.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(const r of t.attributes)if(r){const s=`${r.location} ${r.name}: ${r.type}`;i[`in ${s}`]={[n]:r.stepMode||"vertex"}}for(const r of t.varyings||[]){const s=`${r.location} ${r.name}`;i[`out ${s}`]={[n]:JSON.stringify(r)}}return i}const Vl="__debugFramebufferState",Vs=8;function $T(t,e,i){if(t.device.type!=="webgl")return;const n=iE(t.device);if(!n.flushing){if(rE(t)){eE(t,i,n);return}e&&nE(e)&&e.handle!==null&&(n.queuedFramebuffers.includes(e)||n.queuedFramebuffers.push(e))}}function eE(t,e,i){if(i.queuedFramebuffers.length===0)return;const n=t.device,{gl:r}=n,s=r.getParameter(36010),o=r.getParameter(36006),[a,c]=t.device.getDefaultCanvasContext().getDrawingBufferSize();let l=zl(e.top,Vs);const f=zl(e.left,Vs);i.flushing=!0;try{for(const u of i.queuedFramebuffers){const[h,p,d,m,g]=tE({framebuffer:u,targetWidth:a,targetHeight:c,topPx:l,leftPx:f,minimap:e.minimap});r.bindFramebuffer(36008,u.handle),r.bindFramebuffer(36009,null),r.blitFramebuffer(0,0,u.width,u.height,h,p,d,m,16384,9728),l+=g+Vs}}finally{r.bindFramebuffer(36008,s),r.bindFramebuffer(36009,o),i.flushing=!1}}function tE(t){const{framebuffer:e,targetWidth:i,targetHeight:n,topPx:r,leftPx:s}=t,o=Math.max(Math.floor(i/4),1),a=Math.max(Math.floor(n/4),1),c=Math.min(o/e.width,a/e.height),l=Math.max(Math.floor(e.width*c),1),f=Math.max(Math.floor(e.height*c),1),u=s,h=Math.max(n-r-f,0),p=u+l,d=h+f;return[u,h,p,d,f]}function iE(t){return t.userData[Vl]||={flushing:!1,queuedFramebuffers:[]},t.userData[Vl]}function nE(t){return"colorAttachments"in t}function rE(t){const e=t.props.framebuffer;return!e||e.handle===null}function zl(t,e){if(!t)return e;const i=Number.parseInt(t,10);return Number.isFinite(i)?i:e}function Bo(t,e,i){if(t===e)return!0;if(!i||!t||!e)return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let n=0;ni.name===e)||null}getAttributeNamesForBuffer(e){return e.attributes?e.attributes?.map(i=>i.attribute):[e.name]}mergeBufferLayouts(e,i){const n=[...e];for(const r of i){const s=n.findIndex(o=>o.name===r.name);s<0?n.push(r):n[s]=r}return n}getBufferIndex(e){const i=this.bufferLayouts.findIndex(n=>n.name===e);return i===-1&&C.warn(`BufferLayout: Missing buffer for "${e}".`)(),i}}function jl(t,e){let i=1/0;for(const n of t){const r=e[n];r!==void 0&&(i=Math.min(i,r))}return i}function sE(t,e){const i=Object.fromEntries(t.attributes.map(r=>[r.name,r.location])),n=e.slice();return n.sort((r,s)=>{const o=r.attributes?r.attributes.map(f=>f.attribute):[r.name],a=s.attributes?s.attributes.map(f=>f.attribute):[s.name],c=jl(o,i),l=jl(a,i);return c-l}),n}function Hl(t,e){if(!t||!e.some(n=>n.bindingLayout?.length))return t;const i={...t,bindings:t.bindings.map(n=>({...n}))};"attributes"in(t||{})&&(i.attributes=t?.attributes||[]);for(const n of e)for(const r of n.bindingLayout||[])for(const s of aE(r.name)){const o=i.bindings.find(a=>a.name===s);o?.group===0&&(o.group=r.group)}return i}function oE(t){return!!(t.uniformTypes&&!cE(t.uniformTypes))}function aE(t){const e=new Set([t,`${t}Uniforms`]);return t.endsWith("Uniforms")||e.add(`${t}Sampler`),[...e]}function cE(t){for(const e in t)return!1;return!0}function lE(t){return vm(t)||typeof t=="number"||typeof t=="boolean"}function fE(t,e={}){const i={bindings:{},uniforms:{}};return Object.keys(t).forEach(n=>{const r=t[n];Object.prototype.hasOwnProperty.call(e,n)||lE(r)?i.uniforms[n]=r:i.bindings[n]=r}),i}class uE{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;constructor(e,i){Object.assign(this.options,i);const n=Ea(Object.values(e).filter(hE));for(const r of n)e[r.name]=r;C.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(const[r,s]of Object.entries(e))s&&(this._addModule(s),s.name&&r!==s.name&&!this.options.disableWarnings&&C.warn(`Module name: ${r} vs ${s.name}`)())}destroy(){}setProps(e){for(const i of Object.keys(e)){const n=i,r=e[n]||{},s=this.modules[n];if(!s)this.options.disableWarnings||C.warn(`Module ${i} not found`)();else{const o=this.moduleUniforms[n],a=this.moduleBindings[n],c=s.getUniforms?.(r,o)||r,{uniforms:l,bindings:f}=fE(c,s.uniformTypes);this.moduleUniforms[n]=Yl(o,l,s.uniformTypes),this.moduleBindings[n]={...a,...f}}}}getModules(){return Object.values(this.modules)}getUniformValues(){return this.moduleUniforms}getBindingValues(){const e={};for(const i of Object.values(this.moduleBindings))Object.assign(e,i);return e}getDebugTable(){const e={};for(const[i,n]of Object.entries(this.moduleUniforms))for(const[r,s]of Object.entries(n))e[`${i}.${r}`]={type:this.modules[i].uniformTypes?.[r],value:String(s)};return e}_addModule(e){const i=e.name;this.moduleUniforms[i]=Yl({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[i]={}}}function Yl(t={},e={},i={}){const n={...t};for(const[r,s]of Object.entries(e))s!==void 0&&(n[r]=No(t[r],s,i[r]));return n}function No(t,e,i){if(!i||typeof i=="string")return on(e);if(Array.isArray(i)){if(Do(e)||!Array.isArray(e))return on(e);const o=Array.isArray(t)&&!Do(t)?[...t]:[],a=o.slice();for(let c=0;ci===void 0?void 0:on(i)):Fo(t)?Object.fromEntries(Object.entries(t).map(([e,i])=>[e,i===void 0?void 0:on(i)])):t}function Do(t){return ArrayBuffer.isView(t)||Array.isArray(t)&&(t.length===0||typeof t[0]=="number")}function Fo(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&!ArrayBuffer.isView(t)}function hE(t){return!!t?.dependencies}const $h={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function ji(t){return t?Array.isArray(t)?t[0]??null:t:null}function dE(t){const{dimension:e,data:i}=t;if(!i)return null;switch(e){case"1d":{const n=ji(i);if(!n)return null;const{width:r}=Hi(n);return{width:r,height:1}}case"2d":{const n=ji(i);return n?Hi(n):null}case"3d":case"2d-array":{if(!Array.isArray(i)||i.length===0)return null;const n=ji(i[0]);return n?Hi(n):null}case"cube":{const n=Object.keys(i)[0]??null;if(!n)return null;const r=i[n],s=ji(r);return s?Hi(s):null}case"cube-array":{if(!Array.isArray(i)||i.length===0)return null;const n=i[0],r=Object.keys(n)[0]??null;if(!r)return null;const s=ji(n[r]);return s?Hi(s):null}default:return null}}function Hi(t){if(Ia(t))return Th(t);if(typeof t=="object"&&"width"in t&&"height"in t)return{width:t.width,height:t.height};throw new Error("Unsupported mip-level data")}function pE(t){return typeof t=="object"&&t!==null&&"data"in t&&"width"in t&&"height"in t}function gE(t){return ArrayBuffer.isView(t)}function ed(t){const{textureFormat:e,format:i}=t;if(e&&i&&e!==i)throw new Error(`Conflicting texture formats "${e}" and "${i}" provided for the same mip level`);return e??i}function td(t){const e=$h[t];if(e===void 0)throw new Error(`Invalid cube face: ${t}`);return e}function mE(t,e){return 6*t+td(e)}function id(t){throw new Error("setTexture1DData not supported in WebGL.")}function _E(t){return Array.isArray(t)?t:[t]}function Ui(t,e,i,n){const r=_E(e),s=t,o=[];for(let a=0;a>a),height:Math.max(1,i.height>>a),...n?{format:n}:{}},textureFormat:n,z:s,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return o}function nd(t){const e=[];for(let i=0;i{for(const[r,s]of Object.entries(i)){const o=mE(n,r);e.push(...Ui(o,s))}}),e}class mi{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;resolveReady=()=>{};rejectReady=()=>{};get texture(){if(!this._texture)throw new Error("Texture not initialized yet");return this._texture}get sampler(){if(!this._sampler)throw new Error("Sampler not initialized yet");return this._sampler}get view(){if(!this._view)throw new Error("View not initialized yet");return this._view}get[Symbol.toStringTag](){return"DynamicTexture"}toString(){const e=this._texture?.width??this.props.width??"?",i=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${i}px:(${this.isReady?"ready":"loading..."})`}constructor(e,i){this.device=e;const n=ns("dynamic-texture"),r=i;this.props={...mi.defaultProps,id:n,...i,data:null},this.id=this.props.id,this.ready=new Promise((s,o)=>{this.resolveReady=s,this.rejectReady=o}),this.initAsync(r)}async initAsync(e){try{const i=await this._loadAllData(e);this._checkNotDestroyed();const n=i.data?AE({...i,width:e.width,height:e.height,format:e.format}):[],r="format"in e&&e.format!==void 0,s="usage"in e&&e.usage!==void 0,a=(()=>{if(this.props.width&&this.props.height)return{width:this.props.width,height:this.props.height};const m=dE(i);return m||{width:this.props.width||1,height:this.props.height||1}})();if(!a||a.width<=0||a.height<=0)throw new Error(`${this} size could not be determined or was zero`);const c=yE(this.device,n,a,{format:r?e.format:void 0}),l=c.format??this.props.format,f={...this.props,...a,format:l,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(l)&&!s&&(f.usage=Y.SAMPLE|Y.COPY_DST);const u=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(l);if(this.device.type==="webgpu"&&u){const m=this.props.dimension==="3d"?Y.SAMPLE|Y.STORAGE|Y.COPY_DST|Y.COPY_SRC:Y.SAMPLE|Y.RENDER|Y.COPY_DST|Y.COPY_SRC;f.usage|=m}const h=this.device.getMipLevelCount(f.width,f.height),p=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?h:Math.max(1,Math.min(h,this.props.mipLevels??1)),d={...f,mipLevels:p};this._texture=this.device.createTexture(d),this._sampler=this.texture.sampler,this._view=this.texture.view,c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!u&&C.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),u&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),C.info(0,`${this} created`)()}catch(i){const n=i instanceof Error?i:new Error(String(i));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?this.texture.generateMipmapsWebGL():this.device.type==="webgpu"?this.device.generateMipmapsWebGPU(this.texture):C.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();const i=e instanceof Gt?e:this.device.createSampler(e);this.texture.setSampler(i),this._sampler=i}async readBuffer(e={}){this.isReady||await this.ready;const i=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:i,height:n,depthOrArrayLayers:r}),o=this.device.createBuffer({byteLength:s.byteLength,usage:q.COPY_DST|q.MAP_READ});this.texture.readBuffer({...e,width:i,height:n,depthOrArrayLayers:r},o);const a=this.device.createFence();return await a.signaled,a.destroy(),o}async readAsync(e={}){this.isReady||await this.ready;const i=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:i,height:n,depthOrArrayLayers:r}),o=await this.readBuffer(e),a=await o.readAsync(0,s.byteLength);return o.destroy(),a.buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;const i=this.texture;return this._texture=i.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,i.destroy(),C.info(`${this} resized`),!0}getCubeFaceIndex(e){const i=$h[e];if(i===void 0)throw new Error(`Invalid cube face: ${e}`);return i}getCubeArrayFaceIndex(e,i){return 6*e+this.getCubeFaceIndex(i)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);const i=id();this._setTextureSubresources(i)}setTexture2DData(e,i=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);const n=Ui(i,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);const i=nd(e);this._setTextureSubresources(i)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);const i=rd(e);this._setTextureSubresources(i)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);const i=sd(e);this._setTextureSubresources(i)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);const i=od(e);this._setTextureSubresources(i)}_setTextureSubresources(e){for(const i of e){const{z:n,mipLevel:r}=i;switch(i.type){case"external-image":const{image:s,flipY:o}=i;this.texture.copyExternalImage({image:s,z:n,mipLevel:r,flipY:o});break;case"texture-data":const{data:a,textureFormat:c}=i;if(c&&c!==this.texture.format)throw new Error(`${this} mip level ${r} uses format "${c}" but texture format is "${this.texture.format}"`);this.texture.writeData(a.data,{x:0,y:0,z:n,width:a.width,height:a.height,depthOrArrayLayers:1,mipLevel:r});break;default:throw new Error("Unsupported 2D mip-level payload")}}}async _loadAllData(e){const i=await Uo(e.data);return{dimension:e.dimension??"2d",data:i??null}}_checkNotDestroyed(){this.destroyed&&C.warn(`${this} already destroyed`)}_checkReady(){this.isReady||C.warn(`${this} Cannot perform this operation before ready`)}static defaultProps={...Y.defaultProps,dimension:"2d",data:null,mipmaps:!1}}function AE(t){if(!t.data)return[];const e=t.width&&t.height?{width:t.width,height:t.height}:void 0,i="format"in t?t.format:void 0;switch(t.dimension){case"1d":return id();case"2d":return Ui(0,t.data,e,i);case"3d":return nd(t.data);case"2d-array":return rd(t.data);case"cube":return sd(t.data);case"cube-array":return od(t.data);default:throw new Error(`Unhandled dimension ${t.dimension}`)}}function yE(t,e,i,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};const r=new Map;for(const f of e){const u=r.get(f.z)??[];u.push(f),r.set(f.z,u)}const s=e.some(f=>f.mipLevel>0);let o=n.format,a=Number.POSITIVE_INFINITY;const c=[];for(const[f,u]of r){const h=[...u].sort((y,A)=>y.mipLevel-A.mipLevel),p=h[0];if(!p||p.mipLevel!==0)throw new Error(`DynamicTexture: slice ${f} is missing mip level 0`);const d=Ql(t,p);if(d.width!==i.width||d.height!==i.height)throw new Error(`DynamicTexture: slice ${f} base level dimensions ${d.width}x${d.height} do not match expected ${i.width}x${i.height}`);const m=Xl(p);if(m){if(o&&o!==m)throw new Error(`DynamicTexture: slice ${f} base level format "${m}" does not match texture format "${o}"`);o=m}const g=o&&t.isTextureFormatCompressed(o)?bE(t,d.width,d.height,o):t.getMipLevelCount(d.width,d.height);let _=0;for(let y=0;y=g)break;const b=Ql(t,A),T=Math.max(1,d.width>>y),w=Math.max(1,d.height>>y);if(b.width!==T||b.height!==w)break;const v=Xl(A);if(v&&(o||(o=v),v!==o))break;_++,c.push(A)}a=Math.min(a,_)}const l=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(f=>f.mipLevel>a),l=Math.max(1,i>>a);if(c[c.name,c])||[]),r=i.shaderInputs||new uE(n,{disableWarnings:this.props.disableWarnings});this.setShaderInputs(r);const s=TE(e),o=(this.props.modules?.length>0?this.props.modules:this.shaderInputs?.getModules())||[];if(this.props.shaderLayout=Hl(this.props.shaderLayout,o)||null,this.device.type==="webgpu"&&this.props.source){const{source:c,getUniforms:l,bindingTable:f}=this.props.shaderAssembler.assembleWGSLShader({platformInfo:s,...this.props,modules:o});this.source=c,this._getModuleUniforms=l,this._bindingTable=f;const u=e.getShaderLayout?.(this.source);this.props.shaderLayout=Hl(this.props.shaderLayout||u||null,o)||null}else{const{vs:c,fs:l,getUniforms:f}=this.props.shaderAssembler.assembleGLSLShaderPair({platformInfo:s,...this.props,modules:o});this.vs=c,this.fs=l,this._getModuleUniforms=f,this._bindingTable=[]}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,i.geometry&&this.setGeometry(i.geometry),this.pipelineFactory=i.pipelineFactory||Ma.getDefaultPipelineFactory(this.device),this.shaderFactory=i.shaderFactory||Oa.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=e.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in i&&(this.isInstanced=i.isInstanced),i.instanceCount&&this.setInstanceCount(i.instanceCount),i.vertexCount&&this.setVertexCount(i.vertexCount),i.indexBuffer&&this.setIndexBuffer(i.indexBuffer),i.attributes&&this.setAttributes(i.attributes),i.constantAttributes&&this.setConstantAttributes(i.constantAttributes),i.bindings&&this.setBindings(i.bindings),i.transformFeedback&&(this.transformFeedback=i.transformFeedback)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&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");const e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(){this.updateShaderInputs(),this.pipeline=this._updatePipeline()}draw(e){const i=this._areBindingsLoading();if(i)return C.info(pt,`>>> DRAWING ABORTED ${this.id}: ${i} not loaded`)(),!1;try{e.pushDebugGroup(`${this}.predraw(${e})`),this.predraw()}finally{e.popDebugGroup()}let n,r=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),r=this.pipeline.isErrored,r)C.info(pt,`>>> DRAWING ABORTED ${this.id}: ${Kl}`)(),n=!1;else{const s=this._getBindings(),o=this._getBindGroups(),{indexBuffer:a}=this.vertexArray,c=a?a.byteLength/(a.indexType==="uint32"?4:2):void 0;n=this.pipeline.draw({renderPass:e,vertexArray:this.vertexArray,isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.instanceCount,indexCount:c,transformFeedback:this.transformFeedback||void 0,bindings:s,bindGroups:o,_bindGroupCacheKeys:this._getBindGroupCacheKeys(),uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):r?this._needsRedraw=Kl:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){this._gpuGeometry?.destroy();const i=e&&qT(this.device,e);if(i){this.setTopology(i.topology||"triangle-list");const n=new zs(this.bufferLayout);this.bufferLayout=n.mergeBufferLayouts(i.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(i)}this._gpuGeometry=i}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){const i=new zs(this.bufferLayout);this.bufferLayout=this._gpuGeometry?i.mergeBufferLayouts(e,this._gpuGeometry.bufferLayout):e,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry)}setParameters(e){Bo(e,this.parameters,2)||(this.parameters=e,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,this.isInstanced===void 0&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this.setNeedsRedraw("vertexCount")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new _b(this.device,this.shaderInputs.modules);for(const[i,n]of Object.entries(this.shaderInputs.modules))if(oE(n)&&!this.material?.ownsModule(i)){const r=this._uniformStore.getManagedUniformBuffer(i);this.bindings[`${i}Uniforms`]=r}this.setNeedsRedraw("shaderInputs")}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}updateShaderInputs(){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues()),this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues())),this.setNeedsRedraw("shaderInputs")}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){this.vertexArray.setIndexBuffer(e),this.setNeedsRedraw("indexBuffer")}setAttributes(e,i){const n=i?.disableWarnings??this.props.disableWarnings;e.indices&&C.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=sE(this.pipeline.shaderLayout,this.bufferLayout);const r=new zs(this.bufferLayout);for(const[s,o]of Object.entries(e)){const a=r.getBufferLayout(s);if(!a){n||C.warn(`Model(${this.id}): Missing layout for buffer "${s}".`)();continue}const c=r.getAttributeNamesForBuffer(a);let l=!1;for(const f of c){const u=this._attributeInfos[f];if(u){const h=this.device.type==="webgpu"?r.getBufferIndex(u.bufferName):u.location;this.vertexArray.setBuffer(h,o),l=!0}}!l&&!n&&C.warn(`Model(${this.id}): Ignoring buffer "${o.id}" for unknown attribute "${s}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,i){for(const[n,r]of Object.entries(e)){const s=this._attributeInfos[n];s?this.vertexArray.setConstantWebGL(s.location,r):(i?.disableWarnings??this.props.disableWarnings)||C.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(const e of Object.values(this.bindings))if(e instanceof mi&&!e.isReady)return e.id;for(const e of Object.values(this.material?.bindings||{}))if(e instanceof mi&&!e.isReady)return e.id;return!1}_getBindings(){const e={};for(const[i,n]of Object.entries(this.bindings))n instanceof mi?n.isReady&&(e[i]=n.texture):e[i]=n;return e}_getBindGroups(){const e=this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]},i=e.bindings.length?Rh(e,this._getBindings()):{0:this._getBindings()};if(!this.material)return i;for(const[n,r]of Object.entries(this.material.getBindingsByGroup())){const s=Number(n);i[s]={...i[s]||{},...r}}return i}_getBindGroupCacheKeys(){const e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){let e=0;for(const i of Object.values(this.bindings))i instanceof Zr?e=Math.max(e,i.texture.updateTimestamp):i instanceof q||i instanceof Y?e=Math.max(e,i.updateTimestamp):i instanceof mi?e=i.texture?Math.max(e,i.texture.updateTimestamp):1/0:i instanceof Gt||(e=Math.max(e,i.buffer.updateTimestamp));return Math.max(e,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(e){const i={...e.attributes};for(const[n]of Object.entries(i))!this.pipeline.shaderLayout.attributes.find(r=>r.name===n)&&n!=="positions"&&delete i[n];this.vertexCount=e.vertexCount,this.setIndexBuffer(e.indices||null),this.setAttributes(e.attributes,{disableWarnings:!0}),this.setAttributes(i,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this.setNeedsRedraw(e)}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null,i=null;this.pipeline&&(C.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.pipeline.vs,i=this.pipeline.fs),this._pipelineNeedsUpdate=!1;const n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders});let r=null;this.source?r=n:this.fs&&(r=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bindings:void 0,bufferLayout:this.bufferLayout,topology:this.topology,parameters:this.parameters,bindGroups:this._getBindGroups(),vs:n,fs:r}),this._attributeInfos=Ch(this.pipeline.shaderLayout,this.bufferLayout),e&&this.shaderFactory.release(e),i&&i!==e&&this.shaderFactory.release(i)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){const e=C.level>3?0:wE;C.level<2||Date.now()-this._lastLogTime>> DRAWING MODEL ${this.id}`,{collapsed:C.level<=2})())}_logDrawCallEnd(){if(this._logOpen){const e=JT(this.pipeline.shaderLayout,this.id);C.table(pt,e)();const i=this.shaderInputs.getDebugTable();C.table(pt,i)();const n=this._getAttributeDebugTable();C.table(pt,this._attributeInfos)(),C.table(pt,n)(),C.groupEnd(pt)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){const i=this.device.props.debugFramebuffers;if(this._drawCount++,!i)return;const n=e.props.framebuffer;$T(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){const e={};for(const[i,n]of Object.entries(this._attributeInfos)){const r=this.vertexArray.attributes[n.location];e[n.location]={name:i,type:n.shaderType,values:r?this._getBufferOrConstantValues(r,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){const{indexBuffer:i}=this.vertexArray,n=i.indexType==="uint32"?new Uint32Array(i.debugData):new Uint16Array(i.debugData);e.indices={name:"indices",type:i.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,i){const n=ot.getTypedArrayConstructor(i);return(e instanceof q?new n(e.debugData):e).toString()}_getNonMaterialBindings(e){if(!this.material)return e;const i={};for(const[n,r]of Object.entries(e))this.material.ownsBinding(n)||(i[n]=r);return i}}function TE(t){return{type:t.type,shaderLanguage:t.info.shadingLanguage,shaderLanguageVersion:t.info.shadingLanguageVersion,gpu:t.info.gpu,features:t.features}}class Ni{device;model;transformFeedback;static defaultProps={...yn.defaultProps,outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return e?.info?.type==="webgl"}constructor(e,i=Ni.defaultProps){if(!Ni.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.model=new yn(this.device,{id:i.id||"buffer-transform-model",fs:i.fs||wA(),topology:i.topology||"point-list",varyings:i.outputs||i.varyings,...i}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:i.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback),Object.seal(this)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){e?.inputBuffers&&this.model.setAttributes(e.inputBuffers),e?.outputBuffers&&this.transformFeedback.setBuffers(e.outputBuffers);const i=this.device.beginRenderPass(e);this.model.draw(i),i.end()}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){const i=this.getBuffer(e);if(!i)throw new Error("BufferTransform#getBuffer");if(i instanceof q)return i.readAsync();const{buffer:n,byteOffset:r=0,byteLength:s=n.byteLength}=i;return n.readAsync(r,s)}}class EE{id;topology;vertexCount;indices;attributes;userData={};constructor(e){const{attributes:i={},indices:n=null,vertexCount:r=null}=e;this.id=e.id||ns("geometry"),this.topology=e.topology,n&&(this.indices=ArrayBuffer.isView(n)?{value:n,size:1}:n),this.attributes={};for(const[s,o]of Object.entries(i)){const a=ArrayBuffer.isView(o)?{value:o}:o;if(!ArrayBuffer.isView(a.value))throw new Error(`${this._print(s)}: must be typed array or object with value as typed array`);if((s==="POSITION"||s==="positions")&&!a.size&&(a.size=3),s==="indices"){if(this.indices)throw new Error("Multiple indices detected");this.indices=a}else this.attributes[s]=a}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(e){return`Geometry ${this.id} attribute ${e}`}_setAttributes(e,i){return this}_calculateVertexCount(e,i){if(i)return i.value.length;let n=1/0;for(const r of Object.values(e)){const{value:s,size:o,constant:a}=r;!a&&s&&o!==void 0&&o>=1&&(n=Math.min(n,s.length/o))}return n}}const SE={blendColorOperation:"add",blendColorSrcFactor:"one",blendColorDstFactor:"zero",blendAlphaOperation:"add",blendAlphaSrcFactor:"constant",blendAlphaDstFactor:"zero"};class ad extends ja{constructor(){super(...arguments),this._colorEncoderState=null}render(e){return"pickingFBO"in e?this._drawPickingBuffer(e):{decodePickingColor:null,stats:super._render(e)}}_drawPickingBuffer({layers:e,layerFilter:i,views:n,viewports:r,onViewportActive:s,pickingFBO:o,deviceRect:{x:a,y:c,width:l,height:f},cullRect:u,effects:h,pass:p="picking",pickZ:d,shaderModuleProps:m,clearColor:g}){this.pickZ=d;const _=this._resetColorEncoder(d),y=[a,c,l,f],A=super._render({target:o,layers:e,layerFilter:i,views:n,viewports:r,onViewportActive:s,cullRect:u,effects:h?.filter(T=>T.useInPicking),pass:p,isPicking:!0,shaderModuleProps:m,clearColor:g??[0,0,0,0],colorMask:15,scissorRect:y});return this._colorEncoderState=null,{decodePickingColor:_&&RE.bind(null,_),stats:A}}shouldDrawLayer(e){const{pickable:i,operation:n}=e.props;return i&&n.includes("draw")||n.includes("terrain")||n.includes("mask")}getShaderModuleProps(e,i,n){return{picking:{isActive:1,isAttribute:this.pickZ},lighting:{enabled:!1}}}getLayerParameters(e,i,n){const r={...e.props.parameters},{pickable:s,operation:o}=e.props;return this._colorEncoderState?s&&o.includes("draw")?(Object.assign(r,SE),r.blend=!0,this.device.type==="webgpu"?r.blendConstant=ql(this._colorEncoderState,e,n):r.blendColor=ql(this._colorEncoderState,e,n),o.includes("terrain")&&e.state?._hasPickingCover&&(r.blendAlphaSrcFactor="one")):o.includes("terrain")&&(r.blend=!1):r.blend=!1,r}_resetColorEncoder(e){return this._colorEncoderState=e?null:{byLayer:new Map,byAlpha:[]},this._colorEncoderState}}function ql(t,e,i){const{byLayer:n,byAlpha:r}=t;let s,o=n.get(e);return o?(o.viewports.push(i),s=o.a):(s=n.size+1,s<=255?(o={a:s,layer:e,viewports:[i]},n.set(e,o),r[s]=o):(J.warn("Too many pickable layers, only picking the first 255")(),s=0)),[0,0,0,s/255]}function RE(t,e){const i=t.byAlpha[e[3]];return i&&{pickedLayer:i.layer,pickedViewports:i.viewports,pickedObjectIndex:i.layer.decodePickingColor(e)}}const di={NO_STATE:"Awaiting state",MATCHED:"Matched. State transferred from previous layer",INITIALIZED:"Initialized",AWAITING_GC:"Discarded. Awaiting garbage collection",AWAITING_FINALIZATION:"No longer matched. Awaiting garbage collection",FINALIZED:"Finalized! Awaiting garbage collection"},Lr=Symbol.for("component"),zt=Symbol.for("propTypes"),js=Symbol.for("deprecatedProps"),Si=Symbol.for("asyncPropDefaults"),Jt=Symbol.for("asyncPropOriginal"),Tt=Symbol.for("asyncPropResolved");function cd(t,e=()=>!0){return Array.isArray(t)?ld(t,e,[]):e(t)?[t]:[]}function ld(t,e,i){let n=-1;for(;++n0}delete(){}getData(){return this.isLoaded?this._error?Promise.reject(this._error):this._content:this._loader.then(()=>this.getData())}setData(e,i){if(e===this._data&&!i)return;this._data=e;const n=++this._loadCount;let r=e;typeof e=="string"&&(r=po(e)),r instanceof Promise?(this.isLoaded=!1,this._loader=r.then(s=>{this._loadCount===n&&(this.isLoaded=!0,this._error=void 0,this._content=s)}).catch(s=>{this._loadCount===n&&(this.isLoaded=!0,this._error=s||!0)})):(this.isLoaded=!0,this._error=void 0,this._content=e);for(const s of this._subscribers)s.onChange(this.getData())}}class PE{constructor(e){this.protocol=e.protocol||"resource://",this._context={device:e.device,gl:e.device?.gl,resourceManager:this},this._resources={},this._consumers={},this._pruneRequest=null}contains(e){return e.startsWith(this.protocol)?!0:e in this._resources}add({resourceId:e,data:i,forceUpdate:n=!1,persistent:r=!0}){let s=this._resources[e];s?s.setData(i,n):(s=new CE(e,i,this._context),this._resources[e]=s),s.persistent=r}remove(e){const i=this._resources[e];i&&(i.delete(),delete this._resources[e])}unsubscribe({consumerId:e}){const i=this._consumers[e];if(i){for(const n in i){const r=i[n],s=this._resources[r.resourceId];s&&s.unsubscribe(r)}delete this._consumers[e],this.prune()}}subscribe({resourceId:e,onChange:i,consumerId:n,requestId:r="default"}){const{_resources:s,protocol:o}=this;e.startsWith(o)&&(e=e.replace(o,""),s[e]||this.add({resourceId:e,data:null,persistent:!1}));const a=s[e];if(this._track(n,r,a,i),a)return a.getData()}prune(){this._pruneRequest||(this._pruneRequest=setTimeout(()=>this._prune(),0))}finalize(){for(const e in this._resources)this._resources[e].delete()}_track(e,i,n,r){const s=this._consumers,o=s[e]=s[e]||{};let a=o[i];const c=a&&a.resourceId&&this._resources[a.resourceId];c&&(c.unsubscribe(a),this.prune()),n&&(a?(a.onChange=r,a.resourceId=n.id):a={onChange:r,resourceId:n.id},o[i]=a,n.subscribe(a))}_prune(){this._pruneRequest=null;for(const e of Object.keys(this._resources)){const i=this._resources[e];!i.persistent&&!i.inUse()&&(i.delete(),delete this._resources[e])}}}const IE="layerManager.setLayers",xE="layerManager.activateViewport";class ME{constructor(e,i){this._lastRenderedLayers=[],this._needsRedraw=!1,this._needsUpdate=!1,this._nextLayers=null,this._debug=!1,this._defaultShaderModulesChanged=!1,this.activateViewport=a=>{be(xE,this,a),a&&(this.context.viewport=a)};const{deck:n,stats:r,viewport:s,timeline:o}=i||{};this.layers=[],this.resourceManager=new PE({device:e,protocol:"deck://"}),this.context={mousePosition:null,userData:{},layerManager:this,device:e,gl:e?.gl,deck:n,shaderAssembler:_T(e?.info?.shadingLanguage||"glsl"),defaultShaderModules:[bb],renderPass:void 0,stats:r||new Xr({id:"deck.gl"}),viewport:s||new ri({id:"DEFAULT-INITIAL-VIEWPORT"}),timeline:o||new Jh,resourceManager:this.resourceManager,onError:void 0},Object.seal(this)}finalize(){this.resourceManager.finalize();for(const e of this.layers)this._finalizeLayer(e)}needsRedraw(e={clearRedrawFlags:!1}){let i=this._needsRedraw;e.clearRedrawFlags&&(this._needsRedraw=!1);for(const n of this.layers){const r=n.getNeedsRedraw(e);i=i||r}return i}needsUpdate(){return this._nextLayers&&this._nextLayers!==this._lastRenderedLayers?"layers changed":this._defaultShaderModulesChanged?"shader modules changed":this._needsUpdate}setNeedsRedraw(e){this._needsRedraw=this._needsRedraw||e}setNeedsUpdate(e){this._needsUpdate=this._needsUpdate||e}getLayers({layerIds:e}={}){return e?this.layers.filter(i=>e.find(n=>i.id.indexOf(n)===0)):this.layers}setProps(e){"debug"in e&&(this._debug=e.debug),"userData"in e&&(this.context.userData=e.userData),"layers"in e&&(this._nextLayers=e.layers),"onError"in e&&(this.context.onError=e.onError)}setLayers(e,i){be(IE,this,i,e),this._lastRenderedLayers=e;const n=cd(e,Boolean);for(const r of n)r.context=this.context;this._updateLayers(this.layers,n)}updateLayers(){const e=this.needsUpdate();e&&(this.setNeedsRedraw(`updating layers: ${e}`),this.setLayers(this._nextLayers||this._lastRenderedLayers,e)),this._nextLayers=null}addDefaultShaderModule(e){const{defaultShaderModules:i}=this.context;i.find(n=>n.name===e.name)||(i.push(e),this._defaultShaderModulesChanged=!0)}removeDefaultShaderModule(e){const{defaultShaderModules:i}=this.context,n=i.findIndex(r=>r.name===e.name);n>=0&&(i.splice(n,1),this._defaultShaderModulesChanged=!0)}_handleError(e,i,n){n.raiseError(i,`${e} of ${n}`)}_updateLayers(e,i){const n={};for(const o of e)n[o.id]?J.warn(`Multiple old layers with same id ${o.id}`)():n[o.id]=o;if(this._defaultShaderModulesChanged){for(const o of e)o.setNeedsUpdate(),o.setChangeFlags({extensionsChanged:!0});this._defaultShaderModulesChanged=!1}const r=[];this._updateSublayersRecursively(i,n,r),this._finalizeOldLayers(n);let s=!1;for(const o of r)if(o.hasUniformTransition()){s=`Uniform transition in ${o}`;break}this._needsUpdate=s,this.layers=r}_updateSublayersRecursively(e,i,n){for(const r of e){r.context=this.context;const s=i[r.id];s===null&&J.warn(`Multiple new layers with same id ${r.id}`)(),i[r.id]=null;let o=null;try{this._debug&&s!==r&&r.validateProps(),s?(this._transferLayerState(s,r),this._updateLayer(r)):this._initializeLayer(r),n.push(r),o=r.isComposite?r.getSubLayers():null}catch(a){this._handleError("matching",a,r)}o&&this._updateSublayersRecursively(o,i,n)}}_finalizeOldLayers(e){for(const i in e){const n=e[i];n&&this._finalizeLayer(n)}}_initializeLayer(e){try{e._initialize(),e.lifecycle=di.INITIALIZED}catch(i){this._handleError("initialization",i,e)}}_transferLayerState(e,i){i._transferState(e),i.lifecycle=di.MATCHED,i!==e&&(e.lifecycle=di.AWAITING_GC)}_updateLayer(e){try{e._update()}catch(i){this._handleError("update",i,e)}}_finalizeLayer(e){this._needsRedraw=this._needsRedraw||`finalized ${e}`,e.lifecycle=di.AWAITING_FINALIZATION;try{e._finalize(),e.lifecycle=di.FINALIZED}catch(i){this._handleError("finalization",i,e)}}}function Me(t,e,i){if(t===e)return!0;if(!i||!t||!e)return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let n=0;ni.containsPixel(e)):this._viewports}getViews(){const e={};return this.views.forEach(i=>{e[i.id]=i}),e}getView(e){return this.views.find(i=>i.id===e)}getViewState(e){const i=typeof e=="string"?this.getView(e):e,n=i&&this.viewState[i.getViewStateId()]||this.viewState;return i?i.filterViewState(n):n}getViewport(e){return this._viewportMap[e]}unproject(e,i){const n=this.getViewports(),r={x:e[0],y:e[1]};for(let s=n.length-1;s>=0;--s){const o=n[s];if(o.containsPixel(r)){const a=e.slice();return a[0]-=o.x,a[1]-=o.y,o.unproject(a,i)}}return null}setProps(e){e.views&&this._setViews(e.views),e.viewState&&this._setViewState(e.viewState),("width"in e||"height"in e)&&this._setSize(e.width,e.height),"pickPosition"in e&&(this._pickPosition=e.pickPosition),this._isUpdating||this._update()}_update(){this._isUpdating=!0,this._needsUpdate&&(this._needsUpdate=!1,this._rebuildViewports()),this._needsUpdate&&(this._needsUpdate=!1,this._rebuildViewports()),this._isUpdating=!1}_setSize(e,i){(e!==this.width||i!==this.height)&&(this.width=e,this.height=i,this.setNeedsUpdate("Size changed"))}_setViews(e){e=cd(e,Boolean),this._diffViews(e,this.views)&&this.setNeedsUpdate("views changed"),this.views=e}_setViewState(e){e?(!Me(e,this.viewState,3)&&this.setNeedsUpdate("viewState changed"),this.viewState=e):J.warn("missing `viewState` or `initialViewState`")()}_createController(e,i){const n=i.type;return new n({timeline:this.timeline,eventManager:this._eventManager,onViewStateChange:this._eventCallbacks.onViewStateChange,onStateChange:this._eventCallbacks.onInteractionStateChange,makeViewport:s=>this.getView(e.id)?.makeViewport({viewState:s,width:this.width,height:this.height}),pickPosition:this._pickPosition})}_updateController(e,i,n,r){const s=e.controller;if(s&&n){const o={...i,...s,id:e.id,x:n.x,y:n.y,width:n.width,height:n.height};return(!r||r.constructor!==s.type)&&(r=this._createController(e,o)),r&&r.setProps(o),r}return null}_rebuildViewports(){const{views:e}=this,i=this.controllers;this._viewports=[],this.controllers={};let n=!1;for(let r=e.length;r--;){const s=e[r],o=this.getViewState(s),a=s.makeViewport({viewState:o,width:this.width,height:this.height});let c=i[s.id];const l=!!s.controller;l&&!c&&(n=!0),(n||!l)&&c&&(c.finalize(),c=null),this.controllers[s.id]=this._updateController(s,o,a,c),a&&this._viewports.unshift(a)}for(const r in i){const s=i[r];s&&!this.controllers[r]&&s.finalize()}this._buildViewportMap()}_buildViewportMap(){this._viewportMap={},this._viewports.forEach(e=>{e.id&&(this._viewportMap[e.id]=this._viewportMap[e.id]||e)})}_diffViews(e,i){return e.length!==i.length?!0:e.some((n,r)=>!e[r].equals(i[r]))}}const BE=/^(?:\d+\.?\d*|\.\d+)$/;function gt(t){switch(typeof t){case"number":if(!Number.isFinite(t))throw new Error(`Could not parse position string ${t}`);return{type:"literal",value:t};case"string":try{const e=NE(t);return new DE(e).parseExpression()}catch(e){const i=e instanceof Error?e.message:String(e);throw new Error(`Could not parse position string ${t}: ${i}`)}default:throw new Error(`Could not parse position string ${t}`)}}function ko(t,e){switch(t.type){case"literal":return t.value;case"percentage":return Math.round(t.value*e);case"binary":const i=ko(t.left,e),n=ko(t.right,e);return t.operator==="+"?i+n:i-n;default:throw new Error("Unknown layout expression type")}}function mt(t,e){return ko(t,e)}function NE(t){const e=[];let i=0;for(;i="0"&&t<="9"}function Gl(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"}function FE(t){return!!(t&&t.type==="symbol"&&(t.value==="+"||t.value==="-"))}function UE(t,e){const i={...t};for(const n in e)n!=="id"&&(Array.isArray(i[n])&&Array.isArray(e[n])?i[n]=kE(i[n],e[n]):i[n]=e[n]);return i}function kE(t,e){t=t.slice();for(let i=0;i{},Lo={BREAK:1,SNAP_TO_END:2,IGNORE:3},LE=t=>t,WE=Lo.BREAK;class VE{constructor(e){this._onTransitionUpdate=i=>{const{time:n,settings:{interpolator:r,startProps:s,endProps:o,duration:a,easing:c}}=i,l=c(n/a),f=r.interpolateProps(s,o,l);this.propsInTransition=this.getControllerState({...this.props,...f}).getViewportProps(),this.onViewStateChange({viewState:this.propsInTransition,oldViewState:this.props})},this.getControllerState=e.getControllerState,this.propsInTransition=null,this.transition=new rs(e.timeline),this.onViewStateChange=e.onViewStateChange||Jl,this.onStateChange=e.onStateChange||Jl}finalize(){this.transition.cancel()}getViewportInTransition(){return this.propsInTransition}processViewStateChange(e){let i=!1;const n=this.props;if(this.props=e,!n||this._shouldIgnoreViewportChange(n,e))return!1;if(this._isTransitionEnabled(e)){let r=n;if(this.transition.inProgress){const{interruption:s,endProps:o}=this.transition.settings;r={...n,...s===Lo.SNAP_TO_END?o:this.propsInTransition||n}}this._triggerTransition(r,e),i=!0}else this.transition.cancel();return i}updateTransition(){this.transition.update()}_isTransitionEnabled(e){const{transitionDuration:i,transitionInterpolator:n}=e;return(i>0||i==="auto")&&!!n}_isUpdateDueToCurrentTransition(e){return this.transition.inProgress&&this.propsInTransition?this.transition.settings.interpolator.arePropsEqual(e,this.propsInTransition):!1}_shouldIgnoreViewportChange(e,i){return this.transition.inProgress?this.transition.settings.interruption===Lo.IGNORE||this._isUpdateDueToCurrentTransition(i):this._isTransitionEnabled(i)?i.transitionInterpolator.arePropsEqual(e,i):!0}_triggerTransition(e,i){const n=this.getControllerState(e),r=this.getControllerState(i).shortestPathFrom(n),s=i.transitionInterpolator,o=s.getDuration?s.getDuration(e,i):i.transitionDuration;if(o===0)return;const a=s.initializeProps(e,r);this.propsInTransition={};const c={duration:o,easing:i.transitionEasing||LE,interpolator:s,interruption:i.transitionInterruption||WE,startProps:a.start,endProps:a.end,onStart:i.onTransitionStart,onUpdate:this._onTransitionUpdate,onInterrupt:this._onTransitionEnd(i.onTransitionInterrupt),onEnd:this._onTransitionEnd(i.onTransitionEnd)};this.transition.start(c),this.onStateChange({inTransition:!0}),this.updateTransition()}_onTransitionEnd(e){return i=>{this.propsInTransition=null,this.onStateChange({inTransition:!1,isZooming:!1,isPanning:!1,isRotating:!1}),e?.(i)}}}function pe(t,e){if(!t)throw new Error(e||"deck.gl: assertion failed.")}class zE{constructor(e){const{compare:i,extract:n,required:r}=e;this._propsToCompare=i,this._propsToExtract=n||i,this._requiredProps=r}arePropsEqual(e,i){for(const n of this._propsToCompare)if(!(n in e)||!(n in i)||!gn(e[n],i[n]))return!1;return!0}initializeProps(e,i){const n={},r={};for(const s of this._propsToExtract)(s in e||s in i)&&(n[s]=e[s],r[s]=i[s]);return this._checkRequiredProps(n),this._checkRequiredProps(r),{start:n,end:r}}getDuration(e,i){return i.transitionDuration}_checkRequiredProps(e){this._requiredProps&&this._requiredProps.forEach(i=>{const n=e[i];pe(Number.isFinite(n)||Array.isArray(n),`${i} is required for transition`)})}}const qn=Math.PI/180,$l=180/Math.PI,_r=6370972,_i=256;function jE(){const t=_i/_r,e=Math.PI/180*_i;return{unitsPerMeter:[t,t,t],unitsPerMeter2:[0,0,0],metersPerUnit:[1/t,1/t,1/t],unitsPerDegree:[e,e,t],unitsPerDegree2:[0,0,0],degreesPerUnit:[1/e,1/e,1/t]}}class ud extends ri{constructor(e={}){const{longitude:i=0,zoom:n=0,nearZMultiplier:r=.5,farZMultiplier:s=1,resolution:o=10}=e;let{latitude:a=0,height:c,altitude:l=1.5,fovy:f}=e;a=Math.max(Math.min(a,wt),-wt),c=c||1,f?l=za(f):f=_n(l);const u=Math.pow(2,n-Zn(a)),h=e.nearZ??r,p=e.farZ??(l+_i*2*u/c)*s,d=new Oe().lookAt({eye:[0,-l,0],up:[0,0,1]});d.rotateX(a*qn),d.rotateZ(-i*qn),d.scale(u/c),super({...e,height:c,viewMatrix:d,longitude:i,latitude:a,zoom:n,distanceScales:jE(),fovy:f,focalDistance:l,near:h,far:p}),this.scale=u,this.latitude=a,this.longitude=i,this.fovy=f,this.resolution=o}get projectionMode(){return xe.GLOBE}getDistanceScales(){return this.distanceScales}getBounds(e={}){const i={targetZ:e.z||0},n=this.unproject([0,this.height/2],i),r=this.unproject([this.width/2,0],i),s=this.unproject([this.width,this.height/2],i),o=this.unproject([this.width/2,this.height],i);return s[0]this.longitude&&(n[0]-=360),[Math.min(n[0],s[0],r[0],o[0]),Math.min(n[1],s[1],r[1],o[1]),Math.max(n[0],s[0],r[0],o[0]),Math.max(n[1],s[1],r[1],o[1])]}unproject(e,{topLeft:i=!0,targetZ:n}={}){const[r,s,o]=e,a=i?s:this.height-s,{pixelUnprojectionMatrix:c}=this;let l;if(Number.isFinite(o))l=Hs(c,[r,a,o,1]);else{const p=Hs(c,[r,a,-1,1]),d=Hs(c,[r,a,1,1]),m=((n||0)/_r+1)*_i,g=Es(dh([],p,d)),_=Es(p),y=Es(d),b=4*((4*_*y-(g-_-y)**2)/16)/g,T=Math.sqrt(_-b),w=Math.sqrt(Math.max(0,m*m-b)),v=(T-w)/Math.sqrt(g);l=HA([],p,d,v)}const[f,u,h]=this.unprojectPosition(l);return Number.isFinite(o)?[f,u,h]:Number.isFinite(n)?[f,u,n]:[f,u]}projectPosition(e){const[i,n,r=0]=e,s=i*qn,o=n*qn,a=Math.cos(o),c=(r/_r+1)*_i;return[Math.sin(s)*a*c,-Math.cos(s)*a*c,Math.sin(o)*c]}unprojectPosition(e){const[i,n,r]=e,s=GA(e),o=Math.asin(r/s),c=Math.atan2(i,-n)*$l,l=o*$l,f=(s/_i-1)*_r;return[c,l,f]}projectFlat(e){return e}unprojectFlat(e){return e}panByPosition([e,i,n],r,s){const a=.25/Math.pow(2,this.zoom-Zn(this.latitude)),c=e+a*(s[0]-r[0]);let l=i-a*(s[1]-r[1]);l=Math.max(Math.min(l,wt),-wt);const f={longitude:c,latitude:l,zoom:n-Zn(i)};return f.zoom+=Zn(f.latitude),f}}ud.displayName="GlobeViewport";function Zn(t){const e=Math.PI*Math.cos(t*Math.PI/180);return Math.log2(e)}function Hs(t,e){const i=Fi([],e,t);return mh(i,i,1/i[3]),i}const HE=["longitude","latitude","zoom","bearing","pitch"],YE=["longitude","latitude","zoom"];class Xa extends zE{constructor(e={}){const i=Array.isArray(e)?e:e.transitionProps,n=Array.isArray(e)?{}:e;n.transitionProps=Array.isArray(i)?{compare:i,required:i}:i||{compare:HE,required:YE},super(n.transitionProps),this.opts=n}initializeProps(e,i){const n=super.initializeProps(e,i),{makeViewport:r,around:s}=this.opts;if(r&&s)if(r(e)instanceof ud)J.warn("around not supported in GlobeView")();else{const a=r(e),c=r(i),l=a.unproject(s);n.start.around=s,Object.assign(n.end,{around:c.project(l),aroundPosition:l,width:i.width,height:i.height})}return n}interpolateProps(e,i,n){const r={};for(const s of this._propsToExtract)r[s]=Mr(e[s]||0,i[s]||0,n);if(i.aroundPosition&&this.opts.makeViewport){const s=this.opts.makeViewport({...i,...r});Object.assign(r,s.panByPosition(i.aroundPosition,Mr(e.around,i.around,n)))}return r}}const rt={transitionDuration:0},XE=300,Gn=t=>1-(1-t)*(1-t),ui={WHEEL:["wheel"],PAN:["panstart","panmove","panend"],PINCH:["pinchstart","pinchmove","pinchend"],MULTI_PAN:["multipanstart","multipanmove","multipanend"],DOUBLE_CLICK:["dblclick"],KEYBOARD:["keydown"]},Mt={};class hd{constructor(e){this.state={},this._events={},this._interactionState={isDragging:!1},this._customEvents=[],this._eventStartBlocked=null,this._panMove=!1,this.invertPan=!1,this.dragMode="rotate",this.inertia=0,this.scrollZoom=!0,this.dragPan=!0,this.dragRotate=!0,this.doubleClickZoom=!0,this.touchZoom=!0,this.touchRotate=!1,this.keyboard=!0,this.transitionManager=new VE({...e,getControllerState:i=>new this.ControllerState(i),onViewStateChange:this._onTransition.bind(this),onStateChange:this._setInteractionState.bind(this)}),this.handleEvent=this.handleEvent.bind(this),this.eventManager=e.eventManager,this.onViewStateChange=e.onViewStateChange||(()=>{}),this.onStateChange=e.onStateChange||(()=>{}),this.makeViewport=e.makeViewport,this.pickPosition=e.pickPosition}set events(e){this.toggleEvents(this._customEvents,!1),this.toggleEvents(e,!0),this._customEvents=e,this.props&&this.setProps(this.props)}finalize(){for(const e in this._events)this._events[e]&&this.eventManager?.off(e,this.handleEvent);this.transitionManager.finalize()}handleEvent(e){this._controllerState=void 0;const i=this._eventStartBlocked;switch(e.type){case"panstart":return i?!1:this._onPanStart(e);case"panmove":return this._onPan(e);case"panend":return this._onPanEnd(e);case"pinchstart":return i?!1:this._onPinchStart(e);case"pinchmove":return this._onPinch(e);case"pinchend":return this._onPinchEnd(e);case"multipanstart":return i?!1:this._onMultiPanStart(e);case"multipanmove":return this._onMultiPan(e);case"multipanend":return this._onMultiPanEnd(e);case"dblclick":return this._onDoubleClick(e);case"wheel":return this._onWheel(e);case"keydown":return this._onKeyDown(e);default:return!1}}get controllerState(){return this._controllerState=this._controllerState||new this.ControllerState({makeViewport:this.makeViewport,...this.props,...this.state}),this._controllerState}getCenter(e){const{x:i,y:n}=this.props,{offsetCenter:r}=e;return[r.x-i,r.y-n]}isPointInBounds(e,i){const{width:n,height:r}=this.props;if(i&&i.handled)return!1;const s=e[0]>=0&&e[0]<=n&&e[1]>=0&&e[1]<=r;return s&&i&&i.stopPropagation(),s}isFunctionKeyPressed(e){const{srcEvent:i}=e;return!!(i.metaKey||i.altKey||i.ctrlKey||i.shiftKey)}isDragging(){return this._interactionState.isDragging||!1}blockEvents(e){const i=setTimeout(()=>{this._eventStartBlocked===i&&(this._eventStartBlocked=null)},e);this._eventStartBlocked=i}setProps(e){e.dragMode&&(this.dragMode=e.dragMode);const i=this.props;this.props=e,"transitionInterpolator"in e||(e.transitionInterpolator=this._getTransitionProps().transitionInterpolator),this.transitionManager.processViewStateChange(e);const{inertia:n}=e;this.inertia=Number.isFinite(n)?n:n===!0?XE:0;const{scrollZoom:r=!0,dragPan:s=!0,dragRotate:o=!0,doubleClickZoom:a=!0,touchZoom:c=!0,touchRotate:l=!1,keyboard:f=!0}=e,u=!!this.onViewStateChange;if(this.toggleEvents(ui.WHEEL,u&&r),this.toggleEvents(ui.PAN,u),this.toggleEvents(ui.PINCH,u&&(c||l)),this.toggleEvents(ui.MULTI_PAN,u&&l),this.toggleEvents(ui.DOUBLE_CLICK,u&&a),this.toggleEvents(ui.KEYBOARD,u&&f),this.scrollZoom=r,this.dragPan=s,this.dragRotate=o,this.doubleClickZoom=a,this.touchZoom=c,this.touchRotate=l,this.keyboard=f,(!i||i.height!==e.height||i.width!==e.width||i.maxBounds!==e.maxBounds)&&e.maxBounds){const p=new this.ControllerState({...e,makeViewport:this.makeViewport}),d=p.getViewportProps();Object.keys(d).some(g=>!Me(d[g],e[g],1))&&this.updateViewport(p)}}updateTransition(){this.transitionManager.updateTransition()}toggleEvents(e,i){this.eventManager&&e.forEach(n=>{this._events[n]!==i&&(this._events[n]=i,i?this.eventManager.on(n,this.handleEvent):this.eventManager.off(n,this.handleEvent))})}updateViewport(e,i=null,n={}){const r={...e.getViewportProps(),...i},s=this.controllerState!==e;if(this.state=e.getState(),this._setInteractionState(n),s){const o=this.controllerState&&this.controllerState.getViewportProps();this.onViewStateChange&&this.onViewStateChange({viewState:r,interactionState:this._interactionState,oldViewState:o,viewId:this.props.id})}}_onTransition(e){this.onViewStateChange({...e,interactionState:this._interactionState,viewId:this.props.id})}_setInteractionState(e){Object.assign(this._interactionState,e),this.onStateChange(this._interactionState)}_onPanStart(e){const i=this.getCenter(e);if(!this.isPointInBounds(i,e))return!1;let n=this.isFunctionKeyPressed(e)||e.rightButton||!1;(this.invertPan||this.dragMode==="pan")&&(n=!n);const r=this.controllerState[n?"panStart":"rotateStart"]({pos:i});return this._panMove=n,this.updateViewport(r,rt,{isDragging:!0}),!0}_onPan(e){return this.isDragging()?this._panMove?this._onPanMove(e):this._onPanRotate(e):!1}_onPanEnd(e){return this.isDragging()?this._panMove?this._onPanMoveEnd(e):this._onPanRotateEnd(e):!1}_onPanMove(e){if(!this.dragPan)return!1;const i=this.getCenter(e),n=this.controllerState.pan({pos:i});return this.updateViewport(n,rt,{isDragging:!0,isPanning:!0}),!0}_onPanMoveEnd(e){const{inertia:i}=this;if(this.dragPan&&i&&e.velocity){const n=this.getCenter(e),r=[n[0]+e.velocityX*i/2,n[1]+e.velocityY*i/2],s=this.controllerState.pan({pos:r}).panEnd();this.updateViewport(s,{...this._getTransitionProps(),transitionDuration:i,transitionEasing:Gn},{isDragging:!1,isPanning:!0})}else{const n=this.controllerState.panEnd();this.updateViewport(n,null,{isDragging:!1,isPanning:!1})}return!0}_onPanRotate(e){if(!this.dragRotate)return!1;const i=this.getCenter(e),n=this.controllerState.rotate({pos:i});return this.updateViewport(n,rt,{isDragging:!0,isRotating:!0}),!0}_onPanRotateEnd(e){const{inertia:i}=this;if(this.dragRotate&&i&&e.velocity){const n=this.getCenter(e),r=[n[0]+e.velocityX*i/2,n[1]+e.velocityY*i/2],s=this.controllerState.rotate({pos:r}).rotateEnd();this.updateViewport(s,{...this._getTransitionProps(),transitionDuration:i,transitionEasing:Gn},{isDragging:!1,isRotating:!0})}else{const n=this.controllerState.rotateEnd();this.updateViewport(n,null,{isDragging:!1,isRotating:!1})}return!0}_onWheel(e){if(!this.scrollZoom)return!1;const i=this.getCenter(e);if(!this.isPointInBounds(i,e))return!1;e.srcEvent.preventDefault();const{speed:n=.01,smooth:r=!1}=this.scrollZoom===!0?{}:this.scrollZoom,{delta:s}=e;let o=2/(1+Math.exp(-Math.abs(s*n)));s<0&&o!==0&&(o=1/o);const a=r?{...this._getTransitionProps({around:i}),transitionDuration:250}:rt,c=this.controllerState.zoom({pos:i,scale:o});return this.updateViewport(c,a,{isZooming:!0,isPanning:!0}),r||this._setInteractionState({isZooming:!1,isPanning:!1}),!0}_onMultiPanStart(e){const i=this.getCenter(e);if(!this.isPointInBounds(i,e))return!1;const n=this.controllerState.rotateStart({pos:i});return this.updateViewport(n,rt,{isDragging:!0}),!0}_onMultiPan(e){if(!this.touchRotate||!this.isDragging())return!1;const i=this.getCenter(e);i[0]-=e.deltaX;const n=this.controllerState.rotate({pos:i});return this.updateViewport(n,rt,{isDragging:!0,isRotating:!0}),!0}_onMultiPanEnd(e){if(!this.isDragging())return!1;const{inertia:i}=this;if(this.touchRotate&&i&&e.velocityY){const n=this.getCenter(e),r=[n[0],n[1]+=e.velocityY*i/2],s=this.controllerState.rotate({pos:r});this.updateViewport(s,{...this._getTransitionProps(),transitionDuration:i,transitionEasing:Gn},{isDragging:!1,isRotating:!0}),this.blockEvents(i)}else{const n=this.controllerState.rotateEnd();this.updateViewport(n,null,{isDragging:!1,isRotating:!1})}return!0}_onPinchStart(e){const i=this.getCenter(e);if(!this.isPointInBounds(i,e))return!1;const n=this.controllerState.zoomStart({pos:i}).rotateStart({pos:i});return Mt._startPinchRotation=e.rotation,Mt._lastPinchEvent=e,this.updateViewport(n,rt,{isDragging:!0}),!0}_onPinch(e){if(!this.touchZoom&&!this.touchRotate||!this.isDragging())return!1;let i=this.controllerState;if(this.touchZoom){const{scale:n}=e,r=this.getCenter(e);i=i.zoom({pos:r,scale:n})}if(this.touchRotate){const{rotation:n}=e;i=i.rotate({deltaAngleX:Mt._startPinchRotation-n})}return this.updateViewport(i,rt,{isDragging:!0,isPanning:this.touchZoom,isZooming:this.touchZoom,isRotating:this.touchRotate}),Mt._lastPinchEvent=e,!0}_onPinchEnd(e){if(!this.isDragging())return!1;const{inertia:i}=this,{_lastPinchEvent:n}=Mt;if(this.touchZoom&&i&&n&&e.scale!==n.scale){const r=this.getCenter(e);let s=this.controllerState.rotateEnd();const o=Math.log2(e.scale),a=(o-Math.log2(n.scale))/(e.deltaTime-n.deltaTime),c=Math.pow(2,o+a*i/2);s=s.zoom({pos:r,scale:c}).zoomEnd(),this.updateViewport(s,{...this._getTransitionProps({around:r}),transitionDuration:i,transitionEasing:Gn},{isDragging:!1,isPanning:this.touchZoom,isZooming:this.touchZoom,isRotating:!1}),this.blockEvents(i)}else{const r=this.controllerState.zoomEnd().rotateEnd();this.updateViewport(r,null,{isDragging:!1,isPanning:!1,isZooming:!1,isRotating:!1})}return Mt._startPinchRotation=null,Mt._lastPinchEvent=null,!0}_onDoubleClick(e){if(!this.doubleClickZoom)return!1;const i=this.getCenter(e);if(!this.isPointInBounds(i,e))return!1;const n=this.isFunctionKeyPressed(e),r=this.controllerState.zoom({pos:i,scale:n?.5:2});return this.updateViewport(r,this._getTransitionProps({around:i}),{isZooming:!0,isPanning:!0}),this.blockEvents(100),!0}_onKeyDown(e){if(!this.keyboard)return!1;const i=this.isFunctionKeyPressed(e),{zoomSpeed:n,moveSpeed:r,rotateSpeedX:s,rotateSpeedY:o}=this.keyboard===!0?{}:this.keyboard,{controllerState:a}=this;let c;const l={};switch(e.srcEvent.code){case"Minus":c=i?a.zoomOut(n).zoomOut(n):a.zoomOut(n),l.isZooming=!0;break;case"Equal":c=i?a.zoomIn(n).zoomIn(n):a.zoomIn(n),l.isZooming=!0;break;case"ArrowLeft":i?(c=a.rotateLeft(s),l.isRotating=!0):(c=a.moveLeft(r),l.isPanning=!0);break;case"ArrowRight":i?(c=a.rotateRight(s),l.isRotating=!0):(c=a.moveRight(r),l.isPanning=!0);break;case"ArrowUp":i?(c=a.rotateUp(o),l.isRotating=!0):(c=a.moveUp(r),l.isPanning=!0);break;case"ArrowDown":i?(c=a.rotateDown(o),l.isRotating=!0):(c=a.moveDown(r),l.isPanning=!0);break;default:return!1}return this.updateViewport(c,this._getTransitionProps(),l),!0}_getTransitionProps(e){const{transition:i}=this;return!i||!i.transitionInterpolator?rt:e?{...i,transitionInterpolator:new Xa({...e,...i.transitionInterpolator.opts,makeViewport:this.controllerState.makeViewport})}:i}}class dd{constructor(e,i,n){this.makeViewport=n,this._viewportProps=this.applyConstraints(e),this._state=i}getViewportProps(){return this._viewportProps}getState(){return this._state}}const ef=5,QE=1.2,tf=512,pd=[[-1/0,-90],[1/0,90]];function Jn([t,e]){if(Math.abs(e)>90&&(e=Math.sign(e)*90),Number.isFinite(t)){const[n,r]=Mi([t,e]);return[n,ge(r,0,tf)]}const[,i]=Mi([0,e]);return[t,ge(i,0,tf)]}class KE extends dd{constructor(e){const{width:i,height:n,latitude:r,longitude:s,zoom:o,bearing:a=0,pitch:c=0,altitude:l=1.5,position:f=[0,0,0],maxZoom:u=20,minZoom:h=0,maxPitch:p=60,minPitch:d=0,startPanLngLat:m,startZoomLngLat:g,startRotatePos:_,startRotateLngLat:y,startBearing:A,startPitch:b,startZoom:T,normalize:w=!0}=e;pe(Number.isFinite(s)),pe(Number.isFinite(r)),pe(Number.isFinite(o));const v=e.maxBounds||(w?pd:null);super({width:i,height:n,latitude:r,longitude:s,zoom:o,bearing:a,pitch:c,altitude:l,maxZoom:u,minZoom:h,maxPitch:p,minPitch:d,normalize:w,position:f,maxBounds:v},{startPanLngLat:m,startZoomLngLat:g,startRotatePos:_,startRotateLngLat:y,startBearing:A,startPitch:b,startZoom:T},e.makeViewport),this.getAltitude=e.getAltitude}panStart({pos:e}){return this._getUpdatedState({startPanLngLat:this._unproject(e)})}pan({pos:e,startPos:i}){const n=this.getState().startPanLngLat||this._unproject(i);if(!n)return this;const s=this.makeViewport(this.getViewportProps()).panByPosition(n,e);return this._getUpdatedState(s)}panEnd(){return this._getUpdatedState({startPanLngLat:null})}rotateStart({pos:e}){const i=this.getAltitude?.(e);return this._getUpdatedState({startRotatePos:e,startRotateLngLat:i!==void 0?this._unproject3D(e,i):void 0,startBearing:this.getViewportProps().bearing,startPitch:this.getViewportProps().pitch})}rotate({pos:e,deltaAngleX:i=0,deltaAngleY:n=0}){const{startRotatePos:r,startRotateLngLat:s,startBearing:o,startPitch:a}=this.getState();if(!r||o===void 0||a===void 0)return this;let c;if(e?c=this._getNewRotation(e,r,a,o):c={bearing:o+i,pitch:a+n},s){const l=this.makeViewport({...this.getViewportProps(),...c}),f="panByPosition3D"in l?"panByPosition3D":"panByPosition";return this._getUpdatedState({...c,...l[f](s,r)})}return this._getUpdatedState(c)}rotateEnd(){return this._getUpdatedState({startRotatePos:null,startRotateLngLat:null,startBearing:null,startPitch:null})}zoomStart({pos:e}){return this._getUpdatedState({startZoomLngLat:this._unproject(e),startZoom:this.getViewportProps().zoom})}zoom({pos:e,startPos:i,scale:n}){let{startZoom:r,startZoomLngLat:s}=this.getState();if(s||(r=this.getViewportProps().zoom,s=this._unproject(i)||this._unproject(e)),!s)return this;const o=this._constrainZoom(r+Math.log2(n)),a=this.makeViewport({...this.getViewportProps(),zoom:o});return this._getUpdatedState({zoom:o,...a.panByPosition(s,e)})}zoomEnd(){return this._getUpdatedState({startZoomLngLat:null,startZoom:null})}zoomIn(e=2){return this._zoomFromCenter(e)}zoomOut(e=2){return this._zoomFromCenter(1/e)}moveLeft(e=100){return this._panFromCenter([e,0])}moveRight(e=100){return this._panFromCenter([-e,0])}moveUp(e=100){return this._panFromCenter([0,e])}moveDown(e=100){return this._panFromCenter([0,-e])}rotateLeft(e=15){return this._getUpdatedState({bearing:this.getViewportProps().bearing-e})}rotateRight(e=15){return this._getUpdatedState({bearing:this.getViewportProps().bearing+e})}rotateUp(e=10){return this._getUpdatedState({pitch:this.getViewportProps().pitch+e})}rotateDown(e=10){return this._getUpdatedState({pitch:this.getViewportProps().pitch-e})}shortestPathFrom(e){const i=e.getViewportProps(),n={...this.getViewportProps()},{bearing:r,longitude:s}=n;return Math.abs(r-i.bearing)>180&&(n.bearing=r<0?r+360:r-360),Math.abs(s-i.longitude)>180&&(n.longitude=s<0?s+360:s-360),n}applyConstraints(e){const{maxPitch:i,minPitch:n,pitch:r,longitude:s,bearing:o,normalize:a,maxBounds:c}=e;if(a&&((s<-180||s>180)&&(e.longitude=Fl(s+180,360)-180),(o<-180||o>180)&&(e.bearing=Fl(o+180,360)-180)),e.pitch=ge(r,n,i),e.zoom=this._constrainZoom(e.zoom,e),c){const l=Jn(c[0]),f=Jn(c[1]),u=2**e.zoom,h=e.width/2/u,p=e.height/2/u,[d,m]=Oi([l[0]+h,l[1]+p]),[g,_]=Oi([f[0]-h,f[1]-p]);e.longitude=ge(e.longitude,d,g),e.latitude=ge(e.latitude,m,_)}return e}_constrainZoom(e,i){i||(i=this.getViewportProps());const{maxZoom:n,maxBounds:r}=i,s=r!==null&&i.width>0&&i.height>0;let{minZoom:o}=i;if(s){const a=Jn(r[0]),c=Jn(r[1]),l=c[0]-a[0],f=c[1]-a[1];Number.isFinite(l)&&l>0&&(o=Math.max(o,Math.log2(i.width/l))),Number.isFinite(f)&&f>0&&(o=Math.max(o,Math.log2(i.height/f))),o>n&&(o=n)}return ge(e,o,n)}_zoomFromCenter(e){const{width:i,height:n}=this.getViewportProps();return this.zoom({pos:[i/2,n/2],scale:e})}_panFromCenter(e){const{width:i,height:n}=this.getViewportProps();return this.pan({startPos:[i/2,n/2],pos:[i/2+e[0],n/2+e[1]]})}_getUpdatedState(e){return new this.constructor({makeViewport:this.makeViewport,...this.getViewportProps(),...this.getState(),...e})}_unproject(e){const i=this.makeViewport(this.getViewportProps());return e&&i.unproject(e)}_unproject3D(e,i){return this.makeViewport(this.getViewportProps()).unproject(e,{targetZ:i})}_getNewRotation(e,i,n,r){const s=e[0]-i[0],o=e[1]-i[1],a=e[1],c=i[1],{width:l,height:f}=this.getViewportProps(),u=s/l;let h=0;o>0?Math.abs(f-c)>ef&&(h=o/(c-f)*QE):o<0&&c>ef&&(h=1-a/c),h=ge(h,-1,1);const{minPitch:p,maxPitch:d}=this.getViewportProps(),m=r+180*u;let g=n;return h>0?g=n+h*(d-n):h<0&&(g=n-h*(p-n)),{pitch:g,bearing:m}}}class qE extends hd{constructor(){super(...arguments),this.ControllerState=KE,this.transition={transitionDuration:300,transitionInterpolator:new Xa({transitionProps:{compare:["longitude","latitude","zoom","bearing","pitch","position"],required:["longitude","latitude","zoom"]}})},this.dragMode="pan",this.rotationPivot="center",this._getAltitude=e=>{if(this.rotationPivot==="2d")return 0;if(this.rotationPivot==="3d"&&this.pickPosition){const{x:i,y:n}=this.props,r=this.pickPosition(i+e[0],n+e[1]);if(r&&r.coordinate&&r.coordinate.length>=3)return r.coordinate[2]}}}setProps(e){"rotationPivot"in e&&(this.rotationPivot=e.rotationPivot||"center"),e.getAltitude=this._getAltitude,e.position=e.position||[0,0,0],e.maxBounds=e.maxBounds||(e.normalize===!1?null:pd),super.setProps(e)}updateViewport(e,i=null,n={}){const r=e.getState();n.isDragging&&r.startRotateLngLat?n={...n,rotationPivotPosition:r.startRotateLngLat}:n.isDragging===!1&&(n={...n,rotationPivotPosition:void 0}),super.updateViewport(e,i,n)}}class gd extends fd{constructor(e={}){super(e)}getViewportType(){return Bi}get ControllerType(){return qE}}gd.displayName="MapView";const ZE=new Gh;function GE(t,e){const i=t.order??1/0,n=e.order??1/0;return i-n}class JE{constructor(e){this._resolvedEffects=[],this._defaultEffects=[],this.effects=[],this._context=e,this._needsRedraw="Initial render",this._setEffects([])}addDefaultEffect(e){const i=this._defaultEffects;if(!i.find(n=>n.id===e.id)){const n=i.findIndex(r=>GE(r,e)>0);n<0?i.push(e):i.splice(n,0,e),e.setup(this._context),this._setEffects(this.effects)}}setProps(e){"effects"in e&&(Me(e.effects,this.effects,1)||this._setEffects(e.effects))}needsRedraw(e={clearRedrawFlags:!1}){const i=this._needsRedraw;return e.clearRedrawFlags&&(this._needsRedraw=!1),i}getEffects(){return this._resolvedEffects}_setEffects(e){const i={};for(const r of this.effects)i[r.id]=r;const n=[];for(const r of e){const s=i[r.id];let o=r;s&&s!==r?s.setProps?(s.setProps(r.props),o=s):s.cleanup(this._context):s||r.setup(this._context),n.push(o),delete i[r.id]}for(const r in i)i[r].cleanup(this._context);this.effects=n,this._resolvedEffects=n.concat(this._defaultEffects),e.some(r=>r instanceof Gh)||this._resolvedEffects.push(ZE),this._needsRedraw="effects changed"}finalize(){for(const e of this._resolvedEffects)e.cleanup(this._context);this.effects.length=0,this._resolvedEffects.length=0,this._defaultEffects.length=0}}class $E extends ja{shouldDrawLayer(e){const{operation:i}=e.props;return i.includes("draw")||i.includes("terrain")}render(e){return this._render(e)}}const e1="deckRenderer.renderLayers";class t1{constructor(e,i={}){this.device=e,this.stats=i.stats,this.layerFilter=null,this.drawPickingColors=!1,this.drawLayersPass=new $E(e),this.pickLayersPass=new ad(e),this.renderCount=0,this._needsRedraw="Initial render",this.renderBuffers=[],this.lastPostProcessEffect=null}setProps(e){this.layerFilter!==e.layerFilter&&(this.layerFilter=e.layerFilter,this._needsRedraw="layerFilter changed"),this.drawPickingColors!==e.drawPickingColors&&(this.drawPickingColors=e.drawPickingColors,this._needsRedraw="drawPickingColors changed")}renderLayers(e){if(!e.viewports.length)return;const i=this.drawPickingColors?this.pickLayersPass:this.drawLayersPass,n={layerFilter:this.layerFilter,isPicking:this.drawPickingColors,...e};n.effects&&this._preRender(n.effects,n);const r=this.lastPostProcessEffect?this.renderBuffers[0]:n.target;this.lastPostProcessEffect&&(n.clearColor=[0,0,0,0],n.clearCanvas=!0);const s=i.render({...n,target:r}),o="stats"in s?s.stats:s;n.effects&&(this.lastPostProcessEffect&&(n.clearCanvas=e.clearCanvas===void 0?!0:e.clearCanvas),this._postRender(n.effects,n)),this.renderCount++,be(e1,this,o,e),this._updateStats(o)}needsRedraw(e={clearRedrawFlags:!1}){const i=this._needsRedraw;return e.clearRedrawFlags&&(this._needsRedraw=!1),i}finalize(){const{renderBuffers:e}=this;for(const i of e)i.delete();e.length=0}_updateStats(e){if(!this.stats)return;let i=0;for(const{visibleCount:n}of e)i+=n;this.stats.get("Layers rendered").addCount(i)}_preRender(e,i){this.lastPostProcessEffect=null,i.preRenderStats=i.preRenderStats||{};for(const n of e)i.preRenderStats[n.id]=n.preRender(i),n.postRender&&(this.lastPostProcessEffect=n.id);this.lastPostProcessEffect&&this._resizeRenderBuffers()}_resizeRenderBuffers(){const{renderBuffers:e}=this,i=this.device.canvasContext.getDrawingBufferSize(),[n,r]=i;e.length===0&&[0,1].map(s=>{const o=this.device.createTexture({sampler:{minFilter:"linear",magFilter:"linear"},width:n,height:r});e.push(this.device.createFramebuffer({id:`deck-renderbuffer-${s}`,colorAttachments:[o]}))});for(const s of e)s.resize(i)}_postRender(e,i){const{renderBuffers:n}=this,r={...i,inputBuffer:n[0],swapBuffer:n[1]};for(const s of e)if(s.postRender){r.target=s.id===this.lastPostProcessEffect?i.target:void 0;const o=s.postRender(r);r.inputBuffer=o,r.swapBuffer=o===n[0]?n[1]:n[0]}}}const i1={pickedColor:null,pickedObjectIndex:-1};function nf({pickedColors:t,decodePickingColor:e,deviceX:i,deviceY:n,deviceRadius:r,deviceRect:s}){const{x:o,y:a,width:c,height:l}=s;let f=r*r,u=-1,h=0;for(let p=0;pf)h+=4*c;else for(let g=0;g=0){const y=g+o-i,A=y*y+m;A<=f&&(f=A,u=h)}h+=4}}if(u>=0){const p=t.slice(u,u+4),d=e(p);if(d){const m=Math.floor(u/4/c),g=u/4-m*c;return{...d,pickedColor:p,pickedX:o+g,pickedY:a+m}}J.error("Picked non-existent layer. Is picking buffer corrupt?")()}return i1}function rf({pickedColors:t,decodePickingColor:e}){const i=new Map;if(t){for(let n=0;n=0){const s=t.slice(n,n+4),o=s.join(",");if(!i.has(o)){const a=e(s);a?i.set(o,{...a,color:s}):J.error("Picked non-existent layer. Is picking buffer corrupt?")()}}}return Array.from(i.values())}function Wo({pickInfo:t,viewports:e,pixelRatio:i,x:n,y:r,z:s}){let o=e[0];e.length>1&&(o=n1(t?.pickedViewports||e,{x:n,y:r}));let a;if(o){const c=[n-o.x,r-o.y];s!==void 0&&(c[2]=s),a=o.unproject(c)}return{color:null,layer:null,viewport:o,index:-1,picked:!1,x:n,y:r,pixel:[n,r],coordinate:a,devicePixel:t&&"pickedX"in t?[t.pickedX,t.pickedY]:void 0,pixelRatio:i}}function sf(t){const{pickInfo:e,lastPickedInfo:i,mode:n,layers:r}=t,{pickedColor:s,pickedLayer:o,pickedObjectIndex:a}=e,c=o?[o]:[];if(n==="hover"){const u=i.index,h=i.layerId,p=o?o.props.id:null;if(p!==h||a!==u){if(p!==h){const d=r.find(m=>m.props.id===h);d&&c.unshift(d)}i.layerId=p,i.index=a,i.info=null}}const l=Wo(t),f=new Map;return f.set(null,l),c.forEach(u=>{let h={...l};u===o&&(h.color=s,h.index=a,h.picked=!0),h=Vo({layer:u,info:h,mode:n});const p=h.layer;u===o&&n==="hover"&&(i.info=h),f.set(p.id,h),n==="hover"&&p.updateAutoHighlight(h)}),f}function Vo({layer:t,info:e,mode:i}){for(;t&&e;){const n=e.layer||null;e.sourceLayer=n,e.layer=t,e=t.getPickingInfo({info:e,mode:i,sourceLayer:n}),t=t.parent}return e}function n1(t,e){for(let i=t.length-1;i>=0;i--){const n=t[i];if(n.containsPixel(e))return n}return t[0]}class r1{constructor(e,i={}){this._pickable=!0,this.device=e,this.stats=i.stats,this.pickLayersPass=new ad(e),this.lastPickedInfo={index:-1,layerId:null,info:null}}setProps(e){"layerFilter"in e&&(this.layerFilter=e.layerFilter),"_pickable"in e&&(this._pickable=e._pickable)}finalize(){this.pickingFBO&&this.pickingFBO.destroy(),this.depthFBO&&this.depthFBO.destroy()}pickObjectAsync(e){return this._pickClosestObjectAsync(e)}pickObjectsAsync(e){return this._pickVisibleObjectsAsync(e)}pickObject(e){return this._pickClosestObject(e)}pickObjects(e){return this._pickVisibleObjects(e)}getLastPickedObject({x:e,y:i,layers:n,viewports:r},s=this.lastPickedInfo.info){const o=s&&s.layer&&s.layer.id,a=s&&s.viewport&&s.viewport.id,c=o?n.find(h=>h.id===o):null,l=a&&r.find(h=>h.id===a)||r[0],f=l&&l.unproject([e-l.x,i-l.y]);return{...s,...{x:e,y:i,viewport:l,coordinate:f,layer:c}}}_resizeBuffer(){if(!this.pickingFBO){const i=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:Y.RENDER_ATTACHMENT|Y.COPY_SRC});if(this.pickingFBO=this.device.createFramebuffer({colorAttachments:[i],depthStencilAttachment:"depth16unorm"}),this.device.isTextureFormatRenderable("rgba32float")){const n=this.device.createTexture({format:"rgba32float",width:1,height:1,usage:Y.RENDER_ATTACHMENT|Y.COPY_SRC}),r=this.device.createFramebuffer({colorAttachments:[n],depthStencilAttachment:"depth16unorm"});this.depthFBO=r}}const{canvas:e}=this.device.getDefaultCanvasContext();this.pickingFBO?.resize({width:e.width,height:e.height}),this.depthFBO?.resize({width:e.width,height:e.height})}_getPickable(e){if(this._pickable===!1)return null;const i=e.filter(n=>this.pickLayersPass.shouldDrawLayer(n)&&!n.isComposite);return i.length?i:null}async _pickClosestObjectAsync({layers:e,views:i,viewports:n,x:r,y:s,radius:o=0,depth:a=1,mode:c="query",unproject3D:l,onViewportActive:f,effects:u}){const h=this.device.canvasContext.cssToDeviceRatio(),p=this._getPickable(e);if(!p||n.length===0)return{result:[],emptyInfo:Wo({viewports:n,x:r,y:s,pixelRatio:h})};this._resizeBuffer();const d=this.device.canvasContext.cssToDevicePixels([r,s],!0),m=[d.x+Math.floor(d.width/2),d.y+Math.floor(d.height/2)],g=Math.round(o*h),{width:_,height:y}=this.pickingFBO,A=this._getPickingRect({deviceX:m[0],deviceY:m[1],deviceRadius:g,deviceWidth:_,deviceHeight:y}),b={x:r-o,y:s-o,width:o*2+1,height:o*2+1};let T;const w=[],v=new Set;for(let M=0;M0){const{pickedColors:I}=await this._drawAndSampleAsync({layers:O,views:i,viewports:n,onViewportActive:f,deviceRect:{x:x.pickedX??m[0],y:x.pickedY??m[1],width:1,height:1},cullRect:b,effects:u,pass:`picking:${c}:z`},!0);I[3]&&(P=I[0])}x.pickedLayer&&M+10){const{pickedColors:I}=this._drawAndSample({layers:O,views:i,viewports:n,onViewportActive:f,deviceRect:{x:x.pickedX??m[0],y:x.pickedY??m[1],width:1,height:1},cullRect:b,effects:u,pass:`picking:${c}:z`},!0);I[3]&&(P=I[0])}x.pickedLayer&&M+1=l);P++){const O=w[P];let I={color:O.pickedColor,layer:null,index:O.pickedObjectIndex,picked:!0,x:r,y:s,pixelRatio:p};I=Vo({layer:O.pickedLayer,info:I,mode:c});const k=I.layer.id;v.has(k)||v.set(k,new Set);const B=v.get(k),D=I.object??I.index;B.has(D)||(B.add(D),M.push(I))}return M}_pickVisibleObjects({layers:e,views:i,viewports:n,x:r,y:s,width:o=1,height:a=1,mode:c="query",maxObjects:l=null,onViewportActive:f,effects:u}){const h=this._getPickable(e);if(!h||n.length===0)return[];this._resizeBuffer();const p=this.device.canvasContext.cssToDeviceRatio(),d=this.device.canvasContext.cssToDevicePixels([r,s],!0),m=d.x,g=d.y+d.height,_=this.device.canvasContext.cssToDevicePixels([r+o,s+a],!0),y=_.x+_.width,A=_.y,b={x:m,y:A,width:y-m,height:g-A},T=this._drawAndSample({layers:h,views:i,viewports:n,onViewportActive:f,deviceRect:b,cullRect:{x:r,y:s,width:o,height:a},effects:u,pass:`picking:${c}`}),w=rf(T),v=new Map,M=[],x=Number.isFinite(l);for(let P=0;P=l);P++){const O=w[P];let I={color:O.pickedColor,layer:null,index:O.pickedObjectIndex,picked:!0,x:r,y:s,pixelRatio:p};I=Vo({layer:O.pickedLayer,info:I,mode:c});const k=I.layer.id;v.has(k)||v.set(k,new Set);const B=v.get(k),D=I.object??I.index;B.has(D)||(B.add(D),M.push(I))}return M}async _drawAndSampleAsync({layers:e,views:i,viewports:n,onViewportActive:r,deviceRect:s,cullRect:o,effects:a,pass:c},l=!1){const f=l?this.depthFBO:this.pickingFBO,u={layers:e,layerFilter:this.layerFilter,views:i,viewports:n,onViewportActive:r,pickingFBO:f,deviceRect:s,cullRect:o,effects:a,pass:c,pickZ:l,preRenderStats:{},isPicking:!0};for(const b of a)b.useInPicking&&(u.preRenderStats[b.id]=b.preRender(u));const{decodePickingColor:h,stats:p}=this.pickLayersPass.render(u);this._updateStats(p);const{x:d,y:m,width:g,height:_}=s,y=f.colorAttachments[0]?.texture;if(!y)throw new Error("Picking framebuffer color attachment is missing");const A=await this._readTextureDataAsync(y,{x:d,y:m,width:g,height:_},l?Float32Array:Uint8Array);if(!l){let b=!1;for(let T=3;T0&&J.warn("Async pick readback returned only zero alpha values",{deviceRect:s,bytes:Array.from(A.subarray(0,Math.min(A.length,16)))})()}return{pickedColors:A,decodePickingColor:h}}async _readTextureDataAsync(e,i,n){const{width:r,height:s}=i,o=e.computeMemoryLayout(i),a=this.device.createBuffer({byteLength:o.byteLength,usage:q.COPY_DST|q.MAP_READ});try{e.readBuffer(i,a);const c=await a.readAsync(0,o.byteLength),l=n.BYTES_PER_ELEMENT;if(o.bytesPerRow%l!==0)throw new Error(`Texture readback row stride ${o.bytesPerRow} is not aligned to ${l}-byte elements.`);const f=new n(c.buffer,c.byteOffset,o.byteLength/l),u=r*4,h=o.bytesPerRow/l;if(ho.props.operation.includes("terrain"))}_getPickingRect({deviceX:e,deviceY:i,deviceRadius:n,deviceWidth:r,deviceHeight:s}){const o=Math.max(0,e-n),a=Math.max(0,i-n),c=Math.min(r,e+n+1)-o,l=Math.min(s,i+n+1)-a;return c<=0||l<=0?null:{x:o,y:a,width:c,height:l}}}const s1={"top-left":{top:0,left:0},"top-right":{top:0,right:0},"bottom-left":{bottom:0,left:0},"bottom-right":{bottom:0,right:0},fill:{top:0,left:0,bottom:0,right:0}},o1="top-left",of="root";class a1{constructor({deck:e,parentElement:i}){this.defaultWidgets=[],this.widgets=[],this.resolvedWidgets=[],this.containers={},this.lastViewports={},this.deck=e,i?.classList.add("deck-widget-container"),this.parentElement=i}getWidgets(){return this.resolvedWidgets}setProps(e){if(e.widgets&&!Me(e.widgets,this.widgets,1)){const i=e.widgets.filter(Boolean);this._setWidgets(i)}}finalize(){for(const e of this.getWidgets())this._removeWidget(e);this.defaultWidgets.length=0,this.resolvedWidgets.length=0;for(const e in this.containers)this.containers[e].remove()}addDefault(e){this.defaultWidgets.find(i=>i.id===e.id)||(this._addWidget(e),this.defaultWidgets.push(e),this._setWidgets(this.widgets))}onRedraw({viewports:e,layers:i}){const n=e.reduce((r,s)=>(r[s.id]=s,r),{});for(const r of this.getWidgets()){const{viewId:s}=r;if(s){const o=n[s];o&&(r.onViewportChange&&r.onViewportChange(o),r.onRedraw?.({viewports:[o],layers:i}))}else{if(r.onViewportChange)for(const o of e)r.onViewportChange(o);r.onRedraw?.({viewports:e,layers:i})}}this.lastViewports=n,this._updateContainers()}onHover(e,i){for(const n of this.getWidgets()){const{viewId:r}=n;(!r||r===e.viewport?.id)&&n.onHover?.(e,i)}}onEvent(e,i){const n=mr[i.type];if(n)for(const r of this.getWidgets()){const{viewId:s}=r;(!s||s===e.viewport?.id)&&r[n]?.(e,i)}}_setWidgets(e){const i={};for(const n of this.resolvedWidgets)i[n.id]=n;this.resolvedWidgets.length=0;for(const n of this.defaultWidgets)i[n.id]=null,this.resolvedWidgets.push(n);for(let n of e){const r=i[n.id];r?r.viewId!==n.viewId||r.placement!==n.placement?(this._removeWidget(r),this._addWidget(n)):n!==r&&(r.setProps(n.props),n=r):this._addWidget(n),i[n.id]=null,this.resolvedWidgets.push(n)}for(const n in i){const r=i[n];r&&this._removeWidget(r)}this.widgets=e}_addWidget(e){const{viewId:i=null,placement:n=o1}=e,r=e.props._container??i;e.widgetManager=this,e.deck=this.deck,e.rootElement=e._onAdd({deck:this.deck,viewId:i}),e.rootElement&&this._getContainer(r,n).append(e.rootElement),e.updateHTML()}_removeWidget(e){e.onRemove?.(),e.rootElement&&e.rootElement.remove(),e.rootElement=void 0,e.deck=void 0,e.widgetManager=void 0}_getContainer(e,i){if(e&&typeof e!="string")return e;const n=e||of;let r=this.containers[n];r||(r=document.createElement("div"),r.style.pointerEvents="none",r.style.position="absolute",r.style.overflow="hidden",this.parentElement?.append(r),this.containers[n]=r);let s=r.querySelector(`.${i}`);return s||(s=globalThis.document.createElement("div"),s.className=i,s.style.position="absolute",s.style.zIndex="2",Object.assign(s.style,s1[i]),r.append(s)),s}_updateContainers(){const e=this.deck.width,i=this.deck.height;for(const n in this.containers){const r=this.lastViewports[n]||null,s=n===of||r,o=this.containers[n];s?(o.style.display="block",o.style.left=`${r?r.x:0}px`,o.style.top=`${r?r.y:0}px`,o.style.width=`${r?r.width:e}px`,o.style.height=`${r?r.height:i}px`):o.style.display="none"}}}function af(t,e){e&&Object.entries(e).map(([i,n])=>{i.startsWith("--")?t.style.setProperty(i,n):t.style[i]=n})}function c1(t,e){e&&Object.keys(e).map(i=>{i.startsWith("--")?t.style.removeProperty(i):t.style[i]=""})}class Qa{constructor(e){this.viewId=null,this.props={...this.constructor.defaultProps,...e},this.id=this.props.id}setProps(e){const i=this.props,n=this.rootElement;n&&i.className!==e.className&&(i.className&&n.classList.remove(i.className),e.className&&n.classList.add(e.className)),n&&!Me(i.style,e.style,1)&&(c1(n,i.style),af(n,e.style)),Object.assign(this.props,e),this.updateHTML()}updateHTML(){this.rootElement&&this.onRenderHTML(this.rootElement)}get viewIds(){return this.viewId?[this.viewId]:this.deck?.getViews().map(e=>e.id)??[]}getViewState(e){return this.deck?.viewManager?.getViewState(e)||{}}setViewState(e,i){this.deck?._onViewStateChange({viewId:e,viewState:i,interactionState:{}})}onCreateRootElement(){const e=["deck-widget",this.className,this.props.className],i=document.createElement("div");return e.filter(n=>typeof n=="string"&&n.length>0).forEach(n=>i.classList.add(n)),af(i,this.props.style),i}_onAdd(e){return this.onAdd(e)??this.onCreateRootElement()}onAdd(e){}onRemove(){}onViewportChange(e){}onRedraw(e){}onHover(e,i){}onClick(e,i){}onDrag(e,i){}onDragStart(e,i){}onDragEnd(e,i){}}Qa.defaultProps={id:"widget",style:{},_container:null,className:""};const l1={zIndex:"1",position:"absolute",pointerEvents:"none",color:"#a0a7b4",backgroundColor:"#29323c",padding:"10px",top:"0",left:"0",display:"none"};class md extends Qa{constructor(e={}){super(e),this.id="default-tooltip",this.placement="fill",this.className="deck-tooltip",this.isVisible=!1,this.setProps(e)}onCreateRootElement(){const e=document.createElement("div");return e.className=this.className,Object.assign(e.style,l1),e}onRenderHTML(e){}onViewportChange(e){this.isVisible&&e.id===this.lastViewport?.id&&!e.equals(this.lastViewport)&&this.setTooltip(null),this.lastViewport=e}onHover(e){const{deck:i}=this,n=i&&i.props.getTooltip;if(!n)return;const r=n(e);this.setTooltip(r,e.x,e.y)}setTooltip(e,i,n){const r=this.rootElement;if(r){if(typeof e=="string")r.innerText=e;else if(e)e.text&&(r.innerText=e.text),e.html&&(r.innerHTML=e.html),e.className&&(r.className=e.className);else{this.isVisible=!1,r.style.display="none";return}this.isVisible=!0,r.style.display="block",r.style.transform=`translate(${i}px, ${n}px)`,e&&typeof e=="object"&&"style"in e&&Object.assign(r.style,e.style)}}}md.defaultProps={...Qa.defaultProps};var Ai;(function(t){t[t.DEPTH_BUFFER_BIT=256]="DEPTH_BUFFER_BIT",t[t.STENCIL_BUFFER_BIT=1024]="STENCIL_BUFFER_BIT",t[t.COLOR_BUFFER_BIT=16384]="COLOR_BUFFER_BIT",t[t.POINTS=0]="POINTS",t[t.LINES=1]="LINES",t[t.LINE_LOOP=2]="LINE_LOOP",t[t.LINE_STRIP=3]="LINE_STRIP",t[t.TRIANGLES=4]="TRIANGLES",t[t.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",t[t.TRIANGLE_FAN=6]="TRIANGLE_FAN",t[t.ZERO=0]="ZERO",t[t.ONE=1]="ONE",t[t.SRC_COLOR=768]="SRC_COLOR",t[t.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",t[t.SRC_ALPHA=770]="SRC_ALPHA",t[t.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",t[t.DST_ALPHA=772]="DST_ALPHA",t[t.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",t[t.DST_COLOR=774]="DST_COLOR",t[t.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",t[t.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE",t[t.CONSTANT_COLOR=32769]="CONSTANT_COLOR",t[t.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",t[t.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",t[t.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",t[t.FUNC_ADD=32774]="FUNC_ADD",t[t.FUNC_SUBTRACT=32778]="FUNC_SUBTRACT",t[t.FUNC_REVERSE_SUBTRACT=32779]="FUNC_REVERSE_SUBTRACT",t[t.BLEND_EQUATION=32777]="BLEND_EQUATION",t[t.BLEND_EQUATION_RGB=32777]="BLEND_EQUATION_RGB",t[t.BLEND_EQUATION_ALPHA=34877]="BLEND_EQUATION_ALPHA",t[t.BLEND_DST_RGB=32968]="BLEND_DST_RGB",t[t.BLEND_SRC_RGB=32969]="BLEND_SRC_RGB",t[t.BLEND_DST_ALPHA=32970]="BLEND_DST_ALPHA",t[t.BLEND_SRC_ALPHA=32971]="BLEND_SRC_ALPHA",t[t.BLEND_COLOR=32773]="BLEND_COLOR",t[t.ARRAY_BUFFER_BINDING=34964]="ARRAY_BUFFER_BINDING",t[t.ELEMENT_ARRAY_BUFFER_BINDING=34965]="ELEMENT_ARRAY_BUFFER_BINDING",t[t.LINE_WIDTH=2849]="LINE_WIDTH",t[t.ALIASED_POINT_SIZE_RANGE=33901]="ALIASED_POINT_SIZE_RANGE",t[t.ALIASED_LINE_WIDTH_RANGE=33902]="ALIASED_LINE_WIDTH_RANGE",t[t.CULL_FACE_MODE=2885]="CULL_FACE_MODE",t[t.FRONT_FACE=2886]="FRONT_FACE",t[t.DEPTH_RANGE=2928]="DEPTH_RANGE",t[t.DEPTH_WRITEMASK=2930]="DEPTH_WRITEMASK",t[t.DEPTH_CLEAR_VALUE=2931]="DEPTH_CLEAR_VALUE",t[t.DEPTH_FUNC=2932]="DEPTH_FUNC",t[t.STENCIL_CLEAR_VALUE=2961]="STENCIL_CLEAR_VALUE",t[t.STENCIL_FUNC=2962]="STENCIL_FUNC",t[t.STENCIL_FAIL=2964]="STENCIL_FAIL",t[t.STENCIL_PASS_DEPTH_FAIL=2965]="STENCIL_PASS_DEPTH_FAIL",t[t.STENCIL_PASS_DEPTH_PASS=2966]="STENCIL_PASS_DEPTH_PASS",t[t.STENCIL_REF=2967]="STENCIL_REF",t[t.STENCIL_VALUE_MASK=2963]="STENCIL_VALUE_MASK",t[t.STENCIL_WRITEMASK=2968]="STENCIL_WRITEMASK",t[t.STENCIL_BACK_FUNC=34816]="STENCIL_BACK_FUNC",t[t.STENCIL_BACK_FAIL=34817]="STENCIL_BACK_FAIL",t[t.STENCIL_BACK_PASS_DEPTH_FAIL=34818]="STENCIL_BACK_PASS_DEPTH_FAIL",t[t.STENCIL_BACK_PASS_DEPTH_PASS=34819]="STENCIL_BACK_PASS_DEPTH_PASS",t[t.STENCIL_BACK_REF=36003]="STENCIL_BACK_REF",t[t.STENCIL_BACK_VALUE_MASK=36004]="STENCIL_BACK_VALUE_MASK",t[t.STENCIL_BACK_WRITEMASK=36005]="STENCIL_BACK_WRITEMASK",t[t.VIEWPORT=2978]="VIEWPORT",t[t.SCISSOR_BOX=3088]="SCISSOR_BOX",t[t.COLOR_CLEAR_VALUE=3106]="COLOR_CLEAR_VALUE",t[t.COLOR_WRITEMASK=3107]="COLOR_WRITEMASK",t[t.UNPACK_ALIGNMENT=3317]="UNPACK_ALIGNMENT",t[t.PACK_ALIGNMENT=3333]="PACK_ALIGNMENT",t[t.MAX_TEXTURE_SIZE=3379]="MAX_TEXTURE_SIZE",t[t.MAX_VIEWPORT_DIMS=3386]="MAX_VIEWPORT_DIMS",t[t.SUBPIXEL_BITS=3408]="SUBPIXEL_BITS",t[t.RED_BITS=3410]="RED_BITS",t[t.GREEN_BITS=3411]="GREEN_BITS",t[t.BLUE_BITS=3412]="BLUE_BITS",t[t.ALPHA_BITS=3413]="ALPHA_BITS",t[t.DEPTH_BITS=3414]="DEPTH_BITS",t[t.STENCIL_BITS=3415]="STENCIL_BITS",t[t.POLYGON_OFFSET_UNITS=10752]="POLYGON_OFFSET_UNITS",t[t.POLYGON_OFFSET_FACTOR=32824]="POLYGON_OFFSET_FACTOR",t[t.TEXTURE_BINDING_2D=32873]="TEXTURE_BINDING_2D",t[t.SAMPLE_BUFFERS=32936]="SAMPLE_BUFFERS",t[t.SAMPLES=32937]="SAMPLES",t[t.SAMPLE_COVERAGE_VALUE=32938]="SAMPLE_COVERAGE_VALUE",t[t.SAMPLE_COVERAGE_INVERT=32939]="SAMPLE_COVERAGE_INVERT",t[t.COMPRESSED_TEXTURE_FORMATS=34467]="COMPRESSED_TEXTURE_FORMATS",t[t.VENDOR=7936]="VENDOR",t[t.RENDERER=7937]="RENDERER",t[t.VERSION=7938]="VERSION",t[t.IMPLEMENTATION_COLOR_READ_TYPE=35738]="IMPLEMENTATION_COLOR_READ_TYPE",t[t.IMPLEMENTATION_COLOR_READ_FORMAT=35739]="IMPLEMENTATION_COLOR_READ_FORMAT",t[t.BROWSER_DEFAULT_WEBGL=37444]="BROWSER_DEFAULT_WEBGL",t[t.STATIC_DRAW=35044]="STATIC_DRAW",t[t.STREAM_DRAW=35040]="STREAM_DRAW",t[t.DYNAMIC_DRAW=35048]="DYNAMIC_DRAW",t[t.ARRAY_BUFFER=34962]="ARRAY_BUFFER",t[t.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",t[t.BUFFER_SIZE=34660]="BUFFER_SIZE",t[t.BUFFER_USAGE=34661]="BUFFER_USAGE",t[t.CURRENT_VERTEX_ATTRIB=34342]="CURRENT_VERTEX_ATTRIB",t[t.VERTEX_ATTRIB_ARRAY_ENABLED=34338]="VERTEX_ATTRIB_ARRAY_ENABLED",t[t.VERTEX_ATTRIB_ARRAY_SIZE=34339]="VERTEX_ATTRIB_ARRAY_SIZE",t[t.VERTEX_ATTRIB_ARRAY_STRIDE=34340]="VERTEX_ATTRIB_ARRAY_STRIDE",t[t.VERTEX_ATTRIB_ARRAY_TYPE=34341]="VERTEX_ATTRIB_ARRAY_TYPE",t[t.VERTEX_ATTRIB_ARRAY_NORMALIZED=34922]="VERTEX_ATTRIB_ARRAY_NORMALIZED",t[t.VERTEX_ATTRIB_ARRAY_POINTER=34373]="VERTEX_ATTRIB_ARRAY_POINTER",t[t.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING=34975]="VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",t[t.CULL_FACE=2884]="CULL_FACE",t[t.FRONT=1028]="FRONT",t[t.BACK=1029]="BACK",t[t.FRONT_AND_BACK=1032]="FRONT_AND_BACK",t[t.BLEND=3042]="BLEND",t[t.DEPTH_TEST=2929]="DEPTH_TEST",t[t.DITHER=3024]="DITHER",t[t.POLYGON_OFFSET_FILL=32823]="POLYGON_OFFSET_FILL",t[t.SAMPLE_ALPHA_TO_COVERAGE=32926]="SAMPLE_ALPHA_TO_COVERAGE",t[t.SAMPLE_COVERAGE=32928]="SAMPLE_COVERAGE",t[t.SCISSOR_TEST=3089]="SCISSOR_TEST",t[t.STENCIL_TEST=2960]="STENCIL_TEST",t[t.NO_ERROR=0]="NO_ERROR",t[t.INVALID_ENUM=1280]="INVALID_ENUM",t[t.INVALID_VALUE=1281]="INVALID_VALUE",t[t.INVALID_OPERATION=1282]="INVALID_OPERATION",t[t.OUT_OF_MEMORY=1285]="OUT_OF_MEMORY",t[t.CONTEXT_LOST_WEBGL=37442]="CONTEXT_LOST_WEBGL",t[t.CW=2304]="CW",t[t.CCW=2305]="CCW",t[t.DONT_CARE=4352]="DONT_CARE",t[t.FASTEST=4353]="FASTEST",t[t.NICEST=4354]="NICEST",t[t.GENERATE_MIPMAP_HINT=33170]="GENERATE_MIPMAP_HINT",t[t.BYTE=5120]="BYTE",t[t.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",t[t.SHORT=5122]="SHORT",t[t.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",t[t.INT=5124]="INT",t[t.UNSIGNED_INT=5125]="UNSIGNED_INT",t[t.FLOAT=5126]="FLOAT",t[t.DOUBLE=5130]="DOUBLE",t[t.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",t[t.ALPHA=6406]="ALPHA",t[t.RGB=6407]="RGB",t[t.RGBA=6408]="RGBA",t[t.LUMINANCE=6409]="LUMINANCE",t[t.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",t[t.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",t[t.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",t[t.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",t[t.FRAGMENT_SHADER=35632]="FRAGMENT_SHADER",t[t.VERTEX_SHADER=35633]="VERTEX_SHADER",t[t.COMPILE_STATUS=35713]="COMPILE_STATUS",t[t.DELETE_STATUS=35712]="DELETE_STATUS",t[t.LINK_STATUS=35714]="LINK_STATUS",t[t.VALIDATE_STATUS=35715]="VALIDATE_STATUS",t[t.ATTACHED_SHADERS=35717]="ATTACHED_SHADERS",t[t.ACTIVE_ATTRIBUTES=35721]="ACTIVE_ATTRIBUTES",t[t.ACTIVE_UNIFORMS=35718]="ACTIVE_UNIFORMS",t[t.MAX_VERTEX_ATTRIBS=34921]="MAX_VERTEX_ATTRIBS",t[t.MAX_VERTEX_UNIFORM_VECTORS=36347]="MAX_VERTEX_UNIFORM_VECTORS",t[t.MAX_VARYING_VECTORS=36348]="MAX_VARYING_VECTORS",t[t.MAX_COMBINED_TEXTURE_IMAGE_UNITS=35661]="MAX_COMBINED_TEXTURE_IMAGE_UNITS",t[t.MAX_VERTEX_TEXTURE_IMAGE_UNITS=35660]="MAX_VERTEX_TEXTURE_IMAGE_UNITS",t[t.MAX_TEXTURE_IMAGE_UNITS=34930]="MAX_TEXTURE_IMAGE_UNITS",t[t.MAX_FRAGMENT_UNIFORM_VECTORS=36349]="MAX_FRAGMENT_UNIFORM_VECTORS",t[t.SHADER_TYPE=35663]="SHADER_TYPE",t[t.SHADING_LANGUAGE_VERSION=35724]="SHADING_LANGUAGE_VERSION",t[t.CURRENT_PROGRAM=35725]="CURRENT_PROGRAM",t[t.NEVER=512]="NEVER",t[t.LESS=513]="LESS",t[t.EQUAL=514]="EQUAL",t[t.LEQUAL=515]="LEQUAL",t[t.GREATER=516]="GREATER",t[t.NOTEQUAL=517]="NOTEQUAL",t[t.GEQUAL=518]="GEQUAL",t[t.ALWAYS=519]="ALWAYS",t[t.KEEP=7680]="KEEP",t[t.REPLACE=7681]="REPLACE",t[t.INCR=7682]="INCR",t[t.DECR=7683]="DECR",t[t.INVERT=5386]="INVERT",t[t.INCR_WRAP=34055]="INCR_WRAP",t[t.DECR_WRAP=34056]="DECR_WRAP",t[t.NEAREST=9728]="NEAREST",t[t.LINEAR=9729]="LINEAR",t[t.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",t[t.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",t[t.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",t[t.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR",t[t.TEXTURE_MAG_FILTER=10240]="TEXTURE_MAG_FILTER",t[t.TEXTURE_MIN_FILTER=10241]="TEXTURE_MIN_FILTER",t[t.TEXTURE_WRAP_S=10242]="TEXTURE_WRAP_S",t[t.TEXTURE_WRAP_T=10243]="TEXTURE_WRAP_T",t[t.TEXTURE_2D=3553]="TEXTURE_2D",t[t.TEXTURE=5890]="TEXTURE",t[t.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",t[t.TEXTURE_BINDING_CUBE_MAP=34068]="TEXTURE_BINDING_CUBE_MAP",t[t.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",t[t.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",t[t.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",t[t.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",t[t.MAX_CUBE_MAP_TEXTURE_SIZE=34076]="MAX_CUBE_MAP_TEXTURE_SIZE",t[t.TEXTURE0=33984]="TEXTURE0",t[t.ACTIVE_TEXTURE=34016]="ACTIVE_TEXTURE",t[t.REPEAT=10497]="REPEAT",t[t.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",t[t.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",t[t.TEXTURE_WIDTH=4096]="TEXTURE_WIDTH",t[t.TEXTURE_HEIGHT=4097]="TEXTURE_HEIGHT",t[t.FLOAT_VEC2=35664]="FLOAT_VEC2",t[t.FLOAT_VEC3=35665]="FLOAT_VEC3",t[t.FLOAT_VEC4=35666]="FLOAT_VEC4",t[t.INT_VEC2=35667]="INT_VEC2",t[t.INT_VEC3=35668]="INT_VEC3",t[t.INT_VEC4=35669]="INT_VEC4",t[t.BOOL=35670]="BOOL",t[t.BOOL_VEC2=35671]="BOOL_VEC2",t[t.BOOL_VEC3=35672]="BOOL_VEC3",t[t.BOOL_VEC4=35673]="BOOL_VEC4",t[t.FLOAT_MAT2=35674]="FLOAT_MAT2",t[t.FLOAT_MAT3=35675]="FLOAT_MAT3",t[t.FLOAT_MAT4=35676]="FLOAT_MAT4",t[t.SAMPLER_2D=35678]="SAMPLER_2D",t[t.SAMPLER_CUBE=35680]="SAMPLER_CUBE",t[t.LOW_FLOAT=36336]="LOW_FLOAT",t[t.MEDIUM_FLOAT=36337]="MEDIUM_FLOAT",t[t.HIGH_FLOAT=36338]="HIGH_FLOAT",t[t.LOW_INT=36339]="LOW_INT",t[t.MEDIUM_INT=36340]="MEDIUM_INT",t[t.HIGH_INT=36341]="HIGH_INT",t[t.FRAMEBUFFER=36160]="FRAMEBUFFER",t[t.RENDERBUFFER=36161]="RENDERBUFFER",t[t.RGBA4=32854]="RGBA4",t[t.RGB5_A1=32855]="RGB5_A1",t[t.RGB565=36194]="RGB565",t[t.DEPTH_COMPONENT16=33189]="DEPTH_COMPONENT16",t[t.STENCIL_INDEX=6401]="STENCIL_INDEX",t[t.STENCIL_INDEX8=36168]="STENCIL_INDEX8",t[t.DEPTH_STENCIL=34041]="DEPTH_STENCIL",t[t.RENDERBUFFER_WIDTH=36162]="RENDERBUFFER_WIDTH",t[t.RENDERBUFFER_HEIGHT=36163]="RENDERBUFFER_HEIGHT",t[t.RENDERBUFFER_INTERNAL_FORMAT=36164]="RENDERBUFFER_INTERNAL_FORMAT",t[t.RENDERBUFFER_RED_SIZE=36176]="RENDERBUFFER_RED_SIZE",t[t.RENDERBUFFER_GREEN_SIZE=36177]="RENDERBUFFER_GREEN_SIZE",t[t.RENDERBUFFER_BLUE_SIZE=36178]="RENDERBUFFER_BLUE_SIZE",t[t.RENDERBUFFER_ALPHA_SIZE=36179]="RENDERBUFFER_ALPHA_SIZE",t[t.RENDERBUFFER_DEPTH_SIZE=36180]="RENDERBUFFER_DEPTH_SIZE",t[t.RENDERBUFFER_STENCIL_SIZE=36181]="RENDERBUFFER_STENCIL_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE=36048]="FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",t[t.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME=36049]="FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",t[t.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL=36050]="FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",t[t.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE=36051]="FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",t[t.COLOR_ATTACHMENT0=36064]="COLOR_ATTACHMENT0",t[t.DEPTH_ATTACHMENT=36096]="DEPTH_ATTACHMENT",t[t.STENCIL_ATTACHMENT=36128]="STENCIL_ATTACHMENT",t[t.DEPTH_STENCIL_ATTACHMENT=33306]="DEPTH_STENCIL_ATTACHMENT",t[t.NONE=0]="NONE",t[t.FRAMEBUFFER_COMPLETE=36053]="FRAMEBUFFER_COMPLETE",t[t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT=36054]="FRAMEBUFFER_INCOMPLETE_ATTACHMENT",t[t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT=36055]="FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",t[t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS=36057]="FRAMEBUFFER_INCOMPLETE_DIMENSIONS",t[t.FRAMEBUFFER_UNSUPPORTED=36061]="FRAMEBUFFER_UNSUPPORTED",t[t.FRAMEBUFFER_BINDING=36006]="FRAMEBUFFER_BINDING",t[t.RENDERBUFFER_BINDING=36007]="RENDERBUFFER_BINDING",t[t.READ_FRAMEBUFFER=36008]="READ_FRAMEBUFFER",t[t.DRAW_FRAMEBUFFER=36009]="DRAW_FRAMEBUFFER",t[t.MAX_RENDERBUFFER_SIZE=34024]="MAX_RENDERBUFFER_SIZE",t[t.INVALID_FRAMEBUFFER_OPERATION=1286]="INVALID_FRAMEBUFFER_OPERATION",t[t.UNPACK_FLIP_Y_WEBGL=37440]="UNPACK_FLIP_Y_WEBGL",t[t.UNPACK_PREMULTIPLY_ALPHA_WEBGL=37441]="UNPACK_PREMULTIPLY_ALPHA_WEBGL",t[t.UNPACK_COLORSPACE_CONVERSION_WEBGL=37443]="UNPACK_COLORSPACE_CONVERSION_WEBGL",t[t.READ_BUFFER=3074]="READ_BUFFER",t[t.UNPACK_ROW_LENGTH=3314]="UNPACK_ROW_LENGTH",t[t.UNPACK_SKIP_ROWS=3315]="UNPACK_SKIP_ROWS",t[t.UNPACK_SKIP_PIXELS=3316]="UNPACK_SKIP_PIXELS",t[t.PACK_ROW_LENGTH=3330]="PACK_ROW_LENGTH",t[t.PACK_SKIP_ROWS=3331]="PACK_SKIP_ROWS",t[t.PACK_SKIP_PIXELS=3332]="PACK_SKIP_PIXELS",t[t.TEXTURE_BINDING_3D=32874]="TEXTURE_BINDING_3D",t[t.UNPACK_SKIP_IMAGES=32877]="UNPACK_SKIP_IMAGES",t[t.UNPACK_IMAGE_HEIGHT=32878]="UNPACK_IMAGE_HEIGHT",t[t.MAX_3D_TEXTURE_SIZE=32883]="MAX_3D_TEXTURE_SIZE",t[t.MAX_ELEMENTS_VERTICES=33e3]="MAX_ELEMENTS_VERTICES",t[t.MAX_ELEMENTS_INDICES=33001]="MAX_ELEMENTS_INDICES",t[t.MAX_TEXTURE_LOD_BIAS=34045]="MAX_TEXTURE_LOD_BIAS",t[t.MAX_FRAGMENT_UNIFORM_COMPONENTS=35657]="MAX_FRAGMENT_UNIFORM_COMPONENTS",t[t.MAX_VERTEX_UNIFORM_COMPONENTS=35658]="MAX_VERTEX_UNIFORM_COMPONENTS",t[t.MAX_ARRAY_TEXTURE_LAYERS=35071]="MAX_ARRAY_TEXTURE_LAYERS",t[t.MIN_PROGRAM_TEXEL_OFFSET=35076]="MIN_PROGRAM_TEXEL_OFFSET",t[t.MAX_PROGRAM_TEXEL_OFFSET=35077]="MAX_PROGRAM_TEXEL_OFFSET",t[t.MAX_VARYING_COMPONENTS=35659]="MAX_VARYING_COMPONENTS",t[t.FRAGMENT_SHADER_DERIVATIVE_HINT=35723]="FRAGMENT_SHADER_DERIVATIVE_HINT",t[t.RASTERIZER_DISCARD=35977]="RASTERIZER_DISCARD",t[t.VERTEX_ARRAY_BINDING=34229]="VERTEX_ARRAY_BINDING",t[t.MAX_VERTEX_OUTPUT_COMPONENTS=37154]="MAX_VERTEX_OUTPUT_COMPONENTS",t[t.MAX_FRAGMENT_INPUT_COMPONENTS=37157]="MAX_FRAGMENT_INPUT_COMPONENTS",t[t.MAX_SERVER_WAIT_TIMEOUT=37137]="MAX_SERVER_WAIT_TIMEOUT",t[t.MAX_ELEMENT_INDEX=36203]="MAX_ELEMENT_INDEX",t[t.RED=6403]="RED",t[t.RGB8=32849]="RGB8",t[t.RGBA8=32856]="RGBA8",t[t.RGB10_A2=32857]="RGB10_A2",t[t.TEXTURE_3D=32879]="TEXTURE_3D",t[t.TEXTURE_WRAP_R=32882]="TEXTURE_WRAP_R",t[t.TEXTURE_MIN_LOD=33082]="TEXTURE_MIN_LOD",t[t.TEXTURE_MAX_LOD=33083]="TEXTURE_MAX_LOD",t[t.TEXTURE_BASE_LEVEL=33084]="TEXTURE_BASE_LEVEL",t[t.TEXTURE_MAX_LEVEL=33085]="TEXTURE_MAX_LEVEL",t[t.TEXTURE_COMPARE_MODE=34892]="TEXTURE_COMPARE_MODE",t[t.TEXTURE_COMPARE_FUNC=34893]="TEXTURE_COMPARE_FUNC",t[t.SRGB=35904]="SRGB",t[t.SRGB8=35905]="SRGB8",t[t.SRGB8_ALPHA8=35907]="SRGB8_ALPHA8",t[t.COMPARE_REF_TO_TEXTURE=34894]="COMPARE_REF_TO_TEXTURE",t[t.RGBA32F=34836]="RGBA32F",t[t.RGB32F=34837]="RGB32F",t[t.RGBA16F=34842]="RGBA16F",t[t.RGB16F=34843]="RGB16F",t[t.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",t[t.TEXTURE_BINDING_2D_ARRAY=35869]="TEXTURE_BINDING_2D_ARRAY",t[t.R11F_G11F_B10F=35898]="R11F_G11F_B10F",t[t.RGB9_E5=35901]="RGB9_E5",t[t.RGBA32UI=36208]="RGBA32UI",t[t.RGB32UI=36209]="RGB32UI",t[t.RGBA16UI=36214]="RGBA16UI",t[t.RGB16UI=36215]="RGB16UI",t[t.RGBA8UI=36220]="RGBA8UI",t[t.RGB8UI=36221]="RGB8UI",t[t.RGBA32I=36226]="RGBA32I",t[t.RGB32I=36227]="RGB32I",t[t.RGBA16I=36232]="RGBA16I",t[t.RGB16I=36233]="RGB16I",t[t.RGBA8I=36238]="RGBA8I",t[t.RGB8I=36239]="RGB8I",t[t.RED_INTEGER=36244]="RED_INTEGER",t[t.RGB_INTEGER=36248]="RGB_INTEGER",t[t.RGBA_INTEGER=36249]="RGBA_INTEGER",t[t.R8=33321]="R8",t[t.RG8=33323]="RG8",t[t.R16F=33325]="R16F",t[t.R32F=33326]="R32F",t[t.RG16F=33327]="RG16F",t[t.RG32F=33328]="RG32F",t[t.R8I=33329]="R8I",t[t.R8UI=33330]="R8UI",t[t.R16I=33331]="R16I",t[t.R16UI=33332]="R16UI",t[t.R32I=33333]="R32I",t[t.R32UI=33334]="R32UI",t[t.RG8I=33335]="RG8I",t[t.RG8UI=33336]="RG8UI",t[t.RG16I=33337]="RG16I",t[t.RG16UI=33338]="RG16UI",t[t.RG32I=33339]="RG32I",t[t.RG32UI=33340]="RG32UI",t[t.R8_SNORM=36756]="R8_SNORM",t[t.RG8_SNORM=36757]="RG8_SNORM",t[t.RGB8_SNORM=36758]="RGB8_SNORM",t[t.RGBA8_SNORM=36759]="RGBA8_SNORM",t[t.RGB10_A2UI=36975]="RGB10_A2UI",t[t.TEXTURE_IMMUTABLE_FORMAT=37167]="TEXTURE_IMMUTABLE_FORMAT",t[t.TEXTURE_IMMUTABLE_LEVELS=33503]="TEXTURE_IMMUTABLE_LEVELS",t[t.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",t[t.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",t[t.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",t[t.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",t[t.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",t[t.HALF_FLOAT=5131]="HALF_FLOAT",t[t.RG=33319]="RG",t[t.RG_INTEGER=33320]="RG_INTEGER",t[t.INT_2_10_10_10_REV=36255]="INT_2_10_10_10_REV",t[t.CURRENT_QUERY=34917]="CURRENT_QUERY",t[t.QUERY_RESULT=34918]="QUERY_RESULT",t[t.QUERY_RESULT_AVAILABLE=34919]="QUERY_RESULT_AVAILABLE",t[t.ANY_SAMPLES_PASSED=35887]="ANY_SAMPLES_PASSED",t[t.ANY_SAMPLES_PASSED_CONSERVATIVE=36202]="ANY_SAMPLES_PASSED_CONSERVATIVE",t[t.MAX_DRAW_BUFFERS=34852]="MAX_DRAW_BUFFERS",t[t.DRAW_BUFFER0=34853]="DRAW_BUFFER0",t[t.DRAW_BUFFER1=34854]="DRAW_BUFFER1",t[t.DRAW_BUFFER2=34855]="DRAW_BUFFER2",t[t.DRAW_BUFFER3=34856]="DRAW_BUFFER3",t[t.DRAW_BUFFER4=34857]="DRAW_BUFFER4",t[t.DRAW_BUFFER5=34858]="DRAW_BUFFER5",t[t.DRAW_BUFFER6=34859]="DRAW_BUFFER6",t[t.DRAW_BUFFER7=34860]="DRAW_BUFFER7",t[t.DRAW_BUFFER8=34861]="DRAW_BUFFER8",t[t.DRAW_BUFFER9=34862]="DRAW_BUFFER9",t[t.DRAW_BUFFER10=34863]="DRAW_BUFFER10",t[t.DRAW_BUFFER11=34864]="DRAW_BUFFER11",t[t.DRAW_BUFFER12=34865]="DRAW_BUFFER12",t[t.DRAW_BUFFER13=34866]="DRAW_BUFFER13",t[t.DRAW_BUFFER14=34867]="DRAW_BUFFER14",t[t.DRAW_BUFFER15=34868]="DRAW_BUFFER15",t[t.MAX_COLOR_ATTACHMENTS=36063]="MAX_COLOR_ATTACHMENTS",t[t.COLOR_ATTACHMENT1=36065]="COLOR_ATTACHMENT1",t[t.COLOR_ATTACHMENT2=36066]="COLOR_ATTACHMENT2",t[t.COLOR_ATTACHMENT3=36067]="COLOR_ATTACHMENT3",t[t.COLOR_ATTACHMENT4=36068]="COLOR_ATTACHMENT4",t[t.COLOR_ATTACHMENT5=36069]="COLOR_ATTACHMENT5",t[t.COLOR_ATTACHMENT6=36070]="COLOR_ATTACHMENT6",t[t.COLOR_ATTACHMENT7=36071]="COLOR_ATTACHMENT7",t[t.COLOR_ATTACHMENT8=36072]="COLOR_ATTACHMENT8",t[t.COLOR_ATTACHMENT9=36073]="COLOR_ATTACHMENT9",t[t.COLOR_ATTACHMENT10=36074]="COLOR_ATTACHMENT10",t[t.COLOR_ATTACHMENT11=36075]="COLOR_ATTACHMENT11",t[t.COLOR_ATTACHMENT12=36076]="COLOR_ATTACHMENT12",t[t.COLOR_ATTACHMENT13=36077]="COLOR_ATTACHMENT13",t[t.COLOR_ATTACHMENT14=36078]="COLOR_ATTACHMENT14",t[t.COLOR_ATTACHMENT15=36079]="COLOR_ATTACHMENT15",t[t.SAMPLER_3D=35679]="SAMPLER_3D",t[t.SAMPLER_2D_SHADOW=35682]="SAMPLER_2D_SHADOW",t[t.SAMPLER_2D_ARRAY=36289]="SAMPLER_2D_ARRAY",t[t.SAMPLER_2D_ARRAY_SHADOW=36292]="SAMPLER_2D_ARRAY_SHADOW",t[t.SAMPLER_CUBE_SHADOW=36293]="SAMPLER_CUBE_SHADOW",t[t.INT_SAMPLER_2D=36298]="INT_SAMPLER_2D",t[t.INT_SAMPLER_3D=36299]="INT_SAMPLER_3D",t[t.INT_SAMPLER_CUBE=36300]="INT_SAMPLER_CUBE",t[t.INT_SAMPLER_2D_ARRAY=36303]="INT_SAMPLER_2D_ARRAY",t[t.UNSIGNED_INT_SAMPLER_2D=36306]="UNSIGNED_INT_SAMPLER_2D",t[t.UNSIGNED_INT_SAMPLER_3D=36307]="UNSIGNED_INT_SAMPLER_3D",t[t.UNSIGNED_INT_SAMPLER_CUBE=36308]="UNSIGNED_INT_SAMPLER_CUBE",t[t.UNSIGNED_INT_SAMPLER_2D_ARRAY=36311]="UNSIGNED_INT_SAMPLER_2D_ARRAY",t[t.MAX_SAMPLES=36183]="MAX_SAMPLES",t[t.SAMPLER_BINDING=35097]="SAMPLER_BINDING",t[t.PIXEL_PACK_BUFFER=35051]="PIXEL_PACK_BUFFER",t[t.PIXEL_UNPACK_BUFFER=35052]="PIXEL_UNPACK_BUFFER",t[t.PIXEL_PACK_BUFFER_BINDING=35053]="PIXEL_PACK_BUFFER_BINDING",t[t.PIXEL_UNPACK_BUFFER_BINDING=35055]="PIXEL_UNPACK_BUFFER_BINDING",t[t.COPY_READ_BUFFER=36662]="COPY_READ_BUFFER",t[t.COPY_WRITE_BUFFER=36663]="COPY_WRITE_BUFFER",t[t.COPY_READ_BUFFER_BINDING=36662]="COPY_READ_BUFFER_BINDING",t[t.COPY_WRITE_BUFFER_BINDING=36663]="COPY_WRITE_BUFFER_BINDING",t[t.FLOAT_MAT2x3=35685]="FLOAT_MAT2x3",t[t.FLOAT_MAT2x4=35686]="FLOAT_MAT2x4",t[t.FLOAT_MAT3x2=35687]="FLOAT_MAT3x2",t[t.FLOAT_MAT3x4=35688]="FLOAT_MAT3x4",t[t.FLOAT_MAT4x2=35689]="FLOAT_MAT4x2",t[t.FLOAT_MAT4x3=35690]="FLOAT_MAT4x3",t[t.UNSIGNED_INT_VEC2=36294]="UNSIGNED_INT_VEC2",t[t.UNSIGNED_INT_VEC3=36295]="UNSIGNED_INT_VEC3",t[t.UNSIGNED_INT_VEC4=36296]="UNSIGNED_INT_VEC4",t[t.UNSIGNED_NORMALIZED=35863]="UNSIGNED_NORMALIZED",t[t.SIGNED_NORMALIZED=36764]="SIGNED_NORMALIZED",t[t.VERTEX_ATTRIB_ARRAY_INTEGER=35069]="VERTEX_ATTRIB_ARRAY_INTEGER",t[t.VERTEX_ATTRIB_ARRAY_DIVISOR=35070]="VERTEX_ATTRIB_ARRAY_DIVISOR",t[t.TRANSFORM_FEEDBACK_BUFFER_MODE=35967]="TRANSFORM_FEEDBACK_BUFFER_MODE",t[t.MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS=35968]="MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS",t[t.TRANSFORM_FEEDBACK_VARYINGS=35971]="TRANSFORM_FEEDBACK_VARYINGS",t[t.TRANSFORM_FEEDBACK_BUFFER_START=35972]="TRANSFORM_FEEDBACK_BUFFER_START",t[t.TRANSFORM_FEEDBACK_BUFFER_SIZE=35973]="TRANSFORM_FEEDBACK_BUFFER_SIZE",t[t.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN=35976]="TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN",t[t.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS=35978]="MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS",t[t.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS=35979]="MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS",t[t.INTERLEAVED_ATTRIBS=35980]="INTERLEAVED_ATTRIBS",t[t.SEPARATE_ATTRIBS=35981]="SEPARATE_ATTRIBS",t[t.TRANSFORM_FEEDBACK_BUFFER=35982]="TRANSFORM_FEEDBACK_BUFFER",t[t.TRANSFORM_FEEDBACK_BUFFER_BINDING=35983]="TRANSFORM_FEEDBACK_BUFFER_BINDING",t[t.TRANSFORM_FEEDBACK=36386]="TRANSFORM_FEEDBACK",t[t.TRANSFORM_FEEDBACK_PAUSED=36387]="TRANSFORM_FEEDBACK_PAUSED",t[t.TRANSFORM_FEEDBACK_ACTIVE=36388]="TRANSFORM_FEEDBACK_ACTIVE",t[t.TRANSFORM_FEEDBACK_BINDING=36389]="TRANSFORM_FEEDBACK_BINDING",t[t.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING=33296]="FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING",t[t.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE=33297]="FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE",t[t.FRAMEBUFFER_ATTACHMENT_RED_SIZE=33298]="FRAMEBUFFER_ATTACHMENT_RED_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE=33299]="FRAMEBUFFER_ATTACHMENT_GREEN_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE=33300]="FRAMEBUFFER_ATTACHMENT_BLUE_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE=33301]="FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE=33302]="FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE",t[t.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE=33303]="FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE",t[t.FRAMEBUFFER_DEFAULT=33304]="FRAMEBUFFER_DEFAULT",t[t.DEPTH24_STENCIL8=35056]="DEPTH24_STENCIL8",t[t.DRAW_FRAMEBUFFER_BINDING=36006]="DRAW_FRAMEBUFFER_BINDING",t[t.READ_FRAMEBUFFER_BINDING=36010]="READ_FRAMEBUFFER_BINDING",t[t.RENDERBUFFER_SAMPLES=36011]="RENDERBUFFER_SAMPLES",t[t.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER=36052]="FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER",t[t.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE=36182]="FRAMEBUFFER_INCOMPLETE_MULTISAMPLE",t[t.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",t[t.UNIFORM_BUFFER_BINDING=35368]="UNIFORM_BUFFER_BINDING",t[t.UNIFORM_BUFFER_START=35369]="UNIFORM_BUFFER_START",t[t.UNIFORM_BUFFER_SIZE=35370]="UNIFORM_BUFFER_SIZE",t[t.MAX_VERTEX_UNIFORM_BLOCKS=35371]="MAX_VERTEX_UNIFORM_BLOCKS",t[t.MAX_FRAGMENT_UNIFORM_BLOCKS=35373]="MAX_FRAGMENT_UNIFORM_BLOCKS",t[t.MAX_COMBINED_UNIFORM_BLOCKS=35374]="MAX_COMBINED_UNIFORM_BLOCKS",t[t.MAX_UNIFORM_BUFFER_BINDINGS=35375]="MAX_UNIFORM_BUFFER_BINDINGS",t[t.MAX_UNIFORM_BLOCK_SIZE=35376]="MAX_UNIFORM_BLOCK_SIZE",t[t.MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS=35377]="MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS",t[t.MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS=35379]="MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS",t[t.UNIFORM_BUFFER_OFFSET_ALIGNMENT=35380]="UNIFORM_BUFFER_OFFSET_ALIGNMENT",t[t.ACTIVE_UNIFORM_BLOCKS=35382]="ACTIVE_UNIFORM_BLOCKS",t[t.UNIFORM_TYPE=35383]="UNIFORM_TYPE",t[t.UNIFORM_SIZE=35384]="UNIFORM_SIZE",t[t.UNIFORM_BLOCK_INDEX=35386]="UNIFORM_BLOCK_INDEX",t[t.UNIFORM_OFFSET=35387]="UNIFORM_OFFSET",t[t.UNIFORM_ARRAY_STRIDE=35388]="UNIFORM_ARRAY_STRIDE",t[t.UNIFORM_MATRIX_STRIDE=35389]="UNIFORM_MATRIX_STRIDE",t[t.UNIFORM_IS_ROW_MAJOR=35390]="UNIFORM_IS_ROW_MAJOR",t[t.UNIFORM_BLOCK_BINDING=35391]="UNIFORM_BLOCK_BINDING",t[t.UNIFORM_BLOCK_DATA_SIZE=35392]="UNIFORM_BLOCK_DATA_SIZE",t[t.UNIFORM_BLOCK_ACTIVE_UNIFORMS=35394]="UNIFORM_BLOCK_ACTIVE_UNIFORMS",t[t.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES=35395]="UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES",t[t.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER=35396]="UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER",t[t.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER=35398]="UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER",t[t.OBJECT_TYPE=37138]="OBJECT_TYPE",t[t.SYNC_CONDITION=37139]="SYNC_CONDITION",t[t.SYNC_STATUS=37140]="SYNC_STATUS",t[t.SYNC_FLAGS=37141]="SYNC_FLAGS",t[t.SYNC_FENCE=37142]="SYNC_FENCE",t[t.SYNC_GPU_COMMANDS_COMPLETE=37143]="SYNC_GPU_COMMANDS_COMPLETE",t[t.UNSIGNALED=37144]="UNSIGNALED",t[t.SIGNALED=37145]="SIGNALED",t[t.ALREADY_SIGNALED=37146]="ALREADY_SIGNALED",t[t.TIMEOUT_EXPIRED=37147]="TIMEOUT_EXPIRED",t[t.CONDITION_SATISFIED=37148]="CONDITION_SATISFIED",t[t.WAIT_FAILED=37149]="WAIT_FAILED",t[t.SYNC_FLUSH_COMMANDS_BIT=1]="SYNC_FLUSH_COMMANDS_BIT",t[t.COLOR=6144]="COLOR",t[t.DEPTH=6145]="DEPTH",t[t.STENCIL=6146]="STENCIL",t[t.MIN=32775]="MIN",t[t.MAX=32776]="MAX",t[t.DEPTH_COMPONENT24=33190]="DEPTH_COMPONENT24",t[t.STREAM_READ=35041]="STREAM_READ",t[t.STREAM_COPY=35042]="STREAM_COPY",t[t.STATIC_READ=35045]="STATIC_READ",t[t.STATIC_COPY=35046]="STATIC_COPY",t[t.DYNAMIC_READ=35049]="DYNAMIC_READ",t[t.DYNAMIC_COPY=35050]="DYNAMIC_COPY",t[t.DEPTH_COMPONENT32F=36012]="DEPTH_COMPONENT32F",t[t.DEPTH32F_STENCIL8=36013]="DEPTH32F_STENCIL8",t[t.INVALID_INDEX=4294967295]="INVALID_INDEX",t[t.TIMEOUT_IGNORED=-1]="TIMEOUT_IGNORED",t[t.MAX_CLIENT_WAIT_TIMEOUT_WEBGL=37447]="MAX_CLIENT_WAIT_TIMEOUT_WEBGL",t[t.UNMASKED_VENDOR_WEBGL=37445]="UNMASKED_VENDOR_WEBGL",t[t.UNMASKED_RENDERER_WEBGL=37446]="UNMASKED_RENDERER_WEBGL",t[t.MAX_TEXTURE_MAX_ANISOTROPY_EXT=34047]="MAX_TEXTURE_MAX_ANISOTROPY_EXT",t[t.TEXTURE_MAX_ANISOTROPY_EXT=34046]="TEXTURE_MAX_ANISOTROPY_EXT",t[t.R16_EXT=33322]="R16_EXT",t[t.RG16_EXT=33324]="RG16_EXT",t[t.RGB16_EXT=32852]="RGB16_EXT",t[t.RGBA16_EXT=32859]="RGBA16_EXT",t[t.R16_SNORM_EXT=36760]="R16_SNORM_EXT",t[t.RG16_SNORM_EXT=36761]="RG16_SNORM_EXT",t[t.RGB16_SNORM_EXT=36762]="RGB16_SNORM_EXT",t[t.RGBA16_SNORM_EXT=36763]="RGBA16_SNORM_EXT",t[t.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",t[t.COMPRESSED_RGBA_S3TC_DXT1_EXT=33777]="COMPRESSED_RGBA_S3TC_DXT1_EXT",t[t.COMPRESSED_RGBA_S3TC_DXT3_EXT=33778]="COMPRESSED_RGBA_S3TC_DXT3_EXT",t[t.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",t[t.COMPRESSED_SRGB_S3TC_DXT1_EXT=35916]="COMPRESSED_SRGB_S3TC_DXT1_EXT",t[t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917]="COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT",t[t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918]="COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT",t[t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919]="COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT",t[t.COMPRESSED_RED_RGTC1_EXT=36283]="COMPRESSED_RED_RGTC1_EXT",t[t.COMPRESSED_SIGNED_RED_RGTC1_EXT=36284]="COMPRESSED_SIGNED_RED_RGTC1_EXT",t[t.COMPRESSED_RED_GREEN_RGTC2_EXT=36285]="COMPRESSED_RED_GREEN_RGTC2_EXT",t[t.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT=36286]="COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT",t[t.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",t[t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=36493]="COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT",t[t.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT=36494]="COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT",t[t.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT=36495]="COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT",t[t.COMPRESSED_R11_EAC=37488]="COMPRESSED_R11_EAC",t[t.COMPRESSED_SIGNED_R11_EAC=37489]="COMPRESSED_SIGNED_R11_EAC",t[t.COMPRESSED_RG11_EAC=37490]="COMPRESSED_RG11_EAC",t[t.COMPRESSED_SIGNED_RG11_EAC=37491]="COMPRESSED_SIGNED_RG11_EAC",t[t.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",t[t.COMPRESSED_RGBA8_ETC2_EAC=37493]="COMPRESSED_RGBA8_ETC2_EAC",t[t.COMPRESSED_SRGB8_ETC2=37494]="COMPRESSED_SRGB8_ETC2",t[t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37495]="COMPRESSED_SRGB8_ALPHA8_ETC2_EAC",t[t.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37496]="COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2",t[t.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37497]="COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2",t[t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",t[t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",t[t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG=35841]="COMPRESSED_RGB_PVRTC_2BPPV1_IMG",t[t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=35843]="COMPRESSED_RGBA_PVRTC_2BPPV1_IMG",t[t.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",t[t.COMPRESSED_RGB_ATC_WEBGL=35986]="COMPRESSED_RGB_ATC_WEBGL",t[t.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=35986]="COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL",t[t.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=34798]="COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL",t[t.COMPRESSED_RGBA_ASTC_4x4_KHR=37808]="COMPRESSED_RGBA_ASTC_4x4_KHR",t[t.COMPRESSED_RGBA_ASTC_5x4_KHR=37809]="COMPRESSED_RGBA_ASTC_5x4_KHR",t[t.COMPRESSED_RGBA_ASTC_5x5_KHR=37810]="COMPRESSED_RGBA_ASTC_5x5_KHR",t[t.COMPRESSED_RGBA_ASTC_6x5_KHR=37811]="COMPRESSED_RGBA_ASTC_6x5_KHR",t[t.COMPRESSED_RGBA_ASTC_6x6_KHR=37812]="COMPRESSED_RGBA_ASTC_6x6_KHR",t[t.COMPRESSED_RGBA_ASTC_8x5_KHR=37813]="COMPRESSED_RGBA_ASTC_8x5_KHR",t[t.COMPRESSED_RGBA_ASTC_8x6_KHR=37814]="COMPRESSED_RGBA_ASTC_8x6_KHR",t[t.COMPRESSED_RGBA_ASTC_8x8_KHR=37815]="COMPRESSED_RGBA_ASTC_8x8_KHR",t[t.COMPRESSED_RGBA_ASTC_10x5_KHR=37816]="COMPRESSED_RGBA_ASTC_10x5_KHR",t[t.COMPRESSED_RGBA_ASTC_10x6_KHR=37817]="COMPRESSED_RGBA_ASTC_10x6_KHR",t[t.COMPRESSED_RGBA_ASTC_10x8_KHR=37818]="COMPRESSED_RGBA_ASTC_10x8_KHR",t[t.COMPRESSED_RGBA_ASTC_10x10_KHR=37819]="COMPRESSED_RGBA_ASTC_10x10_KHR",t[t.COMPRESSED_RGBA_ASTC_12x10_KHR=37820]="COMPRESSED_RGBA_ASTC_12x10_KHR",t[t.COMPRESSED_RGBA_ASTC_12x12_KHR=37821]="COMPRESSED_RGBA_ASTC_12x12_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840]="COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=37841]="COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=37842]="COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=37843]="COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=37844]="COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=37845]="COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=37846]="COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=37847]="COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=37848]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=37849]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=37850]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=37851]="COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=37852]="COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR",t[t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=37853]="COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR",t[t.QUERY_COUNTER_BITS_EXT=34916]="QUERY_COUNTER_BITS_EXT",t[t.CURRENT_QUERY_EXT=34917]="CURRENT_QUERY_EXT",t[t.QUERY_RESULT_EXT=34918]="QUERY_RESULT_EXT",t[t.QUERY_RESULT_AVAILABLE_EXT=34919]="QUERY_RESULT_AVAILABLE_EXT",t[t.TIME_ELAPSED_EXT=35007]="TIME_ELAPSED_EXT",t[t.TIMESTAMP_EXT=36392]="TIMESTAMP_EXT",t[t.GPU_DISJOINT_EXT=36795]="GPU_DISJOINT_EXT",t[t.COMPLETION_STATUS_KHR=37297]="COMPLETION_STATUS_KHR",t[t.DEPTH_CLAMP_EXT=34383]="DEPTH_CLAMP_EXT",t[t.FIRST_VERTEX_CONVENTION_WEBGL=36429]="FIRST_VERTEX_CONVENTION_WEBGL",t[t.LAST_VERTEX_CONVENTION_WEBGL=36430]="LAST_VERTEX_CONVENTION_WEBGL",t[t.PROVOKING_VERTEX_WEBL=36431]="PROVOKING_VERTEX_WEBL",t[t.POLYGON_MODE_WEBGL=2880]="POLYGON_MODE_WEBGL",t[t.POLYGON_OFFSET_LINE_WEBGL=10754]="POLYGON_OFFSET_LINE_WEBGL",t[t.LINE_WEBGL=6913]="LINE_WEBGL",t[t.FILL_WEBGL=6914]="FILL_WEBGL",t[t.MAX_CLIP_DISTANCES_WEBGL=3378]="MAX_CLIP_DISTANCES_WEBGL",t[t.MAX_CULL_DISTANCES_WEBGL=33529]="MAX_CULL_DISTANCES_WEBGL",t[t.MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL=33530]="MAX_COMBINED_CLIP_AND_CULL_DISTANCES_WEBGL",t[t.CLIP_DISTANCE0_WEBGL=12288]="CLIP_DISTANCE0_WEBGL",t[t.CLIP_DISTANCE1_WEBGL=12289]="CLIP_DISTANCE1_WEBGL",t[t.CLIP_DISTANCE2_WEBGL=12290]="CLIP_DISTANCE2_WEBGL",t[t.CLIP_DISTANCE3_WEBGL=12291]="CLIP_DISTANCE3_WEBGL",t[t.CLIP_DISTANCE4_WEBGL=12292]="CLIP_DISTANCE4_WEBGL",t[t.CLIP_DISTANCE5_WEBGL=12293]="CLIP_DISTANCE5_WEBGL",t[t.CLIP_DISTANCE6_WEBGL=12294]="CLIP_DISTANCE6_WEBGL",t[t.CLIP_DISTANCE7_WEBGL=12295]="CLIP_DISTANCE7_WEBGL",t[t.POLYGON_OFFSET_CLAMP_EXT=36379]="POLYGON_OFFSET_CLAMP_EXT",t[t.LOWER_LEFT_EXT=36001]="LOWER_LEFT_EXT",t[t.UPPER_LEFT_EXT=36002]="UPPER_LEFT_EXT",t[t.NEGATIVE_ONE_TO_ONE_EXT=37726]="NEGATIVE_ONE_TO_ONE_EXT",t[t.ZERO_TO_ONE_EXT=37727]="ZERO_TO_ONE_EXT",t[t.CLIP_ORIGIN_EXT=37724]="CLIP_ORIGIN_EXT",t[t.CLIP_DEPTH_MODE_EXT=37725]="CLIP_DEPTH_MODE_EXT",t[t.SRC1_COLOR_WEBGL=35065]="SRC1_COLOR_WEBGL",t[t.SRC1_ALPHA_WEBGL=34185]="SRC1_ALPHA_WEBGL",t[t.ONE_MINUS_SRC1_COLOR_WEBGL=35066]="ONE_MINUS_SRC1_COLOR_WEBGL",t[t.ONE_MINUS_SRC1_ALPHA_WEBGL=35067]="ONE_MINUS_SRC1_ALPHA_WEBGL",t[t.MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL=35068]="MAX_DUAL_SOURCE_DRAW_BUFFERS_WEBGL",t[t.MIRROR_CLAMP_TO_EDGE_EXT=34627]="MIRROR_CLAMP_TO_EDGE_EXT"})(Ai||(Ai={}));const f1="modulepreload",u1=function(t,e){return new URL(t,e).href},cf={},lf=function(e,i,n){let r=Promise.resolve();if(i&&i.length>0){const o=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),c=a?.nonce||a?.getAttribute("nonce");r=Promise.allSettled(i.map(l=>{if(l=u1(l,n),l in cf)return;cf[l]=!0;const f=l.endsWith(".css"),u=f?'[rel="stylesheet"]':"";if(!!n)for(let d=o.length-1;d>=0;d--){const m=o[d];if(m.href===l&&(!f||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${u}`))return;const p=document.createElement("link");if(p.rel=f?"stylesheet":f1,f||(p.as="script"),p.crossOrigin="",p.href=l,c&&p.setAttribute("nonce",c),document.head.appendChild(p),f)return new Promise((d,m)=>{p.addEventListener("load",d),p.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return r.then(o=>{for(const a of o||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})},h1={WEBGL_depth_texture:{UNSIGNED_INT_24_8_WEBGL:34042},OES_element_index_uint:{},OES_texture_float:{},OES_texture_half_float:{HALF_FLOAT_OES:5131},EXT_color_buffer_float:{},OES_standard_derivatives:{FRAGMENT_SHADER_DERIVATIVE_HINT_OES:35723},EXT_frag_depth:{},EXT_blend_minmax:{MIN_EXT:32775,MAX_EXT:32776},EXT_shader_texture_lod:{}},d1=t=>({drawBuffersWEBGL(e){return t.drawBuffers(e)},COLOR_ATTACHMENT0_WEBGL:36064,COLOR_ATTACHMENT1_WEBGL:36065,COLOR_ATTACHMENT2_WEBGL:36066,COLOR_ATTACHMENT3_WEBGL:36067}),p1=t=>({VERTEX_ARRAY_BINDING_OES:34229,createVertexArrayOES(){return t.createVertexArray()},deleteVertexArrayOES(e){return t.deleteVertexArray(e)},isVertexArrayOES(e){return t.isVertexArray(e)},bindVertexArrayOES(e){return t.bindVertexArray(e)}}),g1=t=>({VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE:35070,drawArraysInstancedANGLE(...e){return t.drawArraysInstanced(...e)},drawElementsInstancedANGLE(...e){return t.drawElementsInstanced(...e)},vertexAttribDivisorANGLE(...e){return t.vertexAttribDivisor(...e)}});function m1(t=!0){const e=HTMLCanvasElement.prototype;if(!t&&e.originalGetContext){e.getContext=e.originalGetContext,e.originalGetContext=void 0;return}e.originalGetContext=e.getContext,e.getContext=function(i,n){if(i==="webgl"||i==="experimental-webgl"){const r=this.originalGetContext("webgl2",n);return r instanceof HTMLElement&&_1(r),r}return this.originalGetContext(i,n)}}function _1(t){t.getExtension("EXT_color_buffer_float");const e={...h1,WEBGL_disjoint_timer_query:t.getExtension("EXT_disjoint_timer_query_webgl2"),WEBGL_draw_buffers:d1(t),OES_vertex_array_object:p1(t),ANGLE_instanced_arrays:g1(t)},i=t.getExtension;t.getExtension=function(r){const s=i.call(t,r);return s||(r in e?e[r]:null)};const n=t.getSupportedExtensions;t.getSupportedExtensions=function(){return(n.apply(t)||[])?.concat(Object.keys(e))}}async function _d(t,e){const i=document.getElementsByTagName("head")[0];if(!i)throw new Error("loadScript");const n=document.createElement("script");return n.setAttribute("type","text/javascript"),n.setAttribute("src",t),new Promise((r,s)=>{n.onload=r,n.onerror=o=>s(new Error(`Unable to load script '${t}': ${o}`)),i.appendChild(n)})}function Wr(t){const e=t.luma||{_polyfilled:!1,extensions:{},softwareRenderer:!1};return e._polyfilled??=!1,e.extensions||={},t.luma=e,e}const A1=1;let Ce=null,ff=!1;const Ka={debugSpectorJS:C.get("debug-spectorjs"),debugSpectorJSUrl:"https://cdn.jsdelivr.net/npm/spectorjs@0.9.30/dist/spector.bundle.js",gl:void 0};async function y1(t){if(!globalThis.SPECTOR)try{await _d(t.debugSpectorJSUrl||Ka.debugSpectorJSUrl)}catch(e){C.warn(String(e))}}function b1(t){if(t={...Ka,...t},!t.debugSpectorJS)return null;if(!Ce&&globalThis.SPECTOR&&!globalThis.luma?.spector){C.probe(A1,"SPECTOR found and initialized. Start with `luma.spector.displayUI()`")();const{Spector:e}=globalThis.SPECTOR;Ce=new e,globalThis.luma&&(globalThis.luma.spector=Ce)}if(!Ce)return null;if(ff||(ff=!0,Ce.spyCanvases(),Ce?.onCaptureStarted.add(e=>C.info("Spector capture started:",e)()),Ce?.onCapture.add(e=>{C.info("Spector capture complete:",e)(),Ce?.getResultUI(),Ce?.resultView.display(),Ce?.resultView.addCapture(e)})),t.gl){const e=t.gl,i=Wr(e),n=i.device;Ce?.startCapture(t.gl,500),i.device=n,new Promise(r=>setTimeout(r,2e3)).then(r=>{C.info("Spector capture stopped after 2 seconds")(),Ce?.stopCapture()})}return Ce}const w1="https://unpkg.com/webgl-debug@2.0.1/index.js";function Ad(t){return t.luma=t.luma||{},t.luma}async function T1(){ei()&&!globalThis.WebGLDebugUtils&&(globalThis.global=globalThis.global||globalThis,globalThis.global.module={},await _d(w1))}function E1(t,e={}){return e.debugWebGL||e.traceWebGL?R1(t,e):S1(t)}function S1(t){const e=Ad(t);return e.realContext?e.realContext:t}function R1(t,e){if(!globalThis.WebGLDebugUtils)return C.warn("webgl-debug not loaded")(),t;const i=Ad(t);if(i.debugContext)return i.debugContext;globalThis.WebGLDebugUtils.init({...Ai,...t});const n=globalThis.WebGLDebugUtils.makeDebugContext(t,v1.bind(null,e),C1.bind(null,e));for(const o in Ai)!(o in n)&&typeof Ai[o]=="number"&&(n[o]=Ai[o]);class r{}Object.setPrototypeOf(n,Object.getPrototypeOf(t)),Object.setPrototypeOf(r,n);const s=Object.create(r);return i.realContext=t,i.debugContext=s,s.luma=i,s.debug=!0,s}function uf(t,e){e=Array.from(e).map(n=>n===void 0?"undefined":n);let i=globalThis.WebGLDebugUtils.glFunctionArgsToString(t,e);return i=`${i.slice(0,100)}${i.length>100?"...":""}`,`gl.${t}(${i})`}function v1(t,e,i,n){n=Array.from(n).map(a=>a===void 0?"undefined":a);const r=globalThis.WebGLDebugUtils.glEnumToString(e),s=globalThis.WebGLDebugUtils.glFunctionArgsToString(i,n),o=`${r} in gl.${i}(${s})`;C.error("%cWebGL","color: white; background: red; padding: 2px 6px; border-radius: 3px;",o)();debugger;throw new Error(o)}function C1(t,e,i){let n="";t.traceWebGL&&C.level>=1&&(n=uf(e,i),C.info(1,"%cWebGL","color: white; background: blue; padding: 2px 6px; border-radius: 3px;",n)());for(const r of i)if(r===void 0){n=n||uf(e,i);debugger}}const Yi=1;class P1 extends A0{type="webgl";constructor(){super(),Zt.defaultProps={...Zt.defaultProps,...Ka}}enforceWebGL2(e){m1(e)}isSupported(){return typeof WebGL2RenderingContext<"u"}isDeviceHandle(e){return typeof WebGL2RenderingContext<"u"&&e instanceof WebGL2RenderingContext?!0:(typeof WebGLRenderingContext<"u"&&e instanceof WebGLRenderingContext&&C.warn("WebGL1 is not supported",e)(),!1)}async attach(e,i={}){const{WebGLDevice:n}=await lf(async()=>{const{WebGLDevice:o}=await Promise.resolve().then(()=>Rf);return{WebGLDevice:o}},void 0,import.meta.url);if(e instanceof n)return e;const r=n.getDeviceFromContext(e);if(r)return r;if(!I1(e))throw new Error("Invalid WebGL2RenderingContext");const s=i.createCanvasContext===!0?{}:i.createCanvasContext;return new n({...i,_handle:e,createCanvasContext:{canvas:e.canvas,autoResize:!1,...s}})}async create(e={}){const{WebGLDevice:i}=await lf(async()=>{const{WebGLDevice:s}=await Promise.resolve().then(()=>Rf);return{WebGLDevice:s}},void 0,import.meta.url),n=[];(e.debugWebGL||e.debug)&&n.push(T1()),e.debugSpectorJS&&n.push(y1(e));const r=await Promise.allSettled(n);for(const s of r)s.status==="rejected"&&C.error(`Failed to initialize debug libraries ${s.reason}`)();try{const s=new i(e);C.groupCollapsed(Yi,`WebGLDevice ${s.id} created`)();const o=`${s._reused?"Reusing":"Created"} device with WebGL2 ${s.props.debug?"debug ":""}context: ${s.info.vendor}, ${s.info.renderer} for canvas: ${s.canvasContext.id}`;return C.probe(Yi,o)(),C.table(Yi,s.info)(),s}finally{C.groupEnd(Yi)(),C.info(Yi,"%cWebGL call tracing: luma.log.set('debug-webgl') ","color: white; background: blue; padding: 2px 6px; border-radius: 3px;")()}}}function I1(t){return typeof WebGL2RenderingContext<"u"&&t instanceof WebGL2RenderingContext?!0:!!(t&&typeof t.createVertexArray=="function")}const Ys=new P1,qa={3042:!1,32773:new Float32Array([0,0,0,0]),32777:32774,34877:32774,32969:1,32968:0,32971:1,32970:0,3106:new Float32Array([0,0,0,0]),3107:[!0,!0,!0,!0],2884:!1,2885:1029,2929:!1,2931:1,2932:513,2928:new Float32Array([0,1]),2930:!0,3024:!0,35725:null,36006:null,36007:null,34229:null,34964:null,2886:2305,33170:4352,2849:1,32823:!1,32824:0,10752:0,32926:!1,32928:!1,32938:1,32939:!1,3089:!1,3088:new Int32Array([0,0,1024,1024]),2960:!1,2961:0,2968:4294967295,36005:4294967295,2962:519,2967:0,2963:4294967295,34816:519,36003:0,36004:4294967295,2964:7680,2965:7680,2966:7680,34817:7680,34818:7680,34819:7680,2978:[0,0,1024,1024],36389:null,36662:null,36663:null,35053:null,35055:null,35723:4352,36010:null,35977:!1,3333:4,3317:4,37440:!1,37441:!1,37443:37444,3330:0,3332:0,3331:0,3314:0,32878:0,3316:0,3315:0,32877:0},ce=(t,e,i)=>e?t.enable(i):t.disable(i),hf=(t,e,i)=>t.hint(i,e),Pe=(t,e,i)=>t.pixelStorei(i,e),df=(t,e,i)=>{const n=i===36006?36009:36008;return t.bindFramebuffer(n,e)},Xi=(t,e,i)=>{const r={34964:34962,36662:36662,36663:36663,35053:35051,35055:35052}[i];t.bindBuffer(r,e)};function Xs(t){return Array.isArray(t)||ArrayBuffer.isView(t)&&!(t instanceof DataView)}const x1={3042:ce,32773:(t,e)=>t.blendColor(...e),32777:"blendEquation",34877:"blendEquation",32969:"blendFunc",32968:"blendFunc",32971:"blendFunc",32970:"blendFunc",3106:(t,e)=>t.clearColor(...e),3107:(t,e)=>t.colorMask(...e),2884:ce,2885:(t,e)=>t.cullFace(e),2929:ce,2931:(t,e)=>t.clearDepth(e),2932:(t,e)=>t.depthFunc(e),2928:(t,e)=>t.depthRange(...e),2930:(t,e)=>t.depthMask(e),3024:ce,35723:hf,35725:(t,e)=>t.useProgram(e),36007:(t,e)=>t.bindRenderbuffer(36161,e),36389:(t,e)=>t.bindTransformFeedback?.(36386,e),34229:(t,e)=>t.bindVertexArray(e),36006:df,36010:df,34964:Xi,36662:Xi,36663:Xi,35053:Xi,35055:Xi,2886:(t,e)=>t.frontFace(e),33170:hf,2849:(t,e)=>t.lineWidth(e),32823:ce,32824:"polygonOffset",10752:"polygonOffset",35977:ce,32926:ce,32928:ce,32938:"sampleCoverage",32939:"sampleCoverage",3089:ce,3088:(t,e)=>t.scissor(...e),2960:ce,2961:(t,e)=>t.clearStencil(e),2968:(t,e)=>t.stencilMaskSeparate(1028,e),36005:(t,e)=>t.stencilMaskSeparate(1029,e),2962:"stencilFuncFront",2967:"stencilFuncFront",2963:"stencilFuncFront",34816:"stencilFuncBack",36003:"stencilFuncBack",36004:"stencilFuncBack",2964:"stencilOpFront",2965:"stencilOpFront",2966:"stencilOpFront",34817:"stencilOpBack",34818:"stencilOpBack",34819:"stencilOpBack",2978:(t,e)=>t.viewport(...e),34383:ce,10754:ce,12288:ce,12289:ce,12290:ce,12291:ce,12292:ce,12293:ce,12294:ce,12295:ce,3333:Pe,3317:Pe,37440:Pe,37441:Pe,37443:Pe,3330:Pe,3332:Pe,3331:Pe,3314:Pe,32878:Pe,3316:Pe,3315:Pe,32877:Pe,framebuffer:(t,e)=>{const i=e&&"handle"in e?e.handle:e;return t.bindFramebuffer(36160,i)},blend:(t,e)=>e?t.enable(3042):t.disable(3042),blendColor:(t,e)=>t.blendColor(...e),blendEquation:(t,e)=>{const i=typeof e=="number"?[e,e]:e;t.blendEquationSeparate(...i)},blendFunc:(t,e)=>{const i=e?.length===2?[...e,...e]:e;t.blendFuncSeparate(...i)},clearColor:(t,e)=>t.clearColor(...e),clearDepth:(t,e)=>t.clearDepth(e),clearStencil:(t,e)=>t.clearStencil(e),colorMask:(t,e)=>t.colorMask(...e),cull:(t,e)=>e?t.enable(2884):t.disable(2884),cullFace:(t,e)=>t.cullFace(e),depthTest:(t,e)=>e?t.enable(2929):t.disable(2929),depthFunc:(t,e)=>t.depthFunc(e),depthMask:(t,e)=>t.depthMask(e),depthRange:(t,e)=>t.depthRange(...e),dither:(t,e)=>e?t.enable(3024):t.disable(3024),derivativeHint:(t,e)=>{t.hint(35723,e)},frontFace:(t,e)=>t.frontFace(e),mipmapHint:(t,e)=>t.hint(33170,e),lineWidth:(t,e)=>t.lineWidth(e),polygonOffsetFill:(t,e)=>e?t.enable(32823):t.disable(32823),polygonOffset:(t,e)=>t.polygonOffset(...e),sampleCoverage:(t,e)=>t.sampleCoverage(e[0],e[1]||!1),scissorTest:(t,e)=>e?t.enable(3089):t.disable(3089),scissor:(t,e)=>t.scissor(...e),stencilTest:(t,e)=>e?t.enable(2960):t.disable(2960),stencilMask:(t,e)=>{e=Xs(e)?e:[e,e];const[i,n]=e;t.stencilMaskSeparate(1028,i),t.stencilMaskSeparate(1029,n)},stencilFunc:(t,e)=>{e=Xs(e)&&e.length===3?[...e,...e]:e;const[i,n,r,s,o,a]=e;t.stencilFuncSeparate(1028,i,n,r),t.stencilFuncSeparate(1029,s,o,a)},stencilOp:(t,e)=>{e=Xs(e)&&e.length===3?[...e,...e]:e;const[i,n,r,s,o,a]=e;t.stencilOpSeparate(1028,i,n,r),t.stencilOpSeparate(1029,s,o,a)},viewport:(t,e)=>t.viewport(...e)};function se(t,e,i){return e[t]!==void 0?e[t]:i[t]}const M1={blendEquation:(t,e,i)=>t.blendEquationSeparate(se(32777,e,i),se(34877,e,i)),blendFunc:(t,e,i)=>t.blendFuncSeparate(se(32969,e,i),se(32968,e,i),se(32971,e,i),se(32970,e,i)),polygonOffset:(t,e,i)=>t.polygonOffset(se(32824,e,i),se(10752,e,i)),sampleCoverage:(t,e,i)=>t.sampleCoverage(se(32938,e,i),se(32939,e,i)),stencilFuncFront:(t,e,i)=>t.stencilFuncSeparate(1028,se(2962,e,i),se(2967,e,i),se(2963,e,i)),stencilFuncBack:(t,e,i)=>t.stencilFuncSeparate(1029,se(34816,e,i),se(36003,e,i),se(36004,e,i)),stencilOpFront:(t,e,i)=>t.stencilOpSeparate(1028,se(2964,e,i),se(2965,e,i),se(2966,e,i)),stencilOpBack:(t,e,i)=>t.stencilOpSeparate(1029,se(34817,e,i),se(34818,e,i),se(34819,e,i))},pf={enable:(t,e)=>t({[e]:!0}),disable:(t,e)=>t({[e]:!1}),pixelStorei:(t,e,i)=>t({[e]:i}),hint:(t,e,i)=>t({[e]:i}),useProgram:(t,e)=>t({35725:e}),bindRenderbuffer:(t,e,i)=>t({36007:i}),bindTransformFeedback:(t,e,i)=>t({36389:i}),bindVertexArray:(t,e)=>t({34229:e}),bindFramebuffer:(t,e,i)=>{switch(e){case 36160:return t({36006:i,36010:i});case 36009:return t({36006:i});case 36008:return t({36010:i});default:return null}},bindBuffer:(t,e,i)=>{const n={34962:[34964],36662:[36662],36663:[36663],35051:[35053],35052:[35055]}[e];return n?t({[n]:i}):{valueChanged:!0}},blendColor:(t,e,i,n,r)=>t({32773:new Float32Array([e,i,n,r])}),blendEquation:(t,e)=>t({32777:e,34877:e}),blendEquationSeparate:(t,e,i)=>t({32777:e,34877:i}),blendFunc:(t,e,i)=>t({32969:e,32968:i,32971:e,32970:i}),blendFuncSeparate:(t,e,i,n,r)=>t({32969:e,32968:i,32971:n,32970:r}),clearColor:(t,e,i,n,r)=>t({3106:new Float32Array([e,i,n,r])}),clearDepth:(t,e)=>t({2931:e}),clearStencil:(t,e)=>t({2961:e}),colorMask:(t,e,i,n,r)=>t({3107:[e,i,n,r]}),cullFace:(t,e)=>t({2885:e}),depthFunc:(t,e)=>t({2932:e}),depthRange:(t,e,i)=>t({2928:new Float32Array([e,i])}),depthMask:(t,e)=>t({2930:e}),frontFace:(t,e)=>t({2886:e}),lineWidth:(t,e)=>t({2849:e}),polygonOffset:(t,e,i)=>t({32824:e,10752:i}),sampleCoverage:(t,e,i)=>t({32938:e,32939:i}),scissor:(t,e,i,n,r)=>t({3088:new Int32Array([e,i,n,r])}),stencilMask:(t,e)=>t({2968:e,36005:e}),stencilMaskSeparate:(t,e,i)=>t({[e===1028?2968:36005]:i}),stencilFunc:(t,e,i,n)=>t({2962:e,2967:i,2963:n,34816:e,36003:i,36004:n}),stencilFuncSeparate:(t,e,i,n,r)=>t({[e===1028?2962:34816]:i,[e===1028?2967:36003]:n,[e===1028?2963:36004]:r}),stencilOp:(t,e,i,n)=>t({2964:e,2965:i,2966:n,34817:e,34818:i,34819:n}),stencilOpSeparate:(t,e,i,n,r)=>t({[e===1028?2964:34817]:i,[e===1028?2965:34818]:n,[e===1028?2966:34819]:r}),viewport:(t,e,i,n,r)=>t({2978:[e,i,n,r]})},Je=(t,e)=>t.isEnabled(e),gf={3042:Je,2884:Je,2929:Je,3024:Je,32823:Je,32926:Je,32928:Je,3089:Je,2960:Je,35977:Je},O1=new Set([34016,36388,36387,35983,35368,34965,35739,35738,3074,34853,34854,34855,34856,34857,34858,34859,34860,34861,34862,34863,34864,34865,34866,34867,34868,35097,32873,35869,32874,34068]);function ki(t,e){if(N1(e))return;const i={};for(const r in e){const s=Number(r),o=x1[r];o&&(typeof o=="string"?i[o]=!0:o(t,e[r],s))}const n=t.lumaState?.cache;if(n)for(const r in i){const s=M1[r];s(t,e,n)}}function yd(t,e=qa){if(typeof e=="number"){const r=e,s=gf[r];return s?s(t,r):t.getParameter(r)}const i=Array.isArray(e)?e:Object.keys(e),n={};for(const r of i){const s=gf[r];n[r]=s?s(t,Number(r)):t.getParameter(Number(r))}return n}function B1(t){ki(t,qa)}function N1(t){for(const e in t)return!1;return!0}function D1(t,e){if(t===e)return!0;if(mf(t)&&mf(e)&&t.length===e.length){for(let i=0;i{}),this._updateCache=this._updateCache.bind(this),Object.seal(this)}push(e={}){this.stateStack.push({})}pop(){const e=this.stateStack[this.stateStack.length-1];ki(this.gl,e),this.stateStack.pop()}trackState(e,i){if(this.cache=i?.copyState?yd(e):Object.assign({},qa),this.initialized)throw new Error("WebGLStateTracker");this.initialized=!0,this.gl.lumaState=this,U1(e);for(const n in pf){const r=pf[n];F1(e,n,r)}_f(e,"getParameter"),_f(e,"isEnabled")}_updateCache(e){let i=!1,n;const r=this.stateStack.length>0?this.stateStack[this.stateStack.length-1]:null;for(const s in e){const o=e[s],a=this.cache[s];D1(o,a)||(i=!0,n=a,r&&!(s in r)&&(r[s]=a),this.cache[s]=o)}return{valueChanged:i,oldValue:n}}}function _f(t,e){const i=t[e].bind(t);t[e]=function(r){if(r===void 0||O1.has(r))return i(r);const s=jt.get(t);return r in s.cache||(s.cache[r]=i(r)),s.enable?s.cache[r]:i(r)},Object.defineProperty(t[e],"name",{value:`${e}-from-cache`,configurable:!1})}function F1(t,e,i){if(!t[e])return;const n=t[e].bind(t);t[e]=function(...s){const o=jt.get(t),{valueChanged:a,oldValue:c}=i(o._updateCache,...s);return a&&n(...s),c},Object.defineProperty(t[e],"name",{value:`${e}-to-cache`,configurable:!1})}function U1(t){const e=t.useProgram.bind(t);t.useProgram=function(n){const r=jt.get(t);r.program!==n&&(e(n),r.program=n)}}function k1(t,e,i){let n="";const r=c=>{const l=c.statusMessage;l&&(n||=l)};t.addEventListener("webglcontextcreationerror",r,!1);const s=i.failIfMajorPerformanceCaveat!==!0,o={preserveDrawingBuffer:!0,...i,failIfMajorPerformanceCaveat:!0};let a=null;try{a||=t.getContext("webgl2",o),!a&&o.failIfMajorPerformanceCaveat&&(n||="Only software GPU is available. Set `failIfMajorPerformanceCaveat: false` to allow.");let c=!1;if(!a&&s&&(o.failIfMajorPerformanceCaveat=!1,a=t.getContext("webgl2",o),c=!0),a||(a=t.getContext("webgl",{}),a&&(a=null,n||="Your browser only supports WebGL1")),!a)throw n||="Your browser does not support WebGL",new Error(`Failed to create WebGL context: ${n}`);const l=Wr(a);l.softwareRenderer=c;const{onContextLost:f,onContextRestored:u}=e;return t.addEventListener("webglcontextlost",h=>f(h),!1),t.addEventListener("webglcontextrestored",h=>u(h),!1),a}finally{t.removeEventListener("webglcontextcreationerror",r,!1)}}function $t(t,e,i){return i[e]===void 0&&(i[e]=t.getExtension(e)||null),i[e]}function L1(t,e){const i=t.getParameter(7936),n=t.getParameter(7937);$t(t,"WEBGL_debug_renderer_info",e);const r=e.WEBGL_debug_renderer_info,s=t.getParameter(r?r.UNMASKED_VENDOR_WEBGL:7936),o=t.getParameter(r?r.UNMASKED_RENDERER_WEBGL:7937),a=s||i,c=o||n,l=t.getParameter(7938),f=bd(a,c),u=W1(a,c),h=V1(a,c);return{type:"webgl",gpu:f,gpuType:h,gpuBackend:u,vendor:a,renderer:c,version:l,shadingLanguage:"glsl",shadingLanguageVersion:300}}function bd(t,e){return/NVIDIA/i.exec(t)||/NVIDIA/i.exec(e)?"nvidia":/INTEL/i.exec(t)||/INTEL/i.exec(e)?"intel":/Apple/i.exec(t)||/Apple/i.exec(e)?"apple":/AMD/i.exec(t)||/AMD/i.exec(e)||/ATI/i.exec(t)||/ATI/i.exec(e)?"amd":/SwiftShader/i.exec(t)||/SwiftShader/i.exec(e)?"software":"unknown"}function W1(t,e){return/Metal/i.exec(t)||/Metal/i.exec(e)?"metal":/ANGLE/i.exec(t)||/ANGLE/i.exec(e)?"opengl":"unknown"}function V1(t,e){if(/SwiftShader/i.exec(t)||/SwiftShader/i.exec(e))return"cpu";switch(bd(t,e)){case"apple":return z1(t,e)?"integrated":"unknown";case"intel":return"integrated";case"software":return"cpu";case"unknown":return"unknown";default:return"discrete"}}function z1(t,e){return/Apple (M\d|A\d|GPU)/i.test(`${t} ${e}`)}function wd(t){switch(t){case"uint8":return 5121;case"sint8":return 5120;case"unorm8":return 5121;case"snorm8":return 5120;case"uint16":return 5123;case"sint16":return 5122;case"unorm16":return 5123;case"snorm16":return 5122;case"uint32":return 5125;case"sint32":return 5124;case"float16":return 5131;case"float32":return 5126}throw new Error(String(t))}const Gi="WEBGL_compressed_texture_s3tc",Ji="WEBGL_compressed_texture_s3tc_srgb",yi="EXT_texture_compression_rgtc",bi="EXT_texture_compression_bptc",j1="WEBGL_compressed_texture_etc",H1="WEBGL_compressed_texture_astc",Y1="WEBGL_compressed_texture_etc1",X1="WEBGL_compressed_texture_pvrtc",Q1="WEBGL_compressed_texture_atc",K1="EXT_texture_norm16",Af="EXT_render_snorm",Td="EXT_color_buffer_float",Qs="snorm8-renderable-webgl",Ks="norm16-renderable-webgl",qs="snorm16-renderable-webgl",Zs="float16-renderable-webgl",$n="float32-renderable-webgl",q1="rgb9e5ufloat-renderable-webgl",Za={"float32-renderable-webgl":{extensions:[Td]},"float16-renderable-webgl":{extensions:["EXT_color_buffer_half_float"]},"rgb9e5ufloat-renderable-webgl":{extensions:["WEBGL_render_shared_exponent"]},"snorm8-renderable-webgl":{extensions:[Af]},"norm16-webgl":{extensions:[K1]},"norm16-renderable-webgl":{features:["norm16-webgl"]},"snorm16-renderable-webgl":{features:["norm16-webgl"],extensions:[Af]},"float32-filterable":{extensions:["OES_texture_float_linear"]},"float16-filterable-webgl":{extensions:["OES_texture_half_float_linear"]},"texture-filterable-anisotropic-webgl":{extensions:["EXT_texture_filter_anisotropic"]},"texture-blend-float-webgl":{extensions:["EXT_float_blend"]},"texture-compression-bc":{extensions:[Gi,Ji,yi,bi]},"texture-compression-bc5-webgl":{extensions:[yi]},"texture-compression-bc7-webgl":{extensions:[bi]},"texture-compression-etc2":{extensions:[j1]},"texture-compression-astc":{extensions:[H1]},"texture-compression-etc1-webgl":{extensions:[Y1]},"texture-compression-pvrtc-webgl":{extensions:[X1]},"texture-compression-atc-webgl":{extensions:[Q1]}};function Z1(t){return t in Za}function Ed(t,e,i){return Sd(t,e,i,new Set)}function Sd(t,e,i,n){const r=Za[e];if(!r||n.has(e))return!1;n.add(e);const s=(r.features||[]).every(o=>Sd(t,o,i,n));return n.delete(e),s?(r.extensions||[]).every(o=>!!$t(t,o,i)):!1}const ss={r8unorm:{gl:33321,rb:!0},r8snorm:{gl:36756,r:Qs},r8uint:{gl:33330,rb:!0},r8sint:{gl:33329,rb:!0},rg8unorm:{gl:33323,rb:!0},rg8snorm:{gl:36757,r:Qs},rg8uint:{gl:33336,rb:!0},rg8sint:{gl:33335,rb:!0},r16uint:{gl:33332,rb:!0},r16sint:{gl:33331,rb:!0},r16float:{gl:33325,rb:!0,r:Zs},r16unorm:{gl:33322,rb:!0,r:Ks},r16snorm:{gl:36760,r:qs},"rgba4unorm-webgl":{gl:32854,rb:!0},"rgb565unorm-webgl":{gl:36194,rb:!0},"rgb5a1unorm-webgl":{gl:32855,rb:!0},"rgb8unorm-webgl":{gl:32849},"rgb8snorm-webgl":{gl:36758},rgba8unorm:{gl:32856},"rgba8unorm-srgb":{gl:35907},rgba8snorm:{gl:36759,r:Qs},rgba8uint:{gl:36220},rgba8sint:{gl:36238},bgra8unorm:{},"bgra8unorm-srgb":{},rg16uint:{gl:33338},rg16sint:{gl:33337},rg16float:{gl:33327,rb:!0,r:Zs},rg16unorm:{gl:33324,r:Ks},rg16snorm:{gl:36761,r:qs},r32uint:{gl:33334,rb:!0},r32sint:{gl:33333,rb:!0},r32float:{gl:33326,r:$n},rgb9e5ufloat:{gl:35901,r:q1},rg11b10ufloat:{gl:35898,rb:!0},rgb10a2unorm:{gl:32857,rb:!0},rgb10a2uint:{gl:36975,rb:!0},"rgb16unorm-webgl":{gl:32852,r:!1},"rgb16snorm-webgl":{gl:36762,r:!1},rg32uint:{gl:33340,rb:!0},rg32sint:{gl:33339,rb:!0},rg32float:{gl:33328,rb:!0,r:$n},rgba16uint:{gl:36214,rb:!0},rgba16sint:{gl:36232,rb:!0},rgba16float:{gl:34842,r:Zs},rgba16unorm:{gl:32859,rb:!0,r:Ks},rgba16snorm:{gl:36763,r:qs},"rgb32float-webgl":{gl:34837,x:Td,r:$n,dataFormat:6407,types:[5126]},rgba32uint:{gl:36208,rb:!0},rgba32sint:{gl:36226,rb:!0},rgba32float:{gl:34836,rb:!0,r:$n},stencil8:{gl:36168,rb:!0},depth16unorm:{gl:33189,dataFormat:6402,types:[5123],rb:!0},depth24plus:{gl:33190,dataFormat:6402,types:[5125]},depth32float:{gl:36012,dataFormat:6402,types:[5126],rb:!0},"depth24plus-stencil8":{gl:35056,rb:!0,depthTexture:!0,dataFormat:34041,types:[34042]},"depth32float-stencil8":{gl:36013,dataFormat:34041,types:[36269],rb:!0},"bc1-rgb-unorm-webgl":{gl:33776,x:Gi},"bc1-rgb-unorm-srgb-webgl":{gl:35916,x:Ji},"bc1-rgba-unorm":{gl:33777,x:Gi},"bc1-rgba-unorm-srgb":{gl:35916,x:Ji},"bc2-rgba-unorm":{gl:33778,x:Gi},"bc2-rgba-unorm-srgb":{gl:35918,x:Ji},"bc3-rgba-unorm":{gl:33779,x:Gi},"bc3-rgba-unorm-srgb":{gl:35919,x:Ji},"bc4-r-unorm":{gl:36283,x:yi},"bc4-r-snorm":{gl:36284,x:yi},"bc5-rg-unorm":{gl:36285,x:yi},"bc5-rg-snorm":{gl:36286,x:yi},"bc6h-rgb-ufloat":{gl:36495,x:bi},"bc6h-rgb-float":{gl:36494,x:bi},"bc7-rgba-unorm":{gl:36492,x:bi},"bc7-rgba-unorm-srgb":{gl:36493,x:bi},"etc2-rgb8unorm":{gl:37492},"etc2-rgb8unorm-srgb":{gl:37494},"etc2-rgb8a1unorm":{gl:37496},"etc2-rgb8a1unorm-srgb":{gl:37497},"etc2-rgba8unorm":{gl:37493},"etc2-rgba8unorm-srgb":{gl:37495},"eac-r11unorm":{gl:37488},"eac-r11snorm":{gl:37489},"eac-rg11unorm":{gl:37490},"eac-rg11snorm":{gl:37491},"astc-4x4-unorm":{gl:37808},"astc-4x4-unorm-srgb":{gl:37840},"astc-5x4-unorm":{gl:37809},"astc-5x4-unorm-srgb":{gl:37841},"astc-5x5-unorm":{gl:37810},"astc-5x5-unorm-srgb":{gl:37842},"astc-6x5-unorm":{gl:37811},"astc-6x5-unorm-srgb":{gl:37843},"astc-6x6-unorm":{gl:37812},"astc-6x6-unorm-srgb":{gl:37844},"astc-8x5-unorm":{gl:37813},"astc-8x5-unorm-srgb":{gl:37845},"astc-8x6-unorm":{gl:37814},"astc-8x6-unorm-srgb":{gl:37846},"astc-8x8-unorm":{gl:37815},"astc-8x8-unorm-srgb":{gl:37847},"astc-10x5-unorm":{gl:37816},"astc-10x5-unorm-srgb":{gl:37848},"astc-10x6-unorm":{gl:37817},"astc-10x6-unorm-srgb":{gl:37849},"astc-10x8-unorm":{gl:37818},"astc-10x8-unorm-srgb":{gl:37850},"astc-10x10-unorm":{gl:37819},"astc-10x10-unorm-srgb":{gl:37851},"astc-12x10-unorm":{gl:37820},"astc-12x10-unorm-srgb":{gl:37852},"astc-12x12-unorm":{gl:37821},"astc-12x12-unorm-srgb":{gl:37853},"pvrtc-rgb4unorm-webgl":{gl:35840},"pvrtc-rgba4unorm-webgl":{gl:35842},"pvrtc-rgb2unorm-webgl":{gl:35841},"pvrtc-rgba2unorm-webgl":{gl:35843},"etc1-rbg-unorm-webgl":{gl:36196},"atc-rgb-unorm-webgl":{gl:35986},"atc-rgba-unorm-webgl":{gl:35986},"atc-rgbai-unorm-webgl":{gl:34798}};function G1(t,e,i){let n=e.create;const r=ss[e.format];r?.gl===void 0&&(n=!1),r?.x&&(n=n&&!!$t(t,r.x,i)),e.format==="stencil8"&&(n=!1);const s=r?.r===!1?!1:r?.r===void 0||Ed(t,r.r,i),o=n&&e.render&&s&&J1(t,e.format,i);return{format:e.format,create:n&&e.create,render:o,filter:n&&e.filter,blend:n&&e.blend,store:n&&e.store}}function J1(t,e,i){const n=ss[e],r=n?.gl;if(r===void 0||n?.x&&!$t(t,n.x,i))return!1;const s=t.getParameter(32873),o=t.getParameter(36006),a=t.createTexture(),c=t.createFramebuffer();if(!a||!c)return!1;const l=0;let f=Number(t.getError());for(;f!==l;)f=t.getError();let u=!1;try{if(t.bindTexture(3553,a),t.texStorage2D(3553,1,r,1,1),Number(t.getError())!==l)return!1;t.bindFramebuffer(36160,c),t.framebufferTexture2D(36160,36064,3553,a,0),u=Number(t.checkFramebufferStatus(36160))===36053&&Number(t.getError())===l}finally{t.bindFramebuffer(36160,o),t.deleteFramebuffer(c),t.bindTexture(3553,s),t.deleteTexture(a)}return u}function Rd(t){const e=ss[t],i=t3(t),n=He.getInfo(t);return n.compressed&&(e.dataFormat=i),{internalFormat:i,format:e?.dataFormat||e3(n.channels,n.integer,n.normalized,i),type:n.dataType?wd(n.dataType):e?.types?.[0]||5121,compressed:n.compressed||!1}}function $1(t){switch(He.getInfo(t).attachment){case"depth":return 36096;case"stencil":return 36128;case"depth-stencil":return 33306;default:throw new Error(`Not a depth stencil format: ${t}`)}}function e3(t,e,i,n){if(n===6408||n===6407)return n;switch(t){case"r":return e&&!i?36244:6403;case"rg":return e&&!i?33320:33319;case"rgb":return e&&!i?36248:6407;case"rgba":return e&&!i?36249:6408;case"bgra":throw new Error("bgra pixels not supported by WebGL");default:return 6408}}function t3(t){const i=ss[t]?.gl;if(i===void 0)throw new Error(`Unsupported texture format ${t}`);return i}const yf={"depth-clip-control":"EXT_depth_clamp","timestamp-query":"EXT_disjoint_timer_query_webgl2","compilation-status-async-webgl":"KHR_parallel_shader_compile","polygon-mode-webgl":"WEBGL_polygon_mode","provoking-vertex-webgl":"WEBGL_provoking_vertex","shader-clip-cull-distance-webgl":"WEBGL_clip_cull_distance","shader-noperspective-interpolation-webgl":"NV_shader_noperspective_interpolation","shader-conservative-depth-webgl":"EXT_conservative_depth"};class i3 extends d0{gl;extensions;testedFeatures=new Set;constructor(e,i,n){super([],n),this.gl=e,this.extensions=i,$t(e,"EXT_color_buffer_float",i)}*[Symbol.iterator](){const e=this.getFeatures();for(const i of e)this.has(i)&&(yield i);return[]}has(e){return this.disabledFeatures?.[e]?!1:(this.testedFeatures.has(e)||(this.testedFeatures.add(e),Z1(e)&&Ed(this.gl,e,this.extensions)&&this.features.add(e),this.getWebGLFeature(e)&&this.features.add(e)),this.features.has(e))}initializeFeatures(){const e=this.getFeatures().filter(i=>i!=="polygon-mode-webgl");for(const i of e)this.has(i)}getFeatures(){return[...Object.keys(yf),...Object.keys(Za)]}getWebGLFeature(e){const i=yf[e];return typeof i=="string"?!!$t(this.gl,i,this.extensions):!!i}}class n3 extends c0{get maxTextureDimension1D(){return 0}get maxTextureDimension2D(){return this.getParameter(3379)}get maxTextureDimension3D(){return this.getParameter(32883)}get maxTextureArrayLayers(){return this.getParameter(35071)}get maxBindGroups(){return 0}get maxDynamicUniformBuffersPerPipelineLayout(){return 0}get maxDynamicStorageBuffersPerPipelineLayout(){return 0}get maxSampledTexturesPerShaderStage(){return this.getParameter(35660)}get maxSamplersPerShaderStage(){return this.getParameter(35661)}get maxStorageBuffersPerShaderStage(){return 0}get maxStorageTexturesPerShaderStage(){return 0}get maxUniformBuffersPerShaderStage(){return this.getParameter(35375)}get maxUniformBufferBindingSize(){return this.getParameter(35376)}get maxStorageBufferBindingSize(){return 0}get minUniformBufferOffsetAlignment(){return this.getParameter(35380)}get minStorageBufferOffsetAlignment(){return 0}get maxVertexBuffers(){return 16}get maxVertexAttributes(){return this.getParameter(34921)}get maxVertexBufferArrayStride(){return 2048}get maxInterStageShaderVariables(){return this.getParameter(35659)}get maxComputeWorkgroupStorageSize(){return 0}get maxComputeInvocationsPerWorkgroup(){return 0}get maxComputeWorkgroupSizeX(){return 0}get maxComputeWorkgroupSizeY(){return 0}get maxComputeWorkgroupSizeZ(){return 0}get maxComputeWorkgroupsPerDimension(){return 0}gl;limits={};constructor(e){super(),this.gl=e}getParameter(e){return this.limits[e]===void 0&&(this.limits[e]=this.gl.getParameter(e)),this.limits[e]||0}}class an extends Jr{device;gl;handle;colorAttachments=[];depthStencilAttachment=null;constructor(e,i){super(e,i);const n=i.handle===null;this.device=e,this.gl=e.gl,this.handle=this.props.handle||n?this.props.handle:this.gl.createFramebuffer(),n||(e._setWebGLDebugMetadata(this.handle,this,{spector:this.props}),i.handle||(this.autoCreateAttachmentTextures(),this.updateAttachments()))}destroy(){super.destroy(),!this.destroyed&&this.handle!==null&&!this.props.handle&&this.gl.deleteFramebuffer(this.handle)}updateAttachments(){const e=this.gl.bindFramebuffer(36160,this.handle);for(let i=0;i{this.compilationStatus="error"})}destroy(){this.handle&&(this.removeStats(),this.device.gl.deleteShader(this.handle),this.destroyed=!0,this.handle.destroyed=!0)}get asyncCompilationStatus(){return this._waitForCompilationComplete().then(()=>(this._getCompilationStatus(),this.compilationStatus))}async getCompilationInfo(){return await this._waitForCompilationComplete(),this.getCompilationInfoSync()}getCompilationInfoSync(){const e=this.device.gl.getShaderInfoLog(this.handle);return e?u3(e):[]}getTranslatedSource(){return this.device.getExtension("WEBGL_debug_shaders").WEBGL_debug_shaders?.getTranslatedShaderSource(this.handle)||null}_compile(e){e=e.startsWith("#version ")?e:`#version 300 es ${e}`;const{gl:i}=this.device;if(i.shaderSource(this.handle,e),i.compileShader(this.handle),!this.device.props.debug){this.compilationStatus="pending";return}if(!this.device.features.has("compilation-status-async-webgl")){if(this._getCompilationStatus(),this.debugShader(),this.compilationStatus==="error")throw new Error(`GLSL compilation errors in ${this.props.stage} shader ${this.props.id}`);return}return C.once(1,"Shader compilation is asynchronous")(),this._waitForCompilationComplete().then(()=>{C.info(2,`Shader ${this.id} - async compilation complete: ${this.compilationStatus}`)(),this._getCompilationStatus(),this.debugShader()})}async _waitForCompilationComplete(){const e=async r=>await new Promise(s=>setTimeout(s,r));if(!this.device.features.has("compilation-status-async-webgl")){await e(10);return}const{gl:n}=this.device;for(;;){if(n.getShaderParameter(this.handle,37297))return;await e(10)}}_getCompilationStatus(){this.compilationStatus=this.device.gl.getShaderParameter(this.handle,35713)?"success":"error"}}function d3(t,e,i,n){if(_3(e))return n(t);const r=t;r.pushState();try{return p3(t,e),ki(r.gl,i),n(t)}finally{r.popState()}}function p3(t,e){const i=t,{gl:n}=i;if(e.cullMode)switch(e.cullMode){case"none":n.disable(2884);break;case"front":n.enable(2884),n.cullFace(1028);break;case"back":n.enable(2884),n.cullFace(1029);break}if(e.frontFace&&n.frontFace(Ht("frontFace",e.frontFace,{ccw:2305,cw:2304})),e.unclippedDepth&&t.features.has("depth-clip-control")&&n.enable(34383),e.depthBias!==void 0&&(n.enable(32823),n.polygonOffset(e.depthBias,e.depthBiasSlopeScale||0)),e.provokingVertex&&t.features.has("provoking-vertex-webgl")){const s=i.getExtension("WEBGL_provoking_vertex").WEBGL_provoking_vertex,o=Ht("provokingVertex",e.provokingVertex,{first:36429,last:36430});s?.provokingVertexWEBGL(o)}if((e.polygonMode||e.polygonOffsetLine)&&t.features.has("polygon-mode-webgl")){if(e.polygonMode){const s=i.getExtension("WEBGL_polygon_mode").WEBGL_polygon_mode,o=Ht("polygonMode",e.polygonMode,{fill:6914,line:6913});s?.polygonModeWEBGL(1028,o),s?.polygonModeWEBGL(1029,o)}e.polygonOffsetLine&&n.enable(10754)}if(t.features.has("shader-clip-cull-distance-webgl")&&(e.clipDistance0&&n.enable(12288),e.clipDistance1&&n.enable(12289),e.clipDistance2&&n.enable(12290),e.clipDistance3&&n.enable(12291),e.clipDistance4&&n.enable(12292),e.clipDistance5&&n.enable(12293),e.clipDistance6&&n.enable(12294),e.clipDistance7&&n.enable(12295)),e.depthWriteEnabled!==void 0&&n.depthMask(m3("depthWriteEnabled",e.depthWriteEnabled)),e.depthCompare&&(e.depthCompare!=="always"?n.enable(2929):n.disable(2929),n.depthFunc(zo("depthCompare",e.depthCompare))),e.clearDepth!==void 0&&n.clearDepth(e.clearDepth),e.stencilWriteMask){const r=e.stencilWriteMask;n.stencilMaskSeparate(1028,r),n.stencilMaskSeparate(1029,r)}if(e.stencilReadMask&&C.warn("stencilReadMask not supported under WebGL"),e.stencilCompare){const r=e.stencilReadMask||4294967295,s=zo("depthCompare",e.stencilCompare);e.stencilCompare!=="always"?n.enable(2960):n.disable(2960),n.stencilFuncSeparate(1028,s,0,r),n.stencilFuncSeparate(1029,s,0,r)}if(e.stencilPassOperation&&e.stencilFailOperation&&e.stencilDepthFailOperation){const r=Js("stencilPassOperation",e.stencilPassOperation),s=Js("stencilFailOperation",e.stencilFailOperation),o=Js("stencilDepthFailOperation",e.stencilDepthFailOperation);n.stencilOpSeparate(1028,s,o,r),n.stencilOpSeparate(1029,s,o,r)}switch(e.blend){case!0:n.enable(3042);break;case!1:n.disable(3042);break}if(e.blendColorOperation||e.blendAlphaOperation){const r=bf("blendColorOperation",e.blendColorOperation||"add"),s=bf("blendAlphaOperation",e.blendAlphaOperation||"add");n.blendEquationSeparate(r,s);const o=tr("blendColorSrcFactor",e.blendColorSrcFactor||"one"),a=tr("blendColorDstFactor",e.blendColorDstFactor||"zero"),c=tr("blendAlphaSrcFactor",e.blendAlphaSrcFactor||"one"),l=tr("blendAlphaDstFactor",e.blendAlphaDstFactor||"zero");n.blendFuncSeparate(o,a,c,l)}}function zo(t,e){return Ht(t,e,{never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519})}function Js(t,e){return Ht(t,e,{keep:7680,zero:0,replace:7681,invert:5386,"increment-clamp":7682,"decrement-clamp":7683,"increment-wrap":34055,"decrement-wrap":34056})}function bf(t,e){return Ht(t,e,{add:32774,subtract:32778,"reverse-subtract":32779,min:32775,max:32776})}function tr(t,e,i="color"){return Ht(t,e,{one:1,zero:0,src:768,"one-minus-src":769,dst:774,"one-minus-dst":775,"src-alpha":770,"one-minus-src-alpha":771,"dst-alpha":772,"one-minus-dst-alpha":773,"src-alpha-saturated":776,constant:i==="color"?32769:32771,"one-minus-constant":i==="color"?32770:32772,src1:768,"one-minus-src1":769,"src1-alpha":770,"one-minus-src1-alpha":771})}function g3(t,e){return`Illegal parameter ${e} for ${t}`}function Ht(t,e,i){if(!(e in i))throw new Error(g3(t,e));return i[e]}function m3(t,e){return e}function _3(t){let e=!0;for(const i in t){e=!1;break}return e}function vd(t){const e={};return t.addressModeU&&(e[10242]=$s(t.addressModeU)),t.addressModeV&&(e[10243]=$s(t.addressModeV)),t.addressModeW&&(e[32882]=$s(t.addressModeW)),t.magFilter&&(e[10240]=jo(t.magFilter)),(t.minFilter||t.mipmapFilter)&&(e[10241]=A3(t.minFilter||"linear",t.mipmapFilter)),t.lodMinClamp!==void 0&&(e[33082]=t.lodMinClamp),t.lodMaxClamp!==void 0&&(e[33083]=t.lodMaxClamp),t.type==="comparison-sampler"&&(e[34892]=34894),t.compare&&(e[34893]=zo("compare",t.compare)),t.maxAnisotropy&&(e[34046]=t.maxAnisotropy),e}function $s(t){switch(t){case"clamp-to-edge":return 33071;case"repeat":return 10497;case"mirror-repeat":return 33648}}function jo(t){switch(t){case"nearest":return 9728;case"linear":return 9729}}function A3(t,e="none"){if(!e)return jo(t);switch(e){case"none":return jo(t);case"nearest":switch(t){case"nearest":return 9984;case"linear":return 9985}break;case"linear":switch(t){case"nearest":return 9986;case"linear":return 9987}}}class y3 extends Gt{device;handle;parameters;constructor(e,i){super(e,i),this.device=e,this.parameters=vd(i),this.handle=i.handle||this.device.gl.createSampler(),this._setSamplerParameters(this.parameters)}destroy(){this.handle&&(this.device.gl.deleteSampler(this.handle),this.handle=void 0)}toString(){return`Sampler(${this.id},${JSON.stringify(this.props)})`}_setSamplerParameters(e){for(const[i,n]of Object.entries(e)){const r=Number(i);switch(r){case 33082:case 33083:this.device.gl.samplerParameterf(this.handle,r,n);break;default:this.device.gl.samplerParameteri(this.handle,r,n);break}}}}function Ft(t,e,i){if(b3(e))return i(t);const{nocatch:n=!0}=e,r=jt.get(t);r.push(),ki(t,e);let s;if(n)s=i(t),r.pop();else try{s=i(t)}finally{r.pop()}return s}function b3(t){for(const e in t)return!1;return!0}class wi extends Zr{device;gl;handle;texture;constructor(e,i){super(e,{...Y.defaultProps,...i}),this.device=e,this.gl=this.device.gl,this.handle=null,this.texture=i.texture}}function Cd(t){return w3[t]}const w3={5124:"sint32",5125:"uint32",5122:"sint16",5123:"uint16",5120:"sint8",5121:"uint8",5126:"float32",5131:"float16",33635:"uint16",32819:"uint16",32820:"uint16",33640:"uint32",35899:"uint32",35902:"uint32",34042:"uint32",36269:"uint32"};class ln extends Y{device;gl;handle;sampler=void 0;view;glTarget;glFormat;glType;glInternalFormat;compressed;_textureUnit=0;_framebuffer=null;_framebufferAttachmentKey=null;constructor(e,i){super(e,i,{byteAlignment:1}),this.device=e,this.gl=this.device.gl;const n=Rd(this.props.format);this.glTarget=S3(this.props.dimension),this.glInternalFormat=n.internalFormat,this.glFormat=n.format,this.glType=n.type,this.compressed=n.compressed,this.handle=this.props.handle||this.gl.createTexture(),this.device._setWebGLDebugMetadata(this.handle,this,{spector:this.props}),this.gl.bindTexture(this.glTarget,this.handle);const{dimension:r,width:s,height:o,depth:a,mipLevels:c,glTarget:l,glInternalFormat:f}=this;if(!this.compressed)switch(r){case"2d":case"cube":this.gl.texStorage2D(l,c,f,s,o);break;case"2d-array":case"3d":this.gl.texStorage3D(l,c,f,s,o,a);break;default:throw new Error(r)}this.gl.bindTexture(this.glTarget,null),this._initializeData(i.data),this.props.handle?this.trackReferencedMemory(this.getAllocatedByteLength(),"Texture"):this.trackAllocatedMemory(this.getAllocatedByteLength(),"Texture"),this.setSampler(this.props.sampler),this.view=new wi(this.device,{...this.props,texture:this}),Object.seal(this)}destroy(){this.handle&&(this._framebuffer?.destroy(),this._framebuffer=null,this._framebufferAttachmentKey=null,this.removeStats(),this.props.handle?this.trackDeallocatedReferencedMemory("Texture"):(this.gl.deleteTexture(this.handle),this.trackDeallocatedMemory("Texture")),this.destroyed=!0)}createView(e){return new wi(this.device,{...e,texture:this})}setSampler(e={}){super.setSampler(e);const i=vd(this.sampler.props);this._setSamplerParameters(i)}copyExternalImage(e){const i=this._normalizeCopyExternalImageOptions(e);if(i.sourceX||i.sourceY)throw new Error("WebGL does not support sourceX/sourceY)");const{glFormat:n,glType:r}=this,{image:s,depth:o,mipLevel:a,x:c,y:l,z:f,width:u,height:h}=i,p=ir(this.glTarget,this.dimension,f),d=i.flipY?{37440:!0}:{};return this.gl.bindTexture(this.glTarget,this.handle),Ft(this.gl,d,()=>{switch(this.dimension){case"2d":case"cube":this.gl.texSubImage2D(p,a,c,l,u,h,n,r,s);break;case"2d-array":case"3d":this.gl.texSubImage3D(p,a,c,l,f,u,h,o,n,r,s);break;default:}}),this.gl.bindTexture(this.glTarget,null),{width:i.width,height:i.height}}copyImageData(e){super.copyImageData(e)}readBuffer(e={},i){if(!i)throw new Error(`${this} readBuffer requires a destination buffer`);const n=this._getSupportedColorReadOptions(e),r=e.byteOffset??0,s=this.computeMemoryLayout(n);if(i.byteLength{this.gl.readPixels(n.x,n.y,n.width,n.height,this.glFormat,this.glType,r+a)})}finally{this.gl.bindBuffer(35051,null)}return i}async readDataAsync(e={}){throw new Error(`${this} readDataAsync is deprecated; use readBuffer() with an explicit destination buffer or DynamicTexture.readAsync()`)}writeBuffer(e,i={}){const n=this._normalizeTextureWriteOptions(i),{width:r,height:s,depthOrArrayLayers:o,mipLevel:a,byteOffset:c,x:l,y:f,z:u}=n,{glFormat:h,glType:p,compressed:d}=this,m=ir(this.glTarget,this.dimension,u);if(d)throw new Error("writeBuffer for compressed textures is not implemented in WebGL");const{bytesPerPixel:g}=this.device.getTextureFormatInfo(this.format),_=g?n.bytesPerRow/g:void 0,y={3317:this.byteAlignment,..._!==void 0?{3314:_}:{},32878:n.rowsPerImage};this.gl.bindTexture(this.glTarget,this.handle),this.gl.bindBuffer(35052,e.handle),Ft(this.gl,y,()=>{switch(this.dimension){case"2d":case"cube":this.gl.texSubImage2D(m,a,l,f,r,s,h,p,c);break;case"2d-array":case"3d":this.gl.texSubImage3D(m,a,l,f,u,r,s,o,h,p,c);break;default:}}),this.gl.bindBuffer(35052,null),this.gl.bindTexture(this.glTarget,null)}writeData(e,i={}){const n=this._normalizeTextureWriteOptions(i),r=ArrayBuffer.isView(e)?e:new Uint8Array(e),{width:s,height:o,depthOrArrayLayers:a,mipLevel:c,x:l,y:f,z:u,byteOffset:h}=n,{glFormat:p,glType:d,compressed:m}=this,g=ir(this.glTarget,this.dimension,u);let _;if(!m){const{bytesPerPixel:v}=this.device.getTextureFormatInfo(this.format);v&&(_=n.bytesPerRow/v)}const y=this.compressed?{}:{3317:this.byteAlignment,..._!==void 0?{3314:_}:{},32878:n.rowsPerImage},A=E3(r,h),b=m?T3(r,h):r,T=this._getMipLevelSize(c),w=l===0&&f===0&&u===0&&s===T.width&&o===T.height&&a===T.depthOrArrayLayers;this.gl.bindTexture(this.glTarget,this.handle),this.gl.bindBuffer(35052,null),Ft(this.gl,y,()=>{switch(this.dimension){case"2d":case"cube":m?w?this.gl.compressedTexImage2D(g,c,p,s,o,0,b):this.gl.compressedTexSubImage2D(g,c,l,f,s,o,p,b):this.gl.texSubImage2D(g,c,l,f,s,o,p,d,r,A);break;case"2d-array":case"3d":m?w?this.gl.compressedTexImage3D(g,c,p,s,o,a,0,b):this.gl.compressedTexSubImage3D(g,c,l,f,u,s,o,a,p,b):this.gl.texSubImage3D(g,c,l,f,u,s,o,a,p,d,r,A);break;default:}}),this.gl.bindTexture(this.glTarget,null)}_getRowByteAlignment(e,i){return 1}_getFramebuffer(){return this._framebuffer||=this.device.createFramebuffer({id:`framebuffer-for-${this.id}`,width:this.width,height:this.height,colorAttachments:[this]}),this._framebuffer}readDataSyncWebGL(e={}){const i=this._getSupportedColorReadOptions(e),n=this.computeMemoryLayout(i),r=Cd(this.glType),s=Ph(r),o=new s(n.byteLength/s.BYTES_PER_ELEMENT);return this._readColorTextureLayers(i,n,a=>{const c=new s(o.buffer,o.byteOffset+a,n.bytesPerImage/s.BYTES_PER_ELEMENT);this.gl.readPixels(i.x,i.y,i.width,i.height,this.glFormat,this.glType,c)}),o.buffer}_readColorTextureLayers(e,i,n){const r=this._getFramebuffer(),s=i.bytesPerRow/i.bytesPerPixel,o={3333:this.byteAlignment,...s!==e.width?{3330:s}:{}},a=this.gl.getParameter(3074),c=this.gl.bindFramebuffer(36160,r.handle);try{this.gl.readBuffer(36064),Ft(this.gl,o,()=>{for(let l=0;l`"${c.name}"`).join(", ");i?.disableWarnings||C.warn(`No binding "${r}" in render pipeline "${this.id}", expected one of ${a}`,s)()}}}draw(e){this._syncLinkStatus();const i=e.bindGroups?ul(e.bindGroups):e.bindings||this.bindings,{renderPass:n,parameters:r=this.props.parameters,topology:s=this.props.topology,vertexArray:o,vertexCount:a,instanceCount:c,isInstanced:l=!1,firstVertex:f=0,transformFeedback:u,uniforms:h=this.uniforms}=e,p=v3(s),d=!!o.indexBuffer,m=o.indexBuffer?.glIndexType;if(this.linkStatus!=="success")return C.info(2,`RenderPipeline:${this.id}.draw() aborted - waiting for shader linking`)(),!1;if(!this._areTexturesRenderable(i))return C.info(2,`RenderPipeline:${this.id}.draw() aborted - textures not yet loaded`)(),!1;this.device.gl.useProgram(this.handle),o.bindBeforeRender(n),u&&u.begin(this.props.topology),this._applyBindings(i,{disableWarnings:this.props.disableWarnings}),this._applyUniforms(h);const g=n;return d3(this.device,r,g.glParameters,()=>{d&&l?this.device.gl.drawElementsInstanced(p,a||0,m,f,c||0):d?this.device.gl.drawElements(p,a||0,m,f):l?this.device.gl.drawArraysInstanced(p,f,a||0,c||0):this.device.gl.drawArrays(p,f,a||0),u&&u.end()}),o.unbindAfterRender(n),!0}_areTexturesRenderable(e){let i=!0;for(const n of this.shaderLayout.bindings)wf(e,n.name)||(C.warn(`Binding ${n.name} not found in ${this.id}`)(),i=!1);return i}_applyBindings(e,i){if(this._syncLinkStatus(),this.linkStatus!=="success")return;const{gl:n}=this.device;n.useProgram(this.handle);let r=0,s=0;for(const o of this.shaderLayout.bindings){const a=wf(e,o.name);if(!a)throw new Error(`No value for binding ${o.name} in ${this.id}`);switch(o.type){case"uniform":const{name:c}=o,l=n.getUniformBlockIndex(this.handle,c);if(l===4294967295)throw new Error(`Invalid uniform block name ${c}`);if(n.uniformBlockBinding(this.handle,l,s),a instanceof cn)n.bindBufferBase(35345,s,a.handle);else{const u=a;n.bindBufferRange(35345,s,u.buffer.handle,u.offset||0,u.size||u.buffer.byteLength-(u.offset||0))}s+=1;break;case"texture":if(!(a instanceof wi||a instanceof ln||a instanceof an))throw new Error("texture");let f;if(a instanceof wi)f=a.texture;else if(a instanceof ln)f=a;else if(a instanceof an&&a.colorAttachments[0]instanceof wi)C.warn("Passing framebuffer in texture binding may be deprecated. Use fbo.colorAttachments[0] instead")(),f=a.colorAttachments[0].texture;else throw new Error("No texture");n.activeTexture(33984+r),n.bindTexture(f.glTarget,f.handle),r+=1;break;case"sampler":break;case"storage":case"read-only-storage":throw new Error(`binding type '${o.type}' not supported in WebGL`)}}}_applyUniforms(e){for(const i of this.shaderLayout.uniforms||[]){const{name:n,location:r,type:s,textureUnit:o}=i,a=e[n]??o;a!==void 0&&R3(this.device.gl,r,s,a)}}_syncLinkStatus(){this.linkStatus=this.sharedRenderPipeline.linkStatus}}function I3(t,e){const i={...t,attributes:t.attributes.map(n=>({...n})),bindings:t.bindings.map(n=>({...n}))};for(const n of e?.attributes||[]){const r=i.attributes.find(s=>s.name===n.name);r?(r.type=n.type||r.type,r.stepMode=n.stepMode||r.stepMode):C.warn(`shader layout attribute ${n.name} not present in shader`)}for(const n of e?.bindings||[]){const r=Pd(i,n.name);if(!r){C.warn(`shader layout binding ${n.name} not present in shader`);continue}Object.assign(r,n)}return i}function Pd(t,e){return t.bindings.find(i=>i.name===e||i.name===`${e}Uniforms`||`${i.name}Uniforms`===e)}function wf(t,e){return t[e]||t[`${e}Uniforms`]||t[e.replace(/Uniforms$/,"")]}function x3(t){return B3[t]}function Ga(t){return O3[t]}function Id(t){return!!xd[t]}function M3(t){return xd[t]}const O3={5126:"f32",35664:"vec2",35665:"vec3",35666:"vec4",5124:"i32",35667:"vec2",35668:"vec3",35669:"vec4",5125:"u32",36294:"vec2",36295:"vec3",36296:"vec4",35670:"f32",35671:"vec2",35672:"vec3",35673:"vec4",35674:"mat2x2",35685:"mat2x3",35686:"mat2x4",35687:"mat3x2",35675:"mat3x3",35688:"mat3x4",35689:"mat4x2",35690:"mat4x3",35676:"mat4x4"},xd={35678:{viewDimension:"2d",sampleType:"float"},35680:{viewDimension:"cube",sampleType:"float"},35679:{viewDimension:"3d",sampleType:"float"},35682:{viewDimension:"3d",sampleType:"depth"},36289:{viewDimension:"2d-array",sampleType:"float"},36292:{viewDimension:"2d-array",sampleType:"depth"},36293:{viewDimension:"cube",sampleType:"float"},36298:{viewDimension:"2d",sampleType:"sint"},36299:{viewDimension:"3d",sampleType:"sint"},36300:{viewDimension:"cube",sampleType:"sint"},36303:{viewDimension:"2d-array",sampleType:"uint"},36306:{viewDimension:"2d",sampleType:"uint"},36307:{viewDimension:"3d",sampleType:"uint"},36308:{viewDimension:"cube",sampleType:"uint"},36311:{viewDimension:"2d-array",sampleType:"uint"}},B3={uint8:5121,sint8:5120,unorm8:5121,snorm8:5120,uint16:5123,sint16:5122,unorm16:5123,snorm16:5122,uint32:5125,sint32:5124,float16:5131,float32:5126};function N3(t,e){const i={attributes:[],bindings:[]};i.attributes=D3(t,e);const n=k3(t,e);for(const a of n){const c=a.uniforms.map(l=>({name:l.name,format:l.format,byteOffset:l.byteOffset,byteStride:l.byteStride,arrayLength:l.arrayLength}));i.bindings.push({type:"uniform",name:a.name,group:0,location:a.location,visibility:(a.vertex?1:0)&(a.fragment?2:0),minBindingSize:a.byteLength,uniforms:c})}const r=U3(t,e);let s=0;for(const a of r)if(Id(a.type)){const{viewDimension:c,sampleType:l}=M3(a.type);i.bindings.push({type:"texture",name:a.name,group:0,location:s,viewDimension:c,sampleType:l}),a.textureUnit=s,s+=1}r.length&&(i.uniforms=r);const o=F3(t,e);return o?.length&&(i.varyings=o),i}function D3(t,e){const i=[],n=t.getProgramParameter(e,35721);for(let r=0;r=0){const l=Ga(a),f=/instance/i.test(o)?"instance":"vertex";i.push({name:o,location:c,stepMode:f,type:l})}}return i.sort((r,s)=>r.location-s.location),i}function F3(t,e){const i=[],n=t.getProgramParameter(e,35971);for(let r=0;rr.location-s.location),i}function U3(t,e){const i=[],n=t.getProgramParameter(e,35718);for(let r=0;r1)for(let p=0;pt.getActiveUniformBlockParameter(e,s,o),n=[],r=t.getProgramParameter(e,35382);for(let s=0;sd.name.split(".")[0]).filter(d=>!!d)),p=o.name.replace(/Uniforms$/,"");if(h.size===1&&!h.has(o.name)&&!h.has(p)){const[d]=h;C.warn(`Uniform block "${o.name}" uses GLSL instance "${d}". luma.gl binds uniform buffers by block name ("${o.name}") and alias ("${p}"). Prefer matching the instance name to one of those to avoid confusing silent mismatches.`)()}n.push(o)}return n.sort((s,o)=>s.location-o.location),n}function L3(t){if(t[t.length-1]!=="]")return{name:t,length:1,isArray:!1};const i=/([^[]*)(\[[0-9]+\])?/.exec(t);return{name:xa(i?.[1],`Failed to parse GLSL uniform name ${t}`),length:i?.[2]?1:0,isArray:!!i?.[2]}}const Tf=4;class W3 extends U0{device;handle;vs;fs;introspectedLayout={attributes:[],bindings:[],uniforms:[]};linkStatus="pending";constructor(e,i){super(e,i),this.device=e,this.handle=i.handle||this.device.gl.createProgram(),this.vs=i.vs,this.fs=i.fs,i.varyings&&i.varyings.length>0&&this.device.gl.transformFeedbackVaryings(this.handle,i.varyings,i.bufferMode||35981),this._linkShaders(),C.time(3,`RenderPipeline ${this.id} - shaderLayout introspection`)(),this.introspectedLayout=N3(this.device.gl,this.handle),C.timeEnd(3,`RenderPipeline ${this.id} - shaderLayout introspection`)()}destroy(){this.destroyed||(this.device.gl.useProgram(null),this.device.gl.deleteProgram(this.handle),this.handle.destroyed=!0,this.destroyResource())}async _linkShaders(){const{gl:e}=this.device;if(e.attachShader(this.handle,this.vs.handle),e.attachShader(this.handle,this.fs.handle),C.time(Tf,`linkProgram for ${this.id}`)(),e.linkProgram(this.handle),C.timeEnd(Tf,`linkProgram for ${this.id}`)(),!this.device.features.has("compilation-status-async-webgl")){const n=this._getLinkStatus();this._reportLinkStatus(n);return}C.once(1,"RenderPipeline linking is asynchronous")(),await this._waitForLinkComplete(),C.info(2,`RenderPipeline ${this.id} - async linking complete: ${this.linkStatus}`)();const i=this._getLinkStatus();this._reportLinkStatus(i)}async _reportLinkStatus(e){switch(e){case"success":return;default:const i=e==="link-error"?"Link error":"Validation error";switch(this.vs.compilationStatus){case"error":throw this.vs.debugShader(),new Error(`${this} ${i} during compilation of ${this.vs}`);case"pending":await this.vs.asyncCompilationStatus,this.vs.debugShader();break}switch(this.fs?.compilationStatus){case"error":throw this.fs.debugShader(),new Error(`${this} ${i} during compilation of ${this.fs}`);case"pending":await this.fs.asyncCompilationStatus,this.fs.debugShader();break}const n=this.device.gl.getProgramInfoLog(this.handle);this.device.reportError(new Error(`${i} during ${e}: ${n}`),this)(),this.device.debug()}}_getLinkStatus(){const{gl:e}=this.device;return e.getProgramParameter(this.handle,35714)?(this._initializeSamplerUniforms(),e.validateProgram(this.handle),e.getProgramParameter(this.handle,35715)?(this.linkStatus="success","success"):(this.linkStatus="error","validation-error")):(this.linkStatus="error","link-error")}_initializeSamplerUniforms(){const{gl:e}=this.device;e.useProgram(this.handle);let i=0;const n=e.getProgramParameter(this.handle,35718);for(let r=0;r1){const o=Int32Array.from({length:i.size},(a,c)=>r+c);return s.uniform1iv(e,o),r+i.size}return s.uniform1i(e,r),r+1}async _waitForLinkComplete(){const e=async r=>await new Promise(s=>setTimeout(s,r));if(!this.device.features.has("compilation-status-async-webgl")){await e(10);return}const{gl:n}=this.device;for(;;){if(n.getProgramParameter(this.handle,37297))return;await e(10)}}}class V3 extends Na{device;handle=null;commands=[];constructor(e,i={}){super(e,i),this.device=e}_executeCommands(e=this.commands){for(const i of e)switch(i.name){case"copy-buffer-to-buffer":z3(this.device,i.options);break;case"copy-buffer-to-texture":j3(this.device,i.options);break;case"copy-texture-to-buffer":H3(this.device,i.options);break;case"copy-texture-to-texture":Y3(this.device,i.options);break;default:throw new Error(i.name)}}}function z3(t,e){const i=e.sourceBuffer,n=e.destinationBuffer;t.gl.bindBuffer(36662,i.handle),t.gl.bindBuffer(36663,n.handle),t.gl.copyBufferSubData(36662,36663,e.sourceOffset??0,e.destinationOffset??0,e.size),t.gl.bindBuffer(36662,null),t.gl.bindBuffer(36663,null)}function j3(t,e){throw new Error("copyBufferToTexture is not supported in WebGL")}function H3(t,e){const{sourceTexture:i,mipLevel:n=0,aspect:r="all",width:s=e.sourceTexture.width,height:o=e.sourceTexture.height,depthOrArrayLayers:a,origin:c=[0,0,0],destinationBuffer:l,byteOffset:f=0,bytesPerRow:u,rowsPerImage:h}=e;if(i instanceof Y){i.readBuffer({x:c[0]??0,y:c[1]??0,z:c[2]??0,width:s,height:o,depthOrArrayLayers:a,mipLevel:n,aspect:r,byteOffset:f},l);return}if(r!=="all")throw new Error("aspect not supported in WebGL");if(n!==0||a!==void 0||u||h)throw new Error("not implemented");const{framebuffer:p,destroyFramebuffer:d}=Md(i);let m;try{const g=l,_=s||p.width,y=o||p.height,A=xa(p.colorAttachments[0]),b=Rd(A.texture.props.format),T=b.format,w=b.type;t.gl.bindBuffer(35051,g.handle),m=t.gl.bindFramebuffer(36160,p.handle),t.gl.readPixels(c[0],c[1],_,y,T,w,f)}finally{t.gl.bindBuffer(35051,null),m!==void 0&&t.gl.bindFramebuffer(36160,m),d&&p.destroy()}}function Y3(t,e){const{sourceTexture:i,destinationMipLevel:n=0,origin:r=[0,0],destinationOrigin:s=[0,0,0],destinationTexture:o}=e;let{width:a=e.destinationTexture.width,height:c=e.destinationTexture.height}=e;const{framebuffer:l,destroyFramebuffer:f}=Md(i),[u=0,h=0]=r,[p,d,m]=s,g=t.gl.bindFramebuffer(36160,l.handle);let _,y;if(o instanceof ln)_=o,a=Number.isFinite(a)?a:_.width,c=Number.isFinite(c)?c:_.height,_._bind(0),y=_.glTarget;else throw new Error("invalid destination");switch(y){case 3553:case 34067:t.gl.copyTexSubImage2D(y,n,p,d,u,h,a,c);break;case 35866:case 32879:t.gl.copyTexSubImage3D(y,n,p,d,m,u,h,a,c);break}_&&_._unbind(),t.gl.bindFramebuffer(36160,g),f&&l.destroy()}function Md(t){if(t instanceof Y){const{width:e,height:i,id:n}=t;return{framebuffer:t.device.createFramebuffer({id:`framebuffer-for-${n}`,width:e,height:i,colorAttachments:[t]}),destroyFramebuffer:!0}}return{framebuffer:t,destroyFramebuffer:!1}}const X3=[1,2,4,8];class Q3 extends Bt{device;handle=null;glParameters={};constructor(e,i){super(e,i),this.device=e;const n=this.props.framebuffer,r=!n||n.handle===null;r&&e.getDefaultCanvasContext()._resizeDrawingBufferIfNeeded();let s;if(!i?.parameters?.viewport)if(!r&&n){const{width:o,height:a}=n;s=[0,0,o,a]}else{const[o,a]=e.getDefaultCanvasContext().getDrawingBufferSize();s=[0,0,o,a]}if(this.device.pushState(),this.setParameters({viewport:s,...this.props.parameters}),!r&&n?.colorAttachments.length){const o=n.colorAttachments.map((a,c)=>36064+c);this.device.gl.drawBuffers(o)}else r&&this.device.gl.drawBuffers([1029]);this.clear(),this.props.timestampQuerySet&&this.props.beginTimestampIndex!==void 0&&this.props.timestampQuerySet.writeTimestamp(this.props.beginTimestampIndex)}end(){this.destroyed||(this.props.timestampQuerySet&&this.props.endTimestampIndex!==void 0&&this.props.timestampQuerySet.writeTimestamp(this.props.endTimestampIndex),this.device.popState(),this.destroy())}pushDebugGroup(e){}popDebugGroup(){}insertDebugMarker(e){}setParameters(e={}){const i={...this.glParameters};i.framebuffer=this.props.framebuffer||null,this.props.depthReadOnly&&(i.depthMask=!this.props.depthReadOnly),i.stencilMask=this.props.stencilReadOnly?0:1,i[35977]=this.props.discard,e.viewport&&(e.viewport.length>=6?(i.viewport=e.viewport.slice(0,4),i.depthRange=[e.viewport[4],e.viewport[5]]):i.viewport=e.viewport),e.scissorRect&&(i.scissorTest=!0,i.scissor=e.scissorRect),e.blendConstant&&(i.blendColor=e.blendConstant),e.stencilReference!==void 0&&(i[2967]=e.stencilReference,i[36003]=e.stencilReference),"colorMask"in e&&(i.colorMask=X3.map(n=>!!(n&e.colorMask))),this.glParameters=i,ki(this.device.gl,i)}beginOcclusionQuery(e){this.props.occlusionQuerySet?.beginOcclusionQuery()}endOcclusionQuery(){this.props.occlusionQuerySet?.endOcclusionQuery()}clear(){const e={...this.glParameters};let i=0;this.props.clearColors&&this.props.clearColors.forEach((n,r)=>{n&&this.clearColorBuffer(r,n)}),this.props.clearColor!==!1&&this.props.clearColors===void 0&&(i|=16384,e.clearColor=this.props.clearColor),this.props.clearDepth!==!1&&(i|=256,e.clearDepth=this.props.clearDepth),this.props.clearStencil!==!1&&(i|=1024,e.clearStencil=this.props.clearStencil),i!==0&&Ft(this.device.gl,e,()=>{this.device.gl.clear(i)})}clearColorBuffer(e=0,i=[0,0,0,0]){Ft(this.device.gl,{framebuffer:this.props.framebuffer},()=>{switch(i.constructor){case Int8Array:case Int16Array:case Int32Array:this.device.gl.clearBufferiv(6144,e,i);break;case Uint8Array:case Uint8ClampedArray:case Uint16Array:case Uint32Array:this.device.gl.clearBufferuiv(6144,e,i);break;case Float32Array:this.device.gl.clearBufferfv(6144,e,i);break;default:throw new Error("clearColorBuffer: color must be typed array")}})}}class Ef extends Ba{device;handle=null;commandBuffer;constructor(e,i){super(e,i),this.device=e,this.commandBuffer=new V3(e,{id:`${this.props.id}-command-buffer`})}destroy(){this.destroyResource()}finish(e){return e?.id&&this.commandBuffer.id!==e.id&&(this.commandBuffer.id=e.id,this.commandBuffer.props.id=e.id),this.destroy(),this.commandBuffer}beginRenderPass(e={}){return new Q3(this.device,this._applyTimeProfilingToPassProps(e))}beginComputePass(e={}){throw new Error("ComputePass not supported in WebGL")}copyBufferToBuffer(e){this.commandBuffer.commands.push({name:"copy-buffer-to-buffer",options:e})}copyBufferToTexture(e){this.commandBuffer.commands.push({name:"copy-buffer-to-texture",options:e})}copyTextureToBuffer(e){this.commandBuffer.commands.push({name:"copy-texture-to-buffer",options:e})}copyTextureToTexture(e){this.commandBuffer.commands.push({name:"copy-texture-to-texture",options:e})}pushDebugGroup(e){}popDebugGroup(){}insertDebugMarker(e){}resolveQuerySet(e,i,n){throw new Error("resolveQuerySet is not supported in WebGL")}writeTimestamp(e,i){e.writeTimestamp(i)}}function K3(t){const{target:e,source:i,start:n=0,count:r=1}=t,s=i.length,o=r*s;let a=0;for(let c=n;a{for(const[i,n]of Object.entries(e))this.setBuffer(i,n)})}setBuffer(e,i){const n=this._getVaryingIndex(e),{buffer:r,byteLength:s,byteOffset:o}=this._getBufferRange(i);if(n<0){this.unusedBuffers[e]=r,C.warn(`${this.id} unusedBuffers varying buffer ${e}`)();return}this.buffers[n]={buffer:r,byteLength:s,byteOffset:o},this.bindOnUse||this._bindBuffer(n,r,o,s)}getBuffer(e){if(Sf(e))return this.buffers[e]||null;const i=this._getVaryingIndex(e);return this.buffers[i]??null}bind(e=this.handle){if(typeof e!="function")return this.gl.bindTransformFeedback(36386,e),this;let i;return this._bound?i=e():(this.gl.bindTransformFeedback(36386,this.handle),this._bound=!0,i=e(),this._bound=!1,this.gl.bindTransformFeedback(36386,null)),i}unbind(){this.bind(null)}_getBufferRange(e){if(e instanceof cn)return{buffer:e,byteOffset:0,byteLength:e.byteLength};const{buffer:i,byteOffset:n=0,byteLength:r=e.buffer.byteLength}=e;return{buffer:i,byteOffset:n,byteLength:r}}_getVaryingIndex(e){if(Sf(e))return Number(e);for(const i of this.layout.varyings||[])if(e===i.name)return i.location;return-1}_bindBuffers(){for(const[e,i]of Object.entries(this.buffers)){const{buffer:n,byteLength:r,byteOffset:s}=this._getBufferRange(i);this._bindBuffer(Number(e),n,s,r)}}_unbindBuffers(){for(const e in this.buffers)this.gl.bindBufferBase(35982,Number(e),null)}_bindBuffer(e,i,n=0,r){const s=i&&i.handle;!s||r===void 0?this.gl.bindBufferBase(35982,e,s):this.gl.bindBufferRange(35982,e,s,n,r)}}function Sf(t){return typeof t=="number"?Number.isInteger(t):/^\d+$/.test(t)}class J3 extends La{device;handle;_timestampPairs=[];_pendingReads=new Set;_occlusionQuery=null;_occlusionActive=!1;get[Symbol.toStringTag](){return"QuerySet"}constructor(e,i){if(super(e,i),this.device=e,i.type==="timestamp"){if(i.count<2)throw new Error("Timestamp QuerySet requires at least two query slots");this._timestampPairs=new Array(Math.ceil(i.count/2)).fill(null).map(()=>({activeQuery:null,completedQueries:[]})),this.handle=null}else{if(i.count>1)throw new Error("WebGL occlusion QuerySet can only have one value");const n=this.device.gl.createQuery();if(!n)throw new Error("WebGL query not supported");this.handle=n}Object.seal(this)}destroy(){if(!this.destroyed){this.handle&&this.device.gl.deleteQuery(this.handle);for(const e of this._timestampPairs){e.activeQuery&&(this._cancelPendingQuery(e.activeQuery),this.device.gl.deleteQuery(e.activeQuery.handle));for(const i of e.completedQueries)this._cancelPendingQuery(i),this.device.gl.deleteQuery(i.handle)}this._occlusionQuery&&(this._cancelPendingQuery(this._occlusionQuery),this.device.gl.deleteQuery(this._occlusionQuery.handle));for(const e of Array.from(this._pendingReads))this._cancelPendingQuery(e);this.destroyResource()}}isResultAvailable(e){return this.props.type==="timestamp"?e===void 0?this._timestampPairs.some((i,n)=>this._isTimestampPairAvailable(n)):this._isTimestampPairAvailable(this._getTimestampPairIndex(e)):this._occlusionQuery?this._pollQueryAvailability(this._occlusionQuery):!1}async readResults(e){const i=e?.firstQuery||0,n=e?.queryCount||this.props.count-i;if(this._validateRange(i,n),this.props.type==="timestamp"){const r=new Array(n).fill(0n),s=Math.floor(i/2),o=Math.floor((i+n-1)/2);for(let a=s;a<=o;a++){const c=await this._consumeTimestampPairResult(a),l=a*2,f=l+1;l>=i&&l=i&&f=this.props.count||i<=e)throw new Error("Timestamp duration range is out of bounds");if(e%2!==0||i!==e+1)throw new Error("WebGL timestamp durations require adjacent even/odd query indices");const n=await this._consumeTimestampPairResult(this._getTimestampPairIndex(e));return Number(n)/1e6}beginOcclusionQuery(){if(this.props.type!=="occlusion")throw new Error("Occlusion queries require an occlusion QuerySet");if(!this.handle)throw new Error("WebGL occlusion query is not available");if(this._occlusionActive)throw new Error("Occlusion query is already active");this.device.gl.beginQuery(35887,this.handle),this._occlusionQuery={handle:this.handle,promise:null,result:null,disjoint:!1,cancelled:!1,pollRequestId:null,resolve:null,reject:null},this._occlusionActive=!0}endOcclusionQuery(){if(!this._occlusionActive)throw new Error("Occlusion query is not active");this.device.gl.endQuery(35887),this._occlusionActive=!1}writeTimestamp(e){if(this.props.type!=="timestamp")throw new Error("Timestamp writes require a timestamp QuerySet");const i=this._getTimestampPairIndex(e),n=this._timestampPairs[i];if(e%2===0){if(n.activeQuery)throw new Error("Timestamp query pair is already active");const r=this.device.gl.createQuery();if(!r)throw new Error("WebGL query not supported");const s={handle:r,promise:null,result:null,disjoint:!1,cancelled:!1,pollRequestId:null,resolve:null,reject:null};this.device.gl.beginQuery(35007,r),n.activeQuery=s;return}if(!n.activeQuery)throw new Error("Timestamp query pair was ended before it was started");this.device.gl.endQuery(35007),n.completedQueries.push(n.activeQuery),n.activeQuery=null}_validateRange(e,i){if(e<0||i<0||e+i>this.props.count)throw new Error("Query read range is out of bounds")}_getTimestampPairIndex(e){if(e<0||e>=this.props.count)throw new Error("Query index is out of bounds");return Math.floor(e/2)}_isTimestampPairAvailable(e){const i=this._timestampPairs[e];return!i||i.completedQueries.length===0?!1:this._pollQueryAvailability(i.completedQueries[0])}_pollQueryAvailability(e){if(e.cancelled||this.destroyed)return e.result=0n,!0;if(e.result!==null||e.disjoint)return!0;if(!this.device.gl.getQueryParameter(e.handle,34919))return!1;const n=!!this.device.gl.getParameter(36795);return e.disjoint=n,e.result=n?0n:BigInt(this.device.gl.getQueryParameter(e.handle,34918)),!0}async _consumeTimestampPairResult(e){const i=this._timestampPairs[e];if(!i||i.completedQueries.length===0)throw new Error("Timestamp query pair has no completed result");const n=i.completedQueries.shift();try{return await this._consumeQueryResult(n)}finally{this.device.gl.deleteQuery(n.handle)}}_consumeQueryResult(e){return e.promise||(this._pendingReads.add(e),e.promise=new Promise((i,n)=>{e.resolve=i,e.reject=n;const r=()=>{if(e.pollRequestId=null,e.cancelled||this.destroyed){this._pendingReads.delete(e),e.promise=null,e.resolve=null,e.reject=null,i(0n);return}if(!this._pollQueryAvailability(e)){e.pollRequestId=this._requestAnimationFrame(r);return}this._pendingReads.delete(e),e.promise=null,e.resolve=null,e.reject=null,e.disjoint?n(new Error("GPU timestamp query was invalidated by a disjoint event")):i(e.result||0n)};r()})),e.promise}_cancelPendingQuery(e){if(this._pendingReads.delete(e),e.cancelled=!0,e.pollRequestId!==null&&(this._cancelAnimationFrame(e.pollRequestId),e.pollRequestId=null),e.resolve){const i=e.resolve;e.promise=null,e.resolve=null,e.reject=null,i(0n)}}_requestAnimationFrame(e){return requestAnimationFrame(e)}_cancelAnimationFrame(e){cancelAnimationFrame(e)}}class $3 extends Wa{device;gl;handle;signaled;_signaled=!1;constructor(e,i={}){super(e,{}),this.device=e,this.gl=e.gl;const n=this.props.handle||this.gl.fenceSync(this.gl.SYNC_GPU_COMMANDS_COMPLETE,0);if(!n)throw new Error("Failed to create WebGL fence");this.handle=n,this.signaled=new Promise(r=>{const s=()=>{const o=this.gl.clientWaitSync(this.handle,0,0);o===this.gl.ALREADY_SIGNALED||o===this.gl.CONDITION_SATISFIED?(this._signaled=!0,r()):setTimeout(s,1)};s()})}isSignaled(){if(this._signaled)return!0;const e=this.gl.getSyncParameter(this.handle,this.gl.SYNC_STATUS);return this._signaled=e===this.gl.SIGNALED,this._signaled}destroy(){this.destroyed||this.gl.deleteSync(this.handle)}}function Od(t){switch(t){case 6406:case 33326:case 6403:case 36244:return 1;case 33339:case 33340:case 33328:case 33320:case 33319:return 2;case 6407:case 36248:case 34837:return 3;case 6408:case 36249:case 34836:return 4;default:return 0}}function e2(t){switch(t){case 5121:return 1;case 33635:case 32819:case 32820:return 2;case 5126:return 4;default:return 0}}function t2(t,e){const{sourceX:i=0,sourceY:n=0,sourceAttachment:r=0}=e||{};let{target:s=null,sourceWidth:o,sourceHeight:a,sourceDepth:c,sourceFormat:l,sourceType:f}=e||{};const{framebuffer:u,deleteFramebuffer:h}=Bd(t),{gl:p,handle:d}=u;o||=u.width,a||=u.height;const m=u.colorAttachments[r]?.texture;if(!m)throw new Error(`Invalid framebuffer attachment ${r}`);c=m?.depth||1,l||=m?.glFormat||6408,f||=m?.glType||5121,s=r2(s,f,l,o,a);const g=ot.getDataType(s);f=f||x3(g);const _=p.bindFramebuffer(36160,d);return p.readBuffer(36064+r),p.readPixels(i,n,o,a,l,f,s),p.readBuffer(36064),p.bindFramebuffer(36160,_||null),h&&u.destroy(),s}function i2(t,e){const{target:i,sourceX:n=0,sourceY:r=0,sourceFormat:s=6408,targetByteOffset:o=0}=e||{};let{sourceWidth:a,sourceHeight:c,sourceType:l}=e||{};const{framebuffer:f,deleteFramebuffer:u}=Bd(t);a=a||f.width,c=c||f.height;const h=f;l=l||5121;let p=i;if(!p){const m=Od(s),g=e2(l),_=o+a*c*m*g;p=h.device.createBuffer({byteLength:_})}const d=t.device.createCommandEncoder();return d.copyTextureToBuffer({sourceTexture:t,width:a,height:c,origin:[n,r],destinationBuffer:p,byteOffset:o}),d.destroy(),u&&f.destroy(),p}function Bd(t){return t instanceof Jr?{framebuffer:t,deleteFramebuffer:!1}:{framebuffer:n2(t),deleteFramebuffer:!0}}function n2(t,e){const{device:i,width:n,height:r,id:s}=t;return i.createFramebuffer({...e,id:`framebuffer-for-${s}`,width:n,height:r,colorAttachments:[t]})}function r2(t,e,i,n,r,s){if(t)return t;e||=5121;const o=Cd(e),a=ot.getTypedArrayConstructor(o),c=Od(i);return new a(n*r*c)}class Yt extends Zt{static getDeviceFromContext(e){return e?e.luma?.device??null:null}type="webgl";handle;features;limits;info;canvasContext;preferredColorFormat="rgba8unorm";preferredDepthFormat="depth24plus";commandEncoder;lost;_resolveContextLost;gl;_constants;extensions;_polyfilled=!1;spectorJS;get[Symbol.toStringTag](){return"WebGLDevice"}toString(){return`${this[Symbol.toStringTag]}(${this.id})`}isVertexFormatSupported(e){switch(e){case"unorm8x4-bgra":return!1;default:return!0}}constructor(e){super({...e,id:e.id||c3("webgl-device")});const i=Zt._getCanvasContextProps(e);if(!i)throw new Error("WebGLDevice requires props.createCanvasContext to be set");const n=i.canvas?.gl??null;let r=Yt.getDeviceFromContext(n);if(r)throw new Error(`WebGL context already attached to device ${r.id}`);this.canvasContext=new o3(this,i),this.lost=new Promise(f=>{this._resolveContextLost=f});const s={...e.webgl};i.alphaMode==="premultiplied"&&(s.premultipliedAlpha=!0),e.powerPreference!==void 0&&(s.powerPreference=e.powerPreference),e.failIfMajorPerformanceCaveat!==void 0&&(s.failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat);const a=this.props._handle||k1(this.canvasContext.canvas,{onContextLost:f=>this._resolveContextLost?.({reason:"destroyed",message:"Entered sleep mode, or too many apps or browser tabs are using the GPU."}),onContextRestored:f=>console.log("WebGL context restored")},s);if(!a)throw new Error("WebGL context creation failed");if(r=Yt.getDeviceFromContext(a),r){if(e._reuseDevices)return C.log(1,`Not creating a new Device, instead returning a reference to Device ${r.id} already attached to WebGL context`,r)(),this.canvasContext.destroy(),r._reused=!0,r;throw new Error(`WebGL context already attached to device ${r.id}`)}this.handle=a,this.gl=a,this.spectorJS=b1({...this.props,gl:this.handle});const c=Wr(this.handle);c.device=this,c.extensions||(c.extensions={}),this.extensions=c.extensions,this.info=L1(this.gl,this.extensions),this.limits=new n3(this.gl),this.features=new i3(this.gl,this.extensions,this.props._disabledFeatures),this.props._initializeFeatures&&this.features.initializeFeatures(),new jt(this.gl,{log:(...f)=>C.log(1,...f)()}).trackState(this.gl,{copyState:!1}),(e.debug||e.debugWebGL)&&(this.gl=E1(this.gl,{debugWebGL:!0,traceWebGL:e.debugWebGL}),C.warn("WebGL debug mode activated. Performance reduced.")()),e.debugWebGL&&(C.level=Math.max(C.level,1)),this.commandEncoder=new Ef(this,{id:`${this}-command-encoder`}),this.canvasContext._startObservers()}destroy(){if(this.commandEncoder?.destroy(),!this.props._reuseDevices&&!this._reused){const e=Wr(this.handle);e.device=null}}get isLost(){return this.gl.isContextLost()}createCanvasContext(e){throw new Error("WebGL only supports a single canvas")}createPresentationContext(e){return new a3(this,e||{})}createBuffer(e){const i=this._normalizeBufferProps(e);return new cn(this,i)}createTexture(e){return new ln(this,e)}createExternalTexture(e){throw new Error("createExternalTexture() not implemented")}createSampler(e){return new y3(this,e)}createShader(e){return new h3(this,e)}createFramebuffer(e){return new an(this,e)}createVertexArray(e){return new Ja(this,e)}createTransformFeedback(e){return new G3(this,e)}createQuerySet(e){return new J3(this,e)}createFence(){return new $3(this)}createRenderPipeline(e){return new P3(this,e)}_createSharedRenderPipelineWebGL(e){return new W3(this,e)}createComputePipeline(e){throw new Error("ComputePipeline not supported in WebGL")}createCommandEncoder(e={}){return new Ef(this,e)}submit(e){let i=null;e||({submittedCommandEncoder:i,commandBuffer:e}=this._finalizeDefaultCommandEncoderForSubmit());try{e._executeCommands(),i&&i.resolveTimeProfilingQuerySet().then(()=>{this.commandEncoder._gpuTimeMs=i._gpuTimeMs}).catch(()=>{})}finally{e.destroy()}}_finalizeDefaultCommandEncoderForSubmit(){const e=this.commandEncoder,i=e.finish();return this.commandEncoder.destroy(),this.commandEncoder=this.createCommandEncoder({id:e.props.id,timeProfilingQuerySet:e.getTimeProfilingQuerySet()}),{submittedCommandEncoder:e,commandBuffer:i}}readPixelsToArrayWebGL(e,i){return t2(e,i)}readPixelsToBufferWebGL(e,i){return i2(e,i)}setParametersWebGL(e){ki(this.gl,e)}getParametersWebGL(e){return yd(this.gl,e)}withParametersWebGL(e,i){return Ft(this.gl,e,i)}resetWebGL(){C.warn("WebGLDevice.resetWebGL is deprecated, use only for debugging")(),B1(this.gl)}_getDeviceSpecificTextureFormatCapabilities(e){return G1(this.gl,e,this.extensions)}loseDevice(){let e=!1;const n=this.getExtension("WEBGL_lose_context").WEBGL_lose_context;return n&&(e=!0,n.loseContext()),this._resolveContextLost?.({reason:"destroyed",message:"Application triggered context loss"}),e}pushState(){jt.get(this.gl).push()}popState(){jt.get(this.gl).pop()}getGLKey(e,i){const n=Number(e);for(const r in this.gl)if(this.gl[r]===n)return`GL.${r}`;return i?.emptyIfUnknown?"":String(e)}getGLKeys(e){const i={emptyIfUnknown:!0};return Object.entries(e).reduce((n,[r,s])=>(n[`${r}:${this.getGLKey(r,i)}`]=`${s}:${this.getGLKey(s,i)}`,n),{})}setConstantAttributeWebGL(e,i){const n=this.limits.maxVertexAttributes;this._constants=this._constants||new Array(n).fill(null);const r=this._constants[e];switch(r&&c2(r,i)&&C.info(1,`setConstantAttributeWebGL(${e}) could have been skipped, value unchanged`)(),this._constants[e]=i,i.constructor){case Float32Array:s2(this,e,i);break;case Int32Array:o2(this,e,i);break;case Uint32Array:a2(this,e,i);break;default:throw new Error("constant")}}getExtension(e){return $t(this.gl,e,this.extensions),this.extensions}_setWebGLDebugMetadata(e,i,n){e.luma=i;const r={props:n.spector,id:n.spector.id};e.__SPECTOR_Metadata=r}}function s2(t,e,i){switch(i.length){case 1:t.gl.vertexAttrib1fv(e,i);break;case 2:t.gl.vertexAttrib2fv(e,i);break;case 3:t.gl.vertexAttrib3fv(e,i);break;case 4:t.gl.vertexAttrib4fv(e,i);break}}function o2(t,e,i){t.gl.vertexAttribI4iv(e,i)}function a2(t,e,i){t.gl.vertexAttribI4uiv(e,i)}function c2(t,e){if(!t||!e||t.length!==e.length||t.constructor!==e.constructor)return!1;for(let i=0;it?"grabbing":"grab",Nd={id:"",width:"100%",height:"100%",style:null,viewState:null,initialViewState:null,pickingRadius:0,pickAsync:"auto",layerFilter:null,parameters:{},parent:null,device:null,deviceProps:{},gl:null,canvas:null,layers:[],effects:[],views:null,controller:null,useDevicePixels:!0,touchAction:"none",eventRecognizerOptions:{},_framebuffer:null,_animate:!1,_pickable:!0,_typedArrayManagerProps:{},_customRender:null,widgets:[],onDeviceInitialized:_t,onWebGLInitialized:_t,onResize:_t,onViewStateChange:_t,onInteractionStateChange:_t,onBeforeRender:_t,onAfterRender:_t,onLoad:_t,onError:t=>J.error(t.message,t.cause)(),onHover:null,onClick:null,onDragStart:null,onDrag:null,onDragEnd:null,_onMetrics:null,getCursor:l2,getTooltip:null,debug:!1,drawPickingColors:!1};class $a{constructor(e){this.width=0,this.height=0,this.userData={},this.device=null,this.canvas=null,this.viewManager=null,this.layerManager=null,this.effectManager=null,this.deckRenderer=null,this.deckPicker=null,this.eventManager=null,this.widgetManager=null,this.tooltip=null,this.animationLoop=null,this.cursorState={isHovering:!1,isDragging:!1},this.stats=new Xr({id:"deck.gl"}),this.metrics={fps:0,setPropsTime:0,layersCount:0,drawLayersCount:0,updateLayersCount:0,updateAttributesCount:0,updateAttributesTime:0,framesRedrawn:0,pickTime:0,pickCount:0,pickLayersCount:0,gpuTime:0,gpuTimePerFrame:0,cpuTime:0,cpuTimePerFrame:0,bufferMemory:0,textureMemory:0,renderbufferMemory:0,gpuMemory:0},this._metricsCounter=0,this._hoverPickSequence=0,this._pointerDownPickSequence=0,this._needsRedraw="Initial render",this._pickRequest={mode:"hover",x:-1,y:-1,radius:0,event:null,unproject3D:!1},this._lastPointerDownInfo=null,this._lastPointerDownInfoPromise=null,this._onPointerMove=n=>{const{_pickRequest:r}=this;if(n.type==="pointerleave")r.x=-1,r.y=-1,r.radius=0;else{if(n.leftButton||n.rightButton)return;{const s=n.offsetCenter;if(!s)return;r.x=s.x,r.y=s.y,r.radius=this.props.pickingRadius}}this.layerManager&&(this.layerManager.context.mousePosition={x:r.x,y:r.y}),r.event=n},this._onEvent=n=>{const r=mr[n.type],s=n.offsetCenter;if(!r||!s||!this.layerManager)return;const o=this.layerManager.getLayers(),a=this._getInternalPickingMode();if(!a)return;if(a==="sync"){const l=n.type==="click"&&this._shouldUnproject3D(o)?this._getFirstPickedInfo(this._pickPointSync(this._getPointPickOptions(s.x,s.y,{unproject3D:!0},o))):this._getLastPointerDownPickingInfo(s.x,s.y,o);this._dispatchPickingEvent(l,n);return}(this._lastPointerDownInfoPromise||Promise.resolve(this._getLastPointerDownPickingInfo(s.x,s.y,o))).then(l=>{this._dispatchPickingEvent(l,n)}).catch(l=>this.props.onError?.(l))},this._onPointerDown=n=>{const r=n.offsetCenter;if(!r)return;const s=this._getInternalPickingMode();if(!s)return;const o=this.layerManager?.getLayers()||[],a=++this._pointerDownPickSequence;if(s==="sync"){const l=this._pickPointSync({x:r.x,y:r.y,radius:this.props.pickingRadius}),f=this._getFirstPickedInfo(l);this._lastPointerDownInfo=f,this._lastPointerDownInfoPromise=Promise.resolve(f);return}const c=this._pickPointAsync(this._getPointPickOptions(r.x,r.y,{},o)).then(l=>this._getFirstPickedInfo(l)).then(l=>(a===this._pointerDownPickSequence&&(this._lastPointerDownInfo=l),l)).catch(l=>{this.props.onError?.(l);const f=this.deckPicker&&this.viewManager?this._getLastPointerDownPickingInfo(r.x,r.y,o):{};return a===this._pointerDownPickSequence&&(this._lastPointerDownInfo=f),f});this._lastPointerDownInfo=null,this._lastPointerDownInfoPromise=c},this.props={...Nd,...e},e=this.props,e.viewState&&e.initialViewState&&J.warn("View state tracking is disabled. Use either `initialViewState` for auto update or `viewState` for manual update.")(),this.viewState=this.props.initialViewState,e.device&&(this.device=e.device);let i=this.device;if(!i&&e.gl){e.gl instanceof WebGLRenderingContext&&J.error("WebGL1 context not supported.")();const n=this.props.deviceProps?.onResize;i=Ys.attach(e.gl,{_cacheShaders:!0,_cachePipelines:!0,...this.props.deviceProps,onResize:(r,s)=>{const{width:o,height:a}=r.canvas;r.setDrawingBufferSize(o,a),this._needsRedraw="Canvas resized",n?.(r,s)}})}i||(i=this._createDevice(e)),this.animationLoop=this._createAnimationLoop(i,e),this.setProps(e),e._typedArrayManagerProps&&An.setOptions(e._typedArrayManagerProps),this.animationLoop.start()}finalize(){this.animationLoop?.stop(),this.animationLoop?.destroy(),this.animationLoop=null,this._hoverPickSequence++,this._pointerDownPickSequence++,this._lastPointerDownInfo=null,this._lastPointerDownInfoPromise=null,this.layerManager?.finalize(),this.layerManager=null,this.viewManager?.finalize(),this.viewManager=null,this.effectManager?.finalize(),this.effectManager=null,this.deckRenderer?.finalize(),this.deckRenderer=null,this.deckPicker?.finalize(),this.deckPicker=null,this.eventManager?.destroy(),this.eventManager=null,this.widgetManager?.finalize(),this.widgetManager=null,!this.props.canvas&&!this.props.device&&!this.props.gl&&this.canvas&&(this.canvas.parentElement?.removeChild(this.canvas),this.canvas=null)}setProps(e){this.stats.get("setProps Time").timeStart(),"onLayerHover"in e&&J.removed("onLayerHover","onHover")(),"onLayerClick"in e&&J.removed("onLayerClick","onClick")(),e.initialViewState&&!Me(this.props.initialViewState,e.initialViewState,3)&&(this.viewState=e.initialViewState),Object.assign(this.props,e),this._validateInternalPickingMode(),this._setCanvasSize(this.props);const i=Object.create(this.props);Object.assign(i,{views:this._getViews(),width:this.width,height:this.height,viewState:this._getViewState()}),e.device&&e.device.id!==this.device?.id&&(this.animationLoop?.stop(),this.canvas!==e.device.canvasContext?.canvas&&(this.canvas?.remove(),this.eventManager?.destroy(),this.canvas=null),J.log(`recreating animation loop for new device! id=${e.device.id}`)(),this.animationLoop=this._createAnimationLoop(e.device,e),this.animationLoop.start()),this.animationLoop?.setProps(i),e.useDevicePixels!==void 0&&this.device?.canvasContext?.setProps&&this.device.canvasContext.setProps({useDevicePixels:e.useDevicePixels}),this.layerManager&&(this.viewManager.setProps(i),this.layerManager.activateViewport(this.getViewports()[0]),this.layerManager.setProps(i),this.effectManager.setProps(i),this.deckRenderer.setProps(i),this.deckPicker.setProps(i),this.widgetManager.setProps(i)),this.stats.get("setProps Time").timeEnd()}needsRedraw(e={clearRedrawFlags:!1}){if(!this.layerManager)return!1;if(this.props._animate)return"Deck._animate";let i=this._needsRedraw;e.clearRedrawFlags&&(this._needsRedraw=!1);const n=this.viewManager.needsRedraw(e),r=this.layerManager.needsRedraw(e),s=this.effectManager.needsRedraw(e),o=this.deckRenderer.needsRedraw(e);return i=i||n||r||s||o,i}redraw(e){if(!this.layerManager)return;let i=this.needsRedraw({clearRedrawFlags:!0});i=e||i,i&&(this.stats.get("Redraw Count").incrementCount(),this.props._customRender?this.props._customRender(i):this._drawLayers(i))}get isInitialized(){return this.viewManager!==null}getViews(){return pe(this.viewManager),this.viewManager.views}getView(e){return pe(this.viewManager),this.viewManager.getView(e)}getViewports(e){return pe(this.viewManager),this.viewManager.getViewports(e)}getCanvas(){return this.canvas}async pickObjectAsync(e){const i=(await this._pickAsync("pickObjectAsync","pickObject Time",e)).result;return i.length?i[0]:null}async pickObjectsAsync(e){return await this._pickAsync("pickObjectsAsync","pickObjects Time",e)}pickObject(e){const i=this._pick("pickObject","pickObject Time",e).result;return i.length?i[0]:null}pickMultipleObjects(e){return e.depth=e.depth||10,this._pick("pickObject","pickMultipleObjects Time",e).result}pickObjects(e){return this._pick("pickObjects","pickObjects Time",e)}_pickPositionForController(e,i){return this._getInternalPickingMode()!=="sync"?null:this.pickObject({x:e,y:i,radius:0,unproject3D:!0})}_addResources(e,i=!1){for(const n in e)this.layerManager.resourceManager.add({resourceId:n,data:e[n],forceUpdate:i})}_removeResources(e){for(const i of e)this.layerManager.resourceManager.remove(i)}_addDefaultEffect(e){this.effectManager.addDefaultEffect(e)}_addDefaultShaderModule(e){this.layerManager.addDefaultShaderModule(e)}_removeDefaultShaderModule(e){this.layerManager?.removeDefaultShaderModule(e)}_resolveInternalPickingMode(){const{pickAsync:e}=this.props,i=this.device?.type||this.props.deviceProps?.type;if(e==="auto")return i==="webgpu"?"async":"sync";if(e==="sync"&&i==="webgpu")throw new Error('`pickAsync: "sync"` is not supported when Deck is using a WebGPU device.');return e}_getInternalPickingMode(){try{return this._resolveInternalPickingMode()}catch(e){return this.props.onError?.(e),null}}_validateInternalPickingMode(){this._getInternalPickingMode()}_getFirstPickedInfo({result:e,emptyInfo:i}){return e[0]||i}_shouldUnproject3D(e=this.layerManager?.getLayers()||[]){return e.some(i=>i.props.pickable==="3d")}_getPointPickOptions(e,i,n={},r=this.layerManager?.getLayers()||[]){return{x:e,y:i,radius:this.props.pickingRadius,unproject3D:this._shouldUnproject3D(r),...n}}_pickPointSync(e){return this._pick("pickObject","pickObject Time",e)}_pickPointAsync(e){return this._pickAsync("pickObjectAsync","pickObject Time",e)}_getLastPointerDownPickingInfo(e,i,n=this.layerManager?.getLayers()||[]){return this.deckPicker.getLastPickedObject({x:e,y:i,layers:n,viewports:this.getViewports({x:e,y:i})},this._lastPointerDownInfo)}_applyHoverCallbacks({result:e,emptyInfo:i},n){if(!this.widgetManager)return;this.cursorState.isHovering=e.length>0;let r=i,s=!1;for(const o of e)r=o,s=o.layer?.onHover(o,n)||s;s||(this.props.onHover?.(r,n),this.widgetManager.onHover(r,n))}_dispatchPickingEvent(e,i){if(!this.layerManager||!this.widgetManager)return;const n=mr[i.type];if(!n)return;const{layer:r}=e,s=r&&(r[n]||r.props[n]),o=this.props[n];let a=!1;s&&(a=s.call(r,e,i)),a||(o?.(e,i),this.widgetManager.onEvent(e,i))}_pickAsync(e,i,n){pe(this.deckPicker);const{stats:r}=this;r.get("Pick Count").incrementCount(),r.get(i).timeStart();const s=this.deckPicker[e]({layers:this.layerManager.getLayers(n),views:this.viewManager.getViews(),viewports:this.getViewports(n),onViewportActive:this.layerManager.activateViewport,effects:this.effectManager.getEffects(),...n});return r.get(i).timeEnd(),s}_pick(e,i,n){pe(this.deckPicker);const{stats:r}=this;r.get("Pick Count").incrementCount(),r.get(i).timeStart();const s=this.deckPicker[e]({layers:this.layerManager.getLayers(n),views:this.viewManager.getViews(),viewports:this.getViewports(n),onViewportActive:this.layerManager.activateViewport,effects:this.effectManager.getEffects(),...n});return r.get(i).timeEnd(),s}_createCanvas(e){let i=e.canvas;return typeof i=="string"&&(i=document.getElementById(i),pe(i)),i||(i=document.createElement("canvas"),i.id=e.id||"deckgl-overlay",e.width&&typeof e.width=="number"&&(i.width=e.width),e.height&&typeof e.height=="number"&&(i.height=e.height),(e.parent||document.body).appendChild(i)),Object.assign(i.style,e.style),i}_setCanvasSize(e){if(!this.canvas)return;const{width:i,height:n}=e;if(i||i===0){const r=Number.isFinite(i)?`${i}px`:i;this.canvas.style.width=r}if(n||n===0){const r=Number.isFinite(n)?`${n}px`:n;this.canvas.style.position=e.style?.position||"absolute",this.canvas.style.height=r}}_updateCanvasSize(){const{canvas:e}=this;if(!e)return;const i=e.clientWidth??e.width,n=e.clientHeight??e.height;(i!==this.width||n!==this.height)&&(this.width=i,this.height=n,this.viewManager?.setProps({width:i,height:n}),this.layerManager?.activateViewport(this.getViewports()[0]),this.props.onResize({width:i,height:n}))}_createAnimationLoop(e,i){const{gl:n,onError:r}=i;return new Ya({device:e,autoResizeDrawingBuffer:!n,autoResizeViewport:!1,onInitialize:s=>this._setDevice(s.device),onRender:this._onRenderFrame.bind(this),onError:r})}_createDevice(e){const i=this.props.deviceProps?.createCanvasContext,n=typeof i=="object"?i:void 0,r={adapters:[],_cacheShaders:!0,_cachePipelines:!0,...e.deviceProps};r.adapters.includes(Ys)||r.adapters.push(Ys);const s={alphaMode:this.props.deviceProps?.type==="webgpu"?"premultiplied":void 0},o=this.props.deviceProps?.onResize;return So.createDevice({_reuseDevices:!0,type:"webgl",...r,createCanvasContext:{...s,...n,canvas:this._createCanvas(e),useDevicePixels:this.props.useDevicePixels,autoResize:!0},onResize:(a,c)=>{this._needsRedraw="Canvas resized",o?.(a,c)}})}_getViewState(){return this.props.viewState||this.viewState}_getViews(){const{views:e}=this.props,i=Array.isArray(e)?e:e?[e]:[new gd({id:"default-view"})];return i.length&&this.props.controller&&(i[0].props.controller=this.props.controller),i}_onContextLost(){const{onError:e}=this.props;this.animationLoop&&e&&e(new Error("WebGL context is lost"))}_pickAndCallback(){const{_pickRequest:e}=this;if(e.event){const i=e.event,n=this.layerManager?.getLayers()||[],r=this._getPointPickOptions(e.x,e.y,{radius:e.radius,mode:e.mode},n),s=this._getInternalPickingMode(),o=++this._hoverPickSequence;if(e.event=null,!s)return;if(s==="sync"){this._applyHoverCallbacks(this._pickPointSync(r),i);return}this._pickPointAsync(r).then(({result:a,emptyInfo:c})=>{o===this._hoverPickSequence&&this._applyHoverCallbacks({result:a,emptyInfo:c},i)}).catch(a=>this.props.onError?.(a))}}_updateCursor(){const e=this.props.parent||this.canvas;e&&(e.style.cursor=this.props.getCursor(this.cursorState))}_setDevice(e){if(this.device=e,this._validateInternalPickingMode(),!this.animationLoop)return;this.canvas||(this.canvas=this.device.canvasContext?.canvas,!this.canvas.isConnected&&this.props.parent&&this.props.parent.insertBefore(this.canvas,this.props.parent.firstChild)),this.device.type==="webgl"&&this.device.setParametersWebGL({blend:!0,blendFunc:[770,771,1,771],polygonOffsetFill:!0,depthTest:!0,depthFunc:515}),this.props.onDeviceInitialized(this.device),this.device.type==="webgl"&&this.props.onWebGLInitialized(this.device.gl);const i=new Jh;i.play(),this.animationLoop.attachTimeline(i);const n=this.props.parent?.querySelector(".deck-events-root")||this.canvas;this.eventManager=new yw(n,{touchAction:this.props.touchAction,recognizers:Object.keys(Pl).map(o=>{const[a,c,l,f]=Pl[o],u=this.props.eventRecognizerOptions?.[o],h={...c,...u,event:o};return{recognizer:new a(h),recognizeWith:l,requestFailure:f}}),events:{pointerdown:this._onPointerDown,pointermove:this._onPointerMove,pointerleave:this._onPointerMove}});for(const o in mr)this.eventManager.on(o,this._onEvent);this.viewManager=new OE({timeline:i,eventManager:this.eventManager,onViewStateChange:this._onViewStateChange.bind(this),onInteractionStateChange:this._onInteractionStateChange.bind(this),pickPosition:this._pickPositionForController.bind(this),views:this._getViews(),viewState:this._getViewState(),width:this.width,height:this.height});const r=this.viewManager.getViewports()[0];this.layerManager=new ME(this.device,{deck:this,stats:this.stats,viewport:r,timeline:i}),this.effectManager=new JE({deck:this,device:this.device}),this.deckRenderer=new t1(this.device,{stats:this.stats}),this.deckPicker=new r1(this.device,{stats:this.stats});const s=this.props.parent?.querySelector(".deck-widgets-root")||this.canvas?.parentElement;this.widgetManager=new a1({deck:this,parentElement:s}),this.widgetManager.addDefault(new md),this.setProps(this.props),this._updateCanvasSize(),this.props.onLoad()}_drawLayers(e,i){const{device:n,gl:r}=this.layerManager.context;this.props.onBeforeRender({device:n,gl:r});const s={target:this.props._framebuffer,layers:this.layerManager.getLayers(),viewports:this.viewManager.getViewports(),onViewportActive:this.layerManager.activateViewport,views:this.viewManager.getViews(),pass:"screen",effects:this.effectManager.getEffects(),...i};this.deckRenderer?.renderLayers(s),s.pass==="screen"&&this.widgetManager.onRedraw({viewports:s.viewports,layers:s.layers}),this.props.onAfterRender({device:n,gl:r})}_onRenderFrame(){this._getFrameStats(),this._metricsCounter++%60===0&&(this._getMetrics(),this.stats.reset(),J.table(4,this.metrics)(),this.props._onMetrics&&this.props._onMetrics(this.metrics)),this._updateCanvasSize(),this._updateCursor(),this.layerManager.updateLayers(),this._pickAndCallback(),this.redraw(),this.viewManager&&this.viewManager.updateViewStates()}_onViewStateChange(e){const i=this.props.onViewStateChange(e)||e.viewState;this.viewState&&(this.viewState={...this.viewState,[e.viewId]:i},this.props.viewState||this.viewManager&&this.viewManager.setProps({viewState:this.viewState}))}_onInteractionStateChange(e){this.cursorState.isDragging=e.isDragging||!1,this.props.onInteractionStateChange(e)}_getFrameStats(){const{stats:e}=this;e.get("frameRate").timeEnd(),e.get("frameRate").timeStart();const i=this.animationLoop.stats;e.get("GPU Time").addTime(i.get("GPU Time").lastTiming),e.get("CPU Time").addTime(i.get("CPU Time").lastTiming)}_getMetrics(){const{metrics:e,stats:i}=this;e.fps=i.get("frameRate").getHz(),e.setPropsTime=i.get("setProps Time").time,e.updateAttributesTime=i.get("Update Attributes").time,e.framesRedrawn=i.get("Redraw Count").count,e.pickTime=i.get("pickObject Time").time+i.get("pickMultipleObjects Time").time+i.get("pickObjects Time").time,e.pickCount=i.get("Pick Count").count,e.layersCount=this.layerManager?.layers.length??0,e.drawLayersCount=i.get("Layers rendered").lastSampleCount,e.pickLayersCount=i.get("Layers picked").lastSampleCount,e.updateAttributesCount=i.get("Layers updated").count,e.updateAttributesCount=i.get("Attributes updated").count,e.gpuTime=i.get("GPU Time").time,e.cpuTime=i.get("CPU Time").time,e.gpuTimePerFrame=i.get("GPU Time").getAverageTime(),e.cpuTimePerFrame=i.get("CPU Time").getAverageTime();const n=So.stats.get("GPU Time and Memory");e.bufferMemory=n.get("Buffer Memory").count,e.textureMemory=n.get("Texture Memory").count,e.renderbufferMemory=n.get("Renderbuffer Memory").count,e.gpuMemory=n.get("GPU Memory").count}}$a.defaultProps=Nd;$a.VERSION=f_;function f2(t){switch(t){case"float64":return Float64Array;case"uint8":case"unorm8":return Uint8ClampedArray;default:return Ph(t)}}const u2=ot.getDataType.bind(ot);function nr(t,e,i){if(e.size>4)return null;const n=i==="webgpu"&&e.type==="uint8"?"unorm8":e.type;return{attribute:t,format:e.size>1?`${n}x${e.size}`:e.type,byteOffset:e.offset||0}}function Ut(t){return t.stride||t.size*t.bytesPerElement}function h2(t,e){return t.type===e.type&&t.size===e.size&&Ut(t)===Ut(e)&&(t.offset||0)===(e.offset||0)}function Ho(t,e){e.offset&&J.removed("shaderAttribute.offset","vertexOffset, elementOffset")();const i=Ut(t),n=e.vertexOffset!==void 0?e.vertexOffset:t.vertexOffset||0,r=e.elementOffset||0,s=n*i+r*t.bytesPerElement+(t.offset||0);return{...e,offset:s,stride:i}}function d2(t,e){const i=Ho(t,e);return{high:i,low:{...i,offset:i.offset+t.size*4}}}class p2{constructor(e,i,n){this._buffer=null,this.device=e,this.id=i.id||"",this.size=i.size||1;const r=i.logicalType||i.type,s=r==="float64";let{defaultValue:o}=i;o=Number.isFinite(o)?[o]:o||new Array(this.size).fill(0);let a;s?a="float32":!r&&i.isIndexed?a="uint32":a=r||"float32";let c=f2(r||a);this.doublePrecision=s,s&&i.fp64===!1&&(c=Float32Array),this.value=null,this.settings={...i,defaultType:c,defaultValue:o,logicalType:r,type:a,normalized:a.includes("norm"),size:this.size,bytesPerElement:c.BYTES_PER_ELEMENT},this.state={...n,externalBuffer:null,bufferAccessor:this.settings,allocatedValue:null,numInstances:0,bounds:null,constant:!1}}get isConstant(){return this.state.constant}get buffer(){return this._buffer}get byteOffset(){const e=this.getAccessor();return e.vertexOffset?e.vertexOffset*Ut(e):0}get numInstances(){return this.state.numInstances}set numInstances(e){this.state.numInstances=e}delete(){this._buffer&&(this._buffer.delete(),this._buffer=null),An.release(this.state.allocatedValue)}getBuffer(){return this.state.constant?null:this.state.externalBuffer||this._buffer}getValue(e=this.id,i=null){const n={};if(this.state.constant){const r=this.value;if(i){const s=Ho(this.getAccessor(),i),o=s.offset/r.BYTES_PER_ELEMENT,a=s.size||this.size;n[e]=r.subarray(o,o+a)}else n[e]=r}else n[e]=this.getBuffer();return this.doublePrecision&&(this.value instanceof Float64Array?n[`${e}64Low`]=n[e]:n[`${e}64Low`]=new Float32Array(this.size)),n}_getBufferLayout(e=this.id,i=null){const n=this.getAccessor(),r=[],s={name:this.id,byteStride:Ut(n)};if(this.doublePrecision){const o=d2(n,i||{});r.push(nr(e,{...n,...o.high},this.device.type),nr(`${e}64Low`,{...n,...o.low},this.device.type))}else if(i){const o=Ho(n,i);r.push(nr(e,{...n,...o},this.device.type))}else r.push(nr(e,n,this.device.type));return s.attributes=r.filter(Boolean),s}setAccessor(e){this.state.bufferAccessor=e}getAccessor(){return this.state.bufferAccessor}getBounds(){if(this.state.bounds)return this.state.bounds;let e=null;if(this.state.constant&&this.value){const i=Array.from(this.value);e=[i,i]}else{const{value:i,numInstances:n,size:r}=this,s=n*r;if(i&&s&&i.length>=s){const o=new Array(r).fill(1/0),a=new Array(r).fill(-1/0);for(let c=0;ca[l]&&(a[l]=f)}e=[o,a]}}return this.state.bounds=e,e}setData(e){const{state:i}=this;let n;ArrayBuffer.isView(e)?n={value:e}:e instanceof q?n={buffer:e}:n=e;const r={...this.settings,...n};if(ArrayBuffer.isView(n.value)){if(!n.type)if(this.doublePrecision&&n.value instanceof Float64Array)r.type="float32";else{const o=u2(n.value);r.type=r.normalized?o.replace("int","norm"):o}r.bytesPerElement=n.value.BYTES_PER_ELEMENT,r.stride=Ut(r)}if(i.bounds=null,n.constant){let s=n.value;if(s=this._normalizeValue(s,[],0),this.settings.normalized&&(s=this.normalizeConstant(s)),!(!i.constant||!this._areValuesEqual(s,this.value)))return!1;i.externalBuffer=null,i.constant=!0,this.value=ArrayBuffer.isView(s)?s:new Float32Array(s)}else if(n.buffer){const s=n.buffer;i.externalBuffer=s,i.constant=!1,this.value=n.value||null}else if(n.value){this._checkExternalBuffer(n);let s=n.value;i.externalBuffer=null,i.constant=!1,this.value=s;let{buffer:o}=this;const a=Ut(r),c=(r.vertexOffset||0)*a;if(this.doublePrecision&&s instanceof Float64Array&&(s=ks(s,r)),this.settings.isIndexed){const f=this.settings.defaultType;s.constructor!==f&&(s=new f(s))}const l=s.byteLength+c+a*2;(!o||o.byteLength(i+128)/255*2-1);case"snorm16":return new Float32Array(e).map(i=>(i+32768)/65535*2-1);case"unorm8":return new Float32Array(e).map(i=>i/255);case"unorm16":return new Float32Array(e).map(i=>i/65535);default:return e}}_normalizeValue(e,i,n){const{defaultValue:r,size:s}=this.settings;if(Number.isFinite(e))return i[n]=e,i;if(!e){let o=s;for(;--o>=0;)i[n+o]=r[o];return i}switch(s){case 4:i[n+3]=Number.isFinite(e[3])?e[3]:r[3];case 3:i[n+2]=Number.isFinite(e[2])?e[2]:r[2];case 2:i[n+1]=Number.isFinite(e[1])?e[1]:r[1];case 1:i[n+0]=Number.isFinite(e[0])?e[0]:r[0];break;default:let o=s;for(;--o>=0;)i[n+o]=Number.isFinite(e[o])?e[o]:r[o]}return i}_areValuesEqual(e,i){if(!e||!i)return!1;const{size:n}=this;for(let r=0;r0&&(Cf.length=t.length,n=Cf):n=vf,(e>0||Number.isFinite(i))&&(n=(Array.isArray(n)?n:Array.from(n)).slice(e,i),r.index=e-1),{iterable:n,objectInfo:r}}function Dd(t){return t&&t[Symbol.asyncIterator]}function m2(t,e){const{size:i,stride:n,offset:r,startIndices:s,nested:o}=e,a=t.BYTES_PER_ELEMENT,c=n?n/a:i,l=r?r/a:0,f=Math.floor((t.length-l)/c);return(u,{index:h,target:p})=>{if(!s){const _=h*c+l;for(let y=0;y=e[1]))return t;const i=[],n=t.length;let r=0;for(let s=0;se[1]?i.push(o):e=[Math.min(o[0],e[0]),Math.max(o[1],e[1])]}return i.splice(r,0,e),i}const y2={interpolation:{duration:0,easing:t=>t},spring:{stiffness:.05,damping:.5}};function Fd(t,e){if(!t)return null;Number.isFinite(t)&&(t={type:"interpolation",duration:t});const i=t.type||"interpolation";return{...y2[i],...e,...t,type:i}}class Ud extends p2{constructor(e,i){super(e,i,{startIndices:null,lastExternalBuffer:null,binaryValue:null,binaryAccessor:null,needsUpdate:!0,needsRedraw:!1,layoutChanged:!1,updateRanges:Ar}),this.constant=!1,this.settings.update=i.update||(i.accessor?this._autoUpdater:void 0),Object.seal(this.settings),Object.seal(this.state),this._validateAttributeUpdaters()}get startIndices(){return this.state.startIndices}set startIndices(e){this.state.startIndices=e}needsUpdate(){return this.state.needsUpdate}needsRedraw({clearChangedFlags:e=!1}={}){const i=this.state.needsRedraw;return this.state.needsRedraw=i&&!e,i}layoutChanged(){return this.state.layoutChanged}setAccessor(e){var i;(i=this.state).layoutChanged||(i.layoutChanged=!h2(e,this.getAccessor())),super.setAccessor(e)}getUpdateTriggers(){const{accessor:e}=this.settings;return[this.id].concat(typeof e!="function"&&e||[])}supportsTransition(){return!!this.settings.transition}getTransitionSetting(e){if(!e||!this.supportsTransition())return null;const{accessor:i}=this.settings,n=this.settings.transition,r=Array.isArray(i)?e[i.find(s=>e[s])]:e[i];return Fd(r,n)}setNeedsUpdate(e=this.id,i){if(this.state.needsUpdate=this.state.needsUpdate||e,this.setNeedsRedraw(e),i){const{startRow:n=0,endRow:r=1/0}=i;this.state.updateRanges=A2(this.state.updateRanges,[n,r])}else this.state.updateRanges=Ar}clearNeedsUpdate(){this.state.needsUpdate=!1,this.state.updateRanges=_2}setNeedsRedraw(e=this.id){this.state.needsRedraw=this.state.needsRedraw||e}allocate(e){const{state:i,settings:n}=this;return n.noAlloc?!1:n.update?(super.allocate(e,i.updateRanges!==Ar),!0):!1}updateBuffer({numInstances:e,data:i,props:n,context:r}){if(!this.needsUpdate())return!1;const{state:{updateRanges:s},settings:{update:o,noAlloc:a}}=this;let c=!0;if(o){for(const[l,f]of s)o.call(r,this,{data:i,startRow:l,endRow:f,props:n,numInstances:e});if(this.value)if(this.constant||!this.buffer||this.buffer.byteLengthf?l.set(A,m):(e._normalizeValue(A,_.target,0),vE({target:l,source:_.target,start:m,count:b}));m+=b*f}else e._normalizeValue(A,l,m),m+=f}}_validateAttributeUpdaters(){const{settings:e}=this;if(!(e.noAlloc||typeof e.update=="function"))throw new Error(`Attribute ${this.id} missing update or accessor`)}_checkAttributeArray(){const{value:e}=this,i=Math.min(4,this.size);if(e&&e.length>=i){let n=!0;switch(i){case 4:n=n&&Number.isFinite(e[3]);case 3:n=n&&Number.isFinite(e[2]);case 2:n=n&&Number.isFinite(e[1]);case 1:n=n&&Number.isFinite(e[0]);break;default:n=!1}if(!n)throw new Error(`Illegal attribute generated for ${this.id}`)}}}function eo(t){const{source:e,target:i,start:n=0,size:r,getData:s}=t,o=t.end||i.length,a=e.length,c=o-n;if(a>c){i.set(e.subarray(0,c),n);return}if(i.set(e,n),!s)return;let l=a;for(;ln(f+a,u)),l=Math.min(r.length,s.length);for(let f=1;fa}){const a=i.doublePrecision&&i.value instanceof Float64Array?2:1,c=i.size*a,l=i.byteOffset,f=i.settings.bytesPerElement<4?l/i.settings.bytesPerElement*4:l,u=i.startIndices,h=s&&u,p=i.isConstant;if(!h&&e&&n>=r)return e;const d=i.value instanceof Float64Array?Float32Array:i.value.constructor,m=p?i.value:new d(i.getBuffer().readSyncWebGL(l,r*d.BYTES_PER_ELEMENT).buffer);if(i.settings.normalized&&!p){const A=o;o=(b,T)=>i.normalizeConstant(A(b,T))}const g=p?(A,b)=>o(m,b):(A,b)=>o(m.subarray(A+l,A+l+c),b),_=e?new Float32Array(e.readSyncWebGL(f,n*4).buffer):new Float32Array(0),y=new Float32Array(r);return b2({source:_,target:y,sourceStartIndices:s,targetStartIndices:u,size:c,getData:g}),(!e||e.byteLength0||r.end()}delete(){super.delete(),this.transform.destroy(),this.texture.destroy(),this.framebuffer.destroy()}}const I2=`layout(std140) uniform springUniforms { float damping; float stiffness; } spring; `,x2={name:"spring",vs:I2,uniformTypes:{damping:"f32",stiffness:"f32"}},M2=`#version 300 es #define SHADER_NAME spring-transition-vertex-shader #define EPSILON 0.00001 in ATTRIBUTE_TYPE aPrev; in ATTRIBUTE_TYPE aCur; in ATTRIBUTE_TYPE aTo; out ATTRIBUTE_TYPE vNext; out float vIsTransitioningFlag; ATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) { ATTRIBUTE_TYPE velocity = cur - prev; ATTRIBUTE_TYPE delta = dest - cur; ATTRIBUTE_TYPE force = delta * spring.stiffness; ATTRIBUTE_TYPE resistance = velocity * spring.damping; return force - resistance + velocity + cur; } void main(void) { bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON; vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0; vNext = getNextValue(aCur, aPrev, aTo); gl_Position = vec4(0, 0, 0, 1); gl_PointSize = 100.0; } `,O2=`#version 300 es #define SHADER_NAME spring-transition-is-transitioning-fragment-shader in float vIsTransitioningFlag; out vec4 fragColor; void main(void) { if (vIsTransitioningFlag == 0.0) { discard; } fragColor = vec4(1.0); }`;function B2(t,e){const i=kd(e.size),n=Ld(e.size);return new Ni(t,{vs:M2,fs:O2,bufferLayout:[{name:"aPrev",format:n},{name:"aCur",format:n},{name:"aTo",format:e.getBufferLayout().attributes[0].format}],varyings:["vNext"],modules:[x2],defines:{ATTRIBUTE_TYPE:i},parameters:{depthCompare:"always",blendColorOperation:"max",blendColorSrcFactor:"one",blendColorDstFactor:"one",blendAlphaOperation:"max",blendAlphaSrcFactor:"one",blendAlphaDstFactor:"one"}})}function N2(t){return t.createTexture({data:new Uint8Array(4),format:"rgba8unorm",width:1,height:1})}function D2(t,e){return t.createFramebuffer({id:"spring-transition-is-transitioning-framebuffer",width:1,height:1,colorAttachments:[e]})}const F2={interpolation:E2,spring:P2};class U2{constructor(e,{id:i,timeline:n}){if(!e)throw new Error("AttributeTransitionManager is constructed without device");this.id=i,this.device=e,this.timeline=n,this.transitions={},this.needsRedraw=!1,this.numInstances=1}finalize(){for(const e in this.transitions)this._removeTransition(e)}update({attributes:e,transitions:i,numInstances:n}){this.numInstances=n||1;for(const r in e){const s=e[r],o=s.getTransitionSetting(i);o&&this._updateAttribute(r,s,o)}for(const r in this.transitions){const s=e[r];(!s||!s.getTransitionSetting(i))&&this._removeTransition(r)}}hasAttribute(e){const i=this.transitions[e];return i&&i.inProgress}getAttributes(){const e={};for(const i in this.transitions){const n=this.transitions[i];n.inProgress&&(e[i]=n.attributeInTransition)}return e}run(){if(this.numInstances===0)return!1;for(const i in this.transitions)this.transitions[i].update()&&(this.needsRedraw=!0);const e=this.needsRedraw;return this.needsRedraw=!1,e}_removeTransition(e){this.transitions[e].delete(),delete this.transitions[e]}_updateAttribute(e,i,n){const r=this.transitions[e];let s=!r||r.type!==n.type;if(s){r&&this._removeTransition(e);const o=F2[n.type];o?this.transitions[e]=new o({attribute:i,timeline:this.timeline,device:this.device}):(J.error(`unsupported transition type '${n.type}'`)(),s=!1)}(s||i.needsRedraw())&&(this.needsRedraw=!0,this.transitions[e].start(n,this.numInstances))}}const If="attributeManager.invalidate",k2="attributeManager.updateStart",L2="attributeManager.updateEnd",W2="attribute.updateStart",V2="attribute.allocate",z2="attribute.updateEnd";class j2{constructor(e,{id:i="attribute-manager",stats:n,timeline:r}={}){this.mergeBoundsMemoized=Pn(FT),this.id=i,this.device=e,this.attributes={},this.updateTriggers={},this.needsRedraw=!0,this.userData={},this.stats=n,this.attributeTransitionManager=new U2(e,{id:`${i}-transitions`,timeline:r}),Object.seal(this)}finalize(){for(const e in this.attributes)this.attributes[e].delete();this.attributeTransitionManager.finalize()}getNeedsRedraw(e={clearRedrawFlags:!1}){const i=this.needsRedraw;return this.needsRedraw=this.needsRedraw&&!e.clearRedrawFlags,i&&this.id}setNeedsRedraw(){this.needsRedraw=!0}add(e){this._add(e)}addInstanced(e){this._add(e,{stepMode:"instance"})}remove(e){for(const i of e)this.attributes[i]!==void 0&&(this.attributes[i].delete(),delete this.attributes[i])}invalidate(e,i){const n=this._invalidateTrigger(e,i);be(If,this,e,n)}invalidateAll(e){for(const i in this.attributes)this.attributes[i].setNeedsUpdate(i,e);be(If,this,"all")}update({data:e,numInstances:i,startIndices:n=null,transitions:r,props:s={},buffers:o={},context:a={}}){let c=!1;be(k2,this),this.stats&&this.stats.get("Update Attributes").timeStart();for(const l in this.attributes){const f=this.attributes[l],u=f.settings.accessor;f.startIndices=n,f.numInstances=i,s[l]&&J.removed(`props.${l}`,`data.attributes.${l}`)(),f.setExternalBuffer(o[l])||f.setBinaryValue(typeof u=="string"?o[u]:void 0,e.startIndices)||typeof u=="string"&&!o[u]&&f.setConstantValue(a,s[u])||f.needsUpdate()&&(c=!0,this._updateAttribute({attribute:f,numInstances:i,data:e,props:s,context:a})),this.needsRedraw=this.needsRedraw||f.needsRedraw()}c&&be(L2,this,i),this.stats&&(this.stats.get("Update Attributes").timeEnd(),c&&this.stats.get("Attributes updated").incrementCount()),this.attributeTransitionManager.update({attributes:this.attributes,numInstances:i,transitions:r})}updateTransition(){const{attributeTransitionManager:e}=this,i=e.run();return this.needsRedraw=this.needsRedraw||i,i}getAttributes(){return{...this.attributes,...this.attributeTransitionManager.getAttributes()}}getBounds(e){const i=e.map(n=>this.attributes[n]?.getBounds());return this.mergeBoundsMemoized(i)}getChangedAttributes(e={clearChangedFlags:!1}){const{attributes:i,attributeTransitionManager:n}=this,r={...n.getAttributes()};for(const s in i){const o=i[s];o.needsRedraw(e)&&!n.hasAttribute(s)&&(r[s]=o)}return r}getBufferLayouts(e){return Object.values(this.getAttributes()).map(i=>i.getBufferLayout(e))}_add(e,i){for(const n in e){const r=e[n],s={...r,id:n,size:r.isIndexed&&1||r.size||1,...i};this.attributes[n]=new Ud(this.device,s)}this._mapUpdateTriggersToAttributes()}_mapUpdateTriggersToAttributes(){const e={};for(const i in this.attributes)this.attributes[i].getUpdateTriggers().forEach(r=>{e[r]||(e[r]=[]),e[r].push(i)});this.updateTriggers=e}_invalidateTrigger(e,i){const{attributes:n,updateTriggers:r}=this,s=r[e];return s&&s.forEach(o=>{const a=n[o];a&&a.setNeedsUpdate(a.id,i)}),s}_updateAttribute(e){const{attribute:i,numInstances:n}=e;if(be(W2,i),i.constant){i.setConstantValue(e.context,i.value);return}i.allocate(n)&&be(V2,i,n),i.updateBuffer(e)&&(this.needsRedraw=!0,be(z2,i,n))}}class H2 extends rs{get value(){return this._value}_onUpdate(){const{time:e,settings:{fromValue:i,toValue:n,duration:r,easing:s}}=this,o=s(e/r);this._value=Mr(i,n,o)}}const xf=1e-5;function Mf(t,e,i,n,r){const s=e-t,a=(i-e)*r,c=-s*n;return a+c+s+e}function Y2(t,e,i,n,r){if(Array.isArray(i)){const s=[];for(let o=0;o0}add(e,i,n,r){const{transitions:s}=this;if(s.has(e)){const c=s.get(e),{value:l=c.settings.fromValue}=c;i=l,this.remove(e)}if(r=Fd(r),!r)return;const o=Q2[r.type];if(!o){J.error(`unsupported transition type '${r.type}'`)();return}const a=new o(this.timeline);a.start({...r,fromValue:i,toValue:n}),s.set(e,a)}remove(e){const{transitions:i}=this;i.has(e)&&(i.get(e).cancel(),i.delete(e))}update(){const e={};for(const[i,n]of this.transitions)n.update(),e[i]=n.value,n.inProgress||this.remove(i);return e}clear(){for(const e of this.transitions.keys())this.remove(e)}}function q2(t){const e=t[zt];for(const i in e){const n=e[i],{validate:r}=n;if(r&&!r(t[i],n))throw new Error(`Invalid prop ${i}: ${t[i]}`)}}function Z2(t,e){const i=Yd({newProps:t,oldProps:e,propTypes:t[zt],ignoreProps:{data:null,updateTriggers:null,extensions:null,transitions:null}}),n=J2(t,e);let r=!1;return n||(r=$2(t,e)),{dataChanged:n,propsChanged:i,updateTriggersChanged:r,extensionsChanged:eS(t,e),transitionsChanged:G2(t,e)}}function G2(t,e){if(!t.transitions)return!1;const i={},n=t[zt];let r=!1;for(const s in t.transitions){const o=n[s],a=o&&o.type;(a==="number"||a==="color"||a==="array")&&Yo(t[s],e[s],o)&&(i[s]=!0,r=!0)}return r?i:!1}function Yd({newProps:t,oldProps:e,ignoreProps:i={},propTypes:n={},triggerName:r="props"}){if(e===t)return!1;if(typeof t!="object"||t===null)return`${r} changed shallowly`;if(typeof e!="object"||e===null)return`${r} changed shallowly`;for(const s of Object.keys(t))if(!(s in i)){if(!(s in e))return`${r}.${s} added`;const o=Yo(t[s],e[s],n[s]);if(o)return`${r}.${s} ${o}`}for(const s of Object.keys(e))if(!(s in i)){if(!(s in t))return`${r}.${s} dropped`;if(!Object.hasOwnProperty.call(t,s)){const o=Yo(t[s],e[s],n[s]);if(o)return`${r}.${s} ${o}`}}return!1}function Yo(t,e,i){let n=i&&i.equal;return n&&!n(t,e,i)||!n&&(n=t&&e&&t.equals,n&&!n.call(t,e))?"changed deeply":!n&&e!==t?"changed shallowly":null}function J2(t,e){if(e===null)return"oldProps is null, initial diff";let i=!1;const{dataComparator:n,_dataDiff:r}=t;return n?n(t.data,e.data)||(i="Data comparator detected a change"):t.data!==e.data&&(i="A new data container was supplied"),i&&r&&(i=r(t.data,e.data)||i),i}function $2(t,e){if(e===null)return{all:!0};if("all"in t.updateTriggers&&Bf(t,e,"all"))return{all:!0};const i={};let n=!1;for(const r in t.updateTriggers)r!=="all"&&Bf(t,e,r)&&(i[r]=!0,n=!0);return n?i:!1}function eS(t,e){if(e===null)return!0;const i=e.extensions,{extensions:n}=t;if(n===i)return!1;if(!i||!n||n.length!==i.length)return!0;for(let r=0;rn.name==="project64"))){const n=i.modules.findIndex(r=>r.name==="project32");n>=0&&i.modules.splice(n,1)}if("inject"in e)if(!t.inject)i.inject=e.inject;else{const n={...t.inject};for(const r in e.inject)n[r]=(n[r]||"")+e.inject[r];i.inject=n}return i}const oS={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},Xo={};function aS(t,e,i,n){if(i instanceof Y)return i;i.constructor&&i.constructor.name!=="Object"&&(i={data:i});let r=null;i.compressed&&(r={minFilter:"linear",mipmapFilter:i.data.length>1?"nearest":"linear"});const{width:s,height:o}=i.data,a=e.createTexture({...i,sampler:{...oS,...r,...n},mipLevels:e.getMipLevelCount(s,o)});return e.type==="webgl"?a.generateMipmapsWebGL():e.type==="webgpu"&&e.generateMipmapsWebGPU(a),Xo[a.id]=t,a}function cS(t,e){!e||!(e instanceof Y)||Xo[e.id]===t&&(e.delete(),delete Xo[e.id])}const lS={boolean:{validate(t,e){return!0},equal(t,e,i){return!!t==!!e}},number:{validate(t,e){return Number.isFinite(t)&&(!("max"in e)||t<=e.max)&&(!("min"in e)||t>=e.min)}},color:{validate(t,e){return e.optional&&!t||Qo(t)&&(t.length===3||t.length===4)},equal(t,e,i){return Me(t,e,1)}},accessor:{validate(t,e){const i=Vr(t);return i==="function"||i===Vr(e.value)},equal(t,e,i){return typeof e=="function"?!0:Me(t,e,1)}},array:{validate(t,e){return e.optional&&!t||Qo(t)},equal(t,e,i){const{compare:n}=i,r=Number.isInteger(n)?n:n?1:0;return n?Me(t,e,r):t===e}},object:{equal(t,e,i){if(i.ignore)return!0;const{compare:n}=i,r=Number.isInteger(n)?n:n?1:0;return n?Me(t,e,r):t===e}},function:{validate(t,e){return e.optional&&!t||typeof t=="function"},equal(t,e,i){return!i.compare&&i.ignore!==!1||t===e}},data:{transform:(t,e,i)=>{if(!t)return t;const{dataTransform:n}=i.props;return n?n(t):typeof t.shape=="string"&&t.shape.endsWith("-table")&&Array.isArray(t.data)?t.data:t}},image:{transform:(t,e,i)=>{const n=i.context;return!n||!n.device?null:aS(i.id,n.device,t,{...e.parameters,...i.props.textureParameters})},release:(t,e,i)=>{cS(i.id,t)}}};function fS(t){const e={},i={},n={};for(const[r,s]of Object.entries(t)){const o=s?.deprecatedFor;if(o)n[r]=Array.isArray(o)?o:[o];else{const a=uS(r,s);e[r]=a,i[r]=a.value}}return{propTypes:e,defaultProps:i,deprecatedProps:n}}function uS(t,e){switch(Vr(e)){case"object":return Qi(t,e);case"array":return Qi(t,{type:"array",value:e,compare:!1});case"boolean":return Qi(t,{type:"boolean",value:e});case"number":return Qi(t,{type:"number",value:e});case"function":return Qi(t,{type:"function",value:e,compare:!0});default:return{name:t,type:"unknown",value:e}}}function Qi(t,e){return"type"in e?{name:t,...lS[e.type],...e}:"value"in e?{name:t,type:Vr(e.value),...e}:{name:t,type:"object",value:e}}function Qo(t){return Array.isArray(t)||ArrayBuffer.isView(t)}function Vr(t){return Qo(t)?"array":t===null?"null":typeof t}function hS(t,e){let i;for(let s=e.length-1;s>=0;s--){const o=e[s];"extensions"in o&&(i=o.extensions)}const n=Ko(t.constructor,i),r=Object.create(n);r[Lr]=t,r[Jt]={},r[Tt]={};for(let s=0;s{},this.oldProps=null,this.oldAsyncProps=null}finalize(){for(const e in this.asyncProps){const i=this.asyncProps[e];i&&i.type&&i.type.release&&i.type.release(i.resolvedValue,i.type,this.component)}this.asyncProps={},this.component=null,this.resetOldProps()}getOldProps(){return this.oldAsyncProps||this.oldProps||wS}resetOldProps(){this.oldAsyncProps=null,this.oldProps=this.component?this.component.props:null}hasAsyncProp(e){return e in this.asyncProps}getAsyncProp(e){const i=this.asyncProps[e];return i&&i.resolvedValue}isAsyncPropLoading(e){if(e){const i=this.asyncProps[e];return!!(i&&i.pendingLoadCount>0&&i.pendingLoadCount!==i.resolvedLoadCount)}for(const i in this.asyncProps)if(this.isAsyncPropLoading(i))return!0;return!1}reloadAsyncProp(e,i){this._watchPromise(e,Promise.resolve(i))}setAsyncProps(e){this.component=e[Lr]||this.component;const i=e[Tt]||{},n=e[Jt]||e,r=e[Si]||{};for(const s in i){const o=i[s];this._createAsyncPropData(s,r[s]),this._updateAsyncProp(s,o),i[s]=this.getAsyncProp(s)}for(const s in n){const o=n[s];this._createAsyncPropData(s,r[s]),this._updateAsyncProp(s,o)}}_fetch(e,i){return null}_onResolve(e,i){}_onError(e,i){}_updateAsyncProp(e,i){if(this._didAsyncInputValueChange(e,i)){if(typeof i=="string"&&(i=this._fetch(e,i)),i instanceof Promise){this._watchPromise(e,i);return}if(Dd(i)){this._resolveAsyncIterable(e,i);return}this._setPropValue(e,i)}}_freezeAsyncOldProps(){if(!this.oldAsyncProps&&this.oldProps){this.oldAsyncProps=Object.create(this.oldProps);for(const e in this.asyncProps)Object.defineProperty(this.oldAsyncProps,e,{enumerable:!0,value:this.oldProps[e]})}}_didAsyncInputValueChange(e,i){const n=this.asyncProps[e];return i===n.resolvedValue||i===n.lastValue?!1:(n.lastValue=i,!0)}_setPropValue(e,i){this._freezeAsyncOldProps();const n=this.asyncProps[e];n&&(i=this._postProcessValue(n,i),n.resolvedValue=i,n.pendingLoadCount++,n.resolvedLoadCount=n.pendingLoadCount)}_setAsyncPropValue(e,i,n){const r=this.asyncProps[e];r&&n>=r.resolvedLoadCount&&i!==void 0&&(this._freezeAsyncOldProps(),r.resolvedValue=i,r.resolvedLoadCount=n,this.onAsyncPropUpdated(e,i))}_watchPromise(e,i){const n=this.asyncProps[e];if(n){n.pendingLoadCount++;const r=n.pendingLoadCount;i.then(s=>{this.component&&(s=this._postProcessValue(n,s),this._setAsyncPropValue(e,s,r),this._onResolve(e,s))}).catch(s=>{this._onError(e,s)})}}async _resolveAsyncIterable(e,i){if(e!=="data"){this._setPropValue(e,i);return}const n=this.asyncProps[e];if(!n)return;n.pendingLoadCount++;const r=n.pendingLoadCount;let s=[],o=0;for await(const a of i){if(!this.component)return;const{dataTransform:c}=this.component.props;c?s=c(a,s):s=s.concat(a),Object.defineProperty(s,"__diff",{enumerable:!1,value:[{startRow:o,endRow:s.length}]}),o=s.length,this._setAsyncPropValue(e,s,r)}this._onResolve(e,s)}_postProcessValue(e,i){const n=e.type;return n&&this.component&&(n.release&&n.release(e.resolvedValue,n,this.component),n.transform)?n.transform(i,n,this.component):i}_createAsyncPropData(e,i){if(!this.asyncProps[e]){const r=this.component&&this.component.props[zt];this.asyncProps[e]={type:r&&r[e],lastValue:null,resolvedValue:i,pendingLoadCount:0,resolvedLoadCount:0}}}}class ES extends TS{constructor({attributeManager:e,layer:i}){super(i),this.attributeManager=e,this.needsRedraw=!0,this.needsUpdate=!0,this.subLayers=null,this.usesPickingColorCache=!1}get layer(){return this.component}_fetch(e,i){const n=this.layer,r=n?.props.fetch;return r?r(i,{propName:e,layer:n}):super._fetch(e,i)}_onResolve(e,i){const n=this.layer;if(n){const r=n.props.onDataLoad;e==="data"&&r&&r(i,{propName:e,layer:n})}}_onError(e,i){const n=this.layer;n&&n.raiseError(i,`loading ${e} of ${this.layer}`)}}const SS="layer.changeFlag",RS="layer.initialize",vS="layer.update",CS="layer.finalize",PS="layer.matched",Df=2**24-1,IS=Object.freeze([]),xS=Pn(({oldViewport:t,viewport:e})=>t.equals(e));let ze=new Uint8ClampedArray(0);const MS={data:{type:"data",value:IS,async:!0},dataComparator:{type:"function",value:null,optional:!0},_dataDiff:{type:"function",value:t=>t&&t.__diff,optional:!0},dataTransform:{type:"function",value:null,optional:!0},onDataLoad:{type:"function",value:null,optional:!0},onError:{type:"function",value:null,optional:!0},fetch:{type:"function",value:(t,{propName:e,layer:i,loaders:n,loadOptions:r,signal:s})=>{const{resourceManager:o}=i.context;r=r||i.getLoadOptions(),n=n||i.props.loaders,s&&(r={...r,core:{...r?.core,fetch:{...r?.core?.fetch,signal:s}}});let a=o.contains(t);return!a&&!r&&(o.add({resourceId:t,data:po(t,n),persistent:!1}),a=!0),a?o.subscribe({resourceId:t,onChange:c=>i.internalState?.reloadAsyncProp(e,c),consumerId:i.id,requestId:e}):po(t,n,r)}},updateTriggers:{},visible:!0,pickable:!1,opacity:{type:"number",min:0,max:1,value:1},operation:"draw",onHover:{type:"function",value:null,optional:!0},onClick:{type:"function",value:null,optional:!0},onDragStart:{type:"function",value:null,optional:!0},onDrag:{type:"function",value:null,optional:!0},onDragEnd:{type:"function",value:null,optional:!0},coordinateSystem:"default",coordinateOrigin:{type:"array",value:[0,0,0],compare:!0},modelMatrix:{type:"array",value:null,compare:!0,optional:!0},wrapLongitude:!1,positionFormat:"XYZ",colorFormat:"RGBA",parameters:{type:"object",value:{},optional:!0,compare:2},loadOptions:{type:"object",value:null,optional:!0,ignore:!0},transitions:null,extensions:[],loaders:{type:"array",value:[],optional:!0,ignore:!0},getPolygonOffset:{type:"function",value:({layerIndex:t})=>[0,-t*100]},highlightedObjectIndex:null,autoHighlight:!1,highlightColor:{type:"accessor",value:[0,0,128,128]}};class tc extends os{constructor(){super(...arguments),this.internalState=null,this.lifecycle=di.NO_STATE,this.parent=null}static get componentName(){return Object.prototype.hasOwnProperty.call(this,"layerName")?this.layerName:""}get root(){let e=this;for(;e.parent;)e=e.parent;return e}toString(){return`${this.constructor.layerName||this.constructor.name}({id: '${this.props.id}'})`}project(e){pe(this.internalState);const i=this.internalState.viewport||this.context.viewport,n=Ha(e,{viewport:i,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem}),[r,s,o]=Kh(n,i.pixelProjectionMatrix);return e.length===2?[r,s]:[r,s,o]}unproject(e){return pe(this.internalState),(this.internalState.viewport||this.context.viewport).unproject(e)}projectPosition(e,i){pe(this.internalState);const n=this.internalState.viewport||this.context.viewport;return zT(e,{viewport:n,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem,...i})}get isComposite(){return!1}get isDrawable(){return!0}setState(e){this.setChangeFlags({stateChanged:!0}),Object.assign(this.state,e),this.setNeedsRedraw()}setNeedsRedraw(){this.internalState&&(this.internalState.needsRedraw=!0)}setNeedsUpdate(){this.internalState&&(this.context.layerManager.setNeedsUpdate(String(this)),this.internalState.needsUpdate=!0)}get isLoaded(){return this.internalState?!this.internalState.isAsyncPropLoading():!1}get wrapLongitude(){return this.props.wrapLongitude}isPickable(){return this.props.pickable&&this.props.visible}getModels(){const e=this.state;return e&&(e.models||e.model&&[e.model])||[]}setShaderModuleProps(...e){for(const i of this.getModels())i.shaderInputs.setProps(...e)}getAttributeManager(){return this.internalState&&this.internalState.attributeManager}getCurrentLayer(){return this.internalState&&this.internalState.layer}getLoadOptions(){return this.props.loadOptions}use64bitPositions(){const{coordinateSystem:e}=this.props;return e==="default"||e==="lnglat"||e==="cartesian"}onHover(e,i){return this.props.onHover&&this.props.onHover(e,i)||!1}onClick(e,i){return this.props.onClick&&this.props.onClick(e,i)||!1}nullPickingColor(){return[0,0,0]}encodePickingColor(e,i=[]){return i[0]=e+1&255,i[1]=e+1>>8&255,i[2]=e+1>>8>>8&255,i}decodePickingColor(e){pe(e instanceof Uint8Array);const[i,n,r]=e;return i+n*256+r*65536-1}getNumInstances(){return Number.isFinite(this.props.numInstances)?this.props.numInstances:this.state&&this.state.numInstances!==void 0?this.state.numInstances:nS(this.props.data)}getStartIndices(){return this.props.startIndices?this.props.startIndices:this.state&&this.state.startIndices?this.state.startIndices:null}getBounds(){return this.getAttributeManager()?.getBounds(["positions","instancePositions"])}getShaders(e){e=Nf(e,{disableWarnings:!0,modules:this.context.defaultShaderModules});for(const i of this.props.extensions)e=Nf(e,i.getShaders.call(this,i));return e}shouldUpdateState(e){return e.changeFlags.propsOrDataChanged}updateState(e){const i=this.getAttributeManager(),{dataChanged:n}=e.changeFlags;if(n&&i)if(Array.isArray(n))for(const r of n)i.invalidateAll(r);else i.invalidateAll();if(i){const{props:r}=e,s=this.internalState.hasPickingBuffer,o=Number.isInteger(r.highlightedObjectIndex)||!!r.pickable||r.extensions.some(a=>a.getNeedsPickingBuffer.call(this,a));if(s!==o){this.internalState.hasPickingBuffer=o;const{pickingColors:a,instancePickingColors:c}=i.attributes,l=a||c;l&&(o&&l.constant&&(l.constant=!1,i.invalidate(l.id)),!l.value&&!o&&(l.constant=!0,l.value=[0,0,0]))}}}finalizeState(e){for(const n of this.getModels())n.destroy();const i=this.getAttributeManager();i&&i.finalize(),this.context&&this.context.resourceManager.unsubscribe({consumerId:this.id}),this.internalState&&(this.internalState.uniformTransitions.clear(),this.internalState.finalize())}draw(e){for(const i of this.getModels())i.draw(e.renderPass)}getPickingInfo({info:e,mode:i,sourceLayer:n}){const{index:r}=e;return r>=0&&Array.isArray(this.props.data)&&(e.object=this.props.data[r]),e}raiseError(e,i){i&&(e=new Error(`${i}: ${e.message}`,{cause:e})),this.props.onError?.(e)||this.context?.onError?.(e,this)}getNeedsRedraw(e={clearRedrawFlags:!1}){return this._getNeedsRedraw(e)}needsUpdate(){return this.internalState?this.internalState.needsUpdate||this.hasUniformTransition()||this.shouldUpdateState(this._getUpdateParams()):!1}hasUniformTransition(){return this.internalState?.uniformTransitions.active||!1}activateViewport(e){if(!this.internalState)return;const i=this.internalState.viewport;this.internalState.viewport=e,(!i||!xS({oldViewport:i,viewport:e}))&&(this.setChangeFlags({viewportChanged:!0}),this.isComposite?this.needsUpdate()&&this.setNeedsUpdate():this._update())}invalidateAttribute(e="all"){const i=this.getAttributeManager();i&&(e==="all"?i.invalidateAll():i.invalidate(e))}updateAttributes(e){let i=!1;for(const n in e)e[n].layoutChanged()&&(i=!0);for(const n of this.getModels())this._setModelAttributes(n,e,i)}_updateAttributes(){const e=this.getAttributeManager();if(!e)return;const i=this.props,n=this.getNumInstances(),r=this.getStartIndices();e.update({data:i.data,numInstances:n,startIndices:r,props:i,transitions:i.transitions,buffers:i.data.attributes,context:this});const s=e.getChangedAttributes({clearChangedFlags:!0});this.updateAttributes(s)}_updateAttributeTransition(){const e=this.getAttributeManager();e&&e.updateTransition()}_updateUniformTransition(){const{uniformTransitions:e}=this.internalState;if(e.active){const i=e.update(),n=Object.create(this.props);for(const r in i)Object.defineProperty(n,r,{value:i[r]});return n}return this.props}calculateInstancePickingColors(e,{numInstances:i}){if(e.constant)return;const n=Math.floor(ze.length/4);if(this.internalState.usesPickingColorCache=!0,nDf&&J.warn("Layer has too many data objects. Picking might not be able to distinguish all objects.")(),ze=An.allocate(ze,i,{size:4,copy:!0,maxCount:Math.max(i,Df)});const r=Math.floor(ze.length/4),s=[0,0,0];for(let o=n;o(J.deprecated("layer.state.attributeManager","layer.getAttributeManager()")(),e)}),this.internalState.uniformTransitions=new K2(this.context.timeline),this.internalState.onAsyncPropUpdated=this._onAsyncPropUpdated.bind(this),this.internalState.setAsyncProps(this.props),this.initializeState(this.context);for(const i of this.props.extensions)i.initializeState.call(this,this.context,i);this.setChangeFlags({dataChanged:"init",propsChanged:"init",viewportChanged:!0,extensionsChanged:!0}),this._update()}_transferState(e){be(PS,this,this===e);const{state:i,internalState:n}=e;this!==e&&(this.internalState=n,this.state=i,this.internalState.setAsyncProps(this.props),this._diffProps(this.props,this.internalState.getOldProps()))}_update(){const e=this.needsUpdate();if(be(vS,this,e),!e)return;this.context.stats.get("Layer updates").incrementCount();const i=this.props,n=this.context,r=this.internalState,s=n.viewport,o=this._updateUniformTransition();r.propsInTransition=o,n.viewport=r.viewport||s,this.props=o;try{const a=this._getUpdateParams(),c=this.getModels();if(n.device)this.updateState(a);else try{this.updateState(a)}catch{}for(const f of this.props.extensions)f.updateState.call(this,a,f);this.setNeedsRedraw(),this._updateAttributes();const l=this.getModels()[0]!==c[0];this._postUpdate(a,l)}finally{n.viewport=s,this.props=i,this._clearChangeFlags(),r.needsUpdate=!1,r.resetOldProps()}}_finalize(){be(CS,this),this.finalizeState(this.context);for(const e of this.props.extensions)e.finalizeState.call(this,this.context,e)}_drawLayer({renderPass:e,shaderModuleProps:i=null,uniforms:n={},parameters:r={}}){this._updateAttributeTransition();const s=this.props,o=this.context;this.props=this.internalState.propsInTransition||s;try{i&&this.setShaderModuleProps(i);const{getPolygonOffset:a}=this.props,c=a&&a(n)||[0,0];o.device instanceof Yt&&o.device.setParametersWebGL({polygonOffset:c});const l=o.device instanceof Yt?null:OS(r);if(BS(this.getModels(),e,r,l),o.device instanceof Yt)o.device.withParametersWebGL(r,()=>{const f={renderPass:e,shaderModuleProps:i,uniforms:n,parameters:r,context:o};for(const u of this.props.extensions)u.draw.call(this,f,u);this.draw(f)});else{l?.renderPassParameters&&e.setParameters(l.renderPassParameters);const f={renderPass:e,shaderModuleProps:i,uniforms:n,parameters:r,context:o};for(const u of this.props.extensions)u.draw.call(this,f,u);this.draw(f)}}finally{this.props=s}}getChangeFlags(){return this.internalState?.changeFlags}setChangeFlags(e){if(!this.internalState)return;const{changeFlags:i}=this.internalState;for(const r in e)if(e[r]){let s=!1;switch(r){case"dataChanged":const o=e[r],a=i[r];o&&Array.isArray(a)&&(i.dataChanged=Array.isArray(o)?a.concat(o):o,s=!0);default:i[r]||(i[r]=e[r],s=!0)}s&&be(SS,this,r,e)}const n=!!(i.dataChanged||i.updateTriggersChanged||i.propsChanged||i.extensionsChanged);i.propsOrDataChanged=n,i.somethingChanged=n||i.viewportChanged||i.stateChanged}_clearChangeFlags(){this.internalState.changeFlags={dataChanged:!1,propsChanged:!1,updateTriggersChanged:!1,viewportChanged:!1,stateChanged:!1,extensionsChanged:!1,propsOrDataChanged:!1,somethingChanged:!1}}_diffProps(e,i){const n=Z2(e,i);if(n.updateTriggersChanged)for(const r in n.updateTriggersChanged)n.updateTriggersChanged[r]&&this.invalidateAttribute(r);if(n.transitionsChanged)for(const r in n.transitionsChanged)this.internalState.uniformTransitions.add(r,i[r],e[r],e.transitions?.[r]);return this.setChangeFlags(n)}validateProps(){q2(this.props)}updateAutoHighlight(e){this.props.autoHighlight&&!Number.isInteger(this.props.highlightedObjectIndex)&&this._updateAutoHighlight(e)}_updateAutoHighlight(e){const i={highlightedObjectColor:e.picked?e.color:null},{highlightColor:n}=this.props;e.picked&&typeof n=="function"&&(i.highlightColor=n(e)),this.setShaderModuleProps({picking:i}),this.setNeedsRedraw()}_getAttributeManager(){const e=this.context;return new j2(e.device,{id:this.props.id,stats:e.stats,timeline:e.timeline})}_postUpdate(e,i){const{props:n,oldProps:r}=e,s=this.state.model;s?.isInstanced&&s.setInstanceCount(this.getNumInstances());const{autoHighlight:o,highlightedObjectIndex:a,highlightColor:c}=n;if(i||r.autoHighlight!==o||r.highlightedObjectIndex!==a||r.highlightColor!==c){const l={};Array.isArray(c)&&(l.highlightColor=c),(i||r.autoHighlight!==o||a!==r.highlightedObjectIndex)&&(l.highlightedObjectColor=Number.isFinite(a)&&a>=0?this.encodePickingColor(a):null),this.setShaderModuleProps({picking:l})}}_getUpdateParams(){return{props:this.props,oldProps:this.internalState.getOldProps(),context:this.context,changeFlags:this.internalState.changeFlags}}_getNeedsRedraw(e){if(!this.internalState)return!1;let i=!1;i=i||this.internalState.needsRedraw&&this.id;const n=this.getAttributeManager(),r=n?n.getNeedsRedraw(e):!1;if(i=i||r,i)for(const s of this.props.extensions)s.onNeedsRedraw.call(this,s);return this.internalState.needsRedraw=this.internalState.needsRedraw&&!e.clearRedrawFlags,i}_onAsyncPropUpdated(){this._diffProps(this.props,this.internalState.getOldProps()),this.setNeedsUpdate()}}tc.defaultProps=MS;tc.layerName="Layer";function OS(t){const{blendConstant:e,...i}=t;return e?{pipelineParameters:i,renderPassParameters:{blendConstant:e}}:{pipelineParameters:i}}function BS(t,e,i,n){for(const r of t)r.device.type==="webgpu"?(NS(r,e),r.setParameters({...r.parameters,...n?.pipelineParameters})):r.setParameters(i)}function NS(t,e){const i=e.props.framebuffer||(e.framebuffer??null);if(!i)return;const n=i.colorAttachments.map(o=>o?.texture?.format??null),r=i.depthStencilAttachment?.texture?.format,s=t;(!DS(s.props.colorAttachmentFormats,n)||s.props.depthStencilAttachmentFormat!==r)&&(s.props.colorAttachmentFormats=n,s.props.depthStencilAttachmentFormat=r,s._setPipelineNeedsUpdate("attachment formats"))}function DS(t,e){if(t===e)return!0;if(!t||!e||t.length!==e.length)return!1;for(let i=0;i0&&n.height>0){const u=a[0],h=a[1],p=h[0]-u[0],d=h[1]-u[1];Number.isFinite(p)&&p>0&&(c=Math.max(c,Math.log2(n.width/p)),c>s&&(c=s)),Number.isFinite(d)&&d>0&&(l=Math.max(l,Math.log2(n.height/d)),l>o&&(l=o))}switch(r){case"X":e=ge(e,c,s);break;case"Y":i=ge(i,l,o);break;default:let u=Math.min(s-e,o-i,0);u===0&&(u=Math.max(c-e,l-i,0)),u!==0&&(e+=u,i+=u)}return{zoomX:e,zoomY:i}}}class LS extends hd{constructor(){super(...arguments),this.ControllerState=kS,this.transition={transitionDuration:300,transitionInterpolator:new Xa(["target","zoomX","zoomY"])},this.dragMode="pan"}setProps(e){Object.assign(e,Kd(e)),super.setProps(e)}_onPanRotate(){return!1}}class qd extends fd{constructor(e={}){super(e)}getViewportType(){return Qd}get ControllerType(){return LS}}qd.displayName="OrthographicView";const Ff=`layout(std140) uniform scatterplotUniforms { float radiusScale; float radiusMinPixels; float radiusMaxPixels; float lineWidthScale; float lineWidthMinPixels; float lineWidthMaxPixels; float stroked; float filled; bool antialiasing; bool billboard; highp int radiusUnits; highp int lineWidthUnits; } scatterplot; `,WS={name:"scatterplot",vs:Ff,fs:Ff,source:"",uniformTypes:{radiusScale:"f32",radiusMinPixels:"f32",radiusMaxPixels:"f32",lineWidthScale:"f32",lineWidthMinPixels:"f32",lineWidthMaxPixels:"f32",stroked:"f32",filled:"f32",antialiasing:"f32",billboard:"f32",radiusUnits:"i32",lineWidthUnits:"i32"}},VS=`#version 300 es #define SHADER_NAME scatterplot-layer-vertex-shader in vec3 positions; in vec3 instancePositions; in vec3 instancePositions64Low; in float instanceRadius; in float instanceLineWidths; in vec4 instanceFillColors; in vec4 instanceLineColors; in vec3 instancePickingColors; out vec4 vFillColor; out vec4 vLineColor; out vec2 unitPosition; out float innerUnitRadius; out float outerRadiusPixels; void main(void) { geometry.worldPosition = instancePositions; outerRadiusPixels = clamp( project_size_to_pixel(scatterplot.radiusScale * instanceRadius, scatterplot.radiusUnits), scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels ); float lineWidthPixels = clamp( project_size_to_pixel(scatterplot.lineWidthScale * instanceLineWidths, scatterplot.lineWidthUnits), scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels ); outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0; float edgePadding = scatterplot.antialiasing ? (outerRadiusPixels + SMOOTH_EDGE_RADIUS) / outerRadiusPixels : 1.0; unitPosition = edgePadding * positions.xy; geometry.uv = unitPosition; geometry.pickingColor = instancePickingColors; innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / outerRadiusPixels; if (scatterplot.billboard) { gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position); DECKGL_FILTER_GL_POSITION(gl_Position, geometry); vec3 offset = edgePadding * positions * outerRadiusPixels; DECKGL_FILTER_SIZE(offset, geometry); gl_Position.xy += project_pixel_size_to_clipspace(offset.xy); } else { vec3 offset = edgePadding * positions * project_pixel_size(outerRadiusPixels); DECKGL_FILTER_SIZE(offset, geometry); gl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position); DECKGL_FILTER_GL_POSITION(gl_Position, geometry); } vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity); DECKGL_FILTER_COLOR(vFillColor, geometry); vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity); DECKGL_FILTER_COLOR(vLineColor, geometry); } `,zS=`#version 300 es #define SHADER_NAME scatterplot-layer-fragment-shader precision highp float; in vec4 vFillColor; in vec4 vLineColor; in vec2 unitPosition; in float innerUnitRadius; in float outerRadiusPixels; out vec4 fragColor; void main(void) { geometry.uv = unitPosition; float distToCenter = length(unitPosition) * outerRadiusPixels; float inCircle = scatterplot.antialiasing ? smoothedge(distToCenter, outerRadiusPixels) : step(distToCenter, outerRadiusPixels); if (inCircle == 0.0) { discard; } if (scatterplot.stroked > 0.5) { float isLine = scatterplot.antialiasing ? smoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) : step(innerUnitRadius * outerRadiusPixels, distToCenter); if (scatterplot.filled > 0.5) { fragColor = mix(vFillColor, vLineColor, isLine); } else { if (isLine == 0.0) { discard; } fragColor = vec4(vLineColor.rgb, vLineColor.a * isLine); } } else if (scatterplot.filled < 0.5) { discard; } else { fragColor = vFillColor; } fragColor.a *= inCircle; DECKGL_FILTER_COLOR(fragColor, geometry); } `,jS=`// Main shaders struct ScatterplotUniforms { radiusScale: f32, radiusMinPixels: f32, radiusMaxPixels: f32, lineWidthScale: f32, lineWidthMinPixels: f32, lineWidthMaxPixels: f32, stroked: f32, filled: i32, antialiasing: i32, billboard: i32, radiusUnits: i32, lineWidthUnits: i32, }; struct ConstantAttributeUniforms { instancePositions: vec3, instancePositions64Low: vec3, instanceRadius: f32, instanceLineWidths: f32, instanceFillColors: vec4, instanceLineColors: vec4, instancePickingColors: vec3, instancePositionsConstant: i32, instancePositions64LowConstant: i32, instanceRadiusConstant: i32, instanceLineWidthsConstant: i32, instanceFillColorsConstant: i32, instanceLineColorsConstant: i32, instancePickingColorsConstant: i32 }; @group(0) @binding(0) var scatterplot: ScatterplotUniforms; struct ConstantAttributes { instancePositions: vec3, instancePositions64Low: vec3, instanceRadius: f32, instanceLineWidths: f32, instanceFillColors: vec4, instanceLineColors: vec4, instancePickingColors: vec3 }; const constants = ConstantAttributes( vec3(0.0), vec3(0.0), 0.0, 0.0, vec4(0.0, 0.0, 0.0, 1.0), vec4(0.0, 0.0, 0.0, 1.0), vec3(0.0) ); struct Attributes { @builtin(instance_index) instanceIndex : u32, @builtin(vertex_index) vertexIndex : u32, @location(0) positions: vec3, @location(1) instancePositions: vec3, @location(2) instancePositions64Low: vec3, @location(3) instanceRadius: f32, @location(4) instanceLineWidths: f32, @location(5) instanceFillColors: vec4, @location(6) instanceLineColors: vec4, @location(7) instancePickingColors: vec3, }; struct Varyings { @builtin(position) position: vec4, @location(0) vFillColor: vec4, @location(1) vLineColor: vec4, @location(2) unitPosition: vec2, @location(3) innerUnitRadius: f32, @location(4) outerRadiusPixels: f32, @location(5) pickingColor: vec3, }; @vertex fn vertexMain(attributes: Attributes) -> Varyings { var varyings: Varyings; // Draw an inline geometry constant array clip space triangle to verify that rendering works. // var positions = array, 3>(vec2(0.0, 0.5), vec2(-0.5, -0.5), vec2(0.5, -0.5)); // if (attributes.instanceIndex == 0) { // varyings.position = vec4(positions[attributes.vertexIndex], 0.0, 1.0); // return varyings; // } geometry.worldPosition = attributes.instancePositions; // Multiply out radius and clamp to limits varyings.outerRadiusPixels = clamp( project_unit_size_to_pixel(scatterplot.radiusScale * attributes.instanceRadius, scatterplot.radiusUnits), scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels ); // Multiply out line width and clamp to limits let lineWidthPixels = clamp( project_unit_size_to_pixel(scatterplot.lineWidthScale * attributes.instanceLineWidths, scatterplot.lineWidthUnits), scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels ); // outer radius needs to offset by half stroke width varyings.outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0; // Expand geometry to accommodate edge smoothing let edgePadding = select( (varyings.outerRadiusPixels + SMOOTH_EDGE_RADIUS) / varyings.outerRadiusPixels, 1.0, scatterplot.antialiasing != 0 ); // position on the containing square in [-1, 1] space varyings.unitPosition = edgePadding * attributes.positions.xy; geometry.uv = varyings.unitPosition; geometry.pickingColor = attributes.instancePickingColors; varyings.innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / varyings.outerRadiusPixels; if (scatterplot.billboard != 0) { varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, vec3(0.0)); // TODO , geometry.position); // DECKGL_FILTER_GL_POSITION(varyings.position, geometry); let offset = attributes.positions; // * edgePadding * varyings.outerRadiusPixels; // DECKGL_FILTER_SIZE(offset, geometry); let clipPixels = project_pixel_size_to_clipspace(offset.xy); varyings.position.x = clipPixels.x; varyings.position.y = clipPixels.y; } else { let offset = edgePadding * attributes.positions * project_pixel_size_float(varyings.outerRadiusPixels); // DECKGL_FILTER_SIZE(offset, geometry); varyings.position = project_position_to_clipspace(attributes.instancePositions, attributes.instancePositions64Low, offset); // TODO , geometry.position); // DECKGL_FILTER_GL_POSITION(varyings.position, geometry); } // Apply opacity to instance color, or return instance picking color varyings.vFillColor = vec4(attributes.instanceFillColors.rgb, attributes.instanceFillColors.a * layer.opacity); // DECKGL_FILTER_COLOR(varyings.vFillColor, geometry); varyings.vLineColor = vec4(attributes.instanceLineColors.rgb, attributes.instanceLineColors.a * layer.opacity); // DECKGL_FILTER_COLOR(varyings.vLineColor, geometry); varyings.pickingColor = attributes.instancePickingColors; return varyings; } @fragment fn fragmentMain(varyings: Varyings) -> @location(0) vec4 { // var geometry: Geometry; // geometry.uv = unitPosition; let distToCenter = length(varyings.unitPosition) * varyings.outerRadiusPixels; let inCircle = select( smoothedge(distToCenter, varyings.outerRadiusPixels), step(distToCenter, varyings.outerRadiusPixels), scatterplot.antialiasing != 0 ); if (inCircle == 0.0) { discard; } var fragColor: vec4; if (scatterplot.stroked != 0) { let isLine = select( smoothedge(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter), step(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter), scatterplot.antialiasing != 0 ); if (scatterplot.filled != 0) { fragColor = mix(varyings.vFillColor, varyings.vLineColor, isLine); } else { if (isLine == 0.0) { discard; } fragColor = vec4(varyings.vLineColor.rgb, varyings.vLineColor.a * isLine); } } else if (scatterplot.filled == 0) { discard; } else { fragColor = varyings.vFillColor; } fragColor.a *= inCircle; if (picking.isActive > 0.5) { if (!picking_isColorValid(varyings.pickingColor)) { discard; } return vec4(varyings.pickingColor, 1.0); } if (picking.isHighlightActive > 0.5) { let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor); if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) { let highLightAlpha = picking.highlightColor.a; let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha); if (blendedAlpha > 0.0) { let highLightRatio = highLightAlpha / blendedAlpha; fragColor = vec4( mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio), blendedAlpha ); } else { fragColor = vec4(fragColor.rgb, 0.0); } } } // Apply premultiplied alpha as required by transparent canvas fragColor = deckgl_premultiplied_alpha(fragColor); return fragColor; // return vec4(0, 0, 1, 1); } `,Uf=[0,0,0,255],HS={radiusUnits:"meters",radiusScale:{type:"number",min:0,value:1},radiusMinPixels:{type:"number",min:0,value:0},radiusMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},lineWidthUnits:"meters",lineWidthScale:{type:"number",min:0,value:1},lineWidthMinPixels:{type:"number",min:0,value:0},lineWidthMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},stroked:!1,filled:!0,billboard:!1,antialiasing:!0,getPosition:{type:"accessor",value:t=>t.position},getRadius:{type:"accessor",value:1},getFillColor:{type:"accessor",value:Uf},getLineColor:{type:"accessor",value:Uf},getLineWidth:{type:"accessor",value:1},strokeWidth:{deprecatedFor:"getLineWidth"},outline:{deprecatedFor:"stroked"},getColor:{deprecatedFor:["getFillColor","getLineColor"]}};class Ti extends tc{getShaders(){return super.getShaders({vs:VS,fs:zS,source:jS,modules:[jw,Tb,dT,WS]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceRadius:{size:1,transition:!0,accessor:"getRadius",defaultValue:1},instanceFillColors:{size:this.props.colorFormat.length,transition:!0,type:"unorm8",accessor:"getFillColor",defaultValue:[0,0,0,255]},instanceLineColors:{size:this.props.colorFormat.length,transition:!0,type:"unorm8",accessor:"getLineColor",defaultValue:[0,0,0,255]},instanceLineWidths:{size:1,transition:!0,accessor:"getLineWidth",defaultValue:1}})}updateState(e){super.updateState(e),e.changeFlags.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){const{radiusUnits:i,radiusScale:n,radiusMinPixels:r,radiusMaxPixels:s,stroked:o,filled:a,billboard:c,antialiasing:l,lineWidthUnits:f,lineWidthScale:u,lineWidthMinPixels:h,lineWidthMaxPixels:p}=this.props,d={stroked:o,filled:a,billboard:c,antialiasing:l,radiusUnits:Ii[i],radiusScale:n,radiusMinPixels:r,radiusMaxPixels:s,lineWidthUnits:Ii[f],lineWidthScale:u,lineWidthMinPixels:h,lineWidthMaxPixels:p},m=this.state.model;m.shaderInputs.setProps({scatterplot:d}),m.draw(this.context.renderPass)}_getModel(){const e=[-1,-1,0,1,-1,0,-1,1,0,1,1,0];return new yn(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new EE({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array(e)}}}),isInstanced:!0})}}Ti.defaultProps=HS;Ti.layerName="ScatterplotLayer";let ic="jasperai/monet-umap-data",nc="main",Zd="jasperai/monet",Gd="main",qo="v1.2.0";const rc="https://huggingface.co";let bn="https://huggingface.co/buckets/jasperai/monet-retrieval-storage/resolve/v1.2.0/umap-data/umap-1m",Zo="",Go="";async function YS(t="./runtime-config.json"){let e;try{const r=await fetch(t,{cache:"no-store"});if(!r.ok){r.status!==404&&console.warn(`[config] ${t} -> HTTP ${r.status}, using build defaults`);return}e=await r.json()}catch(r){console.warn(`[config] ${t} fetch failed, using build defaults`,r);return}const i=r=>typeof r=="string"&&r.length>0,n={};i(e.dataBaseUrl)&&(bn=e.dataBaseUrl,n.dataBaseUrl=e.dataBaseUrl),i(e.thumbsBaseUrl)&&(Go=e.thumbsBaseUrl,n.thumbsBaseUrl=e.thumbsBaseUrl),i(e.sourceBaseUrl)&&(Zo=e.sourceBaseUrl,n.sourceBaseUrl=e.sourceBaseUrl),i(e.dataRepo)&&(ic=e.dataRepo,n.dataRepo=e.dataRepo),i(e.dataRevision)&&(nc=e.dataRevision,n.dataRevision=e.dataRevision),i(e.sourceRepo)&&(Zd=e.sourceRepo,n.sourceRepo=e.sourceRepo),i(e.sourceRevision)&&(Gd=e.sourceRevision,n.sourceRevision=e.sourceRevision),i(e.datasetVersion)&&(qo=e.datasetVersion,n.datasetVersion=e.datasetVersion),Object.keys(n).length>0?console.info("[config] runtime overrides applied",n):console.info("[config] runtime-config.json fetched but all keys empty — using build-time defaults (VITE_DATA_BASE_URL etc).")}function In(t){return bn?`${bn.replace(/\/$/,"")}/${t}`:`${rc}/datasets/${ic}/resolve/${nc}/${t}`}function Jd(){return bn?bn.replace(/\/$/,""):`${rc}/datasets/${ic}/resolve/${nc}`}function XS(){if(qo)return qo;const t=Jd().match(/\/(v\d+\.\d+(?:\.\d+)?)(?:\/|$)/);return t?t[1]:null}function QS(t){return`${rc}/datasets/${Zd}/resolve/${Gd}/${t}`}const KS=["cluster_name","cluster_cohesion","source","aesthetic_jasperai","nsfw_jasperai","wk_jasperai","classifier_clip-vit-base-patch32","resolution","aspect_ratio"],qS=["source","aesthetic_jasperai","nsfw_jasperai","resolution","aspect_ratio","cluster_name","cluster_cohesion","classifier_clip-vit-base-patch32"],kt=1e4,ZS=1e5,Jo="monet-umap.maxPoints";function $d(){try{const t=window.localStorage.getItem(Jo);if(!t)return null;const e=parseInt(t,10);return!Number.isFinite(e)||e<=0?null:e}catch{return null}}function GS(t){try{t==null?window.localStorage.removeItem(Jo):window.localStorage.setItem(Jo,String(Math.round(t)))}catch{}}function JS(t){const i=new URL(window.location.href).searchParams.get("n");if(i){const s=parseInt(i,10);if(Number.isFinite(s)&&s>0)return Math.max(kt,Math.min(s,t))}const n=$d();return n!=null?Math.max(kt,Math.min(n,t)):Math.max(kt,Math.min(ZS,t))}const kf=["BOOLEAN","INT32","INT64","INT96","FLOAT","DOUBLE","BYTE_ARRAY","FIXED_LEN_BYTE_ARRAY"],Nt=["PLAIN","GROUP_VAR_INT","PLAIN_DICTIONARY","RLE","BIT_PACKED","DELTA_BINARY_PACKED","DELTA_LENGTH_BYTE_ARRAY","DELTA_BYTE_ARRAY","RLE_DICTIONARY","BYTE_STREAM_SPLIT"],$S=["REQUIRED","OPTIONAL","REPEATED"],eR=["UTF8","MAP","MAP_KEY_VALUE","LIST","ENUM","DECIMAL","DATE","TIME_MILLIS","TIME_MICROS","TIMESTAMP_MILLIS","TIMESTAMP_MICROS","UINT_8","UINT_16","UINT_32","UINT_64","INT_8","INT_16","INT_32","INT_64","JSON","BSON","INTERVAL"],tR=["UNCOMPRESSED","SNAPPY","GZIP","LZO","BROTLI","LZ4","ZSTD","LZ4_RAW"],ep=["DATA_PAGE","INDEX_PAGE","DICTIONARY_PAGE","DATA_PAGE_V2"],iR=["SPHERICAL","VINCENTY","THOMAS","ANDOYER","KARNEY"];function $o(t){const e=rr(t);if(e.type===1)return{type:"Point",coordinates:ea(t,e)};if(e.type===2)return{type:"LineString",coordinates:ta(t,e)};if(e.type===3)return{type:"Polygon",coordinates:Lf(t,e)};if(e.type===4){const i=[];for(let n=0;n1&&r<=7&&(o=e.getUint32(t.offset,i),t.offset+=4);let a=2;return s&&a++,s===3&&a++,{littleEndian:i,type:r,dim:a,count:o}}function ea(t,e){const i=[];for(let n=0;ni.toString(16).padStart(2,"0")).join("");return e.slice(0,8)+"-"+e.slice(8,12)+"-"+e.slice(12,16)+"-"+e.slice(16,20)+"-"+e.slice(20,32)}};function Wf(t,e,i,n){if(e&&i.endsWith("_DICTIONARY")){let r=t;t instanceof Uint8Array&&!(e instanceof Uint8Array)&&(r=new e.constructor(t.length));for(let s=0;su.element.logical_type?.type==="VARIANT")&&o==="BYTE_ARRAY"&&a!=="UTF8"&&c?.type!=="STRING")return t;if(a==="DECIMAL"){const h=10**-(i.scale||0),p=new Array(t.length);for(let d=0;dn.timestampFromNanoseconds(nR(u)));if(a==="DATE")return Array.from(t).map(u=>n.dateFromDays(u));if(a==="TIMESTAMP_MILLIS")return Array.from(t).map(u=>n.timestampFromMilliseconds(u));if(a==="TIMESTAMP_MICROS")return Array.from(t).map(u=>n.timestampFromMicroseconds(u));if(a==="JSON")return t.map(u=>JSON.parse(tp.decode(u)));if(a==="BSON")throw new Error("parquet bson not supported");if(a==="INTERVAL")throw new Error("parquet interval not supported");if(c?.type==="GEOMETRY")return t.map(u=>n.geometryFromBytes(u));if(c?.type==="GEOGRAPHY")return t.map(u=>n.geographyFromBytes(u));if(c?.type==="UUID")return t.map(u=>n.uuidFromBytes(u));if(a==="UTF8"||c?.type==="STRING"||r&&o==="BYTE_ARRAY")return t.map(u=>n.stringFromBytes(u));if(a==="UINT_64"||c?.type==="INTEGER"&&c.bitWidth===64&&!c.isSigned){if(t instanceof BigInt64Array)return new BigUint64Array(t.buffer,t.byteOffset,t.length);const u=l?new Array(t.length):new BigUint64Array(t.length);for(let h=0;h=2n**BigInt(i-1)&&(e-=2n**BigInt(i)),Number(e)}function nR(t){const e=(t>>64n)-2440588n,i=t&0xffffffffffffffffn;return e*86400000000000n+i}function rp(t){if(!t)return;const e=t[1]<<8|t[0],i=e>>15?-1:1,n=e>>10&31,r=e&1023;return n===0?i*2**-14*(r/1024):n===31?r?NaN:i*(1/0):i*2**(n-15)*(1+r/1024)}function sp(t,e,i){const n=t[e],r=[];let s=1;if(n.num_children)for(;r.lengtho.element.name===r);if(!s)throw new Error(`parquet schema element not found: ${e}`);n.push(s),i=s}return n}function rR(t){const e=[];function i(n){if(n.children.length)for(const r of n.children)i(r);else e.push(n.path.join("."))}return i(t),e}function ap(t){let e=0;for(const{element:i}of t)i.repetition_type==="REPEATED"&&e++;return e}function sc(t){let e=0;for(const{element:i}of t.slice(1))i.repetition_type!=="REQUIRED"&&e++;return e}function sR(t){if(!t||t.element.converted_type!=="LIST"||t.children.length>1)return!1;const e=t.children[0];return!(e.children.length>1||e.element.repetition_type!=="REPEATED")}function oR(t){if(!t||t.element.converted_type!=="MAP"||t.children.length>1)return!1;const e=t.children[0];return!(e.children.length!==2||e.element.repetition_type!=="REPEATED"||e.children.find(r=>r.element.name==="key")?.element.repetition_type==="REPEATED"||e.children.find(r=>r.element.name==="value")?.element.repetition_type==="REPEATED")}function cp(t){if(t.length!==2)return!1;const[,e]=t;return!(e.element.repetition_type==="REPEATED"||e.children.length)}const aR=0,Vf=1,zf=2,jf=3,cR=4,lR=5,fR=6,uR=7,hR=8,dR=9,pR=12;function cs(t){const e={};let i=0;for(;t.offset>4;i=s?i+s:lp(t),e[`field_${i}`]=ia(t,r)}return e}function ia(t,e){switch(e){case Vf:return!0;case zf:return!1;case jf:return t.view.getInt8(t.offset++);case cR:case lR:return lp(t);case fR:return na(t);case uR:{const i=t.view.getFloat64(t.offset,!0);return t.offset+=8,i}case hR:{const i=Xt(t),n=new Uint8Array(t.view.buffer,t.view.byteOffset+t.offset,i);return t.offset+=i,n}case dR:{const i=t.view.getUint8(t.offset++),n=i&15;let r=i>>4;r===15&&(r=Xt(t));const s=n===Vf||n===zf,o=new Array(r);for(let a=0;a>>1^-(e&1)}function na(t){const e=gR(t);return e>>1n^-(e&1n)}function mR(t,e){const i=new Map,n=e?.find(({key:s})=>s==="geo")?.value,r=(n&&JSON.parse(n)?.columns)??{};for(const[s,o]of Object.entries(r)){if(o.encoding!=="WKB")continue;const a=o.edges==="spherical"?"GEOGRAPHY":"GEOMETRY",c=o.crs?.id??o.crs?.ids?.[0],l=c?`${c.authority}:${c.code.toString()}`:void 0;i.set(s,{type:a,crs:l})}for(let s=1;s=0))throw new Error("parquet expected AsyncBuffer");const r=Math.max(0,t.byteLength-i),s=await t.slice(r,t.byteLength),o=new DataView(s);if(o.getUint32(s.byteLength-4,!0)!==827474256)throw new Error("parquet file invalid (footer != PAR1)");const a=o.getUint32(s.byteLength-8,!0);if(a>t.byteLength-8)throw new Error(`parquet metadata length ${a} exceeds available buffer ${t.byteLength-8}`);if(a+8>i){const c=t.byteLength-a-8,l=await t.slice(c,r),f=new ArrayBuffer(a+8),u=new Uint8Array(f);return u.set(new Uint8Array(l)),u.set(new Uint8Array(s),r-c),Hf(f,{parsers:e,geoparquet:n})}else return Hf(s,{parsers:e,geoparquet:n})}function Hf(t,{parsers:e,geoparquet:i=!0}={}){if(!(t instanceof ArrayBuffer))throw new Error("parquet expected ArrayBuffer");const n=new DataView(t);if(e={...as,...e},n.byteLength<8)throw new Error("parquet file is too short");if(n.getUint32(n.byteLength-4,!0)!==827474256)throw new Error("parquet file invalid (footer != PAR1)");const r=n.byteLength-8,s=n.getUint32(r,!0);if(s>n.byteLength-8)throw new Error(`parquet metadata length ${s} exceeds available buffer ${n.byteLength-8}`);const o=r-s,c=cs({view:n,offset:o}),l=c.field_1,f=c.field_2.map(g=>({type:kf[g.field_1],type_length:g.field_2,repetition_type:$S[g.field_3],name:$e(g.field_4),num_children:g.field_5,converted_type:eR[g.field_6],scale:g.field_7,precision:g.field_8,field_id:g.field_9,logical_type:AR(g.field_10)})),u=f.filter(g=>g.type),h=c.field_3,p=c.field_4.map(g=>({columns:g.field_1.map((_,y)=>({file_path:$e(_.field_1),file_offset:_.field_2,meta_data:_.field_3&&{type:kf[_.field_3.field_1],encodings:_.field_3.field_2?.map(A=>Nt[A]),path_in_schema:_.field_3.field_3.map($e),codec:tR[_.field_3.field_4],num_values:_.field_3.field_5,total_uncompressed_size:_.field_3.field_6,total_compressed_size:_.field_3.field_7,key_value_metadata:_.field_3.field_8?.map(A=>({key:$e(A.field_1),value:$e(A.field_2)})),data_page_offset:_.field_3.field_9,index_page_offset:_.field_3.field_10,dictionary_page_offset:_.field_3.field_11,statistics:yR(_.field_3.field_12,u[y],e),encoding_stats:_.field_3.field_13?.map(A=>({page_type:ep[A.field_1],encoding:Nt[A.field_2],count:A.field_3})),bloom_filter_offset:_.field_3.field_14,bloom_filter_length:_.field_3.field_15,size_statistics:_.field_3.field_16&&{unencoded_byte_array_data_bytes:_.field_3.field_16.field_1,repetition_level_histogram:_.field_3.field_16.field_2,definition_level_histogram:_.field_3.field_16.field_3},geospatial_statistics:_.field_3.field_17&&{bbox:_.field_3.field_17.field_1&&{xmin:_.field_3.field_17.field_1.field_1,xmax:_.field_3.field_17.field_1.field_2,ymin:_.field_3.field_17.field_1.field_3,ymax:_.field_3.field_17.field_1.field_4,zmin:_.field_3.field_17.field_1.field_5,zmax:_.field_3.field_17.field_1.field_6,mmin:_.field_3.field_17.field_1.field_7,mmax:_.field_3.field_17.field_1.field_8},geospatial_types:_.field_3.field_17.field_2}},offset_index_offset:_.field_4,offset_index_length:_.field_5,column_index_offset:_.field_6,column_index_length:_.field_7,crypto_metadata:_.field_8,encrypted_column_metadata:_.field_9})),total_byte_size:g.field_2,num_rows:g.field_3,sorting_columns:g.field_4?.map(_=>({column_idx:_.field_1,descending:_.field_2,nulls_first:_.field_3})),file_offset:g.field_5,total_compressed_size:g.field_6,ordinal:g.field_7})),d=c.field_5?.map(g=>({key:$e(g.field_1),value:$e(g.field_2)})),m=$e(c.field_6);return i&&mR(f,d),{version:l,schema:f,num_rows:h,row_groups:p,key_value_metadata:d,created_by:m,metadata_length:s}}function ra({schema:t}){return op(t,[])[0]}function AR(t){return t?.field_1?{type:"STRING"}:t?.field_2?{type:"MAP"}:t?.field_3?{type:"LIST"}:t?.field_4?{type:"ENUM"}:t?.field_5?{type:"DECIMAL",scale:t.field_5.field_1,precision:t.field_5.field_2}:t?.field_6?{type:"DATE"}:t?.field_7?{type:"TIME",isAdjustedToUTC:t.field_7.field_1,unit:Yf(t.field_7.field_2)}:t?.field_8?{type:"TIMESTAMP",isAdjustedToUTC:t.field_8.field_1,unit:Yf(t.field_8.field_2)}:t?.field_10?{type:"INTEGER",bitWidth:t.field_10.field_1,isSigned:t.field_10.field_2}:t?.field_11?{type:"NULL"}:t?.field_12?{type:"JSON"}:t?.field_13?{type:"BSON"}:t?.field_14?{type:"UUID"}:t?.field_15?{type:"FLOAT16"}:t?.field_16?{type:"VARIANT",specification_version:t.field_16.field_1}:t?.field_17?{type:"GEOMETRY",crs:$e(t.field_17.field_1)}:t?.field_18?{type:"GEOGRAPHY",crs:$e(t.field_18.field_1),algorithm:iR[t.field_18.field_2]}:t}function Yf(t){if(t.field_1)return"MILLIS";if(t.field_2)return"MICROS";if(t.field_3)return"NANOS";throw new Error("parquet time unit required")}function yR(t,e,i){return t&&{max:sr(t.field_1,e,i),min:sr(t.field_2,e,i),null_count:t.field_3,distinct_count:t.field_4,max_value:sr(t.field_5,e,i),min_value:sr(t.field_6,e,i),is_max_value_exact:t.field_7,is_min_value_exact:t.field_8}}function sr(t,e,i){const{type:n,converted_type:r,logical_type:s}=e;if(t===void 0)return t;if(n==="BOOLEAN")return t[0]===1;if(n==="BYTE_ARRAY")return i.stringFromBytes(t);const o=new DataView(t.buffer,t.byteOffset,t.byteLength);return n==="FLOAT"&&o.byteLength===4?o.getFloat32(0,!0):n==="DOUBLE"&&o.byteLength===8?o.getFloat64(0,!0):n==="INT32"&&r==="DATE"?i.dateFromDays(o.getInt32(0,!0)):n==="INT64"&&r==="TIMESTAMP_MILLIS"?i.timestampFromMilliseconds(o.getBigInt64(0,!0)):n==="INT64"&&r==="TIMESTAMP_MICROS"?i.timestampFromMicroseconds(o.getBigInt64(0,!0)):n==="INT64"&&s?.type==="TIMESTAMP"&&s?.unit==="NANOS"?i.timestampFromNanoseconds(o.getBigInt64(0,!0)):n==="INT64"&&s?.type==="TIMESTAMP"&&s?.unit==="MICROS"?i.timestampFromMicroseconds(o.getBigInt64(0,!0)):n==="INT64"&&s?.type==="TIMESTAMP"?i.timestampFromMilliseconds(o.getBigInt64(0,!0)):n==="INT32"&&o.byteLength===4?o.getInt32(0,!0):n==="INT64"&&o.byteLength===8?o.getBigInt64(0,!0):r==="DECIMAL"?np(t)*10**-(e.scale||0):s?.type==="FLOAT16"?rp(t):t}function bR(t){const e=cs(t);return{page_locations:e.field_1.map(i=>({offset:i.field_1,compressed_page_size:i.field_2,first_row_index:i.field_3})),unencoded_byte_array_data_bytes:e.field_2}}function hp(t,e){for(let n=0;nh.slice(a,c));const l=new Headers(o.headers),f=c===void 0?"":c-1;l.set("Range",`bytes=${a}-${f}`);const u=await r(t,{...o,headers:l});if(!u.ok||!u.body)throw new Error(`fetch failed ${u.status}`);if(u.status===200)return s=u.arrayBuffer(),s.then(h=>h.slice(a,c));if(u.status===206)return u.arrayBuffer();throw new Error(`fetch received unexpected status code ${u.status}`)}}}function TR({byteLength:t,slice:e},{minSize:i=fp}={}){if(te)throw new Error(`invalid empty range [${t}, ${e}]`);return`${t},${e}`}else return i===void 0?`${t},`:`${t},${i}`}function dp(t){if(!t)return[];if(t.length===1)return t[0];const e=[];for(const i of t)hp(e,i);return e}function yr(t){if(!t)return[];const e=[];return"$and"in t&&Array.isArray(t.$and)?e.push(...t.$and.flatMap(yr)):"$or"in t&&Array.isArray(t.$or)?e.push(...t.$or.flatMap(yr)):"$nor"in t&&Array.isArray(t.$nor)?e.push(...t.$nor.flatMap(yr)):e.push(...Object.keys(t).map(i=>i.split(".")[0])),[...new Set(e)]}function $i(t,e,i=!0){return"$and"in e&&Array.isArray(e.$and)?e.$and.every(n=>$i(t,n,i)):"$or"in e&&Array.isArray(e.$or)?e.$or.some(n=>$i(t,n,i)):"$nor"in e&&Array.isArray(e.$nor)?!e.$nor.some(n=>$i(t,n,i)):Object.entries(e).every(([n,r])=>{const s=SR(t,n);return typeof r!="object"||r===null||Array.isArray(r)?St(s,r,i):Object.entries(r||{}).every(([o,a])=>o==="$gt"?s>a:o==="$gte"?s>=a:o==="$lt"?ssa({rowGroup:t,physicalColumns:e,filter:r,strict:n}));if("$or"in i&&Array.isArray(i.$or))return i.$or.every(r=>sa({rowGroup:t,physicalColumns:e,filter:r,strict:n}));if("$nor"in i&&Array.isArray(i.$nor))return!1;for(const[r,s]of Object.entries(i)){const o=e.indexOf(r);if(o===-1)continue;const a=t.columns[o].meta_data?.statistics;if(!a)continue;const{min:c,max:l,min_value:f,max_value:u}=a,h=f!==void 0?f:c,p=u!==void 0?u:l;if(!(h===void 0||p===void 0)){for(const[d,m]of Object.entries(s||{}))if(d==="$gt"&&p<=m||d==="$gte"&&p=m||d==="$lte"&&h>m||d==="$eq"&&(mp)||d==="$ne"&&St(h,p,n)&&St(h,m,n)||d==="$in"&&Array.isArray(m)&&m.every(g=>gp)||d==="$nin"&&Array.isArray(m)&&St(h,p,n)&&m.includes(h))return!0}}return!1}function SR(t,e){let i=t;for(const n of e.split("."))i=i?.[n];return i}const RR=1<<21;function vR({metadata:t,rowStart:e=0,rowEnd:i=1/0,columns:n,filter:r,filterStrict:s=!0,useOffsetIndex:o=!1}){if(!t)throw new Error("parquetPlan requires metadata");const a=[],c=[],l=[],f=rR(ra(t));let u=0;for(const h of t.row_groups){const p=Number(h.num_rows),d=u+p;if(p>0&&d>e&&uu||it.slice(n,r));return{byteLength:t.byteLength,slice(n,r=t.byteLength){const s=e.findIndex(({startByte:o,endByte:a})=>o<=n&&r<=a);if(s<0)return t.slice(n,r);if(e[s].startByte!==n||e[s].endByte!==r){const o=n-e[s].startByte,a=r-e[s].startByte;return i[s]instanceof Promise?i[s].then(c=>c.slice(o,a)):i[s].slice(o,a)}else return i[s]}}}const ac=new TextDecoder,Qf=new WeakMap;function pp(t,e=as){if(Array.isArray(t))return t.map(i=>pp(i,e));if(typeof t!="object")return t;if("metadata"in t){const i=PR(t.metadata),n=t.typed_value&&br(t.typed_value,i,e),r=t.value&&wn(zr(t.value),i,e);return n&&r?{...r,...n}:n??r}return t}function br(t,e,i){if(t instanceof Date)return t;if(t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Uint8Array)){if("typed_value"in t&&t.typed_value!==null&&t.typed_value!==void 0)return br(t.typed_value,e,i);if("value"in t&&t.value instanceof Uint8Array)return wn(zr(t.value),e,i);if("typed_value"in t||"value"in t)return null;const n={};for(const[r,s]of Object.entries(t))e.dictionary.includes(r)&&(n[r]=br(s,e,i));return n}return t instanceof Uint8Array?wn(zr(t),e,i):Array.isArray(t)?t.map(n=>br(n,e,i)):t}function zr(t){return{view:new DataView(t.buffer,t.byteOffset,t.byteLength),offset:0}}function PR(t){let e=Qf.get(t.buffer);e||(e=new Map,Qf.set(t.buffer,e));const i=`${t.byteOffset}:${t.byteLength}`,n=e.get(i);if(n)return n;const r=zr(t),s=r.view.getUint8(r.offset++),o=s&15;if(o!==1)throw new Error(`parquet unsupported variant metadata version: ${o}`);const a=(s>>4&1)===1,c=(s>>6&3)+1,l=Qt(r,c),f=new Array(l+1);for(let d=0;d>2;if(r===0)return IR(t,s,i);if(r===2)return xR(t,s,e,i);if(r===3)return MR(t,s,e,i);const o=new Uint8Array(t.view.buffer,t.view.byteOffset+t.offset,s);return t.offset+=s,ac.decode(o)}function IR(t,e,i){switch(e){case 0:return null;case 1:return!0;case 2:return!1;case 3:{const n=t.view.getInt8(t.offset);return t.offset+=1,n}case 4:{const n=t.view.getInt16(t.offset,!0);return t.offset+=2,n}case 5:{const n=t.view.getInt32(t.offset,!0);return t.offset+=4,n}case 6:{const n=t.view.getBigInt64(t.offset,!0);return t.offset+=8,n}case 7:{const n=t.view.getFloat64(t.offset,!0);return t.offset+=8,n}case 8:return to(t,4);case 9:return to(t,8);case 10:return to(t,16);case 11:{const n=t.view.getInt32(t.offset,!0);return t.offset+=4,i.dateFromDays(n)}case 12:case 13:{const n=t.view.getBigInt64(t.offset,!0);return t.offset+=8,i.timestampFromMicroseconds(n)}case 14:{const n=t.view.getFloat32(t.offset,!0);return t.offset+=4,n}case 15:return Kf(t);case 16:{const n=Kf(t);return ac.decode(n)}case 17:{const n=t.view.getBigInt64(t.offset,!0);return t.offset+=8,n}case 18:case 19:{const n=t.view.getBigInt64(t.offset,!0);return t.offset+=8,i.timestampFromNanoseconds(n)}case 20:{const n=new Uint8Array(t.view.buffer,t.view.byteOffset+t.offset,16);t.offset+=16;const r=Array.from(n,s=>s.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}default:throw new Error(`parquet unsupported variant primitive type: ${e}`)}}function xR(t,e,i,n){const r=(e&3)+1,s=(e>>2&3)+1,a=e>>4&1?Qt(t,4):t.view.getUint8(t.offset++),c=new Array(a);for(let u=0;u>2&1,o=r+1,a=Qt(t,s?4:1),c=new Array(a+1);for(let u=0;ud.repetition_type);let c=0;const l=[t];let f=t,u=0,h=0,p=0;if(i[0])for(;u>p&m;for(p+=h;p>=8;)p-=8n,t.offset++,p&&(g|=BigInt(t.view.getUint8(t.offset))<>>1;BR(t,a,e,i,s),s+=a}}t.offset=r+n}function BR(t,e,i,n,r){const s=i+7>>3;let o=0;for(let a=0;a>1<<3;const o=(1<8?(l-=8,c-=8,a>>>=8):c-l>l&o),s--,l+=i);return r}function Ap(t,e,i,n){const r=DR(i,n),s=new Uint8Array(e*r);for(let o=0;o=i)throw new Error("invalid snappy length header");for(;r=i)throw new Error("missing eof marker");if(o&3){let c=0;switch(o&3){case 1:a=(o>>>2&7)+4,c=t[r]+(o>>>5<<8),r++;break;case 2:if(i<=r+1)throw new Error("snappy error end of input");a=(o>>>2)+1,c=t[r]+(t[r+1]<<8),r+=2;break;case 3:if(i<=r+3)throw new Error("snappy error end of input");a=(o>>>2)+1,c=t[r]+(t[r+1]<<8)+(t[r+2]<<16)+(t[r+3]<<24),r+=4;break}if(c===0||isNaN(c))throw new Error(`invalid offset ${c} pos ${r} inputLength ${i}`);if(c>s)throw new Error("cannot copy from before start of buffer");Zf(e,s-c,e,s,a),s+=a}else{let c=(o>>>2)+1;if(c>60){if(r+3>=i)throw new Error("snappy error literal pos + 3 >= inputLength");const l=c-60;c=t[r]+(t[r+1]<<8)+(t[r+2]<<16)+(t[r+3]<<24),c=(c&HR[l])+1,r+=l}if(r+c>i)throw new Error("snappy error literal exceeds input length");Zf(t,r,e,s,c),r+=c,s+=c}}if(s!==n)throw new Error("premature end of input")}function XR(t,e,{type:i,element:n,schemaPath:r}){const s=new DataView(t.buffer,t.byteOffset,t.byteLength),o={view:s,offset:0};let a;const c=QR(o,e,r),{definitionLevels:l,numNulls:f}=KR(o,e,r),u=e.num_values-f;if(e.encoding==="PLAIN")a=cc(o,i,u,n.type_length);else if(e.encoding==="PLAIN_DICTIONARY"||e.encoding==="RLE_DICTIONARY"||e.encoding==="RLE"){const h=i==="BOOLEAN"?1:s.getUint8(o.offset++);h?(a=new Array(u),i==="BOOLEAN"?(Ct(o,h,a),a=a.map(p=>!!p)):Ct(o,h,a,s.byteLength-o.offset)):a=new Uint8Array(u)}else if(e.encoding==="BYTE_STREAM_SPLIT")a=Ap(o,u,i,n.type_length);else if(e.encoding==="DELTA_BINARY_PACKED")a=i==="INT32"?new Int32Array(u):new BigInt64Array(u),Tn(o,u,a);else if(e.encoding==="DELTA_LENGTH_BYTE_ARRAY")a=new Array(u),_p(o,u,a);else throw new Error(`parquet unsupported encoding: ${e.encoding}`);return{definitionLevels:l,repetitionLevels:c,dataPage:a}}function QR(t,e,i){if(i.length>1){const n=ap(i);if(n){const r=new Array(e.num_values);return Ct(t,fs(n),r),r}}return[]}function KR(t,e,i){const n=sc(i);if(!n)return{definitionLevels:[],numNulls:0};const r=new Array(e.num_values);Ct(t,fs(n),r);let s=e.num_values;for(const o of r)o===n&&s--;return s===0&&(r.length=0),{definitionLevels:r,numNulls:s}}function oa(t,e,i,n){let r;const s=n?.[i];if(i==="UNCOMPRESSED")r=t;else if(s)r=s(t,e);else if(i==="SNAPPY")r=new Uint8Array(e),YR(t,r);else throw new Error(`parquet unsupported compression codec: ${i}`);if(r?.length!==e)throw new Error(`parquet decompressed page length ${r?.length} does not match header ${e}`);return r}function qR(t,e,i){const r={view:new DataView(t.buffer,t.byteOffset,t.byteLength),offset:0},{type:s,element:o,schemaPath:a,codec:c,compressors:l}=i,f=e.data_page_header_v2;if(!f)throw new Error("parquet data page header v2 is undefined");const u=ZR(r,f,a);r.offset=f.repetition_levels_byte_length;const h=GR(r,f,a),p=e.uncompressed_page_size-f.definition_levels_byte_length-f.repetition_levels_byte_length;let d=t.subarray(r.offset);f.is_compressed!==!1&&(d=oa(d,p,c,l));const m=new DataView(d.buffer,d.byteOffset,d.byteLength),g={view:m,offset:0};let _;const y=f.num_values-f.num_nulls;if(f.encoding==="PLAIN")_=cc(g,s,y,o.type_length);else if(f.encoding==="RLE")_=new Array(y),Ct(g,1,_),_=_.map(A=>!!A);else if(f.encoding==="PLAIN_DICTIONARY"||f.encoding==="RLE_DICTIONARY"){const A=m.getUint8(g.offset++);_=new Array(y),Ct(g,A,_,p-1)}else if(f.encoding==="DELTA_BINARY_PACKED")_=s==="INT32"?new Int32Array(y):new BigInt64Array(y),Tn(g,y,_);else if(f.encoding==="DELTA_LENGTH_BYTE_ARRAY")_=new Array(y),_p(g,y,_);else if(f.encoding==="DELTA_BYTE_ARRAY")_=new Array(y),OR(g,y,_);else if(f.encoding==="BYTE_STREAM_SPLIT")_=Ap(g,y,s,o.type_length);else throw new Error(`parquet unsupported encoding: ${f.encoding}`);return{definitionLevels:h,repetitionLevels:u,dataPage:_}}function ZR(t,e,i){const n=ap(i);if(!n)return[];const r=new Array(e.num_values);return Ct(t,fs(n),r,e.repetition_levels_byte_length),r}function GR(t,e,i){const n=sc(i);if(n){const r=new Array(e.num_values);return Ct(t,fs(n),r,e.definition_levels_byte_length),r}}function fs(t){return 32-Math.clz32(t)}function Gf(t,{groupStart:e,selectStart:i,selectEnd:n},r,s){const{pathInSchema:o,schemaPath:a}=r,c=cp(a),l=[];let f,u,h=0,p=0;const d=s&&(()=>{u&&s({pathInSchema:o,columnData:u,rowStart:e+h-u.length,rowEnd:e+h})});for(;(c?h=t.view.byteLength-1);){const m=JR(t);if(m.type==="DICTIONARY_PAGE"){const{data:g}=Jf(t,m,r,f,void 0,0);g&&(f=ip(g,r))}else{const g=u?.length||0,_=Jf(t,m,r,f,u,i-h);_.skipped?(l.length||(p+=_.skipped),h+=_.skipped):_.data&&u===_.data?h+=_.data.length-g:_.data&&_.data.length&&(d?.(),l.push(_.data),h+=_.data.length,u=_.data)}}return d?.(),{data:l,skipped:p}}function Jf(t,e,i,n,r,s){const{type:o,element:a,schemaPath:c,codec:l,compressors:f}=i,u=new Uint8Array(t.view.buffer,t.view.byteOffset+t.offset,e.compressed_page_size);if(t.offset+=e.compressed_page_size,e.type==="DATA_PAGE"){const h=e.data_page_header;if(!h)throw new Error("parquet data page header is undefined");if(s>h.num_values&&cp(c))return{skipped:h.num_values};const p=oa(u,Number(e.uncompressed_page_size),l,f),{definitionLevels:d,repetitionLevels:m,dataPage:g}=XR(p,h,i),_=Wf(g,n,h.encoding,i),y=Array.isArray(r)?r:[];return{skipped:0,data:qf(y,d,m,_,c)}}else if(e.type==="DATA_PAGE_V2"){const h=e.data_page_header_v2;if(!h)throw new Error("parquet data page header v2 is undefined");if(s>h.num_rows)return{skipped:h.num_values};const{definitionLevels:p,repetitionLevels:d,dataPage:m}=qR(u,e,i),g=Wf(m,n,h.encoding,i),_=Array.isArray(r)?r:[];return{skipped:0,data:qf(_,p,d,g,c)}}else if(e.type==="DICTIONARY_PAGE"){const h=e.dictionary_page_header;if(!h)throw new Error("parquet dictionary page header is undefined");const p=oa(u,Number(e.uncompressed_page_size),l,f),d={view:new DataView(p.buffer,p.byteOffset,p.byteLength),offset:0};return{skipped:0,data:cc(d,o,h.num_values,a.type_length)}}else throw new Error(`parquet unsupported page type: ${e.type}`)}function JR(t){const e=cs(t),i=ep[e.field_1],n=e.field_2,r=e.field_3,s=e.field_4,o=e.field_5&&{num_values:e.field_5.field_1,encoding:Nt[e.field_5.field_2],definition_level_encoding:Nt[e.field_5.field_3],repetition_level_encoding:Nt[e.field_5.field_4],statistics:e.field_5.field_5&&{max:e.field_5.field_5.field_1,min:e.field_5.field_5.field_2,null_count:e.field_5.field_5.field_3,distinct_count:e.field_5.field_5.field_4,max_value:e.field_5.field_5.field_5,min_value:e.field_5.field_5.field_6}},a=e.field_6,c=e.field_7&&{num_values:e.field_7.field_1,encoding:Nt[e.field_7.field_2],is_sorted:e.field_7.field_3},l=e.field_8&&{num_values:e.field_8.field_1,num_nulls:e.field_8.field_2,num_rows:e.field_8.field_3,encoding:Nt[e.field_8.field_4],definition_levels_byte_length:e.field_8.field_5,repetition_levels_byte_length:e.field_8.field_6,is_compressed:e.field_8.field_7===void 0?!0:e.field_8.field_7,statistics:e.field_8.field_8};return{type:i,uncompressed_page_size:n,compressed_page_size:r,crc:s,data_page_header:o,index_page_header:a,dictionary_page_header:c,data_page_header_v2:l}}function $R(t,{metadata:e},i){const n=[];for(const r of i.chunks){const{data_page_offset:s,dictionary_page_offset:o,path_in_schema:a}=r.columnMetadata,c=op(e.schema,a),l={pathInSchema:a,element:c[c.length-1].element,schemaPath:c,parsers:{...as,...t.parsers},...t,...r.columnMetadata};let{startByte:f,endByte:u}=r.range;if(!("offsetIndex"in r)){n.push({pathInSchema:a,data:Promise.resolve(t.file.slice(f,u)).then(h=>{const p={view:new DataView(h),offset:0};return Gf(p,i,l,t.onPage)})});continue}n.push({pathInSchema:a,data:Promise.resolve(t.file.slice(r.offsetIndex.startByte,r.offsetIndex.endByte)).then(async h=>{const{selectStart:p,selectEnd:d}=i,m=bR({view:new DataView(h),offset:0}).page_locations;let g=-1;const _=o||sp&&(f=Number(M.offset),g=x),xu.data.then(({skipped:h,data:p})=>({skipped:h,data:dp(p)})))),o=i-e;if(r==="object"){const u=Array(o);for(let h=0;hu.pathInSchema[0]).filter(u=>!n||n.includes(u)),c=n??a,l=c.map(u=>t.findIndex(h=>h.pathInSchema[0]===u)),f=Array(o);for(let u=0;ua.pathInSchema[0]===s.element.name);if(!o.length)continue;r.push({pathInSchema:s.path,data:(async()=>{const a=new Map;let c=1/0;for(const f of o){const{data:u}=await f.data,h=dp(u);a.set(f.pathInSchema.join("."),h),c=Math.min(c,h.length)}for(const[f,u]of a)u.length>c&&a.set(f,u.slice(0,c));en(a,s,i);const l=a.get(s.element.name);if(!l)throw new Error("parquet column data not assembled");return{data:[l],skipped:0}})()})}else{const o=n.find(a=>a.pathInSchema[0]===s.element.name);o&&r.push(o)}return{...t,asyncColumns:r}}async function tv(t){t.metadata??=await up(t.file,t);const{rowStart:e=0,rowEnd:i,columns:n,onChunk:r,onComplete:s,rowFormat:o,filter:a,filterStrict:c=!0}=t;if(a&&o!=="object")throw new Error('parquet filter requires rowFormat: "object"');const l=yr(a);if(l.length){const g=ra(t.metadata).children.map(y=>y.element.name),_=l.filter(y=>!g.includes(y));if(_.length)throw new Error(`parquet filter columns not found: ${_.join(", ")}`)}let f=n,u=!1;if(n&&a){const g=l.filter(_=>!n.includes(_));g.length&&(f=[...n,...g],u=!0)}const h=f!==n?{...t,columns:f}:t,p=iv(h);if(!s&&!r){for(const{asyncColumns:g}of p)for(const{data:_}of g)await _;return}const d=ra(t.metadata),m=p.map(g=>ev(g,d,t.parsers));if(r)for(const g of m)for(const _ of g.asyncColumns)_.data.then(({data:y,skipped:A})=>{let b=g.groupStart+A;for(const T of y)r({columnName:_.pathInSchema[0],columnData:T,rowStart:b,rowEnd:b+T.length}),b+=T.length});if(s){const g=[];for(const _ of m){const y=Math.max(e-_.groupStart,0),A=Math.min((i??1/0)-_.groupStart,_.groupRows),b=o==="object"?await $f(_,y,A,f,"object"):await $f(_,y,A,n,"array");if(a){for(const T of b)if($i(T,a,c)){if(u&&n)for(const w of l)n.includes(w)||delete T[w];g.push(T)}}else hp(g,b)}s(g)}else for(const{asyncColumns:g}of m)for(const{data:_}of g)await _}function iv(t){if(!t.metadata)throw new Error("parquet requires metadata");const e=vR(t);return t.file=CR(t.file,e),e.groups.map(i=>$R(t,e,i))}function lc(t){return new Promise((e,i)=>{tv({...t,rowFormat:"object",onComplete:e}).catch(i)})}var nv=ArrayBuffer,ae=Uint8Array,jr=Uint16Array,rv=Int16Array,us=Int32Array,io=function(t,e,i){if(ae.prototype.slice)return ae.prototype.slice.call(t,e,i);(e==null||e<0)&&(e=0),(i==null||i>t.length)&&(i=t.length);var n=new ae(i-e);return n.set(t.subarray(e,i)),n},fn=function(t,e,i,n){if(ae.prototype.fill)return ae.prototype.fill.call(t,e,i,n);for((i==null||i<0)&&(i=0),(n==null||n>t.length)&&(n=t.length);it.length)&&(n=t.length);i2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],ue=function(t,e,i){var n=new Error(e||ov[t]);if(n.code=t,Error.captureStackTrace&&Error.captureStackTrace(n,ue),!i)throw n;return n},eu=function(t,e,i){for(var n=0,r=0;n>>0},cv=function(t,e){var i=t[0]|t[1]<<8|t[2]<<16;if(i==3126568&&t[3]==253){var n=t[4],r=n>>5&1,s=n>>2&1,o=n&3,a=n>>6;n&8&&ue(0);var c=6-r,l=o==3?4:o,f=eu(t,c,l);c+=l;var u=a?1<>3);p=d+(d>>3)*(t[5]&7)}p>2145386496&&ue(1);var m=new ae((e==1?h||p:e?0:p)+12);return m[0]=1,m[4]=4,m[8]=8,{b:c+u,y:0,l:0,d:f,w:e&&e!=1?e:m.subarray(12),e:p,o:new us(m.buffer,0,3),u:h,c:s,m:Math.min(131072,p)}}else if((i>>4|t[3]<<20)==25481893)return av(t,4)+8;ue(0)},Kt=function(t){for(var e=0;1<i&&ue(3);for(var s=1<0;){var y=Kt(o+1),A=n>>3,b=(1<>(n&7)&b,w=(1<w&&(T-=v)),h[++a]=--T,T==-1?(o+=T,g[--f]=a):o-=T,!T)do{var x=n>>3;c=(t[x]|t[x+1]<<8)>>(n&7)&3,n+=2,a+=c}while(c==3)}(a>255||o)&&ue(0);for(var P=0,O=(s>>1)+(s>>3)+3,I=s-1,k=0;k<=a;++k){var B=h[k];if(B<1){p[k]=-B;continue}for(l=0;l=f)}}for(P&&ue(0),l=0;l>3,{b:r,s:g,n:_,t:d}]},lv=function(t,e){var i=0,n=-1,r=new ae(292),s=t[e],o=r.subarray(0,256),a=r.subarray(256,268),c=new jr(r.buffer,268);if(s<128){var l=xn(t,e+1,6),f=l[0],u=l[1];e+=s;var h=f<<3,p=t[e];p||ue(0);for(var d=0,m=0,g=u.b,_=g,y=(++e<<3)-8+Kt(p);y-=g,!(y>3;if(d+=(t[A]|t[A+1]<<8)>>(y&7)&(1<>3,m+=(t[A]|t[A+1]<<8)>>(y&7)&(1<<_)-1,o[++n]=u.s[m],g=u.n[d],d=u.t[d],_=u.n[m],m=u.t[m]}++n>255&&ue(0)}else{for(n=s-127;i>4,o[i+1]=b&15}++e}var T=0;for(i=0;i11&&ue(0),T+=w&&1<0;--i){var k=c[i];fn(I,i,k,c[i-1]=k+a[i]*(1<a&&u>3,p=(t[h]|t[h+1]<<8|t[h+2]<<16)>>(f&7);c=(c<>2,o=s<<1,a=s+o;tn(t.subarray(n,n+=t[0]|t[1]<<8),e.subarray(0,s),i),tn(t.subarray(n,n+=t[2]|t[3]<<8),e.subarray(s,o),i),tn(t.subarray(n,n+=t[4]|t[5]<<8),e.subarray(o,a),i),tn(t.subarray(n),e.subarray(a),i)},mv=function(t,e,i){var n,r=e.b,s=t[r],o=s>>1&3;e.l=s&1;var a=s>>3|t[r+1]<<5|t[r+2]<<13,c=(r+=3)+a;if(o==1)return r>=t.length?void 0:(e.b=r+1,i?(fn(i,t[r],e.y,e.y+=a),i):fn(new ae(a),t[r]));if(!(c>t.length)){if(o==0)return e.b=c,i?(i.set(t.subarray(r,c),e.y),e.y+=a,i):io(t,r,c);if(o==2){var l=t[r],f=l&3,u=l>>2&3,h=l>>4,p=0,d=0;f<2?u&1?h|=t[++r]<<4|(u&2&&t[++r]<<12):h=l>>3:(d=u,u<2?(h|=(t[++r]&63)<<4,p=t[r]>>6|t[++r]<<2):u==2?(h|=t[++r]<<4|(t[++r]&3)<<12,p=t[r]>>2|t[++r]<<6):(h|=t[++r]<<4|(t[++r]&63)<<12,p=t[r]>>6|t[++r]<<2|t[++r]<<10)),++r;var m=i?i.subarray(e.y,e.y+e.m):new ae(e.m),g=m.length-h;if(f==0)m.set(t.subarray(r,r+=h),g);else if(f==1)fn(m,t[r++],g);else{var _=e.h;if(f==2){var y=lv(t,r);p+=r-(r=y[0]),e.h=_=y[1]}else _||ue(0);(d?gv:tn)(t.subarray(r,r+=p),m.subarray(g),_)}var A=t[r++];if(A){A==255?A=(t[r++]|t[r++]<<8)+32512:A>127&&(A=A-128<<8|t[r++]);var b=t[r++];b&3&&ue(0);for(var T=[uv,hv,fv],w=2;w>-1;--w){var v=b>>(w<<1)+2&3;if(v==1){var M=new ae([0,0,t[r++]]);T[w]={s:M.subarray(2,3),n:M.subarray(0,1),t:new jr(M.buffer,0,1),b:0}}else v==2?(n=xn(t,r,9-(w&1)),r=n[0],T[w]=n[1]):v==3&&(e.t||ue(0),T[w]=e.t[w])}var x=e.t=T,P=x[0],O=x[1],I=x[2],k=t[c-1];k||ue(0);var B=(c<<3)-8+Kt(k)-I.b,D=B>>3,K=0,Be=(t[D]|t[D+1]<<8)>>(B&7)&(1<>3;var We=(t[D]|t[D+1]<<8)>>(B&7)&(1<>3;var ct=(t[D]|t[D+1]<<8)>>(B&7)&(1<>3;var me=1<>>(B&7)&me-1);D=(B-=ca[lt])>>3;var we=pv[lt]+((t[D]|t[D+1]<<8|t[D+2]<<16)>>(B&7)&(1<>3;var Ae=dv[Pt]+((t[D]|t[D+1]<<8|t[D+2]<<16)>>(B&7)&(1<>3,Be=I.t[Be]+((t[D]|t[D+1]<<8)>>(B&7)&(1<>3,ct=P.t[ct]+((t[D]|t[D+1]<<8)>>(B&7)&(1<>3,We=O.t[We]+((t[D]|t[D+1]<<8)>>(B&7)&(1<3)e.o[2]=e.o[1],e.o[1]=e.o[0],e.o[0]=V-=3;else{var Ke=V-(Ae!=0);Ke?(V=Ke==3?e.o[0]-1:e.o[Ke],Ke>1&&(e.o[2]=e.o[1]),e.o[1]=e.o[0],e.o[0]=V):V=e.o[0]}for(var w=0;wwe&&(Ee=we);for(var w=0;w{const{memory:n,uncompress:r}=t.exports,s=68e3,o=s+e.byteLength,a=s+e.byteLength+i;if(n.buffer.byteLength0};Xe.prototype.readMoreInput=function(){if(!(this.bit_end_pos_>256))if(this.eos_){if(this.bit_pos_>this.bit_end_pos_)throw new Error("Unexpected end of input "+this.bit_pos_+" "+this.bit_end_pos_)}else{const t=this.buf_ptr_,e=this.input_.read(this.buf_,t,Lt);if(e<0)throw new Error("Unexpected end of input");if(e=8;)this.val_>>>=8,this.val_|=this.buf_[this.pos_&bp]<<24,this.pos_++,this.bit_pos_=this.bit_pos_-8>>>0,this.bit_end_pos_=this.bit_end_pos_-8>>>0};Xe.prototype.readBits=function(t){32-this.bit_pos_>>this.bit_pos_&Ev[t];return this.bit_pos_+=t,e};const Sv=8,la=8,Rv=255,fa=18,vv=new Uint8Array([1,2,3,4,0,5,17,6,16,7,8,9,10,11,12,13,14,15]),Cv=new Uint16Array([256,402,436,468,500,534,566,598,630,662,694,726,758,790,822,854,886,920,952,984,1016,1048,1080]);function te(t,e){this.bits=t,this.value=e}const tu=16,pi=15;function iu(t,e){let i=1<>=1;return(t&i-1)+i}function nu(t,e,i,n,r){do n-=i,t[e+n]=new te(r.bits,r.value);while(n>0)}function Pv(t,e,i){let n=1<0;--o[g]){const y=new te(g&255,c[p++]&65535);nu(t,e+h,_,f,y),h=iu(h,g)}const d=u-1;let m=-1;for(let g=i+1,_=2;g<=pi;++g,_<<=1)for(;o[g]>0;--o[g]){(h&d)!==m&&(e+=f,l=Pv(o,g,i),f=1<>i),_,f,y),h=iu(h,g)}return u}function Hr(t,e,i,n){const r=new Uint8Array(t);n.readMoreInput();const s=n.readBits(2);if(s===1){let a=t-1,c=0;const l=new Int32Array(4),f=n.readBits(2)+1;for(;a;)a>>=1,c++;for(let u=0;u0;u++){const h=vv[u];let p=0;n.fillBitWindow(),p+=n.val_>>>n.bit_pos_&15,n.bit_pos_+=f[p].bits;const d=f[p].value;a[h]=d,d!==0&&(c-=32>>d,l++)}if(!(l===1||c===0))throw new Error("[ReadHuffmanCode] invalid num_codes or space");Iv(a,t,r,n)}const o=wp(e,i,la,r,t);if(!o)throw new Error("brotli BuildHuffmanTable failed");return o}function Ri(t,e,i){i.fillBitWindow(),e+=i.val_>>>i.bit_pos_&Rv;const n=t[e].bits-la;return n>0&&(i.bit_pos_+=la,e+=t[e].value,e+=i.val_>>>i.bit_pos_&(1<0;){let f=0;n.readMoreInput(),n.fillBitWindow(),f+=n.val_>>>n.bit_pos_&31,n.bit_pos_+=l[f].bits;const u=l[f].value&255;if(u>u);else{const h=u-14;let p=0;u===tu&&(p=s),a!==p&&(o=0,a=p);const d=o;o>0&&(o-=2,o<<=h),o+=n.readBits(h)+3;const m=o-d;if(r+m>e)throw new Error("[ReadHuffmanCodeLengths] symbol + repeat_delta > num_symbols");for(let g=0;g1&&s===0)throw new Error("Invalid size byte");e.meta_block_length|=s<4&&r===0)throw new Error("Invalid size nibble");e.meta_block_length|=r<0;)s.readMoreInput(),n[a++]=s.readBits(8),a===o&&(t.write(n,o),a=0);return}if(s.bit_end_pos_<32)throw new Error("copyUncompressedBlockToOutput: br.bit_end_pos_ < 32");for(;s.bit_pos_<32;)n[a]=s.val_>>>s.bit_pos_,s.bit_pos_+=8,a++,e--;let l=s.bit_end_pos_-s.bit_pos_>>3;if(c+l>Xe.IBUF_MASK){const f=Xe.IBUF_MASK+1-c;for(let u=0;u=o){t.write(n,o),a-=o;for(let f=0;f=o;){if(l=o-a,s.input_.read(n,a,l)0?17+e:(e=t.readBits(3),e>0?8+e:17)}function zv(t){const e=t.bit_pos_+7&-8;return!t.readBits(e-t.bit_pos_)}function or(t,e,i){const n=Ri(t,e,i),{offset:r,nbits:s}=xv[n];return r+i.readBits(s)}const ru=new Uint8Array([0,0,0,0,0,0,0,0,0,4,4,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,12,16,12,12,20,12,16,24,28,12,12,32,12,36,12,44,44,44,44,44,44,44,44,44,44,32,32,24,40,28,12,12,48,52,52,52,48,52,52,52,48,52,52,52,52,52,48,52,52,52,52,52,48,52,52,52,52,52,24,12,28,12,12,12,56,60,60,60,56,60,60,60,56,60,60,60,60,60,56,60,60,60,60,60,56,60,60,60,60,60,24,12,28,12,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,0,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48,56,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,14,15,15,15,15,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,22,22,22,22,23,23,23,23,24,24,24,24,25,25,25,25,26,26,26,26,27,27,27,27,28,28,28,28,29,29,29,29,30,30,30,30,31,31,31,31,32,32,32,32,33,33,33,33,34,34,34,34,35,35,35,35,36,36,36,36,37,37,37,37,38,38,38,38,39,39,39,39,40,40,40,40,41,41,41,41,42,42,42,42,43,43,43,43,44,44,44,44,45,45,45,45,46,46,46,46,47,47,47,47,48,48,48,48,49,49,49,49,50,50,50,50,51,51,51,51,52,52,52,52,53,53,53,53,54,54,54,54,55,55,55,55,56,56,56,56,57,57,57,57,58,58,58,58,59,59,59,59,60,60,60,60,61,61,61,61,62,62,62,62,63,63,63,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),ar=new Uint16Array([1024,1536,1280,1536,0,256,768,512]);function su(t,e){let i=0;e.readMoreInput();const n=Pp(e)+1,r=new Uint8Array(t);if(n<=1)return[n,r];e.readBits(1)&&(i=e.readBits(4)+1);const o=[];for(let a=0;a=t)throw new Error("[DecodeContextMap] i >= context_map_size");r[a]=0,a++}}else r[a]=c-i,a++}return e.readBits(1)&&Hv(r,t),[n,r]}function jv(t,e){const i=t[e];for(let n=e;n;n--)t[n]=t[n-1];t[0]=i}function Hv(t,e){const i=new Uint8Array(256);for(let n=0;n<256;n++)i[n]=n;for(let n=0;nthis.buffer.length&&(i=this.buffer.length-this.pos);for(let n=0;nthis.buffer.length)throw new Error("brotli output buffer is not large enough");return this.buffer.set(t.subarray(0,e),this.pos),this.pos+=e,e};const Yv=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);function je(t,e,i){const n=e/8|0;return(t[n]|t[n+1]<<8)>>(e&7)&i}function ro(t,e){const i=e/8|0;return(t[i]|t[i+1]<<8|t[i+2]<<16)>>(e&7)}function Xv(t){return(t+7)/8|0}function Qv(t,e){if(t[e++]!==31||t[e++]!==139||t[e++]!==8)return 0;const i=t[e++];e+=6,i&4&&(e+=(t[e+10]|t[e+11]<<8)+2);for(let n=(i>>3&1)+(i>>4&1);n>0;n-=+!t[e++]);return e+(i&2)}function uc(t,e,i=0,n=0){let r=e??new Uint8Array(1024);if(!(t.length-i))return r;const s=Qv(t,i);if(s===t.length-8)return r;if(s>t.length-8)throw new Error("unexpected EOF");let o=s*8,a=0,c=0,l=0,f,u;const h=t.length*8;function p(d){if(!e&&d>r.length){const m=r;r=new Uint8Array(Math.max(m.length*2,d)),r.set(m)}}do{if(!f){a=je(t,o,1);const _=je(t,o+1,3);if(o+=3,_)if(_===1)f=Uv,u=kv,c=9,l=5;else if(_===2){const y=je(t,o,31)+257,A=je(t,o+10,15)+4,b=y+je(t,o+5,31)+1;o+=14;const T=new Uint8Array(b),w=new Uint8Array(19);for(let I=0;I>4;if(B<16)T[I++]=B;else{let D=0,K=0;for(B===16?(K=3+je(t,o,3),o+=2,D=T[I-1]):B===17?(K=3+je(t,o,7),o+=3):B===18&&(K=11+je(t,o,127),o+=7);K--;)T[I++]=D}}const P=T.subarray(0,y),O=T.subarray(y);c=Math.max(...P),l=Math.max(...O),f=un(P,c),u=un(O,l)}else throw new Error("invalid block type");else{const y=Xv(o)+4,A=t[y-4]|t[y-3]<<8,b=y+A;if(b>t.length)throw new Error("unexpected EOF");p(n+A),r.set(t.subarray(y,b),n),n+=A,o=b*8;continue}if(o>h)throw new Error("unexpected EOF")}p(n+131072);const d=(1<>4;if(o+=_&15,o>h)throw new Error("unexpected EOF");if(!_)throw new Error("invalid length/literal");if(y<256)r[n++]=y;else if(y===256){g=o,f=void 0;break}else{let A=y-254;if(y>264){const M=y-257,x=Tp[M];A=je(t,o,(1<>4;if(!b)throw new Error("invalid distance");o+=b&15;let w=Fv[T];if(T>3){const M=Ep[T];w+=ro(t,o)&(1<h)throw new Error("unexpected EOF");const v=n+A;if(n'),new R("",N,` `),new R("",Gv,""),new R("",N,"]"),new R("",N," for "),new R("",rC,""),new R("",Zv,""),new R("",N," a "),new R("",N," that "),new R(" ",oe,""),new R("",N,". "),new R(".",N,""),new R(" ",N,", "),new R("",sC,""),new R("",N," with "),new R("",N,"'"),new R("",N," from "),new R("",N," by "),new R("",oC,""),new R("",aC,""),new R(" the ",N,""),new R("",Jv,""),new R("",N,". The "),new R("",le,""),new R("",N," on "),new R("",N," as "),new R("",N," is "),new R("",tC,""),new R("",ou,"ing "),new R("",N,` `),new R("",N,":"),new R(" ",N,". "),new R("",N,"ed "),new R("",lC,""),new R("",cC,""),new R("",eC,""),new R("",N,"("),new R("",oe,", "),new R("",iC,""),new R("",N," at "),new R("",N,"ly "),new R(" the ",N," of "),new R("",$v,""),new R("",Mp,""),new R(" ",oe,", "),new R("",oe,'"'),new R(".",N,"("),new R("",le," "),new R("",oe,'">'),new R("",N,'="'),new R(" ",N,"."),new R(".com/",N,""),new R(" the ",N," of the "),new R("",oe,"'"),new R("",N,". This "),new R("",N,","),new R(".",N," "),new R("",oe,"("),new R("",oe,"."),new R("",N," not "),new R(" ",N,'="'),new R("",N,"er "),new R(" ",le," "),new R("",N,"al "),new R(" ",le,""),new R("",N,"='"),new R("",le,'"'),new R("",oe,". "),new R(" ",N,"("),new R("",N,"ful "),new R(" ",oe,". "),new R("",N,"ive "),new R("",N,"less "),new R("",le,"'"),new R("",N,"est "),new R(" ",oe,"."),new R("",le,'">'),new R(" ",N,"='"),new R("",oe,","),new R("",N,"ize "),new R("",le,"."),new R(" ",N,""),new R(" ",N,","),new R("",oe,'="'),new R("",le,'="'),new R("",N,"ous "),new R("",le,", "),new R("",oe,"='"),new R(" ",oe,","),new R(" ",le,'="'),new R(" ",le,", "),new R("",le,","),new R("",le,"("),new R("",le,". "),new R(" ",le,"."),new R("",le,"='"),new R(" ",le,". "),new R(" ",oe,'="'),new R(" ",le,"='"),new R(" ",oe,"='")],fC=Tr.length;function au(t,e){return t[e]<192?(t[e]>=97&&t[e]<=122&&(t[e]^=32),1):t[e]<224?(t[e+1]^=32,2):(t[e+2]^=5,3)}function uC(t,e,i,n,r){const s=qv(),{prefix:o}=Tr[r],{suffix:a}=Tr[r],c=Tr[r].transform;let l=cn&&(l=n);let u=0;for(;u0;){const d=au(t,h);h+=d,n-=d}let p=0;for(;pe.buffer.length){const V=new Uint8Array(i+b);V.set(e.buffer),e.buffer=V}if(n=O.input_end,O.is_metadata){for(zv(h);b>0;--b)h.readMoreInput(),h.readBits(8);continue}if(b===0)continue;if(O.is_uncompressed){h.bit_pos_=h.bit_pos_+7&-8,Wv(e,b,i,g,m,h),i+=b;continue}for(let V=0;V<3;V++)v[V]=Pp(h)+1,v[V]>=2&&(Hr(v[V]+2,y,V*At,h),Hr(pC,A,V*At,h),T[V]=or(A,V*At,h),x[V]=1);h.readMoreInput();const I=h.readBits(2),k=ha+(h.readBits(4)<0;){let V;h.readMoreInput(),T[1]===0&&(no(v[1],y,1,w,M,x,h),T[1]=or(A,At,h),me=f[1].htrees[w[1]]),T[1]--;const we=Ri(f[1].codes,me,h);let Ae=we>>6;Ae>=2?(Ae-=2,V=-1):V=0;const Ke=Bv[Ae]+(we>>3&7),he=Mv[Ke],Ee=he.offset+h.readBits(he.nbits),Li=Nv[Ae]+(we&7),On=Ov[Li],Se=On.offset+h.readBits(On.nbits);c=g[i-1&m],l=g[i-2&m];for(let Re=0;Re4?3:Se-2)&255,ft=Pt[lt+Re];if(V=Ri(f[2].codes,f[2].htrees[ft],h),V>=k){V-=k;const ut=V&B;V>>=I;const Ze=(V>>1)+1,nt=(2+(V&1)<s)if(Se>=yC&&Se<=fu){let Re=_C[Se];const ft=qe-s-1,ut=AC[Se],Ze=(1<>ut;if(Re+=nt*Se,Bn=_){e.write(g,d);for(let oi=0;oi0&&(o[a&3]=qe,a++),Se>b)throw new Error("Invalid backward reference");for(let Re=0;Re>4;if(o){let h=o+240;for(;h===255;)o+=h=t[r++];if(e.set(t.subarray(r,r+o),n),n+=o,r+=o,r>=t.length)return n-i}const a=t[r++]|t[r++]<<8;if(!a||a>n)throw new Error(`lz4 offset out of range ${a}`);let c=(s&15)+4,l=c+240;for(;l===255;)c+=l=t[r++];let f=n-a;const u=n+c;for(;nuc(t,new Uint8Array(e)),BROTLI:bC,ZSTD:t=>Av(t),LZ4:EC,LZ4_RAW:SC};function RC(t){if(t==null)return null;if(typeof t=="string")return t;if(t instanceof Uint8Array){let e="";for(let i=0;i=t){const s=new Uint32Array(t);for(let o=0;o0;s--){const o=Math.floor(Math.random()*(s+1)),a=n[s];n[s]=n[o],n[o]=a}return n}function uu(t,e){if(e>=t.n)return t;const i=CC(t.n,e),n=new Float32Array(e),r=new Float32Array(e),s=new Array(e),o=new Uint32Array(e),a={};for(const c of t.availableFields)a[c]=new Array(e);for(let c=0;cn&&(n=c),lr&&(r=l)}const s=(n-e)*.04||1,o=(r-i)*.04||1;return{xmin:e-s,ymin:i-o,xmax:n+s,ymax:r+o}}const hu=[[102,194,165,255],[252,141,98,255],[141,160,203,255],[231,138,195,255],[166,216,84,255],[255,217,47,255],[229,196,148,255],[179,179,179,255],[31,119,180,255],[255,127,14,255],[44,160,44,255],[214,39,40,255],[148,103,189,255],[140,86,75,255],[227,119,194,255],[127,127,127,255],[188,189,34,255],[23,190,207,255]],nn=[110,110,128,220],lr=[[232,184,204],[196,174,222],[148,186,224],[104,192,202],[129,199,160],[216,198,124],[245,231,130]];function so(t,e,i){return t+(e-t)*i}function du(t){return Number.isFinite(t)?Math.abs(t)>=1e5||t!==0&&Math.abs(t)<.01?t.toExponential(2):Number.isInteger(t)?t.toLocaleString():t.toFixed(3):"—"}function IC(t,e,i){if(!Number.isFinite(t))return nn;const n=i>e?(t-e)/(i-e):.5,s=Math.max(0,Math.min(1,n))*(lr.length-1),o=Math.floor(s),a=s-o,c=lr[o],l=lr[Math.min(o+1,lr.length-1)];return[Math.round(so(c[0],l[0],a)),Math.round(so(c[1],l[1],a)),Math.round(so(c[2],l[2],a)),255]}function xC(t,e,i){const n=(1-Math.abs(2*i-1))*e,r=t*6,s=n*(1-Math.abs(r%2-1));let o=0,a=0,c=0;r<1?(o=n,a=s):r<2?(o=s,a=n):r<3?(a=n,c=s):r<4?(a=s,c=n):r<5?(o=s,c=n):(o=n,c=s);const l=i-n/2;return[Math.round((o+l)*255),Math.round((a+l)*255),Math.round((c+l)*255)]}function oo(t){let e=2166136261;for(let i=0;i>>0;return e>>>0}function MC(t){const n=((oo(t)/4294967295+0)%1+.6180339887498949)%1,r=.55+oo(`${t}#s`)%1e3/1e3*.2,s=.55+oo(`${t}#l`)%1e3/1e3*.1,[o,a,c]=xC(n,r,s);return[o,a,c,255]}function Yr(t){if(t==null)return null;if(typeof t=="string"){const e=t.trim();if(!e.startsWith("[")&&!e.startsWith("{"))return null;try{return Yr(JSON.parse(e))}catch{return null}}if(Array.isArray(t)){let e=null,i=-1/0;for(const n of t){if(!n||typeof n!="object")continue;const r=n,s=r.name??r.label??r.class,o=r.prob??r.score??r.confidence??0,a=typeof o=="number"?o:Number(o);typeof s=="string"&&a>i&&(i=a,e=s)}return e}if(typeof t=="object"){const e=t,i=e.name??e.label??e.class;return typeof i=="string"?i:null}return null}function Op(t){if(t==null)return"∅";const e=Yr(t);if(e!=null)return e;if(typeof t=="bigint")return t.toString();if(typeof t=="string")return t;if(typeof t=="number")return Number.isInteger(t)?t.toString():t.toFixed(3);try{return JSON.stringify(t)}catch{return String(t)}}const OC=1e4,BC={aspect_ratio:{vmin:.1,vmax:3,scale:"log"},resolution:{scale:"log"}};function NC(t,e,i){const n=t.length,r=new Uint8Array(n*4),s=i&&BC[i]||{},o=s.scale==="log";function a(A){return typeof A=="number"?A:typeof A=="bigint"?Number(A):NaN}function c(A){return o?A>0?Math.log10(A):NaN:A}let l=0,f=0,u=1/0,h=-1/0;for(let A=0;Ah&&(h=T))}if(f>0&&l/f>.8&&h>u){const A=s.vmin!=null?c(s.vmin):u,b=s.vmax!=null?c(s.vmax):h,T=Number.isFinite(A)?A:u,w=Number.isFinite(b)?b:h;for(let O=0;Ob[1]-A[1]),_=new Map;for(let A=0;A({key:A,color:_.get(A)??nn,count:b}));return{kind:"categorical",colors:r,info:`${d.size} categor${d.size===1?"y":"ies"}`,categories:y}}let Ki=null;const fr=new Map;async function DC(){if(!Ki){const t=In("idx/shards.json"),e=fetch(t).then(async i=>{if(!i.ok){const n=await i.text().catch(()=>"");throw new Error(`idx/shards.json: ${i.status} ${i.statusText} ${n.slice(0,200)}`)}return await i.json()});e.catch(i=>{console.error("[idx] manifest load FAILED — no thumbnails will resolve",i),Ki===e&&(Ki=null)}),Ki=e}return Ki}function FC(t){const e=t instanceof Error?t.message:String(t);return/\b404\b/.test(e)}let Er=!1,pu=!1;function UC(){return Er}function kC(t){const e=parseInt(t.slice(0,2),16);return Number.isFinite(e)?e:0}async function LC(t){let e=fr.get(t);if(e)return e;const i=t.toString(16).padStart(2,"0"),n=In(`idx/idx_${i}.parquet`);return e=(async()=>{let r;try{r=await oc({url:n})}catch(a){if(FC(a))return console.warn(`[idx] bucket 0x${i} has no parquet (404) — treating as empty`,{url:n}),new Map;throw a}const s=await lc({file:r,columns:["hash_perceptual","shard_id","row_idx"],compressors:hc,utf8:!1}),o=new Map;for(const a of s){const c=typeof a.hash_perceptual=="string"?a.hash_perceptual:new TextDecoder().decode(a.hash_perceptual);o.set(c,{shard_id:a.shard_id,row_idx:a.row_idx})}return o})(),e.catch(r=>{console.error(`[idx] bucket 0x${i} load FAILED`,{url:n,err:r}),fr.get(t)===e&&fr.delete(t)}),fr.set(t,e),e}async function WC(t){let e;try{e=await DC()}catch{return Er=!0,null}if(!e.shards||e.shards.length===0)return Er=!0,pu||(pu=!0,console.warn("[idx] hash index is empty (idx/shards.json has no shards) — hover thumbnails will fall back to the preview atlas. Re-run build_thumb_shards for this dataset to enable full-res hovers.")),null;Er=!1;const i=kC(t),n=await LC(i),r=n.get(t);if(!r){const o=[];for(const a of n.keys())if(o.push(a),o.length>=3)break;return console.warn(`[idx] miss hash=${t} bucket=0x${i.toString(16).padStart(2,"0")} (${n.size.toLocaleString()} entries; sample keys: ${o.join(", ")})`),null}const s=e.shards.find(o=>o.id===r.shard_id);return s?{uri:s.uri,row_idx:r.row_idx}:(console.warn(`[idx] hash ${t} found in bucket but shard_id=${r.shard_id} is not in the manifest`),null)}function VC(t){if(!Go)return null;const e=t.lastIndexOf("/");if(e<0)return null;const i=t.slice(e+1);let n=Go.replace(/\/$/,"");if(n.startsWith("hf://buckets/")){const r=n.slice(13),[s,o,...a]=r.split("/");if(!s||!o)return null;n=`https://huggingface.co/buckets/${s}/${o}/resolve/${a.join("/")}`}return`${n}/${i}`}function zC(t){const e=new Map;return{get(i){if(!e.has(i))return;const n=e.get(i);return e.delete(i),e.set(i,n),n},set(i,n){if(e.has(i)&&e.delete(i),e.set(i,n),e.size>t){const r=e.keys().next().value;r!==void 0&&e.delete(r)}}}}const dc=zC(1024),Sr=new Map,ao=new Map;function jC(t){let e=ao.get(t);return e||(e=(async()=>{const i=await oc({url:t});return TR(i)})(),e.catch(()=>ao.delete(t)),ao.set(t,e),e)}const Bp=8;let hn=0;const Np=[];async function HC(){if(hnNp.push(t)),hn++}function YC(){hn--;const t=Np.shift();t&&t()}function gu(t,e,i){return new Promise((n,r)=>{const s=setTimeout(()=>r(new Error(`timeout after ${e}ms: ${i}`)),e);t.then(o=>{clearTimeout(s),n(o)},o=>{clearTimeout(s),r(o)})})}function XC(t){const e=VC(t);if(e)return e;if(t.startsWith("http://")||t.startsWith("https://"))return t;if(t.startsWith("hf://")){const i=t.slice(5);if(i.startsWith("datasets/")){const[n,...r]=i.slice(9).split("/"),[s,o="main"]=n.split("@");return`https://huggingface.co/datasets/${s}/resolve/${o}/${r.join("/")}`}if(i.startsWith("buckets/")){const[n,r,...s]=i.slice(8).split("/");if(n&&r&&s.length)return`https://huggingface.co/buckets/${n}/${r}/resolve/${s.join("/")}`}}if(t.startsWith("s3://")){if(!Zo)return null;const i=t.slice(5),n=i.indexOf("/"),r=n>=0?i.slice(n+1):i;return`${Zo.replace(/\/$/,"")}/${r}`}return QS(t)}function QC(t){const e=new Uint8Array(t.byteLength);e.set(t);const i=new Blob([e.buffer],{type:"image/webp"});return URL.createObjectURL(i)}async function pa(t){const e=dc.get(t);if(e)return e;const i=Sr.get(t);if(i)return i;const n=qC(t);return Sr.set(t,n),n.finally(()=>Sr.delete(t)),n}function KC(t){t&&(dc.get(t)||Sr.has(t)||hn>=Bp||pa(t))}async function qC(t){let e;try{e=await WC(t)}catch(n){return console.error("[hover] hash-index lookup threw",{hash:t,err:n}),null}if(!e)return UC()||console.warn(`[hover] hash "${t}" is not in idx/ — was it included in the pipeline run that produced the hash index? (subsamples / --limit runs only index the rows they processed)`),null;const i=XC(e.uri);if(!i)return console.warn(`[hover] source URI "${e.uri}" not reachable from the browser. Set VITE_SOURCE_BASE_URL to an HTTPS mirror.`),null;await HC();try{const n=await gu(jC(i),3e4,`asyncBufferFromUrl(${i})`),r=await gu(lc({file:n,columns:["thumbnail"],rowStart:e.row_idx,rowEnd:e.row_idx+1,compressors:hc,utf8:!1}),45e3,`parquetReadObjects(${i}, row=${e.row_idx})`);if(!r.length)return console.warn("[hover] empty row read",{hash:t,url:i,row_idx:e.row_idx}),null;let s=null;const o=r[0].thumbnail;if(o instanceof Uint8Array)s=o;else if(o&&typeof o=="object"&&"bytes"in o){const c=o.bytes;c instanceof Uint8Array&&(s=c)}else if(typeof o=="string"){const c=o,l=new Uint8Array(c.length);for(let f=0;f{const t=In("preview/manifest.json");try{const e=await fetch(t);if(!e.ok)return console.warn(`[preview] manifest.json: ${e.status} — preview atlas disabled`),null;const i=await e.json();return console.info(`[preview] manifest: ${i.n_pages} pages, ${i.n_points.toLocaleString()} points, ${i.page_px}px/page (${i.cell_px}px cells)`),tP(i),i}catch(e){return console.warn("[preview] manifest fetch failed",e),null}})()),Rr}function tP(t){const e=t.n_pages<=$C?t.n_pages:JC;console.info(`[preview] preloading ${e}/${t.n_pages} pages (rest are lazy)`);const i=Array.from({length:e},(r,s)=>s),n=Array.from({length:Math.min(GC,i.length)},async()=>{for(;i.length;){const r=i.shift();try{await Dp(r)}catch(s){console.warn(`[preview] preload page ${r} failed`,s)}}});Promise.all(n).then(()=>console.info(`[preview] preload of ${e} pages complete`))}function Dp(t){let e=mu.get(t);if(e)return e;const i=In(`preview/page_${String(t).padStart(4,"0")}.webp`);return e=(async()=>{const n=performance.now(),r=await fetch(i);if(!r.ok)return console.warn(`[preview] page ${t}: ${r.status}`),null;const s=await r.blob(),o=await createImageBitmap(s);return console.info(`[preview] page ${t} loaded ${(s.size/1024).toFixed(0)}KB in ${(performance.now()-n).toFixed(0)}ms (${o.width}×${o.height})`),o})(),e.catch(n=>console.warn(`[preview] page ${t} load failed`,n)),mu.set(t,e),e}async function _u(t){const e=hi.get(t);if(e)return e;const i=await Rr;if(!i||t<0||t>=i.n_points)return null;const n=i.page_cells_side*i.page_cells_side,r=Math.floor(t/n),s=t%n,o=Math.floor(s/i.page_cells_side),a=s%i.page_cells_side,c=await Dp(r);if(!c)return null;const l=i.cell_px;let f=null;try{if(typeof OffscreenCanvas<"u"){const h=new OffscreenCanvas(l,l),p=h.getContext("2d");p&&(p.drawImage(c,a*l,o*l,l,l,0,0,l,l),f=await h.convertToBlob({type:"image/webp",quality:.85}))}else{const h=document.createElement("canvas");h.width=l,h.height=l;const p=h.getContext("2d");p&&(p.drawImage(c,a*l,o*l,l,l,0,0,l,l),f=await new Promise(d=>h.toBlob(m=>d(m),"image/webp",.85)))}}catch(h){return console.warn(`[preview] crop ${t} failed`,h),null}if(!f)return null;const u=URL.createObjectURL(f);if(hi.set(t,u),hi.size>ZC){const h=hi.keys().next().value;if(h!==void 0){const p=hi.get(h);hi.delete(h),p&&URL.revokeObjectURL(p)}}return u}const iP=5;function Au(t){let e=t;if(typeof t=="string"){const n=t.trim();if(!n.startsWith("["))return null;try{e=JSON.parse(n)}catch{return null}}if(!Array.isArray(e)||e.length===0)return null;const i=[];for(const n of e){if(!n||typeof n!="object")return null;const r=n,s=r.name??r.label??r.class,o=r.prob??r.score??r.confidence;if(typeof s!="string"||typeof o!="number"||!Number.isFinite(o))return null;i.push({name:s,prob:o})}return i}function De(t){return t.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function ur(t){return t<0?0:t>1?1:t}function rn(t){return Number.isFinite(t)?Math.abs(t)>=1e5||Math.abs(t)>0&&Math.abs(t)<.001?t.toExponential(2):Number.isInteger(t)?t.toLocaleString():t.toFixed(3):"—"}function yu(t){if(t==null)return"—";if(typeof t=="number")return rn(t);if(typeof t=="boolean")return t?"true":"false";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function nP(t){const e=[...t].sort((n,r)=>r.prob-n.prob).slice(0,iP),i=e[0]?.prob||1;return`
${e.map(n=>`
${De(n.name)} ${(n.prob*100).toFixed(1)}%
`).join("")}
`}function $(t){const e=document.querySelector(t);if(!e)throw new Error(`missing ${t}`);return e}function bu(t){const e=document.getElementById("toast");if(e){if(t==null){e.hidden=!0;return}e.textContent=t,e.hidden=!1}}function hr(t){const e=document.getElementById("stats");e&&(e.textContent=t)}function co(t){if(t>=1e6){const e=t/1e6;return`${e>=10?Math.round(e):e.toFixed(1)}M`}return t>=1e4?`${Math.round(t/1e3)}k`:t.toLocaleString()}function wu(t,e){return t>=e?`${e.toLocaleString()} points · UMAP-2D`:`${t.toLocaleString()} / ${e.toLocaleString()} points · UMAP-2D (sampled)`}const En=1e3;function rP(t,e,i){if(e<=i)return En;const n=Math.log(t/i)/Math.log(e/i);return Math.round(Math.max(0,Math.min(1,n))*En)}function sP(t,e,i){if(e<=i)return e;const n=Math.max(0,Math.min(En,t))/En,r=Math.round(i*Math.pow(e/i,n));return Math.max(i,Math.min(e,r))}function oP(t){const e=document.getElementById("data-source");if(!e)return;let i=t;try{const n=new URL(t),s=n.pathname.split("/").filter(Boolean).slice(-2).join("/");i=s?`${n.host}/…/${s}`:n.host}catch{i=t}e.innerHTML=`data:${i.replace(/[<>&]/g,n=>({"<":"<",">":">","&":"&"})[n])}`,e.setAttribute("title",t)}function aP(t){const e=document.getElementById("dataset-version");if(e){if(!t){e.hidden=!0;return}e.hidden=!1,e.innerHTML=`version:${t.replace(/[<>&]/g,i=>({"<":"<",">":">","&":"&"})[i])}`}}function cP(t){return`rgba(${t[0]}, ${t[1]}, ${t[2]}, ${(t[3]/255).toFixed(2)})`}const Tu="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMTYiIGhlaWdodD0iMjE2Ij48cmVjdCB3aWR0aD0iMjE2IiBoZWlnaHQ9IjIxNiIgZmlsbD0iIzExMTExYSIvPjwvc3ZnPg==";async function lP(){window.addEventListener("unhandledrejection",E=>{console.error("[app] unhandled rejection",E.reason)}),hr("loading points…"),oP(Jd()),aP(XS());let t;try{t=await vC()}catch(E){console.error(E),hr(`failed to load: ${E}`),bu(`Failed to load points: ${E.message??E}`);return}const e=JS(t.n),i=$d();console.info(`[app] render budget: ${e.toLocaleString()} / ${t.n.toLocaleString()} points (source: ${i!=null?"localStorage":"default-100k"}, hc=${navigator.hardwareConcurrency??"?"}, mem=${navigator.deviceMemory??"?"} GiB, mobile=${/Mobi|Android|iPhone|iPad/i.test(navigator.userAgent)})`);const n=uu(t,e);hr(wu(n.n,t.n)),eP();const r=KS.filter(E=>E in n.fields);if(r.length===0){bu("points.parquet has no recognizable color-by columns");return}const s=$("#color-by");s.innerHTML="";for(const E of r){const S=document.createElement("option");S.value=E,S.textContent=E,s.appendChild(S)}const o={allPoints:t,points:n,sampleSize:n.n,colorField:r[0],pointSize:parseFloat($("#point-size").value),opacity:parseFloat($("#opacity").value)/100,colors:new Uint8Array(n.n*4),catKeys:null,hidden:new Set,rangeFilter:null,selectedIndex:-1,encoder:null,labelCentroids:[],labelHits:[],showLabels:$("#show-labels").checked},a=PC(o.allPoints),c=(a.xmin+a.xmax)/2,l=(a.ymin+a.ymax)/2,f=$("#canvas-host"),u=f.getBoundingClientRect(),h=Math.max(a.xmax-a.xmin,a.ymax-a.ymin)||1,p=Math.min(u.width,u.height)||600,d=Math.log2(p/h),m={target:[c,l,0],zoom:d,minZoom:d-4,maxZoom:d+14};let g={...m};const _=$("#hover-card"),y=$("#hover-img"),A=$("#hover-spinner"),b=$("#hover-meta"),T=$("#detail-panel"),w=$("#detail-img"),v=$("#detail-spinner"),M=$("#detail-meta"),x=$("#detail-close"),P=$("#label-overlay"),O=P.getContext("2d");let I=0,k=-1;function B(E,S){const F=_.offsetWidth||248,L=_.offsetHeight||290,H=12,z=f.getBoundingClientRect();let U=E+18,W=S+18;U+F+H>z.right&&(U=E-F-18),W+L+H>z.bottom&&(W=S-L-18),U=Math.max(z.left+H,U),W=Math.max(z.top+H,W),_.style.left=`${U}px`,_.style.top=`${W}px`}function D(E,S){E?(y.src=E,A.hidden=!0):(y.removeAttribute("src"),A.hidden=!!S)}function K(E,S){w.removeAttribute("src"),v.hidden=!1}function Be(E,S,F){const L=o.points.hashes[E]??"",H=S.map(z=>{if(E<0)return null;const U=o.points.fields[z];if(!U)return null;const W=U[E];if(W==null)return null;const X=Au(W);let Z;if(X&&X.length){const ie=X.reduce((ve,re)=>re.prob>ve.prob?re:ve);Z=`${ie.name} (${(ie.prob*100).toFixed(0)}%)`}else Z=Yr(W)??yu(W);return`${De(z)}${De(Z)}`}).filter(Boolean).join("");F.innerHTML=`
${De(L)}
${H}`}function We(){o.selectedIndex=-1,T.hidden=!0,w.removeAttribute("src"),delete w.dataset.hires,v.hidden=!0}function ct(E){if(E<0){We();return}T.hidden=!1;const S=o.points.hashes[E]??"",F=o.points.availableFields,L=[],H=[];for(const W of F){const X=o.points.fields[W]?.[E];if(X==null)continue;const Z=Au(X);Z&&Z.length?H.push({field:W,preds:Z}):L.push(W)}const z=L.map(W=>{const X=o.points.fields[W]?.[E],ie=Yr(X)??yu(X);return`${De(W)}${De(ie)}`}).join(""),U=H.map(({field:W,preds:X})=>`${De(W)}
${nP(X)}
`).join("");M.innerHTML=`
${De(S)}
${z}${U}`,K(),_u(o.points.origIndex[E]).then(W=>{o.selectedIndex===E&&W&&w.dataset.hires!=="1"&&(w.src=W)}),S?pa(S).then(W=>{o.selectedIndex===E&&(W?(w.src=W,w.dataset.hires="1",v.hidden=!0):(v.hidden=!0,w.getAttribute("src")||(w.src=Tu)))}):v.hidden=!0}function Pt(E,S){const F=f.getBoundingClientRect(),L=F.width,H=F.height,z=Math.pow(2,g.zoom),U=L/2+(E-g.target[0])*z,W=H/2-(S-g.target[1])*z;return[U,W]}function Ne(){if(!O)return;const E=window.devicePixelRatio||1,S=f.getBoundingClientRect();if(P.width!==Math.floor(S.width*E)&&(P.width=Math.floor(S.width*E),P.height=Math.floor(S.height*E),P.style.width=`${S.width}px`,P.style.height=`${S.height}px`),O.setTransform(E,0,0,E,0,0),O.clearRect(0,0,S.width,S.height),o.labelHits=[],!o.showLabels||o.labelCentroids.length===0)return;O.font='600 12px ui-sans-serif, system-ui, -apple-system, "Inter", sans-serif',O.textAlign="center",O.textBaseline="middle",O.lineWidth=3,O.lineJoin="round";const F=uP(o,g,S),L=U=>F?F.get(U.key)??0:U.count,H=[],z=[...o.labelCentroids].sort((U,W)=>L(W)-L(U));for(const U of z){if(F){const ye=F.get(U.key)??0,Fn=Math.max(2,Math.floor(U.count*.02));if(yeS.width+50||X>S.height+20)continue;const Z=U.key,ie=O.measureText(Z).width+12,ve=18,re={x:W-ie/2,y:X-ve/2,w:ie,h:ve};let Dn=!1;for(const ye of H)if(re.xye.x&&re.yye.y){Dn=!0;break}Dn||(H.push(re),o.labelHits.push({...re,key:U.key}),O.strokeStyle="rgba(0, 0, 0, 0.85)",O.strokeText(Z,W,X),O.fillStyle="rgba(255, 255, 255, 0.95)",O.fillText(Z,W,X))}}function lt(){return new Ti({id:"points",data:{length:o.points.n},getPosition:(E,S)=>(S.target[0]=o.points.x[S.index],S.target[1]=o.points.y[S.index],S.target[2]=0,S.target),getFillColor:(E,S)=>{const F=S.index*4;return S.target[0]=o.colors[F],S.target[1]=o.colors[F+1],S.target[2]=o.colors[F+2],S.target[3]=o.colors[F+3],S.target},getRadius:()=>o.pointSize,radiusUnits:"pixels",radiusMinPixels:.5,radiusMaxPixels:32,stroked:!1,pickable:!0,autoHighlight:!1,radiusScale:1,lineWidthMinPixels:0,updateTriggers:{getFillColor:o.colors,getRadius:o.pointSize}})}function Qe(){return new Ti({id:"points-pick",data:{length:o.points.n},getPosition:(E,S)=>(S.target[0]=o.points.x[S.index],S.target[1]=o.points.y[S.index],S.target[2]=0,S.target),getFillColor:()=>[0,0,0,0],getRadius:()=>Math.max(o.pointSize*7,12),radiusUnits:"pixels",radiusMinPixels:12,stroked:!1,pickable:!0,opacity:0,parameters:{depthTest:!1}})}function It(){if(o.selectedIndex<0)return null;const E=o.points.x[o.selectedIndex],S=o.points.y[o.selectedIndex];return new Ti({id:"points-selected",data:[{idx:o.selectedIndex}],getPosition:()=>[E,S,0],getFillColor:[247,240,235,255],getLineColor:[79,169,169,255],stroked:!0,filled:!0,lineWidthUnits:"pixels",getLineWidth:2,lineWidthMinPixels:2,getRadius:()=>Math.max(o.pointSize*2.4,8),radiusUnits:"pixels",radiusMinPixels:5,pickable:!1,parameters:{depthTest:!1}})}function xt(){return o.selectedIndex<0?null:new Ti({id:"points-selected-halo",data:[{idx:o.selectedIndex}],getPosition:()=>[o.points.x[o.selectedIndex],o.points.y[o.selectedIndex],0],getFillColor:[79,169,169,0],getLineColor:[79,169,169,170],stroked:!0,filled:!1,lineWidthUnits:"pixels",getLineWidth:4,lineWidthMinPixels:4,getRadius:()=>Math.max(o.pointSize*4.5,16),radiusUnits:"pixels",radiusMinPixels:11,pickable:!1,parameters:{depthTest:!1}})}function me(){const E=[Qe(),lt()],S=xt();S&&E.push(S);const F=It();F&&E.push(F),nt.setProps({layers:E,viewState:{ortho:g}}),Ne()}function V(E){const S=Math.max(kt,Math.min(o.allPoints.n,Math.round(E)));S!==o.points.n&&(o.points=uu(o.allPoints,S),o.sampleSize=o.points.n,o.colors=new Uint8Array(o.points.n*4),o.catKeys=null,o.labelCentroids=[],We(),hr(wu(o.points.n,o.allPoints.n)),hs(o.points.n,o.allPoints.n),we())}function we(){const E=o.points.fields[o.colorField];if(!E){console.warn(`[app] color-by ${o.colorField} not in points.parquet`);return}const S=NC(E,o.opacity,o.colorField);o.encoder=S,o.hidden=new Set,o.rangeFilter=null,S.kind==="categorical"?o.catKeys=E.map(Op):o.catKeys=null,fP(o),Ae(S),Ke(S,o.colorField),me()}function Ae(E){if(o.colors=new Uint8Array(E.colors),E.kind==="categorical"){if(o.catKeys&&o.hidden.size>0){const S=o.catKeys.length;for(let F=0;FL)&&(o.colors[z*4+3]=0)}}}function Ke(E,S){const F=$("#legend-title"),L=$("#legend-body"),H=$("#legend-hint");if(F.textContent=`${S} — ${E.kind}`,H.textContent=E.kind==="continuous"?"drag handles to filter by range":"click toggles · double-click solos",L.innerHTML="",E.kind==="continuous"){L.classList.remove("legend-body");const z=o.rangeFilter??{lo:E.vmin,hi:E.vmax},U=he(z.lo,E),W=he(z.hi,E);L.innerHTML=`
${rn(z.lo)} ${rn(z.hi)}
${E.info}
`,Li(E,L);return}L.classList.add("legend-body");for(const z of E.categories){const U=document.createElement("div");U.className="legend-row",U.dataset.key=z.key,o.hidden.has(z.key)&&U.classList.add("is-hidden");const X=document.createElement("span");X.className="swatch",X.style.background=cP(z.color);const Z=document.createElement("span");Z.className="lbl",Z.textContent=z.key,Z.title=z.key;const ie=document.createElement("span");ie.className="count",ie.textContent=z.count.toLocaleString(),U.append(X,Z,ie),U.addEventListener("click",()=>On(z.key)),U.addEventListener("dblclick",ve=>{ve.preventDefault(),Se(z.key)}),L.appendChild(U)}if(o.encoder?.kind==="categorical"){const z=(o.encoder.info.match(/^(\d+)/)||["0","0"])[1];if(E.categories.length=.999;Te&&Ve?o.rangeFilter=null:o.rangeFilter={lo:ee,hi:ne},Ae(E),me(),ve(ee,ne)}function Dn(ee){const ne=F.getBoundingClientRect();return ur((ee-ne.left)/Math.max(1,ne.width))}let ye=null;function Fn(ee){if(!ye)return;const ne=Dn(ee.clientX),Te=o.rangeFilter??{lo:E.vmin,hi:E.vmax},Ve=he(Te.lo,E),kn=he(Te.hi,E);if(ye==="lo"){const ci=Ee(Math.min(ne,kn-ie),E);re(ci,Te.hi)}else{const ci=Ee(Math.max(ne,Ve+ie),E);re(Te.lo,ci)}}function Un(ee){if(!ye)return;const ne=ye==="lo"?L:H;try{ne.releasePointerCapture(ee.pointerId)}catch{}ye=null}function gc(ee,ne){ne.preventDefault(),ye=ee;const Te=ee==="lo"?L:H;try{Te.setPointerCapture(ne.pointerId)}catch{}}L.addEventListener("pointerdown",ee=>gc("lo",ee)),H.addEventListener("pointerdown",ee=>gc("hi",ee)),L.addEventListener("pointermove",Fn),H.addEventListener("pointermove",Fn),L.addEventListener("pointerup",Un),H.addEventListener("pointerup",Un),L.addEventListener("pointercancel",Un),H.addEventListener("pointercancel",Un);function mc(ee,ne){if(ne.key!=="ArrowLeft"&&ne.key!=="ArrowRight")return;ne.preventDefault();const Te=(ne.shiftKey?.05:.01)*(ne.key==="ArrowRight"?1:-1),Ve=o.rangeFilter??{lo:E.vmin,hi:E.vmax},kn=he(Ve.lo,E),ci=he(Ve.hi,E);if(ee==="lo"){const ds=Ee(Math.min(Math.max(kn+Te,0),ci-ie),E);re(ds,Ve.hi)}else{const ds=Ee(Math.max(Math.min(ci+Te,1),kn+ie),E);re(Ve.lo,ds)}}L.addEventListener("keydown",ee=>mc("lo",ee)),H.addEventListener("keydown",ee=>mc("hi",ee)),Z&&Z.addEventListener("click",()=>{o.rangeFilter=null,Ae(E),me(),ve(E.vmin,E.vmax)})}function On(E){o.hidden.has(E)?o.hidden.delete(E):o.hidden.add(E),o.encoder&&(Ae(o.encoder),Ke(o.encoder,o.colorField),me())}function Se(E){if(o.encoder?.kind!=="categorical")return;const S=new Set;if(o.catKeys)for(const L of o.catKeys)S.add(L);const F=new Set;for(const L of S)o.hidden.has(L)||F.add(L);if(F.size===1&&F.has(E))o.hidden=new Set;else{o.hidden=new Set;for(const L of S)L!==E&&o.hidden.add(L)}Ae(o.encoder),Ke(o.encoder,o.colorField),me()}const qe=16;function si(E){const S=o.points,F=S.x[E],L=S.y[E],H=new Float32Array(qe).fill(1/0),z=new Int32Array(qe).fill(-1);let U=0,W=1/0;for(let X=0;X=W)){H[U]=ve,z[U]=X,W=-1/0,U=0;for(let re=0;reW&&(W=H[re],U=re)}}for(let X=0;X0}async function ft(E){const S=E.index;if(S<0||!E.picked||!Re(S)){_.hidden=!0,k=-1;return}if(S===k){B(E.x??0,E.y??0);return}k=S,Be(S,qS,b),D(null,!1),delete y.dataset.hires,_.hidden=!1,B(E.x??0,E.y??0);const F=++I;_u(o.points.origIndex[S]).then(z=>{F===I&&y.dataset.hires!=="1"&&z&&D(z,!1)});const L=o.points.hashes[S]??"",H=L?await pa(L):null;F===I&&(H?(D(H,!0),y.dataset.hires="1"):y.getAttribute("src")?A.hidden=!0:D(Tu,!0),si(S))}function ut(E){const S=E.index;if(S<0||!E.picked||!Re(S)){We(),me();return}o.selectedIndex=S,ct(S),me()}let Ze=!1;const nt=new $a({parent:f,views:[new qd({id:"ortho",flipY:!1,controller:{dragPan:!0,scrollZoom:{speed:.02,smooth:!0}}})],viewState:{ortho:g},onViewStateChange:({viewState:E})=>{g=E,nt.setProps({viewState:{ortho:g}}),Ne()},layers:[],onHover:ft,onClick:ut,getCursor:({isDragging:E})=>E?"grabbing":Ze?"pointer":"default",style:{background:"transparent"}});we();const Bn=$("#point-size-val"),Wi=$("#opacity-val"),oi=$("#point-sample-val"),ai=$("#point-sample");function hs(E,S){oi.textContent=E>=S?`${co(S)} (all)`:`${co(E)} / ${co(S)}`}o.allPoints.n<=kt?ai.closest(".field")?.setAttribute("hidden",""):(ai.min="0",ai.max=String(En),ai.step="1",ai.value=String(rP(o.points.n,o.allPoints.n,kt))),hs(o.points.n,o.allPoints.n);let Nn=null;function Fp(E){Nn!=null&&window.clearTimeout(Nn),Nn=window.setTimeout(()=>{Nn=null,V(E),GS(E>=o.allPoints.n?null:E)},220)}ai.addEventListener("input",E=>{const S=parseInt(E.target.value,10),F=sP(S,o.allPoints.n,kt);hs(F,o.allPoints.n),Fp(F)}),$("#color-by").addEventListener("change",E=>{o.colorField=E.target.value,we()}),$("#opacity").addEventListener("input",E=>{const S=parseFloat(E.target.value);o.opacity=S/100,Wi.textContent=`${S.toFixed(0)}%`,we()}),$("#point-size").addEventListener("input",E=>{o.pointSize=parseFloat(E.target.value),Bn.textContent=o.pointSize.toFixed(1),me()}),$("#show-labels").addEventListener("change",E=>{o.showLabels=E.target.checked,Ne()}),$("#reset-view").addEventListener("click",()=>{g={...m},nt.setProps({viewState:{ortho:g}}),Ne()});const Up=E=>{E&&(E.preventDefault(),E.stopPropagation()),We(),me(),requestAnimationFrame(()=>{o.selectedIndex===-1&&me()})};x.addEventListener("click",Up),f.addEventListener("mouseleave",()=>{_.hidden=!0,k=-1,Ze&&(Ze=!1,nt.setProps({}))});function pc(E,S){if(!o.showLabels||o.labelHits.length===0)return null;const F=f.getBoundingClientRect(),L=E-F.left,H=S-F.top;for(let z=o.labelHits.length-1;z>=0;z--){const U=o.labelHits[z];if(L>=U.x&&L<=U.x+U.w&&H>=U.y&&H<=U.y+U.h)return U}return null}f.addEventListener("click",E=>{const S=pc(E.clientX,E.clientY);S&&(E.stopPropagation(),E.preventDefault(),Se(S.key))},{capture:!0}),f.addEventListener("pointermove",E=>{const F=!!pc(E.clientX,E.clientY);F!==Ze&&(Ze=F,nt.setProps({}))}),window.addEventListener("resize",()=>{_.hidden=!0,Ne()}),requestAnimationFrame(Ne)}function fP(t){const e=t.catKeys;if(!e){t.labelCentroids=[];return}const i=new Map,n=t.points.n;for(let a=0;ah||yd)continue;const A=n[g];!A||A==="∅"||m.set(A,(m.get(A)??0)+1)}return m}function hP(t,e,i){const n=i.length;if(n===0)return[0,0];if(n===1)return[t[i[0]],e[i[0]]];let r=1/0,s=-1/0,o=1/0,a=-1/0;for(let P=0;Ps&&(s=I),ka&&(a=k)}const c=s-r,l=a-o;if(c===0&&l===0)return[r,o];const f=Math.min(48,Math.max(6,Math.round(Math.sqrt(n)*1.5))),u=c>0?c/f:1,h=l>0?l/f:1,p=c>0?f:1,d=l>0?f:1,m=new Int32Array(p*d),g=new Int32Array(n),_=new Int32Array(n);for(let P=0;P0?Math.min(p-1,Math.floor((t[O]-r)/u)):0,k=l>0?Math.min(d-1,Math.floor((e[O]-o)/h)):0;g[P]=I,_[P]=k,m[k*p+I]++}const y=[1,2,1,2,4,2,1,2,1];let A=0,b=0,T=-1,w=-1;for(let P=0;P=d))for(let K=-1;K<=1;K++){const Be=O+K;Be<0||Be>=p||(I+=m[D*p+Be]*y[(B+1)*3+(K+1)])}}const k=m[P*p+O];(I>T||I===T&&k>w)&&(T=I,w=k,A=P,b=O)}let v=0,M=0,x=0;for(let P=0;P1||Math.abs(_[P]-A)>1)continue;const O=i[P];v+=t[O],M+=e[O],x++}return x===0?[(r+s)/2,(o+a)/2]:[v/x,M/x]}await YS();lP();