@luma.gl/engine 9.4.0-beta.3 → 9.4.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dist.dev.js +41 -21
- package/dist/dist.min.js +22 -22
- package/dist/index.cjs +98 -51
- package/dist/index.cjs.map +2 -2
- package/dist/model/model.d.ts.map +1 -1
- package/dist/model/model.js +4 -1
- package/dist/model/model.js.map +1 -1
- package/dist/passes/shader-pass-renderer.d.ts +2 -0
- package/dist/passes/shader-pass-renderer.d.ts.map +1 -1
- package/dist/passes/shader-pass-renderer.js +2 -1
- package/dist/passes/shader-pass-renderer.js.map +1 -1
- package/dist/utils/shader-module-utils.d.ts +4 -2
- package/dist/utils/shader-module-utils.d.ts.map +1 -1
- package/dist/utils/shader-module-utils.js +22 -0
- package/dist/utils/shader-module-utils.js.map +1 -1
- package/package.json +2 -2
- package/src/model/model.ts +5 -0
- package/src/passes/shader-pass-renderer.ts +2 -1
- package/src/utils/shader-module-utils.ts +33 -2
package/dist/dist.min.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
else if (typeof define === 'function' && define.amd) define([], factory);
|
|
5
5
|
else if (typeof exports === 'object') exports['luma'] = factory();
|
|
6
6
|
else root['luma'] = factory();})(globalThis, function () {
|
|
7
|
-
"use strict";var __exports__=(()=>{var os=Object.create;var ct=Object.defineProperty;var as=Object.getOwnPropertyDescriptor;var cs=Object.getOwnPropertyNames;var hs=Object.getPrototypeOf,us=Object.prototype.hasOwnProperty;var nn=(i,e)=>()=>{try{return e||i((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ls=(i,e)=>{for(var t in e)ct(i,t,{get:e[t],enumerable:!0})},at=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of cs(e))!us.call(i,r)&&r!==t&&ct(i,r,{get:()=>e[r],enumerable:!(n=as(e,r))||n.enumerable});return i},ht=(i,e,t)=>(at(i,e,"default"),t&&at(t,e,"default")),R=(i,e,t)=>(t=i!=null?os(hs(i)):{},at(e||!i||!i.__esModule?ct(t,"default",{value:i,enumerable:!0}):t,i)),ds=i=>at(ct({},"__esModule",{value:!0}),i);var N=nn((mc,rn)=>{rn.exports=globalThis.luma});var ce=nn((Fh,Xn)=>{Xn.exports=globalThis.luma});var it={};ls(it,{AnimationAction:()=>Ve,AnimationClip:()=>pt,AnimationClipController:()=>ut,AnimationLoop:()=>Pe,AnimationLoopTemplate:()=>St,AnimationMixer:()=>gt,AnimationTrack:()=>mt,Animator:()=>lt,AsyncTexture:()=>dc,BackgroundTextureModel:()=>Be,BufferTransform:()=>Nt,ClipSpace:()=>ue,Computation:()=>Ge,ConeGeometry:()=>fe,CubeGeometry:()=>Yt,CylinderGeometry:()=>Wt,DirectionalLightModel:()=>jt,DynamicBuffer:()=>G,DynamicTexture:()=>K,GPUGeometry:()=>Ee,Geometry:()=>z,GroupNode:()=>Vt,IcoSphereGeometry:()=>qt,KeyFrames:()=>At,LegacyPickingManager:()=>ri,Material:()=>De,MaterialFactory:()=>ke,Model:()=>Y,ModelNode:()=>Xt,OrbitControls:()=>Ct,PickingManager:()=>ti,PlaneGeometry:()=>Kt,PointLightModel:()=>Ft,ScenegraphNode:()=>re,ShaderInputs:()=>X,ShaderPassRenderer:()=>ei,SphereGeometry:()=>Fe,SpotLightModel:()=>zt,Swap:()=>ze,SwapBuffers:()=>Jt,SwapFramebuffers:()=>je,TextureTransform:()=>Dt,Timeline:()=>wt,TruncatedConeGeometry:()=>de,VideoTexture:()=>Qt,_resolveLoadFileUrl:()=>Zt,applyMorphTargets:()=>hi,cancelAnimationFramePolyfill:()=>Et,colorPicking:()=>et,decodeMorphTargetAttribute:()=>ci,evaluateAnimationSampler:()=>dt,getIndexPickingModule:()=>Jr,indexColorPicking:()=>ni,indexPicking:()=>tt,legacyColorPicking:()=>ts,loadImage:()=>Nr,loadImageBitmap:()=>kr,makeAnimationLoop:()=>Vn,makeInterleavedGeometry:()=>Me,makeRandomGenerator:()=>Cr,picking:()=>Qr,requestAnimationFramePolyfill:()=>Pt,resolvePickingBackend:()=>Zr,resolvePickingMode:()=>ii,setPathPrefix:()=>Rr,simplifyMesh:()=>Er,supportsIndexPicking:()=>Je,updateMorphTargetBuffers:()=>hn,updateSkinJointMatrices:()=>jn});ht(it,R(N(),1));var sn=R(N(),1),ut=class{name;playing=!0;speed=1;startTime=0;constructor(e={}){this.name=e.name||"unnamed",Object.assign(this,e)}setTime(e){if(!this.playing)return;let n=(e/1e3-this.startTime)*this.speed;this.applyTime(n)}},lt=class{clips;animations;constructor(e){this.clips=e,this.animations=e}animate(e){sn.log.warn(`${this.constructor.name}#animate is deprecated. Use ${this.constructor.name}#setTime instead`)(),this.setTime(e)}setTime(e){this.clips.forEach(t=>t.setTime(e))}getAnimations(){return this.clips}};function dt(i,e,t="vector"){let{input:n,output:r,interpolation:s="LINEAR"}=e;if(!n.length||!r.length||!Number.isFinite(i))return null;let o=n.length-1;if(i<=n[0]||o===0)return si(r,s,0,t);if(i>=n[o])return si(r,s,o,t);let a=0,c=o;for(;c-a>1;){let f=Math.floor((a+c)/2);n[f]<=i?a=f:c=f}let h=n[a],d=n[c]-h;if(d<=0||s==="STEP")return si(r,s,a,t);let l=(i-h)/d;switch(s){case"LINEAR":{let f=r[a],m=r[c];return!f||!m?null:t==="quaternion"?ft(f,m,l):fs(f,m,l)}case"CUBICSPLINE":{let f=r[a*3+1],m=r[a*3+2],p=r[c*3],b=r[c*3+1];if(!f||!m||!p||!b)return null;let _=ms(f,m,p,b,d,l);return t==="quaternion"?ve(_):_}default:return null}}function ft(i,e,t){let n=ve(i),r=ve(e),s=n.reduce((d,l,f)=>d+l*r[f],0),o=s<0?-1:1;if(s=Math.min(Math.abs(s),1),s>.9995)return ve(n.map((d,l)=>d+t*(r[l]*o-d)));let a=Math.acos(s),c=Math.sin(a),h=Math.sin((1-t)*a)/c,u=Math.sin(t*a)/c*o;return ve(n.map((d,l)=>d*h+r[l]*u))}function si(i,e,t,n){let r=i[e==="CUBICSPLINE"?t*3+1:t];return r?n==="quaternion"?ve(r):[...r]:null}function fs(i,e,t){return i.map((n,r)=>(1-t)*n+t*e[r])}function ms(i,e,t,n,r,s){let o=s*s,a=o*s;return i.map((c,h)=>(2*a-3*o+1)*c+(a-2*o+s)*e[h]*r+(-2*a+3*o)*n[h]+(a-o)*t[h]*r)}function ve(i){let e=Math.hypot(...i);return e>0?i.map(t=>t/e):[0,0,0,1]}var mt=class{name;times;values;interpolation;valueType;binding;constructor(e){this.name=e.name||e.binding.id||"unnamed",this.times=e.times,this.values=e.values,this.interpolation=e.interpolation||"LINEAR",this.valueType=e.valueType||"vector",this.binding=e.binding}get duration(){return this.times[this.times.length-1]||0}get sampler(){return{input:this.times,output:this.values,interpolation:this.interpolation}}evaluate(e){return dt(e,this.sampler,this.valueType)}};var pt=class{name;tracks;duration;constructor(e){this.name=e.name||"unnamed",this.tracks=e.tracks,this.duration=e.duration??Math.max(0,...e.tracks.map(t=>t.duration))}};var Ve=class{clip;mixer;time=0;timeScale;weight;loop;repetitions;paused=!1;playing=!1;elapsedTime=0;fade=null;constructor(e,t,n={}){this.mixer=e,this.clip=t,this.loop=n.loop||"repeat",this.repetitions=n.repetitions??Number.POSITIVE_INFINITY,this.timeScale=n.timeScale??1,this.weight=n.weight??1}play(){return this.playing=!0,this.paused=!1,this}pause(){return this.paused=!0,this}resume(){return this.playing=!0,this.paused=!1,this}stop(){return this.playing=!1,this.paused=!1,this.fade=null,this.reset()}reset(){return this.elapsedTime=0,this.time=0,this}setTime(e){return this.elapsedTime=e,this.time=this.resolveLocalTime(e),this}setLoop(e,t=Number.POSITIVE_INFINITY){return this.loop=e,this.repetitions=t,this.time=this.resolveLocalTime(this.elapsedTime),this}setEffectiveWeight(e){return this.weight=Math.max(0,e),this.fade=null,this}setEffectiveTimeScale(e){return this.timeScale=e,this}fadeIn(e){return this.scheduleFade(1,e)}fadeOut(e){return this.scheduleFade(0,e)}crossFadeTo(e,t){return e.weight=0,e.play().fadeIn(t),this.fadeOut(t)}crossFadeFrom(e,t){return e.crossFadeTo(this,t),this}advance(e){!this.playing||this.paused||(this.advanceFade(Math.abs(e)),this.elapsedTime+=e*this.timeScale,this.time=this.resolveLocalTime(this.elapsedTime),this.hasFinished()&&(this.playing=!1))}get shouldApply(){return(this.playing||this.hasFinished())&&this.weight>0}scheduleFade(e,t){return t<=0?(this.weight=e,this.fade=null,this):(this.fade={duration:t,elapsedTime:0,startWeight:this.weight,endWeight:e},this)}advanceFade(e){if(!this.fade)return;this.fade.elapsedTime+=e;let t=Math.min(this.fade.elapsedTime/this.fade.duration,1);this.weight=this.fade.startWeight+(this.fade.endWeight-this.fade.startWeight)*t,t===1&&(this.fade=null)}hasFinished(){let e=this.clip.duration;return e<=0?this.loop==="once":this.loop==="once"?this.elapsedTime>=e||this.elapsedTime<0:Number.isFinite(this.repetitions)&&Math.abs(this.elapsedTime)>=e*this.repetitions}resolveLocalTime(e){let t=this.clip.duration;if(t<=0)return 0;if(this.loop==="once")return Math.min(Math.max(e,0),t);if(Number.isFinite(this.repetitions)&&Math.abs(e)>=t*this.repetitions)return this.loop==="ping-pong"&&this.repetitions%2===0||e<0?0:t;let n=e>=0&&e<t?e:(e%t+t)%t;if(this.loop==="repeat")return n;let r=Math.floor(e/t);return Math.abs(r%2)===0?n:t-n}},gt=class{time=0;timeScale=1;clips=new Map;actions=new Map;initialValues=new Map;constructor(e=[]){e.forEach(t=>this.addClip(t))}addClip(e){return this.clips.set(e.name,e),this}clipAction(e,t){let n=typeof e=="string"?this.clips.get(e):e;if(!n)throw new Error(`Unknown animation clip: ${e}`);this.addClip(n);let r=this.actions.get(n);return r||(r=new Ve(this,n,t),this.actions.set(n,r)),r}getAction(e){let t=this.clips.get(e);return t?this.actions.get(t):void 0}update(e){return this.advance(e),this.applyValues(),this}advance(e){let t=e*this.timeScale;return this.time+=t,this.actions.forEach(n=>n.advance(t)),this}setTime(e){return this.time=e,this.actions.forEach(t=>{t.paused||t.setTime(e*t.timeScale)}),this.applyValues(),this}stopAllAction(){return this.actions.forEach(e=>e.stop()),this}applyValues(){let e=new Map;this.actions.forEach(t=>{!t.shouldApply&&!(t.playing&&t.weight===0)||t.clip.tracks.forEach(n=>{let r=n.evaluate(t.time);if(!r)return;let s=n.binding.id||n.binding;if(!this.initialValues.has(s)){let h=n.binding.getValue?.();h&&this.initialValues.set(s,[...h])}if(t.weight===0&&!this.initialValues.has(s))return;let o=e.get(s);if(!o){e.set(s,{binding:n.binding,value:[...r],valueType:n.valueType,weight:t.weight});return}if(t.weight===0)return;let a=o.weight+t.weight,c=t.weight/a;o.value=n.valueType==="quaternion"?ft(o.value,r,c):o.value.map((h,u)=>h+(r[u]-h)*c),o.weight=a})}),e.forEach(({binding:t,value:n,valueType:r,weight:s},o)=>{let a=s<1?this.initialValues.get(o):void 0;a&&a.length===n.length&&(n=r==="quaternion"?ft(a,n,s):n.map((c,h)=>a[h]+(c-a[h])*s)),t.setValue(n)})}};var on=R(N(),1);var oi={};function O(i="id"){oi[i]=oi[i]||1;let e=oi[i]++;return`${i}-${e}`}var z=class{id;topology;vertexCount;indices;attributes;bufferLayout;userData={};constructor(e){let{attributes:t={},indices:n=null,vertexCount:r=null}=e;this.id=e.id||O("geometry"),this.topology=e.topology,n&&(this.indices=ArrayBuffer.isView(n)?{value:n,size:1}:n),this.attributes={};for(let[s,o]of Object.entries(t)){let 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{let c=ge(s),h=Object.keys(this.attributes).find(u=>ge(u)===c);h&&delete this.attributes[h],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),this.bufferLayout=e.bufferLayout||ps(this.attributes)}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,t){return this}_calculateVertexCount(e,t){if(t)return t.value.length;let n=1/0;for(let r of Object.values(e)){if(!r)continue;let{value:s,size:o,constant:a}=r;!a&&s&&o!==void 0&&o>=1&&(n=Math.min(n,s.length/o))}return n}};function ge(i){switch(i){case"POSITION":return"positions";case"NORMAL":return"normals";case"TEXCOORD_0":return"texCoords";case"TEXCOORD_1":return"texCoords1";case"COLOR_0":return"colors";default:return i}}function ps(i){let e=[];for(let[t,n]of Object.entries(i)){if(!n)continue;let{value:r,size:s,normalized:o}=n;if(s===void 0)throw new Error(`Attribute ${t} is missing a size`);e.push({name:ge(t),format:on.vertexFormatDecoder.getVertexFormatFromAttribute(r,s,o)})}return e}var ai=R(N(),1);function cn(i){let{indices:e,attributes:t}=i;if(!e)return i;let n=e.value.length,r={};for(let s in t){let o=t[s];if(!o)continue;let{value:a,size:c}=o;if(o.constant||!c)continue;let u=a.constructor,d=new u(n*c);for(let l=0;l<n;++l){let f=e.value[l];for(let m=0;m<c;m++)d[l*c+m]=a[f*c+m]}r[s]={size:c,value:d}}return{attributes:Object.assign({},t,r)}}function Me(i,e={}){let t=e.bufferName||"geometry";if(gs(i,t))return i;let n=e.minAttributeAlignment||4,r=xs(i,e.attributes),s=[],o=0,a=1/0;for(let[u,d]of r){if(!d)continue;if(d.constant)throw new Error(`Attribute ${u} is constant`);let{value:l,size:f,normalized:m}=d;if(!ArrayBuffer.isView(l))throw new Error(`Attribute ${u} is missing typed array data`);if(f===void 0)throw new Error(`Attribute ${u} is missing a size`);let p=ai.vertexFormatDecoder.getVertexFormatFromAttribute(l,f,m),b=ai.vertexFormatDecoder.getVertexFormatInfo(p);o=an(o,n),s.push({sourceName:u,attributeName:ge(u),value:l,size:f,format:p,byteOffset:o,byteLength:b.byteLength}),o+=b.byteLength;let _=l.length/f;if(!Number.isInteger(_))throw new Error(`Attribute ${u} length is not divisible by size`);a=Math.min(a,_)}if(s.length===0||!Number.isFinite(a))throw new Error(`Geometry ${i.id} has no interleavable attributes`);let c=an(o,n),h=new ArrayBuffer(a*c);for(let u of s)bs(h,a,c,u);return new z({id:i.id,topology:i.topology||"triangle-list",vertexCount:i.vertexCount,indices:i.indices,attributes:{[t]:{value:new Uint8Array(h),size:c,byteStride:c}},bufferLayout:[{name:t,stepMode:"vertex",byteStride:c,attributes:s.map(u=>({attribute:u.attributeName,format:u.format,byteOffset:u.byteOffset}))}]})}function gs(i,e){if(i.bufferLayout.length!==1)return!1;let t=i.bufferLayout[0];return t.name===e&&!!t.attributes?.length&&!!i.attributes[e]}function xs(i,e){return e?e.map(t=>[t,i.attributes[t]]):Object.entries(i.attributes)}function bs(i,e,t,n){let r=n.value.constructor,s=r.BYTES_PER_ELEMENT;if(n.byteOffset%s!==0||t%s!==0)throw new Error(`Attribute ${n.sourceName} is not aligned to its component type`);let o=new r(i),a=n.value,c=n.byteOffset/s,h=t/s;for(let u=0;u<e;u++){let d=u*n.size,l=u*h+c;for(let f=0;f<n.size;f++)o[l+f]=a[d+f]}}function an(i,e){return Math.ceil(i/e)*e}function ci(i){let e=i.value;if(e instanceof Float32Array)return e;let t=new Float32Array(e.length),n=un(e),r=e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array;for(let s=0;s<e.length;s++){let o=Number(e[s]);t[s]=i.normalized&&n?r?Math.max(o/n,-1):o/n:o}return t}function hi(i,e,t){let n={};for(let r of["POSITION","NORMAL","TANGENT"]){let s=i[r];if(!s)continue;let o=new Float32Array(s),a=r==="TANGENT"?4:3,c=Math.floor(s.length/a);for(let h=0;h<Math.min(e.length,t.length);h++){let u=t[h],d=e[h][r];if(!u||!d)continue;let l=r==="TANGENT"&&d.length===c*4?4:3;for(let f=0;f<c;f++){let m=f*a,p=f*l;for(let b=0;b<3;b++)o[m+b]+=(d[p+b]||0)*u}}r!=="POSITION"&&_s(o,a),n[r]=o}return n}function hn(i,e,t,n){let r={};for(let d of["POSITION","NORMAL","TANGENT"]){let l=e.attributes[d];l&&(r[d]=ci(l))}let s=hi(r,t,n),o={};for(let[d,l]of Object.entries(e.attributes))l&&(o[d]=l);for(let d of["POSITION","NORMAL","TANGENT"]){let l=s[d],f=o[d];l&&f&&(o[d]={...f,value:ys(f,l)})}let a=new z({id:e.id,topology:e.topology||"triangle-list",vertexCount:e.vertexCount,indices:e.indices,attributes:o,bufferLayout:e.bufferLayout}),h=Me(a).attributes.geometry?.value,u=i._gpuGeometry?.attributes.geometry||i.bufferAttributes.geometry;if(h&&u){u.write(h);return}for(let d of["POSITION","NORMAL","TANGENT"]){let l=s[d];if(l){let f=d==="POSITION"?"positions":d==="NORMAL"?"normals":"TANGENT";i.bufferAttributes[f]?.write(l)}}}function ys(i,e){if(i.value instanceof Float32Array)return e;let t=i.value.slice(),n=un(t),r=t instanceof Int8Array||t instanceof Int16Array||t instanceof Int32Array;for(let s=0;s<e.length;s++){let o=e[s];t[s]=i.normalized&&n?Math.round(Math.max(r?-1:0,Math.min(1,o))*n):o}return t}function un(i){return i instanceof Int8Array?127:i instanceof Uint8Array||i instanceof Uint8ClampedArray?255:i instanceof Int16Array?32767:i instanceof Uint16Array?65535:i instanceof Int32Array?2147483647:i instanceof Uint32Array?4294967295:0}function _s(i,e){for(let t=0;t<i.length;t+=e){let n=Math.hypot(i[t],i[t+1],i[t+2]);n>0&&(i[t]/=n,i[t+1]/=n,i[t+2]/=n)}}var Cc=1/Math.PI*180,Lc=1/180*Math.PI,Is={EPSILON:1e-12,debug:!1,precision:4,printTypes:!1,printDegrees:!1,printRowMajor:!0,_cartographicRadians:!1};globalThis.mathgl=globalThis.mathgl||{config:{...Is}};var $=globalThis.mathgl.config;function ln(i,{precision:e=$.precision}={}){return i=vs(i),`${parseFloat(i.toPrecision(e))}`}function Te(i){return Array.isArray(i)||ArrayBuffer.isView(i)&&!(i instanceof DataView)}function ui(i,e,t){let n=$.EPSILON;t&&($.EPSILON=t);try{if(i===e)return!0;if(Te(i)&&Te(e)){if(i.length!==e.length)return!1;for(let r=0;r<i.length;++r)if(!ui(i[r],e[r]))return!1;return!0}return i&&i.equals?i.equals(e):e&&e.equals?e.equals(i):typeof i=="number"&&typeof e=="number"?Math.abs(i-e)<=$.EPSILON*Math.max(1,Math.abs(i),Math.abs(e)):!1}finally{$.EPSILON=n}}function vs(i){return Math.round(i/$.EPSILON)*$.EPSILON}var we=class extends Array{clone(){return new this.constructor().copy(this)}fromArray(e,t=0){for(let n=0;n<this.ELEMENTS;++n)this[n]=e[n+t];return this.check()}toArray(e=[],t=0){for(let n=0;n<this.ELEMENTS;++n)e[t+n]=this[n];return e}toObject(e){return e}from(e){return Array.isArray(e)?this.copy(e):this.fromObject(e)}to(e){return e===this?this:Te(e)?this.toArray(e):this.toObject(e)}toTarget(e){return e?this.to(e):this}toFloat32Array(){return new Float32Array(this)}toString(){return this.formatString($)}formatString(e){let t="";for(let n=0;n<this.ELEMENTS;++n)t+=(n>0?", ":"")+ln(this[n],e);return`${e.printTypes?this.constructor.name:""}[${t}]`}equals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(!ui(this[t],e[t]))return!1;return!0}exactEquals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(this[t]!==e[t])return!1;return!0}negate(){for(let e=0;e<this.ELEMENTS;++e)this[e]=-this[e];return this.check()}lerp(e,t,n){if(n===void 0)return this.lerp(this,e,t);for(let r=0;r<this.ELEMENTS;++r){let s=e[r],o=typeof t=="number"?t:t[r];this[r]=s+n*(o-s)}return this.check()}min(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.min(e[t],this[t]);return this.check()}max(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.max(e[t],this[t]);return this.check()}clamp(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],e[n]),t[n]);return this.check()}add(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]+=t[n];return this.check()}subtract(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]-=t[n];return this.check()}scale(e){if(typeof e=="number")for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;else for(let t=0;t<this.ELEMENTS&&t<e.length;++t)this[t]*=e[t];return this.check()}multiplyByScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;return this.check()}check(){if($.debug&&!this.validate())throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`);return this}validate(){let e=this.length===this.ELEMENTS;for(let t=0;t<this.ELEMENTS;++t)e=e&&Number.isFinite(this[t]);return e}sub(e){return this.subtract(e)}setScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=e;return this.check()}addScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]+=e;return this.check()}subScalar(e){return this.addScalar(-e)}multiplyScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;return this.check()}divideScalar(e){return this.multiplyByScalar(1/e)}clampScalar(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],e),t);return this.check()}get elements(){return this}};function Ms(i,e){if(i.length!==e)return!1;for(let t=0;t<i.length;++t)if(!Number.isFinite(i[t]))return!1;return!0}function V(i){if(!Number.isFinite(i))throw new Error(`Invalid number ${JSON.stringify(i)}`);return i}function xt(i,e,t=""){if($.debug&&!Ms(i,e))throw new Error(`math.gl: ${t} some fields set to invalid numbers'`);return i}function li(i,e){if(!i)throw new Error(`math.gl assertion ${e}`)}var bt=class extends we{get x(){return this[0]}set x(e){this[0]=V(e)}get y(){return this[1]}set y(e){this[1]=V(e)}len(){return Math.sqrt(this.lengthSquared())}magnitude(){return this.len()}lengthSquared(){let e=0;for(let t=0;t<this.ELEMENTS;++t)e+=this[t]*this[t];return e}magnitudeSquared(){return this.lengthSquared()}distance(e){return Math.sqrt(this.distanceSquared(e))}distanceSquared(e){let t=0;for(let n=0;n<this.ELEMENTS;++n){let r=this[n]-e[n];t+=r*r}return V(t)}dot(e){let t=0;for(let n=0;n<this.ELEMENTS;++n)t+=this[n]*e[n];return V(t)}normalize(){let e=this.magnitude();if(e!==0)for(let t=0;t<this.ELEMENTS;++t)this[t]/=e;return this.check()}multiply(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]*=t[n];return this.check()}divide(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]/=t[n];return this.check()}lengthSq(){return this.lengthSquared()}distanceTo(e){return this.distance(e)}distanceToSquared(e){return this.distanceSquared(e)}getComponent(e){return li(e>=0&&e<this.ELEMENTS,"index is out of range"),V(this[e])}setComponent(e,t){return li(e>=0&&e<this.ELEMENTS,"index is out of range"),this[e]=t,this.check()}addVectors(e,t){return this.copy(e).add(t)}subVectors(e,t){return this.copy(e).subtract(t)}multiplyVectors(e,t){return this.copy(e).multiply(t)}addScaledVector(e,t){return this.add(new this.constructor(e).multiplyScalar(t))}};var ie=typeof Float32Array<"u"?Float32Array:Array;var Uc=Math.PI/180;function Ts(){let i=new ie(2);return ie!=Float32Array&&(i[0]=0,i[1]=0),i}function mn(i,e,t){let n=e[0],r=e[1];return i[0]=t[0]*n+t[4]*r+t[12],i[1]=t[1]*n+t[5]*r+t[13],i}var $c=(function(){let i=Ts();return function(e,t,n,r,s,o){let a,c;for(t||(t=2),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],s(i,i,o),e[a]=i[0],e[a+1]=i[1];return e}})();function pn(i,e,t){let n=e[0],r=e[1],s=t[3]*n+t[7]*r||1;return i[0]=(t[0]*n+t[4]*r)/s,i[1]=(t[1]*n+t[5]*r)/s,i}function yt(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[3]*n+t[7]*r+t[11]*s||1;return i[0]=(t[0]*n+t[4]*r+t[8]*s)/o,i[1]=(t[1]*n+t[5]*r+t[9]*s)/o,i[2]=(t[2]*n+t[6]*r+t[10]*s)/o,i}function gn(i,e,t){let n=e[0],r=e[1];return i[0]=t[0]*n+t[2]*r,i[1]=t[1]*n+t[3]*r,i[2]=e[2],i}function As(){let i=new ie(3);return ie!=Float32Array&&(i[0]=0,i[1]=0,i[2]=0),i}function Ss(i,e){return i[0]*e[0]+i[1]*e[1]+i[2]*e[2]}function xn(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[0],a=t[1],c=t[2];return i[0]=r*c-s*a,i[1]=s*o-n*c,i[2]=n*a-r*o,i}function _t(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[3]*n+t[7]*r+t[11]*s+t[15];return o=o||1,i[0]=(t[0]*n+t[4]*r+t[8]*s+t[12])/o,i[1]=(t[1]*n+t[5]*r+t[9]*s+t[13])/o,i[2]=(t[2]*n+t[6]*r+t[10]*s+t[14])/o,i}function bn(i,e,t){let n=e[0],r=e[1],s=e[2];return i[0]=n*t[0]+r*t[3]+s*t[6],i[1]=n*t[1]+r*t[4]+s*t[7],i[2]=n*t[2]+r*t[5]+s*t[8],i}function yn(i,e,t){let n=t[0],r=t[1],s=t[2],o=t[3],a=e[0],c=e[1],h=e[2],u=r*h-s*c,d=s*a-n*h,l=n*c-r*a,f=r*l-s*d,m=s*u-n*l,p=n*d-r*u,b=o*2;return u*=b,d*=b,l*=b,f*=2,m*=2,p*=2,i[0]=a+u+f,i[1]=c+d+m,i[2]=h+l+p,i}function _n(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[0],s[1]=r[1]*Math.cos(n)-r[2]*Math.sin(n),s[2]=r[1]*Math.sin(n)+r[2]*Math.cos(n),i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function In(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[2]*Math.sin(n)+r[0]*Math.cos(n),s[1]=r[1],s[2]=r[2]*Math.cos(n)-r[0]*Math.sin(n),i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function vn(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[0]*Math.cos(n)-r[1]*Math.sin(n),s[1]=r[0]*Math.sin(n)+r[1]*Math.cos(n),s[2]=r[2],i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function Mn(i,e){let t=i[0],n=i[1],r=i[2],s=e[0],o=e[1],a=e[2],c=Math.sqrt((t*t+n*n+r*r)*(s*s+o*o+a*a)),h=c&&Ss(i,e)/c;return Math.acos(Math.min(Math.max(h,-1),1))}var Xc=(function(){let i=As();return function(e,t,n,r,s,o){let a,c;for(t||(t=3),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],i[2]=e[a+2],s(i,i,o),e[a]=i[0],e[a+1]=i[1],e[a+2]=i[2];return e}})();var fi=[0,0,0],It,H=class i extends bt{static get ZERO(){return It||(It=new i(0,0,0),Object.freeze(It)),It}constructor(e=0,t=0,n=0){super(-0,-0,-0),arguments.length===1&&Te(e)?this.copy(e):($.debug&&(V(e),V(t),V(n)),this[0]=e,this[1]=t,this[2]=n)}set(e,t,n){return this[0]=e,this[1]=t,this[2]=n,this.check()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this.check()}fromObject(e){return $.debug&&(V(e.x),V(e.y),V(e.z)),this[0]=e.x,this[1]=e.y,this[2]=e.z,this.check()}toObject(e){return e.x=this[0],e.y=this[1],e.z=this[2],e}get ELEMENTS(){return 3}get z(){return this[2]}set z(e){this[2]=V(e)}angle(e){return Mn(this,e)}cross(e){return xn(this,this,e),this.check()}rotateX({radians:e,origin:t=fi}){return _n(this,this,t,e),this.check()}rotateY({radians:e,origin:t=fi}){return In(this,this,t,e),this.check()}rotateZ({radians:e,origin:t=fi}){return vn(this,this,t,e),this.check()}transform(e){return this.transformAsPoint(e)}transformAsPoint(e){return _t(this,this,e),this.check()}transformAsVector(e){return yt(this,this,e),this.check()}transformByMatrix3(e){return bn(this,this,e),this.check()}transformByMatrix2(e){return gn(this,this,e),this.check()}transformByQuaternion(e){return yn(this,this,e),this.check()}};var vt=class extends we{toString(){let e="[";if($.printRowMajor){e+="row-major:";for(let t=0;t<this.RANK;++t)for(let n=0;n<this.RANK;++n)e+=` ${this[n*this.RANK+t]}`}else{e+="column-major:";for(let t=0;t<this.ELEMENTS;++t)e+=` ${this[t]}`}return e+="]",e}getElementIndex(e,t){return t*this.RANK+e}getElement(e,t){return this[t*this.RANK+e]}setElement(e,t,n){return this[t*this.RANK+e]=V(n),this}getColumn(e,t=new Array(this.RANK).fill(-0)){let n=e*this.RANK;for(let r=0;r<this.RANK;++r)t[r]=this[n+r];return t}setColumn(e,t){let n=e*this.RANK;for(let r=0;r<this.RANK;++r)this[n+r]=t[r];return this}};function Es(i){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function Tn(i,e){if(i===e){let t=e[1],n=e[2],r=e[3],s=e[6],o=e[7],a=e[11];i[1]=e[4],i[2]=e[8],i[3]=e[12],i[4]=t,i[6]=e[9],i[7]=e[13],i[8]=n,i[9]=s,i[11]=e[14],i[12]=r,i[13]=o,i[14]=a}else i[0]=e[0],i[1]=e[4],i[2]=e[8],i[3]=e[12],i[4]=e[1],i[5]=e[5],i[6]=e[9],i[7]=e[13],i[8]=e[2],i[9]=e[6],i[10]=e[10],i[11]=e[14],i[12]=e[3],i[13]=e[7],i[14]=e[11],i[15]=e[15];return i}function wn(i,e){let t=e[0],n=e[1],r=e[2],s=e[3],o=e[4],a=e[5],c=e[6],h=e[7],u=e[8],d=e[9],l=e[10],f=e[11],m=e[12],p=e[13],b=e[14],_=e[15],M=t*a-n*o,y=t*c-r*o,I=t*h-s*o,g=n*c-r*a,x=n*h-s*a,v=r*h-s*c,w=u*p-d*m,T=u*b-l*m,C=u*_-f*m,S=d*b-l*p,A=d*_-f*p,L=l*_-f*b,E=M*L-y*A+I*S+g*C-x*T+v*w;return E?(E=1/E,i[0]=(a*L-c*A+h*S)*E,i[1]=(r*A-n*L-s*S)*E,i[2]=(p*v-b*x+_*g)*E,i[3]=(l*x-d*v-f*g)*E,i[4]=(c*C-o*L-h*T)*E,i[5]=(t*L-r*C+s*T)*E,i[6]=(b*I-m*v-_*y)*E,i[7]=(u*v-l*I+f*y)*E,i[8]=(o*A-a*C+h*w)*E,i[9]=(n*C-t*A-s*w)*E,i[10]=(m*x-p*I+_*M)*E,i[11]=(d*I-u*x-f*M)*E,i[12]=(a*T-o*S-c*w)*E,i[13]=(t*S-n*T+r*w)*E,i[14]=(p*y-m*g-b*M)*E,i[15]=(u*g-d*y+l*M)*E,i):null}function An(i){let e=i[0],t=i[1],n=i[2],r=i[3],s=i[4],o=i[5],a=i[6],c=i[7],h=i[8],u=i[9],d=i[10],l=i[11],f=i[12],m=i[13],p=i[14],b=i[15],_=e*o-t*s,M=e*a-n*s,y=t*a-n*o,I=h*m-u*f,g=h*p-d*f,x=u*p-d*m,v=e*x-t*g+n*I,w=s*x-o*g+a*I,T=h*y-u*M+d*_,C=f*y-m*M+p*_;return c*v-r*w+b*T-l*C}function mi(i,e,t){let n=e[0],r=e[1],s=e[2],o=e[3],a=e[4],c=e[5],h=e[6],u=e[7],d=e[8],l=e[9],f=e[10],m=e[11],p=e[12],b=e[13],_=e[14],M=e[15],y=t[0],I=t[1],g=t[2],x=t[3];return i[0]=y*n+I*a+g*d+x*p,i[1]=y*r+I*c+g*l+x*b,i[2]=y*s+I*h+g*f+x*_,i[3]=y*o+I*u+g*m+x*M,y=t[4],I=t[5],g=t[6],x=t[7],i[4]=y*n+I*a+g*d+x*p,i[5]=y*r+I*c+g*l+x*b,i[6]=y*s+I*h+g*f+x*_,i[7]=y*o+I*u+g*m+x*M,y=t[8],I=t[9],g=t[10],x=t[11],i[8]=y*n+I*a+g*d+x*p,i[9]=y*r+I*c+g*l+x*b,i[10]=y*s+I*h+g*f+x*_,i[11]=y*o+I*u+g*m+x*M,y=t[12],I=t[13],g=t[14],x=t[15],i[12]=y*n+I*a+g*d+x*p,i[13]=y*r+I*c+g*l+x*b,i[14]=y*s+I*h+g*f+x*_,i[15]=y*o+I*u+g*m+x*M,i}function Sn(i,e,t){let n=t[0],r=t[1],s=t[2],o,a,c,h,u,d,l,f,m,p,b,_;return e===i?(i[12]=e[0]*n+e[4]*r+e[8]*s+e[12],i[13]=e[1]*n+e[5]*r+e[9]*s+e[13],i[14]=e[2]*n+e[6]*r+e[10]*s+e[14],i[15]=e[3]*n+e[7]*r+e[11]*s+e[15]):(o=e[0],a=e[1],c=e[2],h=e[3],u=e[4],d=e[5],l=e[6],f=e[7],m=e[8],p=e[9],b=e[10],_=e[11],i[0]=o,i[1]=a,i[2]=c,i[3]=h,i[4]=u,i[5]=d,i[6]=l,i[7]=f,i[8]=m,i[9]=p,i[10]=b,i[11]=_,i[12]=o*n+u*r+m*s+e[12],i[13]=a*n+d*r+p*s+e[13],i[14]=c*n+l*r+b*s+e[14],i[15]=h*n+f*r+_*s+e[15]),i}function Pn(i,e,t){let n=t[0],r=t[1],s=t[2];return i[0]=e[0]*n,i[1]=e[1]*n,i[2]=e[2]*n,i[3]=e[3]*n,i[4]=e[4]*r,i[5]=e[5]*r,i[6]=e[6]*r,i[7]=e[7]*r,i[8]=e[8]*s,i[9]=e[9]*s,i[10]=e[10]*s,i[11]=e[11]*s,i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15],i}function En(i,e,t,n){let r=n[0],s=n[1],o=n[2],a=Math.sqrt(r*r+s*s+o*o),c,h,u,d,l,f,m,p,b,_,M,y,I,g,x,v,w,T,C,S,A,L,E,U;return a<1e-6?null:(a=1/a,r*=a,s*=a,o*=a,h=Math.sin(t),c=Math.cos(t),u=1-c,d=e[0],l=e[1],f=e[2],m=e[3],p=e[4],b=e[5],_=e[6],M=e[7],y=e[8],I=e[9],g=e[10],x=e[11],v=r*r*u+c,w=s*r*u+o*h,T=o*r*u-s*h,C=r*s*u-o*h,S=s*s*u+c,A=o*s*u+r*h,L=r*o*u+s*h,E=s*o*u-r*h,U=o*o*u+c,i[0]=d*v+p*w+y*T,i[1]=l*v+b*w+I*T,i[2]=f*v+_*w+g*T,i[3]=m*v+M*w+x*T,i[4]=d*C+p*S+y*A,i[5]=l*C+b*S+I*A,i[6]=f*C+_*S+g*A,i[7]=m*C+M*S+x*A,i[8]=d*L+p*E+y*U,i[9]=l*L+b*E+I*U,i[10]=f*L+_*E+g*U,i[11]=m*L+M*E+x*U,e!==i&&(i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i)}function Cn(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[4],o=e[5],a=e[6],c=e[7],h=e[8],u=e[9],d=e[10],l=e[11];return e!==i&&(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[4]=s*r+h*n,i[5]=o*r+u*n,i[6]=a*r+d*n,i[7]=c*r+l*n,i[8]=h*r-s*n,i[9]=u*r-o*n,i[10]=d*r-a*n,i[11]=l*r-c*n,i}function Ln(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],h=e[8],u=e[9],d=e[10],l=e[11];return e!==i&&(i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[0]=s*r-h*n,i[1]=o*r-u*n,i[2]=a*r-d*n,i[3]=c*r-l*n,i[8]=s*n+h*r,i[9]=o*n+u*r,i[10]=a*n+d*r,i[11]=c*n+l*r,i}function On(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],h=e[4],u=e[5],d=e[6],l=e[7];return e!==i&&(i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[0]=s*r+h*n,i[1]=o*r+u*n,i[2]=a*r+d*n,i[3]=c*r+l*n,i[4]=h*r-s*n,i[5]=u*r-o*n,i[6]=d*r-a*n,i[7]=l*r-c*n,i}function Rn(i,e){let t=e[0],n=e[1],r=e[2],s=e[3],o=t+t,a=n+n,c=r+r,h=t*o,u=n*o,d=n*a,l=r*o,f=r*a,m=r*c,p=s*o,b=s*a,_=s*c;return i[0]=1-d-m,i[1]=u+_,i[2]=l-b,i[3]=0,i[4]=u-_,i[5]=1-h-m,i[6]=f+p,i[7]=0,i[8]=l+b,i[9]=f-p,i[10]=1-h-d,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function kn(i,e,t,n,r,s,o){let a=1/(t-e),c=1/(r-n),h=1/(s-o);return i[0]=s*2*a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s*2*c,i[6]=0,i[7]=0,i[8]=(t+e)*a,i[9]=(r+n)*c,i[10]=(o+s)*h,i[11]=-1,i[12]=0,i[13]=0,i[14]=o*s*2*h,i[15]=0,i}function Cs(i,e,t,n,r){let s=1/Math.tan(e/2);if(i[0]=s/t,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=-1,i[12]=0,i[13]=0,i[15]=0,r!=null&&r!==1/0){let o=1/(n-r);i[10]=(r+n)*o,i[14]=2*r*n*o}else i[10]=-1,i[14]=-2*n;return i}var Nn=Cs;function Ls(i,e,t,n,r,s,o){let a=1/(e-t),c=1/(n-r),h=1/(s-o);return i[0]=-2*a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=-2*c,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=2*h,i[11]=0,i[12]=(e+t)*a,i[13]=(r+n)*c,i[14]=(o+s)*h,i[15]=1,i}var Dn=Ls;function Bn(i,e,t,n){let r,s,o,a,c,h,u,d,l,f,m=e[0],p=e[1],b=e[2],_=n[0],M=n[1],y=n[2],I=t[0],g=t[1],x=t[2];return Math.abs(m-I)<1e-6&&Math.abs(p-g)<1e-6&&Math.abs(b-x)<1e-6?Es(i):(d=m-I,l=p-g,f=b-x,r=1/Math.sqrt(d*d+l*l+f*f),d*=r,l*=r,f*=r,s=M*f-y*l,o=y*d-_*f,a=_*l-M*d,r=Math.sqrt(s*s+o*o+a*a),r?(r=1/r,s*=r,o*=r,a*=r):(s=0,o=0,a=0),c=l*a-f*o,h=f*s-d*a,u=d*o-l*s,r=Math.sqrt(c*c+h*h+u*u),r?(r=1/r,c*=r,h*=r,u*=r):(c=0,h=0,u=0),i[0]=s,i[1]=c,i[2]=d,i[3]=0,i[4]=o,i[5]=h,i[6]=l,i[7]=0,i[8]=a,i[9]=u,i[10]=f,i[11]=0,i[12]=-(s*m+o*p+a*b),i[13]=-(c*m+h*p+u*b),i[14]=-(d*m+l*p+f*b),i[15]=1,i)}function Rs(){let i=new ie(4);return ie!=Float32Array&&(i[0]=0,i[1]=0,i[2]=0,i[3]=0),i}function Fn(i,e,t){let n=e[0],r=e[1],s=e[2],o=e[3];return i[0]=t[0]*n+t[4]*r+t[8]*s+t[12]*o,i[1]=t[1]*n+t[5]*r+t[9]*s+t[13]*o,i[2]=t[2]*n+t[6]*r+t[10]*s+t[14]*o,i[3]=t[3]*n+t[7]*r+t[11]*s+t[15]*o,i}var ih=(function(){let i=Rs();return function(e,t,n,r,s,o){let a,c;for(t||(t=4),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],i[2]=e[a+2],i[3]=e[a+3],s(i,i,o),e[a]=i[0],e[a+1]=i[1],e[a+2]=i[2],e[a+3]=i[3];return e}})();var xi;(function(i){i[i.COL0ROW0=0]="COL0ROW0",i[i.COL0ROW1=1]="COL0ROW1",i[i.COL0ROW2=2]="COL0ROW2",i[i.COL0ROW3=3]="COL0ROW3",i[i.COL1ROW0=4]="COL1ROW0",i[i.COL1ROW1=5]="COL1ROW1",i[i.COL1ROW2=6]="COL1ROW2",i[i.COL1ROW3=7]="COL1ROW3",i[i.COL2ROW0=8]="COL2ROW0",i[i.COL2ROW1=9]="COL2ROW1",i[i.COL2ROW2=10]="COL2ROW2",i[i.COL2ROW3=11]="COL2ROW3",i[i.COL3ROW0=12]="COL3ROW0",i[i.COL3ROW1=13]="COL3ROW1",i[i.COL3ROW2=14]="COL3ROW2",i[i.COL3ROW3=15]="COL3ROW3"})(xi||(xi={}));var Ns=45*Math.PI/180,Ds=1,pi=.1,gi=500,Bs=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),k=class extends vt{static get IDENTITY(){return zs()}static get ZERO(){return Fs()}get ELEMENTS(){return 16}get RANK(){return 4}get INDICES(){return xi}constructor(e){super(-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0),arguments.length===1&&Array.isArray(e)?this.copy(e):this.identity()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3],this[4]=e[4],this[5]=e[5],this[6]=e[6],this[7]=e[7],this[8]=e[8],this[9]=e[9],this[10]=e[10],this[11]=e[11],this[12]=e[12],this[13]=e[13],this[14]=e[14],this[15]=e[15],this.check()}set(e,t,n,r,s,o,a,c,h,u,d,l,f,m,p,b){return this[0]=e,this[1]=t,this[2]=n,this[3]=r,this[4]=s,this[5]=o,this[6]=a,this[7]=c,this[8]=h,this[9]=u,this[10]=d,this[11]=l,this[12]=f,this[13]=m,this[14]=p,this[15]=b,this.check()}setRowMajor(e,t,n,r,s,o,a,c,h,u,d,l,f,m,p,b){return this[0]=e,this[1]=s,this[2]=h,this[3]=f,this[4]=t,this[5]=o,this[6]=u,this[7]=m,this[8]=n,this[9]=a,this[10]=d,this[11]=p,this[12]=r,this[13]=c,this[14]=l,this[15]=b,this.check()}toRowMajor(e){return e[0]=this[0],e[1]=this[4],e[2]=this[8],e[3]=this[12],e[4]=this[1],e[5]=this[5],e[6]=this[9],e[7]=this[13],e[8]=this[2],e[9]=this[6],e[10]=this[10],e[11]=this[14],e[12]=this[3],e[13]=this[7],e[14]=this[11],e[15]=this[15],e}identity(){return this.copy(Bs)}fromObject(e){return this.check()}fromQuaternion(e){return Rn(this,e),this.check()}frustum(e){let{left:t,right:n,bottom:r,top:s,near:o=pi,far:a=gi}=e;return a===1/0?js(this,t,n,r,s,o):kn(this,t,n,r,s,o,a),this.check()}lookAt(e){let{eye:t,center:n=[0,0,0],up:r=[0,1,0]}=e;return Bn(this,t,n,r),this.check()}ortho(e){let{left:t,right:n,bottom:r,top:s,near:o=pi,far:a=gi}=e;return Dn(this,t,n,r,s,o,a),this.check()}orthographic(e){let{fovy:t=Ns,aspect:n=Ds,focalDistance:r=1,near:s=pi,far:o=gi}=e;zn(t);let a=t/2,c=r*Math.tan(a),h=c*n;return this.ortho({left:-h,right:h,bottom:-c,top:c,near:s,far:o})}perspective(e){let{fovy:t=45*Math.PI/180,aspect:n=1,near:r=.1,far:s=500}=e;return zn(t),Nn(this,t,n,r,s),this.check()}determinant(){return An(this)}getScale(e=[-0,-0,-0]){return e[0]=Math.sqrt(this[0]*this[0]+this[1]*this[1]+this[2]*this[2]),e[1]=Math.sqrt(this[4]*this[4]+this[5]*this[5]+this[6]*this[6]),e[2]=Math.sqrt(this[8]*this[8]+this[9]*this[9]+this[10]*this[10]),e}getTranslation(e=[-0,-0,-0]){return e[0]=this[12],e[1]=this[13],e[2]=this[14],e}getRotation(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),r=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*r,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=0,e[4]=this[4]*r,e[5]=this[5]*s,e[6]=this[6]*o,e[7]=0,e[8]=this[8]*r,e[9]=this[9]*s,e[10]=this[10]*o,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}getRotationMatrix3(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),r=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*r,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=this[4]*r,e[4]=this[5]*s,e[5]=this[6]*o,e[6]=this[8]*r,e[7]=this[9]*s,e[8]=this[10]*o,e}transpose(){return Tn(this,this),this.check()}invert(){return wn(this,this),this.check()}multiplyLeft(e){return mi(this,e,this),this.check()}multiplyRight(e){return mi(this,this,e),this.check()}rotateX(e){return Cn(this,this,e),this.check()}rotateY(e){return Ln(this,this,e),this.check()}rotateZ(e){return On(this,this,e),this.check()}rotateXYZ(e){return this.rotateX(e[0]).rotateY(e[1]).rotateZ(e[2])}rotateAxis(e,t){return En(this,this,e,t),this.check()}scale(e){return Pn(this,this,Array.isArray(e)?e:[e,e,e]),this.check()}translate(e){return Sn(this,this,e),this.check()}transform(e,t){return e.length===4?(t=Fn(t||[-0,-0,-0,-0],e,this),xt(t,4),t):this.transformAsPoint(e,t)}transformAsPoint(e,t){let{length:n}=e,r;switch(n){case 2:r=mn(t||[-0,-0],e,this);break;case 3:r=_t(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return xt(r,e.length),r}transformAsVector(e,t){let n;switch(e.length){case 2:n=pn(t||[-0,-0],e,this);break;case 3:n=yt(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return xt(n,e.length),n}transformPoint(e,t){return this.transformAsPoint(e,t)}transformVector(e,t){return this.transformAsPoint(e,t)}transformDirection(e,t){return this.transformAsVector(e,t)}makeRotationX(e){return this.identity().rotateX(e)}makeTranslation(e,t,n){return this.identity().translate([e,t,n])}},Mt,Tt;function Fs(){return Mt||(Mt=new k([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Object.freeze(Mt)),Mt}function zs(){return Tt||(Tt=new k,Object.freeze(Tt)),Tt}function zn(i){if(i>Math.PI*2)throw Error("expected radians")}function js(i,e,t,n,r,s){let o=2*s/(t-e),a=2*s/(r-n),c=(t+e)/(t-e),h=(r+n)/(r-n),u=-1,d=-1,l=-2*s;return i[0]=o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=a,i[6]=0,i[7]=0,i[8]=c,i[9]=h,i[10]=u,i[11]=d,i[12]=0,i[13]=0,i[14]=l,i[15]=0,i}function jn(i){let{joints:e,meshNode:t,worldMatrices:n,inverseBindMatrices:r,target:s}=i,o=e.length,a=s&&s.length===o*16?s:new Float32Array(o*16),c=t?n.get(t)||t.matrix:void 0,h=c?new k(c).invert():null;for(let u=0;u<o;u++){let d=e[u],l=n.get(d)||d.matrix,f=h?new k(h).multiplyRight(l):new k(l),m=u*16;if(r&&r.length>=m+16){let p=new k;for(let b=0;b<16;b++)p[b]=r[m+b];f.multiplyRight(p)}a.set(f,m)}return a}var Gs=1,Us=1,wt=class{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(e){let{delay:t=0,duration:n=Number.POSITIVE_INFINITY,rate:r=1,repeat:s=1}=e,o=Gs++,a={time:0,delay:t,duration:n,rate:r,repeat:s};return this._setChannelTime(a,this.time),this.channels.set(o,a),o}removeChannel(e){this.channels.delete(e);for(let[t,n]of this.animations)n.channel===e&&this.detachAnimation(t)}isFinished(e){let t=this.channels.get(e);return t===void 0?!1:this.time>=t.delay+t.duration*t.repeat}getTime(e){if(e===void 0)return this.time;let t=this.channels.get(e);return t===void 0?-1:t.time}setTime(e){this.time=Math.max(0,e);let t=this.channels.values();for(let r of t)this._setChannelTime(r,this.time);let n=this.animations.values();for(let r of n){let{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,t){let n=Us++;return this.animations.set(n,{animation:e,channel:t}),e.setTime(this.getTime(t)),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,t){let n=t-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)}};var At=class{startIndex=-1;endIndex=-1;factor=0;times=[];values=[];_lastTime=-1;constructor(e){this.setKeyFrames(e),this.setTime(0)}setKeyFrames(e){let t=e.length;this.times.length=t,this.values.length=t;for(let n=0;n<t;++n)this.times[n]=e[n][0],this.values[n]=e[n][1];this._calculateKeys(this._lastTime)}setTime(e){e=Math.max(0,e),e!==this._lastTime&&(this._calculateKeys(e),this._lastTime=e)}getStartTime(){return this.times[this.startIndex]}getEndTime(){return this.times[this.endIndex]}getStartData(){return this.values[this.startIndex]}getEndData(){return this.values[this.endIndex]}_calculateKeys(e){let t=0,n=this.times.length;for(t=0;t<n-2&&!(this.times[t+1]>e);++t);this.startIndex=t,this.endIndex=t+1;let r=this.times[this.startIndex],s=this.times[this.endIndex];this.factor=Math.min(Math.max(0,(e-r)/(s-r)),1)}};var St=class{constructor(e){}async onInitialize(e){return null}};var Un=R(N(),1);function Pt(i){let e=typeof window<"u"?window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame:null;return e?e.call(window,i):setTimeout(()=>i(typeof performance<"u"?performance.now():Date.now()),1e3/60)}function Et(i){let e=typeof window<"u"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame:null;if(e){e.call(window,i);return}clearTimeout(i)}function Xe(){let i;if(typeof window<"u"&&window.performance)i=window.performance.now();else if(typeof process<"u"&&process.hrtime){let e=process.hrtime();i=e[0]*1e3+e[1]/1e6}else i=Date.now();return i}var xe=class{constructor(e,t){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=t,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=Xe(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(Xe()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}};var Se=class{constructor(e){this.stats={},this.id=e.id,this.stats={},this._initializeStats(e.stats),Object.seal(this)}get(e,t="count"){return this._getOrCreate({name:e,type:t})}get size(){return Object.keys(this.stats).length}reset(){for(let e of Object.values(this.stats))e.reset();return this}forEach(e){for(let t of Object.values(this.stats))e(t)}getTable(){let e={};return this.forEach(t=>{e[t.name]={time:t.time||0,count:t.count||0,average:t.getAverageTime()||0,hz:t.getHz()||0}}),e}_initializeStats(e=[]){e.forEach(t=>this._getOrCreate(t))}_getOrCreate(e){let{name:t,type:n}=e,r=this.stats[t];return r||(e instanceof xe?r=e:r=new xe(t,n),this.stats[t]=r),r}};var $s=0,Vs="Animation Loop",Gn={requestAnimationFrame:i=>Pt(i),cancelAnimationFrame:i=>Et(i)},Pe=class i{static defaultAnimationLoopProps={device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:e=>{console.error(e)},stats:void 0,autoResizeViewport:!1,animationFrameProvider:Gn};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={...i.defaultAnimationLoopProps,...e},e=this.props,!e.device)throw new Error("No device provided");this.stats=e.stats||new Se({id:`animation-loop-${$s++}`}),this.sharedStats=Un.luma.stats.get(Vs),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,animationFrameProvider:e.animationFrameProvider}),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(){let e=this._needsRedraw;return this._needsRedraw=!1,e}setProps(e){if("autoResizeViewport"in e&&(this.props.autoResizeViewport=e.autoResizeViewport||!1),"animationFrameProvider"in e){let t=e.animationFrameProvider||Gn;if(t!==this.props.animationFrameProvider){let n=this._animationFrameId!==null;n&&this._cancelAnimationFrame(),this.props.animationFrameProvider=t,n&&this._requestAnimationFrame()}}return 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){let t=e instanceof Error?e:new Error("Unknown error");throw this.props.onError(t),t}}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,t=null){return this.device?.isLost||this._error?this:(this._beginFrameTimers(e),this._setupFrame(),this.animationProps&&(this.animationProps.animationFrame=t),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=this.props.animationFrameProvider.requestAnimationFrame(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(this.props.animationFrameProvider.cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}_animationFrame(e,t){this._running&&(this.redraw(e,t??null),this._requestAnimationFrame())}_renderFrame(e){if(this.display){this.display._renderFrame(e);return}let t=this.props.onRender(this._getAnimationProps());this.device&&t!==!1&&this.device.submit()}_clearNeedsRedraw(){this._needsRedraw=!1}_setupFrame(){this._resizeViewport()}_initializeAnimationProps(){let e=this.device?.getDefaultCanvasContext();if(!this.device||!e)throw new Error("loop");let t=e?.canvas,n=e.props.useDevicePixels;this.animationProps={animationLoop:this,device:this.device,canvasContext:e,canvas:t,useDevicePixels:n,timeline:this.timeline,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,animationFrame:null,_mousePosition:null}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:e,height:t,aspect:n}=this._getSizeAndAspect();(e!==this.animationProps.width||t!==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=t,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){let e=document.createElement("div");document.body.appendChild(e),e.style.position="relative";let t=document.createElement("div");t.style.position="absolute",t.style.left="10px",t.style.bottom="10px",t.style.width="300px",t.style.background="white",this.canvas instanceof HTMLCanvasElement&&e.appendChild(this.canvas),e.appendChild(t);let n=this.props.onAddHTML(t);n&&(t.innerHTML=n)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[e,t]=this.device.getDefaultCanvasContext().getDrawingBufferSize(),n=e>0&&t>0?e/t:1;return{width:e,height:t,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){let t=e??(typeof performance<"u"?performance.now():Date.now());if(this._lastFrameTime){let n=t-this._lastFrameTime;n>0&&this.frameRate.addTime(n)}this._lastFrameTime=t,this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeStart()}_endFrameTimers(){this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeEnd(),this._updateSharedStats()}_consumeEncodedGpuTime(){if(!this.device)return;let 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(let e of Object.keys(this.sharedStats.stats))this.stats.stats[e]||delete this.sharedStats.stats[e];this.stats.forEach(e=>{let t=this.sharedStats.get(e.name,e.type);t.sampleSize=e.sampleSize,t.time=e.time,t.count=e.count,t.samples=e.samples,t.lastTiming=e.lastTiming,t.lastSampleTime=e.lastSampleTime,t.lastSampleCount=e.lastSampleCount,t._count=e._count,t._time=e._time,t._samples=e._samples,t._startTime=e._startTime,t._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}};var $n=R(N(),1);function Vn(i,e){let t=null,n=e?.device||$n.luma.createDevice({id:"animation-loop",adapters:e?.adapters,createCanvasContext:!0}),r=new Pe({...e,device:n,async onInitialize(o){Hs(o.animationLoop.device);try{return t=new i(o),await t?.onInitialize(o)}catch(a){return console.error(a),t=null,Xs(o.animationLoop.device,a),o.animationLoop.stop(),null}},onRender(o){let a=t?.onRender(o),c=e?.onAfterRender?.(o,t);return e?.onAfterRender?a!==!1||c!==!1:a},onFinalize(o){try{t?.onFinalize(o)}finally{t=null}}}),s=r;return s.getAnimationLoopTemplate=()=>t,r.getInfo=()=>this.AnimationLoopTemplateCtor.info,s}function Xs(i,e){if(!i)return;let t=i.getDefaultCanvasContext().canvas;if(t instanceof HTMLCanvasElement){t.style.overflow="visible";let n=document.getElementById("animation-loop-error");n?.remove(),n=document.createElement("h1"),n.id="animation-loop-error",n.innerHTML=e.message,n.style.position="absolute",n.style.top="10px",n.style.left="10px",n.style.color="black",n.style.backgroundColor="red",t.parentElement?.appendChild(n)}}function Hs(i){if(!i)return;let e=document.getElementById("animation-loop-error");e&&e.remove()}var Ys={target:[0,0,0],distance:10,yaw:0,pitch:.25,minDistance:1,maxDistance:100,minPitch:-Math.PI/2+.01,maxPitch:Math.PI/2-.01,rotateSpeed:.006,zoomSpeed:.001,enabled:!0,enableZoom:!0,enablePan:!1,panSpeed:.0018,autoRotate:!1,autoRotateSpeed:.1},Ct=class{canvas;props;yaw;pitch;distance;dragging=!1;activePointers=new Map;lastPointer=[0,0];previousPinchDistance=null;previousTimeMilliseconds=null;previousCursor;previousTouchAction;constructor(e,t={}){this.canvas=e,this.props={...Ys,...t},this.props.target=[...this.props.target],this.yaw=this.props.yaw,this.pitch=Q(this.props.pitch,this.props.minPitch,this.props.maxPitch),this.distance=Q(this.props.distance,this.props.minDistance,this.props.maxDistance),this.previousCursor=e.style.cursor,this.previousTouchAction=e.style.touchAction,e.style.cursor="grab",e.style.touchAction="none",e.addEventListener("pointerdown",this.handlePointerDown),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("pointerup",this.handlePointerUp),e.addEventListener("pointercancel",this.handlePointerUp),e.addEventListener("wheel",this.handleWheel,{passive:!1})}update(e){if(this.previousTimeMilliseconds!==null&&this.props.enabled&&this.props.autoRotate&&!this.dragging){let t=Math.min(Math.max(e-this.previousTimeMilliseconds,0)/1e3,.1);this.yaw+=this.props.autoRotateSpeed*t}this.previousTimeMilliseconds=e}getEyePosition(){let e=this.distance*Math.cos(this.pitch);return[this.props.target[0]+e*Math.sin(this.yaw),this.props.target[1]+this.distance*Math.sin(this.pitch),this.props.target[2]+e*Math.cos(this.yaw)]}setAutoRotate(e){this.props.autoRotate=e}setProps(e){Object.assign(this.props,e),e.enabled===!1&&this.dragging&&this.endPointerInteraction(),e.target&&(this.props.target=[...e.target]),e.yaw!==void 0&&(this.yaw=e.yaw),(e.pitch!==void 0||e.minPitch!==void 0||e.maxPitch!==void 0)&&(this.pitch=Q(e.pitch??this.pitch,this.props.minPitch,this.props.maxPitch)),(e.distance!==void 0||e.minDistance!==void 0||e.maxDistance!==void 0)&&(this.distance=Q(e.distance??this.distance,this.props.minDistance,this.props.maxDistance))}reset(){this.yaw=this.props.yaw,this.pitch=Q(this.props.pitch,this.props.minPitch,this.props.maxPitch),this.distance=Q(this.props.distance,this.props.minDistance,this.props.maxDistance)}destroy(){this.canvas.removeEventListener("pointerdown",this.handlePointerDown),this.canvas.removeEventListener("pointermove",this.handlePointerMove),this.canvas.removeEventListener("pointerup",this.handlePointerUp),this.canvas.removeEventListener("pointercancel",this.handlePointerUp),this.canvas.removeEventListener("wheel",this.handleWheel),this.endPointerInteraction(),this.canvas.style.cursor=this.previousCursor,this.canvas.style.touchAction=this.previousTouchAction}handlePointerDown=e=>{if(!(!this.props.enabled||e.button!==0||this.activePointers.has(e.pointerId)||this.activePointers.size>=2||this.activePointers.size>0&&e.pointerType!=="touch")){if(this.activePointers.size===0&&this.props.onInteractionStart?.(),this.dragging=!0,this.activePointers.set(e.pointerId,[e.clientX,e.clientY]),this.activePointers.size===1)this.lastPointer=[e.clientX,e.clientY];else{let{center:t,distance:n}=this.getMultiPointerState();this.lastPointer=t,this.previousPinchDistance=n}this.canvas.setPointerCapture(e.pointerId),this.canvas.style.cursor="grabbing"}};handlePointerMove=e=>{if(!this.props.enabled||!this.dragging||!this.activePointers.has(e.pointerId))return;if(this.activePointers.set(e.pointerId,[e.clientX,e.clientY]),this.activePointers.size>1){let{center:r,distance:s}=this.getMultiPointerState();this.props.enablePan&&this.panTarget(r[0]-this.lastPointer[0],r[1]-this.lastPointer[1]),this.props.enableZoom&&this.previousPinchDistance&&s>0&&(this.distance=Q(this.distance*this.previousPinchDistance/s,this.props.minDistance,this.props.maxDistance)),this.lastPointer=r,this.previousPinchDistance=s;return}let t=e.clientX-this.lastPointer[0],n=e.clientY-this.lastPointer[1];this.lastPointer=[e.clientX,e.clientY],this.props.enablePan&&e.shiftKey?this.panTarget(t,n):(this.yaw-=t*this.props.rotateSpeed,this.pitch=Q(this.pitch-n*(this.props.pitchSpeed??this.props.rotateSpeed),this.props.minPitch,this.props.maxPitch))};handlePointerUp=e=>{if(!this.activePointers.has(e.pointerId))return;this.canvas.hasPointerCapture(e.pointerId)&&this.canvas.releasePointerCapture(e.pointerId),this.activePointers.delete(e.pointerId),this.previousPinchDistance=null;let t=this.activePointers.entries().next().value;if(t){this.lastPointer=t[1];return}this.endPointerInteraction()};endPointerInteraction(){this.dragging=!1;for(let e of this.activePointers.keys())this.canvas.hasPointerCapture(e)&&this.canvas.releasePointerCapture(e);this.activePointers.clear(),this.previousPinchDistance=null,this.canvas.style.cursor="grab"}getMultiPointerState(){let[e,t]=this.activePointers.values(),n=t[0]-e[0],r=t[1]-e[1];return{center:[(e[0]+t[0])/2,(e[1]+t[1])/2],distance:Math.hypot(n,r)}}panTarget(e,t){let n=this.distance*this.props.panSpeed;this.props.target=[this.props.target[0]-Math.cos(this.yaw)*e*n,this.props.target[1]+t*n,this.props.target[2]+Math.sin(this.yaw)*e*n]}handleWheel=e=>{if(!this.props.enabled||!this.props.enableZoom)return;e.preventDefault(),this.props.onInteractionStart?.();let t=Q(e.deltaY,-240,240);this.distance=Q(this.distance*Math.exp(t*this.props.zoomSpeed),this.props.minDistance,this.props.maxDistance)}};function Q(i,e,t){return Math.min(Math.max(i,e),t)}var P=R(N(),1),ye=R(ce(),1);var bi=R(N(),1);var Ee=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||O("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&bi.Buffer.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let 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 Hn(i,e){if(e instanceof Ee)return e;let t=Me(e),n=Ws(i,t),{attributes:r,bufferLayout:s}=qs(i,t);return new Ee({topology:t.topology||"triangle-list",bufferLayout:s,vertexCount:t.vertexCount,indices:n,attributes:r})}function Ws(i,e){if(!e.indices)return;let t=e.indices.value;return i.createBuffer({usage:bi.Buffer.INDEX,data:t})}function qs(i,e){let t={};for(let[n,r]of Object.entries(e.attributes)){let s=e.bufferLayout.find(o=>o.name===n)?.name||ge(n);r&&(t[s]=i.createBuffer({data:r.value,id:`${n}-buffer`}))}return{attributes:t,bufferLayout:e.bufferLayout,vertexCount:e.vertexCount}}function Yn(i,e){let t={},n="Values";if(i.attributes.length===0&&!i.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(let r of i.attributes)if(r){let s=`${r.location} ${r.name}: ${r.type}`;t[`in ${s}`]={[n]:r.stepMode||"vertex"}}for(let r of i.varyings||[]){let s=`${r.location} ${r.name}`;t[`out ${s}`]={[n]:JSON.stringify(r)}}return t}var Wn="__debugFramebufferState";function Kn(i,e,t){if(i.device.type!=="webgl")return;let n=Qs(i.device);if(!n.flushing){if(eo(i)){Ks(i,t,n);return}e&&Js(e)&&e.handle!==null&&(n.queuedFramebuffers.includes(e)||n.queuedFramebuffers.push(e))}}function Ks(i,e,t){if(t.queuedFramebuffers.length===0)return;let n=i.device,{gl:r}=n,s=r.getParameter(36010),o=r.getParameter(36006),[a,c]=i.device.getDefaultCanvasContext().getDrawingBufferSize(),h=qn(e.top,8),u=qn(e.left,8);t.flushing=!0;try{for(let d of t.queuedFramebuffers){let[l,f,m,p,b]=Zs({framebuffer:d,targetWidth:a,targetHeight:c,topPx:h,leftPx:u,minimap:e.minimap});r.bindFramebuffer(36008,d.handle),r.bindFramebuffer(36009,null),r.blitFramebuffer(0,0,d.width,d.height,l,f,m,p,16384,9728),h+=b+8}}finally{r.bindFramebuffer(36008,s),r.bindFramebuffer(36009,o),t.flushing=!1}}function Zs(i){let{framebuffer:e,targetWidth:t,targetHeight:n,topPx:r,leftPx:s,minimap:o}=i,a=o?Math.max(Math.floor(t/4),1):t,c=o?Math.max(Math.floor(n/4),1):n,h=Math.min(a/e.width,c/e.height),u=Math.max(Math.floor(e.width*h),1),d=Math.max(Math.floor(e.height*h),1),l=s,f=Math.max(n-r-d,0),m=l+u,p=f+d;return[l,f,m,p,d]}function Qs(i){return i.userData[Wn]||={flushing:!1,queuedFramebuffers:[]},i.userData[Wn]}function Js(i){return"colorAttachments"in i}function eo(i){let e=i.props.framebuffer;return!e||e.handle===null}function qn(i,e){if(!i)return e;let t=Number.parseInt(i,10);return Number.isFinite(t)?t:e}function Ce(i,e,t){if(i===e)return!0;if(!t||!i||!e)return!1;if(Array.isArray(i)){if(!Array.isArray(e)||i.length!==e.length)return!1;for(let n=0;n<i.length;n++)if(!Ce(i[n],e[n],t-1))return!1;return!0}if(Array.isArray(e))return!1;if(typeof i=="object"&&typeof e=="object"){let n=Object.keys(i),r=Object.keys(e);if(n.length!==r.length)return!1;for(let s of n)if(!e.hasOwnProperty(s)||!Ce(i[s],e[s],t-1))return!1;return!0}return!1}var Zn=R(N(),1),Le=class{bufferLayouts;constructor(e){this.bufferLayouts=e}getBufferLayout(e){return this.bufferLayouts.find(t=>t.name===e)||null}getAttributeNamesForBuffer(e){return(0,Zn.getBufferLayoutAttributeNames)(e)}mergeBufferLayouts(e,t){let n=[...e];for(let r of t){let s=n.findIndex(o=>o.name===r.name);s<0?n.push(r):n[s]=r}return n}};var he=R(N(),1);function Qn(i,e){let t=(0,he.getShaderAttributeLocationMap)(i),n=e.slice();return n.sort((r,s)=>{let o=(0,he.getMinimumAttributeLocation)((0,he.getBufferLayoutAttributeNames)(r).map(c=>t[c])),a=(0,he.getMinimumAttributeLocation)((0,he.getBufferLayoutAttributeNames)(s).map(c=>t[c]));return o-a}),n}function Oe(i,e){if(!i||!e.some(n=>n.bindingLayout?.length))return i;let t={...i,bindings:i.bindings.map(n=>({...n}))};"attributes"in(i||{})&&(t.attributes=i?.attributes||[]);for(let n of e)for(let r of n.bindingLayout||[])for(let s of to(r.name)){let o=t.bindings.find(a=>a.name===s);o?.group===0&&(o.group=r.group),o&&r.visibility!==void 0&&(o.visibility=r.visibility)}return t}function Jn(i,e,t=[]){return i?e?{...i,attributes:i.attributes.length?ro(i.attributes,e.attributes.filter(n=>t.includes(n.name))):e.attributes,bindings:no(i.bindings,e.bindings)}:i:e}function Re(i){return!!(i.uniformTypes&&!io(i.uniformTypes))}function Lt(i,e){let t=[],n=new Set;for(let r of[...i||[],...e||[]])n.has(r.name)||(n.add(r.name),t.push(r));return t}function to(i){let e=new Set([i,`${i}Uniforms`]);return i.endsWith("Uniforms")||e.add(`${i}Sampler`),[...e]}function io(i){for(let e in i)return!1;return!0}function no(i,e){let t=i.map(s=>({...s})),n=new Set(i.map(s=>s.name)),r=new Set(i.map(s=>`${s.group}:${s.location}`));for(let s of e){let o=`${s.group}:${s.location}`;!n.has(s.name)&&!r.has(o)&&t.push({...s})}return t}function ro(i,e){let t=i.map(s=>({...s})),n=new Map(i.map(s=>[s.name,s])),r=new Map(i.map(s=>[s.location,s]));for(let s of e){let o=n.get(s.name);if(o){if(o.type!==s.type||o.location!==s.location)throw new Error(`Shader attribute "${s.name}" conflicts with its inferred type or location`);continue}let a=r.get(s.location);if(a)throw new Error(`Shader attributes "${a.name}" and "${s.name}" both use location ${s.location}`);t.push({...s})}return t}var Ot=R(N(),1),yi=R(ce(),1);function er(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function tr(i){return Array.isArray(i)?i.length===0||typeof i[0]=="number":!1}function He(i){return er(i)||tr(i)}function so(i){return He(i)||typeof i=="number"||typeof i=="boolean"}function ir(i,e={}){let t={bindings:{},uniforms:{}};return Object.keys(i).forEach(n=>{let r=i[n];Object.prototype.hasOwnProperty.call(e,n)||so(r)?t.uniforms[n]=r:t.bindings[n]=r}),t}var X=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;directBindings={};constructor(e,t){Object.assign(this.options,t);let n=(0,yi.getShaderModuleDependencies)(Object.values(e).filter(oo));for(let r of n)e[r.name]=r;Ot.log.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(let[r,s]of Object.entries(e))s&&(this._addModule(s),s.name&&r!==s.name&&!this.options.disableWarnings&&Ot.log.warn(`Module name: ${r} vs ${s.name}`)())}destroy(){}setProps(e){e.bindings&&Object.assign(this.directBindings,e.bindings);for(let t of Object.keys(e)){if(t==="bindings")continue;let n=t,r=e[n]||{},s=this.modules[n];if(!s)this.options.disableWarnings||Ot.log.warn(`Module ${t} not found`)();else{let o=this.moduleUniforms[n],a=this.moduleBindings[n],c=s.getUniforms?.(r,o)||r,{uniforms:h,bindings:u}=ir(c,s.uniformTypes);this.moduleUniforms[n]=nr(o,h,s.uniformTypes),this.moduleBindings[n]={...a,...u}}}}getModules(){return Object.values(this.modules)}addModules(e){let t=(0,yi.getShaderModuleDependencies)(e);for(let n of t){let r=n.name;this.modules[r]||(this.modules[r]=n,this._addModule(n))}}getUniformValues(){return this.moduleUniforms}getBindingValues(){let e={};for(let t of Object.values(this.moduleBindings))Object.assign(e,t);return Object.assign(e,this.directBindings),e}getModuleBindingValues(e){let t=this.moduleBindings[e];return t?{...t}:{}}getDebugTable(){let e={};for(let[t,n]of Object.entries(this.moduleUniforms))for(let[r,s]of Object.entries(n))e[`${t}.${r}`]={type:this.modules[t].uniformTypes?.[r],value:String(s)};return e}_addModule(e){let t=e.name;this.moduleUniforms[t]=nr({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[t]={}}};function nr(i={},e={},t={}){let n={...i};for(let[r,s]of Object.entries(e))s!==void 0&&(n[r]=_i(i[r],s,t[r]));return n}function _i(i,e,t){if(!t||typeof t=="string")return Ye(e);if(Array.isArray(t)){if(Ii(e)||!Array.isArray(e))return Ye(e);let o=Array.isArray(i)&&!Ii(i)?[...i]:[],a=o.slice();for(let c=0;c<e.length;c++){let h=e[c];h!==void 0&&(a[c]=_i(o[c],h,t[0]))}return a}if(!vi(e))return Ye(e);let n=t,r=vi(i)?i:{},s={...r};for(let[o,a]of Object.entries(e))a!==void 0&&(s[o]=_i(r[o],a,n[o]));return s}function Ye(i){return ArrayBuffer.isView(i)?Array.prototype.slice.call(i):Array.isArray(i)?Ii(i)?i.slice():i.map(t=>t===void 0?void 0:Ye(t)):vi(i)?Object.fromEntries(Object.entries(i).map(([e,t])=>[e,t===void 0?void 0:Ye(t)])):i}function Ii(i){return ArrayBuffer.isView(i)||Array.isArray(i)&&(i.length===0||typeof i[0]=="number")}function vi(i){return!!i&&typeof i=="object"&&!Array.isArray(i)&&!ArrayBuffer.isView(i)}function oo(i){return!!i?.dependencies}var Mi=R(N(),1);var ao=Mi.Buffer.DEBUG_DATA_MAX_LENGTH,G=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:n=!1,buffer:r,ownsBuffer:s=!0,...o}=t;if(r&&r.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(r&&(o.byteLength!==void 0||o.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||r?.id||O("dynamic-buffer"),c={...o,id:a,usage:o.usage??r?.usage,indexType:o.indexType??r?.indexType};(c.usage||0)&Mi.Buffer.INDEX&&!c.indexType&&(o.data instanceof Uint32Array?c.indexType="uint32":o.data instanceof Uint16Array?c.indexType="uint16":o.data instanceof Uint8Array&&(c.indexType="uint8")),delete c.data,delete c.byteOffset,this.device=e,this.id=a,this.props=c,this.usage=c.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:ao,this._ownsBuffer=s,this._buffer=r??this.device.createBuffer({...o,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),o.data&&this._writeDebugData(o.data,o.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let r=null;await this._buffer.mapAndWriteAsync(async(s,o)=>{await e(s,o),r=new Uint8Array(s.slice(0,n))},t,n),this._touch(),r&&this._writeDebugData(r,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let r=null,s=await this._buffer.mapAndReadAsync(async(o,a)=>(r=new Uint8Array(o.slice(0)),await e(o,a)),t,n);return r&&this._writeDebugData(r,t)&&this._touch(),s}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let r=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),s=this._buffer,o=this.debugData.slice(0),{data:a,byteOffset:c,...h}=this.props,u=this.device.createBuffer({...h,byteLength:t});return n&&r>0&&this._copyBufferContents(s,u,r),this._buffer=u,this._resetDebugData(t),n&&o.byteLength>0&&this._writeDebugData(o,0),this._ownsBuffer&&s.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,n){let r=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,s=this.device.createCommandEncoder();s.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:r}),this.device.submit(s.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=new Uint8Array(this.debugData),s=Math.min(n.byteLength,r.byteLength-t);return r.set(n.subarray(0,s),t),s>0}};function be(i){return i!==null&&typeof i=="object"&&"buffer"in i}function rr(i){return i instanceof G?i:be(i)&&i.buffer instanceof G?i.buffer:null}function co(i){return i instanceof G?i.buffer:i}function Rt(i){return{buffer:co(i.buffer),offset:i.offset,size:i.size}}var sr=R(N(),1);function ne(i){return i!==null&&typeof i=="object"&&"resolveTextureBinding"in i&&typeof i.resolveTextureBinding=="function"}function ho(i){return i?.type==="texture"||i?.type==="external-texture"}function kt(i,e,t){let n=(0,sr.getShaderLayoutBinding)(i,e,{ignoreWarnings:!0});return ho(n)?n:i.bindings.length===0&&t?.fallbackGroup!==void 0?{type:"texture",name:e,group:t.fallbackGroup,location:0}:null}var J=2,uo=1e4,Ti="render pipeline initialization failed",lo=["stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8"],Y=class i{static defaultProps={...P.RenderPipeline.defaultProps,source:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],plugins:[],geometry:null,indexBuffer:null,indexCount:void 0,firstVertex:0,firstIndex:0,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,material:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:ye.ShaderAssembler.getDefaultShaderAssembler("glsl"),debugShaders:void 0,disableWarnings:void 0};device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexCount;firstVertex;firstIndex;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;material=null;_uniformStore;_attributeInfos={};_gpuGeometry=null;props;_dynamicIndexBufferSource=null;_dynamicAttributeBufferSources={};_colorAttachmentFormats;_depthStencilAttachmentFormat;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_drawBlockedReason=!1;_destroyed=!1;_lastDrawTimestamp=-1;_bindingTable=[];get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(e,t){let n=i.defaultProps.shaderAssembler;this.props={...i.defaultProps,...t,shaderAssembler:t.shaderAssembler??(wi(n,e.info.shadingLanguage)?n:ye.ShaderAssembler.getDefaultShaderAssembler(e.info.shadingLanguage))},t=this.props,this.id=t.id||O("model"),this.device=e,Object.assign(this.userData,t.userData),this.material=t.material||null;let r=xo(e),s=(0,ye.resolveShaderPlugins)(this.props.plugins,r.shaderLanguage),o=(0,ye.mergeShaderPluginModules)(this.props.modules,s.modules),a=Object.fromEntries(o.map(l=>[l.name,l])),c=t.shaderInputs||new X(a,{disableWarnings:this.props.disableWarnings});t.shaderInputs&&s.modules.length>0&&c.addModules(s.modules),this.setShaderInputs(c);let h=Lt(this.props.modules,c.getModules()),u={...s.defines,...this.props.defines};if(this.props.shaderLayout=Oe(this.props.shaderLayout,h)||null,this.device.type==="webgpu"&&this.props.source){let l=this.props.shaderAssembler;(0,P.assert)(wi(l,"wgsl"));let{source:f,getUniforms:m,bindingTable:p,shaderLayout:b}=l.assembleWGSLShader({platformInfo:r,...this.props,modules:h,defines:u,pluginInjections:s.injections,pluginVertexInputs:s.vertexInputs,pluginVaryings:s.varyings});this.source=f,this._getModuleUniforms=m,this._bindingTable=p;let _=b??e.getShaderLayout?.(this.source),M=fo(_,s.vertexInputs),y=Jn(this.props.shaderLayout,M,Object.keys(s.vertexInputs));this.props.shaderLayout=Oe(y||null,h)||null}else{let l=this.props.shaderAssembler;(0,P.assert)(wi(l,"glsl"));let{vs:f,fs:m,getUniforms:p}=l.assembleGLSLShaderPair({platformInfo:r,...this.props,modules:h,defines:u,pluginInjections:s.injections,pluginVertexInputs:s.vertexInputs,pluginVaryings:s.varyings});this.vs=f,this.fs=m,this._getModuleUniforms=p,this._bindingTable=[]}this.vertexCount=this.props.vertexCount,this.indexCount=this.props.indexCount,this.firstVertex=this.props.firstVertex,this.firstIndex=this.props.firstIndex,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,this._colorAttachmentFormats=this.props.colorAttachmentFormats,this._depthStencilAttachmentFormat=this.props.depthStencilAttachmentFormat,t.geometry&&this.setGeometry(t.geometry),this.pipelineFactory=t.pipelineFactory||P.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||P.ShaderFactory.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 t&&(this.isInstanced=t.isInstanced),t.instanceCount&&this.setInstanceCount(t.instanceCount),t.vertexCount&&this.setVertexCount(t.vertexCount),t.indexBuffer&&this.setIndexBuffer(t.indexBuffer),t.attributes&&this.setAttributes(t.attributes),t.constantAttributes&&this.setConstantAttributes(t.constantAttributes),t.bindings&&this.setBindings(t.bindings),t.transformFeedback&&(this.transformFeedback=t.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");let e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(e){this._syncDynamicBuffers(),this.updateShaderInputs(e),this.material?.updateShaderInputs(e),this.pipeline=this._updatePipeline()}draw(e){if(this._drawBlockedReason&&!this._pipelineNeedsUpdate)return P.log.info(J,`>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)(),!1;let t=this._areBindingsLoading();if(t)return P.log.info(J,`>>> DRAWING ABORTED ${this.id}: ${t} not loaded`)(),!1;this._syncAttachmentFormats(e);try{e.pushDebugGroup(`${this}.predraw(${e})`),this.device.type==="webgpu"?(this.updateShaderInputs(),this.material?.updateShaderInputs(),this._syncDynamicBuffers(),this.pipeline=this._updatePipeline()):this.predraw(this.device.commandEncoder)}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)P.log.info(J,`>>> DRAWING ABORTED ${this.id}: ${Ti}`)(),n=!1;else{let s=this.vertexArray.getDrawValidationError();if(s)P.log.info(J,`>>> DRAWING ABORTED ${this.id}: ${s}`)(),this._drawBlockedReason=s,n=!1;else{let o=this._getCurrentShaderLayout(),a=this._getBindings(o),c=this._getBindGroups(o,a),{indexBuffer:h}=this.vertexArray,u=h?this.indexCount??h.byteLength/(h.indexType==="uint32"?4:2):void 0;e.setPipeline(this.pipeline),e.setBindings(c,{_bindGroupCacheKeys:this._getBindGroupCacheKeys()}),e.setVertexArray(this.vertexArray),n=this.isInstanced===!0&&this.instanceCount===0?!0:e.draw({isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.isInstanced?this.instanceCount:void 0,indexCount:u,firstVertex:this.firstVertex,firstIndex:this.firstIndex,transformFeedback:this.transformFeedback||void 0,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=Ti,this._drawBlockedReason=Ti):this._drawBlockedReason?this._needsRedraw=this._drawBlockedReason:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){this._gpuGeometry?.destroy();let t=e&&Hn(this.device,e);if(t){this.setTopology(t.topology||"triangle-list");let n=new Le(this.bufferLayout);this.bufferLayout=n.mergeBufferLayouts(t.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(t)}this._gpuGeometry=t}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){let t=new Le(this.bufferLayout),n=this._gpuGeometry?t.mergeBufferLayouts(e,this._gpuGeometry.bufferLayout):e;Ce(n,this.bufferLayout,-1)||(this.bufferLayout=n,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){Ce(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")}setIndexCount(e){this.indexCount=e,this.setNeedsRedraw("indexCount")}setDrawOffsets({firstVertex:e,firstIndex:t}){this.firstVertex=e,this.firstIndex=t,this.setNeedsRedraw("drawOffsets")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new P.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(Re(n)&&!this.material?.ownsModule(t)){let r=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=r}this.setNeedsRedraw("shaderInputs")}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),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){let t=e instanceof G?e.buffer:e;this.indexBuffer=t,this._dynamicIndexBufferSource=e instanceof G?{source:e,generation:e.generation}:null,this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(e,t){this._drawBlockedReason=!1;let n=t?.disableWarnings??this.props.disableWarnings;e.indices&&P.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=Qn(this.pipeline.shaderLayout,this.bufferLayout);let r=new Le(this.bufferLayout);for(let[s,o]of Object.entries(e)){let a=o instanceof G?o.buffer:o,c=r.getBufferLayout(s);if(!c){n||P.log.warn(`Model(${this.id}): Missing layout for buffer "${s}".`)();continue}let h=r.getAttributeNamesForBuffer(c),u=!1;for(let d of h){let l=this._attributeInfos[d];if(l){let f=this.device.type==="webgpu"?this.vertexArray.getBufferSlot(l.bufferName):l.location;if(f===null){n||P.log.warn(`Model(${this.id}): Missing vertex array slot for buffer "${l.bufferName}".`)();continue}this.vertexArray.setBuffer(f,a),o instanceof G?this._dynamicAttributeBufferSources[f]={source:o,generation:o.generation}:delete this._dynamicAttributeBufferSources[f],u=!0}}!u&&!n&&P.log.warn(`Model(${this.id}): Ignoring buffer "${a.id}" for unknown attribute "${s}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,t){for(let[n,r]of Object.entries(e)){let s=this._attributeInfos[n];s?this.vertexArray.setConstantWebGL(s.location,r):(t?.disableWarnings??this.props.disableWarnings)||P.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let e of Object.values(this.bindings))if(ne(e)&&!e.isReady)return e.id;for(let e of Object.values(this.material?.bindings||{}))if(ne(e)&&!e.isReady)return e.id;return!1}_getBindings(e=this._getCurrentShaderLayout()){let t={};for(let[n,r]of Object.entries(this.bindings)){let s=mo(n,r,e);s&&(t[n]=s)}return t}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){let n=e.bindings.length?(0,P.normalizeBindingsByGroup)(e,t):{0:t};if(!this.material)return n;for(let[r,s]of Object.entries(this.material.getBindingsByGroup(e))){let o=Number(r);n[o]={...n[o]||{},...s}}return n}_getBindGroupCacheKeys(){let e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){let e=0;this._dynamicIndexBufferSource&&(e=Math.max(e,this._dynamicIndexBufferSource.source.updateTimestamp));for(let t of Object.values(this._dynamicAttributeBufferSources))e=Math.max(e,t.source.updateTimestamp);for(let t of Object.values(this.bindings))t instanceof P.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof P.Buffer||t instanceof P.Texture||t instanceof P.ExternalTexture||t instanceof G?e=Math.max(e,t.updateTimestamp):ne(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:be(t)&&(e=Math.max(e,(t.buffer instanceof G,t.buffer.updateTimestamp)));return Math.max(e,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(e){let t={...e.attributes};for(let[n]of Object.entries(t))!this.pipeline.shaderLayout.attributes.find(r=>r.name===n)&&n!=="positions"&&delete t[n];this.vertexCount=e.vertexCount,this.setIndexBuffer(e.indices||null),this.setAttributes(e.attributes,{disableWarnings:!0}),this.setAttributes(t,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this._drawBlockedReason=!1,this.setNeedsRedraw(e)}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null,t=null;this.pipeline&&(P.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.pipeline.vs,t=this.pipeline.fs),this._pipelineNeedsUpdate=!1;let n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),r=null;this.source?r=n:this.fs&&(r=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bindings:void 0,bufferLayout:this.bufferLayout,colorAttachmentFormats:this._colorAttachmentFormats,depthStencilAttachmentFormat:this._depthStencilAttachmentFormat,topology:this.topology,parameters:this.parameters,bindGroups:void 0,vs:n,fs:r}),this._attributeInfos=(0,P.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),e&&this.shaderFactory.release(e),t&&t!==e&&this.shaderFactory.release(t)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=P.log.level>3?0:uo;P.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,P.log.group(J,`>>> DRAWING MODEL ${this.id}`,{collapsed:P.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=Yn(this.pipeline.shaderLayout,this.id);P.log.table(J,e)();let t=this.shaderInputs.getDebugTable();P.log.table(J,t)();let n=this._getAttributeDebugTable();P.log.table(J,this._attributeInfos)(),P.log.table(J,n)(),P.log.groupEnd(J)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){let t=this.device.props.debugFramebuffers;if(this._drawCount++,!t)return;let n=e.props.framebuffer;Kn(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let e={};for(let[t,n]of Object.entries(this._attributeInfos)){let r=this.vertexArray.attributes[n.location];e[n.location]={name:t,type:n.shaderType,values:r?this._getBufferOrConstantValues(r,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:t}=this.vertexArray,n=t.indexType==="uint32"?new Uint32Array(t.debugData):new Uint16Array(t.debugData);e.indices={name:"indices",type:t.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,t){let n=P.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof P.Buffer?new n(e.debugData):e).toString()}_getNonMaterialBindings(e){if(!this.material)return e;let t={};for(let[n,r]of Object.entries(e))this.material.ownsBinding(n)||(t[n]=r);return t}_getCurrentShaderLayout(){return this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]}}_syncDynamicBuffers(){if(this._dynamicIndexBufferSource&&this._dynamicIndexBufferSource.generation!==this._dynamicIndexBufferSource.source.generation){let e=this._dynamicIndexBufferSource.source.buffer;this.indexBuffer=e,this.vertexArray.setIndexBuffer(e),this._dynamicIndexBufferSource.generation=this._dynamicIndexBufferSource.source.generation,this.setNeedsRedraw("dynamic index buffer")}for(let[e,t]of Object.entries(this._dynamicAttributeBufferSources))t.generation!==t.source.generation&&(this.vertexArray.setBuffer(Number(e),t.source.buffer),t.generation=t.source.generation,this.setNeedsRedraw("dynamic attribute buffer"))}_syncAttachmentFormats(e){if(this.device.type!=="webgpu")return;let t=e.framebuffer||e.props.framebuffer,n=e.props,r=n.colorAttachmentFormats??t?.colorAttachments?.map(o=>po(o?.texture?.format)),s=n.depthStencilAttachmentFormat===!1?void 0:n.depthStencilAttachmentFormat??go(t?.depthStencilAttachment?.texture?.format);(!Ce(this._colorAttachmentFormats,r,1)||this._depthStencilAttachmentFormat!==s)&&(this._colorAttachmentFormats=r,this._depthStencilAttachmentFormat=s,this._setPipelineNeedsUpdate("attachment formats"))}};function wi(i,e){return i.shaderLanguage!==void 0&&i.shaderLanguage!==e?!1:e==="glsl"?"assembleGLSLShaderPair"in i&&typeof i.assembleGLSLShaderPair=="function":"assembleWGSLShader"in i&&typeof i.assembleWGSLShader=="function"}function fo(i,e){return!i||Object.keys(e).length===0?i:{...i,attributes:i.attributes.map(t=>{let n=t.name.startsWith("_luma_")?t.name.slice(6):null;return n&&e[n]?{...t,name:n}:t})}}function mo(i,e,t){if(ne(e)){let n=kt(t,i,{fallbackGroup:0});return n?e.resolveTextureBinding(n):null}return e instanceof G?e.buffer:be(e)?Rt(e):e}function po(i){return i&&!or(i)?i:null}function go(i){return i&&or(i)?i:void 0}function or(i){return lo.includes(i)}function xo(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,limits:i.limits,features:i.features}}var ee=R(N(),1);var Ne=3,ke=class{device;modules;_materialBindingNames;_materialModuleNames;constructor(e,t={}){this.device=e,this.modules=t.modules||[];let n=new X(Object.fromEntries(this.modules.map(r=>[r.name,r])));this._materialBindingNames=bo(n),this._materialModuleNames=yo(n)}createMaterial(e={}){return new De(this.device,{...e,factory:this})}getBindingNames(){return Array.from(this._materialBindingNames)}ownsBinding(e){if(this._materialBindingNames.has(e))return!0;let t=Ai(e);return t?this._materialModuleNames.has(t):!1}ownsModule(e){return this._materialModuleNames.has(e)}getBindingsByGroup(e){return Object.keys(e).length>0?{[Ne]:e}:{}}};function Ai(i){return i.endsWith("Uniforms")?i.slice(0,-8):null}function bo(i){let e=new Set;for(let t of Object.values(i.modules))for(let n of t.bindingLayout||[])n.group===Ne&&e.add(n.name);return e}function yo(i){let e=new Set;for(let t of Object.values(i.modules))t.name&&t.bindingLayout?.some(n=>n.group===Ne&&n.name===t.name)&&e.add(t.name);return e}var De=class{id;device;factory;shaderInputs;bindings={};_uniformStore;_bindGroupCacheToken={};_dynamicResourceGenerations={};constructor(e,t={}){this.id=t.id||O("material"),this.device=e,this.factory=t.factory||new ke(e,{modules:t.modules||t.shaderInputs?.getModules()||[]});let n=Object.fromEntries((t.shaderInputs?.getModules()||this.factory.modules).map(r=>[r.name,r]));this.shaderInputs=t.shaderInputs||new X(n),this._uniformStore=new ee.UniformStore(this.device,this.shaderInputs.modules);for(let[r,s]of Object.entries(this.shaderInputs.modules))if(this.ownsModule(r)&&Re(s)){let o=this._uniformStore.getManagedUniformBuffer(r);this.bindings[`${r}Uniforms`]=o}this.updateShaderInputs(),t.bindings&&this._replaceOwnedBindings(t.bindings)}destroy(){this._uniformStore.destroy()}clone(e={}){let t=this.factory.createMaterial({id:e.id,shaderInputs:e.shaderInputs,bindings:{...this.getResourceBindings(),...e.bindings}});return e.shaderInputs||t.setProps(this.shaderInputs.getUniformValues()),e.moduleProps&&t.setProps(e.moduleProps),t.updateShaderInputs(),t}ownsBinding(e){return this.factory.ownsBinding(e)}ownsModule(e){return this.factory.ownsModule(e)}setProps(e){this.shaderInputs.setProps(e)}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this._setOwnedBindings(this.shaderInputs.getBindingValues())&&(this._bindGroupCacheToken={})}getResourceBindings(){let e={};for(let[t,n]of Object.entries(this.bindings))Ai(t)||(e[t]=n);return e}getBindings(e={bindings:[]}){this._syncDynamicResourceGenerations();let t={},n=t;for(let[r,s]of Object.entries(this.bindings))if(ne(s)){let o=kt(e,r,{fallbackGroup:Ne}),a=o?s.resolveTextureBinding(o):null;a&&(n[r]=a)}else s instanceof G?n[r]=s.buffer:be(s)?n[r]=Rt(s):n[r]=s;return this._syncDynamicResourceGenerations(),t}getBindingsByGroup(e={bindings:[]}){return this.factory.getBindingsByGroup(this.getBindings(e))}getBindGroupCacheKey(e){return this._syncDynamicResourceGenerations(),e===Ne?this._bindGroupCacheToken:null}getBindingsUpdateTimestamp(){let e=0;for(let t of Object.values(this.bindings))t instanceof ee.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof ee.Buffer||t instanceof ee.Texture||t instanceof ee.ExternalTexture||t instanceof G?e=Math.max(e,t.updateTimestamp):ne(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:be(t)&&(e=Math.max(e,(t.buffer instanceof G,t.buffer.updateTimestamp)));return e}_replaceOwnedBindings(e){this._setOwnedBindings(e)&&(this._bindGroupCacheToken={})}_setOwnedBindings(e){let t=!1;for(let[n,r]of Object.entries(e))r!==void 0&&this.ownsBinding(n)&&this.bindings[n]!==r&&(this.bindings[n]=r,t=!0);return t}_syncDynamicResourceGenerations(){let e={},t=!1;for(let[n,r]of Object.entries(this.bindings)){let s=_o(r);s!==null&&(e[n]=s,this._dynamicResourceGenerations[n]!==s&&(t=!0))}Object.keys(e).length!==Object.keys(this._dynamicResourceGenerations).length&&(t=!0),this._dynamicResourceGenerations=e,t&&(this._bindGroupCacheToken={})}};function _o(i){return ne(i)?i.generation:rr(i)?.generation??null}var ar=R(N(),1),cr=R(ce(),1);var Io=35980,vo=35981,Nt=class i{device;model;transformFeedback;static defaultProps={...Y.defaultProps,feedbackBufferMode:"separate",outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return e?.info?.type==="webgl"}constructor(e,t=i.defaultProps){if(!i.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.model=new Y(this.device,{id:t.id||"buffer-transform-model",fs:t.fs||(0,cr.getPassthroughFS)(),topology:t.topology||"point-list",varyings:t.outputs||t.varyings,...t,bufferMode:t.bufferMode||(t.feedbackBufferMode==="interleaved"?Io:vo)}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:t.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback)}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);let t=this.device.beginRenderPass({discard:!0,...e});this.model.draw(t),t.end()}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){let t=this.getBuffer(e);if(!t)throw new Error("BufferTransform#getBuffer");if(t instanceof ar.Buffer)return t.readAsync();let{buffer:n,byteOffset:r=0,byteLength:s=n.byteLength}=t;return n.readAsync(r,s)}};var hr=R(ce(),1);var Mo="transform_output",Dt=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(e,t){this.device=e,this.sampler=e.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new Y(this.device,{id:t.id||O("texture-transform-model"),fs:t.fs||(0,hr.getPassthroughFS)({input:t.targetTextureVarying,inputChannels:t.targetTextureChannels,output:Mo}),vertexCount:t.vertexCount,...t}),this._initialize(t),Object.seal(this)}destroy(){this.model.destroy();for(let e of this.bindings)e.framebuffer?.destroy()}delete(){this.destroy()}run(e){let{framebuffer:t}=this.bindings[this.currentIndex],n=this.device.beginRenderPass({framebuffer:t,...e});this.model.draw(n),n.end(),this.device.submit()}getTargetTexture(){let{targetTexture:e}=this.bindings[this.currentIndex];return e}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(e){this._updateBindings(e)}_updateBindings(e){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],e)}_updateBinding(e,{sourceBuffers:t,sourceTextures:n,targetTexture:r}){if(e||(e={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(e.sourceTextures,n),Object.assign(e.sourceBuffers,t),r){e.targetTexture=r;let{width:s,height:o}=r;e.framebuffer&&e.framebuffer.destroy(),e.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:s,height:o,colorAttachments:[r]}),e.framebuffer.resize({width:s,height:o})}return e}_setSourceTextureParameters(){let e=this.currentIndex,{sourceTextures:t}=this.bindings[e];for(let n in t)t[n].sampler=this.sampler}};var To=`struct VertexInputs {
|
|
7
|
+
"use strict";var __exports__=(()=>{var cs=Object.create;var ct=Object.defineProperty;var hs=Object.getOwnPropertyDescriptor;var us=Object.getOwnPropertyNames;var ls=Object.getPrototypeOf,ds=Object.prototype.hasOwnProperty;var rn=(i,e)=>()=>{try{return e||i((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},fs=(i,e)=>{for(var t in e)ct(i,t,{get:e[t],enumerable:!0})},at=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of us(e))!ds.call(i,r)&&r!==t&&ct(i,r,{get:()=>e[r],enumerable:!(n=hs(e,r))||n.enumerable});return i},ht=(i,e,t)=>(at(i,e,"default"),t&&at(t,e,"default")),R=(i,e,t)=>(t=i!=null?cs(ls(i)):{},at(e||!i||!i.__esModule?ct(t,"default",{value:i,enumerable:!0}):t,i)),ms=i=>at(ct({},"__esModule",{value:!0}),i);var N=rn((gc,sn)=>{sn.exports=globalThis.luma});var ne=rn((jh,Hn)=>{Hn.exports=globalThis.luma});var it={};fs(it,{AnimationAction:()=>Ve,AnimationClip:()=>pt,AnimationClipController:()=>ut,AnimationLoop:()=>Ee,AnimationLoopTemplate:()=>St,AnimationMixer:()=>gt,AnimationTrack:()=>mt,Animator:()=>lt,AsyncTexture:()=>mc,BackgroundTextureModel:()=>Be,BufferTransform:()=>Dt,ClipSpace:()=>ue,Computation:()=>Ge,ConeGeometry:()=>fe,CubeGeometry:()=>Wt,CylinderGeometry:()=>qt,DirectionalLightModel:()=>Gt,DynamicBuffer:()=>G,DynamicTexture:()=>K,GPUGeometry:()=>Ce,Geometry:()=>z,GroupNode:()=>Xt,IcoSphereGeometry:()=>Kt,KeyFrames:()=>At,LegacyPickingManager:()=>si,Material:()=>De,MaterialFactory:()=>ke,Model:()=>Y,ModelNode:()=>Ht,OrbitControls:()=>Ct,PickingManager:()=>ii,PlaneGeometry:()=>Zt,PointLightModel:()=>zt,ScenegraphNode:()=>se,ShaderInputs:()=>X,ShaderPassRenderer:()=>ti,SphereGeometry:()=>Fe,SpotLightModel:()=>jt,Swap:()=>ze,SwapBuffers:()=>ei,SwapFramebuffers:()=>je,TextureTransform:()=>Bt,Timeline:()=>wt,TruncatedConeGeometry:()=>de,VideoTexture:()=>Jt,_resolveLoadFileUrl:()=>Qt,applyMorphTargets:()=>ui,cancelAnimationFramePolyfill:()=>Et,colorPicking:()=>et,decodeMorphTargetAttribute:()=>hi,evaluateAnimationSampler:()=>dt,getIndexPickingModule:()=>ts,indexColorPicking:()=>ri,indexPicking:()=>tt,legacyColorPicking:()=>ns,loadImage:()=>Br,loadImageBitmap:()=>Dr,makeAnimationLoop:()=>Xn,makeInterleavedGeometry:()=>Te,makeRandomGenerator:()=>Or,picking:()=>es,requestAnimationFramePolyfill:()=>Pt,resolvePickingBackend:()=>Jr,resolvePickingMode:()=>ni,setPathPrefix:()=>Nr,simplifyMesh:()=>Lr,supportsIndexPicking:()=>Je,updateMorphTargetBuffers:()=>un,updateSkinJointMatrices:()=>Gn});ht(it,R(N(),1));var on=R(N(),1),ut=class{name;playing=!0;speed=1;startTime=0;constructor(e={}){this.name=e.name||"unnamed",Object.assign(this,e)}setTime(e){if(!this.playing)return;let n=(e/1e3-this.startTime)*this.speed;this.applyTime(n)}},lt=class{clips;animations;constructor(e){this.clips=e,this.animations=e}animate(e){on.log.warn(`${this.constructor.name}#animate is deprecated. Use ${this.constructor.name}#setTime instead`)(),this.setTime(e)}setTime(e){this.clips.forEach(t=>t.setTime(e))}getAnimations(){return this.clips}};function dt(i,e,t="vector"){let{input:n,output:r,interpolation:s="LINEAR"}=e;if(!n.length||!r.length||!Number.isFinite(i))return null;let o=n.length-1;if(i<=n[0]||o===0)return oi(r,s,0,t);if(i>=n[o])return oi(r,s,o,t);let a=0,c=o;for(;c-a>1;){let f=Math.floor((a+c)/2);n[f]<=i?a=f:c=f}let h=n[a],d=n[c]-h;if(d<=0||s==="STEP")return oi(r,s,a,t);let l=(i-h)/d;switch(s){case"LINEAR":{let f=r[a],m=r[c];return!f||!m?null:t==="quaternion"?ft(f,m,l):ps(f,m,l)}case"CUBICSPLINE":{let f=r[a*3+1],m=r[a*3+2],p=r[c*3],b=r[c*3+1];if(!f||!m||!p||!b)return null;let _=gs(f,m,p,b,d,l);return t==="quaternion"?Me(_):_}default:return null}}function ft(i,e,t){let n=Me(i),r=Me(e),s=n.reduce((d,l,f)=>d+l*r[f],0),o=s<0?-1:1;if(s=Math.min(Math.abs(s),1),s>.9995)return Me(n.map((d,l)=>d+t*(r[l]*o-d)));let a=Math.acos(s),c=Math.sin(a),h=Math.sin((1-t)*a)/c,u=Math.sin(t*a)/c*o;return Me(n.map((d,l)=>d*h+r[l]*u))}function oi(i,e,t,n){let r=i[e==="CUBICSPLINE"?t*3+1:t];return r?n==="quaternion"?Me(r):[...r]:null}function ps(i,e,t){return i.map((n,r)=>(1-t)*n+t*e[r])}function gs(i,e,t,n,r,s){let o=s*s,a=o*s;return i.map((c,h)=>(2*a-3*o+1)*c+(a-2*o+s)*e[h]*r+(-2*a+3*o)*n[h]+(a-o)*t[h]*r)}function Me(i){let e=Math.hypot(...i);return e>0?i.map(t=>t/e):[0,0,0,1]}var mt=class{name;times;values;interpolation;valueType;binding;constructor(e){this.name=e.name||e.binding.id||"unnamed",this.times=e.times,this.values=e.values,this.interpolation=e.interpolation||"LINEAR",this.valueType=e.valueType||"vector",this.binding=e.binding}get duration(){return this.times[this.times.length-1]||0}get sampler(){return{input:this.times,output:this.values,interpolation:this.interpolation}}evaluate(e){return dt(e,this.sampler,this.valueType)}};var pt=class{name;tracks;duration;constructor(e){this.name=e.name||"unnamed",this.tracks=e.tracks,this.duration=e.duration??Math.max(0,...e.tracks.map(t=>t.duration))}};var Ve=class{clip;mixer;time=0;timeScale;weight;loop;repetitions;paused=!1;playing=!1;elapsedTime=0;fade=null;constructor(e,t,n={}){this.mixer=e,this.clip=t,this.loop=n.loop||"repeat",this.repetitions=n.repetitions??Number.POSITIVE_INFINITY,this.timeScale=n.timeScale??1,this.weight=n.weight??1}play(){return this.playing=!0,this.paused=!1,this}pause(){return this.paused=!0,this}resume(){return this.playing=!0,this.paused=!1,this}stop(){return this.playing=!1,this.paused=!1,this.fade=null,this.reset()}reset(){return this.elapsedTime=0,this.time=0,this}setTime(e){return this.elapsedTime=e,this.time=this.resolveLocalTime(e),this}setLoop(e,t=Number.POSITIVE_INFINITY){return this.loop=e,this.repetitions=t,this.time=this.resolveLocalTime(this.elapsedTime),this}setEffectiveWeight(e){return this.weight=Math.max(0,e),this.fade=null,this}setEffectiveTimeScale(e){return this.timeScale=e,this}fadeIn(e){return this.scheduleFade(1,e)}fadeOut(e){return this.scheduleFade(0,e)}crossFadeTo(e,t){return e.weight=0,e.play().fadeIn(t),this.fadeOut(t)}crossFadeFrom(e,t){return e.crossFadeTo(this,t),this}advance(e){!this.playing||this.paused||(this.advanceFade(Math.abs(e)),this.elapsedTime+=e*this.timeScale,this.time=this.resolveLocalTime(this.elapsedTime),this.hasFinished()&&(this.playing=!1))}get shouldApply(){return(this.playing||this.hasFinished())&&this.weight>0}scheduleFade(e,t){return t<=0?(this.weight=e,this.fade=null,this):(this.fade={duration:t,elapsedTime:0,startWeight:this.weight,endWeight:e},this)}advanceFade(e){if(!this.fade)return;this.fade.elapsedTime+=e;let t=Math.min(this.fade.elapsedTime/this.fade.duration,1);this.weight=this.fade.startWeight+(this.fade.endWeight-this.fade.startWeight)*t,t===1&&(this.fade=null)}hasFinished(){let e=this.clip.duration;return e<=0?this.loop==="once":this.loop==="once"?this.elapsedTime>=e||this.elapsedTime<0:Number.isFinite(this.repetitions)&&Math.abs(this.elapsedTime)>=e*this.repetitions}resolveLocalTime(e){let t=this.clip.duration;if(t<=0)return 0;if(this.loop==="once")return Math.min(Math.max(e,0),t);if(Number.isFinite(this.repetitions)&&Math.abs(e)>=t*this.repetitions)return this.loop==="ping-pong"&&this.repetitions%2===0||e<0?0:t;let n=e>=0&&e<t?e:(e%t+t)%t;if(this.loop==="repeat")return n;let r=Math.floor(e/t);return Math.abs(r%2)===0?n:t-n}},gt=class{time=0;timeScale=1;clips=new Map;actions=new Map;initialValues=new Map;constructor(e=[]){e.forEach(t=>this.addClip(t))}addClip(e){return this.clips.set(e.name,e),this}clipAction(e,t){let n=typeof e=="string"?this.clips.get(e):e;if(!n)throw new Error(`Unknown animation clip: ${e}`);this.addClip(n);let r=this.actions.get(n);return r||(r=new Ve(this,n,t),this.actions.set(n,r)),r}getAction(e){let t=this.clips.get(e);return t?this.actions.get(t):void 0}update(e){return this.advance(e),this.applyValues(),this}advance(e){let t=e*this.timeScale;return this.time+=t,this.actions.forEach(n=>n.advance(t)),this}setTime(e){return this.time=e,this.actions.forEach(t=>{t.paused||t.setTime(e*t.timeScale)}),this.applyValues(),this}stopAllAction(){return this.actions.forEach(e=>e.stop()),this}applyValues(){let e=new Map;this.actions.forEach(t=>{!t.shouldApply&&!(t.playing&&t.weight===0)||t.clip.tracks.forEach(n=>{let r=n.evaluate(t.time);if(!r)return;let s=n.binding.id||n.binding;if(!this.initialValues.has(s)){let h=n.binding.getValue?.();h&&this.initialValues.set(s,[...h])}if(t.weight===0&&!this.initialValues.has(s))return;let o=e.get(s);if(!o){e.set(s,{binding:n.binding,value:[...r],valueType:n.valueType,weight:t.weight});return}if(t.weight===0)return;let a=o.weight+t.weight,c=t.weight/a;o.value=n.valueType==="quaternion"?ft(o.value,r,c):o.value.map((h,u)=>h+(r[u]-h)*c),o.weight=a})}),e.forEach(({binding:t,value:n,valueType:r,weight:s},o)=>{let a=s<1?this.initialValues.get(o):void 0;a&&a.length===n.length&&(n=r==="quaternion"?ft(a,n,s):n.map((c,h)=>a[h]+(c-a[h])*s)),t.setValue(n)})}};var an=R(N(),1);var ai={};function O(i="id"){ai[i]=ai[i]||1;let e=ai[i]++;return`${i}-${e}`}var z=class{id;topology;vertexCount;indices;attributes;bufferLayout;userData={};constructor(e){let{attributes:t={},indices:n=null,vertexCount:r=null}=e;this.id=e.id||O("geometry"),this.topology=e.topology,n&&(this.indices=ArrayBuffer.isView(n)?{value:n,size:1}:n),this.attributes={};for(let[s,o]of Object.entries(t)){let 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{let c=ge(s),h=Object.keys(this.attributes).find(u=>ge(u)===c);h&&delete this.attributes[h],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),this.bufferLayout=e.bufferLayout||xs(this.attributes)}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,t){return this}_calculateVertexCount(e,t){if(t)return t.value.length;let n=1/0;for(let r of Object.values(e)){if(!r)continue;let{value:s,size:o,constant:a}=r;!a&&s&&o!==void 0&&o>=1&&(n=Math.min(n,s.length/o))}return n}};function ge(i){switch(i){case"POSITION":return"positions";case"NORMAL":return"normals";case"TEXCOORD_0":return"texCoords";case"TEXCOORD_1":return"texCoords1";case"COLOR_0":return"colors";default:return i}}function xs(i){let e=[];for(let[t,n]of Object.entries(i)){if(!n)continue;let{value:r,size:s,normalized:o}=n;if(s===void 0)throw new Error(`Attribute ${t} is missing a size`);e.push({name:ge(t),format:an.vertexFormatDecoder.getVertexFormatFromAttribute(r,s,o)})}return e}var ci=R(N(),1);function hn(i){let{indices:e,attributes:t}=i;if(!e)return i;let n=e.value.length,r={};for(let s in t){let o=t[s];if(!o)continue;let{value:a,size:c}=o;if(o.constant||!c)continue;let u=a.constructor,d=new u(n*c);for(let l=0;l<n;++l){let f=e.value[l];for(let m=0;m<c;m++)d[l*c+m]=a[f*c+m]}r[s]={size:c,value:d}}return{attributes:Object.assign({},t,r)}}function Te(i,e={}){let t=e.bufferName||"geometry";if(bs(i,t))return i;let n=e.minAttributeAlignment||4,r=ys(i,e.attributes),s=[],o=0,a=1/0;for(let[u,d]of r){if(!d)continue;if(d.constant)throw new Error(`Attribute ${u} is constant`);let{value:l,size:f,normalized:m}=d;if(!ArrayBuffer.isView(l))throw new Error(`Attribute ${u} is missing typed array data`);if(f===void 0)throw new Error(`Attribute ${u} is missing a size`);let p=ci.vertexFormatDecoder.getVertexFormatFromAttribute(l,f,m),b=ci.vertexFormatDecoder.getVertexFormatInfo(p);o=cn(o,n),s.push({sourceName:u,attributeName:ge(u),value:l,size:f,format:p,byteOffset:o,byteLength:b.byteLength}),o+=b.byteLength;let _=l.length/f;if(!Number.isInteger(_))throw new Error(`Attribute ${u} length is not divisible by size`);a=Math.min(a,_)}if(s.length===0||!Number.isFinite(a))throw new Error(`Geometry ${i.id} has no interleavable attributes`);let c=cn(o,n),h=new ArrayBuffer(a*c);for(let u of s)_s(h,a,c,u);return new z({id:i.id,topology:i.topology||"triangle-list",vertexCount:i.vertexCount,indices:i.indices,attributes:{[t]:{value:new Uint8Array(h),size:c,byteStride:c}},bufferLayout:[{name:t,stepMode:"vertex",byteStride:c,attributes:s.map(u=>({attribute:u.attributeName,format:u.format,byteOffset:u.byteOffset}))}]})}function bs(i,e){if(i.bufferLayout.length!==1)return!1;let t=i.bufferLayout[0];return t.name===e&&!!t.attributes?.length&&!!i.attributes[e]}function ys(i,e){return e?e.map(t=>[t,i.attributes[t]]):Object.entries(i.attributes)}function _s(i,e,t,n){let r=n.value.constructor,s=r.BYTES_PER_ELEMENT;if(n.byteOffset%s!==0||t%s!==0)throw new Error(`Attribute ${n.sourceName} is not aligned to its component type`);let o=new r(i),a=n.value,c=n.byteOffset/s,h=t/s;for(let u=0;u<e;u++){let d=u*n.size,l=u*h+c;for(let f=0;f<n.size;f++)o[l+f]=a[d+f]}}function cn(i,e){return Math.ceil(i/e)*e}function hi(i){let e=i.value;if(e instanceof Float32Array)return e;let t=new Float32Array(e.length),n=ln(e),r=e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array;for(let s=0;s<e.length;s++){let o=Number(e[s]);t[s]=i.normalized&&n?r?Math.max(o/n,-1):o/n:o}return t}function ui(i,e,t){let n={};for(let r of["POSITION","NORMAL","TANGENT"]){let s=i[r];if(!s)continue;let o=new Float32Array(s),a=r==="TANGENT"?4:3,c=Math.floor(s.length/a);for(let h=0;h<Math.min(e.length,t.length);h++){let u=t[h],d=e[h][r];if(!u||!d)continue;let l=r==="TANGENT"&&d.length===c*4?4:3;for(let f=0;f<c;f++){let m=f*a,p=f*l;for(let b=0;b<3;b++)o[m+b]+=(d[p+b]||0)*u}}r!=="POSITION"&&vs(o,a),n[r]=o}return n}function un(i,e,t,n){let r={};for(let d of["POSITION","NORMAL","TANGENT"]){let l=e.attributes[d];l&&(r[d]=hi(l))}let s=ui(r,t,n),o={};for(let[d,l]of Object.entries(e.attributes))l&&(o[d]=l);for(let d of["POSITION","NORMAL","TANGENT"]){let l=s[d],f=o[d];l&&f&&(o[d]={...f,value:Is(f,l)})}let a=new z({id:e.id,topology:e.topology||"triangle-list",vertexCount:e.vertexCount,indices:e.indices,attributes:o,bufferLayout:e.bufferLayout}),h=Te(a).attributes.geometry?.value,u=i._gpuGeometry?.attributes.geometry||i.bufferAttributes.geometry;if(h&&u){u.write(h);return}for(let d of["POSITION","NORMAL","TANGENT"]){let l=s[d];if(l){let f=d==="POSITION"?"positions":d==="NORMAL"?"normals":"TANGENT";i.bufferAttributes[f]?.write(l)}}}function Is(i,e){if(i.value instanceof Float32Array)return e;let t=i.value.slice(),n=ln(t),r=t instanceof Int8Array||t instanceof Int16Array||t instanceof Int32Array;for(let s=0;s<e.length;s++){let o=e[s];t[s]=i.normalized&&n?Math.round(Math.max(r?-1:0,Math.min(1,o))*n):o}return t}function ln(i){return i instanceof Int8Array?127:i instanceof Uint8Array||i instanceof Uint8ClampedArray?255:i instanceof Int16Array?32767:i instanceof Uint16Array?65535:i instanceof Int32Array?2147483647:i instanceof Uint32Array?4294967295:0}function vs(i,e){for(let t=0;t<i.length;t+=e){let n=Math.hypot(i[t],i[t+1],i[t+2]);n>0&&(i[t]/=n,i[t+1]/=n,i[t+2]/=n)}}var Oc=1/Math.PI*180,Rc=1/180*Math.PI,Ms={EPSILON:1e-12,debug:!1,precision:4,printTypes:!1,printDegrees:!1,printRowMajor:!0,_cartographicRadians:!1};globalThis.mathgl=globalThis.mathgl||{config:{...Ms}};var $=globalThis.mathgl.config;function dn(i,{precision:e=$.precision}={}){return i=Ts(i),`${parseFloat(i.toPrecision(e))}`}function we(i){return Array.isArray(i)||ArrayBuffer.isView(i)&&!(i instanceof DataView)}function li(i,e,t){let n=$.EPSILON;t&&($.EPSILON=t);try{if(i===e)return!0;if(we(i)&&we(e)){if(i.length!==e.length)return!1;for(let r=0;r<i.length;++r)if(!li(i[r],e[r]))return!1;return!0}return i&&i.equals?i.equals(e):e&&e.equals?e.equals(i):typeof i=="number"&&typeof e=="number"?Math.abs(i-e)<=$.EPSILON*Math.max(1,Math.abs(i),Math.abs(e)):!1}finally{$.EPSILON=n}}function Ts(i){return Math.round(i/$.EPSILON)*$.EPSILON}var Ae=class extends Array{clone(){return new this.constructor().copy(this)}fromArray(e,t=0){for(let n=0;n<this.ELEMENTS;++n)this[n]=e[n+t];return this.check()}toArray(e=[],t=0){for(let n=0;n<this.ELEMENTS;++n)e[t+n]=this[n];return e}toObject(e){return e}from(e){return Array.isArray(e)?this.copy(e):this.fromObject(e)}to(e){return e===this?this:we(e)?this.toArray(e):this.toObject(e)}toTarget(e){return e?this.to(e):this}toFloat32Array(){return new Float32Array(this)}toString(){return this.formatString($)}formatString(e){let t="";for(let n=0;n<this.ELEMENTS;++n)t+=(n>0?", ":"")+dn(this[n],e);return`${e.printTypes?this.constructor.name:""}[${t}]`}equals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(!li(this[t],e[t]))return!1;return!0}exactEquals(e){if(!e||this.length!==e.length)return!1;for(let t=0;t<this.ELEMENTS;++t)if(this[t]!==e[t])return!1;return!0}negate(){for(let e=0;e<this.ELEMENTS;++e)this[e]=-this[e];return this.check()}lerp(e,t,n){if(n===void 0)return this.lerp(this,e,t);for(let r=0;r<this.ELEMENTS;++r){let s=e[r],o=typeof t=="number"?t:t[r];this[r]=s+n*(o-s)}return this.check()}min(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.min(e[t],this[t]);return this.check()}max(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=Math.max(e[t],this[t]);return this.check()}clamp(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],e[n]),t[n]);return this.check()}add(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]+=t[n];return this.check()}subtract(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]-=t[n];return this.check()}scale(e){if(typeof e=="number")for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;else for(let t=0;t<this.ELEMENTS&&t<e.length;++t)this[t]*=e[t];return this.check()}multiplyByScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;return this.check()}check(){if($.debug&&!this.validate())throw new Error(`math.gl: ${this.constructor.name} some fields set to invalid numbers'`);return this}validate(){let e=this.length===this.ELEMENTS;for(let t=0;t<this.ELEMENTS;++t)e=e&&Number.isFinite(this[t]);return e}sub(e){return this.subtract(e)}setScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]=e;return this.check()}addScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]+=e;return this.check()}subScalar(e){return this.addScalar(-e)}multiplyScalar(e){for(let t=0;t<this.ELEMENTS;++t)this[t]*=e;return this.check()}divideScalar(e){return this.multiplyByScalar(1/e)}clampScalar(e,t){for(let n=0;n<this.ELEMENTS;++n)this[n]=Math.min(Math.max(this[n],e),t);return this.check()}get elements(){return this}};function ws(i,e){if(i.length!==e)return!1;for(let t=0;t<i.length;++t)if(!Number.isFinite(i[t]))return!1;return!0}function V(i){if(!Number.isFinite(i))throw new Error(`Invalid number ${JSON.stringify(i)}`);return i}function xt(i,e,t=""){if($.debug&&!ws(i,e))throw new Error(`math.gl: ${t} some fields set to invalid numbers'`);return i}function di(i,e){if(!i)throw new Error(`math.gl assertion ${e}`)}var bt=class extends Ae{get x(){return this[0]}set x(e){this[0]=V(e)}get y(){return this[1]}set y(e){this[1]=V(e)}len(){return Math.sqrt(this.lengthSquared())}magnitude(){return this.len()}lengthSquared(){let e=0;for(let t=0;t<this.ELEMENTS;++t)e+=this[t]*this[t];return e}magnitudeSquared(){return this.lengthSquared()}distance(e){return Math.sqrt(this.distanceSquared(e))}distanceSquared(e){let t=0;for(let n=0;n<this.ELEMENTS;++n){let r=this[n]-e[n];t+=r*r}return V(t)}dot(e){let t=0;for(let n=0;n<this.ELEMENTS;++n)t+=this[n]*e[n];return V(t)}normalize(){let e=this.magnitude();if(e!==0)for(let t=0;t<this.ELEMENTS;++t)this[t]/=e;return this.check()}multiply(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]*=t[n];return this.check()}divide(...e){for(let t of e)for(let n=0;n<this.ELEMENTS;++n)this[n]/=t[n];return this.check()}lengthSq(){return this.lengthSquared()}distanceTo(e){return this.distance(e)}distanceToSquared(e){return this.distanceSquared(e)}getComponent(e){return di(e>=0&&e<this.ELEMENTS,"index is out of range"),V(this[e])}setComponent(e,t){return di(e>=0&&e<this.ELEMENTS,"index is out of range"),this[e]=t,this.check()}addVectors(e,t){return this.copy(e).add(t)}subVectors(e,t){return this.copy(e).subtract(t)}multiplyVectors(e,t){return this.copy(e).multiply(t)}addScaledVector(e,t){return this.add(new this.constructor(e).multiplyScalar(t))}};var ie=typeof Float32Array<"u"?Float32Array:Array;var Vc=Math.PI/180;function As(){let i=new ie(2);return ie!=Float32Array&&(i[0]=0,i[1]=0),i}function pn(i,e,t){let n=e[0],r=e[1];return i[0]=t[0]*n+t[4]*r+t[12],i[1]=t[1]*n+t[5]*r+t[13],i}var Xc=(function(){let i=As();return function(e,t,n,r,s,o){let a,c;for(t||(t=2),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],s(i,i,o),e[a]=i[0],e[a+1]=i[1];return e}})();function gn(i,e,t){let n=e[0],r=e[1],s=t[3]*n+t[7]*r||1;return i[0]=(t[0]*n+t[4]*r)/s,i[1]=(t[1]*n+t[5]*r)/s,i}function yt(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[3]*n+t[7]*r+t[11]*s||1;return i[0]=(t[0]*n+t[4]*r+t[8]*s)/o,i[1]=(t[1]*n+t[5]*r+t[9]*s)/o,i[2]=(t[2]*n+t[6]*r+t[10]*s)/o,i}function xn(i,e,t){let n=e[0],r=e[1];return i[0]=t[0]*n+t[2]*r,i[1]=t[1]*n+t[3]*r,i[2]=e[2],i}function Ps(){let i=new ie(3);return ie!=Float32Array&&(i[0]=0,i[1]=0,i[2]=0),i}function Es(i,e){return i[0]*e[0]+i[1]*e[1]+i[2]*e[2]}function bn(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[0],a=t[1],c=t[2];return i[0]=r*c-s*a,i[1]=s*o-n*c,i[2]=n*a-r*o,i}function _t(i,e,t){let n=e[0],r=e[1],s=e[2],o=t[3]*n+t[7]*r+t[11]*s+t[15];return o=o||1,i[0]=(t[0]*n+t[4]*r+t[8]*s+t[12])/o,i[1]=(t[1]*n+t[5]*r+t[9]*s+t[13])/o,i[2]=(t[2]*n+t[6]*r+t[10]*s+t[14])/o,i}function yn(i,e,t){let n=e[0],r=e[1],s=e[2];return i[0]=n*t[0]+r*t[3]+s*t[6],i[1]=n*t[1]+r*t[4]+s*t[7],i[2]=n*t[2]+r*t[5]+s*t[8],i}function _n(i,e,t){let n=t[0],r=t[1],s=t[2],o=t[3],a=e[0],c=e[1],h=e[2],u=r*h-s*c,d=s*a-n*h,l=n*c-r*a,f=r*l-s*d,m=s*u-n*l,p=n*d-r*u,b=o*2;return u*=b,d*=b,l*=b,f*=2,m*=2,p*=2,i[0]=a+u+f,i[1]=c+d+m,i[2]=h+l+p,i}function In(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[0],s[1]=r[1]*Math.cos(n)-r[2]*Math.sin(n),s[2]=r[1]*Math.sin(n)+r[2]*Math.cos(n),i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function vn(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[2]*Math.sin(n)+r[0]*Math.cos(n),s[1]=r[1],s[2]=r[2]*Math.cos(n)-r[0]*Math.sin(n),i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function Mn(i,e,t,n){let r=[],s=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],s[0]=r[0]*Math.cos(n)-r[1]*Math.sin(n),s[1]=r[0]*Math.sin(n)+r[1]*Math.cos(n),s[2]=r[2],i[0]=s[0]+t[0],i[1]=s[1]+t[1],i[2]=s[2]+t[2],i}function Tn(i,e){let t=i[0],n=i[1],r=i[2],s=e[0],o=e[1],a=e[2],c=Math.sqrt((t*t+n*n+r*r)*(s*s+o*o+a*a)),h=c&&Es(i,e)/c;return Math.acos(Math.min(Math.max(h,-1),1))}var Yc=(function(){let i=Ps();return function(e,t,n,r,s,o){let a,c;for(t||(t=3),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],i[2]=e[a+2],s(i,i,o),e[a]=i[0],e[a+1]=i[1],e[a+2]=i[2];return e}})();var mi=[0,0,0],It,H=class i extends bt{static get ZERO(){return It||(It=new i(0,0,0),Object.freeze(It)),It}constructor(e=0,t=0,n=0){super(-0,-0,-0),arguments.length===1&&we(e)?this.copy(e):($.debug&&(V(e),V(t),V(n)),this[0]=e,this[1]=t,this[2]=n)}set(e,t,n){return this[0]=e,this[1]=t,this[2]=n,this.check()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this.check()}fromObject(e){return $.debug&&(V(e.x),V(e.y),V(e.z)),this[0]=e.x,this[1]=e.y,this[2]=e.z,this.check()}toObject(e){return e.x=this[0],e.y=this[1],e.z=this[2],e}get ELEMENTS(){return 3}get z(){return this[2]}set z(e){this[2]=V(e)}angle(e){return Tn(this,e)}cross(e){return bn(this,this,e),this.check()}rotateX({radians:e,origin:t=mi}){return In(this,this,t,e),this.check()}rotateY({radians:e,origin:t=mi}){return vn(this,this,t,e),this.check()}rotateZ({radians:e,origin:t=mi}){return Mn(this,this,t,e),this.check()}transform(e){return this.transformAsPoint(e)}transformAsPoint(e){return _t(this,this,e),this.check()}transformAsVector(e){return yt(this,this,e),this.check()}transformByMatrix3(e){return yn(this,this,e),this.check()}transformByMatrix2(e){return xn(this,this,e),this.check()}transformByQuaternion(e){return _n(this,this,e),this.check()}};var vt=class extends Ae{toString(){let e="[";if($.printRowMajor){e+="row-major:";for(let t=0;t<this.RANK;++t)for(let n=0;n<this.RANK;++n)e+=` ${this[n*this.RANK+t]}`}else{e+="column-major:";for(let t=0;t<this.ELEMENTS;++t)e+=` ${this[t]}`}return e+="]",e}getElementIndex(e,t){return t*this.RANK+e}getElement(e,t){return this[t*this.RANK+e]}setElement(e,t,n){return this[t*this.RANK+e]=V(n),this}getColumn(e,t=new Array(this.RANK).fill(-0)){let n=e*this.RANK;for(let r=0;r<this.RANK;++r)t[r]=this[n+r];return t}setColumn(e,t){let n=e*this.RANK;for(let r=0;r<this.RANK;++r)this[n+r]=t[r];return this}};function Ls(i){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function wn(i,e){if(i===e){let t=e[1],n=e[2],r=e[3],s=e[6],o=e[7],a=e[11];i[1]=e[4],i[2]=e[8],i[3]=e[12],i[4]=t,i[6]=e[9],i[7]=e[13],i[8]=n,i[9]=s,i[11]=e[14],i[12]=r,i[13]=o,i[14]=a}else i[0]=e[0],i[1]=e[4],i[2]=e[8],i[3]=e[12],i[4]=e[1],i[5]=e[5],i[6]=e[9],i[7]=e[13],i[8]=e[2],i[9]=e[6],i[10]=e[10],i[11]=e[14],i[12]=e[3],i[13]=e[7],i[14]=e[11],i[15]=e[15];return i}function An(i,e){let t=e[0],n=e[1],r=e[2],s=e[3],o=e[4],a=e[5],c=e[6],h=e[7],u=e[8],d=e[9],l=e[10],f=e[11],m=e[12],p=e[13],b=e[14],_=e[15],M=t*a-n*o,y=t*c-r*o,I=t*h-s*o,g=n*c-r*a,x=n*h-s*a,v=r*h-s*c,w=u*p-d*m,T=u*b-l*m,C=u*_-f*m,S=d*b-l*p,A=d*_-f*p,L=l*_-f*b,E=M*L-y*A+I*S+g*C-x*T+v*w;return E?(E=1/E,i[0]=(a*L-c*A+h*S)*E,i[1]=(r*A-n*L-s*S)*E,i[2]=(p*v-b*x+_*g)*E,i[3]=(l*x-d*v-f*g)*E,i[4]=(c*C-o*L-h*T)*E,i[5]=(t*L-r*C+s*T)*E,i[6]=(b*I-m*v-_*y)*E,i[7]=(u*v-l*I+f*y)*E,i[8]=(o*A-a*C+h*w)*E,i[9]=(n*C-t*A-s*w)*E,i[10]=(m*x-p*I+_*M)*E,i[11]=(d*I-u*x-f*M)*E,i[12]=(a*T-o*S-c*w)*E,i[13]=(t*S-n*T+r*w)*E,i[14]=(p*y-m*g-b*M)*E,i[15]=(u*g-d*y+l*M)*E,i):null}function Sn(i){let e=i[0],t=i[1],n=i[2],r=i[3],s=i[4],o=i[5],a=i[6],c=i[7],h=i[8],u=i[9],d=i[10],l=i[11],f=i[12],m=i[13],p=i[14],b=i[15],_=e*o-t*s,M=e*a-n*s,y=t*a-n*o,I=h*m-u*f,g=h*p-d*f,x=u*p-d*m,v=e*x-t*g+n*I,w=s*x-o*g+a*I,T=h*y-u*M+d*_,C=f*y-m*M+p*_;return c*v-r*w+b*T-l*C}function pi(i,e,t){let n=e[0],r=e[1],s=e[2],o=e[3],a=e[4],c=e[5],h=e[6],u=e[7],d=e[8],l=e[9],f=e[10],m=e[11],p=e[12],b=e[13],_=e[14],M=e[15],y=t[0],I=t[1],g=t[2],x=t[3];return i[0]=y*n+I*a+g*d+x*p,i[1]=y*r+I*c+g*l+x*b,i[2]=y*s+I*h+g*f+x*_,i[3]=y*o+I*u+g*m+x*M,y=t[4],I=t[5],g=t[6],x=t[7],i[4]=y*n+I*a+g*d+x*p,i[5]=y*r+I*c+g*l+x*b,i[6]=y*s+I*h+g*f+x*_,i[7]=y*o+I*u+g*m+x*M,y=t[8],I=t[9],g=t[10],x=t[11],i[8]=y*n+I*a+g*d+x*p,i[9]=y*r+I*c+g*l+x*b,i[10]=y*s+I*h+g*f+x*_,i[11]=y*o+I*u+g*m+x*M,y=t[12],I=t[13],g=t[14],x=t[15],i[12]=y*n+I*a+g*d+x*p,i[13]=y*r+I*c+g*l+x*b,i[14]=y*s+I*h+g*f+x*_,i[15]=y*o+I*u+g*m+x*M,i}function Pn(i,e,t){let n=t[0],r=t[1],s=t[2],o,a,c,h,u,d,l,f,m,p,b,_;return e===i?(i[12]=e[0]*n+e[4]*r+e[8]*s+e[12],i[13]=e[1]*n+e[5]*r+e[9]*s+e[13],i[14]=e[2]*n+e[6]*r+e[10]*s+e[14],i[15]=e[3]*n+e[7]*r+e[11]*s+e[15]):(o=e[0],a=e[1],c=e[2],h=e[3],u=e[4],d=e[5],l=e[6],f=e[7],m=e[8],p=e[9],b=e[10],_=e[11],i[0]=o,i[1]=a,i[2]=c,i[3]=h,i[4]=u,i[5]=d,i[6]=l,i[7]=f,i[8]=m,i[9]=p,i[10]=b,i[11]=_,i[12]=o*n+u*r+m*s+e[12],i[13]=a*n+d*r+p*s+e[13],i[14]=c*n+l*r+b*s+e[14],i[15]=h*n+f*r+_*s+e[15]),i}function En(i,e,t){let n=t[0],r=t[1],s=t[2];return i[0]=e[0]*n,i[1]=e[1]*n,i[2]=e[2]*n,i[3]=e[3]*n,i[4]=e[4]*r,i[5]=e[5]*r,i[6]=e[6]*r,i[7]=e[7]*r,i[8]=e[8]*s,i[9]=e[9]*s,i[10]=e[10]*s,i[11]=e[11]*s,i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15],i}function Cn(i,e,t,n){let r=n[0],s=n[1],o=n[2],a=Math.sqrt(r*r+s*s+o*o),c,h,u,d,l,f,m,p,b,_,M,y,I,g,x,v,w,T,C,S,A,L,E,U;return a<1e-6?null:(a=1/a,r*=a,s*=a,o*=a,h=Math.sin(t),c=Math.cos(t),u=1-c,d=e[0],l=e[1],f=e[2],m=e[3],p=e[4],b=e[5],_=e[6],M=e[7],y=e[8],I=e[9],g=e[10],x=e[11],v=r*r*u+c,w=s*r*u+o*h,T=o*r*u-s*h,C=r*s*u-o*h,S=s*s*u+c,A=o*s*u+r*h,L=r*o*u+s*h,E=s*o*u-r*h,U=o*o*u+c,i[0]=d*v+p*w+y*T,i[1]=l*v+b*w+I*T,i[2]=f*v+_*w+g*T,i[3]=m*v+M*w+x*T,i[4]=d*C+p*S+y*A,i[5]=l*C+b*S+I*A,i[6]=f*C+_*S+g*A,i[7]=m*C+M*S+x*A,i[8]=d*L+p*E+y*U,i[9]=l*L+b*E+I*U,i[10]=f*L+_*E+g*U,i[11]=m*L+M*E+x*U,e!==i&&(i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i)}function Ln(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[4],o=e[5],a=e[6],c=e[7],h=e[8],u=e[9],d=e[10],l=e[11];return e!==i&&(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[4]=s*r+h*n,i[5]=o*r+u*n,i[6]=a*r+d*n,i[7]=c*r+l*n,i[8]=h*r-s*n,i[9]=u*r-o*n,i[10]=d*r-a*n,i[11]=l*r-c*n,i}function On(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],h=e[8],u=e[9],d=e[10],l=e[11];return e!==i&&(i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[0]=s*r-h*n,i[1]=o*r-u*n,i[2]=a*r-d*n,i[3]=c*r-l*n,i[8]=s*n+h*r,i[9]=o*n+u*r,i[10]=a*n+d*r,i[11]=c*n+l*r,i}function Rn(i,e,t){let n=Math.sin(t),r=Math.cos(t),s=e[0],o=e[1],a=e[2],c=e[3],h=e[4],u=e[5],d=e[6],l=e[7];return e!==i&&(i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15]),i[0]=s*r+h*n,i[1]=o*r+u*n,i[2]=a*r+d*n,i[3]=c*r+l*n,i[4]=h*r-s*n,i[5]=u*r-o*n,i[6]=d*r-a*n,i[7]=l*r-c*n,i}function kn(i,e){let t=e[0],n=e[1],r=e[2],s=e[3],o=t+t,a=n+n,c=r+r,h=t*o,u=n*o,d=n*a,l=r*o,f=r*a,m=r*c,p=s*o,b=s*a,_=s*c;return i[0]=1-d-m,i[1]=u+_,i[2]=l-b,i[3]=0,i[4]=u-_,i[5]=1-h-m,i[6]=f+p,i[7]=0,i[8]=l+b,i[9]=f-p,i[10]=1-h-d,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function Nn(i,e,t,n,r,s,o){let a=1/(t-e),c=1/(r-n),h=1/(s-o);return i[0]=s*2*a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s*2*c,i[6]=0,i[7]=0,i[8]=(t+e)*a,i[9]=(r+n)*c,i[10]=(o+s)*h,i[11]=-1,i[12]=0,i[13]=0,i[14]=o*s*2*h,i[15]=0,i}function Os(i,e,t,n,r){let s=1/Math.tan(e/2);if(i[0]=s/t,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=s,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=-1,i[12]=0,i[13]=0,i[15]=0,r!=null&&r!==1/0){let o=1/(n-r);i[10]=(r+n)*o,i[14]=2*r*n*o}else i[10]=-1,i[14]=-2*n;return i}var Dn=Os;function Rs(i,e,t,n,r,s,o){let a=1/(e-t),c=1/(n-r),h=1/(s-o);return i[0]=-2*a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=-2*c,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=2*h,i[11]=0,i[12]=(e+t)*a,i[13]=(r+n)*c,i[14]=(o+s)*h,i[15]=1,i}var Bn=Rs;function Fn(i,e,t,n){let r,s,o,a,c,h,u,d,l,f,m=e[0],p=e[1],b=e[2],_=n[0],M=n[1],y=n[2],I=t[0],g=t[1],x=t[2];return Math.abs(m-I)<1e-6&&Math.abs(p-g)<1e-6&&Math.abs(b-x)<1e-6?Ls(i):(d=m-I,l=p-g,f=b-x,r=1/Math.sqrt(d*d+l*l+f*f),d*=r,l*=r,f*=r,s=M*f-y*l,o=y*d-_*f,a=_*l-M*d,r=Math.sqrt(s*s+o*o+a*a),r?(r=1/r,s*=r,o*=r,a*=r):(s=0,o=0,a=0),c=l*a-f*o,h=f*s-d*a,u=d*o-l*s,r=Math.sqrt(c*c+h*h+u*u),r?(r=1/r,c*=r,h*=r,u*=r):(c=0,h=0,u=0),i[0]=s,i[1]=c,i[2]=d,i[3]=0,i[4]=o,i[5]=h,i[6]=l,i[7]=0,i[8]=a,i[9]=u,i[10]=f,i[11]=0,i[12]=-(s*m+o*p+a*b),i[13]=-(c*m+h*p+u*b),i[14]=-(d*m+l*p+f*b),i[15]=1,i)}function Ns(){let i=new ie(4);return ie!=Float32Array&&(i[0]=0,i[1]=0,i[2]=0,i[3]=0),i}function zn(i,e,t){let n=e[0],r=e[1],s=e[2],o=e[3];return i[0]=t[0]*n+t[4]*r+t[8]*s+t[12]*o,i[1]=t[1]*n+t[5]*r+t[9]*s+t[13]*o,i[2]=t[2]*n+t[6]*r+t[10]*s+t[14]*o,i[3]=t[3]*n+t[7]*r+t[11]*s+t[15]*o,i}var rh=(function(){let i=Ns();return function(e,t,n,r,s,o){let a,c;for(t||(t=4),n||(n=0),r?c=Math.min(r*t+n,e.length):c=e.length,a=n;a<c;a+=t)i[0]=e[a],i[1]=e[a+1],i[2]=e[a+2],i[3]=e[a+3],s(i,i,o),e[a]=i[0],e[a+1]=i[1],e[a+2]=i[2],e[a+3]=i[3];return e}})();var bi;(function(i){i[i.COL0ROW0=0]="COL0ROW0",i[i.COL0ROW1=1]="COL0ROW1",i[i.COL0ROW2=2]="COL0ROW2",i[i.COL0ROW3=3]="COL0ROW3",i[i.COL1ROW0=4]="COL1ROW0",i[i.COL1ROW1=5]="COL1ROW1",i[i.COL1ROW2=6]="COL1ROW2",i[i.COL1ROW3=7]="COL1ROW3",i[i.COL2ROW0=8]="COL2ROW0",i[i.COL2ROW1=9]="COL2ROW1",i[i.COL2ROW2=10]="COL2ROW2",i[i.COL2ROW3=11]="COL2ROW3",i[i.COL3ROW0=12]="COL3ROW0",i[i.COL3ROW1=13]="COL3ROW1",i[i.COL3ROW2=14]="COL3ROW2",i[i.COL3ROW3=15]="COL3ROW3"})(bi||(bi={}));var Bs=45*Math.PI/180,Fs=1,gi=.1,xi=500,zs=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),k=class extends vt{static get IDENTITY(){return Gs()}static get ZERO(){return js()}get ELEMENTS(){return 16}get RANK(){return 4}get INDICES(){return bi}constructor(e){super(-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0),arguments.length===1&&Array.isArray(e)?this.copy(e):this.identity()}copy(e){return this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3],this[4]=e[4],this[5]=e[5],this[6]=e[6],this[7]=e[7],this[8]=e[8],this[9]=e[9],this[10]=e[10],this[11]=e[11],this[12]=e[12],this[13]=e[13],this[14]=e[14],this[15]=e[15],this.check()}set(e,t,n,r,s,o,a,c,h,u,d,l,f,m,p,b){return this[0]=e,this[1]=t,this[2]=n,this[3]=r,this[4]=s,this[5]=o,this[6]=a,this[7]=c,this[8]=h,this[9]=u,this[10]=d,this[11]=l,this[12]=f,this[13]=m,this[14]=p,this[15]=b,this.check()}setRowMajor(e,t,n,r,s,o,a,c,h,u,d,l,f,m,p,b){return this[0]=e,this[1]=s,this[2]=h,this[3]=f,this[4]=t,this[5]=o,this[6]=u,this[7]=m,this[8]=n,this[9]=a,this[10]=d,this[11]=p,this[12]=r,this[13]=c,this[14]=l,this[15]=b,this.check()}toRowMajor(e){return e[0]=this[0],e[1]=this[4],e[2]=this[8],e[3]=this[12],e[4]=this[1],e[5]=this[5],e[6]=this[9],e[7]=this[13],e[8]=this[2],e[9]=this[6],e[10]=this[10],e[11]=this[14],e[12]=this[3],e[13]=this[7],e[14]=this[11],e[15]=this[15],e}identity(){return this.copy(zs)}fromObject(e){return this.check()}fromQuaternion(e){return kn(this,e),this.check()}frustum(e){let{left:t,right:n,bottom:r,top:s,near:o=gi,far:a=xi}=e;return a===1/0?Us(this,t,n,r,s,o):Nn(this,t,n,r,s,o,a),this.check()}lookAt(e){let{eye:t,center:n=[0,0,0],up:r=[0,1,0]}=e;return Fn(this,t,n,r),this.check()}ortho(e){let{left:t,right:n,bottom:r,top:s,near:o=gi,far:a=xi}=e;return Bn(this,t,n,r,s,o,a),this.check()}orthographic(e){let{fovy:t=Bs,aspect:n=Fs,focalDistance:r=1,near:s=gi,far:o=xi}=e;jn(t);let a=t/2,c=r*Math.tan(a),h=c*n;return this.ortho({left:-h,right:h,bottom:-c,top:c,near:s,far:o})}perspective(e){let{fovy:t=45*Math.PI/180,aspect:n=1,near:r=.1,far:s=500}=e;return jn(t),Dn(this,t,n,r,s),this.check()}determinant(){return Sn(this)}getScale(e=[-0,-0,-0]){return e[0]=Math.sqrt(this[0]*this[0]+this[1]*this[1]+this[2]*this[2]),e[1]=Math.sqrt(this[4]*this[4]+this[5]*this[5]+this[6]*this[6]),e[2]=Math.sqrt(this[8]*this[8]+this[9]*this[9]+this[10]*this[10]),e}getTranslation(e=[-0,-0,-0]){return e[0]=this[12],e[1]=this[13],e[2]=this[14],e}getRotation(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),r=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*r,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=0,e[4]=this[4]*r,e[5]=this[5]*s,e[6]=this[6]*o,e[7]=0,e[8]=this[8]*r,e[9]=this[9]*s,e[10]=this[10]*o,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}getRotationMatrix3(e,t){e=e||[-0,-0,-0,-0,-0,-0,-0,-0,-0],t=t||[-0,-0,-0];let n=this.getScale(t),r=1/n[0],s=1/n[1],o=1/n[2];return e[0]=this[0]*r,e[1]=this[1]*s,e[2]=this[2]*o,e[3]=this[4]*r,e[4]=this[5]*s,e[5]=this[6]*o,e[6]=this[8]*r,e[7]=this[9]*s,e[8]=this[10]*o,e}transpose(){return wn(this,this),this.check()}invert(){return An(this,this),this.check()}multiplyLeft(e){return pi(this,e,this),this.check()}multiplyRight(e){return pi(this,this,e),this.check()}rotateX(e){return Ln(this,this,e),this.check()}rotateY(e){return On(this,this,e),this.check()}rotateZ(e){return Rn(this,this,e),this.check()}rotateXYZ(e){return this.rotateX(e[0]).rotateY(e[1]).rotateZ(e[2])}rotateAxis(e,t){return Cn(this,this,e,t),this.check()}scale(e){return En(this,this,Array.isArray(e)?e:[e,e,e]),this.check()}translate(e){return Pn(this,this,e),this.check()}transform(e,t){return e.length===4?(t=zn(t||[-0,-0,-0,-0],e,this),xt(t,4),t):this.transformAsPoint(e,t)}transformAsPoint(e,t){let{length:n}=e,r;switch(n){case 2:r=pn(t||[-0,-0],e,this);break;case 3:r=_t(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return xt(r,e.length),r}transformAsVector(e,t){let n;switch(e.length){case 2:n=gn(t||[-0,-0],e,this);break;case 3:n=yt(t||[-0,-0,-0],e,this);break;default:throw new Error("Illegal vector")}return xt(n,e.length),n}transformPoint(e,t){return this.transformAsPoint(e,t)}transformVector(e,t){return this.transformAsPoint(e,t)}transformDirection(e,t){return this.transformAsVector(e,t)}makeRotationX(e){return this.identity().rotateX(e)}makeTranslation(e,t,n){return this.identity().translate([e,t,n])}},Mt,Tt;function js(){return Mt||(Mt=new k([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Object.freeze(Mt)),Mt}function Gs(){return Tt||(Tt=new k,Object.freeze(Tt)),Tt}function jn(i){if(i>Math.PI*2)throw Error("expected radians")}function Us(i,e,t,n,r,s){let o=2*s/(t-e),a=2*s/(r-n),c=(t+e)/(t-e),h=(r+n)/(r-n),u=-1,d=-1,l=-2*s;return i[0]=o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=a,i[6]=0,i[7]=0,i[8]=c,i[9]=h,i[10]=u,i[11]=d,i[12]=0,i[13]=0,i[14]=l,i[15]=0,i}function Gn(i){let{joints:e,meshNode:t,worldMatrices:n,inverseBindMatrices:r,target:s}=i,o=e.length,a=s&&s.length===o*16?s:new Float32Array(o*16),c=t?n.get(t)||t.matrix:void 0,h=c?new k(c).invert():null;for(let u=0;u<o;u++){let d=e[u],l=n.get(d)||d.matrix,f=h?new k(h).multiplyRight(l):new k(l),m=u*16;if(r&&r.length>=m+16){let p=new k;for(let b=0;b<16;b++)p[b]=r[m+b];f.multiplyRight(p)}a.set(f,m)}return a}var $s=1,Vs=1,wt=class{time=0;channels=new Map;animations=new Map;playing=!1;lastEngineTime=-1;constructor(){}addChannel(e){let{delay:t=0,duration:n=Number.POSITIVE_INFINITY,rate:r=1,repeat:s=1}=e,o=$s++,a={time:0,delay:t,duration:n,rate:r,repeat:s};return this._setChannelTime(a,this.time),this.channels.set(o,a),o}removeChannel(e){this.channels.delete(e);for(let[t,n]of this.animations)n.channel===e&&this.detachAnimation(t)}isFinished(e){let t=this.channels.get(e);return t===void 0?!1:this.time>=t.delay+t.duration*t.repeat}getTime(e){if(e===void 0)return this.time;let t=this.channels.get(e);return t===void 0?-1:t.time}setTime(e){this.time=Math.max(0,e);let t=this.channels.values();for(let r of t)this._setChannelTime(r,this.time);let n=this.animations.values();for(let r of n){let{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,t){let n=Vs++;return this.animations.set(n,{animation:e,channel:t}),e.setTime(this.getTime(t)),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,t){let n=t-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)}};var At=class{startIndex=-1;endIndex=-1;factor=0;times=[];values=[];_lastTime=-1;constructor(e){this.setKeyFrames(e),this.setTime(0)}setKeyFrames(e){let t=e.length;this.times.length=t,this.values.length=t;for(let n=0;n<t;++n)this.times[n]=e[n][0],this.values[n]=e[n][1];this._calculateKeys(this._lastTime)}setTime(e){e=Math.max(0,e),e!==this._lastTime&&(this._calculateKeys(e),this._lastTime=e)}getStartTime(){return this.times[this.startIndex]}getEndTime(){return this.times[this.endIndex]}getStartData(){return this.values[this.startIndex]}getEndData(){return this.values[this.endIndex]}_calculateKeys(e){let t=0,n=this.times.length;for(t=0;t<n-2&&!(this.times[t+1]>e);++t);this.startIndex=t,this.endIndex=t+1;let r=this.times[this.startIndex],s=this.times[this.endIndex];this.factor=Math.min(Math.max(0,(e-r)/(s-r)),1)}};var St=class{constructor(e){}async onInitialize(e){return null}};var $n=R(N(),1);function Pt(i){let e=typeof window<"u"?window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame:null;return e?e.call(window,i):setTimeout(()=>i(typeof performance<"u"?performance.now():Date.now()),1e3/60)}function Et(i){let e=typeof window<"u"?window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame:null;if(e){e.call(window,i);return}clearTimeout(i)}function Xe(){let i;if(typeof window<"u"&&window.performance)i=window.performance.now();else if(typeof process<"u"&&process.hrtime){let e=process.hrtime();i=e[0]*1e3+e[1]/1e6}else i=Date.now();return i}var xe=class{constructor(e,t){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=t,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=Xe(),this._timerPending=!0,this}timeEnd(){return this._timerPending?(this.addTime(Xe()-this._startTime),this._timerPending=!1,this._checkSampling(),this):this}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1e3):0}getAverageCount(){return this.samples>0?this.count/this.samples:0}getAverageTime(){return this.samples>0?this.time/this.samples:0}getHz(){return this.time>0?this.samples/(this.time/1e3):0}_checkSampling(){this._samples===this.sampleSize&&(this.lastSampleTime=this._time,this.lastSampleCount=this._count,this.count+=this._count,this.time+=this._time,this.samples+=this._samples,this._time=0,this._count=0,this._samples=0)}};var Pe=class{constructor(e){this.stats={},this.id=e.id,this.stats={},this._initializeStats(e.stats),Object.seal(this)}get(e,t="count"){return this._getOrCreate({name:e,type:t})}get size(){return Object.keys(this.stats).length}reset(){for(let e of Object.values(this.stats))e.reset();return this}forEach(e){for(let t of Object.values(this.stats))e(t)}getTable(){let e={};return this.forEach(t=>{e[t.name]={time:t.time||0,count:t.count||0,average:t.getAverageTime()||0,hz:t.getHz()||0}}),e}_initializeStats(e=[]){e.forEach(t=>this._getOrCreate(t))}_getOrCreate(e){let{name:t,type:n}=e,r=this.stats[t];return r||(e instanceof xe?r=e:r=new xe(t,n),this.stats[t]=r),r}};var Xs=0,Hs="Animation Loop",Un={requestAnimationFrame:i=>Pt(i),cancelAnimationFrame:i=>Et(i)},Ee=class i{static defaultAnimationLoopProps={device:null,onAddHTML:()=>"",onInitialize:async()=>null,onRender:()=>{},onFinalize:()=>{},onError:e=>{console.error(e)},stats:void 0,autoResizeViewport:!1,animationFrameProvider:Un};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={...i.defaultAnimationLoopProps,...e},e=this.props,!e.device)throw new Error("No device provided");this.stats=e.stats||new Pe({id:`animation-loop-${Xs++}`}),this.sharedStats=$n.luma.stats.get(Hs),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,animationFrameProvider:e.animationFrameProvider}),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(){let e=this._needsRedraw;return this._needsRedraw=!1,e}setProps(e){if("autoResizeViewport"in e&&(this.props.autoResizeViewport=e.autoResizeViewport||!1),"animationFrameProvider"in e){let t=e.animationFrameProvider||Un;if(t!==this.props.animationFrameProvider){let n=this._animationFrameId!==null;n&&this._cancelAnimationFrame(),this.props.animationFrameProvider=t,n&&this._requestAnimationFrame()}}return 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){let t=e instanceof Error?e:new Error("Unknown error");throw this.props.onError(t),t}}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,t=null){return this.device?.isLost||this._error?this:(this._beginFrameTimers(e),this._setupFrame(),this.animationProps&&(this.animationProps.animationFrame=t),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=this.props.animationFrameProvider.requestAnimationFrame(this._animationFrame.bind(this)))}_cancelAnimationFrame(){this._animationFrameId!==null&&(this.props.animationFrameProvider.cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}_animationFrame(e,t){this._running&&(this.redraw(e,t??null),this._requestAnimationFrame())}_renderFrame(e){if(this.display){this.display._renderFrame(e);return}let t=this.props.onRender(this._getAnimationProps());this.device&&t!==!1&&this.device.submit()}_clearNeedsRedraw(){this._needsRedraw=!1}_setupFrame(){this._resizeViewport()}_initializeAnimationProps(){let e=this.device?.getDefaultCanvasContext();if(!this.device||!e)throw new Error("loop");let t=e?.canvas,n=e.props.useDevicePixels;this.animationProps={animationLoop:this,device:this.device,canvasContext:e,canvas:t,useDevicePixels:n,timeline:this.timeline,needsRedraw:!1,width:1,height:1,aspect:1,time:0,startTime:Date.now(),engineTime:0,tick:0,tock:0,animationFrame:null,_mousePosition:null}}_getAnimationProps(){if(!this.animationProps)throw new Error("animationProps");return this.animationProps}_updateAnimationProps(){if(!this.animationProps)return;let{width:e,height:t,aspect:n}=this._getSizeAndAspect();(e!==this.animationProps.width||t!==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=t,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){let e=document.createElement("div");document.body.appendChild(e),e.style.position="relative";let t=document.createElement("div");t.style.position="absolute",t.style.left="10px",t.style.bottom="10px",t.style.width="300px",t.style.background="white",this.canvas instanceof HTMLCanvasElement&&e.appendChild(this.canvas),e.appendChild(t);let n=this.props.onAddHTML(t);n&&(t.innerHTML=n)}}_getSizeAndAspect(){if(!this.device)return{width:1,height:1,aspect:1};let[e,t]=this.device.getDefaultCanvasContext().getDrawingBufferSize(),n=e>0&&t>0?e/t:1;return{width:e,height:t,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){let t=e??(typeof performance<"u"?performance.now():Date.now());if(this._lastFrameTime){let n=t-this._lastFrameTime;n>0&&this.frameRate.addTime(n)}this._lastFrameTime=t,this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeStart()}_endFrameTimers(){this.device?._isDebugGPUTimeEnabled()&&this._consumeEncodedGpuTime(),this.cpuTime.timeEnd(),this._updateSharedStats()}_consumeEncodedGpuTime(){if(!this.device)return;let 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(let e of Object.keys(this.sharedStats.stats))this.stats.stats[e]||delete this.sharedStats.stats[e];this.stats.forEach(e=>{let t=this.sharedStats.get(e.name,e.type);t.sampleSize=e.sampleSize,t.time=e.time,t.count=e.count,t.samples=e.samples,t.lastTiming=e.lastTiming,t.lastSampleTime=e.lastSampleTime,t.lastSampleCount=e.lastSampleCount,t._count=e._count,t._time=e._time,t._samples=e._samples,t._startTime=e._startTime,t._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}};var Vn=R(N(),1);function Xn(i,e){let t=null,n=e?.device||Vn.luma.createDevice({id:"animation-loop",adapters:e?.adapters,createCanvasContext:!0}),r=new Ee({...e,device:n,async onInitialize(o){Ws(o.animationLoop.device);try{return t=new i(o),await t?.onInitialize(o)}catch(a){return console.error(a),t=null,Ys(o.animationLoop.device,a),o.animationLoop.stop(),null}},onRender(o){let a=t?.onRender(o),c=e?.onAfterRender?.(o,t);return e?.onAfterRender?a!==!1||c!==!1:a},onFinalize(o){try{t?.onFinalize(o)}finally{t=null}}}),s=r;return s.getAnimationLoopTemplate=()=>t,r.getInfo=()=>this.AnimationLoopTemplateCtor.info,s}function Ys(i,e){if(!i)return;let t=i.getDefaultCanvasContext().canvas;if(t instanceof HTMLCanvasElement){t.style.overflow="visible";let n=document.getElementById("animation-loop-error");n?.remove(),n=document.createElement("h1"),n.id="animation-loop-error",n.innerHTML=e.message,n.style.position="absolute",n.style.top="10px",n.style.left="10px",n.style.color="black",n.style.backgroundColor="red",t.parentElement?.appendChild(n)}}function Ws(i){if(!i)return;let e=document.getElementById("animation-loop-error");e&&e.remove()}var qs={target:[0,0,0],distance:10,yaw:0,pitch:.25,minDistance:1,maxDistance:100,minPitch:-Math.PI/2+.01,maxPitch:Math.PI/2-.01,rotateSpeed:.006,zoomSpeed:.001,enabled:!0,enableZoom:!0,enablePan:!1,panSpeed:.0018,autoRotate:!1,autoRotateSpeed:.1},Ct=class{canvas;props;yaw;pitch;distance;dragging=!1;activePointers=new Map;lastPointer=[0,0];previousPinchDistance=null;previousTimeMilliseconds=null;previousCursor;previousTouchAction;constructor(e,t={}){this.canvas=e,this.props={...qs,...t},this.props.target=[...this.props.target],this.yaw=this.props.yaw,this.pitch=Q(this.props.pitch,this.props.minPitch,this.props.maxPitch),this.distance=Q(this.props.distance,this.props.minDistance,this.props.maxDistance),this.previousCursor=e.style.cursor,this.previousTouchAction=e.style.touchAction,e.style.cursor="grab",e.style.touchAction="none",e.addEventListener("pointerdown",this.handlePointerDown),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("pointerup",this.handlePointerUp),e.addEventListener("pointercancel",this.handlePointerUp),e.addEventListener("wheel",this.handleWheel,{passive:!1})}update(e){if(this.previousTimeMilliseconds!==null&&this.props.enabled&&this.props.autoRotate&&!this.dragging){let t=Math.min(Math.max(e-this.previousTimeMilliseconds,0)/1e3,.1);this.yaw+=this.props.autoRotateSpeed*t}this.previousTimeMilliseconds=e}getEyePosition(){let e=this.distance*Math.cos(this.pitch);return[this.props.target[0]+e*Math.sin(this.yaw),this.props.target[1]+this.distance*Math.sin(this.pitch),this.props.target[2]+e*Math.cos(this.yaw)]}setAutoRotate(e){this.props.autoRotate=e}setProps(e){Object.assign(this.props,e),e.enabled===!1&&this.dragging&&this.endPointerInteraction(),e.target&&(this.props.target=[...e.target]),e.yaw!==void 0&&(this.yaw=e.yaw),(e.pitch!==void 0||e.minPitch!==void 0||e.maxPitch!==void 0)&&(this.pitch=Q(e.pitch??this.pitch,this.props.minPitch,this.props.maxPitch)),(e.distance!==void 0||e.minDistance!==void 0||e.maxDistance!==void 0)&&(this.distance=Q(e.distance??this.distance,this.props.minDistance,this.props.maxDistance))}reset(){this.yaw=this.props.yaw,this.pitch=Q(this.props.pitch,this.props.minPitch,this.props.maxPitch),this.distance=Q(this.props.distance,this.props.minDistance,this.props.maxDistance)}destroy(){this.canvas.removeEventListener("pointerdown",this.handlePointerDown),this.canvas.removeEventListener("pointermove",this.handlePointerMove),this.canvas.removeEventListener("pointerup",this.handlePointerUp),this.canvas.removeEventListener("pointercancel",this.handlePointerUp),this.canvas.removeEventListener("wheel",this.handleWheel),this.endPointerInteraction(),this.canvas.style.cursor=this.previousCursor,this.canvas.style.touchAction=this.previousTouchAction}handlePointerDown=e=>{if(!(!this.props.enabled||e.button!==0||this.activePointers.has(e.pointerId)||this.activePointers.size>=2||this.activePointers.size>0&&e.pointerType!=="touch")){if(this.activePointers.size===0&&this.props.onInteractionStart?.(),this.dragging=!0,this.activePointers.set(e.pointerId,[e.clientX,e.clientY]),this.activePointers.size===1)this.lastPointer=[e.clientX,e.clientY];else{let{center:t,distance:n}=this.getMultiPointerState();this.lastPointer=t,this.previousPinchDistance=n}this.canvas.setPointerCapture(e.pointerId),this.canvas.style.cursor="grabbing"}};handlePointerMove=e=>{if(!this.props.enabled||!this.dragging||!this.activePointers.has(e.pointerId))return;if(this.activePointers.set(e.pointerId,[e.clientX,e.clientY]),this.activePointers.size>1){let{center:r,distance:s}=this.getMultiPointerState();this.props.enablePan&&this.panTarget(r[0]-this.lastPointer[0],r[1]-this.lastPointer[1]),this.props.enableZoom&&this.previousPinchDistance&&s>0&&(this.distance=Q(this.distance*this.previousPinchDistance/s,this.props.minDistance,this.props.maxDistance)),this.lastPointer=r,this.previousPinchDistance=s;return}let t=e.clientX-this.lastPointer[0],n=e.clientY-this.lastPointer[1];this.lastPointer=[e.clientX,e.clientY],this.props.enablePan&&e.shiftKey?this.panTarget(t,n):(this.yaw-=t*this.props.rotateSpeed,this.pitch=Q(this.pitch-n*(this.props.pitchSpeed??this.props.rotateSpeed),this.props.minPitch,this.props.maxPitch))};handlePointerUp=e=>{if(!this.activePointers.has(e.pointerId))return;this.canvas.hasPointerCapture(e.pointerId)&&this.canvas.releasePointerCapture(e.pointerId),this.activePointers.delete(e.pointerId),this.previousPinchDistance=null;let t=this.activePointers.entries().next().value;if(t){this.lastPointer=t[1];return}this.endPointerInteraction()};endPointerInteraction(){this.dragging=!1;for(let e of this.activePointers.keys())this.canvas.hasPointerCapture(e)&&this.canvas.releasePointerCapture(e);this.activePointers.clear(),this.previousPinchDistance=null,this.canvas.style.cursor="grab"}getMultiPointerState(){let[e,t]=this.activePointers.values(),n=t[0]-e[0],r=t[1]-e[1];return{center:[(e[0]+t[0])/2,(e[1]+t[1])/2],distance:Math.hypot(n,r)}}panTarget(e,t){let n=this.distance*this.props.panSpeed;this.props.target=[this.props.target[0]-Math.cos(this.yaw)*e*n,this.props.target[1]+t*n,this.props.target[2]+Math.sin(this.yaw)*e*n]}handleWheel=e=>{if(!this.props.enabled||!this.props.enableZoom)return;e.preventDefault(),this.props.onInteractionStart?.();let t=Q(e.deltaY,-240,240);this.distance=Q(this.distance*Math.exp(t*this.props.zoomSpeed),this.props.minDistance,this.props.maxDistance)}};function Q(i,e,t){return Math.min(Math.max(i,e),t)}var P=R(N(),1),_e=R(ne(),1);var yi=R(N(),1);var Ce=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||O("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&yi.Buffer.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(let 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 Yn(i,e){if(e instanceof Ce)return e;let t=Te(e),n=Ks(i,t),{attributes:r,bufferLayout:s}=Zs(i,t);return new Ce({topology:t.topology||"triangle-list",bufferLayout:s,vertexCount:t.vertexCount,indices:n,attributes:r})}function Ks(i,e){if(!e.indices)return;let t=e.indices.value;return i.createBuffer({usage:yi.Buffer.INDEX,data:t})}function Zs(i,e){let t={};for(let[n,r]of Object.entries(e.attributes)){let s=e.bufferLayout.find(o=>o.name===n)?.name||ge(n);r&&(t[s]=i.createBuffer({data:r.value,id:`${n}-buffer`}))}return{attributes:t,bufferLayout:e.bufferLayout,vertexCount:e.vertexCount}}function Wn(i,e){let t={},n="Values";if(i.attributes.length===0&&!i.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(let r of i.attributes)if(r){let s=`${r.location} ${r.name}: ${r.type}`;t[`in ${s}`]={[n]:r.stepMode||"vertex"}}for(let r of i.varyings||[]){let s=`${r.location} ${r.name}`;t[`out ${s}`]={[n]:JSON.stringify(r)}}return t}var qn="__debugFramebufferState";function Zn(i,e,t){if(i.device.type!=="webgl")return;let n=eo(i.device);if(!n.flushing){if(io(i)){Qs(i,t,n);return}e&&to(e)&&e.handle!==null&&(n.queuedFramebuffers.includes(e)||n.queuedFramebuffers.push(e))}}function Qs(i,e,t){if(t.queuedFramebuffers.length===0)return;let n=i.device,{gl:r}=n,s=r.getParameter(36010),o=r.getParameter(36006),[a,c]=i.device.getDefaultCanvasContext().getDrawingBufferSize(),h=Kn(e.top,8),u=Kn(e.left,8);t.flushing=!0;try{for(let d of t.queuedFramebuffers){let[l,f,m,p,b]=Js({framebuffer:d,targetWidth:a,targetHeight:c,topPx:h,leftPx:u,minimap:e.minimap});r.bindFramebuffer(36008,d.handle),r.bindFramebuffer(36009,null),r.blitFramebuffer(0,0,d.width,d.height,l,f,m,p,16384,9728),h+=b+8}}finally{r.bindFramebuffer(36008,s),r.bindFramebuffer(36009,o),t.flushing=!1}}function Js(i){let{framebuffer:e,targetWidth:t,targetHeight:n,topPx:r,leftPx:s,minimap:o}=i,a=o?Math.max(Math.floor(t/4),1):t,c=o?Math.max(Math.floor(n/4),1):n,h=Math.min(a/e.width,c/e.height),u=Math.max(Math.floor(e.width*h),1),d=Math.max(Math.floor(e.height*h),1),l=s,f=Math.max(n-r-d,0),m=l+u,p=f+d;return[l,f,m,p,d]}function eo(i){return i.userData[qn]||={flushing:!1,queuedFramebuffers:[]},i.userData[qn]}function to(i){return"colorAttachments"in i}function io(i){let e=i.props.framebuffer;return!e||e.handle===null}function Kn(i,e){if(!i)return e;let t=Number.parseInt(i,10);return Number.isFinite(t)?t:e}function Le(i,e,t){if(i===e)return!0;if(!t||!i||!e)return!1;if(Array.isArray(i)){if(!Array.isArray(e)||i.length!==e.length)return!1;for(let n=0;n<i.length;n++)if(!Le(i[n],e[n],t-1))return!1;return!0}if(Array.isArray(e))return!1;if(typeof i=="object"&&typeof e=="object"){let n=Object.keys(i),r=Object.keys(e);if(n.length!==r.length)return!1;for(let s of n)if(!e.hasOwnProperty(s)||!Le(i[s],e[s],t-1))return!1;return!0}return!1}var Qn=R(N(),1),Oe=class{bufferLayouts;constructor(e){this.bufferLayouts=e}getBufferLayout(e){return this.bufferLayouts.find(t=>t.name===e)||null}getAttributeNamesForBuffer(e){return(0,Qn.getBufferLayoutAttributeNames)(e)}mergeBufferLayouts(e,t){let n=[...e];for(let r of t){let s=n.findIndex(o=>o.name===r.name);s<0?n.push(r):n[s]=r}return n}};var he=R(N(),1);function Jn(i,e){let t=(0,he.getShaderAttributeLocationMap)(i),n=e.slice();return n.sort((r,s)=>{let o=(0,he.getMinimumAttributeLocation)((0,he.getBufferLayoutAttributeNames)(r).map(c=>t[c])),a=(0,he.getMinimumAttributeLocation)((0,he.getBufferLayoutAttributeNames)(s).map(c=>t[c]));return o-a}),n}var Lt=R(ne(),1);function Re(i,e){if(!i||!e.some(n=>n.bindingLayout?.length))return i;let t={...i,bindings:i.bindings.map(n=>({...n}))};"attributes"in(i||{})&&(t.attributes=i?.attributes||[]);for(let n of e)for(let r of n.bindingLayout||[])for(let s of no(r.name)){let o=t.bindings.find(a=>a.name===s);o?.group===0&&(o.group=r.group),o&&r.visibility!==void 0&&(o.visibility=r.visibility)}return t}function er(i,e,t=[]){return i?e?{...i,attributes:i.attributes.length?oo(i.attributes,e.attributes.filter(n=>t.includes(n.name))):e.attributes,bindings:so(i.bindings,e.bindings)}:i:e}function be(i){return!!(i.uniformTypes&&!ro(i.uniformTypes))}function tr(i){let e=[];for(let t of i){let n=(0,Lt.getShaderModuleUniformBlockName)(t),r=new Set([t.vs,t.fs].flatMap(o=>o?(0,Lt.getGLSLUniformBlocks)(o).filter(a=>a.isStd140).map(a=>a.blockName):[])),s=r.has(n)?n:r.size===1?r.values().next().value:void 0;be(t)&&s&&e.push({name:s,uniformTypes:t.uniformTypes})}return e}function Ot(i,e){let t=[],n=new Set;for(let r of[...i||[],...e||[]])n.has(r.name)||(n.add(r.name),t.push(r));return t}function no(i){let e=new Set([i,`${i}Uniforms`]);return i.endsWith("Uniforms")||e.add(`${i}Sampler`),[...e]}function ro(i){for(let e in i)return!1;return!0}function so(i,e){let t=i.map(s=>({...s})),n=new Set(i.map(s=>s.name)),r=new Set(i.map(s=>`${s.group}:${s.location}`));for(let s of e){let o=`${s.group}:${s.location}`;!n.has(s.name)&&!r.has(o)&&t.push({...s})}return t}function oo(i,e){let t=i.map(s=>({...s})),n=new Map(i.map(s=>[s.name,s])),r=new Map(i.map(s=>[s.location,s]));for(let s of e){let o=n.get(s.name);if(o){if(o.type!==s.type||o.location!==s.location)throw new Error(`Shader attribute "${s.name}" conflicts with its inferred type or location`);continue}let a=r.get(s.location);if(a)throw new Error(`Shader attributes "${a.name}" and "${s.name}" both use location ${s.location}`);t.push({...s})}return t}var Rt=R(N(),1),_i=R(ne(),1);function ir(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function nr(i){return Array.isArray(i)?i.length===0||typeof i[0]=="number":!1}function He(i){return ir(i)||nr(i)}function ao(i){return He(i)||typeof i=="number"||typeof i=="boolean"}function rr(i,e={}){let t={bindings:{},uniforms:{}};return Object.keys(i).forEach(n=>{let r=i[n];Object.prototype.hasOwnProperty.call(e,n)||ao(r)?t.uniforms[n]=r:t.bindings[n]=r}),t}var X=class{options={disableWarnings:!1};modules;moduleUniforms;moduleBindings;directBindings={};constructor(e,t){Object.assign(this.options,t);let n=(0,_i.getShaderModuleDependencies)(Object.values(e).filter(co));for(let r of n)e[r.name]=r;Rt.log.log(1,"Creating ShaderInputs with modules",Object.keys(e))(),this.modules=e,this.moduleUniforms={},this.moduleBindings={};for(let[r,s]of Object.entries(e))s&&(this._addModule(s),s.name&&r!==s.name&&!this.options.disableWarnings&&Rt.log.warn(`Module name: ${r} vs ${s.name}`)())}destroy(){}setProps(e){e.bindings&&Object.assign(this.directBindings,e.bindings);for(let t of Object.keys(e)){if(t==="bindings")continue;let n=t,r=e[n]||{},s=this.modules[n];if(!s)this.options.disableWarnings||Rt.log.warn(`Module ${t} not found`)();else{let o=this.moduleUniforms[n],a=this.moduleBindings[n],c=s.getUniforms?.(r,o)||r,{uniforms:h,bindings:u}=rr(c,s.uniformTypes);this.moduleUniforms[n]=sr(o,h,s.uniformTypes),this.moduleBindings[n]={...a,...u}}}}getModules(){return Object.values(this.modules)}addModules(e){let t=(0,_i.getShaderModuleDependencies)(e);for(let n of t){let r=n.name;this.modules[r]||(this.modules[r]=n,this._addModule(n))}}getUniformValues(){return this.moduleUniforms}getBindingValues(){let e={};for(let t of Object.values(this.moduleBindings))Object.assign(e,t);return Object.assign(e,this.directBindings),e}getModuleBindingValues(e){let t=this.moduleBindings[e];return t?{...t}:{}}getDebugTable(){let e={};for(let[t,n]of Object.entries(this.moduleUniforms))for(let[r,s]of Object.entries(n))e[`${t}.${r}`]={type:this.modules[t].uniformTypes?.[r],value:String(s)};return e}_addModule(e){let t=e.name;this.moduleUniforms[t]=sr({},e.defaultUniforms||{},e.uniformTypes),this.moduleBindings[t]={}}};function sr(i={},e={},t={}){let n={...i};for(let[r,s]of Object.entries(e))s!==void 0&&(n[r]=Ii(i[r],s,t[r]));return n}function Ii(i,e,t){if(!t||typeof t=="string")return Ye(e);if(Array.isArray(t)){if(vi(e)||!Array.isArray(e))return Ye(e);let o=Array.isArray(i)&&!vi(i)?[...i]:[],a=o.slice();for(let c=0;c<e.length;c++){let h=e[c];h!==void 0&&(a[c]=Ii(o[c],h,t[0]))}return a}if(!Mi(e))return Ye(e);let n=t,r=Mi(i)?i:{},s={...r};for(let[o,a]of Object.entries(e))a!==void 0&&(s[o]=Ii(r[o],a,n[o]));return s}function Ye(i){return ArrayBuffer.isView(i)?Array.prototype.slice.call(i):Array.isArray(i)?vi(i)?i.slice():i.map(t=>t===void 0?void 0:Ye(t)):Mi(i)?Object.fromEntries(Object.entries(i).map(([e,t])=>[e,t===void 0?void 0:Ye(t)])):i}function vi(i){return ArrayBuffer.isView(i)||Array.isArray(i)&&(i.length===0||typeof i[0]=="number")}function Mi(i){return!!i&&typeof i=="object"&&!Array.isArray(i)&&!ArrayBuffer.isView(i)}function co(i){return!!i?.dependencies}var Ti=R(N(),1);var ho=Ti.Buffer.DEBUG_DATA_MAX_LENGTH,G=class{device;id;ready;usage;props;isReady=!0;destroyed=!1;generation=0;updateTimestamp;debugData=new ArrayBuffer(0);_debugDataEnabled;_maxDebugDataByteLength;_ownsBuffer;_buffer;get buffer(){return this._buffer}get byteLength(){return this._buffer.byteLength}get[Symbol.toStringTag](){return"DynamicBuffer"}toString(){return`DynamicBuffer:"${this.id}":${this.byteLength}B`}toJSON(){return this.toString()}constructor(e,t){let{debugData:n=!1,buffer:r,ownsBuffer:s=!0,...o}=t;if(r&&r.device!==e)throw new Error("DynamicBuffer adopted buffers must belong to the supplied device");if(r&&(o.byteLength!==void 0||o.data!==void 0))throw new Error("DynamicBuffer cannot combine an adopted buffer with byteLength or data");let a=t.id||r?.id||O("dynamic-buffer"),c={...o,id:a,usage:o.usage??r?.usage,indexType:o.indexType??r?.indexType};(c.usage||0)&Ti.Buffer.INDEX&&!c.indexType&&(o.data instanceof Uint32Array?c.indexType="uint32":o.data instanceof Uint16Array?c.indexType="uint16":o.data instanceof Uint8Array&&(c.indexType="uint8")),delete c.data,delete c.byteOffset,this.device=e,this.id=a,this.props=c,this.usage=c.usage||0,this._debugDataEnabled=!!n,this._maxDebugDataByteLength=typeof n=="object"&&n.maxByteLength!==void 0?n.maxByteLength:ho,this._ownsBuffer=s,this._buffer=r??this.device.createBuffer({...o,id:a}),this.ready=Promise.resolve(this._buffer),this.updateTimestamp=this._buffer.updateTimestamp,this._resetDebugData(this._buffer.byteLength),o.data&&this._writeDebugData(o.data,o.byteOffset||0)}write(e,t=0){this._buffer.write(e,t),this._touch(),this._writeDebugData(e,t)}async mapAndWriteAsync(e,t=0,n=this.byteLength-t){let r=null;await this._buffer.mapAndWriteAsync(async(s,o)=>{await e(s,o),r=new Uint8Array(s.slice(0,n))},t,n),this._touch(),r&&this._writeDebugData(r,t)}async readAsync(e=0,t=this.byteLength-e){let n=await this._buffer.readAsync(e,t);return this._writeDebugData(n,e)&&this._touch(),n}async mapAndReadAsync(e,t=0,n=this.byteLength-t){let r=null,s=await this._buffer.mapAndReadAsync(async(o,a)=>(r=new Uint8Array(o.slice(0)),await e(o,a)),t,n);return r&&this._writeDebugData(r,t)&&this._touch(),s}resize(e){let{byteLength:t,preserveData:n=!1}=e;if(t===this.byteLength)return!1;let r=Math.min(e.copyByteLength??Math.min(this.byteLength,t),this.byteLength,t),s=this._buffer,o=this.debugData.slice(0),{data:a,byteOffset:c,...h}=this.props,u=this.device.createBuffer({...h,byteLength:t});return n&&r>0&&this._copyBufferContents(s,u,r),this._buffer=u,this._resetDebugData(t),n&&o.byteLength>0&&this._writeDebugData(o,0),this._ownsBuffer&&s.destroy(),this._ownsBuffer=!0,this.generation++,this._touch(),!0}ensureSize(e,t){return e<=this.byteLength?!1:this.resize({byteLength:e,preserveData:t?.preserveData})}getBinding(e){return e?.offset===void 0&&e?.size===void 0?this._buffer:{buffer:this._buffer,offset:e?.offset,size:e?.size}}destroy(){this.destroyed||(this._ownsBuffer&&this._buffer.destroy(),this.destroyed=!0,this.debugData=new ArrayBuffer(0))}_copyBufferContents(e,t,n){let r=this.device.type==="webgpu"?Math.ceil(n/4)*4:n,s=this.device.createCommandEncoder();s.copyBufferToBuffer({sourceBuffer:e,destinationBuffer:t,size:r}),this.device.submit(s.finish())}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_resetDebugData(e){if(!this._debugDataEnabled){this.debugData=new ArrayBuffer(0);return}this.debugData=new ArrayBuffer(Math.min(e,this._maxDebugDataByteLength))}_writeDebugData(e,t){if(!this._debugDataEnabled||this.debugData.byteLength===0||t>=this.debugData.byteLength)return!1;let n=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=new Uint8Array(this.debugData),s=Math.min(n.byteLength,r.byteLength-t);return r.set(n.subarray(0,s),t),s>0}};function ye(i){return i!==null&&typeof i=="object"&&"buffer"in i}function or(i){return i instanceof G?i:ye(i)&&i.buffer instanceof G?i.buffer:null}function uo(i){return i instanceof G?i.buffer:i}function kt(i){return{buffer:uo(i.buffer),offset:i.offset,size:i.size}}var ar=R(N(),1);function re(i){return i!==null&&typeof i=="object"&&"resolveTextureBinding"in i&&typeof i.resolveTextureBinding=="function"}function lo(i){return i?.type==="texture"||i?.type==="external-texture"}function Nt(i,e,t){let n=(0,ar.getShaderLayoutBinding)(i,e,{ignoreWarnings:!0});return lo(n)?n:i.bindings.length===0&&t?.fallbackGroup!==void 0?{type:"texture",name:e,group:t.fallbackGroup,location:0}:null}var J=2,fo=1e4,wi="render pipeline initialization failed",mo=["stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8"],Y=class i{static defaultProps={...P.RenderPipeline.defaultProps,source:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],plugins:[],geometry:null,indexBuffer:null,indexCount:void 0,firstVertex:0,firstIndex:0,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,material:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:_e.ShaderAssembler.getDefaultShaderAssembler("glsl"),debugShaders:void 0,disableWarnings:void 0};device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexCount;firstVertex;firstIndex;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;material=null;_uniformStore;_attributeInfos={};_gpuGeometry=null;props;_dynamicIndexBufferSource=null;_dynamicAttributeBufferSources={};_colorAttachmentFormats;_depthStencilAttachmentFormat;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_drawBlockedReason=!1;_destroyed=!1;_lastDrawTimestamp=-1;_bindingTable=[];get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(e,t){let n=i.defaultProps.shaderAssembler;this.props={...i.defaultProps,...t,shaderAssembler:t.shaderAssembler??(Ai(n,e.info.shadingLanguage)?n:_e.ShaderAssembler.getDefaultShaderAssembler(e.info.shadingLanguage))},t=this.props,this.id=t.id||O("model"),this.device=e,Object.assign(this.userData,t.userData),this.material=t.material||null;let r=yo(e),s=(0,_e.resolveShaderPlugins)(this.props.plugins,r.shaderLanguage),o=(0,_e.mergeShaderPluginModules)(this.props.modules,s.modules),a=Object.fromEntries(o.map(l=>[l.name,l])),c=t.shaderInputs||new X(a,{disableWarnings:this.props.disableWarnings});t.shaderInputs&&s.modules.length>0&&c.addModules(s.modules),this.setShaderInputs(c);let h=Ot(this.props.modules,c.getModules()),u={...s.defines,...this.props.defines};if(this.device.type==="webgl"&&(this.props._uniformBlockLayouts=tr(h)),this.props.shaderLayout=Re(this.props.shaderLayout,h)||null,this.device.type==="webgpu"&&this.props.source){let l=this.props.shaderAssembler;(0,P.assert)(Ai(l,"wgsl"));let{source:f,getUniforms:m,bindingTable:p,shaderLayout:b}=l.assembleWGSLShader({platformInfo:r,...this.props,modules:h,defines:u,pluginInjections:s.injections,pluginVertexInputs:s.vertexInputs,pluginVaryings:s.varyings});this.source=f,this._getModuleUniforms=m,this._bindingTable=p;let _=b??e.getShaderLayout?.(this.source),M=po(_,s.vertexInputs),y=er(this.props.shaderLayout,M,Object.keys(s.vertexInputs));this.props.shaderLayout=Re(y||null,h)||null}else{let l=this.props.shaderAssembler;(0,P.assert)(Ai(l,"glsl"));let{vs:f,fs:m,getUniforms:p}=l.assembleGLSLShaderPair({platformInfo:r,...this.props,modules:h,defines:u,pluginInjections:s.injections,pluginVertexInputs:s.vertexInputs,pluginVaryings:s.varyings});this.vs=f,this.fs=m,this._getModuleUniforms=p,this._bindingTable=[]}this.vertexCount=this.props.vertexCount,this.indexCount=this.props.indexCount,this.firstVertex=this.props.firstVertex,this.firstIndex=this.props.firstIndex,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,this._colorAttachmentFormats=this.props.colorAttachmentFormats,this._depthStencilAttachmentFormat=this.props.depthStencilAttachmentFormat,t.geometry&&this.setGeometry(t.geometry),this.pipelineFactory=t.pipelineFactory||P.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||P.ShaderFactory.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 t&&(this.isInstanced=t.isInstanced),t.instanceCount&&this.setInstanceCount(t.instanceCount),t.vertexCount&&this.setVertexCount(t.vertexCount),t.indexBuffer&&this.setIndexBuffer(t.indexBuffer),t.attributes&&this.setAttributes(t.attributes),t.constantAttributes&&this.setConstantAttributes(t.constantAttributes),t.bindings&&this.setBindings(t.bindings),t.transformFeedback&&(this.transformFeedback=t.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");let e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(e){this._syncDynamicBuffers(),this.updateShaderInputs(e),this.material?.updateShaderInputs(e),this.pipeline=this._updatePipeline()}draw(e){if(this._drawBlockedReason&&!this._pipelineNeedsUpdate)return P.log.info(J,`>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)(),!1;let t=this._areBindingsLoading();if(t)return P.log.info(J,`>>> DRAWING ABORTED ${this.id}: ${t} not loaded`)(),!1;this._syncAttachmentFormats(e);try{e.pushDebugGroup(`${this}.predraw(${e})`),this.device.type==="webgpu"?(this.updateShaderInputs(),this.material?.updateShaderInputs(),this._syncDynamicBuffers(),this.pipeline=this._updatePipeline()):this.predraw(this.device.commandEncoder)}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)P.log.info(J,`>>> DRAWING ABORTED ${this.id}: ${wi}`)(),n=!1;else{let s=this.vertexArray.getDrawValidationError();if(s)P.log.info(J,`>>> DRAWING ABORTED ${this.id}: ${s}`)(),this._drawBlockedReason=s,n=!1;else{let o=this._getCurrentShaderLayout(),a=this._getBindings(o),c=this._getBindGroups(o,a),{indexBuffer:h}=this.vertexArray,u=h?this.indexCount??h.byteLength/(h.indexType==="uint32"?4:2):void 0;e.setPipeline(this.pipeline),e.setBindings(c,{_bindGroupCacheKeys:this._getBindGroupCacheKeys()}),e.setVertexArray(this.vertexArray),n=this.isInstanced===!0&&this.instanceCount===0?!0:e.draw({isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.isInstanced?this.instanceCount:void 0,indexCount:u,firstVertex:this.firstVertex,firstIndex:this.firstIndex,transformFeedback:this.transformFeedback||void 0,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=wi,this._drawBlockedReason=wi):this._drawBlockedReason?this._needsRedraw=this._drawBlockedReason:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){this._gpuGeometry?.destroy();let t=e&&Yn(this.device,e);if(t){this.setTopology(t.topology||"triangle-list");let n=new Oe(this.bufferLayout);this.bufferLayout=n.mergeBufferLayouts(t.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(t)}this._gpuGeometry=t}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){let t=new Oe(this.bufferLayout),n=this._gpuGeometry?t.mergeBufferLayouts(e,this._gpuGeometry.bufferLayout):e;Le(n,this.bufferLayout,-1)||(this.bufferLayout=n,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){Le(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")}setIndexCount(e){this.indexCount=e,this.setNeedsRedraw("indexCount")}setDrawOffsets({firstVertex:e,firstIndex:t}){this.firstVertex=e,this.firstIndex=t,this.setNeedsRedraw("drawOffsets")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new P.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(be(n)&&!this.material?.ownsModule(t)){let r=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=r}this.setNeedsRedraw("shaderInputs")}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),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){let t=e instanceof G?e.buffer:e;this.indexBuffer=t,this._dynamicIndexBufferSource=e instanceof G?{source:e,generation:e.generation}:null,this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(e,t){this._drawBlockedReason=!1;let n=t?.disableWarnings??this.props.disableWarnings;e.indices&&P.log.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=Jn(this.pipeline.shaderLayout,this.bufferLayout);let r=new Oe(this.bufferLayout);for(let[s,o]of Object.entries(e)){let a=o instanceof G?o.buffer:o,c=r.getBufferLayout(s);if(!c){n||P.log.warn(`Model(${this.id}): Missing layout for buffer "${s}".`)();continue}let h=r.getAttributeNamesForBuffer(c),u=!1;for(let d of h){let l=this._attributeInfos[d];if(l){let f=this.device.type==="webgpu"?this.vertexArray.getBufferSlot(l.bufferName):l.location;if(f===null){n||P.log.warn(`Model(${this.id}): Missing vertex array slot for buffer "${l.bufferName}".`)();continue}this.vertexArray.setBuffer(f,a),o instanceof G?this._dynamicAttributeBufferSources[f]={source:o,generation:o.generation}:delete this._dynamicAttributeBufferSources[f],u=!0}}!u&&!n&&P.log.warn(`Model(${this.id}): Ignoring buffer "${a.id}" for unknown attribute "${s}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,t){for(let[n,r]of Object.entries(e)){let s=this._attributeInfos[n];s?this.vertexArray.setConstantWebGL(s.location,r):(t?.disableWarnings??this.props.disableWarnings)||P.log.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(let e of Object.values(this.bindings))if(re(e)&&!e.isReady)return e.id;for(let e of Object.values(this.material?.bindings||{}))if(re(e)&&!e.isReady)return e.id;return!1}_getBindings(e=this._getCurrentShaderLayout()){let t={};for(let[n,r]of Object.entries(this.bindings)){let s=go(n,r,e);s&&(t[n]=s)}return t}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){let n=e.bindings.length?(0,P.normalizeBindingsByGroup)(e,t):{0:t};if(!this.material)return n;for(let[r,s]of Object.entries(this.material.getBindingsByGroup(e))){let o=Number(r);n[o]={...n[o]||{},...s}}return n}_getBindGroupCacheKeys(){let e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){let e=0;this._dynamicIndexBufferSource&&(e=Math.max(e,this._dynamicIndexBufferSource.source.updateTimestamp));for(let t of Object.values(this._dynamicAttributeBufferSources))e=Math.max(e,t.source.updateTimestamp);for(let t of Object.values(this.bindings))t instanceof P.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof P.Buffer||t instanceof P.Texture||t instanceof P.ExternalTexture||t instanceof G?e=Math.max(e,t.updateTimestamp):re(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:ye(t)&&(e=Math.max(e,(t.buffer instanceof G,t.buffer.updateTimestamp)));return Math.max(e,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(e){let t={...e.attributes};for(let[n]of Object.entries(t))!this.pipeline.shaderLayout.attributes.find(r=>r.name===n)&&n!=="positions"&&delete t[n];this.vertexCount=e.vertexCount,this.setIndexBuffer(e.indices||null),this.setAttributes(e.attributes,{disableWarnings:!0}),this.setAttributes(t,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this._drawBlockedReason=!1,this.setNeedsRedraw(e)}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null,t=null;this.pipeline&&(P.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.pipeline.vs,t=this.pipeline.fs),this._pipelineNeedsUpdate=!1;let n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders}),r=null;this.source?r=n:this.fs&&(r=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bindings:void 0,bufferLayout:this.bufferLayout,colorAttachmentFormats:this._colorAttachmentFormats,depthStencilAttachmentFormat:this._depthStencilAttachmentFormat,topology:this.topology,parameters:this.parameters,bindGroups:void 0,vs:n,fs:r}),this._attributeInfos=(0,P.getAttributeInfosFromLayouts)(this.pipeline.shaderLayout,this.bufferLayout),e&&this.shaderFactory.release(e),t&&t!==e&&this.shaderFactory.release(t)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=P.log.level>3?0:fo;P.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,P.log.group(J,`>>> DRAWING MODEL ${this.id}`,{collapsed:P.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=Wn(this.pipeline.shaderLayout,this.id);P.log.table(J,e)();let t=this.shaderInputs.getDebugTable();P.log.table(J,t)();let n=this._getAttributeDebugTable();P.log.table(J,this._attributeInfos)(),P.log.table(J,n)(),P.log.groupEnd(J)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){let t=this.device.props.debugFramebuffers;if(this._drawCount++,!t)return;let n=e.props.framebuffer;Zn(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){let e={};for(let[t,n]of Object.entries(this._attributeInfos)){let r=this.vertexArray.attributes[n.location];e[n.location]={name:t,type:n.shaderType,values:r?this._getBufferOrConstantValues(r,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){let{indexBuffer:t}=this.vertexArray,n=t.indexType==="uint32"?new Uint32Array(t.debugData):new Uint16Array(t.debugData);e.indices={name:"indices",type:t.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,t){let n=P.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof P.Buffer?new n(e.debugData):e).toString()}_getNonMaterialBindings(e){if(!this.material)return e;let t={};for(let[n,r]of Object.entries(e))this.material.ownsBinding(n)||(t[n]=r);return t}_getCurrentShaderLayout(){return this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]}}_syncDynamicBuffers(){if(this._dynamicIndexBufferSource&&this._dynamicIndexBufferSource.generation!==this._dynamicIndexBufferSource.source.generation){let e=this._dynamicIndexBufferSource.source.buffer;this.indexBuffer=e,this.vertexArray.setIndexBuffer(e),this._dynamicIndexBufferSource.generation=this._dynamicIndexBufferSource.source.generation,this.setNeedsRedraw("dynamic index buffer")}for(let[e,t]of Object.entries(this._dynamicAttributeBufferSources))t.generation!==t.source.generation&&(this.vertexArray.setBuffer(Number(e),t.source.buffer),t.generation=t.source.generation,this.setNeedsRedraw("dynamic attribute buffer"))}_syncAttachmentFormats(e){if(this.device.type!=="webgpu")return;let t=e.framebuffer||e.props.framebuffer,n=e.props,r=n.colorAttachmentFormats??t?.colorAttachments?.map(o=>xo(o?.texture?.format)),s=n.depthStencilAttachmentFormat===!1?void 0:n.depthStencilAttachmentFormat??bo(t?.depthStencilAttachment?.texture?.format);(!Le(this._colorAttachmentFormats,r,1)||this._depthStencilAttachmentFormat!==s)&&(this._colorAttachmentFormats=r,this._depthStencilAttachmentFormat=s,this._setPipelineNeedsUpdate("attachment formats"))}};function Ai(i,e){return i.shaderLanguage!==void 0&&i.shaderLanguage!==e?!1:e==="glsl"?"assembleGLSLShaderPair"in i&&typeof i.assembleGLSLShaderPair=="function":"assembleWGSLShader"in i&&typeof i.assembleWGSLShader=="function"}function po(i,e){return!i||Object.keys(e).length===0?i:{...i,attributes:i.attributes.map(t=>{let n=t.name.startsWith("_luma_")?t.name.slice(6):null;return n&&e[n]?{...t,name:n}:t})}}function go(i,e,t){if(re(e)){let n=Nt(t,i,{fallbackGroup:0});return n?e.resolveTextureBinding(n):null}return e instanceof G?e.buffer:ye(e)?kt(e):e}function xo(i){return i&&!cr(i)?i:null}function bo(i){return i&&cr(i)?i:void 0}function cr(i){return mo.includes(i)}function yo(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,limits:i.limits,features:i.features}}var ee=R(N(),1);var Ne=3,ke=class{device;modules;_materialBindingNames;_materialModuleNames;constructor(e,t={}){this.device=e,this.modules=t.modules||[];let n=new X(Object.fromEntries(this.modules.map(r=>[r.name,r])));this._materialBindingNames=_o(n),this._materialModuleNames=Io(n)}createMaterial(e={}){return new De(this.device,{...e,factory:this})}getBindingNames(){return Array.from(this._materialBindingNames)}ownsBinding(e){if(this._materialBindingNames.has(e))return!0;let t=Si(e);return t?this._materialModuleNames.has(t):!1}ownsModule(e){return this._materialModuleNames.has(e)}getBindingsByGroup(e){return Object.keys(e).length>0?{[Ne]:e}:{}}};function Si(i){return i.endsWith("Uniforms")?i.slice(0,-8):null}function _o(i){let e=new Set;for(let t of Object.values(i.modules))for(let n of t.bindingLayout||[])n.group===Ne&&e.add(n.name);return e}function Io(i){let e=new Set;for(let t of Object.values(i.modules))t.name&&t.bindingLayout?.some(n=>n.group===Ne&&n.name===t.name)&&e.add(t.name);return e}var De=class{id;device;factory;shaderInputs;bindings={};_uniformStore;_bindGroupCacheToken={};_dynamicResourceGenerations={};constructor(e,t={}){this.id=t.id||O("material"),this.device=e,this.factory=t.factory||new ke(e,{modules:t.modules||t.shaderInputs?.getModules()||[]});let n=Object.fromEntries((t.shaderInputs?.getModules()||this.factory.modules).map(r=>[r.name,r]));this.shaderInputs=t.shaderInputs||new X(n),this._uniformStore=new ee.UniformStore(this.device,this.shaderInputs.modules);for(let[r,s]of Object.entries(this.shaderInputs.modules))if(this.ownsModule(r)&&be(s)){let o=this._uniformStore.getManagedUniformBuffer(r);this.bindings[`${r}Uniforms`]=o}this.updateShaderInputs(),t.bindings&&this._replaceOwnedBindings(t.bindings)}destroy(){this._uniformStore.destroy()}clone(e={}){let t=this.factory.createMaterial({id:e.id,shaderInputs:e.shaderInputs,bindings:{...this.getResourceBindings(),...e.bindings}});return e.shaderInputs||t.setProps(this.shaderInputs.getUniformValues()),e.moduleProps&&t.setProps(e.moduleProps),t.updateShaderInputs(),t}ownsBinding(e){return this.factory.ownsBinding(e)}ownsModule(e){return this.factory.ownsModule(e)}setProps(e){this.shaderInputs.setProps(e)}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this._setOwnedBindings(this.shaderInputs.getBindingValues())&&(this._bindGroupCacheToken={})}getResourceBindings(){let e={};for(let[t,n]of Object.entries(this.bindings))Si(t)||(e[t]=n);return e}getBindings(e={bindings:[]}){this._syncDynamicResourceGenerations();let t={},n=t;for(let[r,s]of Object.entries(this.bindings))if(re(s)){let o=Nt(e,r,{fallbackGroup:Ne}),a=o?s.resolveTextureBinding(o):null;a&&(n[r]=a)}else s instanceof G?n[r]=s.buffer:ye(s)?n[r]=kt(s):n[r]=s;return this._syncDynamicResourceGenerations(),t}getBindingsByGroup(e={bindings:[]}){return this.factory.getBindingsByGroup(this.getBindings(e))}getBindGroupCacheKey(e){return this._syncDynamicResourceGenerations(),e===Ne?this._bindGroupCacheToken:null}getBindingsUpdateTimestamp(){let e=0;for(let t of Object.values(this.bindings))t instanceof ee.TextureView?e=Math.max(e,t.texture.updateTimestamp):t instanceof ee.Buffer||t instanceof ee.Texture||t instanceof ee.ExternalTexture||t instanceof G?e=Math.max(e,t.updateTimestamp):re(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:ye(t)&&(e=Math.max(e,(t.buffer instanceof G,t.buffer.updateTimestamp)));return e}_replaceOwnedBindings(e){this._setOwnedBindings(e)&&(this._bindGroupCacheToken={})}_setOwnedBindings(e){let t=!1;for(let[n,r]of Object.entries(e))r!==void 0&&this.ownsBinding(n)&&this.bindings[n]!==r&&(this.bindings[n]=r,t=!0);return t}_syncDynamicResourceGenerations(){let e={},t=!1;for(let[n,r]of Object.entries(this.bindings)){let s=vo(r);s!==null&&(e[n]=s,this._dynamicResourceGenerations[n]!==s&&(t=!0))}Object.keys(e).length!==Object.keys(this._dynamicResourceGenerations).length&&(t=!0),this._dynamicResourceGenerations=e,t&&(this._bindGroupCacheToken={})}};function vo(i){return re(i)?i.generation:or(i)?.generation??null}var hr=R(N(),1),ur=R(ne(),1);var Mo=35980,To=35981,Dt=class i{device;model;transformFeedback;static defaultProps={...Y.defaultProps,feedbackBufferMode:"separate",outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return e?.info?.type==="webgl"}constructor(e,t=i.defaultProps){if(!i.isSupported(e))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=e,this.model=new Y(this.device,{id:t.id||"buffer-transform-model",fs:t.fs||(0,ur.getPassthroughFS)(),topology:t.topology||"point-list",varyings:t.outputs||t.varyings,...t,bufferMode:t.bufferMode||(t.feedbackBufferMode==="interleaved"?Mo:To)}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:t.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback)}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);let t=this.device.beginRenderPass({discard:!0,...e});this.model.draw(t),t.end()}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){let t=this.getBuffer(e);if(!t)throw new Error("BufferTransform#getBuffer");if(t instanceof hr.Buffer)return t.readAsync();let{buffer:n,byteOffset:r=0,byteLength:s=n.byteLength}=t;return n.readAsync(r,s)}};var lr=R(ne(),1);var wo="transform_output",Bt=class{device;model;sampler;currentIndex=0;samplerTextureMap=null;bindings=[];resources={};constructor(e,t){this.device=e,this.sampler=e.createSampler({addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",minFilter:"nearest",magFilter:"nearest",mipmapFilter:"nearest"}),this.model=new Y(this.device,{id:t.id||O("texture-transform-model"),fs:t.fs||(0,lr.getPassthroughFS)({input:t.targetTextureVarying,inputChannels:t.targetTextureChannels,output:wo}),vertexCount:t.vertexCount,...t}),this._initialize(t),Object.seal(this)}destroy(){this.model.destroy();for(let e of this.bindings)e.framebuffer?.destroy()}delete(){this.destroy()}run(e){let{framebuffer:t}=this.bindings[this.currentIndex],n=this.device.beginRenderPass({framebuffer:t,...e});this.model.draw(n),n.end(),this.device.submit()}getTargetTexture(){let{targetTexture:e}=this.bindings[this.currentIndex];return e}getFramebuffer(){return this.bindings[this.currentIndex].framebuffer}_initialize(e){this._updateBindings(e)}_updateBindings(e){this.bindings[this.currentIndex]=this._updateBinding(this.bindings[this.currentIndex],e)}_updateBinding(e,{sourceBuffers:t,sourceTextures:n,targetTexture:r}){if(e||(e={sourceBuffers:{},sourceTextures:{},targetTexture:null}),Object.assign(e.sourceTextures,n),Object.assign(e.sourceBuffers,t),r){e.targetTexture=r;let{width:s,height:o}=r;e.framebuffer&&e.framebuffer.destroy(),e.framebuffer=this.device.createFramebuffer({id:"transform-framebuffer",width:s,height:o,colorAttachments:[r]}),e.framebuffer.resize({width:s,height:o})}return e}_setSourceTextureParameters(){let e=this.currentIndex,{sourceTextures:t}=this.bindings[e];for(let n in t)t[n].sampler=this.sampler}};var Ao=`struct VertexInputs {
|
|
8
8
|
@location(0) clipSpacePositions: vec2<f32>,
|
|
9
9
|
@location(1) texCoords: vec2<f32>,
|
|
10
10
|
@location(2) coordinates: vec2<f32>
|
|
@@ -26,7 +26,7 @@ fn vertexMain(inputs: VertexInputs) -> FragmentInputs {
|
|
|
26
26
|
outputs.uv = inputs.texCoords;
|
|
27
27
|
return outputs;
|
|
28
28
|
}
|
|
29
|
-
`,
|
|
29
|
+
`,So=`#version 300 es
|
|
30
30
|
in vec2 clipSpacePositions;
|
|
31
31
|
in vec2 texCoords;
|
|
32
32
|
in vec2 coordinates;
|
|
@@ -41,8 +41,8 @@ void main(void) {
|
|
|
41
41
|
coordinate = coordinates;
|
|
42
42
|
uv = texCoords;
|
|
43
43
|
}
|
|
44
|
-
`,
|
|
45
|
-
${t.source}`}),super(e,{id:t.id||O("clip-space"),...t,vs:wo,vertexCount:4,geometry:new z({topology:"triangle-strip",vertexCount:4,attributes:{clipSpacePositions:{size:2,value:new Float32Array(ur)},texCoords:{size:2,value:new Float32Array(n)},coordinates:{size:2,value:new Float32Array(n)}}})})}};var D=R(N(),1);var Ke=R(N(),1);var Si={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function We(i){return i?Array.isArray(i)?i[0]??null:i:null}function lr(i){let{dimension:e,data:t}=i;if(!t)return null;switch(e){case"1d":{let n=We(t);if(!n)return null;let{width:r}=qe(n);return{width:r,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=We(t);return n?qe(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=We(t[0]);return n?qe(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let r=t[n],s=We(r);return s?qe(s):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],r=Object.keys(n)[0]??null;if(!r)return null;let s=We(n[r]);return s?qe(s):null}default:return null}}function qe(i){if((0,Ke.isExternalImage)(i))return(0,Ke.getExternalImageSize)(i);if(typeof i=="object"&&"width"in i&&"height"in i)return{width:i.width,height:i.height};throw new Error("Unsupported mip-level data")}function Ao(i){return typeof i=="object"&&i!==null&&"data"in i&&"width"in i&&"height"in i}function So(i){return ArrayBuffer.isView(i)}function Pi(i){let{textureFormat:e,format:t}=i;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function dr(i){let e=Si[i];if(e===void 0)throw new Error(`Invalid cube face: ${i}`);return e}function Po(i,e){return 6*i+dr(e)}function Ei(i){throw new Error("setTexture1DData not supported in WebGL.")}function Eo(i){return Array.isArray(i)?i:[i]}function _e(i,e,t,n){let r=Eo(e),s=i,o=[];for(let a=0;a<r.length;a++){let c=r[a];if((0,Ke.isExternalImage)(c))o.push({type:"external-image",image:c,z:s,mipLevel:a});else if(Ao(c))o.push({type:"texture-data",data:c,textureFormat:Pi(c),z:s,mipLevel:a});else if(So(c)&&t)o.push({type:"texture-data",data:{data:c,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:s,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return o}function Ci(i){let e=[];for(let t=0;t<i.length;t++)e.push(..._e(t,i[t]));return e}function Li(i){let e=[];for(let t=0;t<i.length;t++)e.push(..._e(t,i[t]));return e}function Oi(i){let e=[];for(let[t,n]of Object.entries(i)){let r=dr(t);e.push(..._e(r,n))}return e}function Ri(i){let e=[];return i.forEach((t,n)=>{for(let[r,s]of Object.entries(t)){let o=Po(n,r);e.push(..._e(o,s))}}),e}var K=class i{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;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(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let n=O("dynamic-texture"),r=t;this.props={...i.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((s,o)=>{this.resolveReady=s,this.rejectReady=o}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(r)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?Co({...t,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};let p=lr(t);return p||{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`);let c=Lo(this.device,n,a,{format:r?e.format:void 0}),h=c.format??this.props.format,u={...this.props,...a,format:h,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(h)&&!s&&(u.usage=D.Texture.SAMPLE|D.Texture.COPY_DST);let d=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(h);if(this.device.type==="webgpu"&&d){let p=this.props.dimension==="3d"?D.Texture.SAMPLE|D.Texture.STORAGE|D.Texture.COPY_DST|D.Texture.COPY_SRC:D.Texture.SAMPLE|D.Texture.RENDER|D.Texture.COPY_DST|D.Texture.COPY_SRC;u.usage|=p}let l=this.device.getMipLevelCount(u.width,u.height),f=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?l:Math.max(1,Math.min(l,this.props.mipLevels??1)),m={...u,mipLevels:f};this._texture=this.device.createTexture(m),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!d&&D.log.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),d&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),D.log.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):D.log.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof D.Sampler?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:r}),o=this.device.createBuffer({byteLength:s.byteLength,usage:D.Buffer.COPY_DST|D.Buffer.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:r},o);let a=this.device.createFence();return await a.signaled,a.destroy(),o}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:r}),o=await this.readBuffer(e),a=await o.readAsync(0,s.byteLength);return o.destroy(),a.buffer instanceof ArrayBuffer?a.buffer:a.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),D.log.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=Si[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=Ei(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=_e(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=Ci(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=Li(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=Oi(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=Ri(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:r}=t;switch(t.type){case"external-image":let{image:s,flipY:o}=t;this.texture.copyExternalImage({image:s,z:n,mipLevel:r,flipY:o});break;case"texture-data":let{data:a,textureFormat:c}=t;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")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await ki(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&D.log.warn(`${this} already destroyed`)}_checkReady(){this.isReady||D.log.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...D.Texture.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function Co(i){if(!i.data)return[];let e=i.width&&i.height?{width:i.width,height:i.height}:void 0,t="format"in i?i.format:void 0;switch(i.dimension){case"1d":return Ei(i.data);case"2d":return _e(0,i.data,e,t);case"3d":return Ci(i.data);case"2d-array":return Li(i.data);case"cube":return Oi(i.data);case"cube-array":return Ri(i.data);default:throw new Error(`Unhandled dimension ${i.dimension}`)}}function Lo(i,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let r=new Map;for(let u of e){let d=r.get(u.z)??[];d.push(u),r.set(u.z,d)}let s=e.some(u=>u.mipLevel>0),o=n.format,a=Number.POSITIVE_INFINITY,c=[];for(let[u,d]of r){let l=[...d].sort((M,y)=>M.mipLevel-y.mipLevel),f=l[0];if(!f||f.mipLevel!==0)throw new Error(`DynamicTexture: slice ${u} is missing mip level 0`);let m=mr(i,f);if(m.width!==t.width||m.height!==t.height)throw new Error(`DynamicTexture: slice ${u} base level dimensions ${m.width}x${m.height} do not match expected ${t.width}x${t.height}`);let p=fr(f);if(p){if(o&&o!==p)throw new Error(`DynamicTexture: slice ${u} base level format "${p}" does not match texture format "${o}"`);o=p}let b=o&&i.isTextureFormatCompressed(o)?Oo(i,m.width,m.height,o):i.getMipLevelCount(m.width,m.height),_=0;for(let M=0;M<l.length;M++){let y=l[M];if(!y||y.mipLevel!==M||M>=b)break;let I=mr(i,y),g=Math.max(1,m.width>>M),x=Math.max(1,m.height>>M);if(I.width!==g||I.height!==x)break;let v=fr(y);if(v&&(o||(o=v),v!==o))break;_++,c.push(y)}a=Math.min(a,_)}let h=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(u=>u.mipLevel<h),mipLevels:h,format:o,hasExplicitMipChain:s}}function fr(i){if(i.type==="texture-data")return i.textureFormat??Pi(i.data)}function mr(i,e){switch(e.type){case"external-image":return i.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function Oo(i,e,t,n){let{blockWidth:r=1,blockHeight:s=1}=i.getTextureFormatInfo(n),o=1;for(let a=1;;a++){let c=Math.max(1,e>>a),h=Math.max(1,t>>a);if(c<r||h<s)break;o++}return o}async function ki(i){if(i=await i,Array.isArray(i))return await Promise.all(i.map(ki));if(i&&typeof i=="object"&&i.constructor===Object){let e=i,t=await Promise.all(Object.values(e).map(ki)),n=Object.keys(e),r={};for(let s=0;s<n.length;s++)r[n[s]]=t[s];return r}return i}var Ro={name:"background",uniformTypes:{scale:"vec2<f32>",flipY:"i32"}},ko=`@group(0) @binding(auto) var backgroundTexture: texture_2d<f32>;
|
|
44
|
+
`,dr=[-1,-1,1,-1,-1,1,1,1],ue=class extends Y{constructor(e,t){let n=dr.map(r=>r===-1?0:r);t.source&&(t={...t,source:`${Ao}
|
|
45
|
+
${t.source}`}),super(e,{id:t.id||O("clip-space"),...t,vs:So,vertexCount:4,geometry:new z({topology:"triangle-strip",vertexCount:4,attributes:{clipSpacePositions:{size:2,value:new Float32Array(dr)},texCoords:{size:2,value:new Float32Array(n)},coordinates:{size:2,value:new Float32Array(n)}}})})}};var D=R(N(),1);var Ke=R(N(),1);var Pi={"+X":0,"-X":1,"+Y":2,"-Y":3,"+Z":4,"-Z":5};function We(i){return i?Array.isArray(i)?i[0]??null:i:null}function fr(i){let{dimension:e,data:t}=i;if(!t)return null;switch(e){case"1d":{let n=We(t);if(!n)return null;let{width:r}=qe(n);return{width:r,height:1}}case"2d":{if(ArrayBuffer.isView(t))return null;let n=We(t);return n?qe(n):null}case"3d":case"2d-array":{if(!Array.isArray(t)||t.length===0)return null;let n=We(t[0]);return n?qe(n):null}case"cube":{let n=Object.keys(t)[0]??null;if(!n)return null;let r=t[n],s=We(r);return s?qe(s):null}case"cube-array":{if(!Array.isArray(t)||t.length===0)return null;let n=t[0],r=Object.keys(n)[0]??null;if(!r)return null;let s=We(n[r]);return s?qe(s):null}default:return null}}function qe(i){if((0,Ke.isExternalImage)(i))return(0,Ke.getExternalImageSize)(i);if(typeof i=="object"&&"width"in i&&"height"in i)return{width:i.width,height:i.height};throw new Error("Unsupported mip-level data")}function Po(i){return typeof i=="object"&&i!==null&&"data"in i&&"width"in i&&"height"in i}function Eo(i){return ArrayBuffer.isView(i)}function Ei(i){let{textureFormat:e,format:t}=i;if(e&&t&&e!==t)throw new Error(`Conflicting texture formats "${e}" and "${t}" provided for the same mip level`);return e??t}function mr(i){let e=Pi[i];if(e===void 0)throw new Error(`Invalid cube face: ${i}`);return e}function Co(i,e){return 6*i+mr(e)}function Ci(i){throw new Error("setTexture1DData not supported in WebGL.")}function Lo(i){return Array.isArray(i)?i:[i]}function Ie(i,e,t,n){let r=Lo(e),s=i,o=[];for(let a=0;a<r.length;a++){let c=r[a];if((0,Ke.isExternalImage)(c))o.push({type:"external-image",image:c,z:s,mipLevel:a});else if(Po(c))o.push({type:"texture-data",data:c,textureFormat:Ei(c),z:s,mipLevel:a});else if(Eo(c)&&t)o.push({type:"texture-data",data:{data:c,width:Math.max(1,t.width>>a),height:Math.max(1,t.height>>a),...n?{format:n}:{}},textureFormat:n,z:s,mipLevel:a});else throw new Error("Unsupported 2D mip-level payload")}return o}function Li(i){let e=[];for(let t=0;t<i.length;t++)e.push(...Ie(t,i[t]));return e}function Oi(i){let e=[];for(let t=0;t<i.length;t++)e.push(...Ie(t,i[t]));return e}function Ri(i){let e=[];for(let[t,n]of Object.entries(i)){let r=mr(t);e.push(...Ie(r,n))}return e}function ki(i){let e=[];return i.forEach((t,n)=>{for(let[r,s]of Object.entries(t)){let o=Co(n,r);e.push(...Ie(o,s))}}),e}var K=class i{device;id;props;_texture=null;_sampler=null;_view=null;ready;isReady=!1;destroyed=!1;generation=0;updateTimestamp;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(){let e=this._texture?.width??this.props.width??"?",t=this._texture?.height??this.props.height??"?";return`DynamicTexture:"${this.id}":${e}x${t}px:(${this.isReady?"ready":"loading..."})`}resolveTextureBinding(e){return this.isReady?this.texture:null}constructor(e,t){this.device=e;let n=O("dynamic-texture"),r=t;this.props={...i.defaultProps,id:n,...t,data:null},this.id=this.props.id,this.ready=new Promise((s,o)=>{this.resolveReady=s,this.rejectReady=o}),this.updateTimestamp=this.device.incrementTimestamp(),this.initAsync(r)}async initAsync(e){try{let t=await this._loadAllData(e);this._checkNotDestroyed();let n=t.data?Oo({...t,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};let p=fr(t);return p||{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`);let c=Ro(this.device,n,a,{format:r?e.format:void 0}),h=c.format??this.props.format,u={...this.props,...a,format:h,mipLevels:1,data:void 0};this.device.isTextureFormatCompressed(h)&&!s&&(u.usage=D.Texture.SAMPLE|D.Texture.COPY_DST);let d=this.props.mipmaps&&!c.hasExplicitMipChain&&!this.device.isTextureFormatCompressed(h);if(this.device.type==="webgpu"&&d){let p=this.props.dimension==="3d"?D.Texture.SAMPLE|D.Texture.STORAGE|D.Texture.COPY_DST|D.Texture.COPY_SRC:D.Texture.SAMPLE|D.Texture.RENDER|D.Texture.COPY_DST|D.Texture.COPY_SRC;u.usage|=p}let l=this.device.getMipLevelCount(u.width,u.height),f=c.hasExplicitMipChain?c.mipLevels:this.props.mipLevels==="auto"?l:Math.max(1,Math.min(l,this.props.mipLevels??1)),m={...u,mipLevels:f};this._texture=this.device.createTexture(m),this._sampler=this.texture.sampler,this._view=this.texture.view,this._touchGeneration(),c.subresources.length&&this._setTextureSubresources(c.subresources),this.props.mipmaps&&!c.hasExplicitMipChain&&!d&&D.log.warn(`${this} skipping auto-generated mipmaps for compressed texture format`)(),d&&this.generateMipmaps(),this.isReady=!0,this.resolveReady(this.texture),D.log.info(1,`${this} created`)()}catch(t){let n=t instanceof Error?t:new Error(String(t));this.rejectReady(n)}}destroy(){this._texture&&(this._texture.destroy(),this._texture=null,this._sampler=null,this._view=null),this.isReady=!1,this.destroyed=!0}generateMipmaps(){this.device.type==="webgl"?(this.texture.generateMipmapsWebGL(),this._touch()):this.device.type==="webgpu"?(this.device.generateMipmapsWebGPU(this.texture),this._touch()):D.log.warn(`${this} mipmaps not supported on ${this.device.type}`)}setSampler(e={}){this._checkReady();let t=e instanceof D.Sampler?e:this.device.createSampler(e);this.texture.setSampler(t),this._sampler=t,this._touchGeneration()}async readBuffer(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:r}),o=this.device.createBuffer({byteLength:s.byteLength,usage:D.Buffer.COPY_DST|D.Buffer.MAP_READ});this.texture.readBuffer({...e,width:t,height:n,depthOrArrayLayers:r},o);let a=this.device.createFence();return await a.signaled,a.destroy(),o}async readAsync(e={}){this.isReady||await this.ready;let t=e.width??this.texture.width,n=e.height??this.texture.height,r=e.depthOrArrayLayers??this.texture.depth,s=this.texture.computeMemoryLayout({width:t,height:n,depthOrArrayLayers:r}),o=await this.readBuffer(e),a=await o.readAsync(0,s.byteLength);return o.destroy(),a.buffer instanceof ArrayBuffer?a.buffer:a.slice().buffer}resize(e){if(this._checkReady(),e.width===this.texture.width&&e.height===this.texture.height)return!1;let t=this.texture;return this._texture=t.clone(e),this._sampler=this.texture.sampler,this._view=this.texture.view,t.destroy(),this._touchGeneration(),D.log.info(`${this} resized`),!0}getCubeFaceIndex(e){let t=Pi[e];if(t===void 0)throw new Error(`Invalid cube face: ${e}`);return t}getCubeArrayFaceIndex(e,t){return 6*e+this.getCubeFaceIndex(t)}setTexture1DData(e){if(this._checkReady(),this.texture.props.dimension!=="1d")throw new Error(`${this} is not 1d`);let t=Ci(e);this._setTextureSubresources(t)}setTexture2DData(e,t=0){if(this._checkReady(),this.texture.props.dimension!=="2d")throw new Error(`${this} is not 2d`);let n=Ie(t,e);this._setTextureSubresources(n)}setTexture3DData(e){if(this.texture.props.dimension!=="3d")throw new Error(`${this} is not 3d`);let t=Li(e);this._setTextureSubresources(t)}setTextureArrayData(e){if(this.texture.props.dimension!=="2d-array")throw new Error(`${this} is not 2d-array`);let t=Oi(e);this._setTextureSubresources(t)}setTextureCubeData(e){if(this.texture.props.dimension!=="cube")throw new Error(`${this} is not cube`);let t=Ri(e);this._setTextureSubresources(t)}setTextureCubeArrayData(e){if(this.texture.props.dimension!=="cube-array")throw new Error(`${this} is not cube-array`);let t=ki(e);this._setTextureSubresources(t)}_setTextureSubresources(e){for(let t of e){let{z:n,mipLevel:r}=t;switch(t.type){case"external-image":let{image:s,flipY:o}=t;this.texture.copyExternalImage({image:s,z:n,mipLevel:r,flipY:o});break;case"texture-data":let{data:a,textureFormat:c}=t;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")}}e.length>0&&this._touch()}async _loadAllData(e){let t=await Ni(e.data);return{dimension:e.dimension??"2d",data:t??null}}_checkNotDestroyed(){this.destroyed&&D.log.warn(`${this} already destroyed`)}_checkReady(){this.isReady||D.log.warn(`${this} Cannot perform this operation before ready`)}_touch(){this.updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}static defaultProps={...D.Texture.defaultProps,dimension:"2d",data:null,mipmaps:!1}};function Oo(i){if(!i.data)return[];let e=i.width&&i.height?{width:i.width,height:i.height}:void 0,t="format"in i?i.format:void 0;switch(i.dimension){case"1d":return Ci(i.data);case"2d":return Ie(0,i.data,e,t);case"3d":return Li(i.data);case"2d-array":return Oi(i.data);case"cube":return Ri(i.data);case"cube-array":return ki(i.data);default:throw new Error(`Unhandled dimension ${i.dimension}`)}}function Ro(i,e,t,n){if(e.length===0)return{subresources:e,mipLevels:1,format:n.format,hasExplicitMipChain:!1};let r=new Map;for(let u of e){let d=r.get(u.z)??[];d.push(u),r.set(u.z,d)}let s=e.some(u=>u.mipLevel>0),o=n.format,a=Number.POSITIVE_INFINITY,c=[];for(let[u,d]of r){let l=[...d].sort((M,y)=>M.mipLevel-y.mipLevel),f=l[0];if(!f||f.mipLevel!==0)throw new Error(`DynamicTexture: slice ${u} is missing mip level 0`);let m=gr(i,f);if(m.width!==t.width||m.height!==t.height)throw new Error(`DynamicTexture: slice ${u} base level dimensions ${m.width}x${m.height} do not match expected ${t.width}x${t.height}`);let p=pr(f);if(p){if(o&&o!==p)throw new Error(`DynamicTexture: slice ${u} base level format "${p}" does not match texture format "${o}"`);o=p}let b=o&&i.isTextureFormatCompressed(o)?ko(i,m.width,m.height,o):i.getMipLevelCount(m.width,m.height),_=0;for(let M=0;M<l.length;M++){let y=l[M];if(!y||y.mipLevel!==M||M>=b)break;let I=gr(i,y),g=Math.max(1,m.width>>M),x=Math.max(1,m.height>>M);if(I.width!==g||I.height!==x)break;let v=pr(y);if(v&&(o||(o=v),v!==o))break;_++,c.push(y)}a=Math.min(a,_)}let h=Number.isFinite(a)?Math.max(1,a):1;return{subresources:c.filter(u=>u.mipLevel<h),mipLevels:h,format:o,hasExplicitMipChain:s}}function pr(i){if(i.type==="texture-data")return i.textureFormat??Ei(i.data)}function gr(i,e){switch(e.type){case"external-image":return i.getExternalImageSize(e.image);case"texture-data":return{width:e.data.width,height:e.data.height};default:throw new Error("Unsupported texture subresource")}}function ko(i,e,t,n){let{blockWidth:r=1,blockHeight:s=1}=i.getTextureFormatInfo(n),o=1;for(let a=1;;a++){let c=Math.max(1,e>>a),h=Math.max(1,t>>a);if(c<r||h<s)break;o++}return o}async function Ni(i){if(i=await i,Array.isArray(i))return await Promise.all(i.map(Ni));if(i&&typeof i=="object"&&i.constructor===Object){let e=i,t=await Promise.all(Object.values(e).map(Ni)),n=Object.keys(e),r={};for(let s=0;s<n.length;s++)r[n[s]]=t[s];return r}return i}var No={name:"background",uniformTypes:{scale:"vec2<f32>",flipY:"i32"}},Do=`@group(0) @binding(auto) var backgroundTexture: texture_2d<f32>;
|
|
46
46
|
@group(0) @binding(auto) var backgroundTextureSampler: sampler;
|
|
47
47
|
struct backgroundUniforms {
|
|
48
48
|
scale: vec2<f32>,
|
|
@@ -64,7 +64,7 @@ fn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4<f32> {
|
|
|
64
64
|
let position: vec2<f32> = billboardTexture_getTextureUV(inputs.uv);
|
|
65
65
|
return textureSample(backgroundTexture, backgroundTextureSampler, position);
|
|
66
66
|
}
|
|
67
|
-
`,
|
|
67
|
+
`,Bo=`#version 300 es
|
|
68
68
|
precision highp float;
|
|
69
69
|
|
|
70
70
|
uniform sampler2D backgroundTexture;
|
|
@@ -89,7 +89,7 @@ void main(void) {
|
|
|
89
89
|
vec2 position = billboardTexture_getTextureUV(coordinate);
|
|
90
90
|
fragColor = texture(backgroundTexture, position);
|
|
91
91
|
}
|
|
92
|
-
`,Be=class extends ue{backgroundTexture=null;flipY=!1;constructor(e,t){if(super(e,{...t,id:t.id||"background-texture-model",source:
|
|
92
|
+
`,Be=class extends ue{backgroundTexture=null;flipY=!1;constructor(e,t){if(super(e,{...t,id:t.id||"background-texture-model",source:Do,fs:Bo,modules:[...t.modules||[],No],parameters:{depthWriteEnabled:!1,...t.parameters||{},...t.blend?{blend:!0,blendColorOperation:"add",blendAlphaOperation:"add",blendColorSrcFactor:"one-minus-dst-alpha",blendColorDstFactor:"one",blendAlphaSrcFactor:"one-minus-dst-alpha",blendAlphaDstFactor:"one"}:{}}}),!t.backgroundTexture)throw new Error("BackgroundTextureModel requires a backgroundTexture prop");this.setProps(t)}setProps(e){let{backgroundTexture:t}=e;if(e.flipY!==void 0&&(this.flipY=e.flipY,this.backgroundTexture&&this.updateScale(this.backgroundTexture)),t)if(this.setBindings({backgroundTexture:t}),t.isReady){let n=t instanceof K?t.texture:t;this.backgroundTexture=n,this.updateScale(n)}else t.ready.then(n=>{this.backgroundTexture=n,this.updateScale(n)})}predraw(e){super.predraw(e)}updateScale(e){if(!e){this.shaderInputs.setProps({background:{scale:[1,1],flipY:0}});return}let[t,n]=this.device.getCanvasContext().getDrawingBufferSize(),r=e.width,s=e.height,o=t/n,a=r/s,c=1,h=1;o>a?h=o/a:c=a/o,this.shaderInputs.setProps({background:{scale:[c,h],flipY:this.flipY?1:0}})}};var Fe=class extends z{constructor(e={}){let{id:t=O("sphere-geometry")}=e,{indices:n,attributes:r}=Fo(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function Fo(i){let{nlat:e=10,nlong:t=10}=i,s=Math.PI-0,c=2*Math.PI-0,h=(e+1)*(t+1),u=(_,M,y,I,g)=>i.radius||1,d=new Float32Array(h*3),l=new Float32Array(h*3),f=new Float32Array(h*2),m=h>65535?Uint32Array:Uint16Array,p=new m(e*t*6);for(let _=0;_<=e;_++)for(let M=0;M<=t;M++){let y=M/t,I=_/e,g=M+_*(t+1),x=g*2,v=g*3,w=c*y,T=s*I,C=Math.sin(w),S=Math.cos(w),A=Math.sin(T),L=Math.cos(T),E=S*A,U=L,te=C*A,q=u(E,U,te,y,I);d[v+0]=q*E,d[v+1]=q*U,d[v+2]=q*te,l[v+0]=E,l[v+1]=U,l[v+2]=te,f[x+0]=y,f[x+1]=1-I}let b=t+1;for(let _=0;_<t;_++)for(let M=0;M<e;M++){let y=(_*e+M)*6;p[y+0]=M*b+_,p[y+1]=M*b+_+1,p[y+2]=(M+1)*b+_,p[y+3]=(M+1)*b+_,p[y+4]=M*b+_+1,p[y+5]=(M+1)*b+_+1}return{indices:{size:1,value:p},attributes:{POSITION:{size:3,value:d},NORMAL:{size:3,value:l},TEXCOORD_0:{size:2,value:f}}}}var zo=.02,jo=.12,Go=.15,Uo=.2,Fi=[0,1,0],$o=[255,255,255],Vo=1,Di=.35,Bi=255,Xo=1,Ho=.01,Yo={depthCompare:"less-equal",depthWriteEnabled:!1,cullMode:"none"},Wo=[{name:"instancePosition",format:"float32x3",stepMode:"instance"},{name:"instanceDirection",format:"float32x3",stepMode:"instance"},{name:"instanceScale",format:"float32x3",stepMode:"instance"},{name:"instanceColor",format:"float32x4",stepMode:"instance"}],qo={name:"lightMarker",props:{},uniforms:{},uniformTypes:{viewProjectionMatrix:"mat4x4<f32>"}},Ko="inputs.positions * inputs.instanceScale",Zo="vec3<f32>(inputs.positions.x * inputs.instanceScale.x, (inputs.positions.y - 0.5) * inputs.instanceScale.y, inputs.positions.z * inputs.instanceScale.z)",Qo="positions * instanceScale",Jo="vec3(positions.x * instanceScale.x, (positions.y - 0.5) * instanceScale.y, positions.z * instanceScale.z)",le=class extends Y{lightModelProps;_instanceData;_managedBuffers;buildInstanceData;sizePropNames;constructor(e,t,n){let r=n.buildInstanceData(t),s=xr(e,t.id||n.idPrefix,r),o=new X({lightMarker:qo});o.setProps({lightMarker:{viewProjectionMatrix:yr(t)}});let{source:a,vs:c,fs:h}=ra(n.anchorMode),u=t;super(e,{...u,id:t.id||n.idPrefix,source:a,vs:c,fs:h,geometry:n.geometry,shaderInputs:o,bufferLayout:[...Wo],attributes:s,instanceCount:r.instanceCount,parameters:_r(t.parameters)}),this.lightModelProps=t,this._instanceData=r,this._managedBuffers=s,this.buildInstanceData=n.buildInstanceData,this.sizePropNames=n.sizePropNames}destroy(){super.destroy(),br(this._managedBuffers),this._managedBuffers={}}draw(e){return this.instanceCount===0?!0:super.draw(e)}setProps(e){this.lightModelProps={...this.lightModelProps,...e},e.parameters&&this.setParameters(_r(this.lightModelProps.parameters)),("viewMatrix"in e||"projectionMatrix"in e)&&(this.shaderInputs.setProps({lightMarker:{viewProjectionMatrix:yr(this.lightModelProps)}}),this.setNeedsRedraw("lightMarker camera")),na(e,this.sizePropNames)&&this.rebuildInstanceData()}rebuildInstanceData(){let e=this.buildInstanceData(this.lightModelProps),t=xr(this.device,this.id,e);this.setAttributes(t),this.setInstanceCount(e.instanceCount),br(this._managedBuffers),this._managedBuffers=t,this._instanceData=e}};function Ir(i){let e=Tr(i.lights),t=zi(i),n=i.pointLightRadius??zo*t.sceneScale*t.markerScale;return Gi(e.length,(r,s)=>({color:ji(r),direction:Fi,position:r.position,scale:[n,n,n]}),e)}function vr(i){let e=wr(i.lights),t=zi(i),n=i.spotLightLength??jo*t.sceneScale*t.markerScale;return Gi(e.length,(r,s)=>{let o=Ze(r.outerConeAngle??Math.PI/4,0,Math.PI/2-Ho),a=Math.tan(o)*n;return{color:ji(r),direction:Ar(r.direction),position:r.position,scale:[a,n,a]}},e)}function Mr(i){let e=ea(i.lights),t=zi(i),n=i.directionalLightLength??Go*t.sceneScale*t.markerScale,r=n*Uo;return Gi(e.length,(s,o)=>{let a=Ar(s.direction),c=[t.sceneCenter[0]-a[0]*t.sceneScale*Di,t.sceneCenter[1]-a[1]*t.sceneScale*Di,t.sceneCenter[2]-a[2]*t.sceneScale*Di];return{color:ji(s),direction:a,position:c,scale:[r,n,r]}},e)}function Tr(i){return i.filter(e=>e.type==="point")}function wr(i){return i.filter(e=>e.type==="spot")}function ea(i){return i.filter(e=>e.type==="directional")}function zi(i){let e=ta(i.lights,i.bounds),t=[(e[0][0]+e[1][0])/2,(e[0][1]+e[1][1])/2,(e[0][2]+e[1][2])/2],n=Math.max(Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1],e[1][2]-e[0][2]),Xo);return{bounds:e,markerScale:Math.max(i.markerScale??Vo,0),sceneCenter:t,sceneScale:n}}function ji(i){let e=i.color||$o,t=Math.max(i.intensity??1,0),n=Ze(.35+.3*Math.log10(t+1),.35,1);return[Ze(e[0]/Bi,0,1)*n,Ze(e[1]/Bi,0,1)*n,Ze(e[2]/Bi,0,1)*n,1]}function Ar(i){let[e,t,n]=i||Fi,r=Math.hypot(e,t,n);return r===0?[...Fi]:[e/r,t/r,n/r]}function Gi(i,e,t=[]){let n=new Float32Array(i*3),r=new Float32Array(i*3),s=new Float32Array(i*3),o=new Float32Array(i*4);for(let[a,c]of t.entries()){let h=e(c,a);n.set(h.position,a*3),r.set(h.direction,a*3),s.set(h.scale,a*3),o.set(h.color,a*4)}return{instanceCount:i,instancePositions:n,instanceDirections:r,instanceScales:s,instanceColors:o}}function ta(i,e){if(e)return ia(e);let t=[...Tr(i).map(s=>s.position),...wr(i).map(s=>s.position)];if(t.length===0)return[[-.5,-.5,-.5],[.5,.5,.5]];let n=[...t[0]],r=[...t[0]];for(let s of t.slice(1))n[0]=Math.min(n[0],s[0]),n[1]=Math.min(n[1],s[1]),n[2]=Math.min(n[2],s[2]),r[0]=Math.max(r[0],s[0]),r[1]=Math.max(r[1],s[1]),r[2]=Math.max(r[2],s[2]);return[n,r]}function ia(i){return[[...i[0]],[...i[1]]]}function xr(i,e,t){return{instancePosition:i.createBuffer({id:`${e}-instance-position`,data:Ft(t.instancePositions,3)}),instanceDirection:i.createBuffer({id:`${e}-instance-direction`,data:Ft(t.instanceDirections,3)}),instanceScale:i.createBuffer({id:`${e}-instance-scale`,data:Ft(t.instanceScales,3)}),instanceColor:i.createBuffer({id:`${e}-instance-color`,data:Ft(t.instanceColors,4)})}}function Ft(i,e){return i.length>0?i:new Float32Array(e)}function br(i){for(let e of Object.values(i))e?.destroy()}function yr(i){return new k(i.projectionMatrix).multiplyRight(i.viewMatrix)}function na(i,e){return"lights"in i||"bounds"in i||"markerScale"in i?!0:e.some(t=>t in i)}function _r(i){return{...Yo,...i||{}}}function ra(i){let e=i==="apex"?Zo:Ko,t=i==="apex"?Jo:Qo;return{source:`struct lightMarkerUniforms {
|
|
93
93
|
viewProjectionMatrix: mat4x4<f32>,
|
|
94
94
|
};
|
|
95
95
|
|
|
@@ -171,7 +171,7 @@ out vec4 fragColor;
|
|
|
171
171
|
void main(void) {
|
|
172
172
|
fragColor = vColor;
|
|
173
173
|
}
|
|
174
|
-
`}}function Ze(i,e,t){return Math.min(t,Math.max(e,i))}var na=new Fe({nlat:8,nlong:12,radius:1}),Ft=class extends le{constructor(e,t){super(e,t,{anchorMode:"centered",buildInstanceData:yr,geometry:na,idPrefix:"point-light-model",sizePropNames:["pointLightRadius"]})}};var ra={x:[2,0,1],y:[0,1,2],z:[1,2,0]},de=class extends z{constructor(e={}){let{id:t=O("truncated-code-geometry")}=e,{indices:n,attributes:r}=sa(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{POSITION:{size:3,value:r.POSITION},NORMAL:{size:3,value:r.NORMAL},TEXCOORD_0:{size:2,value:r.TEXCOORD_0},...e.attributes}})}};function sa(i={}){let{bottomRadius:e=0,topRadius:t=0,height:n=1,nradial:r=10,nvertical:s=10,verticalAxis:o="y",topCap:a=!1,bottomCap:c=!1}=i,h=(a?2:0)+(c?2:0),u=(r+1)*(s+1+h),d=Math.atan2(e-t,n),l=Math.sin,f=Math.cos,m=Math.PI,p=f(d),b=l(d),_=a?-2:0,M=s+(c?2:0),y=r+1,I=new Uint16Array(r*(s+h)*6),g=ra[o],x=new Float32Array(u*3),v=new Float32Array(u*3),w=new Float32Array(u*2),T=0,C=0;for(let S=_;S<=M;S++){let A=S/s,L=n*A,E;S<0?(L=0,A=1,E=e):S>s?(L=n,A=1,E=t):E=e+(t-e)*(S/s),(S===-2||S===s+2)&&(E=0,A=0),L-=n/2;for(let U=0;U<y;U++){let te=l(U*m*2/r),q=f(U*m*2/r);x[T+g[0]]=te*E,x[T+g[1]]=L,x[T+g[2]]=q*E,v[T+g[0]]=S<0||S>s?0:te*p,v[T+g[1]]=S<0?-1:S>s?1:b,v[T+g[2]]=S<0||S>s?0:q*p,w[C+0]=U/r,w[C+1]=A,C+=2,T+=3}}for(let S=0;S<s+h;S++)for(let A=0;A<r;A++){let L=(S*r+A)*6;I[L+0]=y*(S+0)+0+A,I[L+1]=y*(S+0)+1+A,I[L+2]=y*(S+1)+1+A,I[L+3]=y*(S+0)+0+A,I[L+4]=y*(S+1)+1+A,I[L+5]=y*(S+1)+0+A}return{indices:I,attributes:{POSITION:x,NORMAL:v,TEXCOORD_0:w}}}var fe=class extends de{constructor(e={}){let{id:t=O("cone-geometry"),radius:n=1,cap:r=!0}=e;super({...e,id:t,topRadius:0,topCap:!!r,bottomCap:!!r,bottomRadius:n})}};var oa=new fe({cap:!0,nradial:16,nvertical:1,radius:1}),zt=class extends le{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:_r,geometry:oa,idPrefix:"spot-light-model",sizePropNames:["spotLightLength"]})}};var aa=new fe({cap:!0,nradial:12,nvertical:1,radius:1}),jt=class extends le{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:Ir,geometry:aa,idPrefix:"directional-light-model",sizePropNames:["directionalLightLength"]})}};function Gi(i,e){if(!i)throw new Error(e)}var re=class{id;matrix=new k;display=!0;position=new H;rotation=new H;scale=new H(1,1,1);userData={};props={};constructor(e={}){let{id:t}=e;this.id=t||O(this.constructor.name),this._setScenegraphNodeProps(e)}getBounds(){return null}destroy(){}delete(){this.destroy()}setProps(e){return this._setScenegraphNodeProps(e),this}toString(){return`{type: ScenegraphNode, id: ${this.id})}`}setPosition(e){return Gi(e.length===3,"setPosition requires vector argument"),this.position=e,this}setRotation(e){return Gi(e.length===3||e.length===4,"setRotation requires vector argument"),this.rotation=e,this}setScale(e){return Gi(e.length===3,"setScale requires vector argument"),this.scale=e,this}setMatrix(e,t=!0){t?this.matrix.copy(e):this.matrix=e}setMatrixComponents(e){let{position:t,rotation:n,scale:r,update:s=!0}=e;return t&&this.setPosition(t),n&&this.setRotation(n),r&&this.setScale(r),s&&this.updateMatrix(),this}updateMatrix(){if(this.matrix.identity(),this.matrix.translate(this.position),this.rotation.length===4){let e=new k().fromQuaternion(this.rotation);this.matrix.multiplyRight(e)}else this.matrix.rotateXYZ(this.rotation);return this.matrix.scale(this.scale),this}update({position:e,rotation:t,scale:n}={}){return e&&this.setPosition(e),t&&this.setRotation(t),n&&this.setScale(n),this.updateMatrix(),this}getCoordinateUniforms(e,t){t=t||this.matrix;let n=new k(e).multiplyRight(t),r=n.invert(),s=r.transpose();return{viewMatrix:e,modelMatrix:t,objectMatrix:t,worldMatrix:n,worldInverseMatrix:r,worldInverseTransposeMatrix:s}}_setScenegraphNodeProps(e){e.display!==void 0&&(this.display=e.display),e?.position&&this.setPosition(e.position),e?.rotation&&this.setRotation(e.rotation),e?.scale&&this.setScale(e.scale),this.updateMatrix(),e?.matrix&&this.setMatrix(e.matrix),Object.assign(this.props,e)}};var wr=R(N(),1);function Gt(){return[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]]}function Ut(i,e,t){let n=new k(t);for(let r=0;r<8;r++){let s=new H(e[r&1?1:0][0],e[r&2?1:0][1],e[r&4?1:0][2]);n.transformAsPoint(s,s);for(let o=0;o<3;o++)i[0][o]=Math.min(i[0][o],s[o]),i[1][o]=Math.max(i[1][o],s[o])}}function $t(i){return Number.isFinite(i[0][0])}var Vt=class i extends re{children;constructor(e={}){e=Array.isArray(e)?{children:e}:e;let{children:t=[]}=e;wr.log.assert(t.every(n=>n instanceof re),"every child must an instance of ScenegraphNode"),super(e),this.children=t}getBounds(){let e=Gt();return this.traverse((t,{worldMatrix:n})=>{let r=t.getBounds();if(!r)return;let s=new k(n).multiplyRight(t.matrix);Ut(e,r,s)}),$t(e)?e:null}destroy(){this.children.forEach(e=>e.destroy()),this.removeAll(),super.destroy()}add(...e){for(let t of e)Array.isArray(t)?this.add(...t):this.children.push(t);return this}remove(e){let t=this.children,n=t.indexOf(e);return n>-1&&t.splice(n,1),this}removeAll(){return this.children=[],this}traverse(e,{worldMatrix:t=new k}={}){if(!this.display)return;let n=new k(t).multiplyRight(this.matrix);for(let r of this.children)r.display&&(r instanceof i?r.traverse(e,{worldMatrix:n}):e(r,{worldMatrix:n}))}traverseDepthSorted(e,{viewMatrix:t,worldMatrix:n=new k,order:r="back-to-front"}){let s=new k(t),o=[];this.traverse((c,h)=>{let u=c.getBounds(),d=u?new H(u[0]).add(u[1]).divide([2,2,2]):new H,l=new k(h.worldMatrix).multiplyRight(c.matrix);l.transformAsPoint(d,d),s.transformAsPoint(d,d),o.push({node:c,context:{worldMatrix:l,bounds:u,depth:-d[2]},index:o.length})},{worldMatrix:new k(n)});let a=r==="back-to-front"?-1:1;o.sort((c,h)=>a*(c.context.depth-h.context.depth)||c.index-h.index);for(let{node:c,context:h}of o)e(c,h)}preorderTraversal(e,{worldMatrix:t=new k}={}){let n=new k(t).multiplyRight(this.matrix);e(this,{worldMatrix:n});for(let r of this.children)r instanceof i?r.preorderTraversal(e,{worldMatrix:n}):e(r,{worldMatrix:n})}};var Xt=class extends re{model;instanceMatrices;bounds=null;managedResources;constructor(e){super(e),this.model=e.model,this.managedResources=e.managedResources||[],this.instanceMatrices=e.instanceMatrices||null,this.bounds=e.bounds?this.instanceMatrices?ca(e.bounds,this.instanceMatrices):e.bounds:null,this.setProps(e)}destroy(){this.model&&(this.model.destroy(),this.model=null),this.managedResources.forEach(e=>e.destroy()),this.managedResources=[]}getBounds(){return this.bounds}draw(e){return this.model.draw(e)}};function ca(i,e){let t=Gt();for(let n of e)Ut(t,i,n);return $t(t)?t:null}var Vi=R(N(),1),Ar=10,ha=1e-10;function Er(i){let{positions:e,indices:t,attributes:n=[],preserveBoundary:r=!0}=i;(0,Vi.assert)(t.length%3===0&&e.length%3===0);let s=Math.max(0,Math.min(t.length,Math.floor((i.targetIndexCount??t.length*(i.targetRatio??.5))/3)*3));if(t.length===0||s>=t.length)return{indices:t.slice(),geometricError:0};let o=e.length/3,a=Array.from({length:o},()=>({quadric:new Float64Array(Ar),neighbors:new Set,boundaryNeighbors:new Set,triangles:new Set,active:!1,version:0})),c=[],h=new Map,u=new Map,d=new Hi,l=0,f=0,m=(g,x,v)=>{let w=Math.min(g,x),T=Math.max(g,x),C=w*o+T,A=(h.get(C)||0)+v;A<=0?(h.delete(C),a[g].neighbors.delete(x),a[x].neighbors.delete(g)):(h.set(C,A),a[g].neighbors.add(x),a[x].neighbors.add(g)),A===1?(a[g].boundaryNeighbors.add(x),a[x].boundaryNeighbors.add(g)):(a[g].boundaryNeighbors.delete(x),a[x].boundaryNeighbors.delete(g))},p=g=>{let x=c[g];if(!x.active)return;let[v,w,T]=x.vertices;u.delete(Pr(v,w,T)),m(v,w,-1),m(w,T,-1),m(T,v,-1),a[v].triangles.delete(g),a[w].triangles.delete(g),a[T].triangles.delete(g),x.active=!1,l--},b=g=>{let x=c[g],[v,w,T]=x.vertices;if(v===w||w===T||T===v)return!1;let C=Pr(v,w,T);return u.has(C)?!1:(u.set(C,g),m(v,w,1),m(w,T,1),m(T,v,1),a[v].triangles.add(g),a[w].triangles.add(g),a[T].triangles.add(g),a[v].active=!0,a[w].active=!0,a[T].active=!0,x.active=!0,l++,!0)};for(let g=0;g<t.length;g+=3){let x=t[g],v=t[g+1],w=t[g+2];(0,Vi.assert)(x<o&&v<o&&w<o);let T={vertices:[x,v,w],active:!1},C=c.push(T)-1;b(C)&&ua(a,e,x,v,w)}let _=(g,x)=>{if(!a[g].active||!a[x].active)return;let v=da(n,g,x);if(Number.isFinite(v))for(let[w,T]of[[g,x],[x,g]]){if(r&&!Sr(a,e,w,T))continue;let C=Math.max(0,la(a,e,g,x,w));d.add({retainedVertex:w,removedVertex:T,retainedVersion:a[w].version,removedVersion:a[T].version,geometricCost:C,cost:C+v})}};for(let g=0;g<a.length;g++)for(let x of a[g].neighbors)g<x&&_(g,x);for(;l*3>s;){let g=d.remove();if(!g)break;let{retainedVertex:x,removedVertex:v}=g,w=a[x],T=a[v];if(!w.active||!T.active||w.version!==g.retainedVersion||T.version!==g.removedVersion||!w.neighbors.has(v)||r&&!Sr(a,e,x,v)||!fa(c,a,e,x,v))continue;let C=new Set([x,v,...w.neighbors,...T.neighbors]),S=[...T.triangles];for(let A of S)p(A);for(let A of S){let L=c[A];for(let E=0;E<3;E++)L.vertices[E]===v&&(L.vertices[E]=x);b(A)}for(let A=0;A<Ar;A++)w.quadric[A]+=T.quadric[A];T.active=!1,f=Math.max(f,g.geometricCost);for(let A of C)a[A].version++;for(let A of C)if(a[A].active)for(let L of a[A].neighbors)_(A,L)}let M=t.constructor,y=new M(l*3),I=0;for(let g of c)g.active&&(y[I++]=g.vertices[0],y[I++]=g.vertices[1],y[I++]=g.vertices[2]);return{indices:y,geometricError:Math.sqrt(f)}}function ua(i,e,t,n,r){let s=Xi(e,t,n,r),o=Math.hypot(s[0],s[1],s[2]);if(o===0)return;let a=s[0]/o,c=s[1]/o,h=s[2]/o,u=-(a*e[t*3]+c*e[t*3+1]+h*e[t*3+2]),d=[a,c,h,u];for(let l of[t,n,r]){let f=0;for(let m=0;m<4;m++)for(let p=m;p<4;p++)i[l].quadric[f++]+=d[m]*d[p]}}function la(i,e,t,n,r){let s=[e[r*3],e[r*3+1],e[r*3+2],1],o=0,a=0;for(let c=0;c<4;c++)for(let h=c;h<4;h++){let u=i[t].quadric[o]+i[n].quadric[o];a+=u*s[c]*s[h]*(c===h?1:2),o++}return a}function da(i,e,t){let n=0;for(let r of i){let s=r.weight??1;if(s===0)continue;let o=r.values instanceof Uint8Array||r.values instanceof Uint16Array||r.values instanceof Uint32Array;for(let a=0;a<r.size;a++){let c=r.values[e*r.size+a]-r.values[t*r.size+a];if(o&&c!==0)return 1/0;n+=c*c*s}}return n}function Sr(i,e,t,n){let r=i[t].boundaryNeighbors.size>0,s=i[n].boundaryNeighbors.size>0;if(r!==s)return!1;if(!s)return!0;let o=i[n].boundaryNeighbors;if(o.size!==2||!o.has(t))return!1;let a=[...o].find(m=>m!==t);if(a===void 0)return!1;let c=Ht(e,t,n),h=Ht(e,a,n),u=Ui(c),d=Ui(h),l=[c[1]*h[2]-c[2]*h[1],c[2]*h[0]-c[0]*h[2],c[0]*h[1]-c[1]*h[0]];return c[0]*h[0]+c[1]*h[1]+c[2]*h[2]<=0&&Ui(l)<=ha*u*d}function fa(i,e,t,n,r){for(let s of e[r].triangles){let o=i[s];if(o.vertices.includes(n))continue;let a=Xi(t,...o.vertices),c=o.vertices.map(d=>d===r?n:d),h=Xi(t,...c);if(a[0]*h[0]+a[1]*h[1]+a[2]*h[2]<=0)return!1}return!0}function Xi(i,e,t,n){let r=Ht(i,t,e),s=Ht(i,n,e);return[r[1]*s[2]-r[2]*s[1],r[2]*s[0]-r[0]*s[2],r[0]*s[1]-r[1]*s[0]]}function Ht(i,e,t){return[i[e*3]-i[t*3],i[e*3+1]-i[t*3+1],i[e*3+2]-i[t*3+2]]}function Ui(i){return i[0]*i[0]+i[1]*i[1]+i[2]*i[2]}function Pr(i,e,t){return[i,e,t].sort((n,r)=>n-r).join(":")}var Hi=class{entries=[];add(e){this.entries.push(e);let t=this.entries.length-1;for(;t>0;){let n=t-1>>1;if($i(this.entries[n],e)<=0)break;this.entries[t]=this.entries[n],this.entries[n]=e,t=n}}remove(){let e=this.entries[0],t=this.entries.pop();if(!e||!t||this.entries.length===0)return e;this.entries[0]=t;let n=0;for(;;){let r=n*2+1;if(r>=this.entries.length)break;let s=r+1,o=s<this.entries.length&&$i(this.entries[s],this.entries[r])<0?s:r;if($i(this.entries[n],this.entries[o])<=0)break;[this.entries[n],this.entries[o]]=[this.entries[o],this.entries[n]],n=o}return e}};function $i(i,e){return i.cost-e.cost||i.retainedVertex-e.retainedVertex||i.removedVertex-e.removedVertex}var Yt=class extends z{constructor(e={}){let{id:t=O("cube-geometry"),indices:n=!0}=e;super(n?{...e,id:t,topology:"triangle-list",indices:{size:1,value:ma},attributes:{...Ma,...e.attributes}}:{...e,id:t,topology:"triangle-list",indices:void 0,attributes:{...Ta,...e.attributes}})}},ma=new Uint16Array([0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]),pa=new Float32Array([-1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1]),ga=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0]),xa=new Float32Array([0,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1]),ba=new Uint32Array([0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5]),ya=new Float32Array([1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,1,1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,1,-1,1,1,1,-1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1]),_a=new Float32Array([1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0]),Ia=new Float32Array([1,0,1,1,0,0,1,1,0,0,0,1,1,0,0,1,1,0,1,1,0,0,0,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,1,0,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,0,1,1,0,0,1,1,1,0,1,1,1,1,1,1,1,0,0,1,0,0,0,1,0,1,0,1,1,1,0,1,1,0,0,1,0,1,0,1]),va=new Uint32Array([3,3,3,3,3,3,4,4,4,4,4,4,2,2,2,2,2,2,5,5,5,5,5,5,0,0,0,0,0,0,1,1,1,1,1,1]),Ma={POSITION:{size:3,value:pa},NORMAL:{size:3,value:ga},TEXCOORD_0:{size:2,value:xa},faceIndex:{size:1,value:ba}},Ta={POSITION:{size:3,value:ya},TEXCOORD_0:{size:2,value:_a},COLOR_0:{size:3,value:Ia},faceIndex:{size:1,value:va}};var Wt=class extends de{constructor(e={}){let{id:t=O("cylinder-geometry"),radius:n=1}=e;super({...e,id:t,bottomRadius:n,topRadius:n})}};var wa=[-1,0,0,0,1,0,0,0,-1,0,0,1,0,-1,0,1,0,0],Aa=[3,4,5,3,5,1,3,1,0,3,0,4,4,0,2,4,2,5,2,0,1,5,2,1],qt=class extends z{constructor(e={}){let{id:t=O("ico-sphere-geometry")}=e,{indices:n,attributes:r}=Sa(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function Sa(i){let{iterations:e=0}=i,t=Math.PI,n=t*2,r=[...wa],s=[...Aa];r.push(),s.push();let o=(()=>{let u={};return(d,l)=>{d*=3,l*=3;let f=d<l?d:l,m=d>l?d:l,p=`${f}|${m}`;if(p in u)return u[p];let b=r[d],_=r[d+1],M=r[d+2],y=r[l],I=r[l+1],g=r[l+2],x=(b+y)/2,v=(_+I)/2,w=(M+g)/2,T=Math.sqrt(x*x+v*v+w*w);x/=T,v/=T,w/=T,r.push(x,v,w);let C=r.length/3-1;return u[p]=C,C}})();for(let u=0;u<e;u++){let d=[];for(let l=0;l<s.length;l+=3){let f=o(s[l+0],s[l+1]),m=o(s[l+1],s[l+2]),p=o(s[l+2],s[l+0]);d.push(p,s[l+0],f,f,s[l+1],m,m,s[l+2],p,f,m,p)}s=d}let a=new Array(r.length),c=new Array(r.length/3*2),h=s.length;for(let u=h-3;u>=0;u-=3){let d=s[u+0],l=s[u+1],f=s[u+2],m=d*3,p=l*3,b=f*3,_=d*2,M=l*2,y=f*2,I=r[m+0],g=r[m+1],x=r[m+2],v=Math.acos(x/Math.sqrt(I*I+g*g+x*x)),w=Math.atan2(g,I)+t,T=v/t,C=1-w/n,S=r[p+0],A=r[p+1],L=r[p+2],E=Math.acos(L/Math.sqrt(S*S+A*A+L*L)),U=Math.atan2(A,S)+t,te=E/t,q=1-U/n,nt=r[b+0],rt=r[b+1],st=r[b+2],is=Math.acos(st/Math.sqrt(nt*nt+rt*rt+st*st)),ns=Math.atan2(rt,nt)+t,tn=is/t,ot=1-ns/n,rs=[nt-S,rt-A,st-L],ss=[I-S,g-A,x-L],W=new H(rs).cross(ss).normalize(),F;(C===0||q===0||ot===0)&&(C===0||C>.5)&&(q===0||q>.5)&&(ot===0||ot>.5)&&(r.push(r[m+0],r[m+1],r[m+2]),F=r.length/3-1,s.push(F),c[F*2+0]=1,c[F*2+1]=T,a[F*3+0]=W.x,a[F*3+1]=W.y,a[F*3+2]=W.z,r.push(r[p+0],r[p+1],r[p+2]),F=r.length/3-1,s.push(F),c[F*2+0]=1,c[F*2+1]=te,a[F*3+0]=W.x,a[F*3+1]=W.y,a[F*3+2]=W.z,r.push(r[b+0],r[b+1],r[b+2]),F=r.length/3-1,s.push(F),c[F*2+0]=1,c[F*2+1]=tn,a[F*3+0]=W.x,a[F*3+1]=W.y,a[F*3+2]=W.z),a[m+0]=a[p+0]=a[b+0]=W.x,a[m+1]=a[p+1]=a[b+1]=W.y,a[m+2]=a[p+2]=a[b+2]=W.z,c[_+0]=C,c[_+1]=T,c[M+0]=q,c[M+1]=te,c[y+0]=ot,c[y+1]=tn}return{indices:{size:1,value:new Uint16Array(s)},attributes:{POSITION:{size:3,value:new Float32Array(r)},NORMAL:{size:3,value:new Float32Array(a)},TEXCOORD_0:{size:2,value:new Float32Array(c)}}}}var Kt=class extends z{constructor(e={}){let{id:t=O("plane-geometry")}=e,{indices:n,attributes:r}=Pa(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function Pa(i){let{type:e="x,y",offset:t=0,flipCull:n=!1,unpack:r=!1}=i,s=e.split(","),o=i[`${s[0]}len`]||1,a=i[`${s[1]}len`]||1,c=i[`n${s[0]}`]||1,h=i[`n${s[1]}`]||1,u=(c+1)*(h+1),d=new Float32Array(u*3),l=new Float32Array(u*3),f=new Float32Array(u*2);n&&(o=-o);let m=0,p=0;for(let y=0;y<=h;y++)for(let I=0;I<=c;I++){let g=I/c,x=y/h;switch(f[m+0]=n?1-g:g,f[m+1]=x,e){case"x,y":d[p+0]=o*g-o*.5,d[p+1]=a*x-a*.5,d[p+2]=t,l[p+0]=0,l[p+1]=0,l[p+2]=n?1:-1;break;case"x,z":d[p+0]=o*g-o*.5,d[p+1]=t,d[p+2]=a*x-a*.5,l[p+0]=0,l[p+1]=n?1:-1,l[p+2]=0;break;case"y,z":d[p+0]=t,d[p+1]=o*g-o*.5,d[p+2]=a*x-a*.5,l[p+0]=n?1:-1,l[p+1]=0,l[p+2]=0;break;default:throw new Error("PlaneGeometry: unknown type")}m+=2,p+=3}let b=c+1,_=new Uint16Array(c*h*6);for(let y=0;y<h;y++)for(let I=0;I<c;I++){let g=(y*c+I)*6;_[g+0]=(y+0)*b+I,_[g+1]=(y+1)*b+I,_[g+2]=(y+0)*b+I+1,_[g+3]=(y+1)*b+I,_[g+4]=(y+1)*b+I+1,_[g+5]=(y+0)*b+I+1}let M={indices:{size:1,value:_},attributes:{POSITION:{size:3,value:d},NORMAL:{size:3,value:l},TEXCOORD_0:{size:2,value:f}}};return r?cn(M):M}function Cr(){let i=1,e=1;return()=>(i=Math.sin(e*17.23),e=Math.cos(i*27.92),Ea(Math.abs(i*e)*1432.71))}function Ea(i){return i-Math.floor(i)}var Or="";function Rr(i){Or=i}function Zt(i){return Ca(i)?i:Or+i}async function kr(i,e){let t=new Image,n=Zt(i);t.crossOrigin=e?.crossOrigin||"anonymous",t.src=n;try{await t.decode()}catch(r){throw Lr("decode",n,r)}try{return e?await createImageBitmap(t,e):await createImageBitmap(t)}catch(r){throw Lr("create",n,r)}}async function Nr(i,e){return await new Promise((t,n)=>{try{let r=new Image,s=Zt(i);r.onload=()=>t(r),r.onerror=()=>n(new Error(`Could not load image ${s}.`)),r.crossOrigin=e?.crossOrigin||"anonymous",r.src=s}catch(r){n(r)}})}function Lr(i,e,t){let n=t instanceof Error?t.message:String(t),r=i==="decode"?`Could not decode source image "${e}": ${n}`:`Could not create ImageBitmap from decoded image "${e}": ${n}`;return new Error(r,{cause:t})}function Ca(i){return i.startsWith("/")||/^[a-z][a-z\d+\-.]*:/i.test(i)}var Ie=R(N(),1);var Qt=class{device;id;destroyed=!1;generation=0;_source;_colorSpace;_sampler;_isReady=!1;_updateTimestamp;_sourceVersion=0;_sourceFrameToken=null;_texture=null;_textureFrameToken=void 0;_externalTexture=null;get source(){return this._source}get isReady(){return this._observeSource(),this._isReady}get updateTimestamp(){return this._observeSource(),this._updateTimestamp}get[Symbol.toStringTag](){return"VideoTexture"}toString(){let e=Yi(this._source);return`VideoTexture:"${this.id}":${e.width}x${e.height}px:(${this._isReady?"ready":"loading..."})`}constructor(e,t){(0,Ie.assert)(Qe(t?.source)||Dr(t?.source)),this.device=e,this.id=t.id||O("video-texture"),this._source=t.source,this._colorSpace=t.colorSpace??"srgb",this._sampler=t.sampler??{},this._updateTimestamp=this.device.incrementTimestamp(),this.setSource(t.source)}setSource(e){(0,Ie.assert)(Qe(e)||Dr(e)),this._destroyExternalTexture(),this._source=e,this._sourceVersion++,this._sourceFrameToken=null,this._textureFrameToken=void 0,this._observeSource(),this._touchGeneration()}resolveTextureBinding(e){return this._observeSource(),!this._isReady||this.destroyed?null:e.type==="external-texture"&&this.device.type==="webgpu"?this._createNativeExternalTexture():this._resolveCopiedTexture()}setSampler(e){this._sampler=e,this._texture?.setSampler(e),this._externalTexture?.setSampler?.(e),this._touchGeneration()}destroy(){this.destroyed||(this._destroyExternalTexture(),this._texture?.destroy(),this._texture=null,this._textureFrameToken=void 0,this._isReady=!1,this.destroyed=!0,this._touchGeneration())}_resolveCopiedTexture(){let e=this._getOrCreateCopiedTexture();return Object.is(this._textureFrameToken,this._sourceFrameToken)||(e.copyExternalImage({image:this._source,colorSpace:this._colorSpace}),this._textureFrameToken=this._sourceFrameToken),e}_getOrCreateCopiedTexture(){let e=this._getResolvedSize(),t=this._texture;if(t&&t.width===e.width&&t.height===e.height)return t;t?.destroy();let n=this.device.createTexture({id:`${this.id}-texture`,width:e.width,height:e.height,format:"rgba8unorm",usage:Ie.Texture.SAMPLE|Ie.Texture.COPY_DST,mipLevels:1,sampler:this._sampler});return this._texture=n,this._textureFrameToken=void 0,this._touchGeneration(),n}_createNativeExternalTexture(){return this._destroyExternalTexture(),this._externalTexture=this.device.createExternalTexture({id:`${this.id}-external`,source:this._source,colorSpace:this._colorSpace,sampler:this._sampler}),this.generation++,this._externalTexture}_destroyExternalTexture(){this._externalTexture?.destroy(),this._externalTexture=null}_getResolvedSize(){let e=Yi(this._source);return(0,Ie.assert)(e.width>0&&e.height>0),e}_observeSource(){if(this.destroyed)return;let e=La(this._source);if(e!==this._isReady&&(this._isReady=e,this._touch()),!e)return;let t=Oa(this._source,this._sourceVersion);Object.is(t,this._sourceFrameToken)||(this._sourceFrameToken=t,this._touch())}_touch(){this._updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}};function Qe(i){return!i||typeof i!="object"?!1:typeof HTMLVideoElement<"u"&&i instanceof HTMLVideoElement||"videoWidth"in i&&"videoHeight"in i&&"readyState"in i&&"currentTime"in i}function Dr(i){return!i||typeof i!="object"?!1:typeof VideoFrame<"u"&&i instanceof VideoFrame||"displayWidth"in i&&"displayHeight"in i&&"timestamp"in i&&!("videoWidth"in i)}function La(i){let e=Yi(i);return e.width<=0||e.height<=0?!1:Qe(i)?i.readyState>=2:!0}function Yi(i){return Qe(i)?{width:i.videoWidth,height:i.videoHeight}:{width:i.displayWidth,height:i.displayHeight}}function Oa(i,e){return Qe(i)?`${e}:${i.currentTime}:${i.videoWidth}x${i.videoHeight}`:`${e}:${i.timestamp}:${i.displayWidth}x${i.displayHeight}`}var oe=R(N(),1),Vr=R(ce(),1);var se=R(N(),1),ze=class{id;current;next;constructor(e){this.id=e.id||"swap",this.current=e.current,this.next=e.next}destroy(){this.current?.destroy(),this.next?.destroy()}swap(){let e=this.current;this.current=this.next,this.next=e}},je=class extends ze{constructor(e,t){t={...t};let{width:n=1,height:r=1}=t,s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-0`,format:c,usage:se.Texture.SAMPLE|se.Texture.RENDER|se.Texture.COPY_SRC|se.Texture.COPY_DST,width:n,height:r})),o=e.createFramebuffer({...t,colorAttachments:s});s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-1`,format:c,usage:se.Texture.SAMPLE|se.Texture.RENDER|se.Texture.COPY_SRC|se.Texture.COPY_DST,width:n,height:r}));let a=e.createFramebuffer({...t,colorAttachments:s});super({current:o,next:a});for(let[c,h]of(t.colorAttachments||[]).entries())typeof h=="string"&&(o.attachResource(o.colorAttachments[c].texture),a.attachResource(a.colorAttachments[c].texture))}resize(e){if(e.width===this.current.width&&e.height===this.current.height)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),Br(this.current),t.destroy(),this.next=n.clone(e),Br(this.next),n.destroy(),!0}};function Br(i){for(let e of i.colorAttachments)i.attachResource(e.texture);i.depthStencilAttachment&&i.attachResource(i.depthStencilAttachment.texture)}var Jt=class extends ze{constructor(e,t){super({current:e.createBuffer(t),next:e.createBuffer(t)})}resize(e){if(e.byteLength===this.current.byteLength)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),t.destroy(),this.next=n.clone(e),n.destroy(),!0}};var B=R(N(),1),me=R(ce(),1);var Wi=2,Ra=1e4,Ge=class i{static defaultProps={...B.ComputePipeline.defaultProps,id:"unnamed",handle:void 0,userData:{},source:"",modules:[],defines:{},plugins:[],bindings:void 0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,shaderAssembler:me.ShaderAssembler.getDefaultShaderAssembler("wgsl"),debugShaders:void 0};device;id;pipelineFactory;shaderFactory;userData={};bindings={};pipeline;source;shader;shaderInputs;_uniformStore;_pipelineNeedsUpdate="newly created";_getModuleUniforms;props;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Computation is only supported in WebGPU");this.props={...i.defaultProps,...t},t=this.props,this.id=t.id||O("model"),this.device=e,Object.assign(this.userData,t.userData);let n=ka(e),r=(0,me.resolveShaderPlugins)(this.props.plugins,n.shaderLanguage);if(Object.keys(r.vertexInputs).length>0||Object.keys(r.varyings).length>0)throw new Error("Computation does not support ShaderPlugin vertex inputs or varyings");let s=(0,me.mergeShaderPluginModules)(this.props.modules,r.modules),o=Object.fromEntries(s.map(m=>[m.name,m]));this.shaderInputs=t.shaderInputs||new X(o),t.shaderInputs&&r.modules.length>0&&this.shaderInputs.addModules(r.modules),this.setShaderInputs(this.shaderInputs);let a=Lt(this.props.modules,this.shaderInputs?.getModules()),c={...r.defines,...this.props.defines};this.props.shaderLayout=Oe(this.props.shaderLayout,a)||null,this.pipelineFactory=t.pipelineFactory||B.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||B.ShaderFactory.getDefaultShaderFactory(this.device);let h=this.props.shaderAssembler;(0,B.assert)(h instanceof me.WGSLShaderAssembler);let{source:u,getUniforms:d,shaderLayout:l}=h.assembleWGSLShader({platformInfo:n,...this.props,modules:a,defines:c,scanVertexAttributes:!1,pluginInjections:r.injections});this.source=u,this._getModuleUniforms=d;let f=l??e.getShaderLayout?.(this.source,{scanVertexAttributes:!1});this.props.shaderLayout=Oe(this.props.shaderLayout||f||null,a)||null,this.pipeline=this._updatePipeline(),t.bindings&&this.setBindings(t.bindings)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._uniformStore.destroy(),this._destroyed=!0)}predraw(e){this.updateShaderInputs(e)}dispatch(e,t,n,r){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatch(t,n,r)}finally{this._logDrawCallEnd()}}dispatchIndirect(e,t,n=0){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatchIndirect(t,n)}finally{this._logDrawCallEnd()}}_setPipeline(e){this.pipeline=this._updatePipeline(),this.pipeline.setBindings(this.bindings),e.setPipeline(this.pipeline),e.setBindings({})}setVertexCount(e){}setInstanceCount(e){}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new B.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(Re(n)){let r=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=r}}setShaderModuleProps(e){let t=this._getModuleUniforms(e),n=Object.keys(t).filter(s=>{let o=t[s];return!He(o)&&typeof o!="number"&&typeof o!="boolean"}),r={};for(let s of n)r[s]=t[s],delete t[s]}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e)}setBindings(e){Object.assign(this.bindings,e)}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate=this._pipelineNeedsUpdate||e}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null;this.pipeline&&(B.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.shader),this._pipelineNeedsUpdate=!1,this.shader=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"compute",source:this.source,debugShaders:this.props.debugShaders}),this.pipeline=this.pipelineFactory.createComputePipeline({...this.props,shader:this.shader}),e&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=B.log.level>3?0:Ra;B.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,B.log.group(Wi,`>>> DRAWING MODEL ${this.id}`,{collapsed:B.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=this.shaderInputs.getDebugTable();B.log.table(Wi,e)(),B.log.groupEnd(Wi)(),this._logOpen=!1}}_drawCount=0;_getBufferOrConstantValues(e,t){let n=B.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof B.Buffer?new n(e.debugData):e).toString()}};function ka(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,limits:i.limits,features:i.features}}function Fr(i){let{shaderPass:e,action:t,shadingLanguage:n}=i;switch(t){case"filter":let r=`${e.name}_filterColor_ext`;return n==="wgsl"?Na(r):Ba(r);case"sample":let s=`${e.name}_sampleColor`;return n==="wgsl"?Da(s):Fa(s);default:throw new Error(`${e.name} no fragment shader generated for shader pass`)}}function Na(i){return`@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;
|
|
174
|
+
`}}function Ze(i,e,t){return Math.min(t,Math.max(e,i))}var sa=new Fe({nlat:8,nlong:12,radius:1}),zt=class extends le{constructor(e,t){super(e,t,{anchorMode:"centered",buildInstanceData:Ir,geometry:sa,idPrefix:"point-light-model",sizePropNames:["pointLightRadius"]})}};var oa={x:[2,0,1],y:[0,1,2],z:[1,2,0]},de=class extends z{constructor(e={}){let{id:t=O("truncated-code-geometry")}=e,{indices:n,attributes:r}=aa(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{POSITION:{size:3,value:r.POSITION},NORMAL:{size:3,value:r.NORMAL},TEXCOORD_0:{size:2,value:r.TEXCOORD_0},...e.attributes}})}};function aa(i={}){let{bottomRadius:e=0,topRadius:t=0,height:n=1,nradial:r=10,nvertical:s=10,verticalAxis:o="y",topCap:a=!1,bottomCap:c=!1}=i,h=(a?2:0)+(c?2:0),u=(r+1)*(s+1+h),d=Math.atan2(e-t,n),l=Math.sin,f=Math.cos,m=Math.PI,p=f(d),b=l(d),_=a?-2:0,M=s+(c?2:0),y=r+1,I=new Uint16Array(r*(s+h)*6),g=oa[o],x=new Float32Array(u*3),v=new Float32Array(u*3),w=new Float32Array(u*2),T=0,C=0;for(let S=_;S<=M;S++){let A=S/s,L=n*A,E;S<0?(L=0,A=1,E=e):S>s?(L=n,A=1,E=t):E=e+(t-e)*(S/s),(S===-2||S===s+2)&&(E=0,A=0),L-=n/2;for(let U=0;U<y;U++){let te=l(U*m*2/r),q=f(U*m*2/r);x[T+g[0]]=te*E,x[T+g[1]]=L,x[T+g[2]]=q*E,v[T+g[0]]=S<0||S>s?0:te*p,v[T+g[1]]=S<0?-1:S>s?1:b,v[T+g[2]]=S<0||S>s?0:q*p,w[C+0]=U/r,w[C+1]=A,C+=2,T+=3}}for(let S=0;S<s+h;S++)for(let A=0;A<r;A++){let L=(S*r+A)*6;I[L+0]=y*(S+0)+0+A,I[L+1]=y*(S+0)+1+A,I[L+2]=y*(S+1)+1+A,I[L+3]=y*(S+0)+0+A,I[L+4]=y*(S+1)+1+A,I[L+5]=y*(S+1)+0+A}return{indices:I,attributes:{POSITION:x,NORMAL:v,TEXCOORD_0:w}}}var fe=class extends de{constructor(e={}){let{id:t=O("cone-geometry"),radius:n=1,cap:r=!0}=e;super({...e,id:t,topRadius:0,topCap:!!r,bottomCap:!!r,bottomRadius:n})}};var ca=new fe({cap:!0,nradial:16,nvertical:1,radius:1}),jt=class extends le{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:vr,geometry:ca,idPrefix:"spot-light-model",sizePropNames:["spotLightLength"]})}};var ha=new fe({cap:!0,nradial:12,nvertical:1,radius:1}),Gt=class extends le{constructor(e,t){super(e,t,{anchorMode:"apex",buildInstanceData:Mr,geometry:ha,idPrefix:"directional-light-model",sizePropNames:["directionalLightLength"]})}};function Ui(i,e){if(!i)throw new Error(e)}var se=class{id;matrix=new k;display=!0;position=new H;rotation=new H;scale=new H(1,1,1);userData={};props={};constructor(e={}){let{id:t}=e;this.id=t||O(this.constructor.name),this._setScenegraphNodeProps(e)}getBounds(){return null}destroy(){}delete(){this.destroy()}setProps(e){return this._setScenegraphNodeProps(e),this}toString(){return`{type: ScenegraphNode, id: ${this.id})}`}setPosition(e){return Ui(e.length===3,"setPosition requires vector argument"),this.position=e,this}setRotation(e){return Ui(e.length===3||e.length===4,"setRotation requires vector argument"),this.rotation=e,this}setScale(e){return Ui(e.length===3,"setScale requires vector argument"),this.scale=e,this}setMatrix(e,t=!0){t?this.matrix.copy(e):this.matrix=e}setMatrixComponents(e){let{position:t,rotation:n,scale:r,update:s=!0}=e;return t&&this.setPosition(t),n&&this.setRotation(n),r&&this.setScale(r),s&&this.updateMatrix(),this}updateMatrix(){if(this.matrix.identity(),this.matrix.translate(this.position),this.rotation.length===4){let e=new k().fromQuaternion(this.rotation);this.matrix.multiplyRight(e)}else this.matrix.rotateXYZ(this.rotation);return this.matrix.scale(this.scale),this}update({position:e,rotation:t,scale:n}={}){return e&&this.setPosition(e),t&&this.setRotation(t),n&&this.setScale(n),this.updateMatrix(),this}getCoordinateUniforms(e,t){t=t||this.matrix;let n=new k(e).multiplyRight(t),r=n.invert(),s=r.transpose();return{viewMatrix:e,modelMatrix:t,objectMatrix:t,worldMatrix:n,worldInverseMatrix:r,worldInverseTransposeMatrix:s}}_setScenegraphNodeProps(e){e.display!==void 0&&(this.display=e.display),e?.position&&this.setPosition(e.position),e?.rotation&&this.setRotation(e.rotation),e?.scale&&this.setScale(e.scale),this.updateMatrix(),e?.matrix&&this.setMatrix(e.matrix),Object.assign(this.props,e)}};var Sr=R(N(),1);function Ut(){return[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]]}function $t(i,e,t){let n=new k(t);for(let r=0;r<8;r++){let s=new H(e[r&1?1:0][0],e[r&2?1:0][1],e[r&4?1:0][2]);n.transformAsPoint(s,s);for(let o=0;o<3;o++)i[0][o]=Math.min(i[0][o],s[o]),i[1][o]=Math.max(i[1][o],s[o])}}function Vt(i){return Number.isFinite(i[0][0])}var Xt=class i extends se{children;constructor(e={}){e=Array.isArray(e)?{children:e}:e;let{children:t=[]}=e;Sr.log.assert(t.every(n=>n instanceof se),"every child must an instance of ScenegraphNode"),super(e),this.children=t}getBounds(){let e=Ut();return this.traverse((t,{worldMatrix:n})=>{let r=t.getBounds();if(!r)return;let s=new k(n).multiplyRight(t.matrix);$t(e,r,s)}),Vt(e)?e:null}destroy(){this.children.forEach(e=>e.destroy()),this.removeAll(),super.destroy()}add(...e){for(let t of e)Array.isArray(t)?this.add(...t):this.children.push(t);return this}remove(e){let t=this.children,n=t.indexOf(e);return n>-1&&t.splice(n,1),this}removeAll(){return this.children=[],this}traverse(e,{worldMatrix:t=new k}={}){if(!this.display)return;let n=new k(t).multiplyRight(this.matrix);for(let r of this.children)r.display&&(r instanceof i?r.traverse(e,{worldMatrix:n}):e(r,{worldMatrix:n}))}traverseDepthSorted(e,{viewMatrix:t,worldMatrix:n=new k,order:r="back-to-front"}){let s=new k(t),o=[];this.traverse((c,h)=>{let u=c.getBounds(),d=u?new H(u[0]).add(u[1]).divide([2,2,2]):new H,l=new k(h.worldMatrix).multiplyRight(c.matrix);l.transformAsPoint(d,d),s.transformAsPoint(d,d),o.push({node:c,context:{worldMatrix:l,bounds:u,depth:-d[2]},index:o.length})},{worldMatrix:new k(n)});let a=r==="back-to-front"?-1:1;o.sort((c,h)=>a*(c.context.depth-h.context.depth)||c.index-h.index);for(let{node:c,context:h}of o)e(c,h)}preorderTraversal(e,{worldMatrix:t=new k}={}){let n=new k(t).multiplyRight(this.matrix);e(this,{worldMatrix:n});for(let r of this.children)r instanceof i?r.preorderTraversal(e,{worldMatrix:n}):e(r,{worldMatrix:n})}};var Ht=class extends se{model;instanceMatrices;bounds=null;managedResources;constructor(e){super(e),this.model=e.model,this.managedResources=e.managedResources||[],this.instanceMatrices=e.instanceMatrices||null,this.bounds=e.bounds?this.instanceMatrices?ua(e.bounds,this.instanceMatrices):e.bounds:null,this.setProps(e)}destroy(){this.model&&(this.model.destroy(),this.model=null),this.managedResources.forEach(e=>e.destroy()),this.managedResources=[]}getBounds(){return this.bounds}draw(e){return this.model.draw(e)}};function ua(i,e){let t=Ut();for(let n of e)$t(t,i,n);return Vt(t)?t:null}var Xi=R(N(),1),Pr=10,la=1e-10;function Lr(i){let{positions:e,indices:t,attributes:n=[],preserveBoundary:r=!0}=i;(0,Xi.assert)(t.length%3===0&&e.length%3===0);let s=Math.max(0,Math.min(t.length,Math.floor((i.targetIndexCount??t.length*(i.targetRatio??.5))/3)*3));if(t.length===0||s>=t.length)return{indices:t.slice(),geometricError:0};let o=e.length/3,a=Array.from({length:o},()=>({quadric:new Float64Array(Pr),neighbors:new Set,boundaryNeighbors:new Set,triangles:new Set,active:!1,version:0})),c=[],h=new Map,u=new Map,d=new Yi,l=0,f=0,m=(g,x,v)=>{let w=Math.min(g,x),T=Math.max(g,x),C=w*o+T,A=(h.get(C)||0)+v;A<=0?(h.delete(C),a[g].neighbors.delete(x),a[x].neighbors.delete(g)):(h.set(C,A),a[g].neighbors.add(x),a[x].neighbors.add(g)),A===1?(a[g].boundaryNeighbors.add(x),a[x].boundaryNeighbors.add(g)):(a[g].boundaryNeighbors.delete(x),a[x].boundaryNeighbors.delete(g))},p=g=>{let x=c[g];if(!x.active)return;let[v,w,T]=x.vertices;u.delete(Cr(v,w,T)),m(v,w,-1),m(w,T,-1),m(T,v,-1),a[v].triangles.delete(g),a[w].triangles.delete(g),a[T].triangles.delete(g),x.active=!1,l--},b=g=>{let x=c[g],[v,w,T]=x.vertices;if(v===w||w===T||T===v)return!1;let C=Cr(v,w,T);return u.has(C)?!1:(u.set(C,g),m(v,w,1),m(w,T,1),m(T,v,1),a[v].triangles.add(g),a[w].triangles.add(g),a[T].triangles.add(g),a[v].active=!0,a[w].active=!0,a[T].active=!0,x.active=!0,l++,!0)};for(let g=0;g<t.length;g+=3){let x=t[g],v=t[g+1],w=t[g+2];(0,Xi.assert)(x<o&&v<o&&w<o);let T={vertices:[x,v,w],active:!1},C=c.push(T)-1;b(C)&&da(a,e,x,v,w)}let _=(g,x)=>{if(!a[g].active||!a[x].active)return;let v=ma(n,g,x);if(Number.isFinite(v))for(let[w,T]of[[g,x],[x,g]]){if(r&&!Er(a,e,w,T))continue;let C=Math.max(0,fa(a,e,g,x,w));d.add({retainedVertex:w,removedVertex:T,retainedVersion:a[w].version,removedVersion:a[T].version,geometricCost:C,cost:C+v})}};for(let g=0;g<a.length;g++)for(let x of a[g].neighbors)g<x&&_(g,x);for(;l*3>s;){let g=d.remove();if(!g)break;let{retainedVertex:x,removedVertex:v}=g,w=a[x],T=a[v];if(!w.active||!T.active||w.version!==g.retainedVersion||T.version!==g.removedVersion||!w.neighbors.has(v)||r&&!Er(a,e,x,v)||!pa(c,a,e,x,v))continue;let C=new Set([x,v,...w.neighbors,...T.neighbors]),S=[...T.triangles];for(let A of S)p(A);for(let A of S){let L=c[A];for(let E=0;E<3;E++)L.vertices[E]===v&&(L.vertices[E]=x);b(A)}for(let A=0;A<Pr;A++)w.quadric[A]+=T.quadric[A];T.active=!1,f=Math.max(f,g.geometricCost);for(let A of C)a[A].version++;for(let A of C)if(a[A].active)for(let L of a[A].neighbors)_(A,L)}let M=t.constructor,y=new M(l*3),I=0;for(let g of c)g.active&&(y[I++]=g.vertices[0],y[I++]=g.vertices[1],y[I++]=g.vertices[2]);return{indices:y,geometricError:Math.sqrt(f)}}function da(i,e,t,n,r){let s=Hi(e,t,n,r),o=Math.hypot(s[0],s[1],s[2]);if(o===0)return;let a=s[0]/o,c=s[1]/o,h=s[2]/o,u=-(a*e[t*3]+c*e[t*3+1]+h*e[t*3+2]),d=[a,c,h,u];for(let l of[t,n,r]){let f=0;for(let m=0;m<4;m++)for(let p=m;p<4;p++)i[l].quadric[f++]+=d[m]*d[p]}}function fa(i,e,t,n,r){let s=[e[r*3],e[r*3+1],e[r*3+2],1],o=0,a=0;for(let c=0;c<4;c++)for(let h=c;h<4;h++){let u=i[t].quadric[o]+i[n].quadric[o];a+=u*s[c]*s[h]*(c===h?1:2),o++}return a}function ma(i,e,t){let n=0;for(let r of i){let s=r.weight??1;if(s===0)continue;let o=r.values instanceof Uint8Array||r.values instanceof Uint16Array||r.values instanceof Uint32Array;for(let a=0;a<r.size;a++){let c=r.values[e*r.size+a]-r.values[t*r.size+a];if(o&&c!==0)return 1/0;n+=c*c*s}}return n}function Er(i,e,t,n){let r=i[t].boundaryNeighbors.size>0,s=i[n].boundaryNeighbors.size>0;if(r!==s)return!1;if(!s)return!0;let o=i[n].boundaryNeighbors;if(o.size!==2||!o.has(t))return!1;let a=[...o].find(m=>m!==t);if(a===void 0)return!1;let c=Yt(e,t,n),h=Yt(e,a,n),u=$i(c),d=$i(h),l=[c[1]*h[2]-c[2]*h[1],c[2]*h[0]-c[0]*h[2],c[0]*h[1]-c[1]*h[0]];return c[0]*h[0]+c[1]*h[1]+c[2]*h[2]<=0&&$i(l)<=la*u*d}function pa(i,e,t,n,r){for(let s of e[r].triangles){let o=i[s];if(o.vertices.includes(n))continue;let a=Hi(t,...o.vertices),c=o.vertices.map(d=>d===r?n:d),h=Hi(t,...c);if(a[0]*h[0]+a[1]*h[1]+a[2]*h[2]<=0)return!1}return!0}function Hi(i,e,t,n){let r=Yt(i,t,e),s=Yt(i,n,e);return[r[1]*s[2]-r[2]*s[1],r[2]*s[0]-r[0]*s[2],r[0]*s[1]-r[1]*s[0]]}function Yt(i,e,t){return[i[e*3]-i[t*3],i[e*3+1]-i[t*3+1],i[e*3+2]-i[t*3+2]]}function $i(i){return i[0]*i[0]+i[1]*i[1]+i[2]*i[2]}function Cr(i,e,t){return[i,e,t].sort((n,r)=>n-r).join(":")}var Yi=class{entries=[];add(e){this.entries.push(e);let t=this.entries.length-1;for(;t>0;){let n=t-1>>1;if(Vi(this.entries[n],e)<=0)break;this.entries[t]=this.entries[n],this.entries[n]=e,t=n}}remove(){let e=this.entries[0],t=this.entries.pop();if(!e||!t||this.entries.length===0)return e;this.entries[0]=t;let n=0;for(;;){let r=n*2+1;if(r>=this.entries.length)break;let s=r+1,o=s<this.entries.length&&Vi(this.entries[s],this.entries[r])<0?s:r;if(Vi(this.entries[n],this.entries[o])<=0)break;[this.entries[n],this.entries[o]]=[this.entries[o],this.entries[n]],n=o}return e}};function Vi(i,e){return i.cost-e.cost||i.retainedVertex-e.retainedVertex||i.removedVertex-e.removedVertex}var Wt=class extends z{constructor(e={}){let{id:t=O("cube-geometry"),indices:n=!0}=e;super(n?{...e,id:t,topology:"triangle-list",indices:{size:1,value:ga},attributes:{...wa,...e.attributes}}:{...e,id:t,topology:"triangle-list",indices:void 0,attributes:{...Aa,...e.attributes}})}},ga=new Uint16Array([0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]),xa=new Float32Array([-1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1]),ba=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0]),ya=new Float32Array([0,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1]),_a=new Uint32Array([0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5]),Ia=new Float32Array([1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,1,1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,1,-1,1,1,1,-1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1]),va=new Float32Array([1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0]),Ma=new Float32Array([1,0,1,1,0,0,1,1,0,0,0,1,1,0,0,1,1,0,1,1,0,0,0,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,1,0,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,0,1,1,0,0,1,1,1,0,1,1,1,1,1,1,1,0,0,1,0,0,0,1,0,1,0,1,1,1,0,1,1,0,0,1,0,1,0,1]),Ta=new Uint32Array([3,3,3,3,3,3,4,4,4,4,4,4,2,2,2,2,2,2,5,5,5,5,5,5,0,0,0,0,0,0,1,1,1,1,1,1]),wa={POSITION:{size:3,value:xa},NORMAL:{size:3,value:ba},TEXCOORD_0:{size:2,value:ya},faceIndex:{size:1,value:_a}},Aa={POSITION:{size:3,value:Ia},TEXCOORD_0:{size:2,value:va},COLOR_0:{size:3,value:Ma},faceIndex:{size:1,value:Ta}};var qt=class extends de{constructor(e={}){let{id:t=O("cylinder-geometry"),radius:n=1}=e;super({...e,id:t,bottomRadius:n,topRadius:n})}};var Sa=[-1,0,0,0,1,0,0,0,-1,0,0,1,0,-1,0,1,0,0],Pa=[3,4,5,3,5,1,3,1,0,3,0,4,4,0,2,4,2,5,2,0,1,5,2,1],Kt=class extends z{constructor(e={}){let{id:t=O("ico-sphere-geometry")}=e,{indices:n,attributes:r}=Ea(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function Ea(i){let{iterations:e=0}=i,t=Math.PI,n=t*2,r=[...Sa],s=[...Pa];r.push(),s.push();let o=(()=>{let u={};return(d,l)=>{d*=3,l*=3;let f=d<l?d:l,m=d>l?d:l,p=`${f}|${m}`;if(p in u)return u[p];let b=r[d],_=r[d+1],M=r[d+2],y=r[l],I=r[l+1],g=r[l+2],x=(b+y)/2,v=(_+I)/2,w=(M+g)/2,T=Math.sqrt(x*x+v*v+w*w);x/=T,v/=T,w/=T,r.push(x,v,w);let C=r.length/3-1;return u[p]=C,C}})();for(let u=0;u<e;u++){let d=[];for(let l=0;l<s.length;l+=3){let f=o(s[l+0],s[l+1]),m=o(s[l+1],s[l+2]),p=o(s[l+2],s[l+0]);d.push(p,s[l+0],f,f,s[l+1],m,m,s[l+2],p,f,m,p)}s=d}let a=new Array(r.length),c=new Array(r.length/3*2),h=s.length;for(let u=h-3;u>=0;u-=3){let d=s[u+0],l=s[u+1],f=s[u+2],m=d*3,p=l*3,b=f*3,_=d*2,M=l*2,y=f*2,I=r[m+0],g=r[m+1],x=r[m+2],v=Math.acos(x/Math.sqrt(I*I+g*g+x*x)),w=Math.atan2(g,I)+t,T=v/t,C=1-w/n,S=r[p+0],A=r[p+1],L=r[p+2],E=Math.acos(L/Math.sqrt(S*S+A*A+L*L)),U=Math.atan2(A,S)+t,te=E/t,q=1-U/n,nt=r[b+0],rt=r[b+1],st=r[b+2],rs=Math.acos(st/Math.sqrt(nt*nt+rt*rt+st*st)),ss=Math.atan2(rt,nt)+t,nn=rs/t,ot=1-ss/n,os=[nt-S,rt-A,st-L],as=[I-S,g-A,x-L],W=new H(os).cross(as).normalize(),F;(C===0||q===0||ot===0)&&(C===0||C>.5)&&(q===0||q>.5)&&(ot===0||ot>.5)&&(r.push(r[m+0],r[m+1],r[m+2]),F=r.length/3-1,s.push(F),c[F*2+0]=1,c[F*2+1]=T,a[F*3+0]=W.x,a[F*3+1]=W.y,a[F*3+2]=W.z,r.push(r[p+0],r[p+1],r[p+2]),F=r.length/3-1,s.push(F),c[F*2+0]=1,c[F*2+1]=te,a[F*3+0]=W.x,a[F*3+1]=W.y,a[F*3+2]=W.z,r.push(r[b+0],r[b+1],r[b+2]),F=r.length/3-1,s.push(F),c[F*2+0]=1,c[F*2+1]=nn,a[F*3+0]=W.x,a[F*3+1]=W.y,a[F*3+2]=W.z),a[m+0]=a[p+0]=a[b+0]=W.x,a[m+1]=a[p+1]=a[b+1]=W.y,a[m+2]=a[p+2]=a[b+2]=W.z,c[_+0]=C,c[_+1]=T,c[M+0]=q,c[M+1]=te,c[y+0]=ot,c[y+1]=nn}return{indices:{size:1,value:new Uint16Array(s)},attributes:{POSITION:{size:3,value:new Float32Array(r)},NORMAL:{size:3,value:new Float32Array(a)},TEXCOORD_0:{size:2,value:new Float32Array(c)}}}}var Zt=class extends z{constructor(e={}){let{id:t=O("plane-geometry")}=e,{indices:n,attributes:r}=Ca(e);super({...e,id:t,topology:"triangle-list",indices:n,attributes:{...r,...e.attributes}})}};function Ca(i){let{type:e="x,y",offset:t=0,flipCull:n=!1,unpack:r=!1}=i,s=e.split(","),o=i[`${s[0]}len`]||1,a=i[`${s[1]}len`]||1,c=i[`n${s[0]}`]||1,h=i[`n${s[1]}`]||1,u=(c+1)*(h+1),d=new Float32Array(u*3),l=new Float32Array(u*3),f=new Float32Array(u*2);n&&(o=-o);let m=0,p=0;for(let y=0;y<=h;y++)for(let I=0;I<=c;I++){let g=I/c,x=y/h;switch(f[m+0]=n?1-g:g,f[m+1]=x,e){case"x,y":d[p+0]=o*g-o*.5,d[p+1]=a*x-a*.5,d[p+2]=t,l[p+0]=0,l[p+1]=0,l[p+2]=n?1:-1;break;case"x,z":d[p+0]=o*g-o*.5,d[p+1]=t,d[p+2]=a*x-a*.5,l[p+0]=0,l[p+1]=n?1:-1,l[p+2]=0;break;case"y,z":d[p+0]=t,d[p+1]=o*g-o*.5,d[p+2]=a*x-a*.5,l[p+0]=n?1:-1,l[p+1]=0,l[p+2]=0;break;default:throw new Error("PlaneGeometry: unknown type")}m+=2,p+=3}let b=c+1,_=new Uint16Array(c*h*6);for(let y=0;y<h;y++)for(let I=0;I<c;I++){let g=(y*c+I)*6;_[g+0]=(y+0)*b+I,_[g+1]=(y+1)*b+I,_[g+2]=(y+0)*b+I+1,_[g+3]=(y+1)*b+I,_[g+4]=(y+1)*b+I+1,_[g+5]=(y+0)*b+I+1}let M={indices:{size:1,value:_},attributes:{POSITION:{size:3,value:d},NORMAL:{size:3,value:l},TEXCOORD_0:{size:2,value:f}}};return r?hn(M):M}function Or(){let i=1,e=1;return()=>(i=Math.sin(e*17.23),e=Math.cos(i*27.92),La(Math.abs(i*e)*1432.71))}function La(i){return i-Math.floor(i)}var kr="";function Nr(i){kr=i}function Qt(i){return Oa(i)?i:kr+i}async function Dr(i,e){let t=new Image,n=Qt(i);t.crossOrigin=e?.crossOrigin||"anonymous",t.src=n;try{await t.decode()}catch(r){throw Rr("decode",n,r)}try{return e?await createImageBitmap(t,e):await createImageBitmap(t)}catch(r){throw Rr("create",n,r)}}async function Br(i,e){return await new Promise((t,n)=>{try{let r=new Image,s=Qt(i);r.onload=()=>t(r),r.onerror=()=>n(new Error(`Could not load image ${s}.`)),r.crossOrigin=e?.crossOrigin||"anonymous",r.src=s}catch(r){n(r)}})}function Rr(i,e,t){let n=t instanceof Error?t.message:String(t),r=i==="decode"?`Could not decode source image "${e}": ${n}`:`Could not create ImageBitmap from decoded image "${e}": ${n}`;return new Error(r,{cause:t})}function Oa(i){return i.startsWith("/")||/^[a-z][a-z\d+\-.]*:/i.test(i)}var ve=R(N(),1);var Jt=class{device;id;destroyed=!1;generation=0;_source;_colorSpace;_sampler;_isReady=!1;_updateTimestamp;_sourceVersion=0;_sourceFrameToken=null;_texture=null;_textureFrameToken=void 0;_externalTexture=null;get source(){return this._source}get isReady(){return this._observeSource(),this._isReady}get updateTimestamp(){return this._observeSource(),this._updateTimestamp}get[Symbol.toStringTag](){return"VideoTexture"}toString(){let e=Wi(this._source);return`VideoTexture:"${this.id}":${e.width}x${e.height}px:(${this._isReady?"ready":"loading..."})`}constructor(e,t){(0,ve.assert)(Qe(t?.source)||Fr(t?.source)),this.device=e,this.id=t.id||O("video-texture"),this._source=t.source,this._colorSpace=t.colorSpace??"srgb",this._sampler=t.sampler??{},this._updateTimestamp=this.device.incrementTimestamp(),this.setSource(t.source)}setSource(e){(0,ve.assert)(Qe(e)||Fr(e)),this._destroyExternalTexture(),this._source=e,this._sourceVersion++,this._sourceFrameToken=null,this._textureFrameToken=void 0,this._observeSource(),this._touchGeneration()}resolveTextureBinding(e){return this._observeSource(),!this._isReady||this.destroyed?null:e.type==="external-texture"&&this.device.type==="webgpu"?this._createNativeExternalTexture():this._resolveCopiedTexture()}setSampler(e){this._sampler=e,this._texture?.setSampler(e),this._externalTexture?.setSampler?.(e),this._touchGeneration()}destroy(){this.destroyed||(this._destroyExternalTexture(),this._texture?.destroy(),this._texture=null,this._textureFrameToken=void 0,this._isReady=!1,this.destroyed=!0,this._touchGeneration())}_resolveCopiedTexture(){let e=this._getOrCreateCopiedTexture();return Object.is(this._textureFrameToken,this._sourceFrameToken)||(e.copyExternalImage({image:this._source,colorSpace:this._colorSpace}),this._textureFrameToken=this._sourceFrameToken),e}_getOrCreateCopiedTexture(){let e=this._getResolvedSize(),t=this._texture;if(t&&t.width===e.width&&t.height===e.height)return t;t?.destroy();let n=this.device.createTexture({id:`${this.id}-texture`,width:e.width,height:e.height,format:"rgba8unorm",usage:ve.Texture.SAMPLE|ve.Texture.COPY_DST,mipLevels:1,sampler:this._sampler});return this._texture=n,this._textureFrameToken=void 0,this._touchGeneration(),n}_createNativeExternalTexture(){return this._destroyExternalTexture(),this._externalTexture=this.device.createExternalTexture({id:`${this.id}-external`,source:this._source,colorSpace:this._colorSpace,sampler:this._sampler}),this.generation++,this._externalTexture}_destroyExternalTexture(){this._externalTexture?.destroy(),this._externalTexture=null}_getResolvedSize(){let e=Wi(this._source);return(0,ve.assert)(e.width>0&&e.height>0),e}_observeSource(){if(this.destroyed)return;let e=Ra(this._source);if(e!==this._isReady&&(this._isReady=e,this._touch()),!e)return;let t=ka(this._source,this._sourceVersion);Object.is(t,this._sourceFrameToken)||(this._sourceFrameToken=t,this._touch())}_touch(){this._updateTimestamp=this.device.incrementTimestamp()}_touchGeneration(){this.generation++,this._touch()}};function Qe(i){return!i||typeof i!="object"?!1:typeof HTMLVideoElement<"u"&&i instanceof HTMLVideoElement||"videoWidth"in i&&"videoHeight"in i&&"readyState"in i&&"currentTime"in i}function Fr(i){return!i||typeof i!="object"?!1:typeof VideoFrame<"u"&&i instanceof VideoFrame||"displayWidth"in i&&"displayHeight"in i&&"timestamp"in i&&!("videoWidth"in i)}function Ra(i){let e=Wi(i);return e.width<=0||e.height<=0?!1:Qe(i)?i.readyState>=2:!0}function Wi(i){return Qe(i)?{width:i.videoWidth,height:i.videoHeight}:{width:i.displayWidth,height:i.displayHeight}}function ka(i,e){return Qe(i)?`${e}:${i.currentTime}:${i.videoWidth}x${i.videoHeight}`:`${e}:${i.timestamp}:${i.displayWidth}x${i.displayHeight}`}var ae=R(N(),1),Hr=R(ne(),1);var oe=R(N(),1),ze=class{id;current;next;constructor(e){this.id=e.id||"swap",this.current=e.current,this.next=e.next}destroy(){this.current?.destroy(),this.next?.destroy()}swap(){let e=this.current;this.current=this.next,this.next=e}},je=class extends ze{constructor(e,t){t={...t};let{width:n=1,height:r=1}=t,s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-0`,format:c,usage:oe.Texture.SAMPLE|oe.Texture.RENDER|oe.Texture.COPY_SRC|oe.Texture.COPY_DST,width:n,height:r})),o=e.createFramebuffer({...t,colorAttachments:s});s=t.colorAttachments?.map(c=>typeof c!="string"?c:e.createTexture({id:`${t.id}-texture-1`,format:c,usage:oe.Texture.SAMPLE|oe.Texture.RENDER|oe.Texture.COPY_SRC|oe.Texture.COPY_DST,width:n,height:r}));let a=e.createFramebuffer({...t,colorAttachments:s});super({current:o,next:a});for(let[c,h]of(t.colorAttachments||[]).entries())typeof h=="string"&&(o.attachResource(o.colorAttachments[c].texture),a.attachResource(a.colorAttachments[c].texture))}resize(e){if(e.width===this.current.width&&e.height===this.current.height)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),zr(this.current),t.destroy(),this.next=n.clone(e),zr(this.next),n.destroy(),!0}};function zr(i){for(let e of i.colorAttachments)i.attachResource(e.texture);i.depthStencilAttachment&&i.attachResource(i.depthStencilAttachment.texture)}var ei=class extends ze{constructor(e,t){super({current:e.createBuffer(t),next:e.createBuffer(t)})}resize(e){if(e.byteLength===this.current.byteLength)return!1;let{current:t,next:n}=this;return this.current=t.clone(e),t.destroy(),this.next=n.clone(e),n.destroy(),!0}};var B=R(N(),1),me=R(ne(),1);var qi=2,Na=1e4,Ge=class i{static defaultProps={...B.ComputePipeline.defaultProps,id:"unnamed",handle:void 0,userData:{},source:"",modules:[],defines:{},plugins:[],bindings:void 0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,shaderAssembler:me.ShaderAssembler.getDefaultShaderAssembler("wgsl"),debugShaders:void 0};device;id;pipelineFactory;shaderFactory;userData={};bindings={};pipeline;source;shader;shaderInputs;_uniformStore;_pipelineNeedsUpdate="newly created";_getModuleUniforms;props;_destroyed=!1;constructor(e,t){if(e.type!=="webgpu")throw new Error("Computation is only supported in WebGPU");this.props={...i.defaultProps,...t},t=this.props,this.id=t.id||O("model"),this.device=e,Object.assign(this.userData,t.userData);let n=Da(e),r=(0,me.resolveShaderPlugins)(this.props.plugins,n.shaderLanguage);if(Object.keys(r.vertexInputs).length>0||Object.keys(r.varyings).length>0)throw new Error("Computation does not support ShaderPlugin vertex inputs or varyings");let s=(0,me.mergeShaderPluginModules)(this.props.modules,r.modules),o=Object.fromEntries(s.map(m=>[m.name,m]));this.shaderInputs=t.shaderInputs||new X(o),t.shaderInputs&&r.modules.length>0&&this.shaderInputs.addModules(r.modules),this.setShaderInputs(this.shaderInputs);let a=Ot(this.props.modules,this.shaderInputs?.getModules()),c={...r.defines,...this.props.defines};this.props.shaderLayout=Re(this.props.shaderLayout,a)||null,this.pipelineFactory=t.pipelineFactory||B.PipelineFactory.getDefaultPipelineFactory(this.device),this.shaderFactory=t.shaderFactory||B.ShaderFactory.getDefaultShaderFactory(this.device);let h=this.props.shaderAssembler;(0,B.assert)(h instanceof me.WGSLShaderAssembler);let{source:u,getUniforms:d,shaderLayout:l}=h.assembleWGSLShader({platformInfo:n,...this.props,modules:a,defines:c,scanVertexAttributes:!1,pluginInjections:r.injections});this.source=u,this._getModuleUniforms=d;let f=l??e.getShaderLayout?.(this.source,{scanVertexAttributes:!1});this.props.shaderLayout=Re(this.props.shaderLayout||f||null,a)||null,this.pipeline=this._updatePipeline(),t.bindings&&this.setBindings(t.bindings)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._uniformStore.destroy(),this._destroyed=!0)}predraw(e){this.updateShaderInputs(e)}dispatch(e,t,n,r){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatch(t,n,r)}finally{this._logDrawCallEnd()}}dispatchIndirect(e,t,n=0){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatchIndirect(t,n)}finally{this._logDrawCallEnd()}}_setPipeline(e){this.pipeline=this._updatePipeline(),this.pipeline.setBindings(this.bindings),e.setPipeline(this.pipeline),e.setBindings({})}setVertexCount(e){}setInstanceCount(e){}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new B.UniformStore(this.device,this.shaderInputs.modules);for(let[t,n]of Object.entries(this.shaderInputs.modules))if(be(n)){let r=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=r}}setShaderModuleProps(e){let t=this._getModuleUniforms(e),n=Object.keys(t).filter(s=>{let o=t[s];return!He(o)&&typeof o!="number"&&typeof o!="boolean"}),r={};for(let s of n)r[s]=t[s],delete t[s]}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e)}setBindings(e){Object.assign(this.bindings,e)}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate=this._pipelineNeedsUpdate||e}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null;this.pipeline&&(B.log.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.shader),this._pipelineNeedsUpdate=!1,this.shader=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"compute",source:this.source,debugShaders:this.props.debugShaders}),this.pipeline=this.pipelineFactory.createComputePipeline({...this.props,shader:this.shader}),e&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){let e=B.log.level>3?0:Na;B.log.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,B.log.group(qi,`>>> DRAWING MODEL ${this.id}`,{collapsed:B.log.level<=2})())}_logDrawCallEnd(){if(this._logOpen){let e=this.shaderInputs.getDebugTable();B.log.table(qi,e)(),B.log.groupEnd(qi)(),this._logOpen=!1}}_drawCount=0;_getBufferOrConstantValues(e,t){let n=B.dataTypeDecoder.getTypedArrayConstructor(t);return(e instanceof B.Buffer?new n(e.debugData):e).toString()}};function Da(i){return{type:i.type,shaderLanguage:i.info.shadingLanguage,shaderLanguageVersion:i.info.shadingLanguageVersion,gpu:i.info.gpu,limits:i.limits,features:i.features}}function jr(i){let{shaderPass:e,action:t,shadingLanguage:n}=i;switch(t){case"filter":let r=`${e.name}_filterColor_ext`;return n==="wgsl"?Ba(r):za(r);case"sample":let s=`${e.name}_sampleColor`;return n==="wgsl"?Fa(s):ja(s);default:throw new Error(`${e.name} no fragment shader generated for shader pass`)}}function Ba(i){return`@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;
|
|
175
175
|
@group(0) @binding(auto) var sourceTextureSampler: sampler;
|
|
176
176
|
|
|
177
177
|
@fragment
|
|
@@ -183,7 +183,7 @@ fn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4f {
|
|
|
183
183
|
fragColor = ${i}(fragColor, texSize, texCoord);
|
|
184
184
|
return fragColor;
|
|
185
185
|
}
|
|
186
|
-
`}function
|
|
186
|
+
`}function Fa(i){return`@group(0) @binding(auto) var sourceTexture: texture_2d<f32>;
|
|
187
187
|
@group(0) @binding(auto) var sourceTextureSampler: sampler;
|
|
188
188
|
|
|
189
189
|
@fragment
|
|
@@ -192,7 +192,7 @@ fn fragmentMain(inputs: FragmentInputs) -> @location(0) vec4f {
|
|
|
192
192
|
let texSize = vec2f(textureDimensions(sourceTexture));
|
|
193
193
|
return ${i}(sourceTexture, sourceTextureSampler, texSize, texCoord);
|
|
194
194
|
}
|
|
195
|
-
`}function
|
|
195
|
+
`}function za(i){return`#version 300 es
|
|
196
196
|
|
|
197
197
|
uniform sampler2D sourceTexture;
|
|
198
198
|
|
|
@@ -210,7 +210,7 @@ void main() {
|
|
|
210
210
|
fragColor = texture(sourceTexture, texCoord);
|
|
211
211
|
fragColor = ${i}(fragColor, texSize, texCoord);
|
|
212
212
|
}
|
|
213
|
-
`}function
|
|
213
|
+
`}function ja(i){return`#version 300 es
|
|
214
214
|
|
|
215
215
|
uniform sampler2D sourceTexture;
|
|
216
216
|
|
|
@@ -227,7 +227,7 @@ void main() {
|
|
|
227
227
|
|
|
228
228
|
fragColor = ${i}(sourceTexture, texSize, texCoord);
|
|
229
229
|
}
|
|
230
|
-
`}var
|
|
230
|
+
`}var Gr={name:"textureTransform",source:`
|
|
231
231
|
struct textureTransformUniforms {
|
|
232
232
|
scale: vec2<f32>,
|
|
233
233
|
flipY: i32,
|
|
@@ -264,7 +264,7 @@ vec2 shaderPassRenderer_getRenderTargetUV(vec2 textureUV) {
|
|
|
264
264
|
vec2 unscaledCoord = (textureUV - 0.5) * textureTransform.scale + 0.5;
|
|
265
265
|
return textureTransform.flipY != 0 ? unscaledCoord : vec2(unscaledCoord.x, 1.0 - unscaledCoord.y);
|
|
266
266
|
}
|
|
267
|
-
`,uniformTypes:{scale:"vec2<f32>",flipY:"i32"}};var za=new Set(["original","previous"]),ei=class{device;shaderInputs;passRenderers;swapFramebuffers;textureModel;constructor(e,t){this.device=e;let n=ja(t.shaderPasses);n.map(a=>(0,Vr.initializeShaderModule)(a));let r=n.reduce((a,c)=>({...a,[c.name]:c}),{});this.shaderInputs=t.shaderInputs||new X(r);let s=e.getCanvasContext().getDrawingBufferSize();this.swapFramebuffers=new je(e,{colorAttachments:[t.colorFormat||e.preferredColorFormat],width:s[0],height:s[1]}),this.textureModel=new Be(e,{backgroundTexture:this.swapFramebuffers.current.colorAttachments[0].texture,flipY:t.flipY??e.type==="webgpu"});let o=t.flipY??e.type==="webgpu";this.passRenderers=t.shaderPasses.map(a=>new qi(e,a,this.shaderInputs,o))}destroy(){for(let e of this.passRenderers)e.destroy();this.swapFramebuffers.destroy(),this.textureModel.destroy()}resize(e){e||=this.device.getCanvasContext().getDrawingBufferSize(),this.swapFramebuffers.resize({width:e[0],height:e[1]});for(let t of this.passRenderers)t.resize(e)}resetHistory(){for(let e of this.passRenderers)e.resetHistory()}renderToScreen(e){return this.encodeToScreen(this.device.commandEncoder,e)}encodeToScreen(e,t){let n=this.encodeToTexture(e,t);if(!n)return!1;let r=this.device.getDefaultCanvasContext().getCurrentFramebuffer({depthStencilFormat:!1});this.textureModel.setProps({backgroundTexture:n}),this.textureModel.predraw(e);let s=e.beginRenderPass({id:"shader-pass-renderer-to-screen",framebuffer:r,clearDepth:!1});return this.textureModel.draw(s),s.end(),!0}renderToTexture(e){return this.encodeToTexture(this.device.commandEncoder,e)}encodeToTexture(e,t){if(e.device!==this.device)throw new Error("ShaderPassRenderer command encoder must belong to the renderer device");let{sourceTexture:n}=t;if(n instanceof K&&!n.isReady)return null;let r=n instanceof K?n.texture:n;if(this.passRenderers.length===0)return r;t.resetHistory&&this.resetHistory(),this.textureModel.setProps({backgroundTexture:r}),this.textureModel.predraw(e);let s=Za(this.swapFramebuffers,r),o=e.beginRenderPass({id:"shader-pass-renderer-seed-source",framebuffer:s,clearColor:[0,0,0,1],clearDepth:!1});this.textureModel.draw(o),o.end();let a=s,c=Ji(s),h=!1;try{for(let u of this.passRenderers){u.initializeHistoryTargets(r,this.textureModel,e),u.runComputeOptimization({commandEncoder:e,originalTexture:r,previousTexture:c,runtimeUniforms:t.uniforms||{}});for(let d of u.subPassExecutions){let l=d.output||"previous",f=l==="previous"?Ka(this.swapFramebuffers,a):u.getOutputFramebuffer(l),m=Ji(f),p=u.resolveBindings({execution:d,originalTexture:r,previousTexture:c,outputTexture:m,externalBindings:t.bindings||{}}),b=Va(this.shaderInputs,d,t.uniforms||{});d.subPassRenderer.prepare({commandEncoder:e,bindings:p,textureScale:Qa(p.sourceTexture||c,m),uniforms:b});let _=e.beginRenderPass({id:"shader-pass-renderer-run-pass",framebuffer:f,clearColor:[0,0,0,1],clearDepth:1});d.subPassRenderer.draw(_),_.end(),l==="previous"?(c=m,a=f):u.markTargetWritten(l)}}h=!0}finally{for(let u of this.passRenderers)u.finishFrame(h)}return c}},qi=class{device;shaderInputs;passDefinition;renderTargets;subPassExecutions;computeRenderer;constructor(e,t,n,r){if(this.device=e,this.shaderInputs=n,this.passDefinition=t,Xr(t)){Ua(t.name,t.renderTargets||{}),this.renderTargets=Xa(e,t.renderTargets||{}),Ga(e,t)&&(this.computeRenderer=new Ki(e,t.compute,this.renderTargets,n));let s=this.computeRenderer?t.steps.filter(o=>!t.compute.replacedPasses.includes(o.shaderPass.name)):t.steps;this.subPassExecutions=s.flatMap(o=>this.createStepExecutions(t,o,r));return}jr(t,t.name),this.renderTargets={},this.subPassExecutions=this.createPassExecutions(t,{ownerName:t.name,flipY:r})}destroy(){this.computeRenderer?.destroy();for(let e of this.subPassExecutions)e.subPassRenderer.destroy();Wa(this.renderTargets)}resize(e){qa(this.device,this.renderTargets,e)}runComputeOptimization(e){if(!this.computeRenderer)return;let t=this.resolveInputTexture(this.computeRenderer.optimization.input,e.originalTexture,e.previousTexture);this.computeRenderer.encode(e.commandEncoder,t,e.runtimeUniforms);for(let n of Object.values(this.computeRenderer.optimization.outputs))this.markTargetWritten(n)}resetHistory(){for(let e of Object.values(this.renderTargets))e.historyInitialized=!1,e.writtenThisFrame=!1}initializeHistoryTargets(e,t,n){for(let r of Object.values(this.renderTargets)){if(r.spec.lifetime!=="history"||r.historyInitialized)continue;let s=$r(r),o=r.spec.initialize||{clearColor:[0,0,0,0]};if(o==="original"){t.setProps({backgroundTexture:e}),t.predraw(n);let a=n.beginRenderPass({id:`${r.name}-initialize-history`,framebuffer:s,clearColor:[0,0,0,0],clearDepth:!1});t.draw(a),a.end()}else n.beginRenderPass({id:`${r.name}-clear-history`,framebuffer:s,clearColor:o.clearColor,clearDepth:!1}).end();r.historyInitialized=!0}}getOutputFramebuffer(e){return this.getRenderTarget(e).framebuffer}markTargetWritten(e){this.getRenderTarget(e).writtenThisFrame=!0}finishFrame(e){for(let t of Object.values(this.renderTargets)){if(e&&t.spec.lifetime==="history"&&t.writtenThisFrame){let n=Ur(t),r=$r(t);t.historyTexture=t.texture,t.historyFramebuffer=t.framebuffer,t.texture=n,t.framebuffer=r,t.historyInitialized=!0}t.writtenThisFrame=!1}}getRenderTarget(e){let t=this.renderTargets[e];if(!t)throw new Error(`${this.getOwnerName()}: unknown render target "${e}"`);return t}resolveBindings(e){let{execution:t,originalTexture:n,previousTexture:r,outputTexture:s,externalBindings:o}=e,a=t.inputs||{sourceTexture:"previous"},c=this.shaderInputs.getModuleBindingValues(t.shaderPass.name),h=Object.fromEntries(Object.entries(o).filter(([l])=>t.shaderPass.bindingLayout?.some(f=>f.name===l))),u={...c,...h},d=t.output||"previous";for(let[l,f]of Object.entries(a)){if(!f)continue;let m=this.resolveInputTexture(f,n,r),p=f in this.renderTargets?this.renderTargets[f]:null;if(d!=="previous"&&f===d&&p?.spec.lifetime!=="history")throw new Error(`${t.ownerName}: subpass cannot read and write render target "${d}" in the same draw`);if(m===s)throw new Error(`${t.ownerName}: subpass cannot sample from the render target it is writing to`);u[l]=m}return"sourceTexture"in u||(u.sourceTexture=r),u}createStepExecutions(e,t,n){return jr(t.shaderPass,`${e.name}/${t.shaderPass.name}`),this.createPassExecutions(t.shaderPass,{ownerName:`${e.name}/${t.shaderPass.name}`,firstInputs:t.inputs,lastOutput:t.output,uniformOverrides:t.uniforms,flipY:n})}createPassExecutions(e,t){let n=e.passes||[];return n.map((r,s)=>{let o=s===0,a=s===n.length-1,c=o&&t.firstInputs!==void 0?t.firstInputs:r.inputs,h=a&&t.lastOutput!==void 0?t.lastOutput:r.output;return $a(t.ownerName,c,h,this.renderTargets),{ownerName:t.ownerName,shaderPass:e,subPassRenderer:new Zi(this.device,e,r,t.flipY),inputs:c,output:h,uniforms:Qi(t.uniformOverrides,r.uniforms)}})}resolveInputTexture(e,t,n){switch(e){case"original":return t;case"previous":return n;default:{let r=this.getRenderTarget(e);return r.spec.lifetime==="history"&&!r.writtenThisFrame?Ur(r):r.texture}}}getOwnerName(){return this.passDefinition.name}},Ki=class{optimization;renderTargets;shaderInputs;computation;parameterBuffer;constructor(e,t,n,r){this.optimization=t,this.renderTargets=n,this.shaderInputs=r,this.parameterBuffer=e.createBuffer({id:`${t.name}-parameters`,byteLength:Math.max(Math.ceil(t.uniformNames.length/4)*16,16),usage:oe.Buffer.UNIFORM|oe.Buffer.COPY_DST});let s=Object.entries(t.outputs).map(([o,a],c)=>({name:o,type:"storage",group:0,location:c+2,access:"write-only",format:n[a].texture.format}));try{this.computation=new Ge(e,{id:t.name,source:t.source,shaderLayout:{bindings:[{name:t.uniformBinding,type:"uniform",group:0,location:0},{name:"sourceTexture",type:"texture",group:0,location:1,sampleType:"unfilterable-float"},...s]}})}catch(o){throw this.parameterBuffer.destroy(),o}}encode(e,t,n){let r={...this.shaderInputs.getUniformValues()[this.optimization.uniformModule]||{},...this.optimization.uniforms,...n[this.optimization.uniformModule]||{}},s=new Float32Array(Math.max(Math.ceil(this.optimization.uniformNames.length/4)*4,4));for(let[u,d]of this.optimization.uniformNames.entries()){let l=r[d];s[u]=typeof l=="number"?l:0}this.parameterBuffer.write(s);let o=Object.entries(this.optimization.outputs),a={[this.optimization.uniformBinding]:this.parameterBuffer,sourceTexture:t.view};for(let[u,d]of o)a[u]=this.renderTargets[d].texture.view;this.computation.setBindings(a),this.computation.predraw(e);let c=this.renderTargets[o[0][1]].texture,h=e.beginComputePass({id:this.optimization.name});this.computation.dispatch(h,Math.ceil(c.width/this.optimization.workgroupSize[0]),Math.ceil(c.height/this.optimization.workgroupSize[1]),1),h.end()}destroy(){this.computation.destroy(),this.parameterBuffer.destroy()}},Zi=class{model;shaderPass;subPass;flipY;constructor(e,t,n,r){this.shaderPass=t,this.subPass=n,this.flipY=r;let s=n.action||n.filter&&"filter"||n.sampler&&"sample"||"filter",o=Fr({shaderPass:t,action:s,shadingLanguage:e.info.shadingLanguage});this.model=new ue(e,{id:`${t.name}-subpass`,source:o,fs:o,modules:[zr,t],parameters:{depthWriteEnabled:!1}})}destroy(){this.model.destroy()}prepare(e){let{commandEncoder:t,bindings:n,textureScale:r,uniforms:s}=e;this.model.shaderInputs.setProps({textureTransform:{scale:r,flipY:this.flipY?1:0}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:this.shaderPass.uniforms||{}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:s||{}}),this.model.setBindings(n||{}),this.model.predraw(t)}draw(e){this.model.draw(e)}};function ja(i){return i.flatMap(e=>Xr(e)?e.steps.map(t=>t.shaderPass):[e])}function Xr(i){return"steps"in i}function Ga(i,e){let t=e.compute;if(!t||i.type!=="webgpu")return!1;let n=Object.values(t.outputs);return n.length===0||n.length>i.limits.maxStorageTexturesPerShaderStage||t.workgroupSize[0]>i.limits.maxComputeWorkgroupSizeX||t.workgroupSize[1]>i.limits.maxComputeWorkgroupSizeY||t.workgroupSize[0]*t.workgroupSize[1]>i.limits.maxComputeInvocationsPerWorkgroup?!1:n.every(r=>{let s=e.renderTargets?.[r];if(!s?.storage)return!1;let o=s.format||i.preferredColorFormat;return i.getTextureFormatCapabilities(o).store})}function jr(i,e){let t=i.renderTargets;if(t&&Object.keys(t).length>0)throw new Error(`${e}: ShaderPass.renderTargets is not supported; use ShaderPassPipeline.renderTargets instead`)}function Ua(i,e){for(let t of Object.keys(e))if(za.has(t))throw new Error(`${i}: render target name "${t}" is reserved`)}function $a(i,e,t,n){let r=e||{sourceTexture:"previous"};for(let s of Object.values(r))if(s&&s!=="original"&&s!=="previous"&&!(s in n))throw new Error(`${i}: unknown input source "${s}"`);if(t&&t!=="previous"&&!(t in n))throw new Error(`${i}: unknown output target "${t}"`)}function Qi(i,e){if(!(!i&&!e))return{...i||{},...e||{}}}function Va(i,e,t){return Qi(Qi(i.getUniformValues()[e.shaderPass.name],e.uniforms),t[e.shaderPass.name])}function Xa(i,e){let t=i.getCanvasContext().getDrawingBufferSize(),n={};for(let[r,s]of Object.entries(e)){if(s.aliasFor){let o=n[s.aliasFor];if(!o)throw new Error(`${r}: target alias references an unknown earlier target`);let a=en(t,s.scale),c=s.format||i.preferredColorFormat;if(s.lifetime==="history"||o.spec.lifetime==="history"||!Ha(s,o.spec)||o.texture.width!==a[0]||o.texture.height!==a[1]||o.texture.format!==c||s.storage&&!o.spec.storage||!Ya(s,o.spec))throw new Error(`${r}: target alias must match a transient target's size, format, and sampler`);n[r]=o;continue}n[r]=Hr(i,r,s,t)}return n}function Ha(i,e){let t=i.scale||[1,1],n=e.scale||[1,1];return t[0]===n[0]&&t[1]===n[1]}function Ya(i,e){let t=i.sampler||{},n=e.sampler||{},r=Object.entries(t);return r.length===Object.keys(n).length&&r.every(([s,o])=>n[s]===o)}function Wa(i){for(let e of new Set(Object.values(i)))e.framebuffer.destroy(),e.texture.destroy(),e.historyFramebuffer?.destroy(),e.historyTexture?.destroy()}function qa(i,e,t){for(let n of new Set(Object.values(e))){let r=en(t,n.spec.scale);if(n.texture.width===r[0]&&n.texture.height===r[1])continue;n.framebuffer.destroy(),n.texture.destroy(),n.historyFramebuffer?.destroy(),n.historyTexture?.destroy();let s=Hr(i,n.name,n.spec,t);n.texture=s.texture,n.framebuffer=s.framebuffer,n.historyTexture=s.historyTexture,n.historyFramebuffer=s.historyFramebuffer,n.historyInitialized=!1,n.writtenThisFrame=!1}}function Hr(i,e,t,n){let r=en(n,t.scale),{texture:s,framebuffer:o}=Gr(i,e,t,r),a,c;if(t.lifetime==="history"){let h=Gr(i,`${e}-history`,t,r);a=h.texture,c=h.framebuffer}return{name:e,spec:t,texture:s,framebuffer:o,historyTexture:a,historyFramebuffer:c,historyInitialized:!1,writtenThisFrame:!1}}function Gr(i,e,t,n){let r=i.createTexture({id:`${e}-texture`,width:n[0],height:n[1],format:t.format||i.preferredColorFormat,usage:oe.Texture.SAMPLE|oe.Texture.RENDER|oe.Texture.COPY_SRC|oe.Texture.COPY_DST|(t.storage&&i.type==="webgpu"&&i.getTextureFormatCapabilities(t.format||i.preferredColorFormat).store?oe.Texture.STORAGE:0),...t.sampler?{sampler:t.sampler}:{}}),s=i.createFramebuffer({id:`${e}-framebuffer`,width:n[0],height:n[1],colorAttachments:[r]});return{texture:r,framebuffer:s}}function Ur(i){if(!i.historyTexture)throw new Error(`${i.name}: transient render target has no history texture`);return i.historyTexture}function $r(i){if(!i.historyFramebuffer)throw new Error(`${i.name}: transient render target has no history framebuffer`);return i.historyFramebuffer}function en(i,e=[1,1]){return[Math.max(1,Math.round(i[0]*e[0])),Math.max(1,Math.round(i[1]*e[1]))]}function Ji(i){let e=i.colorAttachments[0]?.texture;if(!e)throw new Error("ShaderPassRenderer: framebuffer is missing a color attachment texture");return e}function Ka(i,e){return e===i.current?i.next:i.current}function Za(i,e){return Ji(i.current)===e?i.next:i.current}function Qa(i,e){let t=i.width/i.height,n=e.width/e.height;return n>t?[1,n/t]:[t/n,1]}var Z=R(N(),1);var Ja=[0,1,1,1],j=-1,ec={isActive:"i32",indexMode:"i32",batchIndex:"i32",isHighlightActive:"i32",highlightedBatchIndex:"i32",highlightedObjectIndex:"i32",highlightColor:"vec4<f32>"},ae=`precision highp float;
|
|
267
|
+
`,uniformTypes:{scale:"vec2<f32>",flipY:"i32"}};var Ga=new Set(["original","previous"]),ti=class{device;shaderInputs;passRenderers;swapFramebuffers;textureModel;constructor(e,t){this.device=e;let n=Ua(t.shaderPasses);n.map(a=>(0,Hr.initializeShaderModule)(a));let r=n.reduce((a,c)=>({...a,[c.name]:c}),{});this.shaderInputs=t.shaderInputs||new X(r);let s=e.getCanvasContext().getDrawingBufferSize();this.swapFramebuffers=new je(e,{colorAttachments:[t.colorFormat||e.preferredColorFormat],width:s[0],height:s[1]}),this.textureModel=new Be(e,{backgroundTexture:this.swapFramebuffers.current.colorAttachments[0].texture,flipY:t.flipY??e.type==="webgpu"});let o=t.flipY??e.type==="webgpu";this.passRenderers=t.shaderPasses.map(a=>new Ki(e,a,this.shaderInputs,o))}destroy(){for(let e of this.passRenderers)e.destroy();this.swapFramebuffers.destroy(),this.textureModel.destroy()}resize(e){e||=this.device.getCanvasContext().getDrawingBufferSize(),this.swapFramebuffers.resize({width:e[0],height:e[1]});for(let t of this.passRenderers)t.resize(e)}resetHistory(){for(let e of this.passRenderers)e.resetHistory()}renderToScreen(e){return this.encodeToScreen(this.device.commandEncoder,e)}encodeToScreen(e,t){let n=this.encodeToTexture(e,t);if(!n)return!1;let r=this.device.getDefaultCanvasContext().getCurrentFramebuffer({depthStencilFormat:!1});this.textureModel.setProps({backgroundTexture:n}),this.textureModel.predraw(e);let s=e.beginRenderPass({id:"shader-pass-renderer-to-screen",framebuffer:r,clearDepth:!1});return this.textureModel.draw(s),s.end(),!0}renderToTexture(e){return this.encodeToTexture(this.device.commandEncoder,e)}encodeToTexture(e,t){if(e.device!==this.device)throw new Error("ShaderPassRenderer command encoder must belong to the renderer device");let{sourceTexture:n}=t;if(n instanceof K&&!n.isReady)return null;let r=n instanceof K?n.texture:n;if(this.passRenderers.length===0)return r;t.resetHistory&&this.resetHistory(),this.textureModel.setProps({backgroundTexture:r}),this.textureModel.predraw(e);let s=Ja(this.swapFramebuffers,r),o=e.beginRenderPass({id:"shader-pass-renderer-seed-source",framebuffer:s,clearColor:[0,0,0,1],clearDepth:!1});this.textureModel.draw(o),o.end();let a=s,c=en(s),h=!1;try{for(let u of this.passRenderers){u.initializeHistoryTargets(r,this.textureModel,e),u.runComputeOptimization({commandEncoder:e,originalTexture:r,previousTexture:c,runtimeUniforms:t.uniforms||{}});for(let d of u.subPassExecutions){let l=d.output||"previous",f=l==="previous"?Qa(this.swapFramebuffers,a):u.getOutputFramebuffer(l),m=en(f),p=u.resolveBindings({execution:d,originalTexture:r,previousTexture:c,outputTexture:m,externalBindings:t.bindings||{}}),b=Ha(this.shaderInputs,d,t.uniforms||{});d.subPassRenderer.prepare({commandEncoder:e,bindings:p,textureScale:ec(p.sourceTexture||c,m),uniforms:b});let _=e.beginRenderPass({id:"shader-pass-renderer-run-pass",framebuffer:f,clearColor:[0,0,0,1],clearDepth:1});d.subPassRenderer.draw(_),_.end(),l==="previous"?(c=m,a=f):u.markTargetWritten(l)}}h=!0}finally{for(let u of this.passRenderers)u.finishFrame(h)}return c}},Ki=class{device;shaderInputs;passDefinition;renderTargets;subPassExecutions;computeRenderer;constructor(e,t,n,r){if(this.device=e,this.shaderInputs=n,this.passDefinition=t,Yr(t)){Va(t.name,t.renderTargets||{}),this.renderTargets=Ya(e,t.renderTargets||{}),$a(e,t)&&(this.computeRenderer=new Zi(e,t.compute,this.renderTargets,n));let s=this.computeRenderer?t.steps.filter(o=>!t.compute.replacedPasses.includes(o.shaderPass.name)):t.steps;this.subPassExecutions=s.flatMap(o=>this.createStepExecutions(t,o,r));return}Ur(t,t.name),this.renderTargets={},this.subPassExecutions=this.createPassExecutions(t,{ownerName:t.name,flipY:r})}destroy(){this.computeRenderer?.destroy();for(let e of this.subPassExecutions)e.subPassRenderer.destroy();Ka(this.renderTargets)}resize(e){Za(this.device,this.renderTargets,e)}runComputeOptimization(e){if(!this.computeRenderer)return;let t=this.resolveInputTexture(this.computeRenderer.optimization.input,e.originalTexture,e.previousTexture);this.computeRenderer.encode(e.commandEncoder,t,e.runtimeUniforms);for(let n of Object.values(this.computeRenderer.optimization.outputs))this.markTargetWritten(n)}resetHistory(){for(let e of Object.values(this.renderTargets))e.historyInitialized=!1,e.writtenThisFrame=!1}initializeHistoryTargets(e,t,n){for(let r of Object.values(this.renderTargets)){if(r.spec.lifetime!=="history"||r.historyInitialized)continue;let s=Xr(r),o=r.spec.initialize||{clearColor:[0,0,0,0]};if(o==="original"){t.setProps({backgroundTexture:e}),t.predraw(n);let a=n.beginRenderPass({id:`${r.name}-initialize-history`,framebuffer:s,clearColor:[0,0,0,0],clearDepth:!1});t.draw(a),a.end()}else n.beginRenderPass({id:`${r.name}-clear-history`,framebuffer:s,clearColor:o.clearColor,clearDepth:!1}).end();r.historyInitialized=!0}}getOutputFramebuffer(e){return this.getRenderTarget(e).framebuffer}markTargetWritten(e){this.getRenderTarget(e).writtenThisFrame=!0}finishFrame(e){for(let t of Object.values(this.renderTargets)){if(e&&t.spec.lifetime==="history"&&t.writtenThisFrame){let n=Vr(t),r=Xr(t);t.historyTexture=t.texture,t.historyFramebuffer=t.framebuffer,t.texture=n,t.framebuffer=r,t.historyInitialized=!0}t.writtenThisFrame=!1}}getRenderTarget(e){let t=this.renderTargets[e];if(!t)throw new Error(`${this.getOwnerName()}: unknown render target "${e}"`);return t}resolveBindings(e){let{execution:t,originalTexture:n,previousTexture:r,outputTexture:s,externalBindings:o}=e,a=t.inputs||{sourceTexture:"previous"},c=this.shaderInputs.getModuleBindingValues(t.shaderPass.name),h=Object.fromEntries(Object.entries(o).filter(([l])=>t.shaderPass.bindingLayout?.some(f=>f.name===l))),u={...c,...h},d=t.output||"previous";for(let[l,f]of Object.entries(a)){if(!f)continue;let m=this.resolveInputTexture(f,n,r),p=f in this.renderTargets?this.renderTargets[f]:null;if(d!=="previous"&&f===d&&p?.spec.lifetime!=="history")throw new Error(`${t.ownerName}: subpass cannot read and write render target "${d}" in the same draw`);if(m===s)throw new Error(`${t.ownerName}: subpass cannot sample from the render target it is writing to`);u[l]=m}return"sourceTexture"in u||(u.sourceTexture=r),u}createStepExecutions(e,t,n){return Ur(t.shaderPass,`${e.name}/${t.shaderPass.name}`),this.createPassExecutions(t.shaderPass,{ownerName:`${e.name}/${t.shaderPass.name}`,firstInputs:t.inputs,lastOutput:t.output,uniformOverrides:t.uniforms,flipY:n})}createPassExecutions(e,t){let n=e.passes||[];return n.map((r,s)=>{let o=s===0,a=s===n.length-1,c=o&&t.firstInputs!==void 0?t.firstInputs:r.inputs,h=a&&t.lastOutput!==void 0?t.lastOutput:r.output;return Xa(t.ownerName,c,h,this.renderTargets),{ownerName:t.ownerName,shaderPass:e,subPassRenderer:new Qi(this.device,e,r,t.flipY),inputs:c,output:h,uniforms:Ji(t.uniformOverrides,r.uniforms)}})}resolveInputTexture(e,t,n){switch(e){case"original":return t;case"previous":return n;default:{let r=this.getRenderTarget(e);return r.spec.lifetime==="history"&&!r.writtenThisFrame?Vr(r):r.texture}}}getOwnerName(){return this.passDefinition.name}},Zi=class{optimization;renderTargets;shaderInputs;computation;parameterBuffer;constructor(e,t,n,r){this.optimization=t,this.renderTargets=n,this.shaderInputs=r,this.parameterBuffer=e.createBuffer({id:`${t.name}-parameters`,byteLength:Math.max(Math.ceil(t.uniformNames.length/4)*16,16),usage:ae.Buffer.UNIFORM|ae.Buffer.COPY_DST});let s=Object.entries(t.outputs).map(([o,a],c)=>({name:o,type:"storage",group:0,location:c+2,access:"write-only",format:n[a].texture.format}));try{this.computation=new Ge(e,{id:t.name,source:t.source,shaderLayout:{bindings:[{name:t.uniformBinding,type:"uniform",group:0,location:0},{name:"sourceTexture",type:"texture",group:0,location:1,sampleType:"unfilterable-float"},...s]}})}catch(o){throw this.parameterBuffer.destroy(),o}}encode(e,t,n){let r={...this.shaderInputs.getUniformValues()[this.optimization.uniformModule]||{},...this.optimization.uniforms,...n[this.optimization.uniformModule]||{}},s=new Float32Array(Math.max(Math.ceil(this.optimization.uniformNames.length/4)*4,4));for(let[u,d]of this.optimization.uniformNames.entries()){let l=r[d];s[u]=typeof l=="number"?l:0}this.parameterBuffer.write(s);let o=Object.entries(this.optimization.outputs),a={[this.optimization.uniformBinding]:this.parameterBuffer,sourceTexture:t.view};for(let[u,d]of o)a[u]=this.renderTargets[d].texture.view;this.computation.setBindings(a),this.computation.predraw(e);let c=this.renderTargets[o[0][1]].texture,h=e.beginComputePass({id:this.optimization.name});this.computation.dispatch(h,Math.ceil(c.width/this.optimization.workgroupSize[0]),Math.ceil(c.height/this.optimization.workgroupSize[1]),1),h.end()}destroy(){this.computation.destroy(),this.parameterBuffer.destroy()}},Qi=class{model;shaderPass;subPass;flipY;constructor(e,t,n,r){this.shaderPass=t,this.subPass=n,this.flipY=r;let s=n.action||n.filter&&"filter"||n.sampler&&"sample"||"filter",o=jr({shaderPass:t,action:s,shadingLanguage:e.info.shadingLanguage});this.model=new ue(e,{id:`${t.name}-subpass`,source:o,fs:o,modules:[Gr,t],parameters:{depthWriteEnabled:!1}})}destroy(){this.model.destroy()}prepare(e){let{commandEncoder:t,bindings:n,textureScale:r,uniforms:s}=e;this.model.shaderInputs.setProps({textureTransform:{scale:r,flipY:this.flipY?1:0}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:this.shaderPass.uniforms||{}}),this.model.shaderInputs.setProps({[this.shaderPass.name]:s||{}}),this.model.setBindings(n||{}),this.model.predraw(t)}draw(e){this.model.draw(e)}};function Ua(i){return i.flatMap(e=>Yr(e)?e.steps.map(t=>t.shaderPass):[e])}function Yr(i){return"steps"in i}function $a(i,e){let t=e.compute;if(!t||i.type!=="webgpu")return!1;let n=Object.values(t.outputs);return n.length===0||n.length>i.limits.maxStorageTexturesPerShaderStage||t.workgroupSize[0]>i.limits.maxComputeWorkgroupSizeX||t.workgroupSize[1]>i.limits.maxComputeWorkgroupSizeY||t.workgroupSize[0]*t.workgroupSize[1]>i.limits.maxComputeInvocationsPerWorkgroup?!1:n.every(r=>{let s=e.renderTargets?.[r];if(!s?.storage)return!1;let o=s.format||i.preferredColorFormat;return i.getTextureFormatCapabilities(o).store})}function Ur(i,e){let t=i.renderTargets;if(t&&Object.keys(t).length>0)throw new Error(`${e}: ShaderPass.renderTargets is not supported; use ShaderPassPipeline.renderTargets instead`)}function Va(i,e){for(let t of Object.keys(e))if(Ga.has(t))throw new Error(`${i}: render target name "${t}" is reserved`)}function Xa(i,e,t,n){let r=e||{sourceTexture:"previous"};for(let s of Object.values(r))if(s&&s!=="original"&&s!=="previous"&&!(s in n))throw new Error(`${i}: unknown input source "${s}"`);if(t&&t!=="previous"&&!(t in n))throw new Error(`${i}: unknown output target "${t}"`)}function Ji(i,e){if(!(!i&&!e))return{...i||{},...e||{}}}function Ha(i,e,t){return Ji(Ji(i.getUniformValues()[e.shaderPass.name],e.uniforms),t[e.shaderPass.name])}function Ya(i,e){let t=i.getCanvasContext().getDrawingBufferSize(),n={};for(let[r,s]of Object.entries(e)){if(s.aliasFor){let o=n[s.aliasFor];if(!o)throw new Error(`${r}: target alias references an unknown earlier target`);let a=tn(t,s.scale),c=s.format||i.preferredColorFormat;if(s.lifetime==="history"||o.spec.lifetime==="history"||!Wa(s,o.spec)||o.texture.width!==a[0]||o.texture.height!==a[1]||o.texture.format!==c||s.storage&&!o.spec.storage||!qa(s,o.spec))throw new Error(`${r}: target alias must match a transient target's size, format, and sampler`);n[r]=o;continue}n[r]=Wr(i,r,s,t)}return n}function Wa(i,e){let t=i.scale||[1,1],n=e.scale||[1,1];return t[0]===n[0]&&t[1]===n[1]}function qa(i,e){let t=i.sampler||{},n=e.sampler||{},r=Object.entries(t);return r.length===Object.keys(n).length&&r.every(([s,o])=>n[s]===o)}function Ka(i){for(let e of new Set(Object.values(i)))e.framebuffer.destroy(),e.texture.destroy(),e.historyFramebuffer?.destroy(),e.historyTexture?.destroy()}function Za(i,e,t){for(let n of new Set(Object.values(e))){let r=tn(t,n.spec.scale);if(n.texture.width===r[0]&&n.texture.height===r[1])continue;n.framebuffer.destroy(),n.texture.destroy(),n.historyFramebuffer?.destroy(),n.historyTexture?.destroy();let s=Wr(i,n.name,n.spec,t);n.texture=s.texture,n.framebuffer=s.framebuffer,n.historyTexture=s.historyTexture,n.historyFramebuffer=s.historyFramebuffer,n.historyInitialized=!1,n.writtenThisFrame=!1}}function Wr(i,e,t,n){let r=tn(n,t.scale),{texture:s,framebuffer:o}=$r(i,e,t,r),a,c;if(t.lifetime==="history"){let h=$r(i,`${e}-history`,t,r);a=h.texture,c=h.framebuffer}return{name:e,spec:t,texture:s,framebuffer:o,historyTexture:a,historyFramebuffer:c,historyInitialized:!1,writtenThisFrame:!1}}function $r(i,e,t,n){let r=i.createTexture({id:`${e}-texture`,width:n[0],height:n[1],format:t.format||i.preferredColorFormat,usage:ae.Texture.SAMPLE|ae.Texture.RENDER|ae.Texture.COPY_SRC|ae.Texture.COPY_DST|(t.storage&&i.type==="webgpu"&&i.getTextureFormatCapabilities(t.format||i.preferredColorFormat).store?ae.Texture.STORAGE:0),...t.sampler?{sampler:t.sampler}:{}}),s=i.createFramebuffer({id:`${e}-framebuffer`,width:n[0],height:n[1],colorAttachments:[r]});return{texture:r,framebuffer:s}}function Vr(i){if(!i.historyTexture)throw new Error(`${i.name}: transient render target has no history texture`);return i.historyTexture}function Xr(i){if(!i.historyFramebuffer)throw new Error(`${i.name}: transient render target has no history framebuffer`);return i.historyFramebuffer}function tn(i,e=[1,1]){return[Math.max(1,Math.round(i[0]*e[0])),Math.max(1,Math.round(i[1]*e[1]))]}function en(i){let e=i.colorAttachments[0]?.texture;if(!e)throw new Error("ShaderPassRenderer: framebuffer is missing a color attachment texture");return e}function Qa(i,e){return e===i.current?i.next:i.current}function Ja(i,e){return en(i.current)===e?i.next:i.current}function ec(i,e){let t=i.width/i.height,n=e.width/e.height;return n>t?[1,n/t]:[t/n,1]}var Z=R(N(),1);var tc=[0,1,1,1],j=-1,ic={isActive:"i32",indexMode:"i32",batchIndex:"i32",isHighlightActive:"i32",highlightedBatchIndex:"i32",highlightedObjectIndex:"i32",highlightColor:"vec4<f32>"},ce=`precision highp float;
|
|
268
268
|
precision highp int;
|
|
269
269
|
|
|
270
270
|
layout(std140) uniform pickingUniforms {
|
|
@@ -289,7 +289,7 @@ layout(std140) uniform pickingUniforms {
|
|
|
289
289
|
};
|
|
290
290
|
|
|
291
291
|
@group(0) @binding(auto) var<uniform> picking: pickingUniforms;
|
|
292
|
-
`;function
|
|
292
|
+
`;function nc(i={},e){let t={...e};switch(i.isActive!==void 0&&(t.isActive=!!i.isActive),i.indexMode){case"instance":t.indexMode=0;break;case"attribute":t.indexMode=1;break;case"vertex":t.indexMode=2;break;case void 0:break}switch(typeof i.batchIndex=="number"&&(t.batchIndex=i.batchIndex),i.highlightedObjectIndex){case void 0:break;case null:t.isHighlightActive=!1,t.highlightedObjectIndex=j;break;default:t.isHighlightActive=!0,t.highlightedObjectIndex=i.highlightedObjectIndex}switch(i.highlightedBatchIndex){case void 0:break;case null:t.isHighlightActive=!1,t.highlightedBatchIndex=j;break;default:t.isHighlightActive=!0,t.highlightedBatchIndex=i.highlightedBatchIndex}return i.highlightColor&&(t.highlightColor=i.highlightColor),t}var pe={props:{},uniforms:{},name:"picking",uniformTypes:ic,defaultUniforms:{isActive:!1,indexMode:0,batchIndex:0,isHighlightActive:!1,highlightedBatchIndex:j,highlightedObjectIndex:j,highlightColor:tc},getUniforms:nc};var qr=1,rc=new Int32Array([j,j,0,0]);var Kr=14,$e=8;function ni(i,e="color",t=i==="webgpu"){if(e==="auto")return t?"index":"color";if(e==="index"&&!t)throw new Error(`Picking mode "${e}" requires WebGPU or a WebGL device that supports renderable rg32sint textures.`);return e}function Je(i){return i.type==="webgpu"||i.type==="webgl"&&i.isTextureFormatRenderable("rg32sint")}var Jr=ni;function Zr(i){return{objectIndex:i[0]===j?null:i[0],batchIndex:i[1]===j?null:i[1]}}function Qr(i){let e=i[0]+i[1]*256+i[2]*65536;if(e===0)return{objectIndex:null,batchIndex:null};let t=i[3]>0?i[3]-1:0;return{objectIndex:e-1,batchIndex:t}}var ii=class i{device;props;mode;pickInfo={batchIndex:null,objectIndex:null};framebuffer=null;lastMousePosition=null;tooltipElement=null;static defaultProps={shaderInputs:void 0,onObjectPicked:()=>{},getTooltip:()=>null,mode:"color",backend:"color"};constructor(e,t){this.device=e,this.props={...i.defaultProps,...t};let n=t.mode??t.backend??i.defaultProps.mode;this.props.mode=n,this.props.backend=n,this.mode=ni(this.device.type,n,Je(this.device))}destroy(){this.framebuffer?.destroy(),this.tooltipElement?.remove(),this.tooltipElement=null}getFramebuffer(){return this.framebuffer||(this.framebuffer=this.mode==="index"?this.createIndexFramebuffer():this.createColorFramebuffer()),this.framebuffer}clearPickState(){this.lastMousePosition=null,this.setPickingProps({highlightedBatchIndex:null,highlightedObjectIndex:null}),this.hideTooltip()}shouldPick(e,t={}){if(!e)return this.lastMousePosition&&this.clearPickState(),!1;let[n,r]=e;return!t.force&&this.lastMousePosition&&this.lastMousePosition[0]===n&&this.lastMousePosition[1]===r?!1:(this.lastMousePosition=[n,r],!0)}beginRenderPass(){let e=this.getFramebuffer();return e.resize(this.device.getDefaultCanvasContext().getDevicePixelSize()),this.setPickingProps({isActive:!0}),this.mode==="index"?this.device.beginRenderPass({framebuffer:e,clearColors:[new Float32Array([0,0,0,0]),rc],clearDepth:1}):this.device.beginRenderPass({framebuffer:e,clearColor:[0,0,0,0],clearDepth:1})}async updatePickInfo(e){let t=this.getFramebuffer(),n=this.getPickPosition(e),r=await this.readPickInfo(t,n);return r?(this.hasPickInfoChanged(r)&&(this.pickInfo=r,this.props.onObjectPicked(r)),this.updateTooltip(r,e),this.setPickingProps({isActive:!1,highlightedBatchIndex:r.batchIndex,highlightedObjectIndex:r.objectIndex}),this.pickInfo):null}getPickPosition(e){let t=this.device.type!=="webgpu",n=this.device.getDefaultCanvasContext().cssToDevicePixels(e,t),r=n.x+Math.floor(n.width/2),s=n.y+Math.floor(n.height/2);return[r,s]}createIndexFramebuffer(){let e=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:Z.Texture.RENDER_ATTACHMENT}),t=this.device.createTexture({format:"rg32sint",width:1,height:1,usage:Z.Texture.RENDER_ATTACHMENT|Z.Texture.COPY_SRC});return this.device.createFramebuffer({colorAttachments:[e,t],depthStencilAttachment:"depth24plus"})}createColorFramebuffer(){let e=this.device.createTexture({format:"rgba8unorm",width:1,height:1,usage:Z.Texture.RENDER_ATTACHMENT|Z.Texture.COPY_SRC});return this.device.createFramebuffer({colorAttachments:[e],depthStencilAttachment:"depth24plus"})}setPickingProps(e){this.props.shaderInputs?.setProps({picking:e})}async readPickInfo(e,t){return this.mode==="index"?this.readIndexPickInfo(e,t):this.readColorPickInfo(e,t)}async readIndexPickInfo(e,[t,n]){if(this.device.type==="webgpu"){let s=e.colorAttachments[qr]?.texture;if(!s)return null;let o=s.computeMemoryLayout({width:1,height:1}),a=this.device.createBuffer({byteLength:o.byteLength,usage:Z.Buffer.COPY_DST|Z.Buffer.MAP_READ});try{s.readBuffer({x:t,y:n,width:1,height:1},a);let c=await a.readAsync(0,o.byteLength);return Zr(new Int32Array(c.buffer,c.byteOffset,2))}finally{a.destroy()}}let r=this.device.readPixelsToArrayWebGL(e,{sourceX:t,sourceY:n,sourceWidth:1,sourceHeight:1,sourceAttachment:qr});return r?Zr(new Int32Array(r.buffer,r.byteOffset,2)):null}async readColorPickInfo(e,[t,n]){if(this.device.type==="webgpu"){let s=e.colorAttachments[0]?.texture;if(!s)return null;let o=s.computeMemoryLayout({width:1,height:1}),a=this.device.createBuffer({byteLength:o.byteLength,usage:Z.Buffer.COPY_DST|Z.Buffer.MAP_READ});try{s.readBuffer({x:t,y:n,width:1,height:1},a);let c=await a.readAsync(0,o.byteLength);return Qr(new Uint8Array(c.buffer,c.byteOffset,4))}finally{a.destroy()}}let r=this.device.readPixelsToArrayWebGL(e,{sourceX:t,sourceY:n,sourceWidth:1,sourceHeight:1,sourceAttachment:0});return r?Qr(new Uint8Array(r.buffer,r.byteOffset,4)):null}hasPickInfoChanged(e){return e.objectIndex!==this.pickInfo.objectIndex||e.batchIndex!==this.pickInfo.batchIndex}updateTooltip(e,t){let n=this.props.getTooltip(e);if(!n){this.hideTooltip();return}let r=this.getOrCreateTooltipElement();r&&(r.textContent=n,r.style.display="block",this.positionTooltip(r,t))}hideTooltip(){this.tooltipElement&&(this.tooltipElement.style.display="none")}getOrCreateTooltipElement(){if(this.tooltipElement)return this.tooltipElement;if(typeof document>"u"||typeof window>"u"||typeof HTMLCanvasElement>"u"||typeof this.device.getDefaultCanvasContext!="function")return null;let e=this.device.getDefaultCanvasContext().canvas;if(!(e instanceof HTMLCanvasElement)||!e.parentElement)return null;let t=document.createElement("div");t.style.position="absolute",t.style.zIndex="12",t.style.display="none",t.style.maxWidth="220px",t.style.padding="8px 10px",t.style.borderRadius="6px",t.style.background="rgba(15, 23, 42, 0.92)",t.style.color="#f8fafc",t.style.font="600 13px/1.35 system-ui, sans-serif",t.style.pointerEvents="none",t.style.whiteSpace="nowrap",t.style.boxShadow="0 10px 24px rgba(15, 23, 42, 0.22)";let n=e.parentElement;return window.getComputedStyle(n).position==="static"&&(n.style.position="relative"),n.appendChild(t),this.tooltipElement=t,t}positionTooltip(e,t){if(typeof HTMLCanvasElement>"u"||typeof this.device.getDefaultCanvasContext!="function")return;let n=this.device.getDefaultCanvasContext().canvas;if(!(n instanceof HTMLCanvasElement))return;let r=Math.max($e,n.clientWidth-e.offsetWidth-$e),s=Math.max($e,n.clientHeight-e.offsetHeight-$e),o=Math.min(t[0]+Kr,r),a=Math.min(t[1]+Kr,s);e.style.left=`${Math.max($e,o)}px`,e.style.top=`${Math.max($e,a)}px`}};var sc=`${Ue}
|
|
293
293
|
|
|
294
294
|
const COLOR_PICKING_INVALID_INDEX = ${j};
|
|
295
295
|
const COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
|
|
@@ -360,7 +360,7 @@ fn picking_filterPickingColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {
|
|
|
360
360
|
|
|
361
361
|
return color;
|
|
362
362
|
}
|
|
363
|
-
`,
|
|
363
|
+
`,oc=`${ce}
|
|
364
364
|
|
|
365
365
|
const int INDEX_PICKING_MODE_INSTANCE = 0;
|
|
366
366
|
const int INDEX_PICKING_MODE_CUSTOM = 1;
|
|
@@ -379,7 +379,7 @@ void picking_setObjectIndex(int objectIndex) {
|
|
|
379
379
|
break;
|
|
380
380
|
}
|
|
381
381
|
}
|
|
382
|
-
`,
|
|
382
|
+
`,ac=`${ce}
|
|
383
383
|
|
|
384
384
|
const int COLOR_PICKING_INVALID_INDEX = ${j};
|
|
385
385
|
const int COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
|
|
@@ -452,7 +452,7 @@ vec4 picking_filterColor(vec4 color) {
|
|
|
452
452
|
outColor = picking_filterPickingColor(outColor);
|
|
453
453
|
return outColor;
|
|
454
454
|
}
|
|
455
|
-
`,et={...pe,name:"picking",source:
|
|
455
|
+
`,et={...pe,name:"picking",source:sc,vs:oc,fs:ac};var cc=`${Ue}
|
|
456
456
|
|
|
457
457
|
const COLOR_PICKING_INVALID_INDEX = ${j};
|
|
458
458
|
const COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
|
|
@@ -542,7 +542,7 @@ fn picking_filterColor(color: vec4<f32>, objectIndex: i32) -> vec4<f32> {
|
|
|
542
542
|
outColor = picking_filterPickingColor(outColor, objectIndex);
|
|
543
543
|
return outColor;
|
|
544
544
|
}
|
|
545
|
-
`,
|
|
545
|
+
`,hc=`${ce}
|
|
546
546
|
|
|
547
547
|
const int INDEX_PICKING_MODE_INSTANCE = 0;
|
|
548
548
|
const int INDEX_PICKING_MODE_ATTRIBUTE = 1;
|
|
@@ -563,7 +563,7 @@ void picking_setObjectIndex(int objectIndex) {
|
|
|
563
563
|
break;
|
|
564
564
|
}
|
|
565
565
|
}
|
|
566
|
-
`,
|
|
566
|
+
`,uc=`${ce}
|
|
567
567
|
|
|
568
568
|
const int COLOR_PICKING_INVALID_INDEX = ${j};
|
|
569
569
|
const int COLOR_PICKING_MAX_OBJECT_INDEX = 16777214;
|
|
@@ -636,7 +636,7 @@ vec4 picking_filterColor(vec4 color) {
|
|
|
636
636
|
outColor = picking_filterPickingColor(outColor);
|
|
637
637
|
return outColor;
|
|
638
638
|
}
|
|
639
|
-
`,
|
|
639
|
+
`,ri={...pe,name:"picking",source:cc,vs:hc,fs:uc};var lc=`${Ue}
|
|
640
640
|
|
|
641
641
|
const INDEX_PICKING_MODE_INSTANCE = 0;
|
|
642
642
|
const INDEX_PICKING_MODE_ATTRIBUTE = 1;
|
|
@@ -696,7 +696,7 @@ fn picking_getPickingColor(objectIndex: i32) -> vec2<i32> {
|
|
|
696
696
|
return vec2<i32>(objectIndex, picking.batchIndex);
|
|
697
697
|
}
|
|
698
698
|
|
|
699
|
-
`,
|
|
699
|
+
`,dc=`${ce}
|
|
700
700
|
|
|
701
701
|
const int INDEX_PICKING_MODE_INSTANCE = 0;
|
|
702
702
|
const int INDEX_PICKING_MODE_ATTRIBUTE = 1;
|
|
@@ -723,7 +723,7 @@ void picking_setObjectIndex(int objectIndex) {
|
|
|
723
723
|
break;
|
|
724
724
|
}
|
|
725
725
|
}
|
|
726
|
-
`,
|
|
726
|
+
`,fc=`${ce}
|
|
727
727
|
|
|
728
728
|
const int INDEX_PICKING_INVALID_INDEX = ${j}; // 2^32 - 1
|
|
729
729
|
|
|
@@ -791,6 +791,6 @@ vec4 picking_filterColor(vec4 color) {
|
|
|
791
791
|
outColor = picking_filterPickingColor(outColor);
|
|
792
792
|
return outColor;
|
|
793
793
|
}
|
|
794
|
-
`,tt={...pe,name:"picking",source:
|
|
794
|
+
`,tt={...pe,name:"picking",source:lc,vs:dc,fs:fc};var es={...pe,name:"picking",source:tt.source,vs:et.vs,fs:et.fs};function ts(i){return Je(i)?tt:ri}var si=class{device;framebuffer=null;shaderInputs;constructor(e,t){this.device=e,this.shaderInputs=t}destroy(){this.framebuffer?.destroy()}getFramebuffer(){return this.framebuffer||(this.framebuffer=this.device.createFramebuffer({colorAttachments:["rgba8unorm"],depthStencilAttachment:"depth24plus"})),this.framebuffer}clearPickState(){this.shaderInputs.setProps({picking:{highlightedObjectColor:null}})}beginRenderPass(){let e=this.getFramebuffer();return e.resize(this.device.getCanvasContext().getDevicePixelSize()),this.shaderInputs.setProps({picking:{isActive:!0}}),this.device.beginRenderPass({framebuffer:e,clearColor:[0,0,0,0],clearDepth:1})}updatePickState(e){let t=this.getFramebuffer(),[n,r]=this.getPickPosition(e),o=[...this.device.readPixelsToArrayWebGL(t,{sourceX:n,sourceY:r,sourceWidth:1,sourceHeight:1})].map(c=>c/255);o[0]+o[1]+o[2]>0||(o=null),this.shaderInputs.setProps({picking:{isActive:!1,highlightedObjectColor:o}})}getPickPosition(e){let t=this.device.getCanvasContext().cssToDevicePixels(e),n=t.x+Math.floor(t.width/2),r=t.y+Math.floor(t.height/2);return[n,r]}};var is=R(ne(),1),ns=is.picking;var mc=K;return ms(it);})();
|
|
795
795
|
return __exports__;
|
|
796
796
|
});
|