playcanvas
Version:
PlayCanvas WebGL game engine
14,696 lines • 1.96 MB
JavaScript
/**
* @license
* PlayCanvas Engine v2.10.5 revision 8959e32 (RELEASE)
* Copyright 2011-2025 PlayCanvas Ltd. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/let e,t,i,s,r,a,n,o,l,h,c,d,u,f,p,m,_,g;let v="RenderFrame",S="RenderFrameTime",y="RenderPass",x="RenderPassDetail",T="RenderAction",E="RenderTargetAlloc",A="TextureAlloc",b="ShaderAlloc",w="ShaderCompile",C="VRAM.Texture",P="VRAM.Vb",L="VRAM.Ib",I="VRAM.Sb",D="BindGroupAlloc",R="BindGroupFormatAlloc",M="RenderPipelineAlloc",O="ComputePipelineAlloc",N="PipelineLayoutAlloc",F="Element",B="Textures",U="RenderQueue",k="GpuTimings",V="2.10.5",z="8959e32";function G(e,t){for(let i in t){let s=t[i];Array.isArray(s)?e[i]=G([],s):s&&"object"==typeof s?e[i]=G({},s):e[i]=s;}return e}let H={create:()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return ("x"===e?t:3&t|8).toString(16)})},W={delimiter:"/",join(...e){let t=e[0];for(let i=0;i<e.length-1;i++){let s=e[i],r=e[i+1];if(r[0]===W.delimiter){t=r;continue}s&&r&&s[s.length-1]!==W.delimiter&&r[0]!==W.delimiter?t+=W.delimiter+r:t+=r;}return t},normalize(e){let t=e.startsWith(W.delimiter),i=e.endsWith(W.delimiter),s=e.split("/"),r="",a=[];for(let e=0;e<s.length;e++)if(""!==s[e]&&"."!==s[e]){if(".."===s[e]&&a.length>0){a=a.slice(0,a.length-2);continue}e>0&&a.push(W.delimiter),a.push(s[e]);}return r=a.join(""),t||r[0]!==W.delimiter||(r=r.slice(1)),i&&r[r.length-1]!==W.delimiter&&(r+=W.delimiter),r},split(e){let t=e.lastIndexOf(W.delimiter);return -1!==t?[e.substring(0,t),e.substring(t+1)]:["",e]},getBasename:e=>W.split(e)[1],getDirectory:e=>W.split(e)[0],getExtension(e){let t=e.split("?")[0].split(".").pop();return t!==e?`.${t}`:""},isRelativePath:e=>"/"!==e.charAt(0)&&null===e.match(/:\/\//),extractPath(e){let t="",i=e.split("/"),s=0;if(i.length>1)if(W.isRelativePath(e))if("."===i[0])for(s=0;s<i.length-1;++s)t+=0===s?i[s]:`/${i[s]}`;else if(".."===i[0])for(s=0;s<i.length-1;++s)t+=0===s?i[s]:`/${i[s]}`;else for(s=0,t=".";s<i.length-1;++s)t+=`/${i[s]}`;else for(s=0;s<i.length-1;++s)t+=0===s?i[s]:`/${i[s]}`;return t}},X="undefined"!=typeof navigator?navigator.userAgent:"",Y="undefined"!=typeof window?"browser":"undefined"!=typeof global?"node":"worker",q=/android/i.test(X)?"android":/ip(?:[ao]d|hone)/i.test(X)?"ios":/windows/i.test(X)?"windows":/mac os/i.test(X)?"osx":/linux/i.test(X)?"linux":/cros/i.test(X)?"cros":null,$="browser"!==Y?null:/Chrome\/|Chromium\/|Edg.*\//.test(X)?"chrome":/Safari\//.test(X)?"safari":/Firefox\//.test(X)?"firefox":"other",j=/xbox/i.test(X),K="browser"===Y&&("ontouchstart"in window||"maxTouchPoints"in navigator&&navigator.maxTouchPoints>0),Z="browser"===Y&&(!!navigator.getGamepads||!!navigator.webkitGetGamepads),Q="undefined"!=typeof Worker,J=(()=>{let e=false;try{let t=Object.defineProperty({},"passive",{get:function(){return e=!0,!1}});window.addEventListener("testpassive",null,t),window.removeEventListener("testpassive",null,t);}catch(e){}return e})(),ee={name:q,environment:Y,global:("undefined"!=typeof globalThis&&globalThis)??("browser"===Y&&window)??("node"===Y&&global)??("worker"===Y&&self),browser:"browser"===Y,worker:"worker"===Y,desktop:["windows","osx","linux","cros"].includes(q),mobile:["android","ios"].includes(q),ios:"ios"===q,android:"android"===q,xbox:j,gamepads:Z,touch:K,workers:Q,passiveEvents:J,browserName:$},et="abcdefghijklmnopqrstuvwxyz",ei="ABCDEFGHIJKLMNOPQRSTUVWXYZ";function es(e,t=0){let i=e.length;if(t<0||t>=i)return null;let s=e.charCodeAt(t);if(i>1&&s>=55296&&s<=56319){let i=e.charCodeAt(t+1);if(i>=56320&&i<=57343)return {code:(s-55296)*1024+i-56320+65536,long:true}}return {code:s,long:false}}function er(e,t,i){if(!e)return false;let s=es(e);if(s){let e=s.code;return e>=t&&e<=i}return false}let ea={ASCII_LOWERCASE:et,ASCII_UPPERCASE:ei,ASCII_LETTERS:et+ei,format(e,...t){for(let i=0;i<t.length;i++)e=e.replace(`{${i}}`,t[i]);return e},getCodePoint(e,t){let i=es(e,t);return i&&i.code},getCodePoints(e){let t;if("string"!=typeof e)throw TypeError("Not a string");let i=0,s=[];for(;t=es(e,i);)s.push(t.code),i+=t.long?2:1;return s},getSymbols(e){let t;if("string"!=typeof e)throw TypeError("Not a string");let i=0,s=e.length,r=[],a=0;for(;i<s;){if(a+=function(e,t){if(t===e.length-1)return 1;if(er(e[t],55296,56319)){let i=e.substring(t,t+2),s=e.substring(t+2,t+4);return er(s,127995,127999)||er(i,127462,127487)&&er(s,127462,127487)?4:er(s,65024,65039)?3:2}return er(e[t+1],65024,65039)?2:1}(e,i+a),er(t=e[i+a],8400,8447)&&(t=e[i+a++]),er(t,65024,65039)&&(t=e[i+a++]),t&&8205===t.charCodeAt(0)){t=e[i+a++];continue}let s=e.substring(i,i+a);r.push(s),i+=a,a=0;}return r},fromCodePoint:(...e)=>e.map(e=>e>65535?String.fromCharCode(((e-=65536)>>10)+55296,e%1024+56320):String.fromCharCode(e)).join("")};class en{constructor(e,t,i,s,r=false){this._removed=false,this.handler=e,this.name=t,this.callback=i,this.scope=s,this._once=r;}off(){this._removed||this.handler.offByHandle(this);}on(e,t,i=this){return this.handler._addCallback(e,t,i,false)}once(e,t,i=this){return this.handler._addCallback(e,t,i,true)}set removed(e){e&&(this._removed=true);}get removed(){return this._removed}toJSON(e){}}class eo{initEventHandler(){this._callbacks=new Map,this._callbackActive=new Map;}_addCallback(e,t,i,s){if(this._callbacks.has(e)||this._callbacks.set(e,[]),this._callbackActive.has(e)){let t=this._callbackActive.get(e);t&&t===this._callbacks.get(e)&&this._callbackActive.set(e,t.slice());}let r=new en(this,e,t,i,s);return this._callbacks.get(e).push(r),r}on(e,t,i=this){return this._addCallback(e,t,i,false)}once(e,t,i=this){return this._addCallback(e,t,i,true)}off(e,t,i){if(e)this._callbackActive.has(e)&&this._callbackActive.get(e)===this._callbacks.get(e)&&this._callbackActive.set(e,this._callbackActive.get(e).slice());else for(let[e,t]of this._callbackActive)this._callbacks.has(e)&&this._callbacks.get(e)===t&&this._callbackActive.set(e,t.slice());if(e)if(t){let s=this._callbacks.get(e);if(!s)return this;for(let e=0;e<s.length;e++)s[e].callback===t&&(!i||s[e].scope===i)&&(s[e].removed=true,s.splice(e,1),e--);0===s.length&&this._callbacks.delete(e);}else {let t=this._callbacks.get(e);if(t){for(let e=0;e<t.length;e++)t[e].removed=true;this._callbacks.delete(e);}}else {for(let e of this._callbacks.values())for(let t=0;t<e.length;t++)e[t].removed=true;this._callbacks.clear();}return this}offByHandle(e){let t=e.name;e.removed=true,this._callbackActive.has(t)&&this._callbackActive.get(t)===this._callbacks.get(t)&&this._callbackActive.set(t,this._callbackActive.get(t).slice());let i=this._callbacks.get(t);if(!i)return this;let s=i.indexOf(e);return -1!==s&&(i.splice(s,1),0===i.length&&this._callbacks.delete(t)),this}fire(e,t,i,s,r,a,n,o,l){let h;if(!e)return this;let c=this._callbacks.get(e);if(!c)return this;this._callbackActive.has(e)?this._callbackActive.get(e)!==c&&(h=c.slice()):this._callbackActive.set(e,c);for(let c=0;(h||this._callbackActive.get(e))&&c<(h||this._callbackActive.get(e)).length;c++){let d=(h||this._callbackActive.get(e))[c];if(d.callback&&(d.callback.call(d.scope,t,i,s,r,a,n,o,l),d._once)){let t=this._callbacks.get(e),i=t?t.indexOf(d):-1;if(-1!==i){this._callbackActive.get(e)===t&&this._callbackActive.set(e,this._callbackActive.get(e).slice());let s=this._callbacks.get(e);if(!s)continue;s[i].removed=true,s.splice(i,1),0===s.length&&this._callbacks.delete(e);}}}return h||this._callbackActive.delete(e),this}hasEvent(e){return !!this._callbacks.get(e)?.length}constructor(){this._callbacks=new Map,this._callbackActive=new Map;}}class el{push(e,t){if(this._index[e])throw Error(`Key already in index ${e}`);let i=this._list.push(t)-1;this._index[e]=i;}has(e){return void 0!==this._index[e]}get(e){let t=this._index[e];return void 0!==t?this._list[t]:null}remove(e){let t=this._index[e];if(void 0!==t){for(e in this._list.splice(t,1),delete this._index[e],this._index){let i=this._index[e];i>t&&(this._index[e]=i-1);}return true}return false}list(){return this._list}clear(){for(let e in this._list.length=0,this._index)delete this._index[e];}constructor(){this._list=[],this._index={};}}let eh=e=>{let t={},i=t;return ()=>(i===t&&(i=e()),i)};class ec{static{this.modules={};}static{this.wasmSupported=eh(()=>{try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){let e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return false});}static loadScript(e,t){let i=document.createElement("script");i.setAttribute("src",e),i.onload=()=>{t(null);},i.onerror=()=>{t(`Failed to load script='${e}'`);},document.body.appendChild(i);}static loadWasm(e,t,i){let s=ec.wasmSupported()&&t.glueUrl&&t.wasmUrl?t.glueUrl:t.fallbackUrl;s?ec.loadScript(s,s=>{if(s)i(s,null);else {let s=window[e];window[e]=void 0,s({locateFile:()=>t.wasmUrl,onAbort:()=>{i("wasm module aborted.");}}).then(e=>{i(null,e);});}}):i("No supported wasm modules found.",null);}static getModule(e){return ec.modules.hasOwnProperty(e)||(ec.modules[e]={config:null,initializing:false,instance:null,callbacks:[]}),ec.modules[e]}static initialize(e,t){if(t.initializing)return;let i=t.config;(i.glueUrl||i.wasmUrl||i.fallbackUrl)&&(t.initializing=true,ec.loadWasm(e,i,(e,s)=>{e?i.errorHandler&&i.errorHandler(e):(t.instance=s,t.callbacks.forEach(e=>{e(s);}));}));}}class ed{static setConfig(e,t){let i=ec.getModule(e);i.config=t,i.callbacks.length>0&&ec.initialize(e,i);}static getConfig(e){return ec.modules?.[e]?.config}static getInstance(e,t){let i=ec.getModule(e);i.instance?t(i.instance):(i.callbacks.push(t),i.config&&ec.initialize(e,i));}}class eu{constructor(e){this.offset=0,this.arraybuffer=e,this.dataView=new DataView(e);}get remainingBytes(){return this.dataView.byteLength-this.offset}reset(e=0){this.offset=e;}skip(e){this.offset+=e;}align(e){this.offset=this.offset+e-1&~(e-1);}_inc(e){return this.offset+=e,this.offset-e}readChar(){return String.fromCharCode(this.dataView.getUint8(this.offset++))}readChars(e){let t="";for(let i=0;i<e;++i)t+=this.readChar();return t}readU8(){return this.dataView.getUint8(this.offset++)}readU16(){return this.dataView.getUint16(this._inc(2),true)}readU32(){return this.dataView.getUint32(this._inc(4),true)}readU64(){return this.readU32()+0x100000000*this.readU32()}readU32be(){return this.dataView.getUint32(this._inc(4),false)}readArray(e){for(let t=0;t<e.length;++t)e[t]=this.readU8();}readLine(){let e=this.dataView,t="";for(;!(this.offset>=e.byteLength);){let e=String.fromCharCode(this.readU8());if("\n"===e)break;t+=e;}return t}}class ef{constructor(e){this.items=[],this.length=0,this.loopIndex=-1,this._sortBy=e.sortBy,this._sortHandler=this._doSort.bind(this);}_binarySearch(e){let t,i,s=0,r=this.items.length-1,a=e[this._sortBy];for(;s<=r;)t=Math.floor((s+r)/2),(i=this.items[t][this._sortBy])<=a?s=t+1:i>a&&(r=t-1);return s}_doSort(e,t){let i=this._sortBy;return e[i]-t[i]}insert(e){let t=this._binarySearch(e);this.items.splice(t,0,e),this.length++,this.loopIndex>=t&&this.loopIndex++;}append(e){this.items.push(e),this.length++;}remove(e){let t=this.items.indexOf(e);!(t<0)&&(this.items.splice(t,1),this.length--,this.loopIndex>=t&&this.loopIndex--);}sort(){let e=this.loopIndex>=0?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler),null!==e&&(this.loopIndex=this.items.indexOf(e));}}class ep extends eo{static{this.EVENT_ADD="add";}static{this.EVENT_REMOVE="remove";}static{this.EVENT_CHANGE="change";}constructor(e){super(),this._index={},this._list=[],this._parent=e;}add(...e){let t=false,i=this._processArguments(e,true);if(!i.length)return t;for(let e=0;e<i.length;e++)this._index[i[e]]||(t=true,this._index[i[e]]=true,this._list.push(i[e]),this.fire("add",i[e],this._parent));return t&&this.fire("change",this._parent),t}remove(...e){let t=false;if(!this._list.length)return t;let i=this._processArguments(e,true);if(!i.length)return t;for(let e=0;e<i.length;e++)this._index[i[e]]&&(t=true,delete this._index[i[e]],this._list.splice(this._list.indexOf(i[e]),1),this.fire("remove",i[e],this._parent));return t&&this.fire("change",this._parent),t}clear(){if(!this._list.length)return;let e=this._list.slice(0);this._list=[],this._index={};for(let t=0;t<e.length;t++)this.fire("remove",e[t],this._parent);this.fire("change",this._parent);}has(...e){return !!this._list.length&&this._has(this._processArguments(e))}_has(e){if(!this._list.length||!e.length)return false;for(let t=0;t<e.length;t++)if(1===e[t].length){if(this._index[e[t][0]])return true}else {let i=true;for(let s=0;s<e[t].length;s++)if(!this._index[e[t][s]]){i=false;break}if(i)return true}return false}list(){return this._list.slice(0)}_processArguments(e,t){let i=[],s=[];if(!e||!e.length)return i;for(let r=0;r<e.length;r++)if(e[r]instanceof Array){t||(s=[]);for(let a=0;a<e[r].length;a++)"string"==typeof e[r][a]&&(t?i.push(e[r][a]):s.push(e[r][a]));!t&&s.length&&i.push(s);}else "string"==typeof e[r]&&(t?i.push(e[r]):i.push([e[r]]));return i}get size(){return this._list.length}}let em="undefined"!=typeof window&&window.performance&&window.performance.now?performance.now.bind(performance):Date.now;function e_(e){let t="";if((e.authority||e.scheme)&&(e.host||e.hostpath))throw Error("Can't have 'scheme' or 'authority' and 'host' or 'hostpath' option");if(e.host&&e.hostpath)throw Error("Can't have 'host' and 'hostpath' option");if(e.path&&e.hostpath)throw Error("Can't have 'path' and 'hostpath' option");return e.scheme&&(t+=`${e.scheme}:`),e.authority&&(t+=`//${e.authority}`),e.host&&(t+=e.host),e.path&&(t+=e.path),e.hostpath&&(t+=e.hostpath),e.query&&(t+=`?${e.query}`),e.fragment&&(t+=`#${e.fragment}`),t}let eg=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class ev{constructor(e){let t=e.match(eg);this.scheme=t[2],this.authority=t[4],this.path=t[5],this.query=t[7],this.fragment=t[9];}toString(){let e="";return this.scheme&&(e+=`${this.scheme}:`),this.authority&&(e+=`//${this.authority}`),e+=this.path,this.query&&(e+=`?${this.query}`),this.fragment&&(e+=`#${this.fragment}`),e}getQuery(){let e={};if(this.query)for(let t of decodeURIComponent(this.query).split("&")){let i=t.split("=");e[i[0]]=i[1];}return e}setQuery(e){let t="";for(let i in e)e.hasOwnProperty(i)&&(""!==t&&(t+="&"),t+=`${encodeURIComponent(i)}=${encodeURIComponent(e[i])}`);this.query=t;}}class eS{static{this._traceChannels=new Set;}static{this.stack=false;}static set(e,t=true){}static get(e){return eS._traceChannels.has(e)}}let ey=0,ex=1,eT=4,eE=5,eA={DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,clamp:(e,t,i)=>e>=i?i:e<=t?t:e,intToBytes24:e=>[e>>16&255,e>>8&255,255&e],intToBytes32:e=>[e>>24&255,e>>16&255,e>>8&255,255&e],bytesToInt24:(e,t,i)=>(e.length&&(i=e[2],t=e[1],e=e[0]),e<<16|t<<8|i),bytesToInt32:(e,t,i,s)=>(e.length&&(s=e[3],i=e[2],t=e[1],e=e[0]),(e<<24|t<<16|i<<8|s)>>>0),lerp:(e,t,i)=>e+(t-e)*eA.clamp(i,0,1),lerpAngle:(e,t,i)=>(t-e>180&&(t-=360),t-e<-180&&(t+=360),eA.lerp(e,t,eA.clamp(i,0,1))),powerOfTwo:e=>0!==e&&!(e&e-1),nextPowerOfTwo:e=>(e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e),nearestPowerOfTwo:e=>Math.pow(2,Math.round(Math.log2(e))),random:(e,t)=>Math.random()*(t-e)+e,smoothstep:(e,t,i)=>i<=e?0:i>=t?1:(i=(i-e)/(t-e))*i*(3-2*i),smootherstep:(e,t,i)=>i<=e?0:i>=t?1:(i=(i-e)/(t-e))*i*i*(i*(6*i-15)+10),roundUp:(e,t)=>0===t?e:Math.ceil(e/t)*t,between(e,t,i,s){let r=Math.min(t,i),a=Math.max(t,i);return s?e>=r&&e<=a:e>r&&e<a}};class eb{constructor(e=0,t=0,i=0,s=1){let r=e.length;3===r||4===r?(this.r=e[0],this.g=e[1],this.b=e[2],this.a=e[3]??1):(this.r=e,this.g=t,this.b=i,this.a=s);}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}equals(e){return this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}set(e,t,i,s=1){return this.r=e,this.g=t,this.b=i,this.a=s,this}lerp(e,t,i){return this.r=e.r+i*(t.r-e.r),this.g=e.g+i*(t.g-e.g),this.b=e.b+i*(t.b-e.b),this.a=e.a+i*(t.a-e.a),this}linear(e=this){return this.r=Math.pow(e.r,2.2),this.g=Math.pow(e.g,2.2),this.b=Math.pow(e.b,2.2),this.a=e.a,this}gamma(e=this){return this.r=Math.pow(e.r,1/2.2),this.g=Math.pow(e.g,1/2.2),this.b=Math.pow(e.b,1/2.2),this.a=e.a,this}mulScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}fromString(e){let t,i=parseInt(e.replace("#","0x"),16);return e.length>7?t=eA.intToBytes32(i):(t=eA.intToBytes24(i))[3]=255,this.set(t[0]/255,t[1]/255,t[2]/255,t[3]/255),this}fromArray(e,t=0){return this.r=e[t]??this.r,this.g=e[t+1]??this.g,this.b=e[t+2]??this.b,this.a=e[t+3]??this.a,this}toString(e,t){let{r:i,g:s,b:r,a}=this;if(t||i>1||s>1||r>1)return `${i.toFixed(3)}, ${s.toFixed(3)}, ${r.toFixed(3)}, ${a.toFixed(3)}`;let n=`#${(0x1000000+(Math.round(255*i)<<16)+(Math.round(255*s)<<8)+Math.round(255*r)).toString(16).slice(1)}`;if(true===e){let e=Math.round(255*a).toString(16);this.a<16/255?n+=`0${e}`:n+=e;}return n}toArray(e=[],t=0,i=true){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,i&&(e[t+3]=this.a),e}static{this.BLACK=Object.freeze(new eb(0,0,0,1));}static{this.BLUE=Object.freeze(new eb(0,0,1,1));}static{this.CYAN=Object.freeze(new eb(0,1,1,1));}static{this.GRAY=Object.freeze(new eb(.5,.5,.5,1));}static{this.GREEN=Object.freeze(new eb(0,1,0,1));}static{this.MAGENTA=Object.freeze(new eb(1,0,1,1));}static{this.RED=Object.freeze(new eb(1,0,0,1));}static{this.WHITE=Object.freeze(new eb(1,1,1,1));}static{this.YELLOW=Object.freeze(new eb(1,1,0,1));}}class ew{constructor(e,t=0){this._left=-1/0,this._right=1/0,this._recip=0,this._p0=0,this._p1=0,this._m0=0,this._m1=0,this._curve=e,this._reset(t);}evaluate(e,t=false){let i;(t||e<this._left||e>=this._right)&&this._reset(e);let s=this._curve.type;if(s===eE)i=this._p0;else {let t=0===this._recip?0:(e-this._left)*this._recip;i=s===ey?eA.lerp(this._p0,this._p1,t):s===ex?eA.lerp(this._p0,this._p1,t*t*(3-2*t)):this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,t);}return i}_reset(e){let t=this._curve.keys,i=t.length;if(i)if(e<t[0][0])this._left=-1/0,this._right=t[0][0],this._recip=0,this._p0=this._p1=t[0][1],this._m0=this._m1=0;else if(e>=t[i-1][0])this._left=t[i-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=t[i-1][1],this._m0=this._m1=0;else {let i=0;for(;e>=t[i+1][0];)i++;this._left=t[i][0],this._right=t[i+1][0];let s=1/(this._right-this._left);this._recip=isFinite(s)?s:0,this._p0=t[i][1],this._p1=t[i+1][1],this._curve.type===eT&&this._calcTangents(t,i);}else this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0;}_calcTangents(e,t){let i,s,r=e[t],a=e[t+1];if(i=0===t?[e[0][0]+(e[0][0]-e[1][0]),e[0][1]+(e[0][1]-e[1][1])]:e[t-1],s=t===e.length-2?[e[t+1][0]+(e[t+1][0]-e[t][0]),e[t+1][1]+(e[t+1][1]-e[t][1])]:e[t+2],this._curve.type===eT){let e=2*(a[0]-r[0])/(a[0]-i[0]),t=2*(a[0]-r[0])/(s[0]-r[0]);this._m0=this._curve.tension*(isFinite(e)?e:0)*(a[1]-i[1]),this._m1=this._curve.tension*(isFinite(t)?t:0)*(s[1]-r[1]);}else {let e=(a[0]-r[0])/(r[0]-i[0]),t=(a[0]-r[0])/(s[0]-a[0]),n=r[1]+(i[1]-r[1])*(isFinite(e)?e:0),o=a[1]+(s[1]-a[1])*(isFinite(t)?t:0),l=this._curve.tension;this._m0=l*(a[1]-n),this._m1=l*(o-r[1]);}}_evaluateHermite(e,t,i,s,r){let a=r*r,n=r+r,o=1-r,l=o*o;return (1+n)*l*e+r*l*i+a*(3-n)*t+a*(r-1)*s}}class eC{constructor(e){if(this.keys=[],this.type=ex,this.tension=.5,this._eval=new ew(this),e)for(let t=0;t<e.length-1;t+=2)this.keys.push([e[t],e[t+1]]);this.sort();}get length(){return this.keys.length}add(e,t){let i=this.keys,s=i.length,r=0;for(;r<s&&!(i[r][0]>e);r++);let a=[e,t];return this.keys.splice(r,0,a),a}get(e){return this.keys[e]}sort(){this.keys.sort((e,t)=>e[0]-t[0]);}value(e){return this._eval.evaluate(e,true)}closest(e){let t=this.keys,i=t.length,s=2,r=null;for(let a=0;a<i;a++){let i=Math.abs(e-t[a][0]);if(s>=i)s=i,r=t[a];else break}return r}clone(){let e=new this.constructor;return e.keys=this.keys.map(e=>[...e]),e.type=this.type,e.tension=this.tension,e}quantize(e){let t=new Float32Array(e=Math.max(e,2)),i=1/(e-1);t[0]=this._eval.evaluate(0,true);for(let s=1;s<e;s++)t[s]=this._eval.evaluate(i*s);return t}quantizeClamped(e,t,i){let s=this.quantize(e);for(let e=0;e<s.length;++e)s[e]=Math.min(i,Math.max(t,s[e]));return s}}class eP{constructor(...e){if(this.curves=[],this._type=ex,e.length>1)for(let t=0;t<e.length;t++)this.curves.push(new eC(e[t]));else if(0===e.length)this.curves.push(new eC);else {let t=e[0];if("number"==typeof t)for(let e=0;e<t;e++)this.curves.push(new eC);else for(let e=0;e<t.length;e++)this.curves.push(new eC(t[e]));}}get length(){return this.curves.length}set type(e){this._type=e;for(let t=0;t<this.curves.length;t++)this.curves[t].type=e;}get type(){return this._type}get(e){return this.curves[e]}value(e,t=[]){let i=this.curves.length;t.length=i;for(let s=0;s<i;s++)t[s]=this.curves[s].value(e);return t}clone(){let e=new this.constructor;e.curves=[];for(let t=0;t<this.curves.length;t++)e.curves.push(this.curves[t].clone());return e._type=this._type,e}quantize(e){e=Math.max(e,2);let t=this.curves.length,i=new Float32Array(e*t),s=1/(e-1);for(let r=0;r<t;r++){let a=new ew(this.curves[r]);for(let n=0;n<e;n++)i[n*t+r]=a.evaluate(s*n);}return i}quantizeClamped(e,t,i){let s=this.quantize(e);for(let e=0;e<s.length;++e)s[e]=Math.min(i,Math.max(t,s[e]));return s}}let eL=new Float32Array(1),eI=new Int32Array(eL.buffer);class eD{static float2Half(e){eL[0]=e;let t=eI[0],i=t>>16&32768,s=t>>12&2047,r=t>>23&255;return r<103?i:r>142?(i|=31744,i|=+(255!==r)&&8388607&t):r<113?(s|=2048,i|=(s>>114-r)+(s>>113-r&1)):(i|=r-112<<10|s>>1,i+=1&s)}static float2RGBA8(e,t){eL[0]=e;let i=eI[0];t.r=(i>>24&255)/255,t.g=(i>>16&255)/255,t.b=(i>>8&255)/255,t.a=(255&i)/255;}}class eR{static concentric(e,t){let i=[];i.push(0,0);let s=2*Math.PI/e/t;for(let t=1;t<=e;t++){let r=t/e,a=Math.max(1,Math.floor(2*Math.PI*r/s)),n=2*Math.PI/a;for(let e=0;e<a;e++){let t=e*n,s=r*Math.cos(t),a=r*Math.sin(t);i.push(s,a);}}return i}}class eM{constructor(e=0,t=0,i=0){3===e.length?(this.x=e[0],this.y=e[1],this.z=e[2]):(this.x=e,this.y=t,this.z=i);}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}add2(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addScaled(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}cross(e,t){let i=e.x,s=e.y,r=e.z,a=t.x,n=t.y,o=t.z;return this.x=s*o-n*r,this.y=r*a-o*i,this.z=i*n-a*s,this}distance(e){let t=this.x-e.x,i=this.y-e.y,s=this.z-e.z;return Math.sqrt(t*t+i*i+s*s)}div(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}div2(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this.z=e.z/t.z,this}divScalar(e){return this.x/=e,this.y/=e,this.z/=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}equals(e){return this.x===e.x&&this.y===e.y&&this.z===e.z}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)<t&&Math.abs(this.y-e.y)<t&&Math.abs(this.z-e.z)<t}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}lerp(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this.z=e.z+i*(t.z-e.z),this}mul(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}mul2(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}mulScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}normalize(e=this){let t=e.x*e.x+e.y*e.y+e.z*e.z;if(t>0){let i=1/Math.sqrt(t);this.x=e.x*i,this.y=e.y*i,this.z=e.z*i;}return this}floor(e=this){return this.x=Math.floor(e.x),this.y=Math.floor(e.y),this.z=Math.floor(e.z),this}ceil(e=this){return this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this.z=Math.ceil(e.z),this}round(e=this){return this.x=Math.round(e.x),this.y=Math.round(e.y),this.z=Math.round(e.z),this}min(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),this}max(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this}project(e){let t=(this.x*e.x+this.y*e.y+this.z*e.z)/(e.x*e.x+e.y*e.y+e.z*e.z);return this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this}set(e,t,i){return this.x=e,this.y=t,this.z=i,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}sub2(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this.z=e[t+2]??this.z,this}toString(){return `[${this.x}, ${this.y}, ${this.z}]`}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}static{this.ZERO=Object.freeze(new eM(0,0,0));}static{this.HALF=Object.freeze(new eM(.5,.5,.5));}static{this.ONE=Object.freeze(new eM(1,1,1));}static{this.UP=Object.freeze(new eM(0,1,0));}static{this.DOWN=Object.freeze(new eM(0,-1,0));}static{this.RIGHT=Object.freeze(new eM(1,0,0));}static{this.LEFT=Object.freeze(new eM(-1,0,0));}static{this.FORWARD=Object.freeze(new eM(0,0,-1));}static{this.BACK=Object.freeze(new eM(0,0,1));}}class eO{constructor(){this.data=new Float32Array(9),this.data[0]=this.data[4]=this.data[8]=1;}clone(){return new this.constructor().copy(this)}copy(e){let t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],this}set(e){let t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],this}getX(e=new eM){return e.set(this.data[0],this.data[1],this.data[2])}getY(e=new eM){return e.set(this.data[3],this.data[4],this.data[5])}getZ(e=new eM){return e.set(this.data[6],this.data[7],this.data[8])}equals(e){let t=this.data,i=e.data;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]}isIdentity(){let e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&1===e[4]&&0===e[5]&&0===e[6]&&0===e[7]&&1===e[8]}setIdentity(){let e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,this}toString(){return `[${this.data.join(", ")}]`}transpose(e=this){let t=e.data,i=this.data;if(t===i){let e;e=t[1],i[1]=t[3],i[3]=e,e=t[2],i[2]=t[6],i[6]=e,e=t[5],i[5]=t[7],i[7]=e;}else i[0]=t[0],i[1]=t[3],i[2]=t[6],i[3]=t[1],i[4]=t[4],i[5]=t[7],i[6]=t[2],i[7]=t[5],i[8]=t[8];return this}setFromMat4(e){let t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[4],i[4]=t[5],i[5]=t[6],i[6]=t[8],i[7]=t[9],i[8]=t[10],this}setFromQuat(e){let t=e.x,i=e.y,s=e.z,r=e.w,a=t+t,n=i+i,o=s+s,l=t*a,h=t*n,c=t*o,d=i*n,u=i*o,f=s*o,p=r*a,m=r*n,_=r*o,g=this.data;return g[0]=1-(d+f),g[1]=h+_,g[2]=c-m,g[3]=h-_,g[4]=1-(l+f),g[5]=u+p,g[6]=c+m,g[7]=u-p,g[8]=1-(l+d),this}invertMat4(e){let t=e.data,i=t[0],s=t[1],r=t[2],a=t[4],n=t[5],o=t[6],l=t[8],h=t[9],c=t[10],d=c*n-o*h,u=-c*a+o*l,f=h*a-n*l,p=i*d+s*u+r*f;if(0===p)this.setIdentity();else {let e=1/p,t=this.data;t[0]=d*e,t[1]=(-c*s+r*h)*e,t[2]=(o*s-r*n)*e,t[3]=u*e,t[4]=(c*i-r*l)*e,t[5]=(-o*i+r*a)*e,t[6]=f*e,t[7]=(-h*i+s*l)*e,t[8]=(n*i-s*a)*e;}return this}transformVector(e,t=new eM){let i=this.data,{x:s,y:r,z:a}=e;return t.x=s*i[0]+r*i[3]+a*i[6],t.y=s*i[1]+r*i[4]+a*i[7],t.z=s*i[2]+r*i[5]+a*i[8],t}static{this.IDENTITY=Object.freeze(new eO);}static{this.ZERO=Object.freeze(new eO().set([0,0,0,0,0,0,0,0,0]));}}class eN{constructor(e=0,t=0){2===e.length?(this.x=e[0],this.y=e[1]):(this.x=e,this.y=t);}add(e){return this.x+=e.x,this.y+=e.y,this}add2(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addScaled(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}cross(e){return this.x*e.y-this.y*e.x}distance(e){let t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)}div(e){return this.x/=e.x,this.y/=e.y,this}div2(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this}divScalar(e){return this.x/=e,this.y/=e,this}dot(e){return this.x*e.x+this.y*e.y}equals(e){return this.x===e.x&&this.y===e.y}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)<t&&Math.abs(this.y-e.y)<t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSq(){return this.x*this.x+this.y*this.y}lerp(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this}mul(e){return this.x*=e.x,this.y*=e.y,this}mul2(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this}mulScalar(e){return this.x*=e,this.y*=e,this}normalize(e=this){let t=e.x*e.x+e.y*e.y;if(t>0){let i=1/Math.sqrt(t);this.x=e.x*i,this.y=e.y*i;}return this}rotate(e){let t=Math.atan2(this.x,this.y)+e*eA.DEG_TO_RAD,i=Math.sqrt(this.x*this.x+this.y*this.y);return this.x=Math.sin(t)*i,this.y=Math.cos(t)*i,this}angle(){return Math.atan2(this.x,this.y)*eA.RAD_TO_DEG}angleTo(e){return Math.atan2(this.x*e.y+this.y*e.x,this.x*e.x+this.y*e.y)*eA.RAD_TO_DEG}floor(e=this){return this.x=Math.floor(e.x),this.y=Math.floor(e.y),this}ceil(e=this){return this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this}round(e=this){return this.x=Math.round(e.x),this.y=Math.round(e.y),this}min(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),this}max(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),this}set(e,t){return this.x=e,this.y=t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}sub2(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}subScalar(e){return this.x-=e,this.y-=e,this}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this}toString(){return `[${this.x}, ${this.y}]`}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}static angleRad(e,t){return Math.atan2(e.x*t.y-e.y*t.x,e.x*t.x+e.y*t.y)}static{this.ZERO=Object.freeze(new eN(0,0));}static{this.HALF=Object.freeze(new eN(.5,.5));}static{this.ONE=Object.freeze(new eN(1,1));}static{this.UP=Object.freeze(new eN(0,1));}static{this.DOWN=Object.freeze(new eN(0,-1));}static{this.RIGHT=Object.freeze(new eN(1,0));}static{this.LEFT=Object.freeze(new eN(-1,0));}}class eF{constructor(e=0,t=0,i=0,s=0){4===e.length?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=i,this.w=s);}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}add2(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addScaled(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}div(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}div2(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this.z=e.z/t.z,this.w=e.w/t.w,this}divScalar(e){return this.x/=e,this.y/=e,this.z/=e,this.w/=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}equals(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)<t&&Math.abs(this.y-e.y)<t&&Math.abs(this.z-e.z)<t&&Math.abs(this.w-e.w)<t}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}lerp(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this.z=e.z+i*(t.z-e.z),this.w=e.w+i*(t.w-e.w),this}mul(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}mul2(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this.w=e.w*t.w,this}mulScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}normalize(e=this){let t=e.x*e.x+e.y*e.y+e.z*e.z+e.w*e.w;if(t>0){let i=1/Math.sqrt(t);this.x=e.x*i,this.y=e.y*i,this.z=e.z*i,this.w=e.w*i;}return this}floor(e=this){return this.x=Math.floor(e.x),this.y=Math.floor(e.y),this.z=Math.floor(e.z),this.w=Math.floor(e.w),this}ceil(e=this){return this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this.z=Math.ceil(e.z),this.w=Math.ceil(e.w),this}round(e=this){return this.x=Math.round(e.x),this.y=Math.round(e.y),this.z=Math.round(e.z),this.w=Math.round(e.w),this}min(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this}max(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}sub2(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this.z=e[t+2]??this.z,this.w=e[t+3]??this.w,this}toString(){return `[${this.x}, ${this.y}, ${this.z}, ${this.w}]`}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}static{this.ZERO=Object.freeze(new eF(0,0,0,0));}static{this.HALF=Object.freeze(new eF(.5,.5,.5,.5));}static{this.ONE=Object.freeze(new eF(1,1,1,1));}}let eB=new eN,eU=new eM,ek=new eM,eV=new eM,ez=new eM;class eG{constructor(){this.data=new Float32Array(16),this.data[0]=this.data[5]=this.data[10]=this.data[15]=1;}static _getPerspectiveHalfSize(e,t,i,s,r){r?(e.x=s*Math.tan(t*Math.PI/360),e.y=e.x/i):(e.y=s*Math.tan(t*Math.PI/360),e.x=e.y*i);}add2(e,t){let i=e.data,s=t.data,r=this.data;return r[0]=i[0]+s[0],r[1]=i[1]+s[1],r[2]=i[2]+s[2],r[3]=i[3]+s[3],r[4]=i[4]+s[4],r[5]=i[5]+s[5],r[6]=i[6]+s[6],r[7]=i[7]+s[7],r[8]=i[8]+s[8],r[9]=i[9]+s[9],r[10]=i[10]+s[10],r[11]=i[11]+s[11],r[12]=i[12]+s[12],r[13]=i[13]+s[13],r[14]=i[14]+s[14],r[15]=i[15]+s[15],this}add(e){return this.add2(this,e)}clone(){return new this.constructor().copy(this)}copy(e){let t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],i[9]=t[9],i[10]=t[10],i[11]=t[11],i[12]=t[12],i[13]=t[13],i[14]=t[14],i[15]=t[15],this}equals(e){let t=this.data,i=e.data;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]}isIdentity(){let e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}mul2(e,t){let i,s,r,a,n=e.data,o=t.data,l=this.data,h=n[0],c=n[1],d=n[2],u=n[3],f=n[4],p=n[5],m=n[6],_=n[7],g=n[8],v=n[9],S=n[10],y=n[11],x=n[12],T=n[13],E=n[14],A=n[15];return i=o[0],s=o[1],r=o[2],a=o[3],l[0]=h*i+f*s+g*r+x*a,l[1]=c*i+p*s+v*r+T*a,l[2]=d*i+m*s+S*r+E*a,l[3]=u*i+_*s+y*r+A*a,i=o[4],s=o[5],r=o[6],a=o[7],l[4]=h*i+f*s+g*r+x*a,l[5]=c*i+p*s+v*r+T*a,l[6]=d*i+m*s+S*r+E*a,l[7]=u*i+_*s+y*r+A*a,i=o[8],s=o[9],r=o[10],a=o[11],l[8]=h*i+f*s+g*r+x*a,l[9]=c*i+p*s+v*r+T*a,l[10]=d*i+m*s+S*r+E*a,l[11]=u*i+_*s+y*r+A*a,i=o[12],s=o[13],r=o[14],a=o[15],l[12]=h*i+f*s+g*r+x*a,l[13]=c*i+p*s+v*r+T*a,l[14]=d*i+m*s+S*r+E*a,l[15]=u*i+_*s+y*r+A*a,this}mulAffine2(e,t){let i,s,r,a=e.data,n=t.data,o=this.data,l=a[0],h=a[1],c=a[2],d=a[4],u=a[5],f=a[6],p=a[8],m=a[9],_=a[10],g=a[12],v=a[13],S=a[14];return i=n[0],s=n[1],r=n[2],o[0]=l*i+d*s+p*r,o[1]=h*i+u*s+m*r,o[2]=c*i+f*s+_*r,o[3]=0,i=n[4],s=n[5],r=n[6],o[4]=l*i+d*s+p*r,o[5]=h*i+u*s+m*r,o[6]=c*i+f*s+_*r,o[7]=0,i=n[8],s=n[9],r=n[10],o[8]=l*i+d*s+p*r,o[9]=h*i+u*s+m*r,o[10]=c*i+f*s+_*r,o[11]=0,i=n[12],s=n[13],r=n[14],o[12]=l*i+d*s+p*r+g,o[13]=h*i+u*s+m*r+v,o[14]=c*i+f*s+_*r+S,o[15]=1,this}mul(e){return this.mul2(this,e)}transformPoint(e,t=new eM){let i=this.data,{x:s,y:r,z:a}=e;return t.x=s*i[0]+r*i[4]+a*i[8]+i[12],t.y=s*i[1]+r*i[5]+a*i[9]+i[13],t.z=s*i[2]+r*i[6]+a*i[10]+i[14],t}transformVector(e,t=new eM){let i=this.data,{x:s,y:r,z:a}=e;return t.x=s*i[0]+r*i[4]+a*i[8],t.y=s*i[1]+r*i[5]+a*i[9],t.z=s*i[2]+r*i[6]+a*i[10],t}transformVec4(e,t=new eF){let i=this.data,{x:s,y:r,z:a,w:n}=e;return t.x=s*i[0]+r*i[4]+a*i[8]+n*i[12],t.y=s*i[1]+r*i[5]+a*i[9]+n*i[13],t.z=s*i[2]+r*i[6]+a*i[10]+n*i[14],t.w=s*i[3]+r*i[7]+a*i[11]+n*i[15],t}setLookAt(e,t,i){eV.sub2(e,t).normalize(),ek.copy(i).normalize(),eU.cross(ek,eV).normalize(),ek.cross(eV,eU);let s=this.data;return s[0]=eU.x,s[1]=eU.y,s[2]=eU.z,s[3]=0,s[4]=ek.x,s[5]=ek.y,s[6]=ek.z,s[7]=0,s[8]=eV.x,s[9]=eV.y,s[10]=eV.z,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}setFrustum(e,t,i,s,r,a){let n=2*r,o=t-e,l=s-i,h=a-r,c=this.data;return c[0]=n/o,c[1]=0,c[2]=0,c[3]=0,c[4]=0,c[5]=n/l,c[6]=0,c[7]=0,c[8]=(t+e)/o,c[9]=(s+i)/l,c[10]=(-a-r)/h,c[11]=-1,c[12]=0,c[13]=0,c[14]=-n*a/h,c[15]=0,this}setPerspective(e,t,i,s,r){return eG._getPerspectiveHalfSize(eB,e,t,i,r),this.setFrustum(-eB.x,eB.x,-eB.y,eB.y,i,s)}setOrtho(e,t,i,s,r,a){let n=this.data;return n[0]=2/(t-e),n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/(s-i),n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/(a-r),n[11]=0,n[12]=-(t+e)/(t-e),n[13]=-(s+i)/(s-i),n[14]=-(a+r)/(a-r),n[15]=1,this}setFromAxisAngle(e,t){t*=eA.DEG_TO_RAD;let{x:i,y:s,z:r}=e,a=Math.cos(t),n=Math.sin(t),o=1-a,l=o*i,h=o*s,c=this.data;return c[0]=l*i+a,c[1]=l*s+n*r,c[2]=l*r-n*s,c[3]=0,c[4]=l*s-n*r,c[5]=h*s+a,c[6]=h*r+n*i,c[7]=0,c[8]=l*r+n*s,c[9]=h*r-i*n,c[10]=o*r*r+a,c[11]=0,c[12]=0,c[13]=0,c[14]=0,c[15]=1,this}setTranslate(e,t,i){let s=this.data;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=e,s[13]=t,s[14]=i,s[15]=1,this}setScale(e,t,i){let s=this.data;return s[0]=e,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=t,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=i,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,this}setViewport(e,t,i,s){let r=this.data;return r[0]=.5*i,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=.5*s,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=.5,r[11]=0,r[12]=e+.5*i,r[13]=t+.5*s,r[14]=.5,r[15]=1,this}setReflection(e,t){let i=e.x,s=e.y,r=e.z,a=this.data;return a[0]=1-2*i*i,a[1]=-2*i*s,a[2]=-2*i*r,a[3]=0,a[4]=-2*i*s,a[5]=1-2*s*s,a[6]=-2*s*r,a[7]=0,a[8]=-2*i*r,a[9]=-2*s*r,a[10]=1-2*r*r,a[11]=0,a[12]=-2*i*t,a[13]=-2*s*t,a[14]=-2*r*t,a[15]=1,this}invert(e=this){let t=e.data,i=t[0],s=t[1],r=t[2],a=t[3],n=t[4],o=t[5],l=t[6],h=t[7],c=t[8],d=t[9],u=t[10],f=t[11],p=t[12],m=t[13],_=t[14],g=t[15],v=i*o-s*n,S=i*l-r*n,y=i*h-a*n,x=s*l-r*o,T=s*h-a*o,E=r*h-a*l,A=c*m-d*p,b=c*_-u*p,w=c*g-f*p,C=d*_-u*m,P=d*g-f*m,L=u*g-f*_,I=v*L-S*P+y*C+x*w-T*b+E*A;if(0===I)this.setIdentity();else {let e=1/I,t=this.data;t[0]=(o*L-l*P+h*C)*e,t[1]=(-s*L+r*P-a*C)*e,t[2]=(m*E-_*T+g*x)*e,t[3]=(-d*E+u*T-f*x)*e,t[4]=(-n*L+l*w-h*b)*e,t[5]=(i*L-r*w+a*b)*e,t[6]=(-p*E+_*y-g*S)*e,t[7]=(c*E-u*y+f*S)*e,t[8]=(n*P-o*w+h*A)*e,t[9]=(-i*P+s*w-a*A)*e,t[10]=(p*T-m*y+g*v)*e,t[11]=(-c*T+d*y-f*v)*e,t[12]=(-n*C+o*b-l*A)*e,t[13]=(i*C-s*b+r*A)*e,t[14]=(-p*x+m*S-_*v)*e,t[15]=(c*x-d*S+u*v)*e;}return this}set(e){let t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],this}setIdentity(){let e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}setTRS(e,t,i){let s=t.x,r=t.y,a=t.z,n=t.w,o=i.x,l=i.y,h=i.z,c=s+s,d=r+r,u=a+a,f=s*c,p=s*d,m=s*u,_=r*d,g=r*u,v=a*u,S=n*c,y=n*d,x=n*u,T=this.data;return T[0]=(1-(_+v))*o,T[1]=(p+x)*o,T[2]=(m-y)*o,T[3]=0,T[4]=(p-x)*l,T[5]=(1-(f+v))*l,T[6]=(g+S)*l,T[7]=0,T[8]=(m+y)*h,T[9]=(g-S)*h,T[10]=(1-(f+_))*h,T[11]=0,T[12]=e.x,T[13]=e.y,T[14]=e.z,T[15]=1,this}transpose(e=this){let t=e.data,i=this.data;if(t===i){let e;e=t[1],i[1]=t[4],i[4]=e,e=t[2],i[2]=t[8],i[8]=e,e=t[3],i[3]=t[12],i[12]=e,e=t[6],i[6]=t[9],i[9]=e,e=t[7],i[7]=t[13],i[13]=e,e=t[11],i[11]=t[14],i[14]=e;}else i[0]=t[0],i[1]=t[4],i[2]=t[8],i[3]=t[12],i[4]=t[1],i[5]=t[5],i[6]=t[9],i[7]=t[13],i[8]=t[2],i[9]=t[6],i[10]=t[10],i[11]=t[14],i[12]=t[3],i[13]=t[7],i[14]=t[11],i[15]=t[15];return this}getTranslation(e=new eM){return e.set(this.data[12],this.data[13],this.data[14])}getX(e=new eM){return e.set(this.data[0],this.data[1],this.data[2])}getY(e=new eM){return e.set(this.data[4],this.data[5],this.data[6])}getZ(e=new eM){return e.set(this.data[8],this.data[9],this.data[10])}getScale(e=new eM){return this.getX(eU),this.getY(ek),this.getZ(eV),e.set(eU.length(),ek.length(),eV.length()),e}get scaleSign(){return this.getX(eU),this.getY(ek),this.getZ(eV),eU.cross(eU,ek),0>eU.dot(eV)?-1:1}setFromEulerAngles(e,t,i){e*=eA.DEG_TO_RAD,t*=eA.DEG_TO_RAD,i*=eA.DEG_TO_RAD;let s=Math.sin(-e),r=Math.cos(-e),a=Math.sin(-t),n=Math.cos(-t),o=Math.sin(-i),l=Math.cos(-i),h=this.data;return h[0]=n*l,h[1]=-n*o,h[2]=a,h[3]=0,h[4]=r*o+l*s*a,h[5]=r*l-s*a*o,h[6]=-n*s,h[7]=0,h[8]=s*o-r*l*a,h[9]=l*s+r*a*o,h[10]=r*n,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,this}getEulerAngles(e=new eM){let t,i;this.getScale(ez);let s=ez.x,r=ez.y,a=ez.z;if(0===s||0===r||0===a)return e.set(0,0,0);let n=this.data,o=Math.asin(-n[2]/s),l=.5*Math.PI;return o<l?o>-l?(t=Math.atan2(n[6]/r,n[10]/a),i=Math.atan2(n[1]/s,n[0]/s)):(i=0,t=-Math.atan2(n[4]/r,n[5]/r)):(i=0,t=Math.atan2(n[4]/r,n[5]/r)),e.set(t,o,i).mulScalar(eA.RAD_TO_DEG)}toString(){return `[${this.data.join(", ")}]`}static{this.IDENTITY=Object.freeze(new eG);}static{this.ZERO=Object.freeze(new eG().set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]));}}class eH{constructor(e=0,t=0,i=0,s=1){4===e.length?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=i,this.w=s);}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}conjugate(e=this){return this.x=-1*e.x,this.y=-1*e.y,this.z=-1*e.z,this.w=e.w,this}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}equals(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)<t&&Math.abs(this.y-e.y)<t&&Math.abs(this.z-e.z)<t&&Math.abs(this.w-e.w)<t}getAxisAngle(e){let t=2*Math.acos(this.w),i=Math.sin(t/2);return 0!==i?(e.x=this.x/i,e.y=this.y/i,e.z=this.z/i,(e.x<0||e.y<0||e.z<0)&&(e.x*=-1,e.y*=-1,e.z*=-1,t*=-1)):(e.x=1,e.y=0,e.z=0),t*eA.RAD_TO_DEG}getEulerAngles(e=new eM){let t,i,s,r=this.x,a=this.y,n=this.z,o=this.w,l=2*(o*a-r*n);return l<=-0.99999?(t=2*Math.atan2(r,o),i=-Math.PI/2,s=0):l>=.99999?(t=2*Math.atan2(r,o),i=Math.PI/2,s=0):(t=Math.atan2(2*(o*r+a*n),1-2*(r*r+a*a)),i=Math.asin(l),s=Math.atan2(2*(o*n+r*a),1-2*(a*a+n*n))),e.set(t,i,s).mulScalar(eA.RAD_TO_DEG)}invert(e=this){return this.conjugate(e).normalize()}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}lerp(e,t,i){let s=(1-i)*(0>e.dot(t)?-1:1);return this.x=e.x*s+t.x*i,this.y=e.y*s+t.y*i,this.z=e.z*s+t.z*i,this.w=e.w*s+t.w*i,this.normalize()}mul(e){let t=this.x,i=this.y,s=this.z,r=this.w,a=e.x,n=e.y,o=e.z,l=e.w;return this.x=r*a+t*l+i*o-s*n,this.y=r*n+i*l+s*a-t*o,this.z=r*o+s*l+t*n-i*a,this.w=r*l-t*a-i*n-s*o,this}mulScalar(e,t=this){return this.x=t.x*e,this.y=t.y*e,this.z=t.z*e,this.w=t.w*e,this}mul2(e,t){let i=e.x,s=e.y,r=e.z,a=e.w,n=t.x,o=t.y,l=t.z,h=t.w;return this.x=a*n+i*h+s*l-r*o,this.y=a*o+s*h+r*n-i*l,this.z=a*l+r*h+i*o-s*n,this.w=a*h-i*n-s*o-r*l,this}normalize(e=this){let t=e.length();return 0===t?(this.x=this.y=this.z=0,this.w=1):(t=1/t,this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this.w=e.w*t),this}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}setFromAxisAngle(e,t){let i=Math.sin(t*=.5*eA.DEG_TO_RAD),s=Math.cos(t);return this.x=i*e.x,this.y=i*e.y,this.z=i*e.z,this.w=s,this}setFromEulerAngles(e,t,i){if(e instanceof eM){let s=e;e=s.x,t=s.y,i=s.z;}let s=.5*eA.DEG_TO_RAD;e*=s,t*=s,i*=s;let r=Math.sin(e),a=Math.cos(e),n=Math.sin(t),o=Math.cos(t),l=Math.sin(i),h=Math.cos(i);return this.x=r*o*h-a*n*l,this.y=a*n*h+r*o*l,this.z=a*o*l-r*n*h,this.w=a*o*h+r*n*l,this}setFromMat4(e){let t,i=e.data,s=i[0],r=i[1],a=i[2],n=i[4],o=i[5],l=i[6],h=i[8],c=i[9],d=i[10];return 0==(t=s*s+r*r+a*a)||(s*=t=1/Math.sqrt(t),r*=t,a*=t,0==(t=n*n+o*o+l*l)||(n*=t=1/Math.sqrt(t),o*=t,l*=t,0==(t=h*h+c*c+d*d)))?this.set(0,0,0,1):(h*=t=1/Math.sqrt(t),c*=t,(d*=t)<0?s>o?this.set(1+s-o-d,r+n,h+a,l-c):this.set(r+n,1-s+o-d,l+c,h-a):s<-o?this.set(h+a,l+c,1-s-o+d,r-n):this.set(l-c,h-a,r-n,1+s+o+d),this.mulScalar(1/this.length()))}setFromDirections(e,t){let i=1+e.dot(t);return i<Number.EPSILON?(Math.abs(e.x)>Math.abs(e.y)?(this.x=-e.z,this.y=0,this.z=e.x):(this.x=0,this.y=-e.z,this.z=e.y),this.w=0):(this.x=e.y*t.z-e.z*t.y,this.y=e.z*t.x-e.x*t.z,this.z=e.x*t.y-e.y*t.x,this.w=i),this.normalize()}slerp(e,t,i){let s=e.x,r=e.y,a=e.z,n=e.w,o=t.x,l=t.y,h=t.z,c=t.w,d=n*c+s*o+r*l+a*h;if(d<0&&(c=-c,o=-o,l=-l,h=-h,d=-d),Math.abs(d)>=1)return this.w=n,this.x=s,this.y=r,this.z=a,this;let u=Math.acos(d),f=Math.sqrt(1-d*d);if(.001>Math.abs(f))return this.w=.5*n+.5*c,this.x=.5*s+.5*o,this.y=.5*r+.5*l,this.z=.5*a+.5*h,this;let p=Math.sin((1-i)*u)/f,m=Math.sin(i*u)/f;return this.w=n*p+c*m,this.x=s*p+o*m,this.y=r*p+l*m,this.z=a*p+h*m,this}transformVector(e,t=new eM){let i=e.x,s=e.y,r=e.z,a=this.x,n=this.y,o=this.z,l=this.w,h=l*i+n*r-o*s,c=l*s+o*i-a*r,d=l*r+a*s-n*i,u=-a*i-n*s-o*r;return t.x=h*l+-(u*a)+-(c*o)- -(d*n),t.y=c*l+-(u*n)+-(d*a)- -(h*o),t.z=d*l+-(u*o)+-(h*n)- -(c*a),t}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this.z=e[t+2]??this.z,this.w=e[t+3]??this.w,this}toString(){return `[${this.x}, ${this.y}, ${this.z}, ${this.w}]`}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}static{this.IDENTITY=Object.freeze(new eH(0,0,0,1));}static{this.ZERO=Object.freeze(new eH(0,0,0,0));}}let eW=new eM,eX=new eM,eY=new eM,eq=new eM,e$=new eM;class ej{constructor(e,t){this.center=new eM,this.halfExtents=new eM(.5,.5,.5),this._min=new eM,this._max=new eM,e&&this.center.copy(e),t&&this.halfExtents.copy(t);}add(e){let t=this.center,i=t.x,s=t.y,r=t.z,a=this.halfExtents,n=a.x,o=a.y,l=a.z,h=i-n,c=i+n,d=s-o,u=s+o,f=r-l,p=r+l,m=e.center,_=m.x,g=m.y,v=m.z,S=e.halfExtents,y=S.x,x=S.y,T=S.z,E=_-y,A=_+y,b=g-x,w=g+x,C=v-T,P=v+T;E<h&&(h=E),A>c&&(c=A),b<d&&(d=b),w>u&&(u=w),C<f&&(f=C),P>p&&(p=P),t.x=(h+c)*.5,t.y=(d+u)*.5,t.z=(f+p)*.5,a.x=(c-h)*.5,a.y=(u-d)*.5,a.z=(p-f)*.5;}copy(e){this.center.copy(e.center),this.halfExtents.copy(e.halfExtents);}clone(){return new ej(this.center,this.halfExtents)}intersects(e){let t=this.getMax(),i=this.getMin(),s=e.getMax(),r=e.getMin();return i.x<=s.x&&t.x>=r.x&&i.y<=s.y&&t.y>=r.y&&i.z<=s.z&&t.z>=r.z}_intersectsRay(e,t){let i=eW.copy(this.getMin()).sub(e.origin),s=eX.copy(this.getMax()).sub(e.origin),r=e.direction;0===r.x?(i.x=i.x<0?-Number.MAX_VALUE:Number.MAX_VALUE,s.x=s.x<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.x/=r.x,s.x/=r.x),0===r.y?(i.y=i.y<0?-Number.MAX_VALUE:Number.MAX_VALUE,s.y=s.y<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.y/=r.y,s.y/=r.y),0===r.z?(i.z=i.z<0?-Number.MAX_VALUE:Number.MAX_VALUE,s.z=s.z<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.z/=r.z,s.z/=r.z);let a=eY.set(Math.min(i.x,s.x),Math.min(i.y,s.y),Math.min(i.z,s.z)),n=eq.set(Math.max(i.x,s.x),Math.max(i.y,s.y),Math.max(i.z,s.z)),o=Math.min(Math.min(n.x,n.y),n.z),l=Math.max(Math.max(a.x,a.y),a.z),h=o>=l&&l>=0;return h&&t.copy(e.direction).mulScalar(l).add(e.origin),h}_fastIntersectsRay(e){let t=e.direction;return eW.sub2(e.origin,this.center),eq.set(Math.abs(eW.x),Math.abs(eW.y),Math.abs(eW.z)),eY.mul2(eW,t),(!(eq.x>this.halfExtents.x)||!(eY.x>=0))&&(!(eq.y>this.halfExtents.y)||!(eY.y>=0))&&(!(eq.z>this.halfExtents.z)||!(eY.z>=0))&&(e$.set(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z)),eX.cross(t,eW),eX.set(Math.abs(eX.x),Math.abs(eX.y),Math.abs(eX.z)),!(eX.x>this.halfExtents.y*e$.z+this.halfExtents.z*e$.y)&&!(eX.y>this.halfExtents.x*e$.z+this.halfExtents.z*e$.x)&&!(eX.z>this.halfExtents.x*e$.y+this.halfExtents.y*e$.x))}intersectsRay(e,t){return t?this._intersectsRay(e,t):this._fastIntersectsRay(e)}setMinMax(e,t){this.center.add2(t,e).mulScalar(.5),this.halfExtents.sub2(t,e).mulScalar(.5);}getMin(){return this._min.copy(this.center).sub(this.halfExtents)}getMax(){return this._max.copy(this.center).add(this.halfExtents)}containsPoint(e){let t=this.getMin(),i=this.getMax();return !(e.x<t.x)&&!(e.x>i.x)&&!(e.y<t.y)&&!(e.y>i.y)&&!(e.z<t.z)&&!(e.z>i.z)}setFromTransformedAabb(e,t,i=false){let s=e.center,r=e.halfExtents,a=t.data,n=a[0],o=a[4],l=a[8],h=a[1],c=a[5],d=a[9],u=a[2],f=a[6],p=a[10];if(i){let e=n*n+o*o+l*l;if(e>0){let t=1/Math.sqrt(e);n*=t,o*=t,l*=t;}if((e=h*h+c*c+d*d)>0){let t=1/Math.sqrt(e);h*=t,c*=t,d*=t;}if((e=u*u+f*f+p*p)>0){let t=1/Math.sqrt(e);u*=t,f*=t,p*=t;}}this.center.set(a[12]+n*s.x+o*s.y+l*s.z,a[13]+h*s.x+c*s.y+d*s.z,a[14]+u*s.x+f*s.y+p*s.z),this.halfExtents.set(Math.abs(n)*r.x+Math.abs(o)*r.y+Math.abs(l)*r.z,Math.abs(h)*r.x+Math.abs(c)*r.y+Math.abs(d)*r.z,Math.abs(u)*r.x+Math.abs(f)*r.y+Math.abs(p)*r.z);}static computeMinMax(e,t,i,s=e.length/3){if(s>0){let r=e[0],a=e[1],n=e[2],o=r,l=a,h=n,c=3*s;for(let t=3;t<c;t+=3){let i=e[t],s=e[t+1],c=e[t+2];i<r&&(r=i),s<a&&(a=s),c<n&&(n=c),i>o&&(o=i),s>l&&(l=s),c>h&&(h=c);}t.set(r,a,n),i.set(o,l,h);}}compute(e,t){ej.computeMinMax(e,eW,eX,t),this.setMinMax(eW,eX);}intersectsBoundingSphere(e){return this._distanceToBoundingSphereSq(e)<=e.radius*e.radius}_distanceToBoundingSphereSq(e){let t=this.getMin(),i=this.getMax(),s=0,r=["x","y","z"];for(let a=0;a<3;++a){let n=0,o=e.center[r[a]],l=t[r[a]],h=i[r[a]],c=0;o<l&&(n+=(c=l-o)*c),o>h&&(n+=(c=o-h)*c),s+=n;}return s}_expand(e,t){eW.add2(this.getMin(),e),eX.add2(this.getMax(),t),this.setMinMax(eW,eX);}}let eK=new eM,eZ=new eM;class eQ{constructor(e=new eM,t=.5){this.center=e,this.radius=t;}containsPoint(e){let t=eK.sub2(e,this.center).lengthSq(),i=this.radius;return t<i*i}intersectsRay(e,t){let i=eK.copy(e.origin).sub(this.center),s=i.dot(eZ.copy(e.direction).normalize()),r=i.dot(i)-this.radius*this.radius;if(r>0&&s>0)return false;let a=s*s-r;if(a<0)return false;let n=Math.abs(-s-Math.sqrt(a));return t&&t.copy(e.direction).mulScalar(n).add(e.origin),true}intersectsBoundingSphere(e){eK.sub2(e.center,this.center);let t=e.radius+this.radius;return eK.lengthSq()<=t*t}}class eJ{constructor(e=eM.UP,t=0){this.normal=new eM,this.normal.copy(e),this.distance=t;}clone(){return new this.constructor().copy(this)}copy(e){return this.normal.copy(e.normal),this.distance=e.distance,this}intersectsLine(e,t,i){let s=this.distance,r=this.normal.dot(e)+s,a=r/(r-(this.normal.dot(t)+s)),n=a>=0&&a<=1;return n&&i&&i.lerp(e,t,a),n}intersectsRay(e,t){let i=this.normal.dot(e.direction);if(0===i)return false;let s=-(this.normal.dot(e.origin)+this.distance)/i;return s>=0&&t&&t.copy(e.direction).mulScalar(s).add(e.origin),s>=0}normalize(){let e=1/this.normal.length();return this.normal.mulScalar(e),this.distance*=e,this}set(e,t,i,s){return this.normal.set(e,t,i),this.distance=s,this}setFromPointNormal(e,t){return this.normal.copy(t),this.distance=-this.normal.dot(e),this}}class e0{constructor(){this.planes=[];for(let e=0;e<6;e++)this.planes[e]=new eJ;}clone(){return new this.constructor().copy(this)}copy(e){for(let t=0;t<6;t++)this.planes[t].copy(e.planes[t]);return this}setFromMat4(e){let[t,i,s,r,a,n,o,l,h,c,d,u,f,p,m,_]=e.data,g=this.planes;g[0].set(r-t,l-a,u-h,_-f).normalize(),g[1].set(r+t,l+a,u+h,_+f).normalize(),g[2].set(r+i,l+n,u+c,_+p).normalize(),g[3].set(r-i,l-n,u-c,_-p).normalize(),g[4].set(r-s,l-o,u-d,_-m).normalize(),g[5].set(r+s,l+o,u+d,_+m).normalize();}containsPoint(e){for(let t=0;t<6;t++){let{normal:i,distance:s}=this.planes[t];if(i.dot(e)+s<=0)return false}return true}containsSphere(e){let{center:t,radius:i}=e,s=0;for(let e=0;e<6;e++){let{normal:r,distance:a}=this.planes[e],n=r.dot(t)+a;if(n<=-i)return 0;n>i&&s++;}return 6===s?2:1}}class e1{constructor(e,t){this.origin=new eM,this.direction=eM.FORWARD.clone(),e&&this.origin.copy(e),t&&this.direction.copy(t);}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.set(e.origin,e.direction)}clone(){return new this.constructor(this.origin,this.direction)}}let e2=new e1,e3=new eM,e4=new eQ,e5=new eG;class e8{constructor(e=new eG,t){this.halfExtents=new eM(.5,.5,.5),t&&this.halfExtents.copy(t),this._modelTransform=e.clone().invert(),this._worldTransform=e.clone(),this._aabb=new ej(new eM,this.halfExtents);}set worldTransform(e){this._worldTransform.copy(e),this._modelTransform.copy(e).invert();}get worldTransform(){return this._worldTransform}intersectsRay(e,t){if(this._modelTransform.transformPoint(e.origin,e2.origin),this._modelTransform.transformVector(e.direction,e2.direction),t){let e=this._aabb._intersectsRay(e2,t);return e5.copy(this._modelTransform).invert().transformPoint(t,t),e}return this._aabb._fastIntersectsRay(e2)}containsPoint(e){return this._modelTransform.transformPoint(e,e3),this._aabb.containsPoint(e3)}intersectsBoundingSphere(e){return this._modelTransform.transformPoint(e.center,e4.center),e4.radius=e.radius,!!this._aabb.intersectsBoundingSphere(e4)}}let e6=new eM,e9=new eM,e7=new eM,te=new eM,tt=new eM;class ti{constructor(e=eM.ZERO,t=eM.ZERO,i=eM.ZERO){this.v0=new eM,this.v1=new eM,this.v2=new eM,this.set(e,t,i);}set(e,t,i){return this.v0.copy(e),this.v1.copy(t),this.v2.copy(i),this}intersectsRay(e,t){e6.sub2(this.v1,this.v0),e9.sub2(this.v2,this.v0),e7.cross(e.direction,e9);let i=e6.dot(e7);if(i>-1e-6&&i<1e-6)return false;let s=1/i;te.sub2(e.origin,this.v0);let r=s*te.dot(e7);if(r<0||r>1)return false;tt.cross(te,e6);let a=s*e.direction.dot(tt);if(a<0||r+a>1)return false;let n=s*e9.dot(tt);return n>1e-6&&(t instanceof eM&&t.copy(e.direction).mulScalar(n).add(e.origin),true)}toString(){return `[${this.v0.toString()}, ${this.v1.toString()}, ${this.v2.toString()}]`}}let ts=0,tr=1,ta=2,tn=0,to=1,tl=2,th=3,tc=4,td=5,tu=6,tf=7,tp=8,tm=9,t_=10,tg=11,tv=12,tS=0,ty=1,tx=2,tT=3,tE=4,tA=1,tb=2,tw=4,tC=8,tP=16,tL=32,tI=64,tD=128,tR=256,tM=0,tO=1,tN=2,tF=3,tB=1,tU=2,tk=4,tV=0,tz=1,tG=2,tH=3,tW=4,tX=5,tY=0,tq=1,t$=2,tj=3,tK=0,tZ=1,tQ=2,tJ=3,t0=4,t1=5,t2=0,t3=1,t4=2,t5=3,t8=4,t6=5,t9=6,t7=7,ie=0,it=1,ii=2,is=0,ir=1,ia=2,io=3,il=4,ih=5,ic=6,id=7,iu=8,ip=9,im=10,i_=11,ig=12,iv=13,iS=14,iy=15,ix=16,iT=17,iE=18,iA=19,ib=20,iw=21,iC=22,iP=23,iL=24,iI=25,iD=26,iR=27,iM=28,iO=29,iN=30,iF=31,iB=32,iU=33,ik=34,iV=35,iz=36,iG=37,iH=38,iW=39,iX=40,iY=41,iq=42,i$=43,ij=44,iK=45,iZ=46,iQ=47,iJ=48,i0=49,i1=50,i2=51,i3=52,i4=53,i5=54,i8=55,i6=56,i9=61,i7=62,se=63,st=64,si=65,ss=66,sr=67,sa=68,sn=69,so=new Map([[is,{name:"A8",size:1,ldr:true}],[i3,{name:"R8",size:1,ldr:true}],[ir,{name:"L8",size:1,ldr:true}],[ia,{name:"LA8",size:2,ldr:true}],[i4,{name:"RG8",size:2,ldr:true}],[io,{name:"RGB565",size:2,ldr:true}],[il,{name:"RGBA5551",size:2,ldr:true}],[ih,{name:"RGBA4",size:2,ldr:true}],[ic,{name:"RGB8",size:4,ldr:true}],[id,{name:"RGBA8",size:4,ldr:true,srgbFormat:ib}],[i1,{name:"R16F",size:2}],[i2,{name:"RG16F",size:4}],[i_,{name:"RGB16F",size:8}],[ig,{name:"RGBA16F",size:8}],[iv,{name:"RGB32F",size:16}],[iS,{name:"RGBA32F",size:16}],[iy,{name:"R32F",size:4}],[ix,{name:"DEPTH",size:4}],[sn,{name:"DEPTH16",size:2}],[iT,{name:"DEPTHSTENCIL",size:4}],[iE,{name:"111110F",size:4}],[iA,{name:"SRGB8",size:4,ldr:true,srgb:true}],[ib,{name:"SRGBA8",size:4,ldr:true,srgb:true}],[iF,{name:"BGRA8",size:4,ldr:true}],[st,{name:"SBGRA8",size:4,ldr:true,srgb:true}],[iu,{name:"DXT1",blockSize:8,ldr:true,srgbFormat:i5}],[ip,{name:"DXT3",blockSize:16,ldr:true,srgbFormat:i8}],[im,{name:"DXT5",blockSize:16,ldr:true,srgbFormat:i6}],[iw,{name:"ETC1",blockSize:8,ldr:true}],[iC,{name:"ETC2_RGB",blockSize:8,ldr:true,srgbFormat:i9}],[iP,{name:"ETC2_RGBA",blockSize:16,ldr:true,srgbFormat:i7}],[iL,{name:"PVRTC_2BPP_RGB_1",ldr:true,blockSize:8}],[iI,{name:"PVRTC_2BPP_RGBA_1",ldr:true,blockSize:8}],[iD,{name:"PVRTC_4BPP_RGB_1",ldr:true,blockSize:8}],[iR,{name:"PVRTC_4BPP_RGBA_1",ldr:true,blockSize:8}],[iM,{name:"ASTC_4x4",blockSize:16,ldr:true,srgbFormat:se}],[iO,{name:"ATC_RGB",blockSize:8,ldr:true}],[iN,{name:"ATC_RGBA",blockSize:16,ldr:true}],[si,{name:"BC6H_RGBF",blockSize:16}],[ss,{name:"BC6H_RGBUF",blockSize:16}],[sr,{name:"BC7_RGBA",blockSize:16,ldr:true,srgbFormat:sa}],[i5,{name:"DXT1_SRGB",blockSize:8,ldr:true,srgb:true}],[i8,{name:"DXT3_SRGBA",blockSize:16,ldr:true,srgb:true}],[i6,{name:"DXT5_SRGBA",blockSize:16,ldr:true,srgb:true}],[i9,{name:"ETC2_SRGB",blockSize:8,ldr:true,srgb:true}],[i7,{name:"ETC2_SRGBA",blockSize:16,ldr:true,srgb:true}],[se,{name:"ASTC_4x4_SRGB",blockSize:16,ldr:true,srgb:true}],[sa,{name:"BC7_SRGBA",blockSize:16,ldr:true,srgb:true}],[iB,{name:"R8I",size:1,isInt:true}],[iU,{name:"R8U",size:1,isInt:true}],[ik,{name:"R16I",size:2,isInt:true}],[iV,{name:"R16U",size:2,isInt:true}],[iz,{name:"R32I",size:4,isInt:true}],[iG,{name:"R32U",size:4,isInt:true}],[iH,{name:"RG8I",size:2,isInt:true}],[iW,{name:"RG8U",size:2,isInt:true}],[iX,{name:"RG16I",size:4,isInt:true}],[iY,{name:"RG16U",size:4,isInt:true}],[iq,{name:"RG32I",size:8,isInt:true}],[i$,{name:"RG32U",size:8,isInt:true}],[ij,{name:"RGBA8I",size:4,isInt:true}],[iK,{name:"RGBA8U",size:4,isInt:true}],[iZ,{name:"RGBA16I",size:8,isInt:true}],[iQ,{name:"RGBA16U",size:8,isInt:true}],[iJ,{name:"RGBA32I",size:16,isInt:true}],[i0,{name:"RGBA32U",size:16,isInt:true}]]),sl=e=>so.get(e)?.blockSize!==void 0,sh=e=>so.get(e)?.srgb===true,sc=e=>so.get(e)?.isInt===true,sd=e=>so.get(e)?.srgbFormat||e,su=e=>{for(let[t,i]of so)if(i.srgbFormat===e)return t;return e},sf=e=>{let t=so.get(e);return !!(t?.ldr&&!t?.srgb)},sp=e=>{switch(e){case iy:case iv:case iS:return Float32Array;case iz:case iq:case iJ:return Int32Array;case iG:case i$:case i0:return Uint32Array;case ik:case iX:case iZ:return Int16Array;case i4:case iV:case iY:case iQ:case io:case il:case ih:case i1:case i2:case i_:case ig:return Uint16Array;case iB:case iH:case ij:return Int8Array;default:return Uint8Array}},sm=0,s_=1,sg=2,sv=3,sS=4,sy=5,sx=6,sT="POSITION",sE="NORMAL",sA="TANGENT",sb="BLENDWEIGHT",sw="BLENDINDICES",sC="COLOR",sP="TEXCOORD",sL="TEXCOORD0",sI="TEXCOORD1",sD="TEXCOORD2",sR="TEXCOORD3",sM="TEXCOORD4",sO="TEXCOORD5",sN="TEXCOORD6",sF="TEXCOORD7",sB="ATTR0",sU="ATTR1",sk="ATTR2",sV="ATTR3",sz="ATTR4",sG="ATTR5",sH="ATTR6",sW="ATTR7",sX="ATTR8",sY="ATTR9",sq="ATTR10",s$="ATTR11",sj="ATTR12",sK="ATTR13",sZ="ATTR14",sQ="ATTR15",sJ=1,s0=0,s1=1,s2=2,s3=3,s4=4,s5=5,s8=6,s6=7,s9=0,s7=1,re=2,rt="default",ri="rgbm",rs="rgbe",rr="rgbp",ra="swizzleGGGR",rn=0,ro=1,rl=2,rh=3,rc="1d",rd="2d",ru="2d-array",rf="cube",rp="cube-array",rm="3d",r_=0,rg=1,rv=2,rS=3,ry=4,rx="none",rT="cube",rE="equirect",rA="octahedral",rb="glsl",rw="wgsl",rC=0,rP=1,rL=2,rI=3,rD=4,rR=5,rM=6,rO=7,rN=0,rF=1,rB=2,rU=3,rk=4,rV=5,rz=6,rG=7,rH=8,rW=9,rX=10,rY=11,rq=12,r$=13,rj=14,rK=15,rZ=16,rQ=17,rJ=18,r0=19,r1=20,r2=21,r3=22,r4=23,r5=24,r8=25,r6=26,r9=27,r7=28,ae=29,at=30,ai=31,as=32,ar=33,aa=34,an=35,ao=36,al=37,ah=38,ac=39,ad=40,au=41,af=42,ap=43,am=44,a_=45,ag=46,av=47,aS=48,ay=49,ax=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","","","","sampler2DArray","uint","uvec2","uvec3","uvec4","","","","","","","","","","","","","isampler2D","usampler2D","isamplerCube","usamplerCube","isampler3D","usampler3D","isampler2DArray","usampler2DArray"],aT=[["bool"],["i32"],["f32"],["vec2f","vec2<f32>"],["vec3f","vec3<f32>"],["vec4f","vec4<f32>"],["vec2i","vec2<i32>"],["vec3i","vec3<i32>"],["vec4i","vec4<i32>"],["vec2<bool>"],["vec3<bool>"],["vec4<bool>"],["mat2x2f","mat2x2<f32>"],["mat3x3f","mat3x3<f32>"],["mat4x4f","mat4x4<f32>"],["texture_2d<f32>"],["texture_cube<f32>"],["array<f32>"],["texture_depth_2d"],["texture_depth_cube"],["texture_3d<f32>"],["array<vec2<f32>>"],["array<vec3<f32>>"],["array<vec4<f32>>"],["array<mat4x4<f32>>"],["texture_2d_array<f32>"],["u32"],["vec2u","vec2<u32>"],["vec3u","vec3<u32>"],["vec4u","vec4<u32>"],["array<i32>"],["array<u32>"],["array<bool>"],["array<vec2i>","array<vec2<i32>>"],["array<vec2u>","array<vec2<u32>>"],["array<vec2b>","array<vec2<bool>>"],["array<vec3i>","array<vec3<i32>>"],["array<vec3u>","array<vec3<u32>>"],["array<vec3b>","array<vec3<bool>>"],["array<vec4i>","array<vec4<i32>>"],["array<vec4u>","array<vec4<u32>>"],["array<vec4b>","array<vec4<bool>>"],["texture_2d<i32>"],["texture_2d<u32>"],["texture_cube<i32>"],["texture_cube<u32>"],["texture_3d<i32>"],["texture_3d<u32>"],["texture_2d_array<i32>"],["texture_2d_array<u32>"]],aE=new Map;aT.forEach((e,t)=>{e.forEach(e=>aE.set(e,t));});let aA=new Uint8Array([rD,rD,rM,rM,rM,rM,rD,rD,rD,rD,rD,rD,rM,rM,rM,rD,rD,rM,rD,rD,rD,rM,rM,rM,rM,rD,rR,rR,rR,rR,rD,rR,rD,rD,rR,rD,rD,rR,rD,rD,rR,rD,rD,rR,rD,rR,rD,rR,rD,rR]),ab="webgl2",aw="webgpu",aC="null",aP=1,aL=2,aI=4,aD="ldr",aR="ldr_srgb",aM="hdr",aO=1,aN=2,aF=4,aB=8,aU=16,ak=32,aV=64,az=128,aG=255,aH=0,aW=1,aX=2,aY=["view","mesh","mesh_ub"],aq="default",a$="_unused_float_uniform",aj=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Uint16Array],aK=[1,1,2,2,4,4,4,2],aZ=["INT8","UINT8","INT16","UINT16","INT32","UINT32","FLOAT32","FLOAT16"],aQ={Int8Array:rC,Uint8Array:rP,Int16Array:rL,Uint16Array:rI,Int32Array:rD,Uint32Array:rR,Float32Array:rM},aJ=[Uint8Array,Uint16Array,Uint32Array],a0=[1,2,4],a1=new Map([["float","f32"],["vec2","vec2f"],["vec3","vec3f"],["vec4","vec4f"],["int","i32"],["ivec2","vec2i"],["ivec3","vec3i"],["ivec4","vec4i"],["uint","u32"],["uvec2","vec2u"],["uvec3","vec3u"],["uvec4","vec4u"]]),a2={};a2[sT]=0,a2[sE]=1,a2[sb]=2,a2[sw]=3,a2[sC]=4,a2[sL]=5,a2[sI]=6,a2[sD]=7,a2[sR]=8,a2[sM]=9,a2[sO]=10,a2[sN]=11,a2[sF]=12,a2[sA]=13,a2[sB]=0,a2[sU]=1,a2[sk]=2,a2[sV]=3,a2[sz]=4,a2[sG]=5,a2[sH]=6,a2[sW]=7,a2[sX]=8,a2[sY]=9,a2[sq]=10,a2[s$]=11,a2[sj]=12,a2[sK]=13,a2[sZ]=14,a2[sQ]=15;let a3=0;class a4{constructor(e,t){this.slot=-1,this.scopeId=null,this.name=e,this.visibility=t;}}class a5 extends a4{}class a8 extends a4{constructor(e,t,i=false){super(e,t),this.format="",this.readOnly=i;}}class a6 extends a4{constructor(e,t,i=rd,s=r_,r=true,a=null){super(e,t),this.textureDimension=i,this.sampleType=s,this.hasSampler=r,this.samplerName=a??`${e}_sampler`;}}class a9 extends a4{constructor(e,t=id,i=rd,s=true,r=false){super(e,aI),this.format=t,this.textureDimension=i,this.write=s,this.read=r;}}class a7{constructor(e,t){this.uniformBufferFormats=[],this.textureFormats=[],this.storageTextureFormats=[],this.storageBufferFormats=[],this.id=a3++;let i=0;t.forEach(e=>{e.slot=i++,e instanceof a6&&e.hasSampler&&i++,e instanceof a5?this.uniformBufferFormats.push(e):e instanceof a6?this.textureFormats.push(e):e instanceof a9?this.storageTextureFormats.push(e):e instanceof a8&&this.storageBufferFormats.push(e);}),this.device=e;let s=e.scope;this.bufferFormatsMap=new Map,this.uniformBufferFormats.forEach((e,t)=>this.bufferFormatsMap.set(e.name,t)),this.textureFormatsMap=new Map,this.textureFormats.forEach((e,t)=>{this.textureFormatsMap.set(e.name,t),e.scopeId=s.resolve(e.name);}),this.storageTextureFormatsMap=new Map,this.storageTextureFormats.forEach((e,t)=>{this.storageTextureFormatsMap.set(e.name,t),e.scopeId=s.resolve(e.name);}),this.storageBufferFormatsMap=new Map,this.storageBufferFormats.forEach((e,t)=>{this.storageBufferFormatsMap.set(e.name,t),e.scopeId=s.resolve(e.name);}),this.impl=e.createBindGroupFormatImpl(this);}destroy(){this.impl.destroy();}getTexture(e){let t=this.textureFormatsMap.get(e);return void 0!==t?this.textureFormats[t]:null}getStorageTexture(e){let t=this.storageTextureFormatsMap.get(e);return void 0!==t?this.storageTextureFormats[t]:null}loseContext(){}}class ne{get(e,t){return this._cache.has(e)||(this._cache.set(e,t()),e.on("destroy",()=>{this.remove(e);}),e.on("devicelost",()=>{this._cache.get(e)?.loseContext?.(e);})),this._cache.get(e)}remove(e){this._cache.get(e)?.destroy?.(e),this._cache.delete(e);}constructor(){this._cache=new Map;}}class nt{static calcLevelDimension(e,t){return Math.max(e>>t,1)}static calcMipLevelsCount(e,t,i=1){return 1+Math.floor(Math.log2(Math.max(e,t,i)))}static calcLevelGpuSize(e,t,i,s){let r=so.get(s),a=so.get(s)?.size??0;if(a>0)return e*t*i*a;let n=r.blockSize??0,o=Math.floor((e+3)/4),l=Math.floor((t+3)/4),h=Math.floor((i+3)/4);return (s===iL||s===iI)&&(o=Math.max(Math.floor(o/2),1)),o*l*h*n}static calcGpuSize(e,t,i,s,r,a){let n=0;for(;n+=nt.calcLevelGpuSize(e,t,i,s),r&&(1!==e||1!==t||1!==i);)e=Math.max(e>>1,1),t=Math.max(t>>1,1),i=Math.max(i>>1,1);return n*(a?6:1)}}let ni=0;class ns{constructor(e,t={}){this._gpuSize=0,this.id=ni++,this._invalid=false,this._lockedLevel=-1,this._lockedMode=s9,this.renderVersionDirty=0,this._storage=false,this._numLevels=0,this.device=e,this.name=t.name??"",this._width=Math.floor(t.width??4),this._height=Math.floor(t.height??4),this._format=t.format??id,this._compressed=sl(this._format),this._integerFormat=sc(this._format),this._integerFormat&&(t.minFilter=tK,t.magFilter=tK),this._volume=t.volume??false,this._depth=Math.floor(t.depth??1),this._arrayLength=Math.floor(t.arrayLength??0),this._storage=t.storage??false,this._cubemap=t.cubemap??false,this._flipY=t.flipY??false,this._premultiplyAlpha=t.premultiplyAlpha??false,this._mipmaps=t.mipmaps??true,this._numLevelsRequested=t.numLevels,void 0!==t.numLevels&&(this._numLevels=t.numLevels),this._updateNumLevel(),this._minFilter=t.minFilter??t1,this._magFilter=t.magFilter??tZ,this._anisotropy=t.anisotropy??1,this._addressU=t.addressU??ts,this._addressV=t.addressV??ts,this._addressW=t.addressW??ts,this._compareOnRead=t.compareOnRead??false,this._compareFunc=t.compareFunc??t3,this._type=t.type??rt,this.projection=rx,this._cubemap?this.projection=rT:t.projection&&t.projection!==rT&&(this.projection=t.projection),this._levels=t.levels;let i=!!t.levels;this._levels||this._clearLevels(),this.recreateImpl(i),e.textures.push(this);}destroy(){let e=this.device;if(e){let t=e.textures.indexOf(this);-1!==t&&e.textures.splice(t,1),e.scope.removeValue(this),this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this._gpuSize),this._levels=null,this.device=null;}}recreateImpl(e=true){let{device:t}=this;this.impl?.destroy(t),this.impl=null,this.impl=t.createTextureImpl(this),this.dirtyAll(),e&&this.upload();}_clearLevels(){this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null];}resize(e,t,i=1){let s=this.device;this.adjustVramSizeTracking(s._vram,-this._gpuSize),this.impl.destroy(s),this._clearLevels(),this._width=Math.floor(e),this._height=Math.floor(t),this._depth=Math.floor(i),this._updateNumLevel(),this.impl=s.createTextureImpl(this),this.dirtyAll();}loseContext(){this.impl.loseContext(),this.dirtyAll();}adjustVramSizeTracking(e,t){e.tex+=t;}propertyChanged(e){this.impl.propertyChanged(e),this.renderVersionDirty=this.device.renderVersion;}_updateNumLevel(){let e=this.mipmaps?nt.calcMipLevelsCount(this.width,this.height):1,t=this._numLevelsRequested;this._numLevels=Math.min(t??e,e),this._mipmaps=this._numLevels>1;}get lockedMode(){return this._lockedMode}set minFilter(e){this._minFilter!==e&&(sc(this._format)||(this._minFilter=e,this.propertyChanged(aO)));}get minFilter(){return this._minFilter}set magFilter(e){this._magFilter!==e&&(sc(this._format)||(this._magFilter=e,this.propertyChanged(aN)));}get magFilter(){return this._magFilter}set addressU(e){this._addressU!==e&&(this._addressU=e,this.propertyChanged(aF));}get addressU(){return this._addressU}set addressV(e){this._addressV!==e&&(this._addressV=e,this.propertyChanged(aB));}get addressV(){return this._addressV}set addressW(e){this._volume&&e!==this._addressW&&(this._addressW=e,this.propertyChanged(aU));}get addressW(){return this._addressW}set compareOnRead(e){this._compareOnRead!==e&&(this._compareOnRead=e,this.propertyChanged(ak));}get compareOnRead(){return this._compareOnRead}set compareFunc(e){this._compareFunc!==e&&(this._compareFunc=e,this.propertyChanged(aV));}get compareFunc(){return this._compareFunc}set anisotropy(e){this._anisotropy!==e&&(this._anisotropy=e,this.propertyChanged(az));}get anisotropy(){return this._anisotropy}set mipmaps(e){this._mipmaps!==e&&(this.device.isWebGPU||sc(this._format)||(this._mipmaps=e),e&&(this._needsMipmapsUpload=true));}get mipmaps(){return this._mipmaps}get numLevels(){return this._numLevels}get storage(){return this._storage}get width(){return this._width}get height(){return this._height}get depth(){return this._depth}get format(){return this._format}get cubemap(){return this._cubemap}get gpuSize(){let e=this.pot&&this._mipmaps&&!(this._compressed&&1===this._levels.length);return nt.calcGpuSize(this._width,this._height,this._depth,this._format,e,this._cubemap)}get array(){return this._arrayLength>0}get arrayLength(){return this._arrayLength}get volume(){return this._volume}set type(e){this._type!==e&&(this._type=e,this.device._shadersDirty=true);}get type(){return this._type}set srgb(e){if(e!==sh(this.format))if(e){let e=sd(this.format);this._format!==e&&(this._format=e,this.recreateImpl(),this.device._shadersDirty=true);}else {let e=su(this.format);this._format!==e&&(this._format=e,this.recreateImpl(),this.device._shadersDirty=true);}}get srgb(){return sh(this.format)}set flipY(e){this._flipY!==e&&(this._flipY=e,this._needsUpload=true);}get flipY(){return this._flipY}set premultiplyAlpha(e){this._premultiplyAlpha!==e&&(this._premultiplyAlpha=e,this._needsUpload=true);}get premultiplyAlpha(){return this._premultiplyAlpha}get pot(){return eA.powerOfTwo(this._width)&&eA.powerOfTwo(this._height)}get encoding(){switch(this.type){case ri:return "rgbm";case rs:return "rgbe";case rr:return "rgbp"}return sf(this.format)?"srgb":"linear"}dirtyAll(){this._levelsUpdated=this._cubemap?[[true,true,true,true,true,true]]:[true],this._needsUpload=true,this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=false,this.propertyChanged(aG);}lock(e={}){e.level??=0,e.face??=0,e.mode??=re,this._lockedMode=e.mode,this._lockedLevel=e.level;let t=this.cubemap?this._levels[e.face]:this._levels;if(null===t[e.level]){let i=Math.max(1,this._width>>e.level),s=Math.max(1,this._height>>e.level),r=Math.max(1,this._depth>>e.level),a=new ArrayBuffer(nt.calcLevelGpuSize(i,s,r,this._format));t[e.level]=new(sp(this._format))(a);}return t[e.level]}setSource(e,t=0){let i,s,r=false;if(this._cubemap){if(e[0]){i=e[0].width||0,s=e[0].height||0;for(let t=0;t<6;t++){let a=e[t];if(!a||a.width!==i||a.height!==s||!this.device._isBrowserInterface(a)){r=true;break}}}else r=true;if(!r)for(let i=0;i<6;i++)this._levels[t][i]!==e[i]&&(this._levelsUpdated[t][i]=true);}else this.device._isBrowserInterface(e)||(r=true),r||(e!==this._levels[t]&&(this._levelsUpdated[t]=true),e instanceof HTMLVideoElement?(i=e.videoWidth,s=e.videoHeight):(i=e.width,s=e.height));if(r)if(this._width=4,this._height=4,this._cubemap)for(let e=0;e<6;e++)this._levels[t][e]=null,this._levelsUpdated[t][e]=true;else this._levels[t]=null,this._levelsUpdated[t]=true;else 0===t&&(this._width=i,this._height=s),this._levels[t]=e;this._invalid===r&&r||(this._invalid=r,this.upload());}getSource(e=0){return this._levels[e]}unlock(){this._lockedMode,this._lockedMode===re&&this.upload(),this._lockedLevel=-1,this._lockedMode=s9;}upload(){this._needsUpload=true,this._needsMipmapsUpload=this._mipmaps,this.impl.uploadImmediate?.(this.device,this);}read(e,t,i,s,r={}){return this.impl.read?.(e,t,i,s,r)}write(e,t,i,s,r){return this.impl.write?.(e,t,i,s,r)}}let nr={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255],pink:[255,128,255,255]};class na{destroy(){this.map.forEach(e=>{e.destroy();});}constructor(){this.map=new Map;}}let nn=new ne,no=(e,t)=>{let i=nn.get(e,()=>new na);if(!i.map.has(t)){let s=new ns(e,{name:`built-in-texture-${t}`,width:1,height:1,format:id}),r=s.lock(),a=nr[t];r.set(a),s.unlock(),i.map.set(t,s);}return i.map.get(t)},nl=0;class nh{constructor(){this.offsets=[];}}class nc{constructor(e,t,i){this.renderVersionUpdated=-1,this.uniformBufferOffsets=[],this.id=nl++,this.device=e,this.format=t,this.dirty=true,this.impl=e.createBindGroupImpl(this),this.textures=[],this.storageTextures=[],this.storageBuffers=[],this.uniformBuffers=[],this.defaultUniformBuffer=i,i&&this.setUniformBuffer(aq,i);}destroy(){this.impl.destroy(),this.impl=null,this.format=null,this.defaultUniformBuffer=null;}setUniformBuffer(e,t){let i=this.format.bufferFormatsMap.get(e);this.uniformBuffers[i]!==t&&(this.uniformBuffers[i]=t,this.dirty=true);}setStorageBuffer(e,t){let i=this.format.storageBufferFormatsMap.get(e);this.storageBuffers[i]!==t&&(this.storageBuffers[i]=t,this.dirty=true);}setTexture(e,t){let i=this.format.textureFormatsMap.get(e);this.textures[i]!==t?(this.textures[i]=t,this.dirty=true):this.renderVersionUpdated<t.renderVersionDirty&&(this.dirty=true);}setStorageTexture(e,t){let i=this.format.storageTextureFormatsMap.get(e);this.storageTextures[i]!==t?(this.storageTextures[i]=t,this.dirty=true):this.renderVersionUpdated<t.renderVersionDirty&&(this.dirty=true);}updateUniformBuffers(){for(let e=0;e<this.uniformBuffers.length;e++)this.uniformBuffers[e].update();}update(){let{textureFormats:e,storageTextureFormats:t,storageBufferFormats:i}=this.format;for(let t=0;t<e.length;t++){let i=e[t],s=i.scopeId.value;!s&&("uSceneDepthMap"===i.name&&(s=no(this.device,"white")),"uSceneColorMap"===i.name&&(s=no(this.device,"pink")),s||(s=no(this.device,"pink"))),this.setTexture(i.name,s);}for(let e=0;e<t.length;e++){let i=t[e],s=i.scopeId.value;this.setStorageTexture(i.name,s);}for(let e=0;e<i.length;e++){let t=i[e],s=t.scopeId.value;this.setStorageBuffer(t.name,s);}this.uniformBufferOffsets.length=this.uniformBuffers.length;for(let e=0;e<this.uniformBuffers.length;e++){let t=this.uniformBuffers[e];this.uniformBufferOffsets[e]=t.offset,this.renderVersionUpdated<t.renderVersionDirty&&(this.dirty=true);}this.dirty&&(this.dirty=false,this.renderVersionUpdated=this.device.renderVersion,this.impl.update(this));}}let nd={set:(e,t,i,s=1)=>e&~(s<<i)|t<<i,get:(e,t,i=1)=>e>>t&i,all(e,t,i=1){let s=i<<t;return (e&s)===s},any:(e,t,i=1)=>(e&i<<t)!=0};class nu{constructor(e=false,t=tS,i=to,s=tn,r,a,n,o=true,l=true,h=true,c=true){this.target0=0,this.setColorBlend(t,i,s),this.setAlphaBlend(r??t,a??i,n??s),this.setColorWrite(o,l,h,c),this.blend=e;}set blend(e){this.target0=nd.set(this.target0,+!!e,26);}get blend(){return nd.all(this.target0,26)}setColorBlend(e,t,i){this.target0=nd.set(this.target0,e,0,7),this.target0=nd.set(this.target0,t,3,15),this.target0=nd.set(this.target0,i,7,15);}setAlphaBlend(e,t,i){this.target0=nd.set(this.target0,e,11,7),this.target0=nd.set(this.target0,t,14,15),this.target0=nd.set(this.target0,i,18,15);}setColorWrite(e,t,i,s){this.redWrite=e,this.greenWrite=t,this.blueWrite=i,this.alphaWrite=s;}get colorOp(){return nd.get(this.target0,0,7)}get colorSrcFactor(){return nd.get(this.target0,3,15)}get colorDstFactor(){return nd.get(this.target0,7,15)}get alphaOp(){return nd.get(this.target0,11,7)}get alphaSrcFactor(){return nd.get(this.target0,14,15)}get alphaDstFactor(){return nd.get(this.target0,18,15)}set redWrite(e){this.target0=nd.set(this.target0,+!!e,22);}get redWrite(){return nd.all(this.target0,22)}set greenWrite(e){this.target0=nd.set(this.target0,+!!e,23);}get greenWrite(){return nd.all(this.target0,23)}set blueWrite(e){this.target0=nd.set(this.target0,+!!e,24);}get blueWrite(){return nd.all(this.target0,24)}set alphaWrite(e){this.target0=nd.set(this.target0,+!!e,25);}get alphaWrite(){return nd.all(this.target0,25)}get allWrite(){return nd.get(this.target0,22,15)}copy(e){return this.target0=e.target0,this}clone(){return new this.constructor().copy(this)}get key(){return this.target0}equals(e){return this.target0===e.target0}static{this.NOBLEND=Object.freeze(new nu);}static{this.NOWRITE=Object.freeze(new nu(void 0,void 0,void 0,void 0,void 0,void 0,void 0,false,false,false,false));}static{this.ALPHABLEND=Object.freeze(new nu(true,tS,tu,tp));}static{this.ADDBLEND=Object.freeze(new nu(true,tS,to,to));}}class nf{get(e){let t=this.map.get(e);return void 0===t&&(t=this.id++,this.map.set(e,t)),t}constructor(){this.map=new Map,this.id=0;}}let np=new nf;class nm{constructor(e=t5,t=true){this.data=0,this._depthBias=0,this._depthBiasSlope=0,this.key=0,this.func=e,this.write=t;}set test(e){this.func=e?t5:t7,this.updateKey();}get test(){return this.func!==t7}set write(e){this.data=nd.set(this.data,+!!e,3),this.updateKey();}get write(){return nd.all(this.data,3)}set func(e){this.data=nd.set(this.data,e,0,7),this.updateKey();}get func(){return nd.get(this.data,0,7)}set depthBias(e){this._depthBias=e,this.updateKey();}get depthBias(){return this._depthBias}set depthBiasSlope(e){this._depthBiasSlope=e,this.updateKey();}get depthBiasSlope(){return this._depthBiasSlope}copy(e){return this.data=e.data,this._depthBias=e._depthBias,this._depthBiasSlope=e._depthBiasSlope,this.key=e.key,this}clone(){return new this.constructor().copy(this)}updateKey(){let{data:e,_depthBias:t,_depthBiasSlope:i}=this,s=`${e}-${t}-${i}`;this.key=np.get(s);}equals(e){return this.key===e.key}static{this.DEFAULT=Object.freeze(new nm);}static{this.NODEPTH=Object.freeze(new nm(t7,false));}static{this.WRITEDEPTH=Object.freeze(new nm(t7,true));}}class n_{equals(e){return this.globalId===e.globalId&&this.revision===e.revision}copy(e){this.globalId=e.globalId,this.revision=e.revision;}reset(){this.globalId=0,this.revision=0;}constructor(){this.globalId=0,this.revision=0;}}let ng=0;class nv{constructor(){ng++,this.version=new n_,this.version.globalId=ng;}increment(){this.version.revision++;}}class nS{constructor(e){this.name=e,this.value=null,this.versionObject=new nv;}toJSON(e){}setValue(e){this.value=e,this.versionObject.increment();}getValue(){return this.value}}class ny{constructor(e){this.name=e,this.variables=new Map;}resolve(e){return this.variables.has(e)||this.variables.set(e,new nS(e)),this.variables.get(e)}removeValue(e){for(let t in this.variables){let i=this.variables[t];i.value===e&&(i.value=null);}}}let nx=0;class nT{constructor(e,t,i,s){this.usage=tM,this.usage=s?.usage??tM,this.device=e,this.format=t,this.numVertices=i,this.id=nx++,this.impl=e.createVertexBufferImpl(this,t,s),this.numBytes=t.verticesByteSize?t.verticesByteSize:t.size*i,this.adjustVramSizeTracking(e._vram,this.numBytes);let r=s?.data;r?this.setData(r):this.storage=new ArrayBuffer(this.numBytes),this.device.buffers.push(this);}destroy(){let e=this.device,t=e.buffers.indexOf(this);-1!==t&&e.buffers.splice(t,1),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength));}adjustVramSizeTracking(e,t){e.vb+=t;}loseContext(){this.impl.loseContext();}getFormat(){return this.format}getUsage(){return this.usage}getNumVertices(){return this.numVertices}lock(){return this.storage}unlock(){this.impl.unlock(this);}setData(e){return e.byteLength===this.numBytes&&(this.storage=e,this.unlock(),true)}}function nE(e){if(null==e)return 0;let t=0;for(let i=0,s=e.length;i<s;i++)t=(t<<5)-t+e.charCodeAt(i)|0;return t}function nA(e){let t=0x811c9dc5;for(let i=0;i<e.length;i++)t^=e[i],t*=0x1000193;return t>>>0}let nb=new nf,nw=[2,4,8,12,16],nC=new ne;class nP{constructor(e,t,i){this.device=e,this._elements=[],this.hasUv0=false,this.hasUv1=false,this.hasColor=false,this.hasTangents=false,this.verticesByteSize=0,this.vertexCount=i,this.interleaved=void 0===i,this.instancing=false,this.size=t.reduce((e,t)=>e+4*Math.ceil(t.components*aK[t.type]/4),0);let s=0,r;for(let e=0,a=t.length;e<a;e++){let a=t[e];r=a.components*aK[a.type],i&&(s=eA.roundUp(s,r));let n=a.asInt??false,o=!n&&(a.normalize??false),l={name:a.semantic,offset:i?s:a.hasOwnProperty("offset")?a.offset:s,stride:i?r:a.hasOwnProperty("stride")?a.stride:this.size,dataType:a.type,numComponents:a.components,normalize:o,size:r,asInt:n};this._elements.push(l),i?s+=r*i:s+=4*Math.ceil(r/4),a.semantic===sL?this.hasUv0=true:a.semantic===sI?this.hasUv1=true:a.semantic===sC?this.hasColor=true:a.semantic===sA&&(this.hasTangents=true);}i&&(this.verticesByteSize=s),this._evaluateHash();}get elements(){return this._elements}static getDefaultInstancingFormat(e){return nC.get(e,()=>new nP(e,[{semantic:s$,components:4,type:rM},{semantic:sj,components:4,type:rM},{semantic:sZ,components:4,type:rM},{semantic:sQ,components:4,type:rM}]))}static isElementValid(e,t){let i=t.components*aK[t.type];return !e.isWebGPU||!!nw.includes(i)}update(){this._evaluateHash();}_evaluateHash(){let e=[],t=[],i=this._elements.length;for(let s=0;s<i;s++){let{name:i,dataType:r,numComponents:a,normalize:n,offset:o,stride:l,size:h,asInt:c}=this._elements[s],d=i+r+a+n+c;e.push(d);let u=d+o+l+h;t.push(u);}e.sort();let s=e.join();this.batchingHash=nE(s),this.shaderProcessingHashString=s,this.renderingHashString=t.join("_"),this.renderingHash=nb.get(this.renderingHashString);}}let nL=new nf;class nI{set func(e){this._func=e,this._dirty=true;}get func(){return this._func}set ref(e){this._ref=e,this._dirty=true;}get ref(){return this._ref}set fail(e){this._fail=e,this._dirty=true;}get fail(){return this._fail}set zfail(e){this._zfail=e,this._dirty=true;}get zfail(){return this._zfail}set zpass(e){this._zpass=e,this._dirty=true;}get zpass(){return this._zpass}set readMask(e){this._readMask=e,this._dirty=true;}get readMask(){return this._readMask}set writeMask(e){this._writeMask=e,this._dirty=true;}get writeMask(){return this._writeMask}constructor(e={}){this._dirty=true,this._func=e.func??t7,this._ref=e.ref??0,this._readMask=e.readMask??255,this._writeMask=e.writeMask??255,this._fail=e.fail??s0,this._zfail=e.zfail??s0,this._zpass=e.zpass??s0,this._evalKey();}_evalKey(){let{_func:e,_ref:t,_fail:i,_zfail:s,_zpass:r,_readMask:a,_writeMask:n}=this,o=`${e},${t},${i},${s},${r},${a},${n}`;this._key=nL.get(o),this._dirty=false;}get key(){return this._dirty&&this._evalKey(),this._key}copy(e){return this._func=e._func,this._ref=e._ref,this._readMask=e._readMask,this._writeMask=e._writeMask,this._fail=e._fail,this._zfail=e._zfail,this._zpass=e._zpass,this._dirty=e._dirty,this._key=e._key,this}clone(){return new this.constructor().copy(this)}static{this.DEFAULT=Object.freeze(new nI);}}class nD extends eo{static{this.EVENT_RESIZE="resizecanvas";}constructor(e,t){super(),this.backBuffer=null,this.backBufferSize=new eN,this.backBufferAntialias=false,this.isWebGPU=false,this.isWebGL2=false,this.isHdr=false,this.maxIndirectDrawCount=1024,this.maxColorAttachments=1,this.maxSamples=1,this.supportsCompute=false,this.supportsStorageTextureRead=false,this.renderTarget=null,this.shaders=[],this.textures=[],this.targets=new Set,this.renderVersion=0,this.insideRenderPass=false,this.supportsUniformBuffers=false,this.supportsClipDistances=false,this.textureRG11B10Renderable=false,this.textureFloatFilterable=false,this.blendState=new nu,this.depthState=new nm,this.stencilEnabled=false,this.stencilFront=new nI,this.stencilBack=new nI,this.defaultClearOptions={color:[0,0,0,1],depth:1,stencil:0,flags:tB|tU},this.clientRect={width:0,height:0},this._shadersDirty=false,this.capsDefines=new Map,this.mapsToClear=new Set,this.canvas=e,"setAttribute"in e&&e.setAttribute("data-engine",`PlayCanvas ${V}`),this.initOptions={...t},this.initOptions.alpha??=true,this.initOptions.depth??=true,this.initOptions.stencil??=true,this.initOptions.antialias??=true,this.initOptions.powerPreference??="high-performance",this.initOptions.displayFormat??=aD,this._maxPixelRatio=ee.browser?Math.min(1,window.devicePixelRatio):1,this.buffers=[],this._vram={tex:0,vb:0,ib:0,ub:0,sb:0},this._shaderStats={vsCompiled:0,fsCompiled:0,linked:0,materialShaders:0,compileTime:0},this.initializeContextCaches(),this._drawCallsPerFrame=0,this._shaderSwitchesPerFrame=0,this._primsPerFrame=[];for(let e=sm;e<=sx;e++)this._primsPerFrame[e]=0;this._renderTargetCreationTime=0,this.scope=new ny("Device"),this.textureBias=this.scope.resolve("textureBias"),this.textureBias.setValue(0);}postInit(){let e=new nP(this,[{semantic:sT,components:2,type:rM}]),t=new Float32Array([-1,-1,1,-1,-1,1,1,1]);this.quadVertexBuffer=new nT(this,e,4,{data:t});}initCapsDefines(){let{capsDefines:e}=this;e.clear(),this.textureFloatFilterable&&e.set("CAPS_TEXTURE_FLOAT_FILTERABLE",""),this.textureFloatRenderable&&e.set("CAPS_TEXTURE_FLOAT_RENDERABLE","");}destroy(){this.fire("destroy"),this.quadVertexBuffer?.destroy(),this.quadVertexBuffer=null,this.dynamicBuffers?.destroy(),this.dynamicBuffers=null,this.gpuProfiler?.destroy(),this.gpuProfiler=null;}onDestroyShader(e){this.fire("destroy:shader",e);let t=this.shaders.indexOf(e);-1!==t&&this.shaders.splice(t,1);}postDestroy(){this.scope=null,this.canvas=null;}loseContext(){for(let e of(this.contextLost=true,this.backBufferSize.set(-1,-1),this.textures))e.loseContext();for(let e of this.buffers)e.loseContext();for(let e of this.targets)e.loseContext();this.gpuProfiler?.loseContext();}restoreContext(){for(let e of(this.contextLost=false,this.initializeRenderState(),this.initializeContextCaches(),this.buffers))e.unlock();this.gpuProfiler?.restoreContext?.();}toJSON(e){}initializeContextCaches(){this.vertexBuffers=[],this.shader=null,this.shaderValid=void 0,this.shaderAsyncCompile=false,this.renderTarget=null;}initializeRenderState(){this.blendState=new nu,this.depthState=new nm,this.cullMode=tq,this.vx=this.vy=this.vw=this.vh=0,this.sx=this.sy=this.sw=this.sh=0,this.blendColor=new eb(0,0,0,0);}setStencilState(e,t){}setBlendState(e){}setBlendColor(e,t,i,s){}setDepthState(e){}setCullMode(e){}setRenderTarget(e){this.renderTarget=e;}setVertexBuffer(e){e&&this.vertexBuffers.push(e);}clearVertexBuffer(){this.vertexBuffers.length=0;}getIndirectDrawSlot(){return 0}get indirectDrawBuffer(){return null}getRenderTarget(){return this.renderTarget}initRenderTarget(e){e.initialized||(e.init(),this.targets.add(e));}draw(e,t,i,s,r=true,a=true){}_isBrowserInterface(e){return this._isImageBrowserInterface(e)||this._isImageCanvasInterface(e)||this._isImageVideoInterface(e)}_isImageBrowserInterface(e){return "undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement}_isImageCanvasInterface(e){return "undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement}_isImageVideoInterface(e){return "undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement}resizeCanvas(e,t){let i=Math.min(this._maxPixelRatio,ee.browser?window.devicePixelRatio:1),s=Math.floor(e*i),r=Math.floor(t*i);(s!==this.canvas.width||r!==this.canvas.height)&&this.setResolution(s,r);}setResolution(e,t){this.canvas.width=e,this.canvas.height=t,this.fire(nD.EVENT_RESIZE,e,t);}update(){this.updateClientRect();}updateClientRect(){if(ee.worker)this.clientRect.width=this.canvas.width,this.clientRect.height=this.canvas.height;else {let e=this.canvas.getBoundingClientRect();this.clientRect.width=e.width,this.clientRect.height=e.height;}}get width(){return this.canvas.width}get height(){return this.canvas.height}set fullscreen(e){}get fullscreen(){return false}set maxPixelRatio(e){this._maxPixelRatio=e;}get maxPixelRatio(){return this._maxPixelRatio}get deviceType(){return this._deviceType}startRenderPass(e){}endRenderPass(e){}startComputePass(e){}endComputePass(){}frameStart(){this.renderPassIndex=0,this.renderVersion++;}frameEnd(){this.mapsToClear.forEach(e=>e.clear()),this.mapsToClear.clear();}computeDispatch(e,t="Unnamed"){}getRenderableHdrFormat(e=[iE,ig,iS],t=true,i=1){for(let s=0;s<e.length;s++){let r=e[s];switch(r){case iE:if(this.textureRG11B10Renderable)return r;break;case ig:if(this.textureHalfFloatRenderable)return r;break;case iS:if(this.isWebGPU&&i>1)continue;if(this.textureFloatRenderable&&(!t||this.textureFloatFilterable))return r}}}validateAttributes(e,t,i){}}let nR=0;class nM{constructor(e={}){this.id=nR++;let t=e.colorBuffer?.device??e.colorBuffers?.[0].device??e.depthBuffer?.device??e.graphicsDevice;this._device=t;let{maxSamples:i}=this._device;if(this._samples=Math.min(e.samples??1,i),t.isWebGPU&&(this._samples=this._samples>1?i:1),this._colorBuffer=e.colorBuffer,e.colorBuffer&&(this._colorBuffers=[e.colorBuffer]),this._depthBuffer=e.depthBuffer,this._face=e.face??0,this._depthBuffer){let e=this._depthBuffer._format;e===ix||e===sn?(this._depth=true,this._stencil=false):e===iT?(this._depth=true,this._stencil=true):(e===iy&&this._depthBuffer.device.isWebGPU&&this._samples>1?this._depth=true:this._depth=false,this._stencil=false);}else this._depth=e.depth??true,this._stencil=e.stencil??false;e.colorBuffers&&!this._colorBuffers&&(this._colorBuffers=[...e.colorBuffers],this._colorBuffer=e.colorBuffers[0]),this.autoResolve=e.autoResolve??true,this.name=e.name,this.name||(this.name=this._colorBuffer?.name),this.name||(this.name=this._depthBuffer?.name),this.name||(this.name="Untitled"),this.flipY=e.flipY??false,this._mipLevel=e.mipLevel??0,this._mipLevel>0&&this._depth&&(this._mipLevel=0),this._mipmaps=void 0===e.mipLevel,this.validateMrt(),this.impl=t.createRenderTargetImpl(this);}destroy(){let e=this._device;e&&(e.targets.delete(this),e.renderTarget===this&&e.setRenderTarget(null),this.destroyFrameBuffers());}destroyFrameBuffers(){let e=this._device;e&&this.impl.destroy(e);}destroyTextureBuffers(){this._depthBuffer?.destroy(),this._depthBuffer=null,this._colorBuffers?.forEach(e=>{e.destroy();}),this._colorBuffers=null,this._colorBuffer=null;}resize(e,t){if(this.width!==e||this.height!==t){if(this.mipLevel>0)return;let i=this._device;this.destroyFrameBuffers(),i.renderTarget===this&&i.setRenderTarget(null),this._depthBuffer?.resize(e,t),this._colorBuffers?.forEach(i=>{i.resize(e,t);}),this.validateMrt(),this.impl=i.createRenderTargetImpl(this);}}validateMrt(){}init(){this.impl.init(this._device,this);}get initialized(){return this.impl.initialized}get device(){return this._device}loseContext(){this.impl.loseContext();}resolve(e=true,t=!!this._depthBuffer){this._device&&this._samples>1&&this.impl.resolve(this._device,this,e,t);}copy(e,t,i){if(!this._device)if(!e._device)return false;else this._device=e._device;return this._device.copyRenderTarget(e,this,t,i)}get samples(){return this._samples}get depth(){return this._depth}get stencil(){return this._stencil}get colorBuffer(){return this._colorBuffer}getColorBuffer(e){return this._colorBuffers?.[e]}get depthBuffer(){return this._depthBuffer}get face(){return this._face}get mipLevel(){return this._mipLevel}get mipmaps(){return this._mipmaps}get width(){let e=this._colorBuffer?.width||this._depthBuffer?.width||this._device.width;return this._mipLevel>0&&(e=nt.calcLevelDimension(e,this._mipLevel)),e}get height(){let e=this._colorBuffer?.height||this._depthBuffer?.height||this._device.height;return this._mipLevel>0&&(e=nt.calcLevelDimension(e,this._mipLevel)),e}isColorBufferSrgb(e=0){if(this.device.backBuffer===this)return sh(this.device.backBufferFormat);let t=this.getColorBuffer(e);return !!t&&sh(t.format)}}class nO{update(e){this.destroy();let t=e.device,i=this.createDescriptor(t,e);this.bindGroup=t.wgpu.createBindGroup(i);}destroy(){this.bindGroup=null;}createDescriptor(e,t){let i=[],s=t.format,r=t.format.uniformBufferFormats;t.uniformBuffers.forEach((e,t)=>{let s=r[t].slot,a=e.persistent?e.impl.buffer:e.allocation.gpuBuffer.buffer;i.push({binding:s,resource:{buffer:a,offset:0,size:e.format.byteSize}});});let a=t.format.textureFormats;t.textures.forEach((t,r)=>{let n=t.impl,o=s.textureFormats[r],l=a[r].slot,h=n.getView(e);if(i.push({binding:l,resource:h}),o.hasSampler){let t=n.getSampler(e,o.sampleType);i.push({binding:l+1,resource:t});}});let n=t.format.storageTextureFormats;t.storageTextures.forEach((t,s)=>{let r=t.impl,a=n[s].slot,o=r.getView(e);i.push({binding:a,resource:o});});let o=t.format.storageBufferFormats;return t.storageBuffers.forEach((e,t)=>{let s=e.impl.buffer,r=o[t].slot;i.push({binding:r,resource:{buffer:s}});}),{layout:t.format.impl.bindGroupLayout,entries:i}}}class nN{static shaderStage(e){let t=0;return e&aP&&(t|=GPUShaderStage.VERTEX),e&aL&&(t|=GPUShaderStage.FRAGMENT),e&aI&&(t|=GPUShaderStage.COMPUTE),t}}let nF=[];nF[is]="",nF[ir]="",nF[ia]="",nF[i3]="r8unorm",nF[i4]="rg8unorm",nF[io]="",nF[il]="",nF[ih]="",nF[ic]="rgba8unorm",nF[id]="rgba8unorm",nF[iu]="bc1-rgba-unorm",nF[ip]="bc2-rgba-unorm",nF[im]="bc3-rgba-unorm",nF[i_]="",nF[ig]="rgba16float",nF[i1]="r16float",nF[i2]="rg16float",nF[iv]="",nF[iS]="rgba32float",nF[iy]="r32float",nF[ix]="depth32float",nF[sn]="depth16unorm",nF[iT]="depth24plus-stencil8",nF[iE]="rg11b10ufloat",nF[iA]="",nF[ib]="rgba8unorm-srgb",nF[iw]="",nF[iC]="etc2-rgb8unorm",nF[iP]="etc2-rgba8unorm",nF[iL]="",nF[iI]="",nF[iD]="",nF[iR]="",nF[iM]="astc-4x4-unorm",nF[iO]="",nF[iN]="",nF[iF]="bgra8unorm",nF[st]="bgra8unorm-srgb",nF[iB]="r8sint",nF[iU]="r8uint",nF[ik]="r16sint",nF[iV]="r16uint",nF[iz]="r32sint",nF[iG]="r32uint",nF[iH]="rg8sint",nF[iW]="rg8uint",nF[iX]="rg16sint",nF[iY]="rg16uint",nF[iq]="rg32sint",nF[i$]="rg32uint",nF[ij]="rgba8sint",nF[iK]="rgba8uint",nF[iZ]="rgba16sint",nF[iQ]="rgba16uint",nF[iJ]="rgba32sint",nF[i0]="rgba32uint",nF[si]="bc6h-rgb-float",nF[ss]="bc6h-rgb-ufloat",nF[sr]="bc7-rgba-unorm",nF[i5]="bc1-rgba-unorm-srgb",nF[i8]="bc2-rgba-unorm-srgb",nF[i6]="bc3-rgba-unorm-srgb",nF[i9]="etc2-rgb8unorm-srgb",nF[i7]="etc2-rgba8unorm-srgb",nF[sa]="bc7-rgba-unorm-srgb",nF[se]="astc-4x4-unorm-srgb";let nB=[];nB[r_]="filtering",nB[rg]="non-filtering",nB[rv]="comparison",nB[rS]="comparison",nB[ry]="comparison";let nU=[];nU[r_]="float",nU[rg]="unfilterable-float",nU[rv]="depth",nU[rS]="sint",nU[ry]="uint";let nk=new nf;class nV{constructor(e){let t=e.device,{key:i,desc:s}=this.createDescriptor(e);this.key=nk.get(i),this.bindGroupLayout=t.wgpu.createBindGroupLayout(s);}destroy(){this.bindGroupLayout=null;}loseContext(){}createDescriptor(e){let t=[],i="";return e.uniformBufferFormats.forEach(e=>{let s=nN.shaderStage(e.visibility);i+=`#${e.slot}U:${s}`,t.push({binding:e.slot,visibility:s,buffer:{type:"uniform",hasDynamicOffset:true}});}),e.textureFormats.forEach(e=>{let s=nN.shaderStage(e.visibility),r=e.sampleType,a=e.textureDimension,n=nU[r];if(i+=`#${e.slot}T:${s}-${n}-${a}-false`,t.push({binding:e.slot,visibility:s,texture:{sampleType:n,viewDimension:a,multisampled:false}}),e.hasSampler){let a=nB[r];i+=`#${e.slot+1}S:${s}-${a}`,t.push({binding:e.slot+1,visibility:s,sampler:{type:a}});}}),e.storageTextureFormats.forEach(e=>{let{format:s,textureDimension:r}=e,{read:a,write:n}=e;i+=`#${e.slot}ST:${s}-${r}-${a?"r1":"r0"}-${n?"w1":"w0"}`,t.push({binding:e.slot,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:a?n?"read-write":"read-only":"write-only",format:nF[s],viewDimension:r}});}),e.storageBufferFormats.forEach(e=>{let s=e.readOnly,r=nN.shaderStage(e.visibility);i+=`#${e.slot}SB:${r}-${s?"ro":"rw"}`,t.push({binding:e.slot,visibility:r,buffer:{type:s?"read-only-storage":"storage"}});}),{key:i,desc:{entries:t}}}}class nz{constructor(e=0){this.buffer=null,this.usageFlags=0,this.usageFlags=e;}destroy(e){this.buffer&&(this.buffer.destroy(),this.buffer=null);}get initialized(){return !!this.buffer}loseContext(){}allocate(e,t){this.buffer=e.wgpu.createBuffer({size:t,usage:this.usageFlags});}unlock(e,t){let i=e.wgpu;if(!this.buffer){let i=t.byteLength+3&-4;this.usageFlags|=GPUBufferUsage.COPY_DST,this.allocate(e,i);}let s=t.byteOffset??0,r=new Uint8Array(t.buffer??t,s,t.byteLength),a=new Uint8Array(this.buffer.size);a.set(r),i.queue.writeBuffer(this.buffer,0,a,0,a.length);}read(e,t,i,s,r){return e.readStorageBuffer(this,t,i,s,r)}write(e,t,i,s,r){e.writeStorageBuffer(this,t,i,s,r);}clear(e,t,i){e.clearStorageBuffer(this,t,i);}}class nG extends nz{constructor(e,t){super(tP|(t?.storage?tD:0)),this.format=null,this.format=e.format===it?"uint16":"uint32";}unlock(e){let t=e.device;super.unlock(t,e.storage);}}let nH={equals(e,t){if(e.length!==t.length)return false;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return false;return true}},nW=[];nW[rC]="sint8",nW[rP]="uint8",nW[rL]="sint16",nW[rI]="uint16",nW[rD]="sint32",nW[rR]="uint32",nW[rM]="float32",nW[rO]="float16";let nX=[];nX[rC]="snorm8",nX[rP]="unorm8",nX[rL]="snorm16",nX[rI]="unorm16",nX[rD]="sint32",nX[rR]="uint32",nX[rM]="float32",nX[rO]="float16";class nY{get(e,t=null){let i=this.getKey(e,t),s=this.cache.get(i);return s||(s=this.create(e,t),this.cache.set(i,s)),s}getKey(e,t=null){return `${e?.renderingHashString}-${t?.renderingHashString}`}create(e,t){let i=[],s=e=>{let t=e.interleaved,s=e.instancing?"instance":"vertex",r=[],a=e.elements.length;for(let n=0;n<a;n++){let o=e.elements[n],l=a2[o.name],h=o.normalize?nX:nW;r.push({shaderLocation:l,offset:t?o.offset:0,format:`${h[o.dataType]}${o.numComponents>1?`x${o.numComponents}`:""}`}),t&&n!==a-1||(i.push({attributes:r,arrayStride:o.stride,stepMode:s}),r=[]);}};return e&&s(e),t&&s(t),i}constructor(){this.cache=new Map;}}class nq{constructor(e){this.device=e;}getPipelineLayout(e){let t=[];return e.forEach(e=>{t.push(e.bindGroupLayout);}),this.device.wgpu.createPipelineLayout({bindGroupLayouts:t})}}let n$=["point-list","line-list",void 0,"line-strip","triangle-list","triangle-strip",void 0],nj=["add","subtract","reverse-subtract","min","max"],nK=["zero","one","src","one-minus-src","dst","one-minus-dst","src-alpha","src-alpha-saturated","one-minus-src-alpha","dst-alpha","one-minus-dst-alpha","constant","one-minus-constant"],nZ=["never","less","equal","less-equal","greater","not-equal","greater-equal","always"],nQ=["none","back","front"],nJ=["keep","zero","replace","increment-clamp","increment-wrap","decrement-clamp","decrement-wrap","invert"],n0=["","uint16","uint32"];class n1{}class n2 extends nq{constructor(e){super(e),this.lookupHashes=new Uint32Array(14),this.vertexBufferLayout=new nY,this.cache=new Map;}get(e,t,i,s,r,a,n,o,l,h,c,d,u){let f=e.type;s&&f!==sv&&f!==sy&&(s=void 0);let p=this.lookupHashes;p[0]=f,p[1]=r.id,p[2]=h,p[3]=l.key,p[4]=o.key,p[5]=t?.renderingHash??0,p[6]=i?.renderingHash??0,p[7]=a.impl.key,p[8]=n[0]?.key??0,p[9]=n[1]?.key??0,p[10]=n[2]?.key??0,p[11]=c?d.key:0,p[12]=c?u.key:0,p[13]=s??0;let m=nA(p),_=this.cache.get(m);if(_)for(let e=0;e<_.length;e++){let t=_[e];if(nH.equals(t.hashes,p))return t.pipeline}let g=n$[f],v=this.getPipelineLayout(n),S=this.vertexBufferLayout.get(t,i),y=new n1;return y.hashes=new Uint32Array(p),y.pipeline=this.create(g,s,r,a,v,o,l,S,h,c,d,u),_?_.push(y):_=[y],this.cache.set(m,_),y.pipeline}getBlend(e){let t;return e.blend&&(t={color:{operation:nj[e.colorOp],srcFactor:nK[e.colorSrcFactor],dstFactor:nK[e.colorDstFactor]},alpha:{operation:nj[e.alphaOp],srcFactor:nK[e.alphaSrcFactor],dstFactor:nK[e.alphaDstFactor]}}),t}getDepthStencil(e,t,i,s,r,a){let n,{depth:o,stencil:l}=t;if(o||l){if(n={format:t.impl.depthAttachment.format},o){n.depthWriteEnabled=e.write,n.depthCompare=nZ[e.func];let t="triangle-list"===a||"triangle-strip"===a;n.depthBias=t?e.depthBias:0,n.depthBiasSlopeScale=t?e.depthBiasSlope:0;}else n.depthWriteEnabled=false,n.depthCompare="always";l&&i&&(n.stencilReadMas=s.readMask,n.stencilWriteMask=s.writeMask,n.stencilFront={compare:nZ[s.func],failOp:nJ[s.fail],passOp:nJ[s.zpass],depthFailOp:nJ[s.zfail]},n.stencilBack={compare:nZ[r.func],failOp:nJ[r.fail],passOp:nJ[r.zpass],depthFailOp:nJ[r.zfail]});}return n}create(e,t,i,s,r,a,n,o,l,h,c,d){let u=this.device.wgpu,f=i.impl,p={vertex:{module:f.getVertexShaderModule(),entryPoint:f.vertexEntryPoint,buffers:o},primitive:{topology:e,frontFace:"ccw",cullMode:nQ[l]},depthStencil:this.getDepthStencil(n,s,h,c,d,e),multisample:{count:s.samples},layout:r};t&&(p.primitive.stripIndexFormat=n0[t]),p.fragment={module:f.getFragmentShaderModule(),entryPoint:f.fragmentEntryPoint,targets:[]};let m=s.impl.colorAttachments;if(m.length>0){let e=0;a.redWrite&&(e|=GPUColorWrite.RED),a.greenWrite&&(e|=GPUColorWrite.GREEN),a.blueWrite&&(e|=GPUColorWrite.BLUE),a.alphaWrite&&(e|=GPUColorWrite.ALPHA);let t=this.getBlend(a);m.forEach(i=>{p.fragment.targets.push({format:i.format,writeMask:e,blend:t});});}return u.createRenderPipeline(p)}}class n3 extends nq{get(e,t){let i=this.getPipelineLayout([t.impl]);return this.create(e,i)}create(e,t){let i=this.device.wgpu,s=e.impl,r={compute:{module:s.getComputeShaderModule(),entryPoint:s.computeEntryPoint},layout:t};return i.createComputePipeline(r)}}class n4{incRefCount(){this._refCount++;}decRefCount(){this._refCount--;}get refCount(){return this._refCount}constructor(){this._refCount=0;}}class n5 extends n4{constructor(e){super(),this.object=e,this.incRefCount();}}class n8{destroy(){this.cache.forEach(e=>{e.object?.destroy();}),this.cache.clear();}clear(){this.cache.clear();}get(e){let t=this.cache.get(e);return t?(t.incRefCount(),t.object):null}set(e,t){this.cache.set(e,new n5(t));}release(e){let t=this.cache.get(e);t&&(t.decRefCount(),0===t.refCount&&(this.cache.delete(e),t.object?.destroy()));}constructor(){this.cache=new Map;}}class n6 extends n8{loseContext(e){this.clear();}}let n9=new ne,n7=e=>n9.get(e,()=>new n6),oe=new nf;class ot{destroy(){this.multisampledBuffer?.destroy(),this.multisampledBuffer=null;}}class oi{constructor(e){this.depthTexture=null,this.depthTextureInternal=false,this.multisampledDepthBuffer=null,this.format=e,this.hasStencil="depth24plus-stencil8"===e;}destroy(e){this.depthTextureInternal&&(this.depthTexture?.destroy(),this.depthTexture=null),this.multisampledDepthBuffer&&(this.multisampledDepthBuffer=null,n7(e).release(this.multisampledDepthBufferKey));}}class os{constructor(e){this.initialized=false,this.colorAttachments=[],this.depthAttachment=null,this.assignedColorTexture=null,this.renderPassDescriptor={},this.isBackbuffer=false,this.renderTarget=e;}destroy(e){this.initialized=false,this.assignedColorTexture=null,this.colorAttachments.forEach(e=>{e.destroy();}),this.colorAttachments.length=0,this.depthAttachment?.destroy(e),this.depthAttachment=null;}updateKey(){let e=this.renderTarget,t=`${e.samples}:${this.depthAttachment?this.depthAttachment.format:"nodepth"}`;this.colorAttachments.forEach(e=>{t+=`:${e.format}`;}),this.key=oe.get(t);}assignColorTexture(e,t){this.assignedColorTexture=t;let i=t.createView({format:e.backBufferViewFormat}),s=this.renderPassDescriptor.colorAttachments[0];this.renderTarget.samples>1?s.resolveTarget=i:s.view=i,this.setColorAttachment(0,void 0,e.backBufferViewFormat),this.updateKey();}setColorAttachment(e,t,i){this.colorAttachments[e]||(this.colorAttachments[e]=new ot),t&&(this.colorAttachments[e].multisampledBuffer=t),i&&(this.colorAttachments[e].format=i);}init(e,t){let i=e.wgpu;this.initDepthStencil(e,i,t),t._colorBuffers&&t._colorBuffers.forEach((e,t)=>{this.setColorAttachment(t,void 0,e.impl.format);}),this.renderPassDescriptor.colorAttachments=[];let s=this.isBackbuffer?1:t._colorBuffers?.length??0;for(let r=0;r<s;++r){let s=this.initColor(e,i,t,r),a=0===r&&this.colorAttachments[0]?.format;(s.view||a)&&this.renderPassDescriptor.colorAttachments.push(s);}this.updateKey(),this.initialized=true;}initDepthStencil(e,t,i){let{samples:s,width:r,height:a,depth:n,depthBuffer:o}=i;if(n||o){let i;if(o)if(this.depthAttachment=new oi(o.impl.format),s>1){let n="depth24plus-stencil8";this.depthAttachment.format=n,this.depthAttachment.hasStencil=true;let l=`${o.id}:${r}:${a}:${s}:${n}`,h=n7(e),c=h.get(l);if(!c){let e={size:[r,a,1],dimension:"2d",sampleCount:s,format:n,usage:GPUTextureUsage.RENDER_ATTACHMENT|(n!==o.impl.format?GPUTextureUsage.TEXTURE_BINDING:0)};c=t.createTexture(e),h.set(l,c);}this.depthAttachment.multisampledDepthBuffer=c,this.depthAttachment.multisampledDepthBufferKey=l,i=c.createView();}else {let e=o.impl.gpuTexture;this.depthAttachment.depthTexture=e,i=e.createView();}else {this.depthAttachment=new oi("depth24plus-stencil8");let e={size:[r,a,1],dimension:"2d",sampleCount:s,format:this.depthAttachment.format,usage:GPUTextureUsage.RENDER_ATTACHMENT};s>1?e.usage|=GPUTextureUsage.TEXTURE_BINDING:e.usage|=GPUTextureUsage.COPY_SRC;let n=t.createTexture(e);this.depthAttachment.depthTexture=n,this.depthAttachment.depthTextureInternal=true,i=n.createView();}this.renderPassDescriptor.depthStencilAttachment={view:i};}}initColor(e,t,i,s){let r={},{samples:a,width:n,height:o,mipLevel:l}=i,h=i.getColorBuffer(s),c=null;if(h&&(c=h.cubemap?h.impl.createView({dimension:"2d",baseArrayLayer:i.face,arrayLayerCount:1,mipLevelCount:1,baseMipLevel:l}):h.impl.createView({mipLevelCount:1,baseMipLevel:l})),a>1){let i={size:[n,o,1],dimension:"2d",sampleCount:a,format:this.isBackbuffer?e.backBufferViewFormat:h.impl.format,usage:GPUTextureUsage.RENDER_ATTACHMENT},l=t.createTexture(i);this.setColorAttachment(s,l,i.format),r.view=l.createView(),r.resolveTarget=c;}else r.view=c;return r}setupForRenderPass(e,t){let i=this.renderPassDescriptor.colorAttachments?.length??0;for(let s=0;s<i;++s){let i=this.renderPassDescriptor.colorAttachments[s],r=e.colorArrayOps[s];i.clearValue=t.isColorBufferSrgb(s)?r.clearValueLinear:r.clearValue,i.loadOp=r.clear?"clear":"load",i.storeOp=r.store?"store":"discard";}let s=this.renderPassDescriptor.depthStencilAttachment;s&&(s.depthClearValue=e.depthStencilOps.clearDepthValue,s.depthLoadOp=e.depthStencilOps.clearDepth?"clear":"load",s.depthStoreOp=e.depthStencilOps.storeDepth?"store":"discard",s.depthReadOnly=false,this.depthAttachment.hasStencil&&(s.stencilClearValue=e.depthStencilOps.clearStencilValue,s.stencilLoadOp=e.depthStencilOps.clearStencil?"clear":"load",s.stencilStoreOp=e.depthStencilOps.storeStencil?"store":"discard",s.stencilReadOnly=false));}loseContext(){this.initialized=false;}resolve(e,t,i,s){}}let or=[];or[rB]=1,or[rU]=2,or[rk]=3,or[rV]=4,or[rF]=1,or[rz]=2,or[rG]=3,or[rH]=4,or[rN]=1,or[rW]=2,or[rX]=3,or[rY]=4,or[rq]=8,or[r$]=12,or[rj]=16,or[r6]=1,or[r9]=2,or[r7]=3,or[ae]=4;class oa{get isArrayType(){return this.count>0}constructor(e,t,i=0){if(this.shortName=e,this.name=i?`${e}[0]`:e,this.type=t,this.numComponents=or[t],this.updateType=t,i>0)switch(t){case rB:this.updateType=rQ;break;case rF:this.updateType=at;break;case r6:this.updateType=ai;break;case rN:this.updateType=as;break;case rU:this.updateType=r2;break;case rz:this.updateType=ar;break;case r9:this.updateType=aa;break;case rW:this.updateType=an;break;case rk:this.updateType=r3;break;case rG:this.updateType=ao;break;case r7:this.updateType=al;break;case rX:this.updateType=ah;break;case rV:this.updateType=r4;break;case rH:this.updateType=ac;break;case ae:this.updateType=ad;break;case rY:this.updateType=au;break;case rj:this.updateType=r5;}this.count=i;let s=this.numComponents;i&&(s=eA.roundUp(s,4)),this.byteSize=4*s,i&&(this.byteSize*=i);}calculateOffset(e){let t=this.byteSize<=8?this.byteSize:16;this.count&&(t=16),e=eA.roundUp(e,t),this.offset=e/4;}}class on{constructor(e,t){this.byteSize=0,this.map=new Map,this.scope=e.scope,this.uniforms=t;let i=0;for(let e=0;e<t.length;e++){let s=t[e];s.calculateOffset(i),i=4*s.offset+s.byteSize,s.scopeId=this.scope.resolve(s.name),this.map.set(s.name,s);}this.byteSize=eA.roundUp(i,16);}get(e){return this.map.get(e)}}let oo=/[ \t]*(\battribute\b|\bvarying\b|\buniform\b)/g,ol=/(\battribute\b|\bvarying\b|\bout\b|\buniform\b)[ \t]*([^;]+)(;+)/g,oh=/([\w-]+)\[(.*?)\]/,oc=new Set(["highp","mediump","lowp"]),od=new Set(["sampler2DShadow","samplerCubeShadow","sampler2DArrayShadow"]),ou={sampler2D:rd,sampler3D:rm,samplerCube:rf,samplerCubeShadow:rf,sampler2DShadow:rd,sampler2DArray:ru,sampler2DArrayShadow:ru,isampler2D:rd,usampler2D:rd,isampler3D:rm,usampler3D:rm,isamplerCube:rf,usamplerCube:rf,isampler2DArray:ru,usampler2DArray:ru},of={[rd]:"texture2D",[rf]:"textureCube",[rm]:"texture3D",[ru]:"texture2DArray"},op=class{constructor(e,t){this.line=e;let i=e.trim().split(/\s+/);if(oc.has(i[0])&&(this.precision=i.shift()),this.type=i.shift(),e.includes(","),e.includes("[")){let e=i.join(" "),s=oh.exec(e);this.name=s[1],this.arraySize=Number(s[2]),isNaN(this.arraySize)&&(t.failed=true);}else this.name=i.shift(),this.arraySize=0;this.isSampler=-1!==this.type.indexOf("sampler"),this.isSignedInt=-1!==this.type.indexOf("isampler"),this.isUnsignedInt=-1!==this.type.indexOf("usampler");}};class om{static run(e,t,i){let s=new Map,r=om.extract(t.vshader),a=om.extract(t.fshader),n=new Map,o=om.processAttributes(r.attributes,t.attributes,n,t.processingOptions),l=om.processVaryings(r.varyings,s,true),h=om.processVaryings(a.varyings,s,false),c=om.processOuts(a.outs),d=Array.from(new Set(r.uniforms.concat(a.uniforms))).map(e=>new op(e,i)),u=om.processUniforms(e,d,t.processingOptions,i),f=`${o}
${l}
${u.code}`,p=r.src.replace("@@@",f),m=`${h}
${c}
${u.code}`;return {vshader:p,fshader:a.src.replace("@@@",m),attributes:n,meshUniformBufferFormat:u.meshUniformBufferFormat,meshBindGroupFormat:u.meshBindGroupFormat}}static extract(e){let t,i=[],s=[],r=[],a=[],n=`@@@
`;for(;null!==(t=oo.exec(e));){let o=t[1];switch(o){case "attribute":case "varying":case "uniform":case "out":{ol.lastIndex=t.index;let l=ol.exec(e);"attribute"===o?i.push(l[2]):"varying"===o?s.push(l[2]):"out"===o?r.push(l[2]):"uniform"===o&&a.push(l[2]),e=om.cutOut(e,t.index,ol.lastIndex,n),oo.lastIndex=t.index+n.length,n="";}}}return {src:e,attributes:i,varyings:s,outs:r,uniforms:a}}static processUniforms(e,t,i,s){let r=[],a=[];t.forEach(e=>{e.isSampler?r.push(e):a.push(e);});let n=[];a.forEach(e=>{if(!i.hasUniform(e.name)){let t=ax.indexOf(e.type),i=new oa(e.name,t,e.arraySize);n.push(i);}}),0===n.length&&n.push(new oa(a$,rB));let o=n.length?new on(e,n):null,l=[];r.forEach(e=>{if(!i.hasTexture(e.name)){let t=r_;e.isSignedInt?t=rS:e.isUnsignedInt?t=ry:("highp"===e.precision&&(t=rg),od.has(e.type)&&(t=rv));let i=ou[e.type];l.push(new a6(e.name,aP|aL,i,t));}});let h=new a7(e,l),c="";return i.uniformFormats.forEach((e,t)=>{e&&(c+=om.getUniformShaderDeclaration(e,t,0));}),o&&(c+=om.getUniformShaderDeclaration(o,aX,0)),i.bindGroupFormats.forEach((e,t)=>{e&&(c+=om.getTexturesShaderDeclaration(e,t));}),{code:c+=om.getTexturesShaderDeclaration(h,aW),meshUniformBufferFormat:o,meshBindGroupFormat:h}}static processVaryings(e,t,i){let s="",r=i?"out":"in";return e.forEach((e,a)=>{let n=om.splitToWords(e),o=n.slice(0,-1).join(" "),l=n[n.length-1];i?t.set(l,a):a=t.get(l),s+=`layout(location = ${a}) ${r} ${o} ${l};
`;}),s}static processOuts(e){let t="";return e.forEach((e,i)=>{t+=`layout(location = ${i}) out ${e};
`;}),t}static getTypeCount(e){let t=parseInt(e.substring(e.length-1),10);return isNaN(t)?1:t}static processAttributes(e,t,i,s){let r="";return e.forEach(e=>{let a=om.splitToWords(e),n=a[0],o=a[1];if(t.hasOwnProperty(o)){let e,a=t[o],l=a2[a];i.set(l,o);let h=s.getVertexElement(a);if(h){let t=h.dataType;if(t!==rM&&t!==rO&&!h.normalize&&!h.asInt){let i=om.getTypeCount(n),s=`_private_${o}`;e=`vec${i} ${o} = vec${i}(${s});
`,o=s;let r=t===rC||t===rL||t===rD;n=1===i?r?"int":"uint":r?`ivec${i}`:`uvec${i}`;}}r+=`layout(location = ${l}) in ${n} ${o};
`,e&&(r+=e);}}),r}static splitToWords(e){return (e=e.replace(/\s+/g," ").trim()).split(" ")}static cutOut(e,t,i,s){return e.substring(0,t)+s+e.substring(i)}static getUniformShaderDeclaration(e,t,i){let s=aY[t],r=`layout(set = ${t}, binding = ${i}, std140) uniform ub_${s} {
`;return e.uniforms.forEach(e=>{let t=ax[e.type];r+=` ${t} ${e.shortName}${e.count?`[${e.count}]`:""};
`;}),`${r}};
`}static getTexturesShaderDeclaration(e,t){let i="";return e.textureFormats.forEach(e=>{let s=of[e.textureDimension],r="texture2DArray"===s,a=e.sampleType===ry?"u":e.sampleType===rS?"i":"";s=`${a}${s}`;let n="",o="";r&&(n="_texture",o=`#define ${e.name} ${a}sampler2DArray(${e.name}${n}, ${e.name}_sampler)
`),i+=`layout(set = ${t}, binding = ${e.slot}) uniform ${s} ${e.name}${n};
`,e.hasSampler&&(i+=`layout(set = ${t}, binding = ${e.slot+1}) uniform sampler ${e.name}_sampler;
`),i+=o;}),i}}let o_=/^[ \t]*(attribute|varying|uniform)[\t ]+/gm,og=/^[ \t]*(attribute|varying|uniform)[ \t]*([^;]+)(;+)/gm,ov=/^[ \t]*var\s*(?:(<storage,[^>]*>)\s*([\w\d_]+)\s*:\s*(.*?)\s*;|(<(?!storage,)[^>]*>)?\s*([\w\d_]+)\s*:\s*(texture_.*|storage_texture_.*|storage\w.*|external_texture|sampler(?:_comparison)?)\s*;)\s*$/gm,oS=/(?:@interpolate\([^)]*\)\s*)?([\w]+)\s*:/,oy=/(@vertex|@fragment)\s*fn\s+\w+\s*\(\s*(\w+)\s*:[\s\S]*?\{/,ox={texture_1d:{viewDimension:rc,baseSampleType:r_},texture_2d:{viewDimension:rd,baseSampleType:r_},texture_2d_array:{viewDimension:ru,baseSampleType:r_},texture_3d:{viewDimension:rm,baseSampleType:r_},texture_cube:{viewDimension:rf,baseSampleType:r_},texture_cube_array:{viewDimension:rp,baseSampleType:r_},texture_multisampled_2d:{viewDimension:rd,baseSampleType:r_},texture_depth_2d:{viewDimension:rd,baseSampleType:rv},texture_depth_2d_array:{viewDimension:ru,baseSampleType:rv},texture_depth_cube:{viewDimension:rf,baseSampleType:rv},texture_depth_cube_array:{viewDimension:rp,baseSampleType:rv},texture_external:{viewDimension:rd,baseSampleType:rg}},oT=(e,t)=>{let i=ox[e],s=i.baseSampleType;if(i.baseSampleType===r_&&"texture_multisampled_2d"!==e)switch(t){case "u32":s=ry;break;case "i32":s=rS;break;case "f32":s=r_;break;case "uff":s=rg;}return {viewDimension:i.viewDimension,sampleType:s}},oE=(e,t)=>{let i,s;if(t===rv)switch(e){case rd:return "texture_depth_2d";case ru:return "texture_depth_2d_array";case rf:return "texture_depth_cube";case rp:return "texture_depth_cube_array"}switch(e){case rc:i="texture_1d";break;case rd:i="texture_2d";break;case ru:i="texture_2d_array";break;case rm:i="texture_3d";break;case rf:i="texture_cube";break;case rp:i="texture_cube_array";}switch(t){case r_:case rg:s="f32";break;case ry:s="u32";break;case rS:s="i32";}return `${i}<${s}>`},oA={f32:"WrappedF32",i32:"WrappedI32",u32:"WrappedU32",vec2f:"WrappedVec2F",vec2i:"WrappedVec2I",vec2u:"WrappedVec2U"},ob=e=>(e=e.replace(/\s+/g," ").trim()).split(/[\s:]+/),ow=/array<([^,]+),\s*([^>]+)>/;class oC{constructor(e,t){this.ubName=null,this.arraySize=0,this.line=e;let i=ob(e);if(i.length<2){t.failed=true;return}if(this.name=i[0],this.type=i.slice(1).join(" "),this.type.includes("array<")){let e=ow.exec(this.type);this.type=e[1].trim(),this.arraySize=Number(e[2]),isNaN(this.arraySize)&&(t.failed=true);}}}let oP=/^\s*var\s+(\w+)\s*:\s*(texture_\w+)(?:<(\w+)>)?;\s*$/,oL=/^\s*var\s+([\w\d_]+)\s*:\s*(texture_storage_2d|texture_storage_2d_array)<([\w\d_]+),\s*(\w+)>\s*;\s*$/,oI=/^\s*var\s*<storage,\s*(read|write)?>\s*([\w\d_]+)\s*:\s*(.*)\s*;\s*$/,oD=/^\s*var\s+([\w\d_]+)\s*:\s*texture_external;\s*$/,oR=/^\s*var\s+([\w\d_]+)\s*:\s*(sampler|sampler_comparison)\s*;\s*$/;class oM{constructor(e,t){this.originalLine=e,this.line=e,this.isTexture=false,this.isSampler=false,this.isStorageTexture=false,this.isStorageBuffer=false,this.isExternalTexture=false,this.type="",this.matchedElements=[];let i=this.line.match(oP);if(i){this.name=i[1],this.type=i[2],this.textureFormat=i[3],this.isTexture=true,this.matchedElements.push(...i);let e=oT(this.type,this.textureFormat);this.textureDimension=e.viewDimension,this.sampleType=e.sampleType;}let s=this.line.match(oL);s&&(this.isStorageTexture=true,this.name=s[1],this.textureType=s[2],this.format=s[3],this.access=s[4],this.matchedElements.push(...s));let r=this.line.match(oI);r&&(this.isStorageBuffer=true,this.accessMode=r[1]||"none",this.name=r[2],this.type=r[3],this.matchedElements.push(...r));let a=this.line.match(oD);a&&(this.name=a[1],this.isExternalTexture=true,this.matchedElements.push(...r));let n=this.line.match(oR);n&&(this.name=n[1],this.samplerType=n[2],this.isSampler=true,this.matchedElements.push(...n)),0===this.matchedElements.length&&(t.failed=true);}equals(e){return this.name===e.name&&this.type===e.type&&this.isTexture===e.isTexture&&this.isSampler===e.isSampler&&this.isStorageTexture===e.isStorageTexture&&this.isStorageBuffer===e.isStorageBuffer&&this.isExternalTexture===e.isExternalTexture&&this.textureFormat===e.textureFormat&&this.textureDimension===e.textureDimension&&this.sampleType===e.sampleType&&this.textureType===e.textureType&&this.format===e.format&&this.access===e.access&&this.accessMode===e.accessMode&&this.samplerType===e.samplerType&&true}}class oO{static run(e,t,i){let s=new Map,r=oO.extract(t.vshader),a=oO.extract(t.fshader),n=new Map,o=oO.processAttributes(r.attributes,t.attributes,n,t.processingOptions,i),l=oO.processVaryings(r.varyings,s,true),h=oO.processVaryings(a.varyings,s,false),c=Array.from(new Set(r.uniforms.concat(a.uniforms))).map(e=>new oC(e,i)),d=oO.processUniforms(e,c,t.processingOptions,i);r.src=oO.renameUniformAccess(r.src,c),a.src=oO.renameUniformAccess(a.src,c);let u=oO.mergeResources(r.resources,a.resources,i),f=oO.processResources(e,u,t.processingOptions,i),p=oO.generateFragmentOutputStruct(a.src,e.maxColorAttachments);r.src=oO.copyInputs(r.src,i),a.src=oO.copyInputs(a.src,i);let m=`${o}
${l}
${d.code}
${f.code}
`,_=r.src.replace("@@@",m),g=`${h}
${p}
${d.code}
${f.code}
`;return {vshader:_,fshader:a.src.replace("@@@",g),attributes:n,meshUniformBufferFormat:d.meshUniformBufferFormat,meshBindGroupFormat:f.meshBindGroupFormat}}static extract(e){let t,i=[],s=[],r=[],a=[],n=`@@@
`;for(;null!==(t=o_.exec(e));){let a=t[1];og.lastIndex=t.index;let o=og.exec(e);"attribute"===a?i.push(o[2]):"varying"===a?s.push(o[2]):"uniform"===a&&r.push(o[2]),e=oO.cutOut(e,t.index,og.lastIndex,n),o_.lastIndex=t.index+n.length,n="";}for(;null!==(t=ov.exec(e));)a.push(t[0]),e=oO.cutOut(e,t.index,ov.lastIndex,n),ov.lastIndex=t.index+n.length,n="";return {src:e,attributes:i,varyings:s,uniforms:r,resources:a}}static processUniforms(e,t,i,s){let r=[];t.forEach(e=>{if(i.hasUniform(e.name))e.ubName="ub_view";else {e.ubName="ub_mesh_ub";let t=aE.get(e.type),i=new oa(e.name,t,e.arraySize);r.push(i);}}),0===r.length&&r.push(new oa(a$,rB));let a=new on(e,r),n="";return i.uniformFormats.forEach((e,t)=>{e&&(n+=oO.getUniformShaderDeclaration(e,t,0));}),a&&(n+=oO.getUniformShaderDeclaration(a,aX,0)),{code:n,meshUniformBufferFormat:a}}static renameUniformAccess(e,t){return t.forEach(t=>{let i=`uniform.${t.name}`,s=`${t.ubName}.${t.name}`,r=RegExp(`\\b${i}\\b`,"g");e=e.replace(r,s);}),e}static mergeResources(e,t,i){let s=e.map(e=>new oM(e,i));return t.map(e=>new oM(e,i)).forEach(e=>{let t=s.find(t=>t.name===e.name);t?t.equals(e)||(i.failed=true):s.push(e);}),s}static processResources(e,t,i,s){let r=[];for(let e=0;e<t.length;e++){let i=t[e];if(i.isTexture){let s=t[e+1],a=s?.isSampler,n=i.sampleType,o=i.textureDimension;r.push(new a6(i.name,aP|aL,o,n,a,a?s.name:null)),a&&e++;}if(i.isStorageBuffer){let e="read_write"!==i.accessMode,t=new a8(i.name,aP|aL,e);t.format=i.type,r.push(t);}}let a=new a7(e,r),n="";return i.bindGroupFormats.forEach((e,t)=>{e&&(n+=oO.getTextureShaderDeclaration(e,t,1));}),{code:n+=oO.getTextureShaderDeclaration(a,aW,0),meshBindGroupFormat:a}}static getUniformShaderDeclaration(e,t,i){let s=aY[t],r=`struct_ub_${s}`,a=`struct ${r} {
`;return e.uniforms.forEach(e=>{let t=aT[e.type][0];e.count>0?(oA.hasOwnProperty(t)&&(t=oA[t]),a+=` ${e.shortName}: array<${t}, ${e.count}>,
`):a+=` ${e.shortName}: ${t},
`;}),a+=`};
@group(${t}) @binding(${i}) var<uniform> ub_${s} : ${r};
`}static getTextureShaderDeclaration(e,t,i){let s="",r=i;return e.textureFormats.forEach(e=>{let i=oE(e.textureDimension,e.sampleType);if(s+=`@group(${t}) @binding(${r}) var ${e.name}: ${i};
`,r++,e.hasSampler){let i=e.sampleType===rv?"sampler_comparison":"sampler";s+=`@group(${t}) @binding(${r}) var ${e.samplerName}: ${i};
`,r++;}}),e.storageBufferFormats.forEach(e=>{let i=e.readOnly?"read":"read_write";s+=`@group(${t}) @binding(${r}) var<storage, ${i}> ${e.name} : ${e.format};
`,r++;}),s}static processVaryings(e,t,i){let s="",r="",a="";e.forEach((e,n)=>{let o=e.match(oS);if(o){let l=o[1];i?t.set(l,n):n=t.get(l),s+=` @location(${n}) ${e},
`,i||(r+=` var<private> ${e};
`,a+=` ${l} = input.${l};
`);}}),i?s+=" @builtin(position) position : vec4f,\n":s+=" @builtin(position) position : vec4f,\n @builtin(front_facing) frontFacing : bool,\n @builtin(sample_index) sampleIndex : u32\n";let n=i?"":`
var<private> pcPosition: vec4f;
var<private> pcFrontFacing: bool;
var<private> pcSampleIndex: u32;
${r}
// function to copy inputs (varyings) to private global variables
fn _pcCopyInputs(input: FragmentInput) {
${a}
pcPosition = input.position;
pcFrontFacing = input.frontFacing;
pcSampleIndex = input.sampleIndex;
}
`;return `
struct ${i?"VertexOutput":"FragmentInput"} {
${s}
};
${n}
`}static generateFragmentOutputStruct(e,t){let i="struct FragmentOutput {\n";for(let e=0;e<t;e++)i+=` @location(${e}) color${e>0?e:""} : pcOutType${e},
`;return -1!==e.search(/\.fragDepth\s*=/)&&(i+=" @builtin(frag_depth) fragDepth : f32\n"),`${i}};
`}static floatAttributeToInt(e,t){return ({f32:t?"i32":"u32",vec2f:t?"vec2i":"vec2u",vec3f:t?"vec3i":"vec3u",vec4f:t?"vec4i":"vec4u"})[({f32:"f32","vec2<f32>":"vec2f","vec3<f32>":"vec3f","vec4<f32>":"vec4f"})[e]||e]||null}static processAttributes(e,t={},i,s,r){let a="",n="",o="";return e.forEach(e=>{let r=ob(e),l=r[0],h=r[1],c=h;if(t.hasOwnProperty(l)){let r=t[l],d=a2[r];i.set(d,l);let u=s.getVertexElement(r);if(u){let e=u.dataType;if(e!==rM&&e!==rO&&!u.normalize&&!u.asInt){let t=e===rC||e===rL||e===rD;h=oO.floatAttributeToInt(h,t);}}a+=` @location(${d}) ${l}: ${h},
`,n+=` var<private> ${e};
`,o+=` ${l} = ${c}(input.${l});
`;}}),`
struct VertexInput {
${a}
@builtin(vertex_index) vertexIndex : u32, // built-in vertex index
@builtin(instance_index) instanceIndex : u32 // built-in instance index
};
${n}
var<private> pcVertexIndex: u32;
var<private> pcInstanceIndex: u32;
fn _pcCopyInputs(input: VertexInput) {
${o}
pcVertexIndex = input.vertexIndex;
pcInstanceIndex = input.instanceIndex;
}
`}static copyInputs(e,t){let i=e.match(oy);if(!i||!i[2])return e;let s=i[2],r=i.index+i[0].length-1,a=e.slice(0,r+1);return a+`
_pcCopyInputs(${s});`+e.slice(r+1)}static cutOut(e,t,i,s){return e.substring(0,t)+s+e.substring(i)}}class oN{constructor(e){this._vertexCode=null,this._fragmentCode=null,this._computeCode=null,this.vertexEntryPoint="main",this.fragmentEntryPoint="main",this.computeEntryPoint="main",this.shader=e;let t=e.definition;t.shaderLanguage===rw?(t.cshader?(this._computeCode=t.cshader??null,this.computeUniformBufferFormats=t.computeUniformBufferFormats,this.computeBindGroupFormat=t.computeBindGroupFormat):(this.vertexEntryPoint="vertexMain",this.fragmentEntryPoint="fragmentMain",t.processingOptions?this.processWGSL():(this._vertexCode=t.vshader??null,this._fragmentCode=t.fshader??null,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat)),e.ready=true):t.processingOptions&&this.processGLSL();}destroy(e){this._vertexCode=null,this._fragmentCode=null;}createShaderModule(e,t){return this.shader.device.wgpu.createShaderModule({code:e})}getVertexShaderModule(){return this.createShaderModule(this._vertexCode,"Vertex")}getFragmentShaderModule(){return this.createShaderModule(this._fragmentCode,"Fragment")}getComputeShaderModule(){return this.createShaderModule(this._computeCode,"Compute")}processGLSL(){let e=this.shader,t=om.run(e.device,e.definition,e);this._vertexCode=this.transpile(t.vshader,"vertex",e.definition.vshader),this._fragmentCode=this.transpile(t.fshader,"fragment",e.definition.fshader),this._vertexCode&&this._fragmentCode?e.ready=true:e.failed=true,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat,e.attributes=t.attributes;}processWGSL(){let e=this.shader,t=oO.run(e.device,e.definition,e);this._vertexCode=t.vshader,this._fragmentCode=t.fshader,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat,e.attributes=t.attributes;}transpile(e,t,i){let s=this.shader.device;if(!s.glslang||!s.twgsl)return null;try{let i=s.glslang.compileGLSL(e,t);return s.twgsl.convertSpirV2WGSL(i)}catch(e){}}get vertexCode(){return this._vertexCode}get fragmentCode(){return this._fragmentCode}loseContext(){}restoreContext(e,t){}}let oF=[];oF[ts]="repeat",oF[tr]="clamp-to-edge",oF[ta]="mirror-repeat";let oB=[];oB[tK]={level:"nearest",mip:"nearest"},oB[tZ]={level:"linear",mip:"nearest"},oB[tQ]={level:"nearest",mip:"nearest"},oB[tJ]={level:"nearest",mip:"linear"},oB[t0]={level:"linear",mip:"nearest"},oB[t1]={level:"linear",mip:"linear"};let oU=e=>{};class ok{constructor(e){this.samplers=[],this.texture=e,this.format=nF[e.format],this.create(e.device);}create(e){let t,i=this.texture,s=e.wgpu,r=i.numLevels;this.desc={size:{width:i.width,height:i.height,depthOrArrayLayers:i.cubemap?6:i.array?i.arrayLength:1},format:this.format,mipLevelCount:r,sampleCount:1,dimension:i.volume?"3d":"2d",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC|(sl(i.format)?0:GPUTextureUsage.RENDER_ATTACHMENT)|(i.storage?GPUTextureUsage.STORAGE_BINDING:0)},this.gpuTexture=s.createTexture(this.desc),this.texture.format===iT&&(t={format:"depth24plus",aspect:"depth-only"}),this.view=this.createView(t);}destroy(e){}propertyChanged(e){this.samplers.length=0;}getView(e){return this.uploadImmediate(e,this.texture),this.view}createView(e){let t=e??{},i=this.desc,s=this.texture,r={format:t.format??i.format,dimension:t.dimension??(s.cubemap?"cube":s.volume?"3d":s.array?"2d-array":"2d"),aspect:t.aspect??"all",baseMipLevel:t.baseMipLevel??0,mipLevelCount:t.mipLevelCount??i.mipLevelCount,baseArrayLayer:t.baseArrayLayer??0,arrayLayerCount:t.arrayLayerCount??i.depthOrArrayLayers};return this.gpuTexture.createView(r)}getSampler(e,t){let i=this.samplers[t];if(!i){let s=this.texture,r={addressModeU:oF[s.addressU],addressModeV:oF[s.addressV],addressModeW:oF[s.addressW]};!t&&s.compareOnRead&&(t=rv),t===rv||t===rS||t===ry?(r.compare="less",r.magFilter="linear",r.minFilter="linear"):t===rg||!e.textureFloatFilterable&&(s.format===iS||s.format===ig)||this.texture.format===iT||sc(this.texture.format)?(r.magFilter="nearest",r.minFilter="nearest",r.mipmapFilter="nearest"):(r.magFilter=oB[s.magFilter].level,r.minFilter=oB[s.minFilter].level,r.mipmapFilter=oB[s.minFilter].mip);let a="linear"===r.minFilter&&"linear"===r.magFilter&&"linear"===r.mipmapFilter;r.maxAnisotropy=a?eA.clamp(Math.round(s._anisotropy),1,e.maxTextureAnisotropy):1,i=e.wgpu.createSampler(r),this.samplers[t]=i;}return i}loseContext(){}uploadImmediate(e,t){(t._needsUpload||t._needsMipmapsUpload)&&(this.uploadData(e),t._needsUpload=false,t._needsMipmapsUpload=false);}uploadData(e){let t=this.texture;if(t._levels){let i=false,s=false,r=t.numLevels;for(let a=0;a<r;a++){let r=t._levels[a];if(r)if(t.cubemap)for(let t=0;t<6;t++){let n=r[t];n?this.isExternalImage(n)?(this.uploadExternalImage(e,n,a,t),i=true):ArrayBuffer.isView(n)&&(this.uploadTypedArrayData(e,n,a,t),i=true):s=true;}else if(t._volume);else if(t.array)if(t.arrayLength===r.length)for(let s=0;s<t._arrayLength;s++){let t=r[s];this.isExternalImage(t)?(this.uploadExternalImage(e,t,a,s),i=true):ArrayBuffer.isView(t)&&(this.uploadTypedArrayData(e,t,a,s),i=true);}else s=true;else this.isExternalImage(r)?(this.uploadExternalImage(e,r,a,0),i=true):ArrayBuffer.isView(r)&&(this.uploadTypedArrayData(e,r,a,0),i=true);else s=true;}i&&s&&t.mipmaps&&!sl(t.format)&&!sc(t.format)&&e.mipmapRenderer.generate(this),t._gpuSize&&t.adjustVramSizeTracking(e._vram,-t._gpuSize),t._gpuSize=t.gpuSize,t.adjustVramSizeTracking(e._vram,t._gpuSize);}}isExternalImage(e){return "undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas}uploadExternalImage(e,t,i,s){let r={texture:this.gpuTexture,mipLevel:i,origin:[0,0,s],aspect:"all"},a={width:this.desc.size.width,height:this.desc.size.height,depthOrArrayLayers:1};e.submit(),oU(t instanceof HTMLCanvasElement&&t.getContext("2d")),e.wgpu.queue.copyExternalImageToTexture({source:t,origin:[0,0],flipY:false},r,a);}uploadTypedArrayData(e,t,i,s){let r,a,n=this.texture,o=e.wgpu,l={texture:this.gpuTexture,origin:[0,0,s],mipLevel:i},h=nt.calcLevelDimension(n.width,i),c=nt.calcLevelDimension(n.height,i);nt.calcLevelGpuSize(h,c,1,n.format);let d=so.get(n.format);if(d.size)r={offset:0,bytesPerRow:d.size*h,rowsPerImage:c},a={width:h,height:c};else if(d.blockSize){let e=e=>Math.floor((e+3)/4);r={offset:0,bytesPerRow:d.blockSize*e(h),rowsPerImage:e(c)},a={width:Math.max(4,h),height:Math.max(4,c)};}e.submit(),o.queue.writeTexture(l,t,r,a);}read(e,t,i,s,r){let a=r.mipLevel??0,n=r.face??0,o=r.data??null,l=r.immediate??false,h=this.texture,c=i*so.get(h.format).size,d=eA.roundUp(c,256),u=d*s,f=h.device,p=f.createBufferImpl(tA|tC);p.allocate(f,u);let m={texture:this.gpuTexture,mipLevel:a,origin:[e,t,n]},_={buffer:p.buffer,offset:0,bytesPerRow:d};return f.getCommandEncoder().copyTextureToBuffer(m,_,{width:i,height:s,depthOrArrayLayers:1}),f.readBuffer(p,u,null,l).then(e=>{let t=o?.constructor===Uint8Array?o:new Uint8Array(o?.buffer??s*c);for(let i=0;i<s;i++){let s=i*d,r=i*c,a=e.subarray(s,s+c);t.set(a,r);}return o??t})}}class oV extends nz{constructor(e){super(tI);}unlock(e){let t=e.device;super.unlock(t,e.storageInt32.buffer);}}class oz extends nz{constructor(e,t,i){super(tL|(i?.storage?tD:0));}unlock(e){let t=e.device;super.unlock(t,e.storage);}}let oG=/[ \t]*#(ifn?def|if|endif|else|elif|define|undef|extension|include)/g,oH=/define[ \t]+([^\n]+)\r?(?:\n|$)/g,oW=/extension[ \t]+([\w-]+)[ \t]*:[ \t]*(enable|require)/g,oX=/undef[ \t]+([^\n]+)\r?(?:\n|$)/g,oY=/(ifdef|ifndef|if)[ \t]*([^\r\n]+)\r?\n/g,oq=/(endif|else|elif)(?:[ \t]+([^\r\n]*))?\r?\n?/g,o$=/\{?[\w-]+\}?/,oj=/(!|\s)?defined\(([\w-]+)\)/,oK=/!?defined\s*\([^)]*\)/g,oZ=/!?defined\s*$/,oQ=/([a-z_]\w*)\s*(==|!=|<|<=|>|>=)\s*([\w"']+)/i,oJ=/[+\-]/g,o0=/include[ \t]+"([\w-]+)(?:\s*,\s*([\w-]+))?"/g,o1=/\{i\}/g,o2=/(pcFragColor[1-8])\b/g;class o3{static run(e,t=new Map,i={}){o3.sourceName=i.sourceName,e=(e=this.stripComments(e)).split(/\r?\n/).map(e=>e.trimEnd()).join("\n");let s=new Map,r=new Map;if(null===(e=this._preprocess(e,s,r,t,i.stripDefines)))return null;let a=new Map;return s.forEach((e,t)=>{Number.isInteger(parseFloat(e))&&!e.includes(".")&&a.set(t,e);}),e=this.stripComments(e),e=this.stripUnusedColorAttachments(e,i),e=this.RemoveEmptyLines(e),e=this.processArraySize(e,a),e=this.injectDefines(e,r)}static stripUnusedColorAttachments(e,t){if(t.stripUnusedColorAttachments){let t=new Map,i=e.match(o2);if(i?.forEach(e=>{let i=parseInt(e.charAt(e.length-1),10);t.set(i,(t.get(i)??0)+1);}),Array.from(t.values()).some(e=>1===e)){let i=e.split("\n"),s=[];for(let e=0;e<i.length;e++){let r=i[e].match(o2);if(r){let e=parseInt(r[0].charAt(r[0].length-1),10);if(e>0&&1===t.get(e))continue}s.push(i[e]);}e=s.join("\n");}}return e}static stripComments(e){return e.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")}static processArraySize(e,t){return null!==e&&t.forEach((t,i)=>{e=e.replace(RegExp(`\\[${i}\\]`,"g"),`[${t}]`);}),e}static injectDefines(e,t){if(null!==e&&t.size>0){let i=e.split("\n");t.forEach((e,t)=>{let s=RegExp(t,"g");for(let t=0;t<i.length;t++)i[t].includes("#")||(i[t]=i[t].replace(s,e));}),e=i.join("\n");}return e}static RemoveEmptyLines(e){return null!==e&&(e=(e=e.split(/\r?\n/).map(e=>""===e.trim()?"":e).join("\n")).replace(/(\n\n){3,}/g,"\n\n")),e}static _preprocess(e,t=new Map,i,s,r){let a,n=[],o=false;for(;null!==(a=oG.exec(e))&&!o;){let l=a[1];switch(l){case "define":{oH.lastIndex=a.index;let s=oH.exec(e);o||=null===s;let l=s[1];o$.lastIndex=s.index;let h=o$.exec(l)[0],c=l.substring(h.length).trim();""===c&&(c="true");let d=o3._keep(n),u=r;if(d){let r=h.startsWith("{")&&h.endsWith("}");r&&(u=true),r?i.set(h,c):t.set(h,c),u&&(e=e.substring(0,s.index-1)+e.substring(oH.lastIndex),oG.lastIndex=s.index-1);}u||(oG.lastIndex=s.index+s[0].length);break}case "undef":{oX.lastIndex=a.index;let i=oX.exec(e),s=i[1].trim();o3._keep(n)&&(t.delete(s),r&&(e=e.substring(0,i.index-1)+e.substring(oX.lastIndex),oG.lastIndex=i.index-1)),r||(oG.lastIndex=i.index+i[0].length);break}case "extension":{oW.lastIndex=a.index;let i=oW.exec(e);if(o||=null===i,i){let e=i[1];o3._keep(n)&&t.set(e,"true");}oG.lastIndex=i.index+i[0].length;break}case "ifdef":case "ifndef":case "if":{oY.lastIndex=a.index;let i=oY.exec(e),s=i[2],r=o3.evaluate(s,t);o||=r.error;let h=r.result;"ifndef"===l&&(h=!h),n.push({anyKeep:h,keep:h,start:a.index,end:oY.lastIndex}),oG.lastIndex=i.index+i[0].length;break}case "endif":case "else":case "elif":{oq.lastIndex=a.index;let i=oq.exec(e),s=n.pop();if(!s){o=true;continue}let r=s.keep?e.substring(s.end,a.index):"";e=e.substring(0,s.start)+r+e.substring(oq.lastIndex),oG.lastIndex=s.start+r.length;let l=i[1];if("else"===l||"elif"===l){let e=false;if(!s.anyKeep)if("else"===l)e=!s.keep;else {let s=o3.evaluate(i[2],t);e=s.result,o||=s.error;}n.push({anyKeep:s.anyKeep||e,keep:e,start:oG.lastIndex,end:oG.lastIndex});}break}case "include":{o0.lastIndex=a.index;let i=o0.exec(e);if(o||=null===i,!i){o=true;continue}let r=i[1].trim(),l=i[2]?.trim();if(o3._keep(n)){let a=s?.get(r);if(void 0!==a){if(a=this.stripComments(a),l){let e=parseFloat(t.get(l));if(Number.isInteger(e)){let t="";for(let i=0;i<e;i++)t+=a.replace(o1,String(i));a=t;}else o=true;}e=e.substring(0,i.index-1)+a+e.substring(o0.lastIndex),oG.lastIndex=i.index-1;}else {o=true;continue}}}}}return (n.length>0&&(o=true),o)?null:e}static _keep(e){for(let t=0;t<e.length;t++)if(!e[t].keep)return false;return true}static evaluateAtomicExpression(e,t){let i=false;e=e.trim();let s=false;if("true"===e)return {result:true,error:i};if("false"===e)return {result:false,error:i};let r=oj.exec(e);if(r){s="!"===r[1],e=r[2].trim();let a=t.has(e);return {result:s?!a:a,error:i}}let a=oQ.exec(e);if(a){let e=t.get(a[1].trim())??a[1].trim(),s=t.get(a[3].trim())??a[3].trim(),r=a[2].trim(),n=false;switch(r){case "==":n=e===s;break;case "!=":n=e!==s;break;case "<":n=e<s;break;case "<=":n=e<=s;break;case ">":n=e>s;break;case ">=":n=e>=s;break;default:i=true;}return {result:n,error:i}}return {result:t.has(e),error:i}}static processParentheses(e,t){let i=false,s=e.trim();for(;s.startsWith("(")&&s.endsWith(")");){let e=0,t=true;for(let i=0;i<s.length-1;i++)if("("===s[i])e++;else if(")"===s[i]&&0==--e){t=false;break}if(t)s=s.slice(1,-1).trim();else break}for(;;){let e=false,r=0,a=0,n=-1,o=-1,l=0;for(let t=0;t<s.length;t++)if("("===s[t]){let i=s.substring(0,t);oZ.test(i)?l++:0===l&&(++r>a&&(a=r,n=t),e=true);}else ")"===s[t]&&(l>0?l--:r>0&&(r===a&&-1!==n&&(o=t),r--));if(!e||-1===n||-1===o)break;let h=s.substring(n+1,o),{result:c,error:d}=o3.evaluate(h,t);i=i||d,s=s.substring(0,n)+(c?"true":"false")+s.substring(o+1);}return {expression:s,error:i}}static evaluate(e,t){let i=null===oJ.exec(e),s=e,r=false;if(-1!==e.replace(oK,"").indexOf("(")){let i=o3.processParentheses(e,t);s=i.expression,r=i.error;}if(r)return {result:false,error:true};for(let e of s.split("||")){let s=e.split("&&"),r=true;for(let e of s){let{result:i,error:s}=o3.evaluateAtomicExpression(e.trim(),t);if(!i||s){r=false;break}}if(r)return {result:true,error:!i}}return {result:false,error:!i}}}var o4=`
#ifndef outType_0
#define outType_0 vec4
#endif
layout(location = 0) out highp outType_0 pcFragColor0;
#if COLOR_ATTACHMENT_1
layout(location = 1) out highp outType_1 pcFragColor1;
#endif
#if COLOR_ATTACHMENT_2
layout(location = 2) out highp outType_2 pcFragColor2;
#endif
#if COLOR_ATTACHMENT_3
layout(location = 3) out highp outType_3 pcFragColor3;
#endif
#if COLOR_ATTACHMENT_4
layout(location = 4) out highp outType_4 pcFragColor4;
#endif
#if COLOR_ATTACHMENT_5
layout(location = 5) out highp outType_5 pcFragColor5;
#endif
#if COLOR_ATTACHMENT_6
layout(location = 6) out highp outType_6 pcFragColor6;
#endif
#if COLOR_ATTACHMENT_7
layout(location = 7) out highp outType_7 pcFragColor7;
#endif
#define gl_FragColor pcFragColor0
#define varying in
#define texture2D texture
#define texture2DBias texture
#define textureCube texture
#define texture2DProj textureProj
#define texture2DLod textureLod
#define texture2DProjLod textureProjLod
#define textureCubeLod textureLod
#define texture2DGrad textureGrad
#define texture2DProjGrad textureProjGrad
#define textureCubeGrad textureGrad
#define utexture2D texture
#define itexture2D texture
#define texture2DLodEXT texture2DLodEXT_is_no_longer_supported_use_texture2DLod_instead
#define texture2DProjLodEXT texture2DProjLodEXT_is_no_longer_supported_use_texture2DProjLod
#define textureCubeLodEXT textureCubeLodEXT_is_no_longer_supported_use_textureCubeLod_instead
#define texture2DGradEXT texture2DGradEXT_is_no_longer_supported_use_texture2DGrad_instead
#define texture2DProjGradEXT texture2DProjGradEXT_is_no_longer_supported_use_texture2DProjGrad_instead
#define textureCubeGradEXT textureCubeGradEXT_is_no_longer_supported_use_textureCubeGrad_instead
#define textureShadow(res, uv) textureGrad(res, uv, vec2(1, 1), vec2(1, 1))
#define SHADOWMAP_PASS(name) name
#define SHADOWMAP_ACCEPT(name) sampler2DShadow name
#define TEXTURE_PASS(name) name
#define TEXTURE_ACCEPT(name) sampler2D name
#define TEXTURE_ACCEPT_HIGHP(name) highp sampler2D name
#define GL2
`,o5=`
#define attribute in
#define varying out
#define texture2D texture
#define utexture2D texture
#define itexture2D texture
#define GL2
#define VERTEXSHADER
#define TEXTURE_PASS(name) name
#define TEXTURE_ACCEPT(name) sampler2D name
#define TEXTURE_ACCEPT_HIGHP(name) highp sampler2D name
`,o8=`
#extension GL_EXT_samplerless_texture_functions : require
#ifndef outType_0
#define outType_0 vec4
#endif
#ifndef outType_1
#define outType_1 vec4
#endif
#ifndef outType_2
#define outType_2 vec4
#endif
#ifndef outType_3
#define outType_3 vec4
#endif
#ifndef outType_4
#define outType_4 vec4
#endif
#ifndef outType_5
#define outType_5 vec4
#endif
#ifndef outType_6
#define outType_6 vec4
#endif
#ifndef outType_7
#define outType_7 vec4
#endif
layout(location = 0) out highp outType_0 pcFragColor0;
layout(location = 1) out highp outType_1 pcFragColor1;
layout(location = 2) out highp outType_2 pcFragColor2;
layout(location = 3) out highp outType_3 pcFragColor3;
layout(location = 4) out highp outType_4 pcFragColor4;
layout(location = 5) out highp outType_5 pcFragColor5;
layout(location = 6) out highp outType_6 pcFragColor6;
layout(location = 7) out highp outType_7 pcFragColor7;
#define gl_FragColor pcFragColor0
#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)
#define texture2DBias(res, uv, bias) texture(sampler2D(res, res ## _sampler), uv, bias)
#define texture2DLod(res, uv, lod) textureLod(sampler2D(res, res ## _sampler), uv, lod)
#define textureCube(res, uv) texture(samplerCube(res, res ## _sampler), uv)
#define textureCubeLod(res, uv, lod) textureLod(samplerCube(res, res ## _sampler), uv, lod)
#define textureShadow(res, uv) textureLod(sampler2DShadow(res, res ## _sampler), uv, 0.0)
#define itexture2D(res, uv) texture(isampler2D(res, res ## _sampler), uv)
#define utexture2D(res, uv) texture(usampler2D(res, res ## _sampler), uv)
#define texture2DLodEXT texture2DLodEXT_is_no_longer_supported_use_texture2DLod_instead
#define texture2DProjLodEXT texture2DProjLodEXT_is_no_longer_supported_use_texture2DProjLod
#define textureCubeLodEXT textureCubeLodEXT_is_no_longer_supported_use_textureCubeLod_instead
#define texture2DGradEXT texture2DGradEXT_is_no_longer_supported_use_texture2DGrad_instead
#define texture2DProjGradEXT texture2DProjGradEXT_is_no_longer_supported_use_texture2DProjGrad_instead
#define textureCubeGradEXT textureCubeGradEXT_is_no_longer_supported_use_textureCubeGrad_instead
#define SHADOWMAP_PASS(name) name, name ## _sampler
#define SHADOWMAP_ACCEPT(name) texture2D name, sampler name ## _sampler
#define TEXTURE_PASS(name) name, name ## _sampler
#define TEXTURE_ACCEPT(name) texture2D name, sampler name ## _sampler
#define TEXTURE_ACCEPT_HIGHP TEXTURE_ACCEPT
#define GL2
#define WEBGPU
`,o6=`
#extension GL_EXT_samplerless_texture_functions : require
#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)
#define itexture2D(res, uv) texture(isampler2D(res, res ## _sampler), uv)
#define utexture2D(res, uv) texture(usampler2D(res, res ## _sampler), uv)
#define TEXTURE_PASS(name) name, name ## _sampler
#define TEXTURE_ACCEPT(name) texture2D name, sampler name ## _sampler
#define TEXTURE_ACCEPT_HIGHP TEXTURE_ACCEPT
#define GL2
#define WEBGPU
#define VERTEXSHADER
#define gl_VertexID gl_VertexIndex
#define gl_InstanceID gl_InstanceIndex
`,o9=`
`,o7=`
#define VERTEXSHADER
`,le=`
vec2 getGrabScreenPos(vec4 clipPos) {
vec2 uv = (clipPos.xy / clipPos.w) * 0.5 + 0.5;
#ifdef WEBGPU
uv.y = 1.0 - uv.y;
#endif
return uv;
}
vec2 getImageEffectUV(vec2 uv) {
#ifdef WEBGPU
uv.y = 1.0 - uv.y;
#endif
return uv;
}
`,lt=`
fn getGrabScreenPos(clipPos: vec4<f32>) -> vec2<f32> {
var uv: vec2<f32> = (clipPos.xy / clipPos.w) * 0.5 + vec2<f32>(0.5);
uv.y = 1.0 - uv.y;
return uv;
}
fn getImageEffectUV(uv: vec2<f32>) -> vec2<f32> {
var modifiedUV: vec2<f32> = uv;
modifiedUV.y = 1.0 - modifiedUV.y;
return modifiedUV;
}
struct WrappedF32 { @size(16) element: f32 }
struct WrappedI32 { @size(16) element: i32 }
struct WrappedU32 { @size(16) element: u32 }
struct WrappedVec2F { @size(16) element: vec2f }
struct WrappedVec2I { @size(16) element: vec2i }
struct WrappedVec2U { @size(16) element: vec2u }
`;let li={vertex_position:sT,vertex_normal:sE,vertex_tangent:sA,vertex_texCoord0:sL,vertex_texCoord1:sI,vertex_texCoord2:sD,vertex_texCoord3:sR,vertex_texCoord4:sM,vertex_texCoord5:sO,vertex_texCoord6:sN,vertex_texCoord7:sF,vertex_color:sC,vertex_boneIndices:sw,vertex_boneWeights:sb};class ls{static createDefinition(e,t){let i,s,r=e=>{let t=e.fragmentOutputTypes??"vec4";return Array.isArray(t)||(t=[t]),t},a=(t,i,s,a)=>{let n=e.isWebGPU?t:i,o="";if(!s){let t=r(a);for(let i=0;i<e.maxColorAttachments;i++){o+=`#define COLOR_ATTACHMENT_${i}
`;let e=t[i]??"vec4";o+=`#define outType_${i} ${e}
`;}}return o+n},n=(t,i)=>{let s="";if(!t){let t=r(i);for(let i=0;i<e.maxColorAttachments;i++){let e=t[i]??"vec4",r=a1.get(e);s+=`alias pcOutType${i} = ${r};
`;}}return s},o=t.name??"Untitled",l=ls.getDefinesCode(e,t.vertexDefines),h=ls.getDefinesCode(e,t.fragmentDefines);return t.shaderLanguage===rw?(i=`
${n(true,t)}
${o7}
${lt}
${l}
${t.vertexCode}
`,s=`
${n(false,t)}
${o9}
${lt}
${h}
${t.fragmentCode}
`):(i=`${ls.versionCode(e)+a(o6,o5,true,t)+l+ls.precisionCode(e)}
${le}
${ls.getShaderNameCode(o)}
${t.vertexCode}`,s=`${(t.fragmentPreamble||"")+ls.versionCode(e)+a(o8,o4,false,t)+h+ls.precisionCode(e)}
${le}
${ls.getShaderNameCode(o)}
${t.fragmentCode}`),{name:o,shaderLanguage:t.shaderLanguage??rb,attributes:t.attributes,vshader:i,vincludes:t.vertexIncludes,fincludes:t.fragmentIncludes,fshader:s,useTransformFeedback:t.useTransformFeedback,meshUniformBufferFormat:t.meshUniformBufferFormat,meshBindGroupFormat:t.meshBindGroupFormat}}static getDefinesCode(e,t){let i="";return e.capsDefines.forEach((e,t)=>{i+=`#define ${t} ${e}
`;}),i+="\n",t?.forEach((e,t)=>{i+=`#define ${t} ${e}
`;}),i+="\n"}static getShaderNameCode(e){return `#define SHADER_NAME ${e}
`}static versionCode(e){return e.isWebGPU?"#version 450\n":"#version 300 es\n"}static precisionCode(e,t){t&&"highp"!==t&&"mediump"!==t&&"lowp"!==t&&(t=null),t&&("highp"===t&&"highp"!==e.maxPrecision&&(t="mediump"),"mediump"===t&&"lowp"===e.maxPrecision&&(t="lowp"));let i=t||e.precision;return `
precision ${i} float;
precision ${i} int;
precision ${i} usampler2D;
precision ${i} isampler2D;
precision ${i} sampler2DShadow;
precision ${i} samplerCubeShadow;
precision ${i} sampler2DArray;
`}static collectAttributes(e){let t={},i=0,s=e.indexOf("attribute");for(;s>=0&&(!(s>0)||"/"!==e[s-1]);){let r=false;if(s>0){let t=e.lastIndexOf("\n",s);t=-1!==t?t+1:0,e.substring(t,s).includes("#")&&(r=true);}if(!r){let r=e.indexOf(";",s),a=e.lastIndexOf(" ",r),n=e.substring(a+1,r);if(t[n]);else {let e=li[n];void 0!==e?t[n]=e:(t[n]=`ATTR${i}`,i++);}}s=e.indexOf("attribute",s+1);}return t}}let lr=0;class la{constructor(e,t){if(this.attributes=new Map,this.id=lr++,this.device=e,this.definition=t,this.name=t.name||"Untitled",this.init(),t.cshader)t.cshader=o3.run(t.cshader,t.cincludes,{sourceName:`compute shader for ${this.label}`,stripDefines:true});else {let i=t.shaderLanguage===rw;t.vshader=o3.run(t.vshader,t.vincludes,{sourceName:`vertex shader for ${this.label}`,stripDefines:i}),t.shaderLanguage===rb&&(t.attributes??=ls.collectAttributes(t.vshader));let s=e.isWebGL2&&("osx"===ee.name||"ios"===ee.name);if(t.fshader=o3.run(t.fshader,t.fincludes,{stripUnusedColorAttachments:s,stripDefines:i,sourceName:`fragment shader for ${this.label}`}),!t.vshader||!t.fshader){this.failed=true;return}}this.impl=e.createShaderImpl(this);}init(){this.ready=false,this.failed=false;}get label(){return `Shader Id ${this.id} (${this.definition.shaderLanguage===rw?"WGSL":"GLSL"}) ${this.name}`}destroy(){this.device.onDestroyShader(this),this.impl.destroy(this);}loseContext(){this.init(),this.impl.loseContext();}restoreContext(){this.impl.restoreContext(this.device,this);}}class ln{}class lo{}class ll{constructor(e,t,i){this.gpuBuffers=[],this.stagingBuffers=[],this.usedBuffers=[],this.activeBuffer=null,this.device=e,this.bufferSize=t,this.bufferAlignment=i;}destroy(){this.gpuBuffers.forEach(e=>{e.destroy(this.device);}),this.gpuBuffers=null,this.stagingBuffers.forEach(e=>{e.destroy(this.device);}),this.stagingBuffers=null,this.usedBuffers=null,this.activeBuffer=null;}alloc(e,t){if(this.activeBuffer){let e=eA.roundUp(this.activeBuffer.size,this.bufferAlignment);this.bufferSize-e<t&&this.scheduleSubmit();}if(!this.activeBuffer){let e=this.gpuBuffers.pop();e||(e=this.createBuffer(this.device,this.bufferSize,false));let t=this.stagingBuffers.pop();t||(t=this.createBuffer(this.device,this.bufferSize,true)),this.activeBuffer=new ln,this.activeBuffer.stagingBuffer=t,this.activeBuffer.gpuBuffer=e,this.activeBuffer.offset=0,this.activeBuffer.size=0;}let i=this.activeBuffer,s=eA.roundUp(i.size,this.bufferAlignment);e.gpuBuffer=i.gpuBuffer,e.offset=s,e.storage=i.stagingBuffer.alloc(s,t),i.size=s+t;}scheduleSubmit(){this.activeBuffer&&(this.usedBuffers.push(this.activeBuffer),this.activeBuffer=null);}submit(){this.scheduleSubmit();}}let lh=[];lh[rB]=function(e,t,i){e.storageFloat32[i]=t;},lh[rU]=(e,t,i)=>{let s=e.storageFloat32;s[i]=t[0],s[i+1]=t[1];},lh[rk]=(e,t,i)=>{let s=e.storageFloat32;s[i]=t[0],s[i+1]=t[1],s[i+2]=t[2];},lh[rV]=(e,t,i)=>{let s=e.storageFloat32;s[i]=t[0],s[i+1]=t[1],s[i+2]=t[2],s[i+3]=t[3];},lh[rF]=function(e,t,i){e.storageInt32[i]=t;},lh[rz]=function(e,t,i){let s=e.storageInt32;s[i]=t[0],s[i+1]=t[1];},lh[rG]=function(e,t,i){let s=e.storageInt32;s[i]=t[0],s[i+1]=t[1],s[i+2]=t[2];},lh[rH]=function(e,t,i){let s=e.storageInt32;s[i]=t[0],s[i+1]=t[1],s[i+2]=t[2],s[i+3]=t[3];},lh[rq]=(e,t,i)=>{let s=e.storageFloat32;s[i]=t[0],s[i+1]=t[1],s[i+4]=t[2],s[i+5]=t[3],s[i+8]=t[4],s[i+9]=t[5];},lh[r$]=(e,t,i)=>{let s=e.storageFloat32;s[i]=t[0],s[i+1]=t[1],s[i+2]=t[2],s[i+4]=t[3],s[i+5]=t[4],s[i+6]=t[5],s[i+8]=t[6],s[i+9]=t[7],s[i+10]=t[8];},lh[rQ]=function(e,t,i,s){let r=e.storageFloat32;for(let e=0;e<s;e++)r[i+4*e]=t[e];},lh[r2]=(e,t,i,s)=>{let r=e.storageFloat32;for(let e=0;e<s;e++)r[i+4*e]=t[2*e],r[i+4*e+1]=t[2*e+1];},lh[r3]=(e,t,i,s)=>{let r=e.storageFloat32;for(let e=0;e<s;e++)r[i+4*e]=t[3*e],r[i+4*e+1]=t[3*e+1],r[i+4*e+2]=t[3*e+2];},lh[r6]=(e,t,i,s)=>{e.storageUint32[i]=t;},lh[r9]=(e,t,i,s)=>{let r=e.storageUint32;r[i]=t[0],r[i+1]=t[1];},lh[r7]=(e,t,i,s)=>{let r=e.storageUint32;r[i]=t[0],r[i+1]=t[1],r[i+2]=t[2];},lh[ae]=(e,t,i,s)=>{let r=e.storageUint32;r[i]=t[0],r[i+1]=t[1],r[i+2]=t[2],r[i+3]=t[3];},lh[at]=function(e,t,i,s){let r=e.storageInt32;for(let e=0;e<s;e++)r[i+4*e]=t[e];},lh[as]=lh[at],lh[ai]=function(e,t,i,s){let r=e.storageUint32;for(let e=0;e<s;e++)r[i+4*e]=t[e];},lh[ar]=(e,t,i,s)=>{let r=e.storageInt32;for(let e=0;e<s;e++)r[i+4*e]=t[2*e],r[i+4*e+1]=t[2*e+1];},lh[an]=lh[ar],lh[aa]=(e,t,i,s)=>{let r=e.storageUint32;for(let e=0;e<s;e++)r[i+4*e]=t[2*e],r[i+4*e+1]=t[2*e+1];},lh[ao]=(e,t,i,s)=>{let r=e.storageInt32;for(let e=0;e<s;e++)r[i+4*e]=t[3*e],r[i+4*e+1]=t[3*e+1],r[i+4*e+2]=t[3*e+2];},lh[ah]=lh[ao],lh[al]=(e,t,i,s)=>{let r=e.storageUint32;for(let e=0;e<s;e++)r[i+4*e]=t[3*e],r[i+4*e+1]=t[3*e+1],r[i+4*e+2]=t[3*e+2];};class lc{constructor(e,t,i=true){if(this.renderVersionDirty=0,this.device=e,this.format=t,this.persistent=i,i){this.impl=e.createUniformBufferImpl(this);let i=new ArrayBuffer(t.byteSize);this.assignStorage(new Int32Array(i)),e._vram.ub+=this.format.byteSize;}else this.allocation=new lo;}destroy(){if(this.persistent){let e=this.device;this.impl.destroy(e),e._vram.ub-=this.format.byteSize;}}get offset(){return this.persistent?0:this.allocation.offset}assignStorage(e){this.storageInt32=e,this.storageUint32=new Uint32Array(e.buffer,e.byteOffset,e.byteLength/4),this.storageFloat32=new Float32Array(e.buffer,e.byteOffset,e.byteLength/4);}loseContext(){this.impl?.loseContext();}setUniform(e,t){let i=e.offset;if(null!=t){let s=lh[e.updateType];s?s(this,t,i,e.count):this.storageFloat32.set(t,i);}}set(e,t){let i=this.format.map.get(e);i&&this.setUniform(i,t);}startUpdate(e){if(!this.persistent){let t=this.allocation,i=t.gpuBuffer;this.device.dynamicBuffers.alloc(t,this.format.byteSize),this.assignStorage(t.storage),e&&(e.bindGroup=t.gpuBuffer.getBindGroup(this),e.offsets[0]=t.offset),i!==t.gpuBuffer&&(this.renderVersionDirty=this.device.renderVersion);}}endUpdate(){this.persistent?this.impl.unlock(this):(this.storageFloat32=null,this.storageInt32=null);}update(e){this.startUpdate(e);let t=this.format.uniforms;for(let e=0;e<t.length;e++){let i=t[e].scopeId.value;this.setUniform(t[e],i);}this.endUpdate();}}let ld={type:sy,base:0,baseVertex:0,count:4,indexed:false};class lu{constructor(e){let t=`
struct ub_mesh {
color : vec4f,
depth: f32
}
@group(2) @binding(0) var<uniform> ubMesh : ub_mesh;
var<private> pos : array<vec2f, 4> = array<vec2f, 4>(
vec2(-1.0, 1.0), vec2(1.0, 1.0),
vec2(-1.0, -1.0), vec2(1.0, -1.0)
);
struct VertexOutput {
@builtin(position) position : vec4f
}
@vertex
fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {
var output : VertexOutput;
output.position = vec4(pos[vertexIndex], ubMesh.depth, 1.0);
return output;
}
@fragment
fn fragmentMain() -> @location(0) vec4f {
return ubMesh.color;
}
`;this.shader=new la(e,{name:"WebGPUClearRendererShader",shaderLanguage:rw,vshader:t,fshader:t}),this.uniformBuffer=new lc(e,new on(e,[new oa("color",rV),new oa("depth",rB)]),false),this.dynamicBindGroup=new nh,this.colorData=new Float32Array(4);}destroy(){this.shader.destroy(),this.shader=null,this.uniformBuffer.destroy(),this.uniformBuffer=null;}clear(e,t,i,s){let r=(i=i||s).flags??s.flags;if(0!==r){let{uniformBuffer:a,dynamicBindGroup:n}=this;if(a.startUpdate(n),e.setBindGroup(aX,n.bindGroup,n.offsets),e.setBindGroup(aW,e.emptyBindGroup),r&tB&&(t.colorBuffer||t.impl.assignedColorTexture)){let t=i.color??s.color;this.colorData.set(t),e.setBlendState(nu.NOBLEND);}else e.setBlendState(nu.NOWRITE);if(a.set("color",this.colorData),r&tU&&t.depth){let t=i.depth??s.depth;a.set("depth",t),e.setDepthState(nm.WRITEDEPTH);}else a.set("depth",1),e.setDepthState(nm.NODEPTH);r&tk&&t.stencil,a.endUpdate(),e.setCullMode(tY),e.setShader(this.shader),e.draw(ld);}}}class lf{constructor(e){this.device=e;let t=`
var<private> pos : array<vec2f, 4> = array<vec2f, 4>(
vec2(-1.0, 1.0), vec2(1.0, 1.0),
vec2(-1.0, -1.0), vec2(1.0, -1.0)
);
struct VertexOutput {
@builtin(position) position : vec4f,
@location(0) texCoord : vec2f
};
@vertex
fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {
var output : VertexOutput;
output.texCoord = pos[vertexIndex] * vec2f(0.5, -0.5) + vec2f(0.5);
output.position = vec4f(pos[vertexIndex], 0, 1);
return output;
}
@group(0) @binding(0) var imgSampler : sampler;
@group(0) @binding(1) var img : texture_2d<f32>;
@fragment
fn fragmentMain(@location(0) texCoord : vec2f) -> @location(0) vec4f {
return textureSample(img, imgSampler, texCoord);
}
`;this.shader=new la(e,{name:"WebGPUMipmapRendererShader",shaderLanguage:rw,vshader:t,fshader:t}),this.minSampler=e.wgpu.createSampler({minFilter:"linear"});}destroy(){this.shader.destroy(),this.shader=null;}generate(e){let t=e.desc;if(t.mipLevelCount<=1||e.texture.volume)return;let i=this.device,s=i.wgpu,r=this.shader.impl,a=s.createRenderPipeline({layout:"auto",vertex:{module:r.getVertexShaderModule(),entryPoint:r.vertexEntryPoint},fragment:{module:r.getFragmentShaderModule(),entryPoint:r.fragmentEntryPoint,targets:[{format:t.format}]},primitive:{topology:"triangle-strip"}}),n=e.texture,o=n.cubemap?6:n.array?n.arrayLength:1,l=[];for(let t=0;t<o;t++)l.push(e.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:t}));let h=i.getCommandEncoder();for(let i=1;i<t.mipLevelCount;i++)for(let t=0;t<o;t++){let r=e.createView({dimension:"2d",baseMipLevel:i,mipLevelCount:1,baseArrayLayer:t}),n=h.beginRenderPass({colorAttachments:[{view:r,loadOp:"clear",storeOp:"store"}]}),o=s.createBindGroup({layout:a.getBindGroupLayout(0),entries:[{binding:0,resource:this.minSampler},{binding:1,resource:l[t]}]});n.setPipeline(a),n.setBindGroup(0,o),n.draw(4),n.end(),l[t]=r;}i.pipeline=null;}}class lp{constructor(e){this.bindGroupCache=new Map,this.device=e,this.bindGroupFormat=new a7(this.device,[new a5(aq,aP|aL)]);}getBindGroup(e){let t=e.format.byteSize,i=this.bindGroupCache.get(t);return i||((i=new nc(this.device,this.bindGroupFormat,e)).update(),this.bindGroupCache.set(t,i)),i}}class lm extends lp{constructor(e,t,i){super(e),this.buffer=null,this.mappedRange=null,this.buffer=e.wgpu.createBuffer({size:t,usage:i?GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,mappedAtCreation:i}),i&&this.onAvailable(),e._vram.ub+=t;}destroy(e){e._vram.ub-=this.buffer.size,this.buffer.destroy(),this.buffer=null;}onAvailable(){this.mappedRange=this.buffer.getMappedRange();}alloc(e,t){return new Int32Array(this.mappedRange,e,t/4)}}class l_ extends ll{createBuffer(e,t,i){return new lm(e,t,i)}submit(){super.submit();let e=this.usedBuffers.length;if(e){let t=this.device,i=this.gpuBuffers,s=t.wgpu.createCommandEncoder();for(let t=e-1;t>=0;t--){let{stagingBuffer:e,gpuBuffer:r,offset:a,size:n}=this.usedBuffers[t],o=e.buffer;o.unmap(),s.copyBufferToBuffer(o,a,r.buffer,a,n),i.push(r);}let r=s.finish();t.addCommandBuffer(r,true);for(let t=0;t<e;t++){let e=this.usedBuffers[t].stagingBuffer;this.pendingStagingBuffers.push(e);}this.usedBuffers.length=0;}}onCommandBuffersSubmitted(){let e=this.pendingStagingBuffers.length;if(e){for(let t=0;t<e;t++){let e=this.pendingStagingBuffers[t];e.buffer.mapAsync(GPUMapMode.WRITE).then(()=>{this.stagingBuffers&&(e.onAvailable(),this.stagingBuffers.push(e));});}this.pendingStagingBuffers.length=0;}}constructor(...e){super(...e),this.pendingStagingBuffers=[];}}class lg{loseContext(){this.pastFrameAllocations.clear();}set enabled(e){this._enableRequest=e;}get enabled(){return this._enableRequest}processEnableRequest(){this._enableRequest!==this._enabled&&(this._enabled=this._enableRequest,this._enabled||(this._frameTime=0));}request(e){this.pastFrameAllocations.set(e,this.frameAllocations),this.frameAllocations=[];}report(e,t){if(t){let i=this.pastFrameAllocations.get(e);if(t.length>0&&(this._frameTime=t.reduce((e,t)=>e+t,0)),eS.get(k))for(let e=0;e<i.length;++e)i[e],t[e];}this.pastFrameAllocations.delete(e);}getSlot(e){let t=this.frameAllocations.length;return this.frameAllocations.push(e),t}get slotCount(){return this.frameAllocations.length}constructor(){this.frameAllocations=[],this.pastFrameAllocations=new Map,this._enabled=false,this._enableRequest=false,this._frameTime=0;}}class lv{constructor(e,t,i){this.stagingBuffers=[],this.activeStagingBuffer=null,this.device=e,this.capacity=i,this.bytesPerSlot=t?8:4;let s=e.wgpu;this.querySet=s.createQuerySet({type:t?"timestamp":"occlusion",count:i}),this.queryBuffer=s.createBuffer({size:this.bytesPerSlot*i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST});}destroy(){this.querySet?.destroy(),this.querySet=null,this.queryBuffer?.destroy(),this.queryBuffer=null,this.activeStagingBuffer=null,this.stagingBuffers.forEach(e=>{e.destroy();}),this.stagingBuffers=null;}getStagingBuffer(){let e=this.stagingBuffers.pop();return e||(e=this.device.wgpu.createBuffer({size:this.queryBuffer.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})),e}resolve(e){let t=this.device.getCommandEncoder();t.resolveQuerySet(this.querySet,0,e,this.queryBuffer,0);let i=this.getStagingBuffer();this.activeStagingBuffer=i,t.copyBufferToBuffer(this.queryBuffer,0,i,0,this.bytesPerSlot*e);}request(e,t){let i=this.activeStagingBuffer;return this.activeStagingBuffer=null,i.mapAsync(GPUMapMode.READ).then(()=>{let s=new BigInt64Array(i.getMappedRange()),r=[];for(let t=0;t<e;t++)r.push(1e-6*Number(s[2*t+1]-s[2*t]));return i.unmap(),this.stagingBuffers?.push(i),{renderVersion:t,timings:r}})}}class lS extends lg{constructor(e){super(),this.device=e,this.timestampQueriesSet=e.supportsTimestampQuery?new lv(e,true,512):null;}destroy(){this.timestampQueriesSet?.destroy(),this.timestampQueriesSet=null;}frameStart(){this.processEnableRequest();}frameEnd(){this._enabled&&this.timestampQueriesSet?.resolve(2*this.slotCount);}request(){if(this._enabled){let e=this.device.renderVersion;this.timestampQueriesSet?.request(this.slotCount,e).then(e=>{this.report(e.renderVersion,e.timings);}),super.request(e);}}}class ly{constructor(e){this.pipelineCache=new Map,this.device=e;let t=`
var<private> pos : array<vec2f, 4> = array<vec2f, 4>(
vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0)
);
struct VertexOutput {
@builtin(position) position : vec4f,
};
@vertex
fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {
var output : VertexOutput;
output.position = vec4f(pos[vertexIndex], 0, 1);
return output;
}
@group(0) @binding(0) var img : texture_depth_multisampled_2d;
@fragment
fn fragmentMain(@builtin(position) fragColor: vec4f) -> @location(0) vec4f {
// load th depth value from sample index 0
var depth = textureLoad(img, vec2i(fragColor.xy), 0u);
return vec4f(depth, 0.0, 0.0, 0.0);
}
`;this.shader=new la(e,{name:"WebGPUResolverDepthShader",shaderLanguage:rw,vshader:t,fshader:t});}destroy(){this.shader.destroy(),this.shader=null,this.pipelineCache=null;}getPipeline(e){let t=this.pipelineCache.get(e);return t||(t=this.createPipeline(e),this.pipelineCache.set(e,t)),t}createPipeline(e){let t=this.shader.impl;return this.device.wgpu.createRenderPipeline({layout:"auto",vertex:{module:t.getVertexShaderModule(),entryPoint:t.vertexEntryPoint},fragment:{module:t.getFragmentShaderModule(),entryPoint:t.fragmentEntryPoint,targets:[{format:e}]},primitive:{topology:"triangle-strip"}})}resolveDepth(e,t,i){let s=this.device,r=s.wgpu,a=this.getPipeline(i.format),n=t.depthOrArrayLayers;for(let s=0;s<n;s++){let n=t.createView({dimension:"2d",aspect:"depth-only",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:s}),o=i.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:s}),l=e.beginRenderPass({colorAttachments:[{view:o,loadOp:"clear",storeOp:"store"}]}),h=r.createBindGroup({layout:a.getBindGroupLayout(0),entries:[{binding:0,resource:n}]});l.setPipeline(a),l.setBindGroup(0,h),l.draw(4),l.end();}s.pipeline=null;}}class lx{constructor(e){this.uniformBuffers=[],this.bindGroup=null,this.compute=e;let{device:t,shader:i}=e,{computeBindGroupFormat:s,computeUniformBufferFormats:r}=i.impl;if(this.bindGroup=new nc(t,s),r){for(let e in r)if(r.hasOwnProperty(e)){let i=new lc(t,r[e],true);this.uniformBuffers.push(i),this.bindGroup.setUniformBuffer(e,i);}}this.pipeline=t.computePipeline.get(i,s);}destroy(){this.uniformBuffers.forEach(e=>e.destroy()),this.uniformBuffers.length=0,this.bindGroup.destroy(),this.bindGroup=null;}updateBindGroup(){let{bindGroup:e}=this;e.updateUniformBuffers(),e.update();}dispatch(e,t,i){let s=this.compute.device;s.setBindGroup(0,this.bindGroup);let r=s.passEncoder;r.setPipeline(this.pipeline),r.dispatchWorkgroups(e,t,i);}}let lT=0;class lE{constructor(e,t,i=0){this.id=lT++,this.device=e,this.byteSize=t,this.bufferUsage=i,this.impl=e.createBufferImpl(tD|i),this.impl.allocate(e,t),this.device.buffers.push(this),this.adjustVramSizeTracking(e._vram,this.byteSize);}destroy(){let e=this.device,t=e.buffers.indexOf(this);-1!==t&&e.buffers.splice(t,1),this.adjustVramSizeTracking(e._vram,-this.byteSize),this.impl.destroy(e);}adjustVramSizeTracking(e,t){e.sb+=t;}read(e=0,t=this.byteSize,i=null,s=false){return this.impl.read(this.device,e,t,i,s)}write(e=0,t,i=0,s){this.impl.write(this.device,e,t,i,s);}clear(e=0,t=this.byteSize){this.impl.clear(this.device,e,t);}}let lA=new Map;class lb extends nD{constructor(e,t={}){super(e,t),this.renderPipeline=new n2(this),this.computePipeline=new n3(this),this._indirectDrawBuffer=null,this._indirectDrawBufferCount=0,this._indirectDrawNextIndex=0,this.pipeline=null,this.bindGroupFormats=[],this.commandEncoder=null,this.commandBuffers=[],this.glslang=null,this.twgsl=null,(t=this.initOptions).alpha=t.alpha??true,this.backBufferAntialias=t.antialias??false,this.isWebGPU=true,this._deviceType=aw,this.scope.resolve(a$).setValue(0);}destroy(){this.clearRenderer.destroy(),this.clearRenderer=null,this.mipmapRenderer.destroy(),this.mipmapRenderer=null,this.resolver.destroy(),this.resolver=null,super.destroy();}initDeviceCaps(){let e=this.wgpu?.limits;this.limits=e,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=e.maxTextureDimension2D,this.maxCubeMapSize=e.maxTextureDimension2D,this.maxVolumeSize=e.maxTextureDimension3D,this.maxColorAttachments=e.maxColorAttachments,this.maxPixelRatio=1,this.maxAnisotropy=16,this.fragmentUniformsCount=e.maxUniformBufferBindingSize/16,this.vertexUniformsCount=e.maxUniformBufferBindingSize/16,this.supportsUniformBuffers=true,this.supportsAreaLights=true,this.supportsGpuParticles=true,this.supportsCompute=true,this.textureFloatRenderable=true,this.textureHalfFloatRenderable=true,this.supportsImageBitmap=true,this.samples=this.backBufferAntialias?4:1;let t=window.navigator.gpu.wgslLanguageFeatures;this.supportsStorageTextureRead=t?.has("readonly_and_readwrite_storage_textures"),this.initCapsDefines();}async initWebGpu(e,t){if(!window.navigator.gpu)throw Error("Unable to retrieve GPU. Ensure you are using a browser that supports WebGPU rendering.");if(e&&t){let i=e=>new URL(e,window.location.href).toString(),s=await Promise.all([import(`${i(t)}`).then(e=>twgsl(t.replace(".js",".wasm"))),import(`${i(e)}`).then(e=>e.default())]);this.twgsl=s[0],this.glslang=s[1];}return this.createDevice()}async createDevice(){let e={powerPreference:"default"!==this.initOptions.powerPreference?this.initOptions.powerPreference:void 0,xrCompatible:this.initOptions.xrCompatible};this.gpuAdapter=await window.navigator.gpu.requestAdapter(e);let t=[],i=e=>{let i=this.gpuAdapter.features.has(e);return i&&t.push(e),i};this.textureFloatFilterable=i("float32-filterable"),this.textureFloatBlendable=i("float32-blendable"),this.extCompressedTextureS3TC=i("texture-compression-bc"),this.extCompressedTextureETC=i("texture-compression-etc2"),this.extCompressedTextureASTC=i("texture-compression-astc"),this.supportsTimestampQuery=i("timestamp-query"),this.supportsDepthClip=i("depth-clip-control"),this.supportsDepth32Stencil=i("depth32float-stencil8"),this.supportsIndirectFirstInstance=i("indirect-first-instance"),this.supportsShaderF16=i("shader-f16"),this.supportsStorageRGBA8=i("bgra8unorm-storage"),this.textureRG11B10Renderable=i("rg11b10ufloat-renderable"),this.supportsClipDistances=i("clip-distances");let s=this.gpuAdapter?.limits,r={};if(s)for(let e in s)"minSubgroupSize"!==e&&"maxSubgroupSize"!==e&&(r[e]=s[e]);this.wgpu=await this.gpuAdapter.requestDevice({requiredFeatures:t,requiredLimits:r,defaultQueue:{label:"Default Queue"}}),this.wgpu.lost?.then(this.handleDeviceLost.bind(this)),this.initDeviceCaps(),this.gpuContext=this.canvas.getContext("webgpu");let a="standard",n=window.navigator.gpu.getPreferredCanvasFormat(),o=this.initOptions.displayFormat;if(this.backBufferFormat="rgba8unorm"===n?o===aR?ib:id:o===aR?st:iF,this.backBufferViewFormat=o===aR?`${n}-srgb`:n,o===aM&&this.textureFloatFilterable){let e=window.matchMedia("(dynamic-range: high)");e?.matches&&(this.backBufferFormat=ig,this.backBufferViewFormat="rgba16float",n="rgba16float",this.isHdr=true,a="extended");}return this.canvasConfig={device:this.wgpu,colorSpace:"srgb",alphaMode:this.initOptions.alpha?"premultiplied":"opaque",format:n,toneMapping:{mode:a},usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST,viewFormats:o===aR?[this.backBufferViewFormat]:[]},this.gpuContext?.configure(this.canvasConfig),this.createBackbuffer(),this.clearRenderer=new lu(this),this.mipmapRenderer=new lf(this),this.resolver=new ly(this),this.postInit(),this}async handleDeviceLost(e){"destroyed"!==e.reason&&(super.loseContext(),await this.createDevice(),super.restoreContext());}postInit(){super.postInit(),this.initializeRenderState(),this.setupPassEncoderDefaults(),this.gpuProfiler=new lS(this),this.dynamicBuffers=new l_(this,102400,this.limits.minUniformBufferOffsetAlignment),this.emptyBindGroup=new nc(this,new a7(this,[])),this.emptyBindGroup.update();}createBackbuffer(){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new nM({name:"WebgpuFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.isBackbuffer=true;}frameStart(){super.frameStart(),this.gpuProfiler.frameStart(),this.submit();let e=this.gpuContext?.getCurrentTexture?.()??this.externalBackbuffer?.impl.gpuTexture;(this.backBufferSize.x!==e.width||this.backBufferSize.y!==e.height)&&(this.backBufferSize.set(e.width,e.height),this.backBuffer.destroy(),this.backBuffer=null,this.createBackbuffer());let t=this.backBuffer,i=t.impl;i.setColorAttachment(0,void 0,this.backBufferViewFormat),this.initRenderTarget(t),i.assignColorTexture(this,e);}frameEnd(){super.frameEnd(),this.gpuProfiler.frameEnd(),this.submit(),this.contextLost||this.gpuProfiler.request(),this._indirectDrawNextIndex=0;}createBufferImpl(e){return new nz(e)}createUniformBufferImpl(e){return new oV(e)}createVertexBufferImpl(e,t,i){return new oz(e,t,i)}createIndexBufferImpl(e,t){return new nG(e,t)}createShaderImpl(e){return new oN(e)}createTextureImpl(e){return new ok(e)}createRenderTargetImpl(e){return new os(e)}createBindGroupFormatImpl(e){return new nV(e)}createBindGroupImpl(e){return new nO}createComputeImpl(e){return new lx(e)}get indirectDrawBuffer(){return this.allocateIndirectDrawBuffer(),this._indirectDrawBuffer}allocateIndirectDrawBuffer(){0===this._indirectDrawNextIndex&&this._indirectDrawBufferCount<this.maxIndirectDrawCount&&(this._indirectDrawBuffer?.destroy(),this._indirectDrawBuffer=null),null===this._indirectDrawBuffer&&(this._indirectDrawBuffer=new lE(this,4*this.maxIndirectDrawCount,tR|tC),this._indirectDrawBufferCount=this.maxIndirectDrawCount);}getIndirectDrawSlot(){this.allocateIndirectDrawBuffer();let e=this._indirectDrawNextIndex;return this._indirectDrawNextIndex++,e}setBindGroup(e,t,i){this.passEncoder&&(this.passEncoder.setBindGroup(e,t.impl.bindGroup,i??t.uniformBufferOffsets),this.bindGroupFormats[e]=t.format.impl);}submitVertexBuffer(e,t){let{interleaved:i,elements:s}=e.format,r=s.length,a=e.impl.buffer;if(i)return this.passEncoder.setVertexBuffer(t,a),1;for(let e=0;e<r;e++)this.passEncoder.setVertexBuffer(t+e,a,s[e].offset);return r}validateVBLocations(e,t){let i=e=>{let{elements:t}=e.format;for(let e=0;e<t.length;e++){let i=t[e].name,s=a2[i];lA.has(s),lA.set(s,i);}};i(e),i(t),lA.clear();}draw(e,t,i=1,s,r=true,a=true){if(this.shader.ready&&!this.shader.failed){let a=this.passEncoder,n=this.pipeline,o=this.vertexBuffers[0],l=this.vertexBuffers[1];if(r){if(o){let e=this.submitVertexBuffer(o,0);l&&this.submitVertexBuffer(l,e);}n=this.renderPipeline.get(e,o?.format,l?.format,t?.format,this.shader,this.renderTarget,this.bindGroupFormats,this.blendState,this.depthState,this.cullMode,this.stencilEnabled,this.stencilFront,this.stencilBack),this.pipeline!==n&&(this.pipeline=n,a.setPipeline(n));}if(t&&a.setIndexBuffer(t.impl.buffer,t.impl.format),void 0!==s){let e=20*s,i=this.indirectDrawBuffer.impl.buffer;t?a.drawIndexedIndirect(i,e):a.drawIndirect(i,e);}else t?a.drawIndexed(e.count,i,e.base,e.baseVertex??0,0):a.draw(e.count,i,e.base,0);}a&&(this.clearVertexBuffer(),this.pipeline=null);}setShader(e,t=false){e!==this.shader&&(this.shader=e);}setBlendState(e){this.blendState.copy(e);}setDepthState(e){this.depthState.copy(e);}setStencilState(e,t){if(e||t){this.stencilEnabled=true,this.stencilFront.copy(e??nI.DEFAULT),this.stencilBack.copy(t??nI.DEFAULT);let i=this.stencilFront.ref;this.stencilRef!==i&&(this.stencilRef=i,this.passEncoder.setStencilReference(i));}else this.stencilEnabled=false;}setBlendColor(e,t,i,s){let r=this.blendColor;(e!==r.r||t!==r.g||i!==r.b||s!==r.a)&&(r.set(e,t,i,s),this.passEncoder.setBlendConstant(r));}setCullMode(e){this.cullMode=e;}setAlphaToCoverage(e){}initializeContextCaches(){super.initializeContextCaches();}setupPassEncoderDefaults(){this.pipeline=null,this.stencilRef=0,this.blendColor.set(0,0,0,0);}_uploadDirtyTextures(){this.textures.forEach(e=>{(e._needsUpload||e._needsMipmaps)&&e.upload();});}setupTimeStampWrites(e,t){if(this.gpuProfiler._enabled&&this.gpuProfiler.timestampQueriesSet){let i=this.gpuProfiler.getSlot(t);(e=e??{}).timestampWrites={querySet:this.gpuProfiler.timestampQueriesSet.querySet,beginningOfPassWriteIndex:2*i,endOfPassWriteIndex:2*i+1};}return e}startRenderPass(e){this._uploadDirtyTextures();let t=e.renderTarget||this.backBuffer;this.renderTarget=t;let i=t.impl;t!==this.backBuffer&&this.initRenderTarget(t),i.setupForRenderPass(e,t);let s=i.renderPassDescriptor;this.setupTimeStampWrites(s,e.name);let r=this.getCommandEncoder();this.passEncoder=r.beginRenderPass(s),this.passEncoder.label=`${e.name}-PassEncoder RT:${t.name}`,this.setupPassEncoderDefaults();let{width:a,height:n}=t;this.setViewport(0,0,a,n),this.setScissor(0,0,a,n),this.insideRenderPass=true;}endRenderPass(e){this.passEncoder.end(),this.passEncoder=null,this.insideRenderPass=false,this.bindGroupFormats.length=0;let t=this.renderTarget;if(t&&t.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&t.autoResolve){let e=t.impl.depthAttachment,i=t.depthBuffer.impl.gpuTexture;e&&i&&this.resolver.resolveDepth(this.commandEncoder,e.multisampledDepthBuffer,i);}for(let t=0;t<e.colorArrayOps.length;t++)e.colorArrayOps[t].genMipmaps&&this.mipmapRenderer.generate(e.renderTarget._colorBuffers[t].impl);}startComputePass(e){this.pipeline=null;let t=this.setupTimeStampWrites(void 0,e),i=this.getCommandEncoder();this.passEncoder=i.beginComputePass(t),this.insideRenderPass=true;}endComputePass(){this.passEncoder.end(),this.passEncoder=null,this.insideRenderPass=false,this.bindGroupFormats.length=0;}computeDispatch(e,t="Unnamed"){this.startComputePass(t);for(let t=0;t<e.length;t++){let i=e[t];i.applyParameters(),i.impl.updateBindGroup();}for(let t=0;t<e.length;t++){let i=e[t];i.impl.dispatch(i.countX,i.countY,i.countZ);}this.endComputePass();}getCommandEncoder(){let e=this.commandEncoder;return e||(e=this.wgpu.createCommandEncoder(),this.commandEncoder=e),e}endCommandEncoder(){let{commandEncoder:e}=this;if(e){let t=e.finish();this.addCommandBuffer(t),this.commandEncoder=null;}}addCommandBuffer(e,t=false){t?this.commandBuffers.unshift(e):this.commandBuffers.push(e);}submit(){this.endCommandEncoder(),this.commandBuffers.length>0&&(this.dynamicBuffers.submit(),this.wgpu.queue.submit(this.commandBuffers),this.commandBuffers.length=0,this.dynamicBuffers.onCommandBuffersSubmitted());}clear(e){e.flags&&this.clearRenderer.clear(this,this.renderTarget,e,this.defaultClearOptions);}setViewport(e,t,i,s){this.passEncoder&&(this.renderTarget.flipY||(t=this.renderTarget.height-t-s),this.vx=e,this.vy=t,this.vw=i,this.vh=s,this.passEncoder.setViewport(e,t,i,s,0,1));}setScissor(e,t,i,s){this.passEncoder&&(this.renderTarget.flipY||(t=this.renderTarget.height-t-s),this.sx=e,this.sy=t,this.sw=i,this.sh=s,this.passEncoder.setScissorRect(e,t,i,s));}clearStorageBuffer(e,t=0,i=e.byteSize){this.getCommandEncoder().clearBuffer(e.buffer,t,i);}readStorageBuffer(e,t=0,i=e.byteSize-t,s=null,r=false){let a=this.createBufferImpl(tA|tC);a.allocate(this,i);let n=a.buffer;return this.getCommandEncoder().copyBufferToBuffer(e.buffer,t,n,0,i),this.readBuffer(a,i,s,r)}readBuffer(e,t,i=null,s=false){let r=e.buffer;return new Promise((a,n)=>{let o=()=>{r?.mapAsync(GPUMapMode.READ).then(()=>{i??=new Uint8Array(t);let s=r.getMappedRange(0,t),n=i.constructor;i.set(new n(s)),r.unmap(),e.destroy(this),a(i);});};s?(this.submit(),o()):setTimeout(()=>{o();});})}writeStorageBuffer(e,t=0,i,s=0,r){this.wgpu.queue.writeBuffer(e.buffer,t,i,s,r);}copyRenderTarget(e,t,i,s){let r={width:e?e.width:t.width,height:e?e.height:t.height,depthOrArrayLayers:1},a=this.getCommandEncoder();if(i){let i={texture:e?e.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:0},s={texture:t?t.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:0};a.copyTextureToTexture(i,s,r);}if(s){let i=(e||this.renderTarget).impl.depthAttachment.depthTexture;if(e.samples>1){let e=t.colorBuffer.impl.gpuTexture;this.resolver.resolveDepth(a,i,e);}else {let e=t?t.depthBuffer.impl.gpuTexture:this.renderTarget.impl.depthAttachment.depthTexture;a.copyTextureToTexture({texture:i,mipLevel:0},{texture:e,mipLevel:0},r);}}return true}}class lw{destroy(e){this.bufferId&&(e.gl.deleteBuffer(this.bufferId),this.bufferId=null);}get initialized(){return !!this.bufferId}loseContext(){this.bufferId=null;}unlock(e,t,i,s){let r=e.gl;if(this.bufferId)r.bindBuffer(i,this.bufferId),r.bufferSubData(i,0,s);else {let e;switch(t){case tM:e=r.STATIC_DRAW;break;case tO:e=r.DYNAMIC_DRAW;break;case tN:e=r.STREAM_DRAW;break;case tF:e=r.DYNAMIC_COPY;}this.bufferId=r.createBuffer(),r.bindBuffer(i,this.bufferId),r.bufferData(i,s,e);}}constructor(){this.bufferId=null;}}class lC extends lw{destroy(e){super.destroy(e),e.unbindVertexArray();}loseContext(){super.loseContext(),this.vao=null;}unlock(e){let t=e.device;super.unlock(t,e.usage,t.gl.ARRAY_BUFFER,e.storage);}constructor(...e){super(...e),this.vao=null;}}class lP extends lw{constructor(e){super();let t=e.device.gl,i=e.format;i===ie?this.glFormat=t.UNSIGNED_BYTE:i===it?this.glFormat=t.UNSIGNED_SHORT:i===ii&&(this.glFormat=t.UNSIGNED_INT);}unlock(e){let t=e.device;super.unlock(t,e.usage,t.gl.ELEMENT_ARRAY_BUFFER,e.storage);}}class lL{constructor(e,t,i,s){if(this.locationId=s,this.scopeId=e.scope.resolve(t),this.version=new n_,"[0]"===t.substring(t.length-3))switch(i){case rB:i=rQ;break;case rF:i=at;break;case r6:i=ai;break;case rN:i=as;break;case rU:i=r2;break;case rz:i=ar;break;case r9:i=aa;break;case rW:i=an;break;case rk:i=r3;break;case rG:i=ao;break;case r7:i=al;break;case rX:i=ah;break;case rV:i=r4;break;case rH:i=ac;break;case ae:i=ad;break;case rY:i=au;}this.dataType=i,this.value=[null,null,null,null],this.array=[];}}let lI=new Set(["gl_VertexID","gl_InstanceID","gl_DrawID","gl_BaseVertex","gl_BaseInstance"]);class lD{destroy(e){this.map.forEach(t=>{e.gl.deleteShader(t);});}loseContext(e){this.map.clear();}constructor(){this.map=new Map;}}let lR=new ne,lM=new ne;class lO{constructor(e){this.compileDuration=0,this.init(),this.compile(e.device,e),this.link(e.device,e),e.device.shaders.push(e);}destroy(e){this.glProgram&&(e.device.gl.deleteProgram(this.glProgram),this.glProgram=null);}init(){this.uniforms=[],this.samplers=[],this.attributes=[],this.glProgram=null,this.glVertexShader=null,this.glFragmentShader=null;}loseContext(){this.init();}restoreContext(e,t){this.compile(e,t),this.link(e,t);}compile(e,t){let i=t.definition;this.glVertexShader=this._compileShaderSource(e,i.vshader,true),this.glFragmentShader=this._compileShaderSource(e,i.fshader,false);}link(e,t){if(this.glProgram)return;let i=e.gl;if(i.isContextLost())return;let s=i.createProgram();this.glProgram=s,i.attachShader(s,this.glVertexShader),i.attachShader(s,this.glFragmentShader);let r=t.definition,a=r.attributes;if(r.useTransformFeedback){let e=[];for(let t in a)a.hasOwnProperty(t)&&e.push(`out_${t}`);i.transformFeedbackVaryings(s,e,i.INTERLEAVED_ATTRIBS);}for(let e in a)if(a.hasOwnProperty(e)){let t=a2[a[e]];i.bindAttribLocation(s,t,e);}i.linkProgram(s);}_compileShaderSource(e,t,i){let s=e.gl;if(s.isContextLost())return null;let r=(i?lR:lM).get(e,()=>new lD),a=r.map.get(t);return a||(a=s.createShader(i?s.VERTEX_SHADER:s.FRAGMENT_SHADER),s.shaderSource(a,t),s.compileShader(a),r.map.set(t,a)),a}finalize(e,t){let i=e.gl;if(i.isContextLost())return true;let s=this.glProgram,r=t.definition;if(!i.getProgramParameter(s,i.LINK_STATUS))return !!this._isCompiled(e,t,this.glVertexShader,r.vshader,"vertex")&&!!this._isCompiled(e,t,this.glFragmentShader,r.fshader,"fragment")&&(i.getProgramInfoLog(s),false);let a=i.getProgramParameter(s,i.ACTIVE_ATTRIBUTES);t.attributes.clear();for(let e=0;e<a;e++){let a=i.getActiveAttrib(s,e),n=i.getAttribLocation(s,a.name);lI.has(a.name)||(void 0===r.attributes[a.name]?t.failed=true:t.attributes.set(n,a.name));}let n=e._samplerTypes,o=i.getProgramParameter(s,i.ACTIVE_UNIFORMS);for(let t=0;t<o;t++){let r=i.getActiveUniform(s,t),a=i.getUniformLocation(s,r.name),o=new lL(e,r.name,e.pcUniformType[r.type],a);n.has(r.type)?this.samplers.push(o):this.uniforms.push(o);}return t.ready=true,true}_isCompiled(e,t,i,s,r){let a=e.gl;if(!a.getShaderParameter(i,a.COMPILE_STATUS)){let e=a.getShaderInfoLog(i),[t,r]=this._processError(s,e);return false}return true}isLinked(e){let{extParallelShaderCompile:t}=e;return !t||e.gl.getProgramParameter(this.glProgram,t.COMPLETION_STATUS_KHR)}_processError(e,t){let i={},s="";if(e){let r=e.split("\n"),a=0,n=r.length;if(t&&t.startsWith("ERROR:")){let e=t.match(/^ERROR:\s(\d+):(\d+):\s*(.+)/);e&&(i.message=e[3],i.line=parseInt(e[2],10),a=Math.max(0,i.line-6),n=Math.min(r.length,i.line+5));}for(let e=a;e<n;e++){let t=e+1===i.line?"> ":" ";s+=`${t}${e+1}: ${r[e]}
`;}i.source=e;}return [s,i]}}function lN(e,t){let i=e.width,s=e.height;if(i>t||s>t){let r=t/Math.max(i,s),a=Math.floor(i*r),n=Math.floor(s*r),o=document.createElement("canvas");return o.width=a,o.height=n,o.getContext("2d").drawImage(e,0,0,i,s,0,0,a,n),o}return e}class lF{constructor(e){this._glTexture=null,this.dirtyParameterFlags=0,this.texture=e;}destroy(e){if(this._glTexture){for(let t=0;t<e.textureUnits.length;t++){let i=e.textureUnits[t];for(let e=0;e<i.length;e++)i[e]===this._glTexture&&(i[e]=null);}e.gl.deleteTexture(this._glTexture),this._glTexture=null;}}loseContext(){this._glTexture=null;}propertyChanged(e){this.dirtyParameterFlags|=e;}initialize(e,t){let i=e.gl;switch(this._glTexture=i.createTexture(),this._glTarget=t._cubemap?i.TEXTURE_CUBE_MAP:t._volume?i.TEXTURE_3D:t.array?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D,t._format){case is:this._glFormat=i.ALPHA,this._glInternalFormat=i.ALPHA,this._glPixelType=i.UNSIGNED_BYTE;break;case ir:this._glFormat=i.LUMINANCE,this._glInternalFormat=i.LUMINANCE,this._glPixelType=i.UNSIGNED_BYTE;break;case ia:this._glFormat=i.LUMINANCE_ALPHA,this._glInternalFormat=i.LUMINANCE_ALPHA,this._glPixelType=i.UNSIGNED_BYTE;break;case i3:this._glFormat=i.RED,this._glInternalFormat=i.R8,this._glPixelType=i.UNSIGNED_BYTE;break;case i4:this._glFormat=i.RG,this._glInternalFormat=i.RG8,this._glPixelType=i.UNSIGNED_BYTE;break;case io:this._glFormat=i.RGB,this._glInternalFormat=i.RGB565,this._glPixelType=i.UNSIGNED_SHORT_5_6_5;break;case il:this._glFormat=i.RGBA,this._glInternalFormat=i.RGB5_A1,this._glPixelType=i.UNSIGNED_SHORT_5_5_5_1;break;case ih:this._glFormat=i.RGBA,this._glInternalFormat=i.RGBA4,this._glPixelType=i.UNSIGNED_SHORT_4_4_4_4;break;case ic:this._glFormat=i.RGB,this._glInternalFormat=i.RGB8,this._glPixelType=i.UNSIGNED_BYTE;break;case id:this._glFormat=i.RGBA,this._glInternalFormat=i.RGBA8,this._glPixelType=i.UNSIGNED_BYTE;break;case iF:case st:break;case iu:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;break;case ip:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case im:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;case iw:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureETC1.COMPRESSED_RGB_ETC1_WEBGL;break;case iL:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;break;case iI:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;break;case iD:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;break;case iR:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;break;case iC:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_RGB8_ETC2;break;case iP:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_RGBA8_ETC2_EAC;break;case iM:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureASTC.COMPRESSED_RGBA_ASTC_4x4_KHR;break;case iO:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureATC.COMPRESSED_RGB_ATC_WEBGL;break;case iN:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureATC.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;break;case si:this._glFormat=i.RGB,this._glInternalFormat=e.extTextureCompressionBPTC.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;break;case ss:this._glFormat=i.RGB,this._glInternalFormat=e.extTextureCompressionBPTC.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;break;case sr:this._glFormat=i.RGBA,this._glInternalFormat=e.extTextureCompressionBPTC.COMPRESSED_RGBA_BPTC_UNORM_EXT;break;case i5:this._glFormat=i.SRGB,this._glInternalFormat=e.extCompressedTextureS3TC_SRGB.COMPRESSED_SRGB_S3TC_DXT1_EXT;break;case i8:this._glFormat=i.SRGB_ALPHA,this._glInternalFormat=e.extCompressedTextureS3TC_SRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;break;case i6:this._glFormat=i.SRGB_ALPHA,this._glInternalFormat=e.extCompressedTextureS3TC_SRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;break;case i9:this._glFormat=i.SRGB,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_SRGB8_ETC2;break;case i7:this._glFormat=i.SRGB_ALPHA,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;break;case se:this._glFormat=i.SRGB_ALPHA,this._glInternalFormat=e.extCompressedTextureASTC.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case sa:this._glFormat=i.RGBA,this._glInternalFormat=e.extTextureCompressionBPTC.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case i1:this._glFormat=i.RED,this._glInternalFormat=i.R16F,this._glPixelType=i.HALF_FLOAT;break;case i2:this._glFormat=i.RG,this._glInternalFormat=i.RG16F,this._glPixelType=i.HALF_FLOAT;break;case i_:this._glFormat=i.RGB,this._glInternalFormat=i.RGB16F,this._glPixelType=i.HALF_FLOAT;break;case ig:this._glFormat=i.RGBA,this._glInternalFormat=i.RGBA16F,this._glPixelType=i.HALF_FLOAT;break;case iv:this._glFormat=i.RGB,this._glInternalFormat=i.RGB32F,this._glPixelType=i.FLOAT;break;case iS:this._glFormat=i.RGBA,this._glInternalFormat=i.RGBA32F,this._glPixelType=i.FLOAT;break;case iy:this._glFormat=i.RED,this._glInternalFormat=i.R32F,this._glPixelType=i.FLOAT;break;case ix:this._glFormat=i.DEPTH_COMPONENT,this._glInternalFormat=i.DEPTH_COMPONENT32F,this._glPixelType=i.FLOAT;break;case sn:this._glFormat=i.DEPTH_COMPONENT,this._glInternalFormat=i.DEPTH_COMPONENT16,this._glPixelType=i.UNSIGNED_SHORT;break;case iT:this._glFormat=i.DEPTH_STENCIL,this._glInternalFormat=i.DEPTH24_STENCIL8,this._glPixelType=i.UNSIGNED_INT_24_8;break;case iE:this._glFormat=i.RGB,this._glInternalFormat=i.R11F_G11F_B10F,this._glPixelType=i.UNSIGNED_INT_10F_11F_11F_REV;break;case iA:this._glFormat=i.RGB,this._glInternalFormat=i.SRGB8,this._glPixelType=i.UNSIGNED_BYTE;break;case ib:this._glFormat=i.RGBA,this._glInternalFormat=i.SRGB8_ALPHA8,this._glPixelType=i.UNSIGNED_BYTE;break;case iB:this._glFormat=i.RED_INTEGER,this._glInternalFormat=i.R8I,this._glPixelType=i.BYTE;break;case iU:this._glFormat=i.RED_INTEGER,this._glInternalFormat=i.R8UI,this._glPixelType=i.UNSIGNED_BYTE;break;case ik:this._glFormat=i.RED_INTEGER,this._glInternalFormat=i.R16I,this._glPixelType=i.SHORT;break;case iV:this._glFormat=i.RED_INTEGER,this._glInternalFormat=i.R16UI,this._glPixelType=i.UNSIGNED_SHORT;break;case iz:this._glFormat=i.RED_INTEGER,this._glInternalFormat=i.R32I,this._glPixelType=i.INT;break;case iG:this._glFormat=i.RED_INTEGER,this._glInternalFormat=i.R32UI,this._glPixelType=i.UNSIGNED_INT;break;case iH:this._glFormat=i.RG_INTEGER,this._glInternalFormat=i.RG8I,this._glPixelType=i.BYTE;break;case iW:this._glFormat=i.RG_INTEGER,this._glInternalFormat=i.RG8UI,this._glPixelType=i.UNSIGNED_BYTE;break;case iX:this._glFormat=i.RG_INTEGER,this._glInternalFormat=i.RG16I,this._glPixelType=i.SHORT;break;case iY:this._glFormat=i.RG_INTEGER,this._glInternalFormat=i.RG16UI,this._glPixelType=i.UNSIGNED_SHORT;break;case iq:this._glFormat=i.RG_INTEGER,this._glInternalFormat=i.RG32I,this._glPixelType=i.INT;break;case i$:this._glFormat=i.RG_INTEGER,this._glInternalFormat=i.RG32UI,this._glPixelType=i.UNSIGNED_INT;break;case ij:this._glFormat=i.RGBA_INTEGER,this._glInternalFormat=i.RGBA8I,this._glPixelType=i.BYTE;break;case iK:this._glFormat=i.RGBA_INTEGER,this._glInternalFormat=i.RGBA8UI,this._glPixelType=i.UNSIGNED_BYTE;break;case iZ:this._glFormat=i.RGBA_INTEGER,this._glInternalFormat=i.RGBA16I,this._glPixelType=i.SHORT;break;case iQ:this._glFormat=i.RGBA_INTEGER,this._glInternalFormat=i.RGBA16UI,this._glPixelType=i.UNSIGNED_SHORT;break;case iJ:this._glFormat=i.RGBA_INTEGER,this._glInternalFormat=i.RGBA32I,this._glPixelType=i.INT;break;case i0:this._glFormat=i.RGBA_INTEGER,this._glInternalFormat=i.RGBA32UI,this._glPixelType=i.UNSIGNED_INT;}this._glCreated=false;}upload(e,t){let i,s,r=e.gl;if(!t._needsUpload&&(t._needsMipmapsUpload&&t._mipmapsUploaded||!t.pot))return;let a=0,n=t.numLevels;for(t.array&&r.texStorage3D(r.TEXTURE_2D_ARRAY,n,this._glInternalFormat,t._width,t._height,t._arrayLength);t._levels[a]||0===a;){if(t._needsUpload||0!==a){if(a&&(!t._needsMipmapsUpload||!t._mipmaps))break}else {a++;continue}if(i=t._levels[a],s=1/Math.pow(2,a),1!==a||t._compressed||t._integerFormat||!(t._levels.length<n)||(r.generateMipmap(this._glTarget),t._mipmapsUploaded=true),t._cubemap){let n;if(e._isBrowserInterface(i[0]))for(n=0;n<6;n++){if(!t._levelsUpdated[0][n])continue;let s=i[n];e._isImageBrowserInterface(s)&&(s.width>e.maxCubeMapSize||s.height>e.maxCubeMapSize)&&(s=lN(s,e.maxCubeMapSize),0===a&&(t._width=s.width,t._height=s.height)),e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated?r.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,0,0,this._glFormat,this._glPixelType,s):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,this._glInternalFormat,this._glFormat,this._glPixelType,s);}else for(n=0,s=1/Math.pow(2,a);n<6;n++){if(!t._levelsUpdated[0][n])continue;let o=i[n];t._compressed?this._glCreated&&o?r.compressedTexSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,0,0,Math.max(t._width*s,1),Math.max(t._height*s,1),this._glInternalFormat,o):r.compressedTexImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,o):(e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated&&o?r.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,0,0,Math.max(t._width*s,1),Math.max(t._height*s,1),this._glFormat,this._glPixelType,o):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+n,a,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,this._glFormat,this._glPixelType,o));}}else if(t._volume)t._compressed?r.compressedTexImage3D(r.TEXTURE_3D,a,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),Math.max(t._depth*s,1),0,i):(e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),r.texImage3D(r.TEXTURE_3D,a,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),Math.max(t._depth*s,1),0,this._glFormat,this._glPixelType,i));else if(t.array&&"object"==typeof i){if(t._arrayLength===i.length)if(t._compressed)for(let e=0;e<t._arrayLength;e++)r.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,a,0,0,e,Math.max(Math.floor(t._width*s),1),Math.max(Math.floor(t._height*s),1),1,this._glInternalFormat,i[e]);else for(let e=0;e<t._arrayLength;e++)r.texSubImage3D(r.TEXTURE_2D_ARRAY,a,0,0,e,Math.max(Math.floor(t._width*s),1),Math.max(Math.floor(t._height*s),1),1,this._glFormat,this._glPixelType,i[e]);}else {if(e._isBrowserInterface(i)){e._isImageBrowserInterface(i)&&(i.width>e.maxTextureSize||i.height>e.maxTextureSize)&&(i=lN(i,e.maxTextureSize),0===a&&(t._width=i.width,t._height=i.height));let s=i.width||i.videoWidth,n=i.height||i.videoHeight;e.setUnpackFlipY(t._flipY),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated&&t._width===s&&t._height===n&&!e._isImageVideoInterface(i)?r.texSubImage2D(r.TEXTURE_2D,a,0,0,this._glFormat,this._glPixelType,i):(r.texImage2D(r.TEXTURE_2D,a,this._glInternalFormat,this._glFormat,this._glPixelType,i),0===a&&(t._width=s,t._height=n));}else s=1/Math.pow(2,a),t._compressed?this._glCreated&&i?r.compressedTexSubImage2D(r.TEXTURE_2D,a,0,0,Math.max(Math.floor(t._width*s),1),Math.max(Math.floor(t._height*s),1),this._glInternalFormat,i):r.compressedTexImage2D(r.TEXTURE_2D,a,this._glInternalFormat,Math.max(Math.floor(t._width*s),1),Math.max(Math.floor(t._height*s),1),0,i):(e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated&&i?r.texSubImage2D(r.TEXTURE_2D,a,0,0,Math.max(t._width*s,1),Math.max(t._height*s,1),this._glFormat,this._glPixelType,i):r.texImage2D(r.TEXTURE_2D,a,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,this._glFormat,this._glPixelType,i));0===a?t._mipmapsUploaded=false:t._mipmapsUploaded=true;}a++;}if(t._needsUpload)if(t._cubemap)for(let e=0;e<6;e++)t._levelsUpdated[0][e]=false;else t._levelsUpdated[0]=false;!t._compressed&&!t._integerFormat&&t._mipmaps&&t._needsMipmapsUpload&&1===t._levels.length&&(r.generateMipmap(this._glTarget),t._mipmapsUploaded=true),t._gpuSize&&t.adjustVramSizeTracking(e._vram,-t._gpuSize),t._gpuSize=t.gpuSize,t.adjustVramSizeTracking(e._vram,t._gpuSize),this._glCreated=true;}read(e,t,i,s,r){let a=this.texture;return a.device.readTextureAsync(a,e,t,i,s,r)}write(e,t,i,s,r){let{texture:a}=this,{device:n}=a;return n.setTexture(a,0),n.writeTextureAsync(a,e,t,i,s,r)}}class lB{constructor(e,t){this.msaaFB=e,this.resolveFB=t;}destroy(e){this.msaaFB&&(e.deleteRenderbuffer(this.msaaFB),this.msaaFB=null),this.resolveFB&&(e.deleteRenderbuffer(this.resolveFB),this.resolveFB=null);}}class lU{destroy(e){let t=e.gl;this._isInitialized=false,this._glFrameBuffer&&(this._glFrameBuffer!==this.suppliedColorFramebuffer&&t.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(t.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(this._glResolveFrameBuffer!==this.suppliedColorFramebuffer&&t.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffers.forEach(e=>{t.deleteRenderbuffer(e);}),this._glMsaaColorBuffers.length=0,this.colorMrtFramebuffers?.forEach(e=>{e.destroy(t);}),this.colorMrtFramebuffers=null,this._glMsaaDepthBuffer&&(this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey&&n7(e).release(this.msaaDepthBufferKey)),this.suppliedColorFramebuffer=void 0;}get initialized(){return this._isInitialized}init(e,t){let i=e.gl;this._isInitialized=true;let s=[];if(void 0!==this.suppliedColorFramebuffer)this._glFrameBuffer=this.suppliedColorFramebuffer;else {this._glFrameBuffer=i.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);let r=t._colorBuffers?.length??0,a=i.COLOR_ATTACHMENT0;for(let n=0;n<r;++n){let r=t.getColorBuffer(n);r&&(r.impl._glTexture||(r._width=Math.min(r.width,e.maxRenderBufferSize),r._height=Math.min(r.height,e.maxRenderBufferSize),e.setTexture(r,0)),i.framebufferTexture2D(i.FRAMEBUFFER,a+n,r._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:i.TEXTURE_2D,r.impl._glTexture,t.mipLevel),s.push(a+n));}i.drawBuffers(s);let n=t._depthBuffer;if(n||t._depth){let s=t._stencil?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;if(n)n.impl._glTexture||(n._width=Math.min(n.width,e.maxRenderBufferSize),n._height=Math.min(n.height,e.maxRenderBufferSize),e.setTexture(n,0)),i.framebufferTexture2D(i.FRAMEBUFFER,s,n._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:i.TEXTURE_2D,t._depthBuffer.impl._glTexture,t.mipLevel);else if(!(t._samples>1)){this._glDepthBuffer||(this._glDepthBuffer=i.createRenderbuffer());let e=t._stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT32F;i.bindRenderbuffer(i.RENDERBUFFER,this._glDepthBuffer),i.renderbufferStorage(i.RENDERBUFFER,e,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,s,i.RENDERBUFFER,this._glDepthBuffer),i.bindRenderbuffer(i.RENDERBUFFER,null);}}}if(t._samples>1){this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=i.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);let r=t._colorBuffers?.length??0;if(void 0!==this.suppliedColorFramebuffer){let s=i.createRenderbuffer();this._glMsaaColorBuffers.push(s);let r=e.backBufferFormat===id?i.RGBA8:i.RGB8;i.bindRenderbuffer(i.RENDERBUFFER,s),i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,r,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,s);}else for(let e=0;e<r;++e){let s=t.getColorBuffer(e);if(s){let r=i.createRenderbuffer();this._glMsaaColorBuffers.push(r),i.bindRenderbuffer(i.RENDERBUFFER,r),i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,s.impl._glInternalFormat,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+e,i.RENDERBUFFER,r);}}if(t._depth){let s,r=t._stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT32F,a=t._stencil?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,n=t._depthBuffer;n&&(s=`${n.id}:${t.width}:${t.height}:${t._samples}:${r}:${a}`,this._glMsaaDepthBuffer=n7(e).get(s)),!this._glMsaaDepthBuffer&&(this._glMsaaDepthBuffer=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,this._glMsaaDepthBuffer),i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,r,t.width,t.height),this._glMsaaDepthBuffer.destroy=function(){i.deleteRenderbuffer(this);},n&&n7(e).set(s,this._glMsaaDepthBuffer)),this.msaaDepthBufferKey=s,i.framebufferRenderbuffer(i.FRAMEBUFFER,a,i.RENDERBUFFER,this._glMsaaDepthBuffer);}r>1&&(this._createMsaaMrtFramebuffers(e,t,r),e.setFramebuffer(this._glFrameBuffer),i.drawBuffers(s));}}_createMsaaMrtFramebuffers(e,t,i){let s=e.gl;this.colorMrtFramebuffers=[];for(let r=0;r<i;++r){let i=t.getColorBuffer(r),a=s.createFramebuffer();e.setFramebuffer(a);let n=this._glMsaaColorBuffers[r];s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorageMultisample(s.RENDERBUFFER,t._samples,i.impl._glInternalFormat,t.width,t.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.RENDERBUFFER,n),s.drawBuffers([s.COLOR_ATTACHMENT0]);let o=s.createFramebuffer();e.setFramebuffer(o),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,i._cubemap?s.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:s.TEXTURE_2D,i.impl._glTexture,0),this.colorMrtFramebuffers[r]=new lB(a,o);}}_checkFbo(e,t,i=""){let s=e.gl;switch(s.checkFramebufferStatus(s.FRAMEBUFFER)){case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:case s.FRAMEBUFFER_UNSUPPORTED:}}loseContext(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffers.length=0,this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey=void 0,this.colorMrtFramebuffers=null,this.suppliedColorFramebuffer=void 0,this._isInitialized=false;}internalResolve(e,t,i,s,r){e.setScissor(0,0,s.width,s.height);let a=e.gl;a.bindFramebuffer(a.READ_FRAMEBUFFER,t),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,i),a.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,r,a.NEAREST);}resolve(e,t,i,s){let r=e.gl;if(this.colorMrtFramebuffers){if(i)for(let i=0;i<this.colorMrtFramebuffers.length;i++){let s=this.colorMrtFramebuffers[i];this.internalResolve(e,s.msaaFB,s.resolveFB,t,r.COLOR_BUFFER_BIT);}s&&this.internalResolve(e,this._glFrameBuffer,this._glResolveFrameBuffer,t,r.DEPTH_BUFFER_BIT);}else this.internalResolve(e,this._glFrameBuffer,this._glResolveFrameBuffer,t,(i?r.COLOR_BUFFER_BIT:0)|(s?r.DEPTH_BUFFER_BIT:0));r.bindFramebuffer(r.FRAMEBUFFER,this._glFrameBuffer);}constructor(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this.colorMrtFramebuffers=null,this._glMsaaColorBuffers=[],this._glMsaaDepthBuffer=null,this._isInitialized=false;}}class lk{destroy(e){this.queries.forEach(t=>e.deleteQuery(t)),this.queries=null;}constructor(){this.queries=[];}}class lV extends lg{constructor(e){super(),this.freeQueries=[],this.frameQueries=[],this.previousFrameQueries=[],this.timings=[],this.device=e,this.ext=e.extDisjointTimerQuery;}destroy(){this.freeQueries.forEach(e=>this.device.gl.deleteQuery(e)),this.frameQueries.forEach(e=>this.device.gl.deleteQuery(e)),this.previousFrameQueries.forEach(e=>e.destroy(this.device.gl)),this.freeQueries=null,this.frameQueries=null,this.previousFrameQueries=null;}loseContext(){super.loseContext(),this.freeQueries=[],this.frameQueries=[],this.previousFrameQueries=[];}restoreContext(){this.ext=this.device.extDisjointTimerQuery;}getQuery(){return this.freeQueries.pop()??this.device.gl.createQuery()}start(e){if(this.ext){let t=this.getSlot(e),i=this.getQuery();return this.frameQueries[t]=i,this.device.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,i),t}}end(e){ void 0!==e&&this.device.gl.endQuery(this.ext.TIME_ELAPSED_EXT);}frameStart(){this.processEnableRequest(),this._enabled&&(this.frameGPUMarkerSlot=this.start("GpuFrame"));}frameEnd(){this._enabled&&this.end(this.frameGPUMarkerSlot);}request(){if(this._enabled){let e=this.ext,t=this.device.gl,i=this.device.renderVersion,s=this.frameQueries;if(s.length>0){this.frameQueries=[];let e=new lk;e.queries=s,e.renderVersion=i,this.previousFrameQueries.push(e);}if(this.previousFrameQueries.length>0){let i=this.previousFrameQueries[0],s=i.queries,r=s[s.length-1],a=t.getQueryParameter(r,t.QUERY_RESULT_AVAILABLE),n=t.getParameter(e.GPU_DISJOINT_EXT);if(a&&!n){this.previousFrameQueries.shift();let e=this.timings;e.length=0;for(let i=0;i<s.length;i++){let r=s[i],a=t.getQueryParameter(r,t.QUERY_RESULT);e[i]=1e-6*a,this.freeQueries.push(r);}this.report(i.renderVersion,e);}n&&(this.previousFrameQueries.forEach(e=>{this.report(e.renderVersion,null),e.destroy(t);}),this.previousFrameQueries.length=0);}super.request(i);}}}let lz=[];class lG extends nD{constructor(e,t={}){let i,s,r,a,n;super(e,t),this._defaultFramebuffer=null,this._defaultFramebufferChanged=false,t=this.initOptions,this.updateClientRect(),this.initTextureUnits(),this.contextLost=false,this._contextLostHandler=e=>{e.preventDefault(),this.loseContext(),this.fire("devicelost");},this._contextRestoredHandler=()=>{this.restoreContext(),this.fire("devicerestored");};let o="undefined"!=typeof navigator&&navigator.userAgent;if(this.forceDisableMultisampling=o&&o.includes("AppleWebKit")&&(o.includes("15.4")||o.includes("15_4")),this.forceDisableMultisampling&&(t.antialias=false),"firefox"===ee.browserName){let e=("undefined"!=typeof navigator?navigator.userAgent:"").match(/Firefox\/(\d+(\.\d+)*)/),i=e?e[1]:null;if(i){let e=parseFloat(i);("windows"===ee.name&&(e>=120||115===e)||"android"===ee.name&&e>=132)&&(t.antialias=false);}}this.backBufferAntialias=t.antialias??false,t.antialias=false;let l=t.gl??e.getContext("webgl2",t);if(!l)throw Error("WebGL not supported");this.gl=l,this.isWebGL2=true,this._deviceType=ab,this.updateBackbufferFormat(null);let h="chrome"===ee.browserName,c="safari"===ee.browserName,d=ee.browser&&-1!==navigator.appVersion.indexOf("Mac");this._tempEnableSafariTextureUnitWorkaround=c,this._tempMacChromeBlitFramebufferWorkaround=d&&h&&!t.alpha,e.addEventListener("webglcontextlost",this._contextLostHandler,false),e.addEventListener("webglcontextrestored",this._contextRestoredHandler,false),this.initializeExtensions(),this.initializeCapabilities(),this.initializeRenderState(),this.initializeContextCaches(),this.createBackbuffer(null),this.supportsImageBitmap=!c&&"undefined"!=typeof ImageBitmap,this._samplerTypes=new Set([l.SAMPLER_2D,l.SAMPLER_CUBE,l.UNSIGNED_INT_SAMPLER_2D,l.INT_SAMPLER_2D,l.SAMPLER_2D_SHADOW,l.SAMPLER_CUBE_SHADOW,l.SAMPLER_3D,l.INT_SAMPLER_3D,l.UNSIGNED_INT_SAMPLER_3D,l.SAMPLER_2D_ARRAY,l.INT_SAMPLER_2D_ARRAY,l.UNSIGNED_INT_SAMPLER_2D_ARRAY]),this.glAddress=[l.REPEAT,l.CLAMP_TO_EDGE,l.MIRRORED_REPEAT],this.glBlendEquation=[l.FUNC_ADD,l.FUNC_SUBTRACT,l.FUNC_REVERSE_SUBTRACT,l.MIN,l.MAX],this.glBlendFunctionColor=[l.ZERO,l.ONE,l.SRC_COLOR,l.ONE_MINUS_SRC_COLOR,l.DST_COLOR,l.ONE_MINUS_DST_COLOR,l.SRC_ALPHA,l.SRC_ALPHA_SATURATE,l.ONE_MINUS_SRC_ALPHA,l.DST_ALPHA,l.ONE_MINUS_DST_ALPHA,l.CONSTANT_COLOR,l.ONE_MINUS_CONSTANT_COLOR],this.glBlendFunctionAlpha=[l.ZERO,l.ONE,l.SRC_COLOR,l.ONE_MINUS_SRC_COLOR,l.DST_COLOR,l.ONE_MINUS_DST_COLOR,l.SRC_ALPHA,l.SRC_ALPHA_SATURATE,l.ONE_MINUS_SRC_ALPHA,l.DST_ALPHA,l.ONE_MINUS_DST_ALPHA,l.CONSTANT_ALPHA,l.ONE_MINUS_CONSTANT_ALPHA],this.glComparison=[l.NEVER,l.LESS,l.EQUAL,l.LEQUAL,l.GREATER,l.NOTEQUAL,l.GEQUAL,l.ALWAYS],this.glStencilOp=[l.KEEP,l.ZERO,l.REPLACE,l.INCR,l.INCR_WRAP,l.DECR,l.DECR_WRAP,l.INVERT],this.glClearFlag=[0,l.COLOR_BUFFER_BIT,l.DEPTH_BUFFER_BIT,l.COLOR_BUFFER_BIT|l.DEPTH_BUFFER_BIT,l.STENCIL_BUFFER_BIT,l.STENCIL_BUFFER_BIT|l.COLOR_BUFFER_BIT,l.STENCIL_BUFFER_BIT|l.DEPTH_BUFFER_BIT,l.STENCIL_BUFFER_BIT|l.COLOR_BUFFER_BIT|l.DEPTH_BUFFER_BIT],this.glCull=[0,l.BACK,l.FRONT,l.FRONT_AND_BACK],this.glFilter=[l.NEAREST,l.LINEAR,l.NEAREST_MIPMAP_NEAREST,l.NEAREST_MIPMAP_LINEAR,l.LINEAR_MIPMAP_NEAREST,l.LINEAR_MIPMAP_LINEAR],this.glPrimitive=[l.POINTS,l.LINES,l.LINE_LOOP,l.LINE_STRIP,l.TRIANGLES,l.TRIANGLE_STRIP,l.TRIANGLE_FAN],this.glType=[l.BYTE,l.UNSIGNED_BYTE,l.SHORT,l.UNSIGNED_SHORT,l.INT,l.UNSIGNED_INT,l.FLOAT,l.HALF_FLOAT],this.pcUniformType={},this.pcUniformType[l.BOOL]=rN,this.pcUniformType[l.INT]=rF,this.pcUniformType[l.FLOAT]=rB,this.pcUniformType[l.FLOAT_VEC2]=rU,this.pcUniformType[l.FLOAT_VEC3]=rk,this.pcUniformType[l.FLOAT_VEC4]=rV,this.pcUniformType[l.INT_VEC2]=rz,this.pcUniformType[l.INT_VEC3]=rG,this.pcUniformType[l.INT_VEC4]=rH,this.pcUniformType[l.BOOL_VEC2]=rW,this.pcUniformType[l.BOOL_VEC3]=rX,this.pcUniformType[l.BOOL_VEC4]=rY,this.pcUniformType[l.FLOAT_MAT2]=rq,this.pcUniformType[l.FLOAT_MAT3]=r$,this.pcUniformType[l.FLOAT_MAT4]=rj,this.pcUniformType[l.SAMPLER_2D]=rK,this.pcUniformType[l.SAMPLER_CUBE]=rZ,this.pcUniformType[l.UNSIGNED_INT]=r6,this.pcUniformType[l.UNSIGNED_INT_VEC2]=r9,this.pcUniformType[l.UNSIGNED_INT_VEC3]=r7,this.pcUniformType[l.UNSIGNED_INT_VEC4]=ae,this.pcUniformType[l.SAMPLER_2D_SHADOW]=rJ,this.pcUniformType[l.SAMPLER_CUBE_SHADOW]=r0,this.pcUniformType[l.SAMPLER_2D_ARRAY]=r8,this.pcUniformType[l.SAMPLER_3D]=r1,this.pcUniformType[l.INT_SAMPLER_2D]=af,this.pcUniformType[l.UNSIGNED_INT_SAMPLER_2D]=ap,this.pcUniformType[l.INT_SAMPLER_CUBE]=am,this.pcUniformType[l.UNSIGNED_INT_SAMPLER_2D]=a_,this.pcUniformType[l.INT_SAMPLER_3D]=ag,this.pcUniformType[l.UNSIGNED_INT_SAMPLER_3D]=av,this.pcUniformType[l.INT_SAMPLER_2D_ARRAY]=aS,this.pcUniformType[l.UNSIGNED_INT_SAMPLER_2D_ARRAY]=ay,this.targetToSlot={},this.targetToSlot[l.TEXTURE_2D]=0,this.targetToSlot[l.TEXTURE_CUBE_MAP]=1,this.targetToSlot[l.TEXTURE_3D]=2,this.commitFunction=[],this.commitFunction[rN]=function(e,t){e.value!==t&&(l.uniform1i(e.locationId,t),e.value=t);},this.commitFunction[rF]=this.commitFunction[rN],this.commitFunction[rB]=function(e,t){e.value!==t&&(l.uniform1f(e.locationId,t),e.value=t);},this.commitFunction[rU]=function(e,t){n=e.value,i=t[0],s=t[1],(n[0]!==i||n[1]!==s)&&(l.uniform2fv(e.locationId,t),n[0]=i,n[1]=s);},this.commitFunction[rk]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],(n[0]!==i||n[1]!==s||n[2]!==r)&&(l.uniform3fv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r);},this.commitFunction[rV]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],a=t[3],(n[0]!==i||n[1]!==s||n[2]!==r||n[3]!==a)&&(l.uniform4fv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r,n[3]=a);},this.commitFunction[rz]=function(e,t){n=e.value,i=t[0],s=t[1],(n[0]!==i||n[1]!==s)&&(l.uniform2iv(e.locationId,t),n[0]=i,n[1]=s);},this.commitFunction[rW]=this.commitFunction[rz],this.commitFunction[rG]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],(n[0]!==i||n[1]!==s||n[2]!==r)&&(l.uniform3iv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r);},this.commitFunction[rX]=this.commitFunction[rG],this.commitFunction[rH]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],a=t[3],(n[0]!==i||n[1]!==s||n[2]!==r||n[3]!==a)&&(l.uniform4iv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r,n[3]=a);},this.commitFunction[rY]=this.commitFunction[rH],this.commitFunction[rq]=function(e,t){l.uniformMatrix2fv(e.locationId,false,t);},this.commitFunction[r$]=function(e,t){l.uniformMatrix3fv(e.locationId,false,t);},this.commitFunction[rj]=function(e,t){l.uniformMatrix4fv(e.locationId,false,t);},this.commitFunction[rQ]=function(e,t){l.uniform1fv(e.locationId,t);},this.commitFunction[r2]=function(e,t){l.uniform2fv(e.locationId,t);},this.commitFunction[r3]=function(e,t){l.uniform3fv(e.locationId,t);},this.commitFunction[r4]=function(e,t){l.uniform4fv(e.locationId,t);},this.commitFunction[r6]=function(e,t){e.value!==t&&(l.uniform1ui(e.locationId,t),e.value=t);},this.commitFunction[r9]=function(e,t){n=e.value,i=t[0],s=t[1],(n[0]!==i||n[1]!==s)&&(l.uniform2uiv(e.locationId,t),n[0]=i,n[1]=s);},this.commitFunction[r7]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],(n[0]!==i||n[1]!==s||n[2]!==r)&&(l.uniform3uiv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r);},this.commitFunction[ae]=function(e,t){n=e.value,i=t[0],s=t[1],r=t[2],a=t[3],(n[0]!==i||n[1]!==s||n[2]!==r||n[3]!==a)&&(l.uniform4uiv(e.locationId,t),n[0]=i,n[1]=s,n[2]=r,n[3]=a);},this.commitFunction[at]=function(e,t){l.uniform1iv(e.locationId,t);},this.commitFunction[ai]=function(e,t){l.uniform1uiv(e.locationId,t);},this.commitFunction[as]=this.commitFunction[at],this.commitFunction[ar]=function(e,t){l.uniform2iv(e.locationId,t);},this.commitFunction[aa]=function(e,t){l.uniform2uiv(e.locationId,t);},this.commitFunction[an]=this.commitFunction[ar],this.commitFunction[ao]=function(e,t){l.uniform3iv(e.locationId,t);},this.commitFunction[al]=function(e,t){l.uniform3uiv(e.locationId,t);},this.commitFunction[ah]=this.commitFunction[ao],this.commitFunction[ac]=function(e,t){l.uniform4iv(e.locationId,t);},this.commitFunction[ad]=function(e,t){l.uniform4uiv(e.locationId,t);},this.commitFunction[au]=this.commitFunction[ac],this.commitFunction[r5]=function(e,t){l.uniformMatrix4fv(e.locationId,false,t);},this.constantTexSource=this.scope.resolve("source"),this.postInit();}postInit(){super.postInit(),this.gpuProfiler=new lV(this);}destroy(){super.destroy();let e=this.gl;this.feedback&&e.deleteTransformFeedback(this.feedback),this.clearVertexArrayObjectCache(),this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,false),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,false),this._contextLostHandler=null,this._contextRestoredHandler=null,this.gl=null,super.postDestroy();}createBackbuffer(e){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new nM({name:"WebglFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.suppliedColorFramebuffer=e;}updateBackbufferFormat(e){let t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e);let i=this.gl.getParameter(this.gl.ALPHA_BITS);this.backBufferFormat=i?id:ic;}updateBackbuffer(){let e=this.canvas.width!==this.backBufferSize.x||this.canvas.height!==this.backBufferSize.y;(this._defaultFramebufferChanged||e)&&(this._defaultFramebufferChanged&&this.updateBackbufferFormat(this._defaultFramebuffer),this._defaultFramebufferChanged=false,this.backBufferSize.set(this.canvas.width,this.canvas.height),this.backBuffer.destroy(),this.createBackbuffer(this._defaultFramebuffer));}createVertexBufferImpl(e,t){return new lC}createIndexBufferImpl(e){return new lP(e)}createShaderImpl(e){return new lO(e)}createTextureImpl(e){return new lF(e)}createRenderTargetImpl(e){return new lU}getPrecision(){let e=this.gl,t="highp";if(e.getShaderPrecisionFormat){let i=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT),s=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT),r=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT),a=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT);if(i&&s&&r&&a){let e=i.precision>0&&r.precision>0,n=s.precision>0&&a.precision>0;e||(t=n?"mediump":"lowp");}}return t}getExtension(){for(let e=0;e<arguments.length;e++)if(-1!==this.supportedExtensions.indexOf(arguments[e]))return this.gl.getExtension(arguments[e]);return null}get extDisjointTimerQuery(){return this._extDisjointTimerQuery||(this._extDisjointTimerQuery=this.getExtension("EXT_disjoint_timer_query_webgl2","EXT_disjoint_timer_query")),this._extDisjointTimerQuery}initializeExtensions(){let e=this.gl;this.supportedExtensions=e.getSupportedExtensions()??[],this._extDisjointTimerQuery=null,this.textureRG11B10Renderable=true,this.extColorBufferFloat=this.getExtension("EXT_color_buffer_float"),this.textureFloatRenderable=!!this.extColorBufferFloat,this.extColorBufferHalfFloat=this.getExtension("EXT_color_buffer_half_float"),this.textureHalfFloatRenderable=!!this.extColorBufferHalfFloat||!!this.extColorBufferFloat,this.extDebugRendererInfo=this.getExtension("WEBGL_debug_renderer_info"),this.extTextureFloatLinear=this.getExtension("OES_texture_float_linear"),this.textureFloatFilterable=!!this.extTextureFloatLinear,this.extFloatBlend=this.getExtension("EXT_float_blend"),this.extTextureFilterAnisotropic=this.getExtension("EXT_texture_filter_anisotropic","WEBKIT_EXT_texture_filter_anisotropic"),this.extParallelShaderCompile=this.getExtension("KHR_parallel_shader_compile"),this.extCompressedTextureETC1=this.getExtension("WEBGL_compressed_texture_etc1"),this.extCompressedTextureETC=this.getExtension("WEBGL_compressed_texture_etc"),this.extCompressedTexturePVRTC=this.getExtension("WEBGL_compressed_texture_pvrtc","WEBKIT_WEBGL_compressed_texture_pvrtc"),this.extCompressedTextureS3TC=this.getExtension("WEBGL_compressed_texture_s3tc","WEBKIT_WEBGL_compressed_texture_s3tc"),this.extCompressedTextureS3TC_SRGB=this.getExtension("WEBGL_compressed_texture_s3tc_srgb"),this.extCompressedTextureATC=this.getExtension("WEBGL_compressed_texture_atc"),this.extCompressedTextureASTC=this.getExtension("WEBGL_compressed_texture_astc"),this.extTextureCompressionBPTC=this.getExtension("EXT_texture_compression_bptc");}initializeCapabilities(){let e,t=this.gl,i="undefined"!=typeof navigator?navigator.userAgent:"";this.maxPrecision=this.precision=this.getPrecision();let s=t.getContextAttributes();this.supportsMsaa=s?.antialias??false,this.supportsStencil=s?.stencil??false,this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubeMapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxRenderBufferSize=t.getParameter(t.MAX_RENDERBUFFER_SIZE),this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxCombinedTextures=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.vertexUniformsCount=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.fragmentUniformsCount=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.maxColorAttachments=t.getParameter(t.MAX_COLOR_ATTACHMENTS),this.maxVolumeSize=t.getParameter(t.MAX_3D_TEXTURE_SIZE),e=this.extDebugRendererInfo,this.unmaskedRenderer=e?t.getParameter(e.UNMASKED_RENDERER_WEBGL):"",this.unmaskedVendor=e?t.getParameter(e.UNMASKED_VENDOR_WEBGL):"",this.supportsGpuParticles=!("ARM"===this.unmaskedVendor&&i.match(/SM-[a-zA-Z0-9]+/))&&!this.unmaskedRenderer.match(/\bMali-G52+/),e=this.extTextureFilterAnisotropic,this.maxAnisotropy=e?t.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY_EXT):1;let r=!this.forceDisableMultisampling;this.maxSamples=r?t.getParameter(t.MAX_SAMPLES):1,this.maxSamples=Math.min(this.maxSamples,4),this.samples=r&&this.backBufferAntialias?this.maxSamples:1,this.supportsAreaLights=!ee.android,this.maxTextures<=8&&(this.supportsAreaLights=false),this.initCapsDefines();}initializeRenderState(){super.initializeRenderState();let e=this.gl;e.disable(e.BLEND),e.blendFunc(e.ONE,e.ZERO),e.blendEquation(e.FUNC_ADD),e.colorMask(true,true,true,true),e.blendColor(0,0,0,0),e.enable(e.CULL_FACE),this.cullFace=e.BACK,e.cullFace(e.BACK),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.depthMask(true),this.stencil=false,e.disable(e.STENCIL_TEST),this.stencilFuncFront=this.stencilFuncBack=t7,this.stencilRefFront=this.stencilRefBack=0,this.stencilMaskFront=this.stencilMaskBack=255,e.stencilFunc(e.ALWAYS,0,255),this.stencilFailFront=this.stencilFailBack=s0,this.stencilZfailFront=this.stencilZfailBack=s0,this.stencilZpassFront=this.stencilZpassBack=s0,this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255,e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.stencilMask(255),this.alphaToCoverage=false,this.raster=true,e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.disable(e.RASTERIZER_DISCARD),this.depthBiasEnabled=false,e.disable(e.POLYGON_OFFSET_FILL),this.clearDepth=1,e.clearDepth(1),this.clearColor=new eb(0,0,0,0),e.clearColor(0,0,0,0),this.clearStencil=0,e.clearStencil(0),e.hint(e.FRAGMENT_SHADER_DERIVATIVE_HINT,e.NICEST),e.enable(e.SCISSOR_TEST),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),this.unpackFlipY=false,e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,false),this.unpackPremultiplyAlpha=false,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false),e.pixelStorei(e.UNPACK_ALIGNMENT,1);}initTextureUnits(e=16){this.textureUnits=[];for(let t=0;t<e;t++)this.textureUnits.push([null,null,null]);}initializeContextCaches(){super.initializeContextCaches(),this._vaoMap=new Map,this.boundVao=null,this.activeFramebuffer=null,this.feedback=null,this.transformFeedbackBuffer=null,this.textureUnit=0,this.initTextureUnits(this.maxCombinedTextures);}loseContext(){for(let e of(super.loseContext(),this.shaders))e.loseContext();}restoreContext(){for(let e of(this.initializeExtensions(),this.initializeCapabilities(),super.restoreContext(),this.shaders))e.restoreContext();}setViewport(e,t,i,s){(this.vx!==e||this.vy!==t||this.vw!==i||this.vh!==s)&&(this.gl.viewport(e,t,i,s),this.vx=e,this.vy=t,this.vw=i,this.vh=s);}setScissor(e,t,i,s){(this.sx!==e||this.sy!==t||this.sw!==i||this.sh!==s)&&(this.gl.scissor(e,t,i,s),this.sx=e,this.sy=t,this.sw=i,this.sh=s);}setFramebuffer(e){if(this.activeFramebuffer!==e){let t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e),this.activeFramebuffer=e;}}copyRenderTarget(e,t,i,s){let r=this.gl;if(e===this.backBuffer&&(e=null),i){if(t){if(e&&(!e._colorBuffer||!t._colorBuffer||e._colorBuffer._format!==t._colorBuffer._format))return false}else if(!e._colorBuffer)return false}if(s&&e&&!e._depth&&(!e._depthBuffer||!t._depthBuffer||e._depthBuffer._format!==t._depthBuffer._format))return false;let a=this.renderTarget;this.renderTarget=t,this.updateBegin();let n=e?e.impl._glFrameBuffer:this.backBuffer?.impl._glFrameBuffer,o=t?t.impl._glFrameBuffer:this.backBuffer?.impl._glFrameBuffer;r.bindFramebuffer(r.READ_FRAMEBUFFER,n),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,o);let l=e?e.width:t?t.width:this.width,h=e?e.height:t?t.height:this.height;return r.blitFramebuffer(0,0,l,h,0,0,l,h,(i?r.COLOR_BUFFER_BIT:0)|(s?r.DEPTH_BUFFER_BIT:0),r.NEAREST),this.renderTarget=a,r.bindFramebuffer(r.FRAMEBUFFER,a?a.impl._glFrameBuffer:null),true}frameStart(){super.frameStart(),this.updateBackbuffer(),this.gpuProfiler.frameStart();}frameEnd(){super.frameEnd(),this.gpuProfiler.frameEnd(),this.gpuProfiler.request();}startRenderPass(e){let t=e.renderTarget??this.backBuffer;this.renderTarget=t,this.updateBegin();let{width:i,height:s}=t;this.setViewport(0,0,i,s),this.setScissor(0,0,i,s);let r=e.colorOps,a=e.depthStencilOps;if(r?.clear||a.clearDepth||a.clearStencil){let e=0,t={};r?.clear&&(e|=tB,t.color=[r.clearValue.r,r.clearValue.g,r.clearValue.b,r.clearValue.a]),a.clearDepth&&(e|=tU,t.depth=a.clearDepthValue),a.clearStencil&&(e|=tk,t.stencil=a.clearStencilValue),t.flags=e,this.clear(t);}this.insideRenderPass=true;}endRenderPass(e){this.unbindVertexArray();let t=this.renderTarget,i=e.colorArrayOps.length;if(t){lz.length=0;let s=this.gl;for(let t=0;t<i;t++){let i=e.colorArrayOps[t];i.store||i.resolve||lz.push(s.COLOR_ATTACHMENT0+t);}t!==this.backBuffer&&(e.depthStencilOps.storeDepth||lz.push(s.DEPTH_ATTACHMENT),e.depthStencilOps.storeStencil||lz.push(s.STENCIL_ATTACHMENT)),lz.length>0&&e.fullSizeClearRect&&s.invalidateFramebuffer(s.DRAW_FRAMEBUFFER,lz),i&&e.colorOps?.resolve&&e.samples>1&&t.autoResolve&&t.resolve(true,false),t.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&t.autoResolve&&t.resolve(false,true);for(let s=0;s<i;s++)if(e.colorArrayOps[s].genMipmaps){let e=t._colorBuffers[s];e&&e.impl._glTexture&&e.mipmaps&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(e),this.gl.generateMipmap(e.impl._glTarget));}}this.insideRenderPass=false;}set defaultFramebuffer(e){this._defaultFramebuffer!==e&&(this._defaultFramebuffer=e,this._defaultFramebufferChanged=true);}get defaultFramebuffer(){return this._defaultFramebuffer}updateBegin(){if(this.boundVao=null,this._tempEnableSafariTextureUnitWorkaround)for(let e=0;e<this.textureUnits.length;++e)for(let t=0;t<3;++t)this.textureUnits[e][t]=null;let e=this.renderTarget??this.backBuffer,t=e.impl;t.initialized||this.initRenderTarget(e),this.setFramebuffer(t._glFrameBuffer);}updateEnd(){this.unbindVertexArray();let e=this.renderTarget;if(e&&e!==this.backBuffer){e._samples>1&&e.autoResolve&&e.resolve();let t=e._colorBuffer;t&&t.impl._glTexture&&t.mipmaps&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(t),this.gl.generateMipmap(t.impl._glTarget));}}setUnpackFlipY(e){if(this.unpackFlipY!==e){this.unpackFlipY=e;let t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e);}}setUnpackPremultiplyAlpha(e){if(this.unpackPremultiplyAlpha!==e){this.unpackPremultiplyAlpha=e;let t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e);}}activeTexture(e){this.textureUnit!==e&&(this.gl.activeTexture(this.gl.TEXTURE0+e),this.textureUnit=e);}bindTexture(e){let t=e.impl,i=t._glTarget,s=t._glTexture,r=this.textureUnit,a=this.targetToSlot[i];this.textureUnits[r][a]!==s&&(this.gl.bindTexture(i,s),this.textureUnits[r][a]=s);}bindTextureOnUnit(e,t){let i=e.impl,s=i._glTarget,r=i._glTexture,a=this.targetToSlot[s];this.textureUnits[t][a]!==r&&(this.activeTexture(t),this.gl.bindTexture(s,r),this.textureUnits[t][a]=r);}setTextureParameters(e){let t=this.gl,i=e.impl.dirtyParameterFlags,s=e.impl._glTarget;if(i&aO){let i=e._minFilter;(!e._mipmaps||e._compressed&&1===e._levels.length)&&(i===tQ||i===tJ?i=tK:(i===t0||i===t1)&&(i=tZ)),t.texParameteri(s,t.TEXTURE_MIN_FILTER,this.glFilter[i]);}if(i&aN&&t.texParameteri(s,t.TEXTURE_MAG_FILTER,this.glFilter[e._magFilter]),i&aF&&t.texParameteri(s,t.TEXTURE_WRAP_S,this.glAddress[e._addressU]),i&aB&&t.texParameteri(s,t.TEXTURE_WRAP_T,this.glAddress[e._addressV]),i&aU&&t.texParameteri(s,t.TEXTURE_WRAP_R,this.glAddress[e._addressW]),i&ak&&t.texParameteri(s,t.TEXTURE_COMPARE_MODE,e._compareOnRead?t.COMPARE_REF_TO_TEXTURE:t.NONE),i&aV&&t.texParameteri(s,t.TEXTURE_COMPARE_FUNC,this.glComparison[e._compareFunc]),i&az){let i=this.extTextureFilterAnisotropic;i&&t.texParameterf(s,i.TEXTURE_MAX_ANISOTROPY_EXT,eA.clamp(Math.round(e._anisotropy),1,this.maxAnisotropy));}}setTexture(e,t){let i=e.impl;i._glTexture||i.initialize(this,e),i.dirtyParameterFlags>0||e._needsUpload||e._needsMipmapsUpload?(this.activeTexture(t),this.bindTexture(e),i.dirtyParameterFlags&&(this.setTextureParameters(e),i.dirtyParameterFlags=0),(e._needsUpload||e._needsMipmapsUpload)&&(i.upload(this,e),e._needsUpload=false,e._needsMipmapsUpload=false)):this.bindTextureOnUnit(e,t);}createVertexArray(e){let t,i,s=e.length>1;if(s){t="";for(let i=0;i<e.length;i++){let s=e[i];t+=s.id+s.format.renderingHash;}i=this._vaoMap.get(t);}if(!i){let r=this.gl;i=r.createVertexArray(),r.bindVertexArray(i),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,null);for(let t=0;t<e.length;t++){let i=e[t];r.bindBuffer(r.ARRAY_BUFFER,i.impl.bufferId);let s=i.format.elements;for(let e=0;e<s.length;e++){let t=s[e],a=a2[t.name];t.asInt?r.vertexAttribIPointer(a,t.numComponents,this.glType[t.dataType],t.stride,t.offset):r.vertexAttribPointer(a,t.numComponents,this.glType[t.dataType],t.normalize,t.stride,t.offset),r.enableVertexAttribArray(a),i.format.instancing&&r.vertexAttribDivisor(a,1);}}r.bindVertexArray(null),r.bindBuffer(r.ARRAY_BUFFER,null),s&&this._vaoMap.set(t,i);}return i}unbindVertexArray(){this.boundVao&&(this.boundVao=null,this.gl.bindVertexArray(null));}setBuffers(e){let t,i=this.gl;if(1===this.vertexBuffers.length){let e=this.vertexBuffers[0];e.impl.vao||(e.impl.vao=this.createVertexArray(this.vertexBuffers)),t=e.impl.vao;}else t=this.createVertexArray(this.vertexBuffers);this.boundVao!==t&&(this.boundVao=t,i.bindVertexArray(t));let s=e?e.impl.bufferId:null;i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,s);}draw(e,t,i,s,r=true,a=true){let n=this.shader;if(n&&(this.activateShader(),this.shaderValid)){let s=this.gl;r&&this.setBuffers(t);let a=0,o=n.impl.samplers;for(let e=0,t=o.length;e<t;e++){let t=o[e],i=t.scopeId.value;if(!i){let e=t.scopeId.name;"uSceneDepthMap"===e&&(i=no(this,"white")),"uSceneColorMap"===e&&(i=no(this,"pink")),i||(i=no(this,"pink"));}if(i instanceof ns){let e=i;this.setTexture(e,a),t.slot!==a&&(s.uniform1i(t.locationId,a),t.slot=a),a++;}else {t.array.length=0;let e=i.length;for(let s=0;s<e;s++){let e=i[s];this.setTexture(e,a),t.array[s]=a,a++;}s.uniform1iv(t.locationId,t.array);}}let l=n.impl.uniforms;for(let e=0,t=l.length;e<t;e++){let t=l[e],i=t.scopeId,s=t.version,r=i.versionObject.version;if(s.globalId!==r.globalId||s.revision!==r.revision){s.globalId=r.globalId,s.revision=r.revision;let e=i.value;null!=e&&this.commitFunction[t.dataType](t,e);}}this.transformFeedbackBuffer&&(s.bindBufferBase(s.TRANSFORM_FEEDBACK_BUFFER,0,this.transformFeedbackBuffer.impl.bufferId),s.beginTransformFeedback(s.POINTS));let h=this.glPrimitive[e.type],c=e.count;if(e.indexed){let r=t.impl.glFormat,a=e.base*t.bytesPerIndex;i>0?s.drawElementsInstanced(h,c,r,a,i):s.drawElements(h,c,r,a);}else {let t=e.base;i>0?s.drawArraysInstanced(h,t,c,i):s.drawArrays(h,t,c);}this.transformFeedbackBuffer&&(s.endTransformFeedback(),s.bindBufferBase(s.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++;}a&&this.clearVertexBuffer();}clear(e){let t=this.defaultClearOptions,i=(e=e||t).flags??t.flags;if(0!==i){let s=this.gl;if(i&tB){let i=e.color??t.color,s=i[0],r=i[1],a=i[2],n=i[3],o=this.clearColor;(s!==o.r||r!==o.g||a!==o.b||n!==o.a)&&(this.gl.clearColor(s,r,a,n),this.clearColor.set(s,r,a,n)),this.setBlendState(nu.NOBLEND);}if(i&tU){let i=e.depth??t.depth;i!==this.clearDepth&&(this.gl.clearDepth(i),this.clearDepth=i),this.setDepthState(nm.WRITEDEPTH);}if(i&tk){let i=e.stencil??t.stencil;i!==this.clearStencil&&(this.gl.clearStencil(i),this.clearStencil=i),s.stencilMask(255),this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255;}s.clear(this.glClearFlag[i]);}}submit(){this.gl.flush();}readPixels(e,t,i,s,r){let a=this.gl;a.readPixels(e,t,i,s,a.RGBA,a.UNSIGNED_BYTE,r);}clientWaitAsync(e,t){let i=this.gl,s=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);return this.submit(),new Promise((r,a)=>{!function n(){let o=i.clientWaitSync(s,e,0);o===i.TIMEOUT_EXPIRED?setTimeout(n,t):(i.deleteSync(s),o===i.WAIT_FAILED?a(Error("webgl clientWaitSync sync failed")):r());}();})}async readPixelsAsync(e,t,i,s,r){let a=this.gl,n=this.renderTarget.colorBuffer?.impl,o=n?._glFormat??a.RGBA,l=n?._glPixelType??a.UNSIGNED_BYTE,h=a.createBuffer();return a.bindBuffer(a.PIXEL_PACK_BUFFER,h),a.bufferData(a.PIXEL_PACK_BUFFER,r.byteLength,a.STREAM_READ),a.readPixels(e,t,i,s,o,l,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),await this.clientWaitAsync(0,16),a.bindBuffer(a.PIXEL_PACK_BUFFER,h),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,r),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(h),r}readTextureAsync(e,t,i,s,r,a){let n=a.face??0,o=a.renderTarget??new nM({colorBuffer:e,depth:false,face:n}),l=new ArrayBuffer(nt.calcLevelGpuSize(s,r,1,e._format)),h=a.data??new(sp(e._format))(l);return this.setRenderTarget(o),this.initRenderTarget(o),new Promise((e,n)=>{this.readPixelsAsync(t,i,s,r,h).then(t=>{a.renderTarget||o.destroy(),e(t);}).catch(n);})}async writeTextureAsync(e,t,i,s,r,a){let n=this.gl,o=e.impl,l=o?._glFormat??n.RGBA,h=o?._glPixelType??n.UNSIGNED_BYTE,c=n.createBuffer();n.bindBuffer(n.PIXEL_UNPACK_BUFFER,c),n.bufferData(n.PIXEL_UNPACK_BUFFER,a,n.STREAM_DRAW),n.bindTexture(n.TEXTURE_2D,o._glTexture),n.texSubImage2D(n.TEXTURE_2D,0,t,i,s,r,l,h,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),e._needsUpload=false,e._mipmapsUploaded=false,await this.clientWaitAsync(0,16);}setAlphaToCoverage(e){this.alphaToCoverage!==e&&(this.alphaToCoverage=e,e?this.gl.enable(this.gl.SAMPLE_ALPHA_TO_COVERAGE):this.gl.disable(this.gl.SAMPLE_ALPHA_TO_COVERAGE));}setTransformFeedbackBuffer(e){if(this.transformFeedbackBuffer!==e){this.transformFeedbackBuffer=e;let t=this.gl;e?(this.feedback||(this.feedback=t.createTransformFeedback()),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,this.feedback)):t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null);}}setRaster(e){this.raster!==e&&(this.raster=e,e?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD));}setStencilTest(e){if(this.stencil!==e){let t=this.gl;e?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.stencil=e;}}setStencilFunc(e,t,i){(this.stencilFuncFront!==e||this.stencilRefFront!==t||this.stencilMaskFront!==i||this.stencilFuncBack!==e||this.stencilRefBack!==t||this.stencilMaskBack!==i)&&(this.gl.stencilFunc(this.glComparison[e],t,i),this.stencilFuncFront=this.stencilFuncBack=e,this.stencilRefFront=this.stencilRefBack=t,this.stencilMaskFront=this.stencilMaskBack=i);}setStencilFuncFront(e,t,i){if(this.stencilFuncFront!==e||this.stencilRefFront!==t||this.stencilMaskFront!==i){let s=this.gl;s.stencilFuncSeparate(s.FRONT,this.glComparison[e],t,i),this.stencilFuncFront=e,this.stencilRefFront=t,this.stencilMaskFront=i;}}setStencilFuncBack(e,t,i){if(this.stencilFuncBack!==e||this.stencilRefBack!==t||this.stencilMaskBack!==i){let s=this.gl;s.stencilFuncSeparate(s.BACK,this.glComparison[e],t,i),this.stencilFuncBack=e,this.stencilRefBack=t,this.stencilMaskBack=i;}}setStencilOperation(e,t,i,s){(this.stencilFailFront!==e||this.stencilZfailFront!==t||this.stencilZpassFront!==i||this.stencilFailBack!==e||this.stencilZfailBack!==t||this.stencilZpassBack!==i)&&(this.gl.stencilOp(this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailFront=this.stencilFailBack=e,this.stencilZfailFront=this.stencilZfailBack=t,this.stencilZpassFront=this.stencilZpassBack=i),(this.stencilWriteMaskFront!==s||this.stencilWriteMaskBack!==s)&&(this.gl.stencilMask(s),this.stencilWriteMaskFront=s,this.stencilWriteMaskBack=s);}setStencilOperationFront(e,t,i,s){(this.stencilFailFront!==e||this.stencilZfailFront!==t||this.stencilZpassFront!==i)&&(this.gl.stencilOpSeparate(this.gl.FRONT,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailFront=e,this.stencilZfailFront=t,this.stencilZpassFront=i),this.stencilWriteMaskFront!==s&&(this.gl.stencilMaskSeparate(this.gl.FRONT,s),this.stencilWriteMaskFront=s);}setStencilOperationBack(e,t,i,s){(this.stencilFailBack!==e||this.stencilZfailBack!==t||this.stencilZpassBack!==i)&&(this.gl.stencilOpSeparate(this.gl.BACK,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailBack=e,this.stencilZfailBack=t,this.stencilZpassBack=i),this.stencilWriteMaskBack!==s&&(this.gl.stencilMaskSeparate(this.gl.BACK,s),this.stencilWriteMaskBack=s);}setBlendState(e){let t=this.blendState;if(!t.equals(e)){let i=this.gl,{blend:s,colorOp:r,alphaOp:a,colorSrcFactor:n,colorDstFactor:o,alphaSrcFactor:l,alphaDstFactor:h}=e;if(t.blend!==s&&(s?i.enable(i.BLEND):i.disable(i.BLEND)),t.colorOp!==r||t.alphaOp!==a){let e=this.glBlendEquation;i.blendEquationSeparate(e[r],e[a]);}(t.colorSrcFactor!==n||t.colorDstFactor!==o||t.alphaSrcFactor!==l||t.alphaDstFactor!==h)&&i.blendFuncSeparate(this.glBlendFunctionColor[n],this.glBlendFunctionColor[o],this.glBlendFunctionAlpha[l],this.glBlendFunctionAlpha[h]),t.allWrite!==e.allWrite&&this.gl.colorMask(e.redWrite,e.greenWrite,e.blueWrite,e.alphaWrite),t.copy(e);}}setBlendColor(e,t,i,s){let r=this.blendColor;(e!==r.r||t!==r.g||i!==r.b||s!==r.a)&&(this.gl.blendColor(e,t,i,s),r.set(e,t,i,s));}setStencilState(e,t){e||t?(this.setStencilTest(true),e===t?(this.setStencilFunc(e.func,e.ref,e.readMask),this.setStencilOperation(e.fail,e.zfail,e.zpass,e.writeMask)):(e??=nI.DEFAULT,this.setStencilFuncFront(e.func,e.ref,e.readMask),this.setStencilOperationFront(e.fail,e.zfail,e.zpass,e.writeMask),t??=nI.DEFAULT,this.setStencilFuncBack(t.func,t.ref,t.readMask),this.setStencilOperationBack(t.fail,t.zfail,t.zpass,t.writeMask))):this.setStencilTest(false);}setDepthState(e){let t=this.depthState;if(!t.equals(e)){let i=this.gl,s=e.write;t.write!==s&&i.depthMask(s);let{func:r,test:a}=e;!a&&s&&(a=true,r=t7),t.func!==r&&i.depthFunc(this.glComparison[r]),t.test!==a&&(a?i.enable(i.DEPTH_TEST):i.disable(i.DEPTH_TEST));let{depthBias:n,depthBiasSlope:o}=e;n||o?(this.depthBiasEnabled||(this.depthBiasEnabled=true,this.gl.enable(this.gl.POLYGON_OFFSET_FILL)),i.polygonOffset(o,n)):this.depthBiasEnabled&&(this.depthBiasEnabled=false,this.gl.disable(this.gl.POLYGON_OFFSET_FILL)),t.copy(e);}}setCullMode(e){if(this.cullMode!==e){if(e===tY)this.gl.disable(this.gl.CULL_FACE);else {this.cullMode===tY&&this.gl.enable(this.gl.CULL_FACE);let t=this.glCull[e];this.cullFace!==t&&(this.gl.cullFace(t),this.cullFace=t);}this.cullMode=e;}}setShader(e,t=false){e!==this.shader&&(this.shader=e,this.shaderAsyncCompile=t,this.shaderValid=void 0);}activateShader(){let{shader:e}=this,{impl:t}=e;void 0===this.shaderValid&&(e.failed?this.shaderValid=false:!e.ready&&(this.shaderAsyncCompile?t.isLinked(this)?t.finalize(this,e)||(e.failed=true,this.shaderValid=false):this.shaderValid=false:t.finalize(this,e)||(e.failed=true,this.shaderValid=false))),void 0===this.shaderValid&&(this.gl.useProgram(t.glProgram),this.shaderValid=true);}clearVertexArrayObjectCache(){let e=this.gl;this._vaoMap.forEach((t,i,s)=>{e.deleteVertexArray(t);}),this._vaoMap.clear();}set fullscreen(e){e?this.gl.canvas.requestFullscreen():document.exitFullscreen();}get fullscreen(){return !!document.fullscreenElement}}class lH{unlock(e){}}class lW{destroy(e){}init(e,t){}loseContext(){}resolve(e,t,i,s){}}class lX{destroy(e){}loseContext(){}restoreContext(e,t){}}class lY{destroy(e){}propertyChanged(e){}loseContext(){}}class lq{destroy(e){}unlock(e){}}class l$ extends nD{constructor(e,t={}){super(e,t),t=this.initOptions,this.isNull=true,this._deviceType=aC,this.samples=1,this.backBuffer=new nM({name:"Framebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.initDeviceCaps();}destroy(){super.destroy();}initDeviceCaps(){this.disableParticleSystem=true,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=4096,this.maxCubeMapSize=4096,this.maxVolumeSize=4096,this.maxColorAttachments=8,this.maxPixelRatio=1,this.maxAnisotropy=16,this.supportsUniformBuffers=false,this.supportsAreaLights=true,this.supportsGpuParticles=false,this.textureFloatRenderable=true,this.textureHalfFloatRenderable=true,this.supportsImageBitmap=false;}postInit(){super.postInit();}frameStart(){super.frameStart();}frameEnd(){super.frameEnd();}updateBegin(){}updateEnd(){}readPixels(e,t,i,s,r){}createVertexBufferImpl(e,t){return new lq(e,t)}createIndexBufferImpl(e){return new lH(e)}createShaderImpl(e){return new lX(e)}createTextureImpl(e){return new lY(e)}createRenderTargetImpl(e){return new lW(e)}draw(e,t,i,s,r=true,a=true){}setShader(e,t=false){}setBlendState(e){}setDepthState(e){}setStencilState(e,t){}setBlendColor(e,t,i,s){}setCullMode(e){}setAlphaToCoverage(e){}initializeContextCaches(){super.initializeContextCaches();}clear(e){}setViewport(e,t,i,s){}setScissor(e,t,i,s){}copyRenderTarget(e,t,i,s){return true}}function lj(e,t={}){let i=t.deviceTypes??[];i.includes(ab)||i.push(ab),i.includes(aC)||i.push(aC),ee.browser&&navigator.xr&&(t.xrCompatible??=true);let s=[];for(let r=0;r<i.length;r++){let a=i[r];a===aw&&window?.navigator?.gpu&&s.push(()=>new lb(e,t).initWebGpu(t.glslangUrl,t.twgslUrl)),a===ab&&s.push(()=>new lG(e,t)),a===aC&&s.push(()=>new l$(e,t));}return new Promise((e,t)=>{let i=0,r=()=>{i>=s.length?t(Error("Failed to create a graphics device")):Promise.resolve(s[i++]()).then(t=>{t?e(t):r();}).catch(e=>{r();});};r();})}class lK{constructor(){this.scopeId=null;}}class lZ{constructor(e,t,i="Unnamed"){this.shader=null,this.parameters=new Map,this.countX=1,this.device=e,this.shader=t,this.name=i,e.supportsCompute&&(this.impl=e.createComputeImpl(this));}setParameter(e,t){let i=this.parameters.get(e);i||((i=new lK).scopeId=this.device.scope.resolve(e),this.parameters.set(e,i)),i.value=t;}getParameter(e){return this.parameters.get(e)?.value}deleteParameter(e){this.parameters.delete(e);}applyParameters(){for(let[,e]of this.parameters)e.scopeId.setValue(e.value);}setupDispatch(e,t,i){this.countX=e,this.countY=t,this.countZ=i;}}let lQ=0;class lJ{constructor(e,t,i,s=tM,r,a){this.device=e,this.format=t,this.numIndices=i,this.usage=s,this.id=lQ++,this.impl=e.createIndexBufferImpl(this,a);let n=a0[t];this.bytesPerIndex=n,this.numBytes=this.numIndices*n,r?this.setData(r):this.storage=new ArrayBuffer(this.numBytes),this.adjustVramSizeTracking(e._vram,this.numBytes),this.device.buffers.push(this);}destroy(){let e=this.device,t=e.buffers.indexOf(this);-1!==t&&e.buffers.splice(t,1),this.device.indexBuffer===this&&(this.device.indexBuffer=null),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength));}adjustVramSizeTracking(e,t){e.ib+=t;}loseContext(){this.impl.loseContext();}getFormat(){return this.format}getNumIndices(){return this.numIndices}lock(){return this.storage}unlock(){this.impl.unlock(this);}setData(e){return e.byteLength===this.numBytes&&(this.storage=e,this.unlock(),true)}_lockTypedArray(){let e=this.lock();return this.format===ii?new Uint32Array(e):this.format===it?new Uint16Array(e):new Uint8Array(e)}writeData(e,t){let i=this._lockTypedArray();if(e.length>t)if(ArrayBuffer.isView(e))e=e.subarray(0,t),i.set(e);else for(let s=0;s<t;s++)i[s]=e[s];else i.set(e);this.unlock();}readData(e){let t=this._lockTypedArray(),i=this.numIndices;if(ArrayBuffer.isView(e))e.set(t);else {e.length=0;for(let s=0;s<i;s++)e[s]=t[s];}return i}}class l0{constructor(){this.clearValue=new eb(0,0,0,1),this.clearValueLinear=new eb(0,0,0,1),this.clear=false,this.store=false,this.resolve=true,this.genMipmaps=false;}}class l1{constructor(){this.clearDepthValue=1,this.clearStencilValue=0,this.clearDepth=false,this.clearStencil=false,this.storeDepth=false,this.resolveDepth=false,this.storeStencil=false;}}class l2{get colorOps(){return this.colorArrayOps[0]}constructor(e){this._enabled=true,this._skipStart=false,this._skipEnd=false,this.executeEnabled=true,this.samples=0,this.colorArrayOps=[],this.requiresCubemaps=true,this.fullSizeClearRect=true,this.beforePasses=[],this.afterPasses=[],this.device=e;}set name(e){this._name=e;}get name(){return this._name||(this._name=this.constructor.name),this._name}set scaleX(e){this._options.scaleX=e;}get scaleX(){return this._options.scaleX}set scaleY(e){this._options.scaleY=e;}get scaleY(){return this._options.scaleY}set options(e){this._options=e,e&&(this.scaleX=this.scaleX??1,this.scaleY=this.scaleY??1);}get options(){return this._options}init(e=null,t){this.options=t,this.renderTarget=e,this.samples=Math.max(this.renderTarget?this.renderTarget.samples:this.device.samples,1),this.allocateAttachments(),this.postInit();}allocateAttachments(){let e=this.renderTarget;this.depthStencilOps=new l1,e?.depthBuffer&&(this.depthStencilOps.storeDepth=true);let t=e?e._colorBuffers?.length??0:1;this.colorArrayOps.length=0;for(let e=0;e<t;e++){let t=new l0;this.colorArrayOps[e]=t,1===this.samples&&(t.store=true,t.resolve=false);let i=this.renderTarget?._colorBuffers?.[e];this.renderTarget?.mipmaps&&i?.mipmaps&&(t.genMipmaps=!sc(i._format));}}destroy(){}postInit(){}frameUpdate(){if(this._options&&this.renderTarget){let e=this._options.resizeSource??this.device.backBuffer,t=Math.floor(e.width*this.scaleX),i=Math.floor(e.height*this.scaleY);this.renderTarget.resize(t,i);}}before(){}execute(){}after(){}onEnable(){}onDisable(){}set enabled(e){this._enabled!==e&&(this._enabled=e,e?this.onEnable():this.onDisable());}get enabled(){return this._enabled}setClearColor(e){let t=this.colorArrayOps.length;for(let i=0;i<t;i++){let t=this.colorArrayOps[i];e&&(t.clearValue.copy(e),t.clearValueLinear.linear(e)),t.clear=!!e;}}setClearDepth(e){e&&(this.depthStencilOps.clearDepthValue=e),this.depthStencilOps.clearDepth=void 0!==e;}setClearStencil(e){e&&(this.depthStencilOps.clearStencilValue=e),this.depthStencilOps.clearStencil=void 0!==e;}render(){if(this.enabled){let e=this.device,t=void 0!==this.renderTarget;this.before(),this.executeEnabled&&(t&&!this._skipStart&&e.startRenderPass(this),this.execute(),t&&!this._skipEnd&&e.endRenderPass(this)),this.after(),e.renderPassIndex++;}}}class l3{constructor(e,t=tF){this.device=e.device;let i=this.device.gl;this._inputBuffer=e,t===tF&&e.usage!==t&&(i.bindBuffer(i.ARRAY_BUFFER,e.impl.bufferId),i.bufferData(i.ARRAY_BUFFER,e.storage,i.DYNAMIC_COPY)),this._outputBuffer=new nT(e.device,e.format,e.numVertices,{usage:t,data:e.storage});}static createShader(e,t,i){return new la(e,ls.createDefinition(e,{name:i,vertexCode:t,useTransformFeedback:true,fragmentCode:"void main(void) {gl_FragColor = vec4(0.0);}"}))}destroy(){this._outputBuffer.destroy();}process(e,t=true){let i=this.device,s=i.getRenderTarget();if(i.setRenderTarget(null),i.updateBegin(),i.setVertexBuffer(this._inputBuffer,0),i.setRaster(false),i.setTransformFeedbackBuffer(this._outputBuffer),i.setShader(e),i.draw({type:sm,base:0,baseVertex:0,count:this._inputBuffer.numVertices,indexed:false}),i.setTransformFeedbackBuffer(null),i.setRaster(true),i.updateEnd(),i.setRenderTarget(s),t){let e=this._inputBuffer.impl.bufferId;this._inputBuffer.impl.bufferId=this._outputBuffer.impl.bufferId,this._outputBuffer.impl.bufferId=e,e=this._inputBuffer.impl.vao,this._inputBuffer.impl.vao=this._outputBuffer.impl.vao,this._outputBuffer.impl.vao=e;}}get inputBuffer(){return this._inputBuffer}get outputBuffer(){return this._outputBuffer}}function l4(e){this.array[this.index]=e;}function l5(e,t){this.array[this.index]=e,this.array[this.index+1]=t;}function l8(e,t,i){this.array[this.index]=e,this.array[this.index+1]=t,this.array[this.index+2]=i;}function l6(e,t,i,s){this.array[this.index]=e,this.array[this.index+1]=t,this.array[this.index+2]=i,this.array[this.index+3]=s;}function l9(e,t,i){this.array[e]=t[i];}function l7(e,t,i){this.array[e]=t[i],this.array[e+1]=t[i+1];}function he(e,t,i){this.array[e]=t[i],this.array[e+1]=t[i+1],this.array[e+2]=t[i+2];}function ht(e,t,i){this.array[e]=t[i],this.array[e+1]=t[i+1],this.array[e+2]=t[i+2],this.array[e+3]=t[i+3];}function hi(e,t,i){t[i]=this.array[e];}function hs(e,t,i){t[i]=this.array[e],t[i+1]=this.array[e+1];}function hr(e,t,i){t[i]=this.array[e],t[i+1]=this.array[e+1],t[i+2]=this.array[e+2];}function ha(e,t,i){t[i]=this.array[e],t[i+1]=this.array[e+1],t[i+2]=this.array[e+2],t[i+3]=this.array[e+3];}class hn{constructor(e,t,i){switch(this.index=0,this.numComponents=t.numComponents,i.interleaved?this.array=new aj[t.dataType](e,t.offset):this.array=new aj[t.dataType](e,t.offset,i.vertexCount*t.numComponents),this.stride=t.stride/this.array.constructor.BYTES_PER_ELEMENT,t.numComponents){case 1:this.set=l4,this.getToArray=hi,this.setFromArray=l9;break;case 2:this.set=l5,this.getToArray=hs,this.setFromArray=l7;break;case 3:this.set=l8,this.getToArray=hr,this.setFromArray=he;break;case 4:this.set=l6,this.getToArray=ha,this.setFromArray=ht;}}get(e){return this.array[this.index+e]}set(e,t,i,s){}getToArray(e,t,i){}setFromArray(e,t,i){}}class ho{constructor(e){this.vertexBuffer=e,this.vertexFormatSize=e.getFormat().size,this.buffer=this.vertexBuffer.lock(),this.accessors=[],this.element={};let t=this.vertexBuffer.getFormat();for(let e=0;e<t.elements.length;e++){let i=t.elements[e];this.accessors[e]=new hn(this.buffer,i,t),this.element[i.name]=this.accessors[e];}}next(e=1){let t=0,i=this.accessors,s=this.accessors.length;for(;t<s;){let s=i[t++];s.index+=e*s.stride;}}end(){this.vertexBuffer.unlock();}writeData(e,t,i){let s=this.element[e];if(s){i>this.vertexBuffer.numVertices&&(i=this.vertexBuffer.numVertices);let e=s.numComponents;if(this.vertexBuffer.getFormat().interleaved){let r=0;for(let a=0;a<i;a++)s.setFromArray(r,t,a*e),r+=s.stride;}else if(t.length>i*e){let r=i*e;if(ArrayBuffer.isView(t))t=t.subarray(0,r),s.array.set(t);else for(let e=0;e<r;e++)s.array[e]=t[e];}else s.array.set(t);}}readData(e,t){let i=this.element[e],s=0;if(i){let e;s=this.vertexBuffer.numVertices;let r=i.numComponents;if(this.vertexBuffer.getFormat().interleaved){Array.isArray(t)&&(t.length=0),i.index=0;let a=0;for(e=0;e<s;e++)i.getToArray(a,t,e*r),a+=i.stride;}else if(ArrayBuffer.isView(t))t.set(i.array);else {t.length=0;let a=s*r;for(e=0;e<a;e++)t[e]=i.array[e];}}return s}}let hl="mouse",hh="keyboard",hc="gamepad",hd="mousex",hu="mousey",hf="padlx",hp="padly",hm="padrx",h_="padry",hg="key",hv=8,hS=9,hy=13,hx=13,hT=16,hE=17,hA=18,hb=19,hw=20,hC=27,hP=32,hL=33,hI=34,hD=35,hR=36,hM=37,hO=38,hN=39,hF=40,hB=44,hU=45,hk=46,hV=48,hz=49,hG=50,hH=51,hW=52,hX=53,hY=54,hq=55,h$=56,hj=57,hK=59,hZ=61,hQ=65,hJ=66,h0=67,h1=68,h2=69,h3=70,h4=71,h5=72,h8=73,h6=74,h9=75,h7=76,ce=77,ct=78,ci=79,cs=80,cr=81,ca=82,cn=83,co=84,cl=85,ch=86,cc=87,cd=88,cu=89,cf=90,cp=91,cm=93,c_=96,cg=97,cv=98,cS=99,cy=100,cx=101,cT=102,cE=103,cA=104,cb=105,cw=106,cC=107,cP=108,cL=109,cI=110,cD=111,cR=112,cM=113,cO=114,cN=115,cF=116,cB=117,cU=118,ck=119,cV=120,cz=121,cG=122,cH=123,cW=188,cX=190,cY=191,cq=219,c$=220,cj=221,cK=224,cZ=-1,cQ=0,cJ=1,c0=2,c1=0,c2=1,c3=2,c4=3,c5=0,c8=1,c6=2,c9=3,c7=4,de=5,dt=6,di=7,ds=8,dr=9,da=10,dn=11,dl=12,dh=13,dc=14,dd=15,du=16,df=0,dp=1,dm=2,d_=3,dg=0,dv=1,dS=2,dy=3,dx=2,dT=0,dE=1,dA=3,db=4,dw=5;class dC{constructor(e,t){this.key=null,this.element=null,this.event=null,t&&(this.key=t.keyCode,this.element=t.target,this.event=t);}}let dP=new dC;function dL(e){return dP.key=e.keyCode,dP.element=e.target,dP.event=e,dP}function dI(e){return "string"==typeof e?e.toUpperCase().charCodeAt(0):e}let dD={9:"Tab",13:"Enter",16:"Shift",17:"Control",18:"Alt",27:"Escape",37:"Left",38:"Up",39:"Right",40:"Down",46:"Delete",91:"Win"};class dR extends eo{static{this.EVENT_KEYDOWN="keydown";}static{this.EVENT_KEYUP="keyup";}constructor(e,t={}){super(),this._element=null,this._keymap={},this._lastmap={},this._keyDownHandler=this._handleKeyDown.bind(this),this._keyUpHandler=this._handleKeyUp.bind(this),this._keyPressHandler=this._handleKeyPress.bind(this),this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),this._windowBlurHandler=this._handleWindowBlur.bind(this),e&&this.attach(e),this.preventDefault=t.preventDefault||false,this.stopPropagation=t.stopPropagation||false;}attach(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("keydown",this._keyDownHandler,false),this._element.addEventListener("keypress",this._keyPressHandler,false),this._element.addEventListener("keyup",this._keyUpHandler,false),document.addEventListener("visibilitychange",this._visibilityChangeHandler,false),window.addEventListener("blur",this._windowBlurHandler,false);}detach(){this._element&&(this._element.removeEventListener("keydown",this._keyDownHandler),this._element.removeEventListener("keypress",this._keyPressHandler),this._element.removeEventListener("keyup",this._keyUpHandler),this._element=null,document.removeEventListener("visibilitychange",this._visibilityChangeHandler,false),window.removeEventListener("blur",this._windowBlurHandler,false));}toKeyIdentifier(e){let t=dD[(e=dI(e)).toString()];if(t)return t;let i=e.toString(16).toUpperCase(),s=i.length;for(let e=0;e<4-s;e++)i=`0${i}`;return `U+${i}`}_handleKeyDown(e){let t=e.keyCode||e.charCode;if(void 0===t)return;let i=this.toKeyIdentifier(t);this._keymap[i]=true,this.fire("keydown",dL(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation();}_handleKeyUp(e){let t=e.keyCode||e.charCode;if(void 0===t)return;let i=this.toKeyIdentifier(t);delete this._keymap[i],this.fire("keyup",dL(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation();}_handleKeyPress(e){this.fire("keypress",dL(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation();}_handleVisibilityChange(){"hidden"===document.visibilityState&&this._handleWindowBlur();}_handleWindowBlur(){this._keymap={},this._lastmap={};}update(){for(let e in this._lastmap)delete this._lastmap[e];for(let e in this._keymap)this._keymap.hasOwnProperty(e)&&(this._lastmap[e]=this._keymap[e]);}isPressed(e){let t=dI(e),i=this.toKeyIdentifier(t);return !!this._keymap[i]}wasPressed(e){let t=dI(e),i=this.toKeyIdentifier(t);return !!this._keymap[i]&&!this._lastmap[i]}wasReleased(e){let t=dI(e),i=this.toKeyIdentifier(t);return !this._keymap[i]&&!!this._lastmap[i]}}function dM(){return !!(document.pointerLockElement||document.mozPointerLockElement||document.webkitPointerLockElement)}class dO{constructor(e,t){this.x=0,this.y=0,this.dx=0,this.dy=0,this.button=cZ,this.wheelDelta=0,this.ctrlKey=false,this.altKey=false,this.shiftKey=false,this.metaKey=false;let i={x:0,y:0};if(t){if(t instanceof dO)throw Error("Expected MouseEvent");i=e._getTargetCoords(t);}else t={};if(i)this.x=i.x,this.y=i.y;else {if(!dM())return;this.x=0,this.y=0;}"wheel"===t.type&&(t.deltaY>0?this.wheelDelta=1:t.deltaY<0&&(this.wheelDelta=-1)),dM()?(this.dx=t.movementX||t.webkitMovementX||t.mozMovementX||0,this.dy=t.movementY||t.webkitMovementY||t.mozMovementY||0):(this.dx=this.x-e._lastX,this.dy=this.y-e._lastY),("mousedown"===t.type||"mouseup"===t.type)&&(this.button=t.button),this.buttons=e._buttons.slice(0),this.element=t.target,this.ctrlKey=t.ctrlKey??false,this.altKey=t.altKey??false,this.shiftKey=t.shiftKey??false,this.metaKey=t.metaKey??false,this.event=t;}}class dN extends eo{static{this.EVENT_MOUSEMOVE="mousemove";}static{this.EVENT_MOUSEDOWN="mousedown";}static{this.EVENT_MOUSEUP="mouseup";}static{this.EVENT_MOUSEWHEEL="mousewheel";}constructor(e){super(),this._lastX=0,this._lastY=0,this._buttons=[false,false,false],this._lastbuttons=[false,false,false],this._target=null,this._attached=false,this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._contextMenuHandler=e=>{e.preventDefault();},this.attach(e);}static isPointerLocked(){return dM()}attach(e){if(this._target=e,this._attached)return;this._attached=true;let t=!!ee.passiveEvents&&{passive:false};window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t);}detach(){if(!this._attached)return;this._attached=false,this._target=null;let e=!!ee.passiveEvents&&{passive:false};window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e);}disableContextMenu(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler);}enableContextMenu(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler);}enablePointerLock(e,t){if(!document.body.requestPointerLock){t&&t();return}let i=()=>{e(),document.removeEventListener("pointerlockchange",i);},s=()=>{t(),document.removeEventListener("pointerlockerror",s);};e&&document.addEventListener("pointerlockchange",i,false),t&&document.addEventListener("pointerlockerror",s,false),document.body.requestPointerLock();}disablePointerLock(e){if(!document.exitPointerLock)return;let t=()=>{e(),document.removeEventListener("pointerlockchange",t);};e&&document.addEventListener("pointerlockchange",t,false),document.exitPointerLock();}update(){this._lastbuttons[0]=this._buttons[0],this._lastbuttons[1]=this._buttons[1],this._lastbuttons[2]=this._buttons[2];}isPressed(e){return this._buttons[e]}wasPressed(e){return this._buttons[e]&&!this._lastbuttons[e]}wasReleased(e){return !this._buttons[e]&&this._lastbuttons[e]}_handleUp(e){this._buttons[e.button]=false;let t=new dO(this,e);t.event&&this.fire("mouseup",t);}_handleDown(e){this._buttons[e.button]=true;let t=new dO(this,e);t.event&&this.fire("mousedown",t);}_handleMove(e){let t=new dO(this,e);t.event&&(this.fire("mousemove",t),this._lastX=t.x,this._lastY=t.y);}_handleWheel(e){let t=new dO(this,e);t.event&&this.fire("mousewheel",t);}_getTargetCoords(e){let t=this._target.getBoundingClientRect(),i=Math.floor(t.left),s=Math.floor(t.top);return e.clientX<i||e.clientX>=i+this._target.clientWidth||e.clientY<s||e.clientY>=s+this._target.clientHeight?null:{x:e.clientX-i,y:e.clientY-s}}}class dF{constructor(e,t={}){this._element=null,this._actions={},this._axes={},this._axesValues={},this._keyboard=t.keyboard||null,this._mouse=t.mouse||null,this._gamepads=t.gamepads||null,e&&this.attach(e);}attach(e){this._element=e,this._keyboard&&this._keyboard.attach(e),this._mouse&&this._mouse.attach(e);}detach(){this._keyboard&&this._keyboard.detach(),this._mouse&&this._mouse.detach(),this._element=null;}disableContextMenu(){this._mouse||this._enableMouse(),this._mouse.disableContextMenu();}enableContextMenu(){this._mouse||this._enableMouse(),this._mouse.enableContextMenu();}update(e){for(let e in this._keyboard&&this._keyboard.update(),this._mouse&&this._mouse.update(),this._gamepads&&this._gamepads.update(),this._axesValues={},this._axes)this._axesValues[e]=[];}appendAction(e,t){this._actions[e]=this._actions[e]||[],this._actions[e].push(t);}registerKeys(e,t){if(this._keyboard||this._enableKeyboard(),this._actions[e])throw Error(`Action: ${e} already registered`);if(void 0===t)throw Error("Invalid button");t.length||(t=[t]),this.appendAction(e,{type:hh,keys:t});}registerMouse(e,t){if(this._mouse||this._enableMouse(),void 0===t)throw Error("Invalid button");this.appendAction(e,{type:hl,button:t});}registerPadButton(e,t,i){if(void 0===i)throw Error("Invalid button");this.appendAction(e,{type:hc,button:i,pad:t});}registerAxis(e){let t=e.name;this._axes[t]||(this._axes[t]=[]);let i=this._axes[t].push(t);(e=e||{}).pad=e.pad||c1;let s=function(s,r,a,n){switch(r){case "mousex":s._mouse.on("mousemove",e=>{s._axesValues[t][i]=e.dx/10;});break;case "mousey":s._mouse.on("mousemove",e=>{s._axesValues[t][i]=e.dy/10;});break;case "key":s._axes[t].push(()=>s._keyboard.isPressed(n)?a:0);break;case "padrx":s._axes[t].push(()=>s._gamepads.getAxis(e.pad,dm));break;case "padry":s._axes[t].push(()=>s._gamepads.getAxis(e.pad,d_));break;case "padlx":s._axes[t].push(()=>s._gamepads.getAxis(e.pad,df));break;case "padly":s._axes[t].push(()=>s._gamepads.getAxis(e.pad,dp));break;default:throw Error("Unknown axis")}};s(this,e.positive,1,e.positiveKey),(e.negativeKey||e.negative!==e.positive)&&s(this,e.negative,-1,e.negativeKey);}isPressed(e){if(!this._actions[e])return false;let t=this._actions[e].length;for(let i=0;i<t;++i){let t=this._actions[e][i];switch(t.type){case hh:if(this._keyboard){let e=t.keys.length;for(let i=0;i<e;i++)if(this._keyboard.isPressed(t.keys[i]))return true}break;case hl:if(this._mouse&&this._mouse.isPressed(t.button))return true;break;case hc:if(this._gamepads&&this._gamepads.isPressed(t.pad,t.button))return true}}return false}wasPressed(e){if(!this._actions[e])return false;let t=this._actions[e].length;for(let i=0;i<t;++i){let t=this._actions[e][i];switch(t.type){case hh:if(this._keyboard){let e=t.keys.length;for(let i=0;i<e;i++)if(this._keyboard.wasPressed(t.keys[i]))return true}break;case hl:if(this._mouse&&this._mouse.wasPressed(t.button))return true;break;case hc:if(this._gamepads&&this._gamepads.wasPressed(t.pad,t.button))return true}}return false}getAxis(e){let t=0;if(this._axes[e]){let i=this._axes[e].length;for(let s=0;s<i;s++)if("function"==typeof this._axes[e][s]){let i=this._axes[e][s]();Math.abs(i)>Math.abs(t)&&(t=i);}else this._axesValues[e]&&Math.abs(this._axesValues[e][s])>Math.abs(t)&&(t=this._axesValues[e][s]);}return t}_enableMouse(){if(this._mouse=new dN,!this._element)throw Error("Controller must be attached to an Element");this._mouse.attach(this._element);}_enableKeyboard(){if(this._keyboard=new dR,!this._element)throw Error("Controller must be attached to an Element");this._keyboard.attach(this._element);}}let dB=Object.freeze([]),dU=function(){return dB};"undefined"!=typeof navigator&&(dU=(navigator.getGamepads||navigator.webkitGetGamepads||dU).bind(navigator));let dk={PAD_FACE_1:c5,PAD_FACE_2:c8,PAD_FACE_3:c6,PAD_FACE_4:c9,PAD_L_SHOULDER_1:c7,PAD_R_SHOULDER_1:de,PAD_L_SHOULDER_2:dt,PAD_R_SHOULDER_2:di,PAD_SELECT:ds,PAD_START:dr,PAD_L_STICK_BUTTON:da,PAD_R_STICK_BUTTON:dn,PAD_UP:dl,PAD_DOWN:dh,PAD_LEFT:dc,PAD_RIGHT:dd,PAD_VENDOR:du,XRPAD_TRIGGER:dT,XRPAD_SQUEEZE:dE,XRPAD_TOUCHPAD_BUTTON:dx,XRPAD_STICK_BUTTON:dA,XRPAD_A:db,XRPAD_B:dw},dV={PAD_L_STICK_X:df,PAD_L_STICK_Y:dp,PAD_R_STICK_X:dm,PAD_R_STICK_Y:d_,XRPAD_TOUCHPAD_X:dg,XRPAD_TOUCHPAD_Y:dv,XRPAD_STICK_X:dS,XRPAD_STICK_Y:dy},dz={DEFAULT:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]},DEFAULT_DUAL:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],synthesizedButtons:{PAD_UP:{axis:0,min:0,max:1},PAD_DOWN:{axis:0,min:-1,max:0},PAD_LEFT:{axis:0,min:-1,max:0},PAD_RIGHT:{axis:0,min:0,max:1}}},PS3:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_4","PAD_FACE_3","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],mapping:"standard"},DEFAULT_XR:{buttons:["XRPAD_TRIGGER","XRPAD_SQUEEZE","XRPAD_TOUCHPAD_BUTTON","XRPAD_STICK_BUTTON","XRPAD_A","XRPAD_B"],axes:["XRPAD_TOUCHPAD_X","XRPAD_TOUCHPAD_Y","XRPAD_STICK_X","XRPAD_STICK_Y"],mapping:"xr-standard"}},dG={"Product: 0268":"PS3"},dH={};function dW(e){let t=dH[e.id];if(t)return t;for(let t in dG)if(-1!==e.id.indexOf(t)){let i=dG[t];if(!e.mapping){let e=dz[`RAW_${i}`];if(e)return e}return dz[i]}if("xr-standard"===e.mapping)return dz.DEFAULT_XR;let i=dz.DEFAULT,s=e.buttons.length<i.buttons.length?dz.DEFAULT_DUAL:i;return s.mapping=e.mapping,s}let dX=.25;class dY{constructor(e,t){this.value=0,this.pressed=false,this.touched=false,this.wasPressed=false,this.wasReleased=false,this.wasTouched=false,"number"==typeof e?(this.value=e,this.pressed=1===e,this.touched=e>0):(this.value=e.value,this.pressed=e.pressed,this.touched=e.touched??e.value>0),t&&("number"==typeof t?(this.wasPressed=1!==t&&this.pressed,this.wasReleased=1===t&&!this.pressed,this.wasTouched=0===t&&this.touched):(this.wasPressed=!t.pressed&&this.pressed,this.wasReleased=t.pressed&&!this.pressed,this.wasTouched=!(t.touched??t.value>0)&&this.touched));}update(e){let{value:t,pressed:i}=e,s=e.touched??t>0;this.wasPressed=!this.pressed&&i,this.wasReleased=this.pressed&&!i,this.wasTouched=!this.touched&&s,this.value=t,this.pressed=i,this.touched=s;}}let dq=Object.freeze(new dY(0));class d${constructor(e,t){this._compiledMapping={buttons:[],axes:[]},this.id=e.id,this.index=e.index,this._buttons=e.buttons.map(e=>new dY(e)),this._axes=[...e.axes],this._previousAxes=[...e.axes],this.mapping=t.mapping,this.map=t,this.hand=e.hand||"none",this.pad=e,this._compileMapping();}get connected(){return this.pad.connected}_compileMapping(){let{axes:e,buttons:t}=this._compiledMapping;e.length=0,t.length=0,this.map.axes&&this.map.axes.forEach((t,i)=>{e[dV[t]]=()=>this.pad.axes[i]||0;});for(let t=0,i=e.length;t<i;t++)e[t]||(e[t]=()=>0);let i=this.map.buttons;i&&i.forEach((e,i)=>{t[dk[e]]=()=>this._buttons[i]||dq;});let s=this.map.synthesizedButtons;s&&Object.entries(s).forEach(e=>{let{axis:i,max:s,min:r}=e[1];t[dk[e[0]]]=()=>new dY(Math.abs(eA.clamp(this._axes[i]??0,r,s)),Math.abs(eA.clamp(this._previousAxes[i]??0,r,s)));});for(let e=0,i=t.length;e<i;e++)t[e]||(t[e]=()=>dq);}update(e){this.pad=e;let t=this._previousAxes,i=this._axes;t.length=0,t.push(...i),i.length=0,i.push(...e.axes);let s=this._buttons;for(let t=0,i=s.length;t<i;t++)s[t].update(e.buttons[t]);return this}updateMap(e){e.mapping="custom",dH[this.id]=e,this.map=e,this.mapping="custom",this._compileMapping();}resetMap(){if(dH[this.id]){delete dH[this.id];let e=dW(this.pad);this.map=e,this.mapping=e.mapping,this._compileMapping();}}get axes(){return this._compiledMapping.axes.map(e=>e())}get buttons(){return this._compiledMapping.buttons.map(e=>e())}async pulse(e,t,i){let s=this.pad.vibrationActuator?[this.pad.vibrationActuator]:this.pad.hapticActuators||dB;if(s.length){let r=i?.startDelay??0,a=i?.strongMagnitude??e,n=i?.weakMagnitude??e;return (await Promise.all(s.map(async i=>{if(!i)return true;if(i.playEffect)return i.playEffect(i.type,{duration:t,startDelay:r,strongMagnitude:a,weakMagnitude:n});if(i.pulse)return await new Promise(e=>{setTimeout(e,r);}),i.pulse(e,t);return false}))).some(e=>true===e||"complete"===e)}return false}getButton(e){let t=this._compiledMapping.buttons[e];return t?t():dq}isPressed(e){return this.getButton(e).pressed}wasPressed(e){return this.getButton(e).wasPressed}wasReleased(e){return this.getButton(e).wasReleased}isTouched(e){return this.getButton(e).touched}wasTouched(e){return this.getButton(e).wasTouched}getValue(e){return this.getButton(e).value}getAxis(e){let t=this.axes[e];return t&&Math.abs(t)>dX?t:0}}class dj extends eo{static{this.EVENT_GAMEPADCONNECTED="gamepadconnected";}static{this.EVENT_GAMEPADDISCONNECTED="gamepaddisconnected";}constructor(){super(),this.gamepadsSupported=ee.gamepads,this.current=[],this._previous=[],this._ongamepadconnectedHandler=this._ongamepadconnected.bind(this),this._ongamepaddisconnectedHandler=this._ongamepaddisconnected.bind(this),window.addEventListener("gamepadconnected",this._ongamepadconnectedHandler,false),window.addEventListener("gamepaddisconnected",this._ongamepaddisconnectedHandler,false),this.poll();}set deadZone(e){dX=e;}get deadZone(){return dX}get previous(){let e=this.current;for(let t=0,i=e.length;t<i;t++){let i=e[t]._buttons;this._previous[t]||(this._previous[t]=[]);for(let e=0,s=i.length;e<s;e++){let s=i[t];this.previous[t][e]=!!s&&(!s.wasPressed&&s.pressed||s.wasReleased);}}return this._previous.length=this.current.length,this._previous}_ongamepadconnected(e){let t=new d$(e.gamepad,this.getMap(e.gamepad)),i=this.current,s=i.findIndex(e=>e.index===t.index);for(;-1!==s;)i.splice(s,1),s=i.findIndex(e=>e.index===t.index);i.push(t),this.fire("gamepadconnected",t);}_ongamepaddisconnected(e){let t=this.current,i=t.findIndex(t=>t.index===e.gamepad.index);-1!==i&&(this.fire("gamepaddisconnected",t[i]),t.splice(i,1));}update(){this.poll();}poll(e=[]){e.length>0&&(e.length=0);let t=dU();for(let i=0,s=t.length;i<s;i++)if(t[i]){let s=this.findByIndex(t[i].index);if(s)e.push(s.update(t[i]));else {let s=new d$(t[i],this.getMap(t[i]));this.current.push(s),e.push(s);}}return e}destroy(){window.removeEventListener("gamepadconnected",this._ongamepadconnectedHandler,false),window.removeEventListener("gamepaddisconnected",this._ongamepaddisconnectedHandler,false);}getMap(e){return dW(e)}isPressed(e,t){return this.current[e]?.isPressed(t)||false}wasPressed(e,t){return this.current[e]?.wasPressed(t)||false}wasReleased(e,t){return this.current[e]?.wasReleased(t)||false}getAxis(e,t){return this.current[e]?.getAxis(t)||0}pulse(e,t,i,s){let r=this.current[e];return r?r.pulse(t,i,s):Promise.resolve(false)}pulseAll(e,t,i){return Promise.all(this.current.map(s=>s.pulse(e,t,i)))}findById(e){return this.current.find(t=>t&&t.id===e)||null}findByIndex(e){return this.current.find(t=>t&&t.index===e)||null}}function dK(e){let t=0,i=0,s=e.target;for(;!(s instanceof HTMLElement)&&s;)s=s.parentNode;for(;s;)t+=s.offsetLeft-s.scrollLeft,i+=s.offsetTop-s.scrollTop,s=s.offsetParent;return {x:e.pageX-t,y:e.pageY-i}}class dZ{constructor(e){let t=dK(e);this.id=e.identifier,this.x=t.x,this.y=t.y,this.target=e.target,this.touch=e;}}class dQ{constructor(e,t){this.touches=[],this.changedTouches=[],this.element=t.target,this.event=t,this.touches=Array.from(t.touches).map(e=>new dZ(e)),this.changedTouches=Array.from(t.changedTouches).map(e=>new dZ(e));}getTouchById(e,t){return t.find(t=>t.id===e)||null}}class dJ extends eo{static{this.EVENT_TOUCHSTART="touchstart";}static{this.EVENT_TOUCHEND="touchend";}static{this.EVENT_TOUCHMOVE="touchmove";}static{this.EVENT_TOUCHCANCEL="touchcancel";}constructor(e){super(),this._element=null,this._startHandler=this._handleTouchStart.bind(this),this._endHandler=this._handleTouchEnd.bind(this),this._moveHandler=this._handleTouchMove.bind(this),this._cancelHandler=this._handleTouchCancel.bind(this),this.attach(e);}attach(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("touchstart",this._startHandler,false),this._element.addEventListener("touchend",this._endHandler,false),this._element.addEventListener("touchmove",this._moveHandler,false),this._element.addEventListener("touchcancel",this._cancelHandler,false);}detach(){this._element&&(this._element.removeEventListener("touchstart",this._startHandler,false),this._element.removeEventListener("touchend",this._endHandler,false),this._element.removeEventListener("touchmove",this._moveHandler,false),this._element.removeEventListener("touchcancel",this._cancelHandler,false)),this._element=null;}_handleTouchStart(e){this.fire("touchstart",new dQ(this,e));}_handleTouchEnd(e){this.fire("touchend",new dQ(this,e));}_handleTouchMove(e){e.preventDefault(),this.fire("touchmove",new dQ(this,e));}_handleTouchCancel(e){this.fire("touchcancel",new dQ(this,e));}}class d0{static{this.ContentType={AAC:"audio/aac",BASIS:"image/basis",BIN:"application/octet-stream",DDS:"image/dds",FORM_URLENCODED:"application/x-www-form-urlencoded",GIF:"image/gif",GLB:"model/gltf-binary",JPEG:"image/jpeg",JSON:"application/json",MP3:"audio/mpeg",MP4:"audio/mp4",OGG:"audio/ogg",OPUS:'audio/ogg; codecs="opus"',PNG:"image/png",TEXT:"text/plain",WAV:"audio/x-wav",XML:"application/xml"};}static{this.ResponseType={TEXT:"text",ARRAY_BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json"};}static{this.binaryExtensions=[".model",".wav",".ogg",".mp3",".mp4",".m4a",".aac",".dds",".basis",".glb",".opus"];}static{this.retryDelay=100;}get(e,t,i){"function"==typeof t&&(i=t,t={});let s=this.request("GET",e,t,i),{progress:r}=t;if(r){let e=e=>{e.lengthComputable&&r.fire("progress",e.loaded,e.total);},t=i=>{e(i),s.removeEventListener("loadstart",e),s.removeEventListener("progress",e),s.removeEventListener("loadend",t);};s.addEventListener("loadstart",e),s.addEventListener("progress",e),s.addEventListener("loadend",t);}return s}post(e,t,i,s){return "function"==typeof i&&(s=i,i={}),i.postdata=t,this.request("POST",e,i,s)}put(e,t,i,s){return "function"==typeof i&&(s=i,i={}),i.postdata=t,this.request("PUT",e,i,s)}del(e,t,i){return "function"==typeof t&&(i=t,t={}),this.request("DELETE",e,t,i)}request(e,t,i,s){let r,a,n,o=false;if("function"==typeof i&&(s=i,i={}),i.retry&&(i=Object.assign({retries:0,maxRetries:5},i)),i.callback=s,null==i.async&&(i.async=true),null==i.headers&&(i.headers={}),null!=i.postdata)if(i.postdata instanceof Document)n=i.postdata;else if(i.postdata instanceof FormData)n=i.postdata;else if(i.postdata instanceof Object){let e=i.headers["Content-Type"];switch(void 0===e&&(i.headers["Content-Type"]=d0.ContentType.FORM_URLENCODED,e=i.headers["Content-Type"]),e){case d0.ContentType.FORM_URLENCODED:{n="";let e=true;for(let t in i.postdata)if(i.postdata.hasOwnProperty(t)){e?e=false:n+="&";let s=encodeURIComponent(t),r=encodeURIComponent(i.postdata[t]);n+=`${s}=${r}`;}break}default:case d0.ContentType.JSON:null==e&&(i.headers["Content-Type"]=d0.ContentType.JSON),n=JSON.stringify(i.postdata);}}else n=i.postdata;if(false===i.cache){let e=em();(r=new ev(t)).query?r.query=`${r.query}&ts=${e}`:r.query=`ts=${e}`,t=r.toString();}i.query&&(a=G((r=new ev(t)).getQuery(),i.query),r.setQuery(a),t=r.toString());let l=new XMLHttpRequest;for(let s in l.open(e,t,i.async),l.withCredentials=void 0!==i.withCredentials&&i.withCredentials,l.responseType=i.responseType||this._guessResponseType(t),i.headers)i.headers.hasOwnProperty(s)&&l.setRequestHeader(s,i.headers[s]);l.onreadystatechange=()=>{this._onReadyStateChange(e,t,i,l);},l.onerror=()=>{this._onError(e,t,i,l),o=true;};try{l.send(n);}catch(e){o||i.error(l.status,l,e);}return l}_guessResponseType(e){let t=new ev(e),i=W.getExtension(t.path).toLowerCase();return d0.binaryExtensions.indexOf(i)>=0?d0.ResponseType.ARRAY_BUFFER:".json"===i?d0.ResponseType.JSON:".xml"===i?d0.ResponseType.DOCUMENT:d0.ResponseType.TEXT}_isBinaryContentType(e){return [d0.ContentType.BASIS,d0.ContentType.BIN,d0.ContentType.DDS,d0.ContentType.GLB,d0.ContentType.MP3,d0.ContentType.MP4,d0.ContentType.OGG,d0.ContentType.OPUS,d0.ContentType.WAV].indexOf(e)>=0}_isBinaryResponseType(e){return e===d0.ResponseType.ARRAY_BUFFER||e===d0.ResponseType.BLOB||e===d0.ResponseType.JSON}_onReadyStateChange(e,t,i,s){if(4===s.readyState)switch(s.status){case 0:s.responseURL&&s.responseURL.startsWith("file:///")?this._onSuccess(e,t,i,s):this._onError(e,t,i,s);break;case 200:case 201:case 206:case 304:this._onSuccess(e,t,i,s);break;default:this._onError(e,t,i,s);}}_onSuccess(e,t,i,s){let r,a,n=s.getResponseHeader("Content-Type");n&&(a=n.split(";")[0].trim());try{r=this._isBinaryContentType(a)||this._isBinaryResponseType(s.responseType)?s.response:a===d0.ContentType.JSON||t.split("?")[0].endsWith(".json")?JSON.parse(s.responseText):s.responseType===d0.ResponseType.DOCUMENT||a===d0.ContentType.XML?s.responseXML:s.responseText,i.callback(null,r);}catch(e){i.callback(e);}}_onError(e,t,i,s){i.retrying||(i.retry&&i.retries<i.maxRetries?(i.retries++,i.retrying=true,setTimeout(()=>{i.retrying=false,this.request(e,t,i,i.callback);},eA.clamp(Math.pow(2,i.retries)*d0.retryDelay,0,i.maxRetryDelay||5e3))):i.callback(0===s.status?"Network error":s.status,null));}}let d1=new d0,d2="linear",d3="inverse",d4="exponential";class d5{constructor(e){this.position=new eM,this.orientation=new eG,this._manager=e;}getPosition(){return this.position}setPosition(e){this.position.copy(e);let t=this.listener;t&&("positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z));}setOrientation(e){this.orientation.copy(e);let t=this.listener;if(t){let i=e.data;"forwardX"in t?(t.forwardX.value=-i[8],t.forwardY.value=-i[9],t.forwardZ.value=-i[10],t.upX.value=i[4],t.upY.value=i[5],t.upZ.value=i[6]):t.setOrientation&&t.setOrientation(-i[8],-i[9],-i[10],i[4],i[5],i[6]);}}getOrientation(){return this.orientation}get listener(){let e=this._manager.context;return e?e.listener:null}}let d8="running",d6=["click","touchstart","mousedown"];class d9 extends eo{constructor(){super(),this._context=null,this.AudioContext="undefined"!=typeof AudioContext&&AudioContext||"undefined"!=typeof webkitAudioContext&&webkitAudioContext,this.AudioContext,this._unlockHandlerFunc=this._unlockHandler.bind(this),this._userSuspended=false,this.listener=new d5(this),this._volume=1;}set volume(e){e=eA.clamp(e,0,1),this._volume=e,this.fire("volumechange",e);}get volume(){return this._volume}get suspended(){return this._userSuspended}get context(){return !this._context&&this.AudioContext&&(this._context=new this.AudioContext,this._context.state!==d8&&this._registerUnlockListeners()),this._context}suspend(){!this._userSuspended&&(this._userSuspended=true,this._context&&this._context.state===d8&&this._suspend());}resume(){this._userSuspended&&(this._userSuspended=false,this._context&&this._context.state!==d8&&this._resume());}destroy(){this.fire("destroy"),this._context&&(this._removeUnlockListeners(),this._context?.close(),this._context=null);}_resume(){this._context.resume().then(()=>{let e=this._context.createBufferSource();e.buffer=this._context.createBuffer(1,1,this._context.sampleRate),e.connect(this._context.destination),e.start(0),e.onended=t=>{e.disconnect(0),this.fire("resume");};},e=>{}).catch(e=>{});}_suspend(){this._context.suspend().then(()=>{this.fire("suspend");},e=>{}).catch(e=>{});}_unlockHandler(){this._removeUnlockListeners(),this._userSuspended||this._context.state===d8||this._resume();}_registerUnlockListeners(){d6.forEach(e=>{window.addEventListener(e,this._unlockHandlerFunc,false);});}_removeUnlockListeners(){d6.forEach(e=>{window.removeEventListener(e,this._unlockHandlerFunc,false);});}}class d7{constructor(e){e instanceof Audio?this.audio=e:this.buffer=e;}get duration(){let e=0;return this.buffer?e=this.buffer.duration:this.audio&&(e=this.audio.duration),e||0}}function ue(){return "undefined"!=typeof AudioContext||"undefined"!=typeof webkitAudioContext}class ut extends eo{static{this.EVENT_PLAY="play";}static{this.EVENT_PAUSE="pause";}static{this.EVENT_RESUME="resume";}static{this.EVENT_STOP="stop";}static{this.EVENT_END="end";}constructor(e,t,i){super(),this.source=null,this._manager=e,this._volume=void 0!==i.volume?eA.clamp(Number(i.volume)||0,0,1):1,this._pitch=void 0!==i.pitch?Math.max(.01,Number(i.pitch)||0):1,this._loop=!!(void 0!==i.loop&&i.loop),this._sound=t,this._state=2,this._suspended=false,this._suspendEndEvent=0,this._suspendInstanceEvents=false,this._playWhenLoaded=true,this._startTime=Math.max(0,Number(i.startTime)||0),this._duration=Math.max(0,Number(i.duration)||0),this._startOffset=null,this._onPlayCallback=i.onPlay,this._onPauseCallback=i.onPause,this._onResumeCallback=i.onResume,this._onStopCallback=i.onStop,this._onEndCallback=i.onEnd,ue()?(this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._inputNode=null,this._connectorNode=null,this._firstNode=null,this._lastNode=null,this._waitingContextSuspension=false,this._initializeNodes(),this._endedHandler=this._onEnded.bind(this)):(this._isReady=false,this._loadedMetadataHandler=this._onLoadedMetadata.bind(this),this._timeUpdateHandler=this._onTimeUpdate.bind(this),this._endedHandler=this._onEnded.bind(this),this._createSource());}set currentTime(e){if(!(e<0))if(0===this._state){let t=this._suspendInstanceEvents;this._suspendInstanceEvents=true,this.stop(),this._startOffset=e,this.play(),this._suspendInstanceEvents=t;}else this._startOffset=e,this._currentTime=e;}get currentTime(){return null!==this._startOffset?this._startOffset:1===this._state?this._currentTime:2!==this._state&&this.source?(this._updateCurrentTime(),this._currentTime):0}set duration(e){this._duration=Math.max(0,Number(e)||0);let t=0===this._state;this.stop(),t&&this.play();}get duration(){if(!this._sound)return 0;if(this._duration)return this._duration%this._sound.duration||0;return this._sound.duration}get isPaused(){return 1===this._state}get isPlaying(){return 0===this._state}get isStopped(){return 2===this._state}get isSuspended(){return this._suspended}set loop(e){this._loop=!!e,this.source&&(this.source.loop=this._loop);}get loop(){return this._loop}set pitch(e){this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime,this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch);}get pitch(){return this._pitch}set sound(e){this._sound=e,2!==this._state?this.stop():this._createSource();}get sound(){return this._sound}set startTime(e){this._startTime=Math.max(0,Number(e)||0);let t=0===this._state;this.stop(),t&&this.play();}get startTime(){return this._startTime}set volume(e){e=eA.clamp(e,0,1),this._volume=e,this.gain&&(this.gain.gain.value=e*this._manager.volume);}get volume(){return this._volume}_onPlay(){this.fire("play"),this._onPlayCallback&&this._onPlayCallback(this);}_onPause(){this.fire("pause"),this._onPauseCallback&&this._onPauseCallback(this);}_onResume(){this.fire("resume"),this._onResumeCallback&&this._onResumeCallback(this);}_onStop(){this.fire("stop"),this._onStopCallback&&this._onStopCallback(this);}_onEnded(){if(this._suspendEndEvent>0)return void this._suspendEndEvent--;this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop();}_onManagerVolumeChange(){this.volume=this._volume;}_onManagerSuspend(){0!==this._state||this._suspended||(this._suspended=true,this.pause());}_onManagerResume(){this._suspended&&(this._suspended=false,this.resume());}_initializeNodes(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination);}play(){return 2!==this._state&&this.stop(),this._state=0,this._playWhenLoaded=false,!this._waitingContextSuspension&&(this._manager.suspended?(this._manager.once("resume",this._playAudioImmediate,this),this._waitingContextSuspension=true,false):(this._playAudioImmediate(),true))}_playAudioImmediate(){if(this._waitingContextSuspension=false,0!==this._state)return;this.source||this._createSource();let e=this._startOffset%this.duration||0;e=(this._startTime+e)%this._sound.duration||0,this._startOffset=null,this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._suspendInstanceEvents||this._onPlay();}pause(){return this._playWhenLoaded=false,0===this._state&&(this._state=1,!!this._waitingContextSuspension||(this._updateCurrentTime(),this._suspendEndEvent++,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),true))}resume(){if(1!==this._state)return false;let e=this.currentTime;if(this._state=0,this._waitingContextSuspension)return true;(this.source||this._createSource(),null!==this._startOffset)&&(e=this._startOffset%this.duration||0,e=(this._startTime+e)%this._sound.duration||0,this._startOffset=null);return this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._playWhenLoaded=false,this._suspendInstanceEvents||this._onResume(),true}stop(){if(this._playWhenLoaded=false,2===this._state)return false;let e=0===this._state;return this._state=2,!!this._waitingContextSuspension||(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._startOffset=null,this._suspendEndEvent++,e&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop(),true)}setExternalNodes(e,t){if(!e)return;t||(t=e);let i=this._manager.context.destination;this._firstNode!==e&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(i),this._firstNode=e,this._connectorNode.connect(e)),this._lastNode!==t&&(this._lastNode&&this._lastNode.disconnect(i),this._lastNode=t,this._lastNode.connect(i));}clearExternalNodes(){let e=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(e),this._lastNode=null),this._connectorNode.connect(e);}getExternalNodes(){return [this._firstNode,this._lastNode]}_createSource(){if(!this._sound)return null;let e=this._manager.context;this._sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=this._startTime%this.source.buffer.duration||0,this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,(this._startTime+this._duration)%this.source.buffer.duration||0)));return this.source}_updateCurrentTime(){this._currentTime=((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset)%this.duration||0;}_onManagerDestroy(){this.source&&0===this._state&&(this.source.stop(0),this.source=null);}}ue()||(Object.assign(ut.prototype,{play:function(){return 2!==this._state&&this.stop(),(!!this.source||!!this._createSource())&&(this.volume=this._volume,this.pitch=this._pitch,this.loop=this._loop,this.source.play(),this._state=0,this._playWhenLoaded=false,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._manager.suspended&&this._onManagerSuspend(),this._suspendInstanceEvents||this._onPlay(),true)},pause:function(){return !!this.source&&0===this._state&&(this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=false,this._state=1,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),true)},resume:function(){return !!this.source&&1===this._state&&(this._state=0,this._playWhenLoaded=false,this.source.paused&&(this.source.play(),this._suspendInstanceEvents||this._onResume()),true)},stop:function(){return !!this.source&&2!==this._state&&(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=false,this._state=2,this._startOffset=null,this._suspendInstanceEvents||this._onStop(),true)},setExternalNodes:function(){},clearExternalNodes:function(){},getExternalNodes:function(){return [null,null]},_onLoadedMetadata:function(){this.source.removeEventListener("loadedmetadata",this._loadedMetadataHandler),this._isReady=true;let e=this._startOffset%this.duration||0;e=(this._startTime+e)%this._sound.duration||0,this._startOffset=null,this.source.currentTime=e;},_createSource:function(){return this._sound&&this._sound.audio&&(this._isReady=false,this.source=this._sound.audio.cloneNode(true),this.source.addEventListener("loadedmetadata",this._loadedMetadataHandler),this.source.addEventListener("timeupdate",this._timeUpdateHandler),this.source.onended=this._endedHandler),this.source},_onTimeUpdate:function(){this._duration&&this.source.currentTime>((this._startTime+this._duration)%this.source.duration||0)&&(this.loop?this.source.currentTime=this._startTime%this.source.duration||0:(this.source.removeEventListener("timeupdate",this._timeUpdateHandler),this.source.pause(),this._onEnded()));},_onManagerDestroy:function(){this.source&&this.source.pause();}}),Object.defineProperty(ut.prototype,"volume",{get:function(){return this._volume},set:function(e){e=eA.clamp(e,0,1),this._volume=e,this.source&&(this.source.volume=e*this._manager.volume);}}),Object.defineProperty(ut.prototype,"pitch",{get:function(){return this._pitch},set:function(e){this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate=this._pitch);}}),Object.defineProperty(ut.prototype,"sound",{get:function(){return this._sound},set:function(e){this.stop(),this._sound=e;}}),Object.defineProperty(ut.prototype,"currentTime",{get:function(){return null!==this._startOffset?this._startOffset:2!==this._state&&this.source?this.source.currentTime-this._startTime:0},set:function(e){!(e<0)&&(this._startOffset=e,this.source&&this._isReady)&&(this.source.currentTime=(this._startTime+(e%this.duration||0))%this._sound.duration||0,this._startOffset=null);}}));class ui extends ut{constructor(e,t,i={}){super(e,t,i),this._position=new eM,this._velocity=new eM,i.position&&(this.position=i.position),this.maxDistance=void 0!==i.maxDistance?Number(i.maxDistance):1e4,this.refDistance=void 0!==i.refDistance?Number(i.refDistance):1,this.rollOffFactor=void 0!==i.rollOffFactor?Number(i.rollOffFactor):1,this.distanceModel=void 0!==i.distanceModel?i.distanceModel:d2;}_initializeNodes(){this.gain=this._manager.context.createGain(),this.panner=this._manager.context.createPanner(),this.panner.connect(this.gain),this._inputNode=this.panner,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination);}set position(e){this._position.copy(e);let t=this.panner;"positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z);}get position(){return this._position}set velocity(e){this._velocity.copy(e);}get velocity(){return this._velocity}set maxDistance(e){this.panner.maxDistance=e;}get maxDistance(){return this.panner.maxDistance}set refDistance(e){this.panner.refDistance=e;}get refDistance(){return this.panner.refDistance}set rollOffFactor(e){this.panner.rolloffFactor=e;}get rollOffFactor(){return this.panner.rolloffFactor}set distanceModel(e){this.panner.distanceModel=e;}get distanceModel(){return this.panner.distanceModel}}if(!ue()){let e=new eM,t=function(t,i,s,r,a,n){let o=(e=e.sub2(t,i)).length();if(o<s)return 1;if(o>r)return 0;let l=0;return n===d2?l=1-a*(o-s)/(r-s):n===d3?l=s/(s+a*(o-s)):n===d4&&(l=Math.pow(o/s,-a)),eA.clamp(l,0,1)};Object.defineProperty(ui.prototype,"position",{get:function(){return this._position},set:function(e){if(this._position.copy(e),this.source){let e=t(this._manager.listener.getPosition(),this._position,this.refDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),i=this.volume;this.source.volume=i*e*this._manager.volume;}}}),Object.defineProperty(ui.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(e){this._maxDistance=e;}}),Object.defineProperty(ui.prototype,"refDistance",{get:function(){return this._refDistance},set:function(e){this._refDistance=e;}}),Object.defineProperty(ui.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(e){this._rollOffFactor=e;}}),Object.defineProperty(ui.prototype,"distanceModel",{get:function(){return this._distanceModel},set:function(e){this._distanceModel=e;}});}let us=0,ur=1,ua=2,un=3,uo=4,ul=5,uh=6,uc=7,ud=8,uu=9,uf=10,up={[us]:"SUBTRACTIVE",[ur]:"ADDITIVE",[ua]:"NORMAL",[un]:"NONE",[uo]:"PREMULTIPLIED",[ul]:"MULTIPLICATIVE",[uh]:"ADDITIVEALPHA",[uc]:"MULTIPLICATIVE2X",[ud]:"SCREEN",[uu]:"MIN",[uf]:"MAX"},um="none",u_="linear",ug="exp",uv="exp2",uS=0,uy=2,ux={[uS]:"NONE",[uy]:"SCHLICK"},uT=0,uE=1,uA=15,ub=0,uw=1,uC=2,uP=3,uL=4,uI=0,uD=1,uR=uD,uM=2,uO=3,uN={[uI]:"DIRECTIONAL",[uD]:"OMNI",[uM]:"SPOT"},uF=100,uB=0,uU=1,uk=2,uV=3,uz={[uB]:"PUNCTUAL",[uU]:"RECT",[uk]:"DISK",[uV]:"SPHERE"},uG=0,uH=1,uW={[uG]:"LINEAR",[uH]:"INVERSESQUARED"},uX=0,uY=0,uq=2,u$=2,uj=3,uK=3,uZ=4,uQ=4,uJ=5,u0=5,u1=6,u2=7,u3=8,u4=9,u5=new Map([[uJ,{name:"PCF1_32F",kind:"PCF1",format:ix,pcf:true}],[uX,{name:"PCF3_32F",kind:"PCF3",format:ix,pcf:true}],[uZ,{name:"PCF5_32F",kind:"PCF5",format:ix,pcf:true}],[u2,{name:"PCF1_16F",kind:"PCF1",format:sn,pcf:true}],[u3,{name:"PCF3_16F",kind:"PCF3",format:sn,pcf:true}],[u4,{name:"PCF5_16F",kind:"PCF5",format:sn,pcf:true}],[uq,{name:"VSM_16F",kind:"VSM",format:ig,vsm:true}],[uj,{name:"VSM_32F",kind:"VSM",format:iS,vsm:true}],[u1,{name:"PCSS_32F",kind:"PCSS",format:iy,pcss:true}]]),u8=1,u6=2,u9=4,u7=8,fe=255,ft=0,fi=1,fs=0,fr=1,fa=2,fn=3,fo=0,fl=1,fh=0,fc=1,fd=0,fu=1,ff=2,fp=0,fm=1,f_=0,fg=1,fv=2,fS=0,fy=1,fx={[fS]:"NONE",[fy]:"BOX"},fT="mul",fE="add",fA="screen",fb="overlay",fw="min",fC="max",fP=0,fL=1,fI={[fP]:"NONE",[fL]:"SRGB"},fD=0,fR=1,fM=2,fO=3,fN=4,fF=5,fB=6,fU=["LINEAR","FILMIC","HEJL","ACES","ACES2","NEUTRAL","NONE"],fk=0,fV=1,fz=2,fG={[fk]:"NONE",[fV]:"AO",[fz]:"GLOSSDEPENDENT"},fH="none",fW="envAtlas",fX="envAtlasHQ",fY="cubeMap",fq="sphereMap",f$={[fH]:"NONE",[fW]:"ENVATLAS",[fX]:"ENVATLASHQ",[fY]:"CUBEMAP",[fq]:"SPHEREMAP"},fj="ambientSH",fK="envAtlas",fZ="constant",fQ={[fj]:"AMBIENTSH",[fK]:"ENVALATLAS",[fZ]:"CONSTANT"},fJ=1,f0=2,f1=4,f2=8,f3=16,f4=32,f5=64,f8=128,f6=256,f9=512,f7=1024,pe=2048,pt=4096,pi=8192,ps=16384,pr=0,pa=1,pn=2,po=1,pl=2,ph=4,pc=0,pd=1,pu=2,pf=3,pp="forward",pm="debug_albedo",p_="debug_world_normal",pg="debug_opacity",pv="debug_specularity",pS="debug_gloss",py="debug_metalness",px="debug_ao",pT="debug_emission",pE="debug_lighting",pA="debug_uv0",pb=0,pw=1,pC=2,pP={[pb]:"SIMPLE",[pw]:"SLICED",[pC]:"TILED"},pL=0,pI=1,pD=0,pR=1,pM=2,pO=0,pN=1,pF=2,pB=3,pU=4,pk=5,pV=0,pz=1,pG=0,pH=1,pW="infinite",pX="box",pY="dome",pq="none",p$="bayer8",pj="bluenoise",pK="ignnoise",pZ={[pq]:"NONE",[p$]:"BAYER8",[pj]:"BLUENOISE",[pK]:"IGNNOISE"},pQ="prerender",pJ="postrender",p0="prerender:layer",p1="postrender:layer",p2="precull",p3="postcull",p4="cull:end";class p5{constructor(e,t,i){this.uniformFormats=[],this.bindGroupFormats=[],this.uniformFormats[aH]=e,this.bindGroupFormats[aH]=t,this.vertexFormat=i;}hasUniform(e){for(let t=0;t<this.uniformFormats.length;t++){let i=this.uniformFormats[t];if(i?.get(e))return true}return false}hasTexture(e){for(let t=0;t<this.bindGroupFormats.length;t++){let i=this.bindGroupFormats[t];if(i?.getTexture(e))return true}return false}getVertexElement(e){return this.vertexFormat?.elements.find(t=>t.name===e)}generateKey(e){let t=JSON.stringify(this.uniformFormats)+JSON.stringify(this.bindGroupFormats);return e.isWebGPU&&(t+=this.vertexFormat?.shaderProcessingHashString),t}}let p8=new ne;function p6(e){return p8.get(e)}class p9{static definesHash(e){return nE(JSON.stringify(Array.from(e).sort((e,t)=>e[0]>t[0]?1:-1)))}}let p7=new ne;class me{constructor(e,t,i={}){this.defines=new Map,this.name=e,this.index=t,Object.assign(this,i),this.buildShaderDefines();}buildShaderDefines(){let e;this.isShadow?e="SHADOW":this.isForward?e="FORWARD":this.index===pf&&(e="PICK"),this.defines.set(`${e}_PASS`,""),this.defines.set(`${this.name.toUpperCase()}_PASS`,"");}}class mt{constructor(){this.passesNamed=new Map,this.passesIndexed=[],this.nextIndex=0;let e=(e,t,i)=>{this.allocate(e,i);};e("forward",pc,{isForward:true}),e("prepass"),e("shadow"),e("pick");}static get(e){return p7.get(e,()=>new mt)}allocate(e,t){let i=this.passesNamed.get(e);return void 0===i&&(i=new me(e,this.nextIndex,t),this.passesNamed.set(i.name,i),this.passesIndexed[i.index]=i,this.nextIndex++),i}getByIndex(e){return this.passesIndexed[e]}getByName(e){return this.passesNamed.get(e)}}class mi extends Map{set(e,t){return this.has(e)&&this.get(e)===t||this.markDirty(),super.set(e,t)}add(e){for(let[t,i]of Object.entries(e))this.set(t,i);return this}delete(e){let t=this.has(e),i=super.delete(e);return t&&i&&this.markDirty(),i}clear(){this.size>0&&this.markDirty(),super.clear();}markDirty(){this._dirty=true,this._keyDirty=true;}isDirty(){return this._dirty}resetDirty(){this._dirty=false;}get key(){return this._keyDirty&&(this._keyDirty=false,this._key=Array.from(this.entries()).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${e}=${nE(t)}`).join(",")),this._key}copy(e){for(let[t,i]of(this.clear(),e))this.set(t,i);return this}constructor(...e){super(...e),this._keyDirty=false,this._key="";}}let ms=new ne;class mr{static get(e,t=rb){let i=ms.get(e,()=>new mr);return t===rb?i.glsl:i.wgsl}get useWGSL(){return 0===this.glsl.size||this.wgsl.size>0}get key(){return `GLSL:${this.glsl.key}|WGSL:${this.wgsl.key}|API:${this.version}`}isDirty(){return this.glsl.isDirty()||this.wgsl.isDirty()}resetDirty(){this.glsl.resetDirty(),this.wgsl.resetDirty();}copy(e){return this.version=e.version,this.glsl.copy(e.glsl),this.wgsl.copy(e.wgsl),this}constructor(){this.glsl=new mi,this.wgsl=new mi,this.version="";}}class ma{static merge(...e){let t=new Map(e[0]??[]);for(let i=1;i<e.length;i++){let s=e[i];if(s)for(let[e,i]of s)t.set(e,i);}return t}}class mn extends p9{constructor(e,t){super(),this.key=e,this.shaderDefinition=t;}generateKey(e){return this.key}createShaderDefinition(e,t){return this.shaderDefinition}}class mo{static createShader(e,t){let i=p6(e),s=i.getCachedShader(t.uniqueName);if(!s){let r=e.isWebGPU&&(!!t.vertexWGSL||!!t.vertexChunk)&&(!!t.fragmentWGSL||!!t.fragmentChunk),a=mr.get(e,r?rw:rb),n=t.vertexChunk?a.get(t.vertexChunk):r?t.vertexWGSL:t.vertexGLSL,o=t.fragmentChunk?a.get(t.fragmentChunk):r?t.fragmentWGSL:t.fragmentGLSL,l=ma.merge(a,t.fragmentIncludes),h=ma.merge(a,t.vertexIncludes);s=new la(e,ls.createDefinition(e,{name:t.uniqueName,shaderLanguage:r?rw:rb,attributes:t.attributes,vertexCode:n,fragmentCode:o,useTransformFeedback:t.useTransformFeedback,vertexIncludes:h,vertexDefines:t.vertexDefines,fragmentIncludes:l,fragmentDefines:t.fragmentDefines,fragmentOutputTypes:t.fragmentOutputTypes})),i.setCachedShader(t.uniqueName,s);}return s}static getCoreDefines(e,t){let i=new Map(e.defines);return t.cameraShaderParams.defines.forEach((e,t)=>i.set(t,e)),mt.get(t.device).getByIndex(t.pass).defines.forEach((e,t)=>i.set(t,e)),i}static processShader(e,t){let i=e.definition,s=i.name??"shader",r=new mn(`${s}-id-${e.id}`,i),a="shader",n=p6(e.device);n.register(a,r);let o=n.getProgram(a,{},t);return n.unregister(a),o}static addScreenDepthChunkDefines(e,t,i){t.sceneDepthMapLinear&&i.set("SCENE_DEPTHMAP_LINEAR",""),e.textureFloatRenderable&&i.set("SCENE_DEPTHMAP_FLOAT","");}}function ml(e,t,i,s=false,r={}){}function mh(e,t,i,s,r,a=false,n={}){"boolean"==typeof a?n.useTransformFeedback=a:"object"==typeof a&&(n={...n,...a});let o=p6(e),l=o.getCachedShader(s);return l||(l=new la(e,ls.createDefinition(e,{...n,name:s,vertexCode:t,fragmentCode:i,attributes:r})),o.setCachedShader(s,l)),l}let mc={type:sy,base:0,baseVertex:0,count:4,indexed:false},md=new eF,mu=new eF,mf=new nh;class mp{constructor(e){let t=e.device;if(this.shader=e,t.supportsUniformBuffers){let i=new p5;this.shader=mo.processShader(e,i);let s=this.shader.meshUniformBufferFormat;s&&(this.uniformBuffer=new lc(t,s,false));let r=this.shader.meshBindGroupFormat;this.bindGroup=new nc(t,r);}}destroy(){this.uniformBuffer?.destroy(),this.uniformBuffer=null,this.bindGroup?.destroy(),this.bindGroup=null;}render(e,t){let i=this.shader.device;e&&(md.set(i.vx,i.vy,i.vw,i.vh),mu.set(i.sx,i.sy,i.sw,i.sh),t=t??e,i.setViewport(e.x,e.y,e.z,e.w),i.setScissor(t.x,t.y,t.z,t.w)),i.setVertexBuffer(i.quadVertexBuffer,0);let s=this.shader;if(i.setShader(s),i.supportsUniformBuffers){i.setBindGroup(aH,i.emptyBindGroup);let e=this.bindGroup;e.update(),i.setBindGroup(aW,e);let t=this.uniformBuffer;t?(t.update(mf),i.setBindGroup(aX,mf.bindGroup,mf.offsets)):i.setBindGroup(aX,i.emptyBindGroup);}i.draw(mc),e&&(i.setViewport(md.x,md.y,md.z,md.w),i.setScissor(mu.x,mu.y,mu.z,mu.w));}}class mm extends l2{constructor(e,t,i,s){super(e),this.quad=t,this.rect=i,this.scissorRect=s;}execute(){let{device:e}=this;e.setCullMode(tY),e.setDepthState(nm.NODEPTH),e.setStencilState(null,null),this.quad.render(this.rect,this.scissorRect);}}let m_=new eF;function mg(e,t,i,s,r){let a=new mp(i);s||((s=m_).x=0,s.y=0,s.z=t?t.width:e.width,s.w=t?t.height:e.height);let n=new mm(e,a,s,r);n.init(t),n.colorOps.clear=false,n.depthStencilOps.clearDepth=false,e.isWebGPU&&null===t&&e.samples>1&&(n.colorOps.store=true),n.render(),a.destroy();}class mv{constructor(e,t,i){this._aabb=new ej,this.meshInstance=null,this.origMeshInstances=e,this.dynamic=t,this.batchGroupId=i;}destroy(e,t){this.meshInstance&&(this.removeFromLayers(e,t),this.meshInstance.destroy(),this.meshInstance=null);}addToLayers(e,t){for(let i=0;i<t.length;i++){let s=e.layers.getLayerById(t[i]);s&&s.addMeshInstances([this.meshInstance]);}}removeFromLayers(e,t){for(let i=0;i<t.length;i++){let s=e.layers.getLayerById(t[i]);s&&s.removeMeshInstances([this.meshInstance]);}}updateBoundingBox(){this._aabb.copy(this.origMeshInstances[0].aabb);for(let e=1;e<this.origMeshInstances.length;e++)this._aabb.add(this.origMeshInstances[e].aabb);this.meshInstance.aabb=this._aabb,this.meshInstance._aabbVer=0;}get model(){}}class mS{constructor(e,t,i,s,r=[ub]){this._ui=false,this._sprite=false,this._obj={model:[],element:[],sprite:[],render:[]},this.id=e,this.name=t,this.dynamic=i,this.maxAabbSize=s,this.layers=r;}static{this.MODEL="model";}static{this.ELEMENT="element";}static{this.SPRITE="sprite";}static{this.RENDER="render";}}let my=new eG;class mx{constructor(e){this._dirty=true,this._rootBone=null,this._skinUpdateIndex=-1,this._updateBeforeCull=true,e&&this.initSkin(e);}set rootBone(e){this._rootBone=e;}get rootBone(){return this._rootBone}init(e,t){let i=3*t,s=Math.ceil(Math.sqrt(i)),r=Math.ceil(i/(s=eA.roundUp(s,3)));this.boneTexture=new ns(e,{width:s,height:r,format:iS,mipmaps:false,minFilter:tK,magFilter:tK,name:"skin"}),this.matrixPalette=this.boneTexture.lock({mode:s7}),this.boneTexture.unlock();}destroy(){this.boneTexture&&(this.boneTexture.destroy(),this.boneTexture=null);}resolve(e,t){this.rootBone=e;let i=this.skin,s=[];for(let r=0;r<i.boneNames.length;r++){let a=i.boneNames[r],n=e.findByName(a);n||(n=t),s.push(n);}this.bones=s;}initSkin(e){this.skin=e,this.bones=[];let t=e.inverseBindPose.length;this.init(e.device,t),this.matrices=[];for(let e=0;e<t;e++)this.matrices[e]=new eG;}uploadBones(e){this.boneTexture.upload();}_updateMatrices(e,t){if(this._skinUpdateIndex!==t){this._skinUpdateIndex=t,my.copy(e.getWorldTransform()).invert();for(let e=this.bones.length-1;e>=0;e--)this.matrices[e].mulAffine2(my,this.bones[e].getWorldTransform()),this.matrices[e].mulAffine2(this.matrices[e],this.skin.inverseBindPose[e]);}}updateMatrices(e,t){this._updateBeforeCull&&this._updateMatrices(e,t);}updateMatrixPalette(e,t){this._updateMatrices(e,t);let i=this.matrixPalette,s=this.bones.length;for(let e=0;e<s;e++){let t=this.matrices[e].data,s=12*e;i[s]=t[0],i[s+1]=t[4],i[s+2]=t[8],i[s+3]=t[12],i[s+4]=t[1],i[s+5]=t[5],i[s+6]=t[9],i[s+7]=t[13],i[s+8]=t[2],i[s+9]=t[6],i[s+10]=t[10],i[s+11]=t[14];}this.uploadBones(this.skin.device);}}class mT extends mx{constructor(e,t,i){super();let s=t.length;this.init(e,s),this.device=e,this.rootNode=i,this.bones=t;}updateMatrices(e,t){}updateMatrixPalette(e,t){let i=this.matrixPalette,s=this.bones.length;for(let e=0;e<s;e++){let t=this.bones[e].getWorldTransform().data,s=12*e;i[s]=t[0],i[s+1]=t[4],i[s+2]=t[8],i[s+3]=t[12],i[s+4]=t[1],i[s+5]=t[5],i[s+6]=t[9],i[s+7]=t[13],i[s+8]=t[2],i[s+9]=t[6],i[s+10]=t[10],i[s+11]=t[14];}this.uploadBones(this.device);}}let mE=0;class mA{constructor(){this.initDefaults();}initDefaults(){this.recreate=false,this.verticesUsage=tM,this.indicesUsage=tM,this.maxVertices=0,this.maxIndices=0,this.vertexCount=0,this.indexCount=0,this.vertexStreamsUpdated=false,this.indexStreamUpdated=false,this.vertexStreamDictionary={},this.indices=null;}_changeVertexCount(e,t){this.vertexCount||(this.vertexCount=e);}static{this.DEFAULT_COMPONENTS_POSITION=3;}static{this.DEFAULT_COMPONENTS_NORMAL=3;}static{this.DEFAULT_COMPONENTS_UV=2;}static{this.DEFAULT_COMPONENTS_COLORS=4;}}class mb{constructor(e,t,i,s,r){this.data=e,this.componentCount=t,this.dataType=i,this.dataTypeNormalize=s,this.asInt=r;}}class mw extends n4{constructor(e,t){super(),this.indexBuffer=[null],this.vertexBuffer=null,this.primitive=[{type:0,base:0,baseVertex:0,count:0}],this.skin=null,this.boneAabb=null,this._aabbVer=0,this._aabb=new ej,this._geometryData=null,this._morph=null,this._storageIndex=false,this._storageVertex=false,this.id=mE++,this.device=e,this._storageIndex=t?.storageIndex||false,this._storageVertex=t?.storageVertex||false;}static fromGeometry(e,t,i={}){let s=new mw(e,i),{positions:r,normals:a,tangents:n,colors:o,uvs:l,uvs1:h,blendIndices:c,blendWeights:d,indices:u}=t;return r&&s.setPositions(r),a&&s.setNormals(a),n&&s.setVertexStream(sA,n,4),o&&s.setColors32(o),l&&s.setUvs(0,l),h&&s.setUvs(1,h),c&&s.setVertexStream(sw,c,4,c.length/4,rP),d&&s.setVertexStream(sb,d,4),u&&s.setIndices(u),s.update(),s}set morph(e){e!==this._morph&&(this._morph&&this._morph.decRefCount(),this._morph=e,e&&e.incRefCount());}get morph(){return this._morph}set aabb(e){this._aabb=e,this._aabbVer++;}get aabb(){return this._aabb}destroy(){let e=this.morph;e&&(this.morph=null,e.refCount<1&&e.destroy()),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);for(let e=0;e<this.indexBuffer.length;e++)this._destroyIndexBuffer(e);this.indexBuffer.length=0,this._geometryData=null;}_destroyIndexBuffer(e){this.indexBuffer[e]&&(this.indexBuffer[e].destroy(),this.indexBuffer[e]=null);}_initBoneAabbs(e){let t,i,s,r,a,n,o,l;this.boneAabb=[],this.boneUsed=[];let h=[],c=[],d=this.boneUsed,u=this.skin.boneNames.length;for(let e=0;e<u;e++)h[e]=new eM(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),c[e]=new eM(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let f=new ho(this.vertexBuffer),p=f.element[sT],m=f.element[sb],_=f.element[sw],g=this.vertexBuffer.numVertices;for(let u=0;u<g;u++){for(let f=0;f<4;f++)if(m.array[m.index+f]>0){let m=_.array[_.index+f];if(d[m]=true,t=p.array[p.index],i=p.array[p.index+1],s=p.array[p.index+2],r=c[m],(a=h[m]).x>t&&(a.x=t),a.y>i&&(a.y=i),a.z>s&&(a.z=s),r.x<t&&(r.x=t),r.y<i&&(r.y=i),r.z<s&&(r.z=s),e){let h=n=t,c=o=i,d=l=s;for(let t=0;t<e.length;t++){let i=e[t],s=i.deltaPositions[3*u],r=i.deltaPositions[3*u+1],a=i.deltaPositions[3*u+2];s<0?h+=s:n+=s,r<0?c+=r:o+=r,a<0?d+=a:l+=a;}a.x>h&&(a.x=h),a.y>c&&(a.y=c),a.z>d&&(a.z=d),r.x<n&&(r.x=n),r.y<o&&(r.y=o),r.z<l&&(r.z=l);}}f.next();}let v=this.vertexBuffer.getFormat().elements.find(e=>e.name===sT);if(v&&v.normalize){let e=(()=>{switch(v.dataType){case rC:return e=>Math.max(e/127,-1);case rP:return e=>e/255;case rL:return e=>Math.max(e/32767,-1);case rI:return e=>e/65535;default:return e=>e}})();for(let t=0;t<u;t++)if(d[t]){let i=h[t],s=c[t];i.set(e(i.x),e(i.y),e(i.z)),s.set(e(s.x),e(s.y),e(s.z));}}for(let e=0;e<u;e++){let t=new ej;t.setMinMax(h[e],c[e]),this.boneAabb.push(t);}}_initGeometryData(){!this._geometryData&&(this._geometryData=new mA,this.vertexBuffer&&(this._geometryData.vertexCount=this.vertexBuffer.numVertices,this._geometryData.maxVertices=this.vertexBuffer.numVertices),this.indexBuffer.length>0&&this.indexBuffer[0]&&(this._geometryData.indexCount=this.indexBuffer[0].numIndices,this._geometryData.maxIndices=this.indexBuffer[0].numIndices));}clear(e,t,i=0,s=0){this._initGeometryData(),this._geometryData.initDefaults(),this._geometryData.recreate=true,this._geometryData.maxVertices=i,this._geometryData.maxIndices=s,this._geometryData.verticesUsage=e?tM:tO,this._geometryData.indicesUsage=t?tM:tO;}setVertexStream(e,t,i,s,r=rM,a=false,n=false){this._initGeometryData();let o=s||t.length/i;this._geometryData._changeVertexCount(o,e),this._geometryData.vertexStreamsUpdated=true,this._geometryData.vertexStreamDictionary[e]=new mb(t,i,r,a,n);}getVertexStream(e,t){let i=0,s=false;if(this._geometryData){let r=this._geometryData.vertexStreamDictionary[e];r&&(s=true,i=this._geometryData.vertexCount,ArrayBuffer.isView(t)?t.set(r.data):(t.length=0,t.push(r.data)));}return !s&&this.vertexBuffer&&(i=new ho(this.vertexBuffer).readData(e,t)),i}setPositions(e,t=mA.DEFAULT_COMPONENTS_POSITION,i){this.setVertexStream(sT,e,t,i,rM,false);}setNormals(e,t=mA.DEFAULT_COMPONENTS_NORMAL,i){this.setVertexStream(sE,e,t,i,rM,false);}setUvs(e,t,i=mA.DEFAULT_COMPONENTS_UV,s){this.setVertexStream(sP+e,t,i,s,rM,false);}setColors(e,t=mA.DEFAULT_COMPONENTS_COLORS,i){this.setVertexStream(sC,e,t,i,rM,false);}setColors32(e,t){this.setVertexStream(sC,e,mA.DEFAULT_COMPONENTS_COLORS,t,rP,true);}setIndices(e,t){this._initGeometryData(),this._geometryData.indexStreamUpdated=true,this._geometryData.indices=e,this._geometryData.indexCount=t||e.length;}getPositions(e){return this.getVertexStream(sT,e)}getNormals(e){return this.getVertexStream(sE,e)}getUvs(e,t){return this.getVertexStream(sP+e,t)}getColors(e){return this.getVertexStream(sC,e)}getIndices(e){let t=0;if(this._geometryData&&this._geometryData.indices){let i=this._geometryData.indices;if(t=this._geometryData.indexCount,ArrayBuffer.isView(e))e.set(i);else {e.length=0;for(let t=0,s=i.length;t<s;t++)e.push(i[t]);}}else this.indexBuffer.length>0&&this.indexBuffer[0]&&(t=this.indexBuffer[0].readData(e));return t}update(e=sS,t=true){if(this._geometryData){if(t){let e=this._geometryData.vertexStreamDictionary[sT];e&&3===e.componentCount&&(this._aabb.compute(e.data,this._geometryData.vertexCount),this._aabbVer++);}let i=this._geometryData.recreate;this._geometryData.vertexCount>this._geometryData.maxVertices&&(i=true,this._geometryData.maxVertices=this._geometryData.vertexCount),i&&this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);let s=this._geometryData.recreate;this._geometryData.indexCount>this._geometryData.maxIndices&&(s=true,this._geometryData.maxIndices=this._geometryData.indexCount),s&&this.indexBuffer.length>0&&this.indexBuffer[0]&&(this.indexBuffer[0].destroy(),this.indexBuffer[0]=null),this._geometryData.vertexStreamsUpdated&&this._updateVertexBuffer(),this._geometryData.indexStreamUpdated&&this._updateIndexBuffer(),this.primitive[0].type=e,this.indexBuffer.length>0&&this.indexBuffer[0]?this._geometryData.indexStreamUpdated&&(this.primitive[0].count=this._geometryData.indexCount,this.primitive[0].indexed=true):this._geometryData.vertexStreamsUpdated&&(this.primitive[0].count=this._geometryData.vertexCount,this.primitive[0].indexed=false),this._geometryData.vertexCount=0,this._geometryData.indexCount=0,this._geometryData.vertexStreamsUpdated=false,this._geometryData.indexStreamUpdated=false,this._geometryData.recreate=false,this.updateRenderStates();}}_buildVertexFormat(e){let t=[];for(let e in this._geometryData.vertexStreamDictionary){let i=this._geometryData.vertexStreamDictionary[e];t.push({semantic:e,components:i.componentCount,type:i.dataType,normalize:i.dataTypeNormalize,asInt:i.asInt});}return new nP(this.device,t,e)}_updateVertexBuffer(){if(!this.vertexBuffer){let e=this._geometryData.maxVertices,t=this._buildVertexFormat(e);this.vertexBuffer=new nT(this.device,t,e,{usage:this._geometryData.verticesUsage,storage:this._storageVertex});}let e=new ho(this.vertexBuffer),t=this._geometryData.vertexCount;for(let i in this._geometryData.vertexStreamDictionary){let s=this._geometryData.vertexStreamDictionary[i];e.writeData(i,s.data,t),delete this._geometryData.vertexStreamDictionary[i];}e.end();}_updateIndexBuffer(){if(this.indexBuffer.length<=0||!this.indexBuffer[0]){let e=this._geometryData.maxVertices,t=e>65535||0===e?ii:it,i=this._storageIndex?{storage:true}:void 0;this.indexBuffer[0]=new lJ(this.device,t,this._geometryData.maxIndices,this._geometryData.indicesUsage,void 0,i);}let e=this._geometryData.indices;e&&(this.indexBuffer[0].writeData(e,this._geometryData.indexCount),this._geometryData.indices=null);}prepareRenderState(e){e===fg?this.generateWireframe():e===fv&&(this.primitive[fv]={type:sm,base:0,baseVertex:0,count:this.vertexBuffer?this.vertexBuffer.numVertices:0,indexed:false});}updateRenderStates(){this.primitive[fv]&&this.prepareRenderState(fv),this.primitive[fg]&&this.prepareRenderState(fg);}generateWireframe(){let e;this._destroyIndexBuffer(fg);let t=this.vertexBuffer.numVertices,i=[];if(this.indexBuffer.length>0&&this.indexBuffer[0]){let s=[[0,1],[1,2],[2,0]],r=this.primitive[f_].base,a=this.primitive[f_].count,n=this.primitive[f_].baseVertex||0,o=this.indexBuffer[f_],l=new aJ[o.format](o.storage),h=new Set;for(let e=r;e<r+a;e+=3)for(let r=0;r<3;r++){let a=l[e+s[r][0]]+n,o=l[e+s[r][1]]+n,c=a>o?o*t+a:a*t+o;h.has(c)||(h.add(c),i.push(a,o));}e=o.format;}else {for(let e=0;e<t;e+=3)i.push(e,e+1,e+1,e+2,e+2,e);e=i.length>65535?ii:it;}let s=new lJ(this.vertexBuffer.device,e,i.length);new aJ[s.format](s.storage).set(i),s.unlock(),this.primitive[fg]={type:s_,base:0,baseVertex:0,count:i.length,indexed:true},this.indexBuffer[fg]=s;}}let mC=new ne;function mP(e){return mC.get(e)}class mL{destroy(){this.cache.forEach((e,t)=>{t.destroy();}),this.cache.clear();}incRef(e){let t=(this.cache.get(e)||0)+1;this.cache.set(e,t);}decRef(e){if(e){let t=this.cache.get(e);t&&(0==--t?(this.cache.delete(e),e.destroy()):this.cache.set(e,t));}}constructor(){this.cache=new Map;}}class mI{static{this.cache=new mL;}static incRef(e){this.cache.incRef(e);}static decRef(e){this.cache.decRef(e);}static destroy(){this.cache.destroy();}}let mD=0,mR=new ej,mM=new ej,mO=new eQ,mN=new Set,mF=new Uint32Array(4);class mB{constructor(e){this.vertexBuffer=null,this._destroyVertexBuffer=false,this.count=e;}destroy(){this._destroyVertexBuffer&&this.vertexBuffer?.destroy(),this.vertexBuffer=null;}}class mU{get(e){return this.map.get(e)??this.map.get(null)}constructor(){this.map=new Map,this.meshMetaData=new Int32Array(4);}}class mk{getBindGroup(e){if(!this.bindGroup){let t=this.shader.meshBindGroupFormat;this.bindGroup=new nc(e,t);}return this.bindGroup}getUniformBuffer(e){if(!this.uniformBuffer){let t=this.shader.meshUniformBufferFormat;this.uniformBuffer=new lc(e,t,false);}return this.uniformBuffer}destroy(){this.bindGroup?.destroy(),this.bindGroup=null,this.uniformBuffer?.destroy(),this.uniformBuffer=null;}constructor(){this.bindGroup=null,this.uniformBuffer=null;}}class mV{constructor(e,t,i=null){if(this.castShadow=false,this.shadowCascadeMask=fe,this.cull=true,this.drawOrder=0,this._drawBucket=127,this.visible=true,this.visibleThisFrame=false,this.flipFacesFactor=1,this.gsplatInstance=null,this.id=mD++,this.isVisibleFunc=null,this.instancingData=null,this.indirectData=null,this.parameters={},this.pick=true,this.stencilFront=null,this.stencilBack=null,this.transparent=false,this._aabb=new ej,this._aabbVer=-1,this._aabbMeshVer=-1,this._customAabb=null,this._updateAabb=true,this._updateAabbFunc=null,this._sortKeyShadow=0,this._sortKeyForward=0,this._sortKeyDynamic=0,this._layer=uA,this._material=null,this._skinInstance=null,this._morphInstance=null,this._receiveShadow=true,this._renderStyle=f_,this._screenSpace=false,this._shaderCache=new Map,this._shaderDefs=po<<16,this._calculateSortDistance=null,this.node=i,this._mesh=e,e.incRefCount(),this.material=t,e.vertexBuffer){let t=e.vertexBuffer.format;this._shaderDefs|=t.hasUv0?f1:0,this._shaderDefs|=t.hasUv1?f2:0,this._shaderDefs|=t.hasColor?f3:0,this._shaderDefs|=t.hasTangents?f9:0;}this.updateKey();}set drawBucket(e){this._drawBucket=255&Math.floor(e),this.updateKey();}get drawBucket(){return this._drawBucket}set renderStyle(e){this._renderStyle=e,this.mesh.prepareRenderState(e);}get renderStyle(){return this._renderStyle}set mesh(e){e!==this._mesh&&(this._mesh&&this._mesh.decRefCount(),this._mesh=e,e&&e.incRefCount());}get mesh(){return this._mesh}set aabb(e){this._aabb=e;}get aabb(){if(!this._updateAabb)return this._aabb;if(this._updateAabbFunc)return this._updateAabbFunc(this._aabb);let e=this._customAabb,t=!!e;if(!e){if(e=mR,this.skinInstance){if(!this.mesh.boneAabb){let e=this._morphInstance?this._morphInstance.morph._targets:null;this.mesh._initBoneAabbs(e);}let i=this.mesh.boneUsed,s=true;for(let t=0;t<this.mesh.boneAabb.length;t++)i[t]&&(mM.setFromTransformedAabb(this.mesh.boneAabb[t],this.skinInstance.matrices[t]),s?(s=false,e.center.copy(mM.center),e.halfExtents.copy(mM.halfExtents)):e.add(mM));t=true;}else if(this.node._aabbVer!==this._aabbVer||this.mesh._aabbVer!==this._aabbMeshVer){if(this.mesh?(e.center.copy(this.mesh.aabb.center),e.halfExtents.copy(this.mesh.aabb.halfExtents)):(e.center.set(0,0,0),e.halfExtents.set(0,0,0)),this.mesh&&this.mesh.morph){let t=this.mesh.morph.aabb;e._expand(t.getMin(),t.getMax());}t=true,this._aabbVer=this.node._aabbVer,this._aabbMeshVer=this.mesh._aabbVer;}}return t&&this._aabb.setFromTransformedAabb(e,this.node.getWorldTransform()),this._aabb}clearShaders(){this._shaderCache.forEach(e=>{e.destroy();}),this._shaderCache.clear();}getShaderInstance(e,t,i,s,r,a,n){let o=this._shaderDefs;mF[0]=e,mF[1]=t,mF[2]=o,mF[3]=s.hash;let l=nA(mF),h=this._shaderCache.get(l);if(!h){let t=this._material;if((h=new mk).shader=t.variants.get(l),h.hashes=new Uint32Array(mF),!h.shader){let c=t.getShaderVariant({device:this.mesh.device,scene:i,objDefs:o,cameraShaderParams:s,pass:e,sortedLights:n,viewUniformFormat:r,viewBindGroupFormat:a,vertexFormat:this.mesh.vertexBuffer?.format});t.variants.set(l,c),h.shader=c;}this._shaderCache.set(l,h);}return h}set material(e){this.clearShaders();let t=this._material;t&&t.removeMeshInstanceRef(this),this._material=e,e&&(e.addMeshInstanceRef(this),this.transparent=e.transparent,this.updateKey());}get material(){return this._material}_updateShaderDefs(e){e!==this._shaderDefs&&(this._shaderDefs=e,this.clearShaders());}set calculateSortDistance(e){this._calculateSortDistance=e;}get calculateSortDistance(){return this._calculateSortDistance}set receiveShadow(e){this._receiveShadow!==e&&(this._receiveShadow=e,this._updateShaderDefs(e?-2&this._shaderDefs:this._shaderDefs|fJ));}get receiveShadow(){return this._receiveShadow}set batching(e){this._updateShaderDefs(e?this._shaderDefs|ps:-16385&this._shaderDefs);}get batching(){return (this._shaderDefs&ps)!=0}set skinInstance(e){this._skinInstance=e,this._updateShaderDefs(e?this._shaderDefs|f0:-3&this._shaderDefs),this._setupSkinUpdate();}get skinInstance(){return this._skinInstance}set morphInstance(e){this._morphInstance?.destroy(),this._morphInstance=e;let t=this._shaderDefs;t=e&&e.morph.morphPositions?t|f7:-1025&t,t=e&&e.morph.morphNormals?t|pe:-2049&t,t=e&&e.morph.intRenderFormat?t|pi:-8193&t,this._updateShaderDefs(t);}get morphInstance(){return this._morphInstance}set screenSpace(e){this._screenSpace!==e&&(this._screenSpace=e,this._updateShaderDefs(e?this._shaderDefs|f6:-257&this._shaderDefs));}get screenSpace(){return this._screenSpace}set key(e){this._sortKeyForward=e;}get key(){return this._sortKeyForward}set mask(e){let t=65535&this._shaderDefs;this._updateShaderDefs(t|e<<16);}get mask(){return this._shaderDefs>>16}set instancingCount(e){this.instancingData&&(this.instancingData.count=e);}get instancingCount(){return this.instancingData?this.instancingData.count:0}destroy(){let e=this.mesh;e&&(this.mesh=null,e.refCount<1&&e.destroy()),this.setRealtimeLightmap(mV.lightmapParamNames[0],null),this.setRealtimeLightmap(mV.lightmapParamNames[1],null),this._skinInstance?.destroy(),this._skinInstance=null,this.morphInstance?.destroy(),this.morphInstance=null,this.clearShaders(),this.material=null,this.instancingData?.destroy();}static{this.lightmapParamNames=["texture_lightMap","texture_dirLightMap"];}static _prepareRenderStyleForArray(e,t){if(e){for(let i=0;i<e.length;i++){e[i]._renderStyle=t;let s=e[i].mesh;mN.has(s)||(mN.add(s),s.prepareRenderState(t));}mN.clear();}}_isVisible(e){return !!this.visible&&(this.isVisibleFunc?this.isVisibleFunc(e):(mO.center=this.aabb.center,mO.radius=this._aabb.halfExtents.length(),e.frustum.containsSphere(mO)>0))}updateKey(){let{material:e}=this;this._sortKeyForward=this._drawBucket<<23|(e.alphaToCoverage||e.alphaTest?4194304:0)|4194303&e.id;}setInstancing(e,t=false){e?(this.instancingData=new mB(e.numVertices),this.instancingData.vertexBuffer=e,e.format.instancing=true,this.cull=t):(this.instancingData=null,this.cull=true),this._updateShaderDefs(e?this._shaderDefs|f4:-33&this._shaderDefs);}setIndirect(e,t){this._allocIndirectData(),this.indirectData.map.set(e?.camera??null,t),this.mesh.device.mapsToClear.add(this.indirectData.map);}getIndirectMetaData(){this._allocIndirectData();let e=this.mesh?.primitive[this.renderStyle],t=this.indirectData.meshMetaData;return t[0]=e.count,t[1]=e.base,t[2]=e.baseVertex,t}_allocIndirectData(){this.indirectData||(this.indirectData=new mU);}ensureMaterial(e){this.material||(this.material=mP(e));}clearParameters(){this.parameters={};}getParameters(){return this.parameters}getParameter(e){return this.parameters[e]}setParameter(e,t,i=0xffffffff){let s=this.parameters[e];s?(s.data=t,s.passFlags=i):this.parameters[e]={scopeId:null,data:t,passFlags:i};}setRealtimeLightmap(e,t){let i=this.getParameter(e);i!==t&&(i&&mI.decRef(i.data),t?(mI.incRef(t),this.setParameter(e,t)):this.deleteParameter(e));}deleteParameter(e){this.parameters[e]&&delete this.parameters[e];}setParameters(e,t){let i=this.parameters;for(let s in i){let r=i[s];r.passFlags&t&&(r.scopeId||(r.scopeId=e.scope.resolve(s)),r.scopeId.setValue(r.data));}}setLightmapped(e){e?this.mask=(this.mask|pl)&-6:(this.setRealtimeLightmap(mV.lightmapParamNames[0],null),this.setRealtimeLightmap(mV.lightmapParamNames[1],null),this._shaderDefs&=-4289,this.mask=(this.mask|po)&-7);}setCustomAabb(e){e?this._customAabb?this._customAabb.copy(e):this._customAabb=e.clone():(this._customAabb=null,this._aabbVer=-1),this._setupSkinUpdate();}_setupSkinUpdate(){this._skinInstance&&(this._skinInstance._updateBeforeCull=!this._customAabb);}}let mz=[0,1,3,2,3,1],mG=[0,1,3,0,3,2],mH=new eO;function mW(e,t){if(e&&!t||!e&&t)return false;if((e=e.data)===(t=t.data))return true;if(e instanceof Float32Array&&t instanceof Float32Array){if(e.length!==t.length)return false;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return false;return true}return false}function mX(e){return e.node.worldTransform.scaleSign}class mY{constructor(e,t,i){this.device=e,this.rootNode=t,this.scene=i,this._init=false,this._batchGroups={},this._batchGroupCounter=0,this._batchList=[],this._dirtyGroups=[];}destroy(){this.device=null,this.rootNode=null,this.scene=null,this._batchGroups={},this._batchList=[],this._dirtyGroups=[];}addGroup(e,t,i,s,r){if(void 0===s&&(s=this._batchGroupCounter,this._batchGroupCounter++),this._batchGroups[s])return;let a=new mS(s,e,t,i,r);return this._batchGroups[s]=a,a}removeGroup(e){if(!this._batchGroups[e])return;let t=[];for(let i=0;i<this._batchList.length;i++)this._batchList[i].batchGroupId===e?this.destroyBatch(this._batchList[i]):t.push(this._batchList[i]);this._batchList=t,this._removeModelsFromBatchGroup(this.rootNode,e),delete this._batchGroups[e];}markGroupDirty(e){0>this._dirtyGroups.indexOf(e)&&this._dirtyGroups.push(e);}getGroupByName(e){let t=this._batchGroups;for(let i in t)if(t.hasOwnProperty(i)&&t[i].name===e)return t[i];return null}getBatches(e){let t=[],i=this._batchList.length;for(let s=0;s<i;s++){let i=this._batchList[s];i.batchGroupId===e&&t.push(i);}return t}_removeModelsFromBatchGroup(e,t){if(e.enabled){e.model&&e.model.batchGroupId===t&&(e.model.batchGroupId=-1),e.render&&e.render.batchGroupId===t&&(e.render.batchGroupId=-1),e.element&&e.element.batchGroupId===t&&(e.element.batchGroupId=-1),e.sprite&&e.sprite.batchGroupId===t&&(e.sprite.batchGroupId=-1);for(let i=0;i<e._children.length;i++)this._removeModelsFromBatchGroup(e._children[i],t);}}insert(e,t,i){let s=this._batchGroups[t];s&&0>s._obj[e].indexOf(i)&&(s._obj[e].push(i),this.markGroupDirty(t));}remove(e,t,i){let s=this._batchGroups[t];if(s){let r=s._obj[e].indexOf(i);r>=0&&(s._obj[e].splice(r,1),this.markGroupDirty(t));}}_extractRender(e,t,i,s){return e.render&&(t=s[e.render.batchGroupId]=t.concat(e.render.meshInstances),e.render.removeFromLayers()),t}_extractModel(e,t,i,s){return e.model&&e.model.model&&(t=s[e.model.batchGroupId]=t.concat(e.model.meshInstances),e.model.removeModelFromLayers()),t}_extractElement(e,t,i){if(!e.element)return;let s=false;e.element._text&&e.element._text._model.meshInstances.length>0?(t.push(e.element._text._model.meshInstances[0]),e.element.removeModelFromLayers(e.element._text._model),s=true):e.element._image&&(t.push(e.element._image._renderable.meshInstance),e.element.removeModelFromLayers(e.element._image._renderable.model),e.element._image._renderable.unmaskMeshInstance&&(t.push(e.element._image._renderable.unmaskMeshInstance),e.element._image._renderable.unmaskMeshInstance.stencilFront&&e.element._image._renderable.unmaskMeshInstance.stencilBack||(e.element._dirtifyMask(),e.element._onPrerender())),s=true),s&&(i._ui=true);}_collectAndRemoveMeshInstances(e,t){for(let i=0;i<t.length;i++){let s=t[i],r=this._batchGroups[s];if(!r)continue;let a=e[s];a||(a=e[s]=[]);for(let t=0;t<r._obj.model.length;t++)a=this._extractModel(r._obj.model[t],a,r,e);for(let t=0;t<r._obj.render.length;t++)a=this._extractRender(r._obj.render[t],a,r,e);for(let e=0;e<r._obj.element.length;e++)this._extractElement(r._obj.element[e],a,r);for(let e=0;e<r._obj.sprite.length;e++){let t=r._obj.sprite[e];t.sprite&&t.sprite._meshInstance&&(r.dynamic||t.sprite.sprite._renderMode===pb)&&(a.push(t.sprite._meshInstance),t.sprite.removeModelFromLayers(),r._sprite=true,t.sprite._batchGroup=r);}}}generate(e){let t,i,s,r,a={};e||(e=Object.keys(this._batchGroups));let n=[];for(let t=0;t<this._batchList.length;t++){if(0>e.indexOf(this._batchList[t].batchGroupId)){n.push(this._batchList[t]);continue}this.destroyBatch(this._batchList[t]);}if(this._batchList=n,this._collectAndRemoveMeshInstances(a,e),e===this._dirtyGroups)this._dirtyGroups.length=0;else {let t=[];for(let i=0;i<this._dirtyGroups.length;i++)0>e.indexOf(this._dirtyGroups[i])&&t.push(this._dirtyGroups[i]);this._dirtyGroups=t;}for(let e in a)if(a.hasOwnProperty(e)&&(t=a[e],s=this._batchGroups[e])){i=this.prepare(t,s.dynamic,s.maxAabbSize,s._ui||s._sprite);for(let t=0;t<i.length;t++)(r=this.create(i[t],s.dynamic,parseInt(e,10)))&&r.addToLayers(this.scene,s.layers);}}prepare(e,t,i=Number.POSITIVE_INFINITY,s){let r,a;if(0===e.length)return [];let n=.5*i,o=new ej,l=new ej,h=null,c=[],d=0;s&&e.sort((e,t)=>e.drawOrder-t.drawOrder);let u=e,f=s?function(e){h?h.add(e.aabb):h=e.aabb.clone(),a.push(e);}:function(e){a.push(e);};for(;u.length>0;){c[d]=[u[0]],a=[];let e=u[0].material,i=u[0].layer,p=u[0]._shaderDefs,m=u[0].parameters,_=u[0].stencilFront,g=u[0].mesh.vertexBuffer.getNumVertices(),v=u[0].drawOrder;o.copy(u[0].aabb);let S=mX(u[0]),y=u[0].mesh.vertexBuffer.format.batchingHash,x=u[0].mesh.primitive[0].indexed;h=null;for(let T=1;T<u.length;T++){let E=u[T];if(t&&c[d].length>=1024){a=a.concat(u.slice(T));break}if(e!==E.material||i!==E.layer||y!==E.mesh.vertexBuffer.format.batchingHash||x!==E.mesh.primitive[0].indexed||p!==E._shaderDefs||g+E.mesh.vertexBuffer.getNumVertices()>0xffffffff||(l.copy(o),l.add(E.aabb),l.halfExtents.x>n||l.halfExtents.y>n||l.halfExtents.z>n||_&&(!(r=E.stencilFront)||_.func!==r.func||_.zpass!==r.zpass)||S!==mX(E)||!function(e,t){for(let i in e)if(e.hasOwnProperty(i)&&!mW(e[i],t[i]))return false;for(let i in t)if(t.hasOwnProperty(i)&&!mW(t[i],e[i]))return false;return true}(m,E.parameters)||s&&h&&h.intersects(E.aabb)&&E.drawOrder!==v)){f(E);continue}o.add(E.aabb),g+=E.mesh.vertexBuffer.getNumVertices(),c[d].push(E);}d++,u=a;}return c}collectBatchedMeshData(e,t){let i=null,s=0,r=0,a=null;for(let n=0;n<e.length;n++)if(e[n].visible){let o=e[n].mesh;if(s+=o.vertexBuffer.numVertices,o.primitive[0].indexed)r+=o.primitive[0].count;else {let e=o.primitive[0].type;(e===sx||e===sy)&&4===o.primitive[0].count&&(r+=6);}if(!i){a=e[n].material,i={};let s=o.vertexBuffer.format.elements;for(let e=0;e<s.length;e++)i[s[e].name]={numComponents:s[e].numComponents,dataType:s[e].dataType,normalize:s[e].normalize,count:0};t&&(i[sw]={numComponents:1,dataType:rM,normalize:false,count:0});}}return {streams:i,batchNumVerts:s,batchNumIndices:r,material:a}}create(e,t,i){let s,r,a;this._init||(this.vertexFormats={},this._init=true);let n=null,o=null,l=this.collectBatchedMeshData(e,t);if(l.streams){let h,c,d,u,f,p=l.streams,m=l.material,_=l.batchNumVerts,g=l.batchNumIndices;o=new mv(e,t,i),this._batchList.push(o);let v=0,S=0,y=new(_<=65535?Uint16Array:Uint32Array)(g);for(s in p)(n=p[s]).typeArrayType=aj[n.dataType],n.elementByteSize=aK[n.dataType],n.buffer=new n.typeArrayType(_*n.numComponents);for(let i=0;i<e.length;i++)if(e[i].visible){for(s in a=(r=e[i].mesh).vertexBuffer.numVertices,t||(f=e[i].node.getWorldTransform()),p)if(s!==sw){let e=new(n=p[s]).typeArrayType(n.buffer.buffer,n.elementByteSize*n.count),i=r.getVertexStream(s,e)*n.numComponents;if(n.count+=i,!t&&n.numComponents>=3){if(s===sT){let t,s,r,a=f.data,o=a[0],l=a[1],h=a[2],c=a[4],d=a[5],u=a[6],p=a[8],m=a[9],_=a[10],g=a[12],v=a[13],S=a[14];for(let a=0;a<i;a+=n.numComponents)t=e[a],s=e[a+1],r=e[a+2],e[a]=t*o+s*c+r*p+g,e[a+1]=t*l+s*d+r*m+v,e[a+2]=t*h+s*u+r*_+S;}else if(s===sE||s===sA){let t,s,r;mH.invertMat4(f).transpose();let[a,o,l,h,c,d,u,p,m]=mH.data;for(let f=0;f<i;f+=n.numComponents)t=e[f],s=e[f+1],r=e[f+2],e[f]=t*a+s*h+r*u,e[f+1]=t*o+s*c+r*p,e[f+2]=t*l+s*d+r*m;}}}if(t){n=p[sw];for(let e=0;e<a;e++)n.buffer[n.count++]=i;}if(r.primitive[0].indexed)h=r.primitive[0].base,c=r.primitive[0].baseVertex||0,d=r.primitive[0].count,u=new aJ[r.indexBuffer[0].getFormat()](r.indexBuffer[0].storage);else {c=0;let e=r.primitive[0].type;if(e===sx||e===sy)if(4===r.primitive[0].count)h=0,d=6,u=e===sx?mz:mG;else {d=0;continue}}for(let e=0;e<d;e++)y[e+S]=u[h+e]+c+v;S+=d,v+=a;}for(s in r=new mw(this.device),p)n=p[s],r.setVertexStream(s,n.buffer,n.numComponents,void 0,n.dataType,n.normalize);y.length>0&&r.setIndices(y),r.update(sS,false),t&&(m=m.clone()).update();let x=new mV(r,m,this.rootNode);x.castShadow=o.origMeshInstances[0].castShadow,x.parameters=o.origMeshInstances[0].parameters,x.layer=o.origMeshInstances[0].layer,x._shaderDefs=o.origMeshInstances[0]._shaderDefs,x.batching=true,x.cull=o.origMeshInstances[0].cull;let T=this._batchGroups[i];if(T&&T._ui&&(x.cull=false),t){let e=[];for(let t=0;t<o.origMeshInstances.length;t++)e.push(o.origMeshInstances[t].node);x.skinInstance=new mT(this.device,e,this.rootNode);}x._updateAabb=false,x.drawOrder=o.origMeshInstances[0].drawOrder,x.stencilFront=o.origMeshInstances[0].stencilFront,x.stencilBack=o.origMeshInstances[0].stencilBack,x.flipFacesFactor=mX(o.origMeshInstances[0]),x.castShadow=o.origMeshInstances[0].castShadow,o.meshInstance=x,o.updateBoundingBox();}return o}updateAll(){this._dirtyGroups.length>0&&this.generate(this._dirtyGroups);for(let e=0;e<this._batchList.length;e++)this._batchList[e].dynamic&&this._batchList[e].updateBoundingBox();}clone(e,t){let i=new mv(t,e.dynamic,e.batchGroupId);this._batchList.push(i);let s=[];for(let e=0;e<t.length;e++)s.push(t[e].node);return i.meshInstance=new mV(e.meshInstance.mesh,e.meshInstance.material,e.meshInstance.node),i.meshInstance._updateAabb=false,i.meshInstance.parameters=t[0].parameters,i.meshInstance.cull=t[0].cull,i.meshInstance.layer=t[0].layer,e.dynamic&&(i.meshInstance.skinInstance=new mT(this.device,s,this.rootNode)),i.meshInstance.castShadow=e.meshInstance.castShadow,i}destroyBatch(e){e.destroy(this.scene,this._batchGroups[e.batchGroupId].layers);}}let mq="uSceneColorMap";class m$ extends l2{destroy(){super.destroy(),this.releaseRenderTarget(this.colorRenderTarget);}shouldReallocate(e,t,i){if(e?.colorBuffer.format!==i)return true;let s=t?.width||this.device.width,r=t?.height||this.device.height;return !e||s!==e.width||r!==e.height}allocateRenderTarget(e,t,i,s){let r=new ns(i,{name:mq,format:s,width:t?t.colorBuffer.width:i.width,height:t?t.colorBuffer.height:i.height,mipmaps:true,minFilter:t1,magFilter:tZ,addressU:tr,addressV:tr});return e?(e.destroyFrameBuffers(),e._colorBuffer=r,e._colorBuffers=[r]):e=new nM({name:"ColorGrabRT",colorBuffer:r,depth:false,stencil:false,autoResolve:false}),e}releaseRenderTarget(e){e&&(e.destroyTextureBuffers(),e.destroy());}frameUpdate(){let e=this.device,t=this.source,i=t?.colorBuffer.format??this.device.backBufferFormat;this.shouldReallocate(this.colorRenderTarget,t?.colorBuffer,i)&&(this.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=this.allocateRenderTarget(this.colorRenderTarget,t,e,i));let s=this.colorRenderTarget.colorBuffer;e.scope.resolve(mq).setValue(s);}execute(){let e=this.device,t=this.source,i=this.colorRenderTarget.colorBuffer;e.isWebGPU?(e.copyRenderTarget(t,this.colorRenderTarget,true,false),e.mipmapRenderer.generate(this.colorRenderTarget.colorBuffer.impl)):(e.copyRenderTarget(t,this.colorRenderTarget,true,false),e.activeTexture(e.maxCombinedTextures-1),e.bindTexture(i),e.gl.generateMipmap(i.impl._glTarget));}constructor(...e){super(...e),this.colorRenderTarget=null,this.source=null;}}let mj="uSceneDepthMap";class mK extends l2{constructor(e,t){super(e),this.depthRenderTarget=null,this.camera=null,this.camera=t;}destroy(){super.destroy(),this.releaseRenderTarget(this.depthRenderTarget);}shouldReallocate(e,t){let i=t?.width||this.device.width,s=t?.height||this.device.height;return !e||i!==e.width||s!==e.height}allocateRenderTarget(e,t,i,s,r){let a=new ns(i,{name:mj,format:s,width:t?t.colorBuffer.width:i.width,height:t?t.colorBuffer.height:i.height,mipmaps:false,minFilter:tK,magFilter:tK,addressU:tr,addressV:tr});return e?(e.destroyFrameBuffers(),r?e._depthBuffer=a:(e._colorBuffer=a,e._colorBuffers=[a])):e=new nM({name:"DepthGrabRT",colorBuffer:r?null:a,depthBuffer:r?a:null,depth:!r,stencil:i.supportsStencil,autoResolve:false}),e}releaseRenderTarget(e){e&&(e.destroyTextureBuffers(),e.destroy());}before(){let e=this.camera,t=this.device,i=e?.renderTarget??t.backBuffer,s=true,r=i.stencil?iT:ix;t.isWebGPU&&i.samples>1&&(r=iy,s=false);let a=e.renderTarget?.depthBuffer??e.renderTarget?.colorBuffer;this.shouldReallocate(this.depthRenderTarget,a)&&(this.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=this.allocateRenderTarget(this.depthRenderTarget,e.renderTarget,t,r,s));let n=s?this.depthRenderTarget.depthBuffer:this.depthRenderTarget.colorBuffer;t.scope.resolve(mj).setValue(n);}execute(){let e=this.device;if(e.isWebGL2&&e.renderTarget.samples>1){let t=e.renderTarget.impl._glFrameBuffer,i=this.depthRenderTarget;e.renderTarget=i,e.updateBegin(),this.depthRenderTarget.impl.internalResolve(e,t,i.impl._glFrameBuffer,this.depthRenderTarget,e.gl.DEPTH_BUFFER_BIT);}else e.copyRenderTarget(e.renderTarget,this.depthRenderTarget,false,true);}}class mZ{get hash(){if(void 0===this._hash){let e=`${this.gammaCorrection}_${this.toneMapping}_${this.srgbRenderTarget}_${this.fog}_${this.ssaoEnabled}_${this.sceneDepthMapLinear}`;this._hash=nE(e);}return this._hash}get defines(){let e=this._defines;return this._definesDirty&&(this._definesDirty=false,e.clear(),this._sceneDepthMapLinear&&e.set("SCENE_DEPTHMAP_LINEAR",true),e.set("FOG",this._fog.toUpperCase()),e.set("TONEMAP",fU[this._toneMapping]),e.set("GAMMA",fI[this.shaderOutputGamma])),e}markDirty(){this._hash=void 0,this._definesDirty=true;}set fog(e){this._fog!==e&&(this._fog=e,this.markDirty());}get fog(){return this._fog}set ssaoEnabled(e){this._ssaoEnabled!==e&&(this._ssaoEnabled=e,this.markDirty());}get ssaoEnabled(){return this._ssaoEnabled}set gammaCorrection(e){this._gammaCorrectionAssigned=true,this._gammaCorrection!==e&&(this._gammaCorrection=e,this.markDirty());}get gammaCorrection(){return this._gammaCorrection}set toneMapping(e){this._toneMapping!==e&&(this._toneMapping=e,this.markDirty());}get toneMapping(){return this._toneMapping}set srgbRenderTarget(e){this._srgbRenderTarget!==e&&(this._srgbRenderTarget=e,this.markDirty());}get srgbRenderTarget(){return this._srgbRenderTarget}set sceneDepthMapLinear(e){this._sceneDepthMapLinear!==e&&(this._sceneDepthMapLinear=e,this.markDirty());}get sceneDepthMapLinear(){return this._sceneDepthMapLinear}get shaderOutputGamma(){return this._gammaCorrection!==fL||this._srgbRenderTarget?fP:fL}constructor(){this._gammaCorrection=fL,this._toneMapping=fD,this._srgbRenderTarget=false,this._ssaoEnabled=false,this._fog=um,this._sceneDepthMapLinear=false,this._defines=new Map,this._definesDirty=true;}}let mQ=new eM,mJ=new eM,m0=new eM,m1=new eG,m2=[new eM,new eM,new eM,new eM,new eM,new eM,new eM,new eM];class m3{constructor(){this.shaderPassInfo=null,this.renderPassColorGrab=null,this.renderPassDepthGrab=null,this.fogParams=null,this.shaderParams=new mZ,this.renderPasses=[],this.jitter=0,this._aspectRatio=16/9,this._aspectRatioMode=pV,this._calculateProjection=null,this._calculateTransform=null,this._clearColor=new eb(.75,.75,.75,1),this._clearColorBuffer=true,this._clearDepth=1,this._clearDepthBuffer=true,this._clearStencil=0,this._clearStencilBuffer=true,this._cullFaces=true,this._farClip=1e3,this._flipFaces=false,this._fov=45,this._frustumCulling=true,this._horizontalFov=false,this._layers=[ub,uw,uC,uL,uP],this._layersSet=new Set(this._layers),this._nearClip=.1,this._node=null,this._orthoHeight=10,this._projection=fp,this._rect=new eF(0,0,1,1),this._renderTarget=null,this._scissorRect=new eF(0,0,1,1),this._scissorRectClear=false,this._aperture=16,this._shutter=.001,this._sensitivity=1e3,this._projMat=new eG,this._projMatDirty=true,this._projMatSkybox=new eG,this._viewMat=new eG,this._viewMatDirty=true,this._viewProjMat=new eG,this._viewProjMatDirty=true,this._shaderMatricesVersion=0,this._viewProjInverse=new eG,this._viewProjCurrent=null,this._viewProjPrevious=new eG,this._jitters=[0,0,0,0],this.frustum=new e0,this._xr=null,this._xrProperties={horizontalFov:this._horizontalFov,fov:this._fov,aspectRatio:this._aspectRatio,farClip:this._farClip,nearClip:this._nearClip};}destroy(){this.renderPassColorGrab?.destroy(),this.renderPassColorGrab=null,this.renderPassDepthGrab?.destroy(),this.renderPassDepthGrab=null,this.renderPasses.length=0;}_storeShaderMatrices(e,t,i,s){this._shaderMatricesVersion!==s&&(this._shaderMatricesVersion=s,this._viewProjPrevious.copy(this._viewProjCurrent??e),this._viewProjCurrent??=new eG,this._viewProjCurrent.copy(e),this._viewProjInverse.invert(e),this._jitters[2]=this._jitters[0],this._jitters[3]=this._jitters[1],this._jitters[0]=t,this._jitters[1]=i);}get fullSizeClearRect(){let e=this._scissorRectClear?this.scissorRect:this._rect;return 0===e.x&&0===e.y&&1===e.z&&1===e.w}set aspectRatio(e){this._aspectRatio!==e&&(this._aspectRatio=e,this._projMatDirty=true);}get aspectRatio(){return this.xr?.active?this._xrProperties.aspectRatio:this._aspectRatio}set aspectRatioMode(e){this._aspectRatioMode!==e&&(this._aspectRatioMode=e,this._projMatDirty=true);}get aspectRatioMode(){return this._aspectRatioMode}set calculateProjection(e){this._calculateProjection=e,this._projMatDirty=true;}get calculateProjection(){return this._calculateProjection}set calculateTransform(e){this._calculateTransform=e;}get calculateTransform(){return this._calculateTransform}set clearColor(e){this._clearColor.copy(e);}get clearColor(){return this._clearColor}set clearColorBuffer(e){this._clearColorBuffer=e;}get clearColorBuffer(){return this._clearColorBuffer}set clearDepth(e){this._clearDepth=e;}get clearDepth(){return this._clearDepth}set clearDepthBuffer(e){this._clearDepthBuffer=e;}get clearDepthBuffer(){return this._clearDepthBuffer}set clearStencil(e){this._clearStencil=e;}get clearStencil(){return this._clearStencil}set clearStencilBuffer(e){this._clearStencilBuffer=e;}get clearStencilBuffer(){return this._clearStencilBuffer}set cullFaces(e){this._cullFaces=e;}get cullFaces(){return this._cullFaces}set farClip(e){this._farClip!==e&&(this._farClip=e,this._projMatDirty=true);}get farClip(){return this.xr?.active?this._xrProperties.farClip:this._farClip}set flipFaces(e){this._flipFaces=e;}get flipFaces(){return this._flipFaces}set fov(e){this._fov!==e&&(this._fov=e,this._projMatDirty=true);}get fov(){return this.xr?.active?this._xrProperties.fov:this._fov}set frustumCulling(e){this._frustumCulling=e;}get frustumCulling(){return this._frustumCulling}set horizontalFov(e){this._horizontalFov!==e&&(this._horizontalFov=e,this._projMatDirty=true);}get horizontalFov(){return this.xr?.active?this._xrProperties.horizontalFov:this._horizontalFov}set layers(e){this._layers=e.slice(0),this._layersSet=new Set(this._layers);}get layers(){return this._layers}get layersSet(){return this._layersSet}set nearClip(e){this._nearClip!==e&&(this._nearClip=e,this._projMatDirty=true);}get nearClip(){return this.xr?.active?this._xrProperties.nearClip:this._nearClip}set node(e){this._node=e;}get node(){return this._node}set orthoHeight(e){this._orthoHeight!==e&&(this._orthoHeight=e,this._projMatDirty=true);}get orthoHeight(){return this._orthoHeight}set projection(e){this._projection!==e&&(this._projection=e,this._projMatDirty=true);}get projection(){return this._projection}get projectionMatrix(){return this._evaluateProjectionMatrix(),this._projMat}set rect(e){this._rect.copy(e);}get rect(){return this._rect}set renderTarget(e){this._renderTarget=e;}get renderTarget(){return this._renderTarget}set scissorRect(e){this._scissorRect.copy(e);}get scissorRect(){return this._scissorRect}get viewMatrix(){if(this._viewMatDirty){let e=this._node.getWorldTransform();this._viewMat.copy(e).invert(),this._viewMatDirty=false;}return this._viewMat}set aperture(e){this._aperture=e;}get aperture(){return this._aperture}set sensitivity(e){this._sensitivity=e;}get sensitivity(){return this._sensitivity}set shutter(e){this._shutter=e;}get shutter(){return this._shutter}set xr(e){this._xr!==e&&(this._xr=e,this._projMatDirty=true);}get xr(){return this._xr}clone(){return new m3().copy(this)}copy(e){return this._aspectRatio=e._aspectRatio,this._farClip=e._farClip,this._fov=e._fov,this._horizontalFov=e._horizontalFov,this._nearClip=e._nearClip,this._xrProperties.aspectRatio=e._xrProperties.aspectRatio,this._xrProperties.farClip=e._xrProperties.farClip,this._xrProperties.fov=e._xrProperties.fov,this._xrProperties.horizontalFov=e._xrProperties.horizontalFov,this._xrProperties.nearClip=e._xrProperties.nearClip,this.aspectRatioMode=e.aspectRatioMode,this.calculateProjection=e.calculateProjection,this.calculateTransform=e.calculateTransform,this.clearColor=e.clearColor,this.clearColorBuffer=e.clearColorBuffer,this.clearDepth=e.clearDepth,this.clearDepthBuffer=e.clearDepthBuffer,this.clearStencil=e.clearStencil,this.clearStencilBuffer=e.clearStencilBuffer,this.cullFaces=e.cullFaces,this.flipFaces=e.flipFaces,this.frustumCulling=e.frustumCulling,this.layers=e.layers,this.orthoHeight=e.orthoHeight,this.projection=e.projection,this.rect=e.rect,this.renderTarget=e.renderTarget,this.scissorRect=e.scissorRect,this.aperture=e.aperture,this.shutter=e.shutter,this.sensitivity=e.sensitivity,this.shaderPassInfo=e.shaderPassInfo,this.jitter=e.jitter,this._projMatDirty=true,this}_enableRenderPassColorGrab(e,t){t?this.renderPassColorGrab||(this.renderPassColorGrab=new m$(e)):(this.renderPassColorGrab?.destroy(),this.renderPassColorGrab=null);}_enableRenderPassDepthGrab(e,t,i){i?this.renderPassDepthGrab||(this.renderPassDepthGrab=new mK(e,this)):(this.renderPassDepthGrab?.destroy(),this.renderPassDepthGrab=null);}_updateViewProjMat(){(this._projMatDirty||this._viewMatDirty||this._viewProjMatDirty)&&(this._viewProjMat.mul2(this.projectionMatrix,this.viewMatrix),this._viewProjMatDirty=false);}worldToScreen(e,t,i,s=new eM){this._updateViewProjMat(),this._viewProjMat.transformPoint(e,s);let r=this._viewProjMat.data,a=e.x*r[3]+e.y*r[7]+e.z*r[11]+ +r[15];s.x=(s.x/a+1)*.5,s.y=(1-s.y/a)*.5;let{x:n,y:o,z:l,w:h}=this._rect;return s.x=s.x*l*t+n*t,s.y=s.y*h*i+(1-o-h)*i,s}screenToWorld(e,t,i,s,r,a=new eM){let{x:n,y:o,z:l,w:h}=this._rect,c=this.farClip-this.nearClip;if(mQ.set((e-n*s)/(l*s),1-(t-(1-o-h)*r)/(h*r),i/c),mQ.mulScalar(2),mQ.sub(eM.ONE),this._projection===fp){eG._getPerspectiveHalfSize(mJ,this.fov,this.aspectRatio,this.nearClip,this.horizontalFov),mJ.x*=mQ.x,mJ.y*=mQ.y;let e=this._node.getWorldTransform();mJ.z=-this.nearClip,e.transformPoint(mJ,m0);let t=this._node.getPosition();a.sub2(m0,t),a.normalize(),a.mulScalar(i),a.add(t);}else this._updateViewProjMat(),m1.copy(this._viewProjMat).invert(),m1.transformPoint(mQ,a);return a}_evaluateProjectionMatrix(){if(this._projMatDirty){if(this._projection===fp)this._projMat.setPerspective(this.fov,this.aspectRatio,this.nearClip,this.farClip,this.horizontalFov),this._projMatSkybox.copy(this._projMat);else {let e=this._orthoHeight,t=e*this.aspectRatio;this._projMat.setOrtho(-t,t,-e,e,this.nearClip,this.farClip),this._projMatSkybox.setPerspective(this.fov,this.aspectRatio,this.nearClip,this.farClip);}this._projMatDirty=false;}}getProjectionMatrixSkybox(){return this._evaluateProjectionMatrix(),this._projMatSkybox}getExposure(){return 1/(1.2*Math.pow(2,Math.log2(this._aperture*this._aperture/this._shutter*100/this._sensitivity)))}getScreenSize(e){if(this._projection===fp){let t=this._node.getPosition().distance(e.center);return t<e.radius?1:Math.min(Math.tan(Math.asin(e.radius/t))/Math.tan(this.fov/2*eA.DEG_TO_RAD),1)}return eA.clamp(e.radius/this._orthoHeight,0,1)}getFrustumCorners(e=this.nearClip,t=this.farClip){let i,s,r=this.fov*Math.PI/180;return this.projection===fp?this.horizontalFov?s=(i=e*Math.tan(r/2))/this.aspectRatio:i=(s=e*Math.tan(r/2))*this.aspectRatio:i=(s=this._orthoHeight)*this.aspectRatio,m2[0].x=i,m2[0].y=-s,m2[0].z=-e,m2[1].x=i,m2[1].y=s,m2[1].z=-e,m2[2].x=-i,m2[2].y=s,m2[2].z=-e,m2[3].x=-i,m2[3].y=-s,m2[3].z=-e,this._projection===fp&&(this.horizontalFov?s=(i=t*Math.tan(r/2))/this.aspectRatio:i=(s=t*Math.tan(r/2))*this.aspectRatio),m2[4].x=i,m2[4].y=-s,m2[4].z=-t,m2[5].x=i,m2[5].y=s,m2[5].z=-t,m2[6].x=-i,m2[6].y=s,m2[6].z=-t,m2[7].x=-i,m2[7].y=-s,m2[7].z=-t,m2}setXrProperties(e){Object.assign(this._xrProperties,e),this._projMatDirty=true;}}let m4=new eG,m5=new eM,m8=new eH,m6=new eH,m9=new eM,m7=new eM,_e=new eG,_t=new eH,_i=new eM,_s=new eG,_r=new eH,_a=new eH,_n=new eG,_o=new eM,_l=new eM;function _h(e,t){return e instanceof Function?e:i=>{let s=i[e];return s instanceof Function&&(s=s()),s===t}}class _c extends eo{constructor(e="Untitled"){super(),this.tags=new ep(this),this.localPosition=new eM,this.localRotation=new eH,this.localScale=new eM(1,1,1),this.localEulerAngles=new eM,this.position=new eM,this.rotation=new eH,this.eulerAngles=new eM,this._scale=null,this.localTransform=new eG,this._dirtyLocal=false,this._aabbVer=0,this._frozen=false,this.worldTransform=new eG,this._dirtyWorld=false,this._worldScaleSign=0,this._normalMatrix=new eO,this._dirtyNormal=true,this._right=null,this._up=null,this._forward=null,this._parent=null,this._children=[],this._graphDepth=0,this._enabled=true,this._enabledInHierarchy=false,this.scaleCompensation=false,this.name=e;}get right(){return this._right||(this._right=new eM),this.getWorldTransform().getX(this._right).normalize()}get up(){return this._up||(this._up=new eM),this.getWorldTransform().getY(this._up).normalize()}get forward(){return this._forward||(this._forward=new eM),this.getWorldTransform().getZ(this._forward).normalize().mulScalar(-1)}get normalMatrix(){let e=this._normalMatrix;return this._dirtyNormal&&(e.invertMat4(this.getWorldTransform()).transpose(),this._dirtyNormal=false),e}set enabled(e){this._enabled!==e&&(this._enabled=e,(e&&this._parent?.enabled||!e)&&this._notifyHierarchyStateChanged(this,e));}get enabled(){return this._enabled&&this._enabledInHierarchy}get parent(){return this._parent}get path(){let e=this._parent;if(!e)return "";let t=this.name;for(;e&&e._parent;)t=`${e.name}/${t}`,e=e._parent;return t}get root(){let e=this;for(;e._parent;)e=e._parent;return e}get children(){return this._children}get graphDepth(){return this._graphDepth}_notifyHierarchyStateChanged(e,t){e._onHierarchyStateChanged(t);let i=e._children;for(let e=0,s=i.length;e<s;e++)i[e]._enabled&&this._notifyHierarchyStateChanged(i[e],t);}_onHierarchyStateChanged(e){this._enabledInHierarchy=e,e&&!this._frozen&&this._unfreezeParentToRoot();}_cloneInternal(e){e.name=this.name;let t=this.tags._list;e.tags.clear();for(let i=0;i<t.length;i++)e.tags.add(t[i]);e.localPosition.copy(this.localPosition),e.localRotation.copy(this.localRotation),e.localScale.copy(this.localScale),e.localEulerAngles.copy(this.localEulerAngles),e.position.copy(this.position),e.rotation.copy(this.rotation),e.eulerAngles.copy(this.eulerAngles),e.localTransform.copy(this.localTransform),e._dirtyLocal=this._dirtyLocal,e.worldTransform.copy(this.worldTransform),e._dirtyWorld=this._dirtyWorld,e._dirtyNormal=this._dirtyNormal,e._aabbVer=this._aabbVer+1,e._enabled=this._enabled,e.scaleCompensation=this.scaleCompensation,e._enabledInHierarchy=false;}clone(){let e=new this.constructor;return this._cloneInternal(e),e}copy(e){return e._cloneInternal(this),this}destroy(){this.remove();let e=this._children;for(;e.length;){let t=e.pop();t._parent=null,t.destroy();}this.fire("destroy",this),this.off();}find(e,t){let i=[],s=_h(e,t);return this.forEach(e=>{s(e)&&i.push(e);}),i}findOne(e,t){return function e(t,i){if(i(t))return t;let s=t._children,r=s.length;for(let t=0;t<r;++t){let r=e(s[t],i);if(r)return r}return null}(this,_h(e,t))}findByTag(...e){let t=[],i=(s,r)=>{r&&s.tags.has(...e)&&t.push(s);for(let e=0;e<s._children.length;e++)i(s._children[e],true);};return i(this,false),t}findByName(e){return this.findOne("name",e)}findByPath(e){let t=Array.isArray(e)?e:e.split("/"),i=this;for(let e=0,s=t.length;e<s;++e)if(!(i=i.children.find(i=>i.name===t[e])))return null;return i}forEach(e,t){e.call(t,this);let i=this._children,s=i.length;for(let r=0;r<s;++r)i[r].forEach(e,t);}isDescendantOf(e){let t=this._parent;for(;t;){if(t===e)return true;t=t._parent;}return false}isAncestorOf(e){return e.isDescendantOf(this)}getEulerAngles(){return this.getWorldTransform().getEulerAngles(this.eulerAngles),this.eulerAngles}getLocalEulerAngles(){return this.localRotation.getEulerAngles(this.localEulerAngles),this.localEulerAngles}getLocalPosition(){return this.localPosition}getLocalRotation(){return this.localRotation}getLocalScale(){return this.localScale}getLocalTransform(){return this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=false),this.localTransform}getPosition(){return this.getWorldTransform().getTranslation(this.position),this.position}getRotation(){return this.rotation.setFromMat4(this.getWorldTransform()),this.rotation}getScale(){return this._scale||(this._scale=new eM),this.getWorldTransform().getScale(this._scale)}getWorldTransform(){return (this._dirtyLocal||this._dirtyWorld)&&(this._parent&&this._parent.getWorldTransform(),this._sync()),this.worldTransform}get worldScaleSign(){return 0===this._worldScaleSign&&(this._worldScaleSign=this.getWorldTransform().scaleSign),this._worldScaleSign}remove(){this._parent?.removeChild(this);}reparent(e,t){this.remove(),e&&(t>=0?e.insertChild(this,t):e.addChild(this));}setLocalEulerAngles(e,t,i){this.localRotation.setFromEulerAngles(e,t,i),this._dirtyLocal||this._dirtifyLocal();}setLocalPosition(e,t,i){e instanceof eM?this.localPosition.copy(e):this.localPosition.set(e,t,i),this._dirtyLocal||this._dirtifyLocal();}setLocalRotation(e,t,i,s){e instanceof eH?this.localRotation.copy(e):this.localRotation.set(e,t,i,s),this._dirtyLocal||this._dirtifyLocal();}setLocalScale(e,t,i){e instanceof eM?this.localScale.copy(e):this.localScale.set(e,t,i),this._dirtyLocal||this._dirtifyLocal();}_dirtifyLocal(){!this._dirtyLocal&&(this._dirtyLocal=true,this._dirtyWorld||this._dirtifyWorld());}_unfreezeParentToRoot(){let e=this._parent;for(;e;)e._frozen=false,e=e._parent;}_dirtifyWorld(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal();}_dirtifyWorldInternal(){if(!this._dirtyWorld){this._frozen=false,this._dirtyWorld=true;for(let e=0;e<this._children.length;e++)this._children[e]._dirtyWorld||this._children[e]._dirtifyWorldInternal();}this._dirtyNormal=true,this._worldScaleSign=0,this._aabbVer++;}setPosition(e,t,i){e instanceof eM?_i.copy(e):_i.set(e,t,i),null===this._parent?this.localPosition.copy(_i):(_s.copy(this._parent.getWorldTransform()).invert(),_s.transformPoint(_i,this.localPosition)),this._dirtyLocal||this._dirtifyLocal();}setRotation(e,t,i,s){if(e instanceof eH?_r.copy(e):_r.set(e,t,i,s),null===this._parent)this.localRotation.copy(_r);else {let e=this._parent.getRotation();_a.copy(e).invert(),this.localRotation.copy(_a).mul(_r);}this._dirtyLocal||this._dirtifyLocal();}setPositionAndRotation(e,t){if(null===this._parent)this.localPosition.copy(e),this.localRotation.copy(t);else {let i=this._parent.getWorldTransform();_s.copy(i).invert(),_s.transformPoint(e,this.localPosition),this.localRotation.setFromMat4(_s).mul(t);}this._dirtyLocal||this._dirtifyLocal();}setEulerAngles(e,t,i){if(this.localRotation.setFromEulerAngles(e,t,i),null!==this._parent){let e=this._parent.getRotation();_a.copy(e).invert(),this.localRotation.mul2(_a,this.localRotation);}this._dirtyLocal||this._dirtifyLocal();}addChild(e){this._prepareInsertChild(e),this._children.push(e),this._onInsertChild(e);}addChildAndSaveTransform(e){let t=e.getPosition(),i=e.getRotation();this._prepareInsertChild(e),e.setPosition(_e.copy(this.worldTransform).invert().transformPoint(t)),e.setRotation(_t.copy(this.getRotation()).invert().mul(i)),this._children.push(e),this._onInsertChild(e);}insertChild(e,t){this._prepareInsertChild(e),this._children.splice(t,0,e),this._onInsertChild(e);}_prepareInsertChild(e){e.remove();}_fireOnHierarchy(e,t,i){this.fire(e,i);for(let e=0;e<this._children.length;e++)this._children[e]._fireOnHierarchy(t,t,i);}_onInsertChild(e){e._parent=this;let t=e._enabled&&this.enabled;e._enabledInHierarchy!==t&&(e._enabledInHierarchy=t,e._notifyHierarchyStateChanged(e,t)),e._updateGraphDepth(),e._dirtifyWorld(),this._frozen&&e._unfreezeParentToRoot(),e._fireOnHierarchy("insert","inserthierarchy",this),this.fire&&this.fire("childinsert",e);}_updateGraphDepth(){this._graphDepth=this._parent?this._parent._graphDepth+1:0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._updateGraphDepth();}removeChild(e){let t=this._children.indexOf(e);-1!==t&&(this._children.splice(t,1),e._parent=null,e._fireOnHierarchy("remove","removehierarchy",this),this.fire("childremove",e));}_sync(){if(this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=false),this._dirtyWorld){if(null===this._parent)this.worldTransform.copy(this.localTransform);else if(this.scaleCompensation){let e,t=this._parent,i=this.localScale,s=t;if(s){for(;s&&s.scaleCompensation;)s=s._parent;s&&(s=s._parent)&&(e=s.worldTransform.getScale(),m9.mul2(e,this.localScale),i=m9);}m6.setFromMat4(t.worldTransform),m8.mul2(m6,this.localRotation);let r=t.worldTransform;t.scaleCompensation&&(m7.mul2(e,t.getLocalScale()),m4.setTRS(t.worldTransform.getTranslation(m5),m6,m7),r=m4),r.transformPoint(this.localPosition,m5),this.worldTransform.setTRS(m5,m8,i);}else this.worldTransform.mulAffine2(this._parent.worldTransform,this.localTransform);this._dirtyWorld=false;}}syncHierarchy(){if(!this._enabled||this._frozen)return;this._frozen=true,(this._dirtyLocal||this._dirtyWorld)&&this._sync();let e=this._children;for(let t=0,i=e.length;t<i;t++)e[t].syncHierarchy();}lookAt(e,t,i,s=0,r=1,a=0){if(e instanceof eM)_o.copy(e),t instanceof eM?_l.copy(t):_l.copy(eM.UP);else {if(void 0===i)return;_o.set(e,t,i),_l.set(s,r,a);}_n.setLookAt(this.getPosition(),_o,_l),_r.setFromMat4(_n),this.setRotation(_r);}translate(e,t,i){e instanceof eM?_i.copy(e):_i.set(e,t,i),_i.add(this.getPosition()),this.setPosition(_i);}translateLocal(e,t,i){e instanceof eM?_i.copy(e):_i.set(e,t,i),this.localRotation.transformVector(_i,_i),this.localPosition.add(_i),this._dirtyLocal||this._dirtifyLocal();}rotate(e,t,i){if(_r.setFromEulerAngles(e,t,i),null===this._parent)this.localRotation.mul2(_r,this.localRotation);else {let e=this.getRotation(),t=this._parent.getRotation();_a.copy(t).invert(),_r.mul2(_a,_r),this.localRotation.mul2(_r,e);}this._dirtyLocal||this._dirtifyLocal();}rotateLocal(e,t,i){_r.setFromEulerAngles(e,t,i),this.localRotation.mul(_r),this._dirtyLocal||this._dirtifyLocal();}}let _d=new eG,_u=new eG,_f=new eG;class _p{static{this.pointLightRotations=[new eH().setFromEulerAngles(0,90,180),new eH().setFromEulerAngles(0,-90,180),new eH().setFromEulerAngles(90,0,0),new eH().setFromEulerAngles(-90,0,0),new eH().setFromEulerAngles(0,180,180),new eH().setFromEulerAngles(0,0,180)];}static create(e,t,i){let s=new m3;switch(s.node=new _c(e),s.aspectRatio=1,s.aspectRatioMode=pz,s._scissorRectClear=true,t){case uD:s.node.setRotation(_p.pointLightRotations[i]),s.fov=90,s.projection=fp;break;case uM:s.projection=fp;break;case uI:s.projection=fm;}return s}static{this._spotCookieCamera=null;}static evalSpotCookieMatrix(e){let t=_p._spotCookieCamera;t||(t=_p.create("SpotCookieCamera",uM),_p._spotCookieCamera=t),t.fov=2*e._outerConeAngle;let i=t._node;i.setPosition(e._node.getPosition()),i.setRotation(e._node.getRotation()),i.rotateLocal(-90,0,0),_d.setTRS(i.getPosition(),i.getRotation(),eM.ONE).invert(),_u.mul2(t.projectionMatrix,_d);let s=e.cookieMatrix,r=e.atlasViewport;return _f.setViewport(r.x,r.y,r.z,r.w),s.mul2(_f,_u),s}}let _m=new eM,__=new Float32Array(6),_g=new eM(-0.5,0,0),_v=new eM(0,0,.5),_S={POSITION_RANGE:0,DIRECTION_FLAGS:1,COLOR_ANGLES_BIAS:2,PROJ_MAT_0:3,ATLAS_VIEWPORT:3,PROJ_MAT_1:4,PROJ_MAT_2:5,PROJ_MAT_3:6,AREA_DATA_WIDTH:7,AREA_DATA_HEIGHT:8,COUNT:9},_y={LIGHTSHAPE_PUNCTUAL:`${uB}u`,LIGHTSHAPE_RECT:`${uU}u`,LIGHTSHAPE_DISK:`${uk}u`,LIGHTSHAPE_SPHERE:`${uV}u`,LIGHT_COLOR_DIVIDER:`${uF}.0`},_x=(e,t)=>Object.keys(e).map(i=>`#define {${t}${i}} ${e[i]}`).join("\n"),_T=`
${_x(_S,"CLUSTER_TEXTURE_")}
${_x(_y,"")}
`;class _E{constructor(e){this.areaLightsEnabled=false,this.device=e,mr.get(e,rb).set("lightBufferDefinesPS",_T),mr.get(e,rw).set("lightBufferDefinesPS",_T),this.cookiesEnabled=false,this.shadowsEnabled=false,this.areaLightsEnabled=false,this.maxLights=255;let t=_S.COUNT;this.lightsFloat=new Float32Array(4*t*this.maxLights),this.lightsUint=new Uint32Array(this.lightsFloat.buffer),this.lightsTexture=this.createTexture(this.device,t,this.maxLights,iS,"LightsTexture"),this._lightsTextureId=this.device.scope.resolve("lightsTexture"),this.invMaxColorValue=0,this.invMaxAttenuation=0,this.boundsMin=new eM,this.boundsDelta=new eM;}destroy(){this.lightsTexture?.destroy(),this.lightsTexture=null;}createTexture(e,t,i,s,r){return new ns(e,{name:r,width:t,height:i,mipmaps:false,format:s,addressU:tr,addressV:tr,type:rt,magFilter:tK,minFilter:tK,anisotropy:1})}setBounds(e,t){this.boundsMin.copy(e),this.boundsDelta.copy(t);}uploadTextures(){this.lightsTexture.lock().set(this.lightsFloat),this.lightsTexture.unlock();}updateUniforms(){this._lightsTextureId.setValue(this.lightsTexture);}getSpotDirection(e,t){t._node.getWorldTransform().getY(e).mulScalar(-1),e.normalize();}getLightAreaSizes(e){let t=e._node.getWorldTransform();return t.transformVector(_g,_m),__[0]=_m.x,__[1]=_m.y,__[2]=_m.z,t.transformVector(_v,_m),__[3]=_m.x,__[4]=_m.y,__[5]=_m.z,__}addLightData(e,t){let i=e._type===uM,s=e.atlasViewportAllocated,r=this.cookiesEnabled&&!!e._cookie&&s,a=this.areaLightsEnabled&&e.shape!==uB,n=this.shadowsEnabled&&e.castShadows&&s,o=e._node.getPosition(),l=null,h=null;i?n?l=e.getRenderData(null,0).shadowMatrix:r&&(l=_p.evalSpotCookieMatrix(e)):(n||r)&&(h=e.atlasViewport);let c=this.lightsFloat,d=this.lightsUint,u=t*this.lightsTexture.width*4;c[u+4*_S.POSITION_RANGE+0]=o.x,c[u+4*_S.POSITION_RANGE+1]=o.y,c[u+4*_S.POSITION_RANGE+2]=o.z,c[u+4*_S.POSITION_RANGE+3]=e.attenuationEnd;let f=e.clusteredData;if(d[u+4*_S.COLOR_ANGLES_BIAS+0]=f[0],d[u+4*_S.COLOR_ANGLES_BIAS+1]=f[1],d[u+4*_S.COLOR_ANGLES_BIAS+2]=f[2],e.castShadows){let t=e.getRenderData(null,0),i=e._getUniformBiasValues(t),s=eD.float2Half(i.bias),r=eD.float2Half(i.normalBias);d[u+4*_S.COLOR_ANGLES_BIAS+3]=s|r<<16;}if(i&&(this.getSpotDirection(_m,e),c[u+4*_S.DIRECTION_FLAGS+0]=_m.x,c[u+4*_S.DIRECTION_FLAGS+1]=_m.y,c[u+4*_S.DIRECTION_FLAGS+2]=_m.z),d[u+4*_S.DIRECTION_FLAGS+3]=e.getClusteredFlags(n,r),l){let e=l.data;for(let t=0;t<16;t++)c[u+4*_S.PROJ_MAT_0+t]=e[t];}if(h&&(c[u+4*_S.ATLAS_VIEWPORT+0]=h.x,c[u+4*_S.ATLAS_VIEWPORT+1]=h.y,c[u+4*_S.ATLAS_VIEWPORT+2]=h.z/3),a){let t=this.getLightAreaSizes(e);c[u+4*_S.AREA_DATA_WIDTH+0]=t[0],c[u+4*_S.AREA_DATA_WIDTH+1]=t[1],c[u+4*_S.AREA_DATA_WIDTH+2]=t[2],c[u+4*_S.AREA_DATA_HEIGHT+0]=t[3],c[u+4*_S.AREA_DATA_HEIGHT+1]=t[4],c[u+4*_S.AREA_DATA_HEIGHT+2]=t[5];}}}let _A=new eM,_b=new eM,_w=new eM,_C=new ej;class _P{constructor(){this.light=null,this.min=new eM,this.max=new eM;}}class _L{constructor(e){this.device=e,this.name="Untitled",this.reportCount=0,this.boundsMin=new eM,this.boundsMax=new eM,this.boundsDelta=new eM,this._cells=new eM(1,1,1),this._cellsLimit=new eM,this.cells=this._cells,this.maxCellLightCount=4,this._usedLights=[],this._usedLights.push(new _P),this.lightsBuffer=new _E(e),this.registerUniforms(e);}set maxCellLightCount(e){e!==this._maxCellLightCount&&(this._maxCellLightCount=e,this._cellsDirty=true);}get maxCellLightCount(){return this._maxCellLightCount}set cells(e){_A.copy(e).floor(),this._cells.equals(_A)||(this._cells.copy(_A),this._cellsLimit.copy(_A).sub(eM.ONE),this._cellsDirty=true);}get cells(){return this._cells}destroy(){this.lightsBuffer.destroy(),this.releaseClusterTexture();}releaseClusterTexture(){this.clusterTexture&&(this.clusterTexture.destroy(),this.clusterTexture=null);}registerUniforms(e){this._clusterSkipId=e.scope.resolve("clusterSkip"),this._clusterMaxCellsId=e.scope.resolve("clusterMaxCells"),this._clusterWorldTextureId=e.scope.resolve("clusterWorldTexture"),this._clusterTextureSizeId=e.scope.resolve("clusterTextureSize"),this._clusterTextureSizeData=new Float32Array(3),this._clusterBoundsMinId=e.scope.resolve("clusterBoundsMin"),this._clusterBoundsMinData=new Float32Array(3),this._clusterBoundsDeltaId=e.scope.resolve("clusterBoundsDelta"),this._clusterBoundsDeltaData=new Float32Array(3),this._clusterCellsCountByBoundsSizeId=e.scope.resolve("clusterCellsCountByBoundsSize"),this._clusterCellsCountByBoundsSizeData=new Float32Array(3),this._clusterCellsDotId=e.scope.resolve("clusterCellsDot"),this._clusterCellsDotData=new Float32Array(3),this._clusterCellsMaxId=e.scope.resolve("clusterCellsMax"),this._clusterCellsMaxData=new Float32Array(3);}updateParams(e){e&&(this.cells=e.cells,this.maxCellLightCount=e.maxLightsPerCell,this.lightsBuffer.cookiesEnabled=e.cookiesEnabled,this.lightsBuffer.shadowsEnabled=e.shadowsEnabled,this.lightsBuffer.areaLightsEnabled=e.areaLightsEnabled);}updateCells(){if(this._cellsDirty){this._cellsDirty=false;let e=this._cells.x,t=this._cells.y,i=this._cells.z,s=e*t*i,r=this.maxCellLightCount*s,a=Math.ceil(Math.sqrt(r)),n=Math.ceil(r/(a=eA.roundUp(a,this.maxCellLightCount)));this._clusterCellsMaxData[0]=e,this._clusterCellsMaxData[1]=t,this._clusterCellsMaxData[2]=i,this._clusterCellsDotData[0]=this.maxCellLightCount,this._clusterCellsDotData[1]=e*i*this.maxCellLightCount,this._clusterCellsDotData[2]=e*this.maxCellLightCount,this.clusters=new Uint8ClampedArray(r),this.counts=new Int32Array(s),this._clusterTextureSizeData[0]=a,this._clusterTextureSizeData[1]=1/a,this._clusterTextureSizeData[2]=1/n,this.releaseClusterTexture(),this.clusterTexture=this.lightsBuffer.createTexture(this.device,a,n,i3,"ClusterTexture");}}uploadTextures(){this.clusterTexture.lock().set(this.clusters),this.clusterTexture.unlock(),this.lightsBuffer.uploadTextures();}updateUniforms(){this._clusterSkipId.setValue(this._usedLights.length>1?0:1),this.lightsBuffer.updateUniforms(),this._clusterWorldTextureId.setValue(this.clusterTexture),this._clusterMaxCellsId.setValue(this.maxCellLightCount);let e=this.boundsDelta;this._clusterCellsCountByBoundsSizeData[0]=this._cells.x/e.x,this._clusterCellsCountByBoundsSizeData[1]=this._cells.y/e.y,this._clusterCellsCountByBoundsSizeData[2]=this._cells.z/e.z,this._clusterCellsCountByBoundsSizeId.setValue(this._clusterCellsCountByBoundsSizeData),this._clusterBoundsMinData[0]=this.boundsMin.x,this._clusterBoundsMinData[1]=this.boundsMin.y,this._clusterBoundsMinData[2]=this.boundsMin.z,this._clusterBoundsDeltaData[0]=e.x,this._clusterBoundsDeltaData[1]=e.y,this._clusterBoundsDeltaData[2]=e.z,this._clusterTextureSizeId.setValue(this._clusterTextureSizeData),this._clusterBoundsMinId.setValue(this._clusterBoundsMinData),this._clusterBoundsDeltaId.setValue(this._clusterBoundsDeltaData),this._clusterCellsDotId.setValue(this._clusterCellsDotData),this._clusterCellsMaxId.setValue(this._clusterCellsMaxData);}evalLightCellMinMax(e,t,i){t.copy(e.min),t.sub(this.boundsMin),t.div(this.boundsDelta),t.mul2(t,this.cells),t.floor(),i.copy(e.max),i.sub(this.boundsMin),i.div(this.boundsDelta),i.mul2(i,this.cells),i.ceil(),t.max(eM.ZERO),i.min(this._cellsLimit);}collectLights(e){let t=this.lightsBuffer.maxLights,i=this._usedLights,s=1;e.forEach(e=>{let r=!!(e.mask&(po|pl)),a=e.type===uM&&0===e._outerConeAngle;if(e.enabled&&e.type!==uI&&e.visibleThisFrame&&e.intensity>0&&r&&!a&&s<t){let t;s<i.length?t=i[s]:(t=new _P,i.push(t)),t.light=e,e.getBoundingBox(_C),t.min.copy(_C.getMin()),t.max.copy(_C.getMax()),s++;}}),i.length=s;}evaluateBounds(){let e=this._usedLights,t=this.boundsMin,i=this.boundsMax;if(e.length>1){t.copy(e[1].min),i.copy(e[1].max);for(let s=2;s<e.length;s++)t.min(e[s].min),i.max(e[s].max);}else t.set(0,0,0),i.set(1,1,1);this.boundsDelta.sub2(i,t),this.lightsBuffer.setBounds(t,this.boundsDelta);}updateClusters(e){this.counts.fill(0),this.clusters.fill(0),this.lightsBuffer.areaLightsEnabled=!!e&&e.areaLightsEnabled;let t=this._cells.x,i=this._cells.z,s=this.counts,r=this._maxCellLightCount,a=this.clusters,n=this.maxCellLightCount,o=this._usedLights;for(let e=1;e<o.length;e++){let l=o[e],h=l.light;this.lightsBuffer.addLightData(h,e),this.evalLightCellMinMax(l,_b,_w);let c=_b.x,d=_w.x,u=_b.y,f=_w.y,p=_b.z,m=_w.z;for(let o=c;o<=d;o++)for(let l=p;l<=m;l++)for(let h=u;h<=f;h++){let c=o+t*(l+h*i),d=s[c];d<r&&(a[n*c+d]=e,s[c]=d+1);}}}update(e,t=null){this.updateParams(t),this.updateCells(),this.collectLights(e),this.evaluateBounds(),this.updateClusters(t),this.uploadTextures();}activate(){this.updateUniforms();}}let _I=null,_D=()=>{if(!_I){let e=atob("muPIHORMLNDCz4DxVR/ZvYfAUVEFR47KRIC4nwAAAAAP7WxlhD6Ci+2HCe7BF8jRAPZwdH2UPpI5PdLCJdkvG4UTaNDJ/0crAzne71GCrb4kbdMjjCEGzdX6fNxDMLJq5xkeoIVTdfiZkodEeArmZmp/FQzFjD4x8iOW7Dg64n+3mWqyEwLxXT8zoJXfbw8QJKDCaarUYyTlMzNFHbgUe9IQV7g4YOgtSKpIFZJ0qERm7u4PpmiF89ktHWCywaGmD6h+hfh2/Zd8KYlKqqo4Cem4T42bT/Z9FpCQF1hhSjfBzZ5XFn/y3jegWC6u86KuELRundQS/1Rp+XuKKGIgRv3CvP5y749yqLlFO495JOT3+f2CXgd71npU0/KjjpkZucbJ5m78IVyuSrSozc9jgBUhDrz0hFsyb7LFUH9//wJbBgLdNWJZObfKxrNt8TliLA9w9sXFv6g26iXpf6r/BqcAusj/QzGBZuoUGeEtw8BCXCZ3jUiw4hvM18ZVqlUD3C40LAFXW6FRjuAZGRNstb0/qVk4skwyT+MHrvRorI4rKHVMWZmKyAkzL/78u/9pMQuX14pZN50b2PHn6fRxeaCQLsfT4dpvIkWWFuFVENZIh+8xgR6lU+85W0PPdAu1j99kcCG40JBQa4JMyRzq6qriOBLtqF87vpCJan0WEduVr/mOYkS00urVA0mA6M3031+GmGmW48PaJDYOEIb3bIXWPaLoAOEinX1TN3+/vwhG6nqJu0TdHpedS7QsGZIoxH3nQYYjQP1jmbahlbNngw5ogsGk1y50XZyUmQBY+/JBJ3Unu4dApm+WmPwHPU9gLb+4mHh4BiY6M86pq+WeTyWdI3s0CXPEtHGXZ8zMZgUoyRomBi1VdazzuN+WOmQ9Pa0Z0tlNopUi8AJ4x2Xn4mmOKEbXLxlbVsWu8XhuDGYFOGCRVdSqDPXrHU5SDdUlti3k5///SBwzTMwK3L4a1H7w4lnpEas6////AfX8asyIBfeFXVJ3tgvxQ/blZuUKyIODIfr/UzdWNu7pciLBpdZRZ4pIfZ1R6szq+XNxkGG///8EZFpu7VHAhFWqHEOrB9unw+YQa5o8/9IR/V5/zq+986rJSyfgJKt2u9hxU1wzyQWPjJGvzG9+eWWxGFOHVKqI4jBQALwZZswesnvZ2UmmkEXdiRpz8B+oWE7PY70ZTMndisYSXg2TqoI+3y9BxbnY2Y4EfbdcRhAvG59NqDENNYbxKvK5HJfPG5M+Wi2AcpLVJrD6caiEOzgSoVNSgQK8fm2M3zGcF4xtClv/8Hs9oD7C3jitTATYNQxmKqKf1LhIxzf1bmfiNn7UKFmcJu4sLqVLwxGSue3taBEyknkw5hXTsUCvqmmL/f8n/w0giR7Hu/9EHvpkz3yuu64TioMkzdTJ30i0+hFnQqW1+v9mMwq+z9qGX0UFu9MomvVG2xod6vc12AAAAACq7sGa5qptFR0jF3nQt/D+7PibKYahaxP3hEixPbGi9nwNf2LAa7LkEZRKxzXeCD64Xpii5n+8Kpg8eHIv7AWXZltgMoGltmoJ0XGdOCL8WkzphvR9N2o3ARSZ42l5e5Pe4B58MCRlP3EKv+mcloknH+fto5BWsmEutW6KvjOVsznFCktkSczVk4aGvj9VXlRcLeDoKG8RkBgdcNG2bf8HUL4MT2DM+ar7NImJhKpxakX4Vk0CnP+/XNhl5UsP0lXgeZXPoDBMSW5An+DXlTCO5FQGwSPYwHLKYVIimEdAoVe49rQLaaNcye5LxU2/c5TijTgJtD5eQQIe1snxauj5jZsxJBUJdoP/zqpjqv8qBruoPsVsP8N44PCUW5Dd0DzqjSS/Dl5mI9cn1w2ndN/0KAEm1QAAAACwu6KM/083IBbH5bPa/9oHUwcU8I9v3j6/v18QYammrf+P6VL///8BrpuM3fOLCxaLNOFNF1zPbPYTP65ni6njft4eVcyrVXRQFrs52tr35StiSp55edVDCBC0H5rIfac6nzUwxQSt7y15QoKb+5zebEQUmVbrPjXuUa19Ey7sqXMiSUKHaw72PJKDdrutJoQr3u6lEYJ8K0MakWKj9zjTFi4X94TsKYco0GrLeB60M6D8M/80rhXUW8iMequg8y5F838WI0+gp3GBN5Kj/xIOxTWQuUaPV/LwvARr1VH93BFgGZR1MFW0Ua30GbYmdnAgo9VWy8SQtpDUgGE2r2zq2eTEMCL7sMKmE1hchVhuF/TCq9iXKEm86kzOf3Rp9ZnCxbpDUj+FKNxVyXe6pVZkRXv/m95SnB/EB8aME29N85MtAcDoXWlor8De2Q5Dg1tar+8wgiZufbMam81j//ASUohoR/zSh2KG4bvT6mkIPz6C5/98DC3LaWlaEZ1zA5JORZRu6J/a0GY285sEYzw71YqOT1ihAG0z5SDt1xNiDQWZdFpndArp6xWhqSDkRb4kSJEHb9liPvw7uLV/6i5MVf//A9Qjr8xkAEUh+KDI+zdtJ68d6MBOktg1iyp/SCq8O9f5pbamn1VVVQPRTWqNBvhQKa07s6P0lc9Luu/3gw4HeyOUfz8MxMwV4UQhua+t9cr4bz/nIB2wnDSK1K7I94M+s6C84htaX/CNlMQUSs2KJO+yaebfTbkNX5yWcqEJevo0vbKUiETuFXiL019A3E+lmsyZMwXrXLLiQAZ5t9+jI3JobhJTMiDH5ZOQ+8Jau5555NMjHSscP9qCVaa40doh+1a3Ukf6jqBmLddgh79/fwTfCyqiuldNkUoy+nUp+4nerwg0OjtGv2x485PJOJvUEokNhYIdWjpx7BWk0VZGWOp3jSFTJ2bnu6KCduZtG/UcBC9RZ3W/jMSfSMw4Etr/DoD/XYP2V5Ovw+YoM3F5g2dGLdvuG6ZkVGLE6Dk5Zr+sdSyGliJP1y2OFf/KFO0RWO+3gsGhesTnfZVpTd8/HwgO216gwaqo+vY3TljfJWowY+i0p0Os4SLn/1wLqDHMlszggmT/D8MRFzs+pLv6LNJSsNZ/r41mWi/rF6ZcKp/yzJdK0VU44hskq3RGpgO6mIpJDsf/mZkFrz0yYOMLbuaj/wp1v7JMFM5eqvBhmTd7U8frQAtHtys4zgpjZmzUhOVTfNNLifElGXADlqHGKrkBT/nYwX8ZRm3RjvyPvjKyEqEGKUpVnvOGx+NKPHiWM//ZDpDVGvvrjmk8RPF/wiYZD3+Us8YCXjrVOfjdd1UPAfjLp8jgSn4me7DPTpz1Ggy9XL80guFO7ECT10AvILKfD18Qx+KY/f8aRqu0oOO8hfKRFZa9PUJwCsp6VdZz6LFkm2b9Pl2LIifCwzRy7TpdG2uAtOxP2OemY26bJMa9ZGSLIRlMsgpDpnDJwd0oa5pQ13x1hrHf52HpulUWonGWsfXZbSQYKu9bnEN76ciQih0opN3deDVrbrxorfVlnCmL1R9zq3ePGWIv21c7pW8kEiFTM5JX8dAw867s/60cf79/BH+MDFCZBHlz1L+qGOJf/1txhhmrf3//As+RIJwevDb+fgNXVeHw67QptZegayhrEwr5Gy+EPo1RLaMtPbqOZYoVzXzwzjMFWZxyUG9YUIf6////AQWy84iAygLk9COtXt92+0mT/xg0zMzMBeLkb8y9SL2TDXgSX422hDgpGNLJyuPioA+YJ91G8znrpNqHkwYyscaJDEc9Vc+j4cXle3hvcd2JqDQH2lBZxDn6mUTs0b75raMvbs727codX01Anj8f3wir9P2xQaQ22v/TxCMglKDFoTjaP01XTLgxnTvPv02JgEUrW6UDgOnobFpLdvKdlypgIzPcq14fgXU5tvVW0FEs7VRlsG1IyA69fN4n+awHhT34cE+xUvdj86C8LgAsFheTjI9Ht9EyYAAAAAAVBVKRx2wLgUTI0/2QfyJo2riRw3JDqzEShmx/Lifo6mRkQVbS7X53t+EvKxcXogtdts31e9MRHdcHgsA8rt4/mt2unlzQ/wsU8Gu7+W6Oj7eD8EQdDp5XlCsVaS/AV/t5ZpPOHR3rGpyAJe9IPV+xMrBL1Oz/8MQhFs31h0N1cVnq371uqIJYHyafKH1jteAK3VpMXBcuC+yt0ZeKyRUY4QhdrJJ4tJ1wg3Hu6kDsbovxupTMkGdRrm8oZSoYPbJ+PwH/xotgTdkA1205vUEfnqkI04T/fnnd1fiZW5AwNcggd7fi4j5zasmcntZexIxqFZQMzMJpfndmI5jn17cgn5EV5t9XN0C///8Q9wlJpMGXdoiaMTG2sVyHQsn8mWRISCLNG777S0OuDRP2GlLcJ2UeOg7Fo8hTNPeJ//iTJhyqxhKRUntdXOihq2wfKfH///8B0GGrwT+fSOQRdctKxjjGCSS11d6BlQ9BDfE0J6Z25FaNTKGpFKNCMr2G/041KpWwBLVe1k08vncseQbKZdXi8x1t9XA45U/Wd43D9wAh3Tal0aiLVzGPusOZ1F+W3TWoqlX/A95+dNef11TsuGful+ctGssldk3fqpfqh+43XTxL42+leSHoF/dWHYGX6maqUEuLX7UB+r/6Llr4LKocbVIeu+hB9QTPfz9fCP8RyWmX4SmbhMFsNtCijV7lVcwejLKlvl0GfCndnWV7/39VBrtTRuUx92oke3GBgKkC5fdGK0YvNK+xenKaDmsHDjNFUM3NMz3ZiXXFuLgojosPVCDEl2W5BjX3Ms+j0GSqACHmh0+RPWyuNm/Qe8vFf9AW7N1uRaxWirrUytqEJnJ4/Flm8hSoiZ2NQBsS6w/yQlC4gCaFo8q4nyY6AFdo4hiwhBXzbNKKvZvktCjSCukRR/BbYVbNwZi2Yh3hGodEacLW8qijiWJODf0P2bhfaiPspPT4lYJBgi/KfcFwCfvyUIgkJOv///8CG/JEepRBLaMFE+2TgrqsJXOVOWHt6g/bFwVLLMVBsMR50dis/39/AlBX+/rMTJkUQrnlxpR2iu0Tp8tATkRYGmDIrcAiRP8PjoWIlb7/0ecTdSCE9Y58+a+n/FovJQTVF4F2jAxMZhTgrM/KVS5BQu6bVbkWY5HXnxRshks3urDdW4RkWp4M4TeLmFK5KF/uHkkiO5Kv96RioH984v/CSDBnG+BwlnU9B+o7Y+0X0Nob+0pLsStxjvPXMy2eCpzhOWV4XbObBHN4UE2sLQ/DIqXhOzxVf38GlTi6aG7EnePO7TRJm9yOfUUcqq1I2iQHrVDqn3TUNRi/lMw8KbMW/3/nqCz/Ef8PoW5Qxcz2yHR/f78EPB2Stbd+ZFmfNTUYILzsb9YNhpaHcaymYrBiNHmFE3Y4ccYJ25Prqm7zHobGHED8/93ZNlWro9vcKivGZs31UiK1k5zjUhexUgbqJb+fUTjxce/7Zly8a5KMC1fX5nfjPgibdvzbXV1jRT2asXvmSAusaLdq1TSIJ8fXINk5AtT34EWPAsfP9IFQqM5K11O6saoHJA==");_I=Uint8Array.from(e,e=>e.charCodeAt(0));}},_R=()=>(_D(),_I);class _M{constructor(e=0){this.seed=0,this.seed=4*e,_D();}_next(){this.seed=(this.seed+4)%_I.length;}value(){return this._next(),_I[this.seed]/255}vec4(e=new eF){return this._next(),e.set(_I[this.seed],_I[this.seed+1],_I[this.seed+2],_I[this.seed+3]).mulScalar(1/255)}}let _O=[new eM(-1,0,0),new eM(1,0,0),new eM(0,-1,0),new eM(0,1,0),new eM(0,0,-1),new eM(0,0,1)];class _N{update(e,t){let i=this.colors,{r:s,g:r,b:a}=e;for(let e=0;e<6;e++)i[3*e]=s,i[3*e+1]=r,i[3*e+2]=a;for(let e=0;e<t.length;e++){let s=t[e];if(s._type===uI)for(let e=0;e<6;e++){let t=Math.max(_O[e].dot(s._direction),0)*s._intensity,r=s._color;i[3*e]+=r.r*t,i[3*e+1]+=r.g*t,i[3*e+2]+=r.b*t;}}}constructor(){this.colors=new Float32Array(18);}}let _F=(e,t,i,s)=>{let r=new ns(e,{name:`${t}${i}`,width:i,height:i,format:id,addressU:ts,addressV:ts,type:rt,magFilter:tK,minFilter:tK,anisotropy:1,mipmaps:false});return r.lock().set(s),r.unlock(),r},_B=new ne,_U=e=>_B.get(e,()=>{let t=_R();return _F(e,"BlueNoise",Math.sqrt(t.length/4),t)});class _k{constructor(e,t){this.texture=e,this.cached=false,this.renderTargets=t;}destroy(){this.texture&&(this.texture.destroy(),this.texture=null);let e=this.renderTargets;for(let t=0;t<e.length;t++)e[t].destroy();this.renderTargets.length=0;}static create(e,t){return t._type===uD?this.createCubemap(e,t._shadowResolution,t._shadowType):this.create2dMap(e,t._shadowResolution,t._shadowType)}static createAtlas(e,t,i){let s=this.create2dMap(e,t,i),r=s.renderTargets,a=r[0];for(let e=0;e<5;e++)r.push(a);return s}static create2dMap(e,t,i){let s=u5.get(i),r=s.format;r===iy&&!e.textureFloatRenderable&&e.textureHalfFloatRenderable&&(r=i1);let a=so.get(r)?.name,n=tZ;i===uj&&(n=e.extTextureFloatLinear?tZ:tK),i===u1&&(n=tK);let o=new ns(e,{format:r,width:t,height:t,mipmaps:false,minFilter:n,magFilter:n,addressU:tr,addressV:tr,name:`ShadowMap2D_${a}`}),l=null;return s?.pcf?(o.compareOnRead=true,o.compareFunc=t3,l=new nM({depthBuffer:o})):l=new nM({colorBuffer:o,depth:true}),e.isWebGPU&&(l.flipY=true),new _k(o,[l])}static createCubemap(e,t,i){let s=u5.get(i),r=so.get(s.format)?.name,a=i===u1,n=a?tK:tZ,o=new ns(e,{format:s?.format,width:t,height:t,cubemap:true,mipmaps:false,minFilter:n,magFilter:n,addressU:tr,addressV:tr,name:`ShadowMapCube_${r}`});a||(o.compareOnRead=true,o.compareFunc=t3);let l=[];for(let e=0;e<6;e++)a?l.push(new nM({colorBuffer:o,face:e,depth:true})):l.push(new nM({depthBuffer:o,face:e}));return new _k(o,l)}}let _V=[],_z=[],_G=new eF,_H=new eF;class _W{constructor(e){this.size=Math.floor(1024*e.w),this.used=false,this.lightId=-1,this.rect=e;}}class _X{constructor(e){this.device=e,this.version=1,this.shadowAtlasResolution=2048,this.shadowAtlas=null,this.shadowEdgePixels=3,this.cookieAtlasResolution=4,this.cookieAtlas=new ns(this.device,{name:"CookieAtlas",width:this.cookieAtlasResolution,height:this.cookieAtlasResolution,format:ib,cubemap:false,mipmaps:false,minFilter:tK,magFilter:tK,addressU:tr,addressV:tr}),this.cookieRenderTarget=new nM({colorBuffer:this.cookieAtlas,depth:false,flipY:true}),this.slots=[],this.atlasSplit=[],this.cubeSlotsOffsets=[new eN(0,0),new eN(0,1),new eN(1,0),new eN(1,1),new eN(2,0),new eN(2,1)],this.scissorVec=new eF,this.allocateShadowAtlas(1),this.allocateCookieAtlas(1),this.allocateUniforms();}destroy(){this.destroyShadowAtlas(),this.destroyCookieAtlas();}destroyShadowAtlas(){this.shadowAtlas?.destroy(),this.shadowAtlas=null;}destroyCookieAtlas(){this.cookieAtlas?.destroy(),this.cookieAtlas=null,this.cookieRenderTarget?.destroy(),this.cookieRenderTarget=null;}allocateShadowAtlas(e,t=uX){let i=this.shadowAtlas?.texture.format,s=u5.get(t).format;if(!this.shadowAtlas||this.shadowAtlas.texture.width!==e||i!==s){this.version++,this.destroyShadowAtlas(),this.shadowAtlas=_k.createAtlas(this.device,e,t),this.shadowAtlas.cached=true;let i=4/this.shadowAtlasResolution;this.scissorVec.set(i,i,-2*i,-2*i);}}allocateCookieAtlas(e){this.cookieAtlas.width!==e&&(this.cookieRenderTarget.resize(e,e),this.version++);}allocateUniforms(){this._shadowAtlasTextureId=this.device.scope.resolve("shadowAtlasTexture"),this._shadowAtlasParamsId=this.device.scope.resolve("shadowAtlasParams"),this._shadowAtlasParams=new Float32Array(2),this._cookieAtlasTextureId=this.device.scope.resolve("cookieAtlasTexture");}updateUniforms(){let e=this.shadowAtlas.renderTargets[0].depthBuffer;this._shadowAtlasTextureId.setValue(e),this._shadowAtlasParams[0]=this.shadowAtlasResolution,this._shadowAtlasParams[1]=this.shadowEdgePixels,this._shadowAtlasParamsId.setValue(this._shadowAtlasParams),this._cookieAtlasTextureId.setValue(this.cookieAtlas);}subdivide(e,t){let i,s,r=t.atlasSplit;if(!r){let t=Math.ceil(Math.sqrt(e));(r=_z)[0]=t,r.length=1;}if(i=r,s=this.atlasSplit,!(i.length===s.length&&i.every((e,t)=>e===s[t]))){this.version++,this.slots.length=0,this.atlasSplit.length=0,this.atlasSplit.push(...r);let e=this.atlasSplit[0];if(e>1){let t=1/e;for(let i=0;i<e;i++)for(let s=0;s<e;s++){let r=new eF(i*t,s*t,t,t),a=this.atlasSplit[1+i*e+s];if(a>1)for(let e=0;e<a;e++)for(let i=0;i<a;i++){let s=t/a,n=new eF(r.x+e*s,r.y+i*s,s,s);this.slots.push(new _W(n));}else this.slots.push(new _W(r));}}else this.slots.push(new _W(new eF(0,0,1,1)));this.slots.sort((e,t)=>t.size-e.size);}}collectLights(e,t){let i=t.cookiesEnabled,s=t.shadowsEnabled,r=false,a=false;return _V.length=0,(i||s)&&(e=>{for(let t=0;t<e.length;t++){let n=e[t];if(n.visibleThisFrame){let e=s&&n.castShadows,t=i&&!!n.cookie;r||=e,a||=t,(e||t)&&_V.push(n);}}})(e),_V.sort((e,t)=>t.maxScreenSize-e.maxScreenSize),r&&this.allocateShadowAtlas(this.shadowAtlasResolution,t.shadowType),a&&this.allocateCookieAtlas(this.cookieAtlasResolution),(r||a)&&this.subdivide(_V.length,t),_V}setupSlot(e,t){e.atlasViewport.copy(t);let i=e.numShadowFaces;for(let s=0;s<i;s++)if(e.castShadows||e._cookie){if(_G.copy(t),_H.copy(t),e._type===uM&&_G.add(this.scissorVec),e._type===uD){let e=_G.z/3,t=this.cubeSlotsOffsets[s];_G.x+=e*t.x,_G.y+=e*t.y,_G.z=e,_G.w=e,_H.copy(_G);}if(e.castShadows){let t=e.getRenderData(null,s);t.shadowViewport.copy(_G),t.shadowScissor.copy(_H);}}}assignSlot(e,t,i){e.atlasViewportAllocated=true;let s=this.slots[t];s.lightId=e.id,s.used=true,i&&(e.atlasSlotUpdated=true,e.atlasVersion=this.version,e.atlasSlotIndex=t);}update(e,t){this.shadowAtlasResolution=t.shadowAtlasResolution,this.cookieAtlasResolution=t.cookieAtlasResolution;let i=this.collectLights(e,t);if(i.length>0){let e=this.slots;for(let t=0;t<e.length;t++)e[t].used=false;let t=Math.min(i.length,e.length);for(let s=0;s<t;s++){let t=i[s];t.castShadows&&(t._shadowMap=this.shadowAtlas);let r=e[t.atlasSlotIndex];if(t.atlasVersion===this.version&&t.id===r?.lightId){let i=e[t.atlasSlotIndex];i.size!==e[s].size||i.used||this.assignSlot(t,t.atlasSlotIndex,false);}}let s=0;for(let r=0;r<t;r++){for(;s<e.length&&e[s].used;)s++;let t=i[r];t.atlasViewportAllocated||this.assignSlot(t,s,true);let a=e[t.atlasSlotIndex];this.setupSlot(t,a.rect);}}this.updateUniforms();}}let _Y=[];_Y[us]={src:to,dst:to,op:tx},_Y[un]={src:to,dst:tn,op:tS},_Y[ua]={src:tu,dst:tp,op:tS,alphaSrc:to},_Y[uo]={src:to,dst:tp,op:tS},_Y[ur]={src:to,dst:to,op:tS},_Y[uh]={src:tu,dst:to,op:tS},_Y[uc]={src:tc,dst:tl,op:tS},_Y[ud]={src:td,dst:to,op:tS},_Y[ul]={src:tc,dst:tn,op:tS},_Y[uu]={src:to,dst:to,op:tT},_Y[uf]={src:to,dst:to,op:tE};let _q=0;class _${constructor(){this.meshInstances=[],this.name="Untitled",this.userId="",this.id=_q++,this.variants=new Map,this.defines=new Map,this._definesDirty=false,this.parameters={},this.alphaTest=0,this.alphaToCoverage=false,this._blendState=new nu,this._depthState=new nm,this.cull=tq,this.stencilFront=null,this.stencilBack=null,this._shaderChunks=null,this._oldChunks={},this._dirtyShader=true,this._shaderVersion=0,this._scene=null,this.dirty=true;}get hasShaderChunks(){return null!=this._shaderChunks}get shaderChunks(){return this._shaderChunks||(this._shaderChunks=new mr),this._shaderChunks}getShaderChunks(e=rb){let t=this.shaderChunks;return e===rb?t.glsl:t.wgsl}set shaderChunksVersion(e){this.shaderChunks.version=e;}get shaderChunksVersion(){return this.shaderChunks.version}set chunks(e){this._oldChunks=e;}get chunks(){return Object.assign(this._oldChunks,Object.fromEntries(this.shaderChunks.glsl)),this._oldChunks}set depthBias(e){this._depthState.depthBias=e;}get depthBias(){return this._depthState.depthBias}set slopeDepthBias(e){this._depthState.depthBiasSlope=e;}get slopeDepthBias(){return this._depthState.depthBiasSlope}set redWrite(e){this._blendState.redWrite=e;}get redWrite(){return this._blendState.redWrite}set greenWrite(e){this._blendState.greenWrite=e;}get greenWrite(){return this._blendState.greenWrite}set blueWrite(e){this._blendState.blueWrite=e;}get blueWrite(){return this._blendState.blueWrite}set alphaWrite(e){this._blendState.alphaWrite=e;}get alphaWrite(){return this._blendState.alphaWrite}get transparent(){return this._blendState.blend}_updateTransparency(){let e=this.transparent,t=this.meshInstances;for(let i=0;i<t.length;i++)t[i].transparent=e;}set blendState(e){this._blendState.copy(e),this._updateTransparency();}get blendState(){return this._blendState}set blendType(e){let t=_Y[e];this._blendState.setColorBlend(t.op,t.src,t.dst),this._blendState.setAlphaBlend(t.alphaOp??t.op,t.alphaSrc??t.src,t.alphaDst??t.dst);let i=e!==un;this._blendState.blend!==i&&(this._blendState.blend=i,this._updateTransparency()),this._updateMeshInstanceKeys();}get blendType(){if(!this.transparent)return un;let{colorOp:e,colorSrcFactor:t,colorDstFactor:i,alphaOp:s,alphaSrcFactor:r,alphaDstFactor:a}=this._blendState;for(let n=0;n<_Y.length;n++){let o=_Y[n];if(o.src===t&&o.dst===i&&o.op===e&&o.src===r&&o.dst===a&&o.op===s)return n}return ua}set depthState(e){this._depthState.copy(e);}get depthState(){return this._depthState}set depthTest(e){this._depthState.test=e;}get depthTest(){return this._depthState.test}set depthFunc(e){this._depthState.func=e;}get depthFunc(){return this._depthState.func}set depthWrite(e){this._depthState.write=e;}get depthWrite(){return this._depthState.write}copy(e){for(let t in this.name=e.name,this.alphaTest=e.alphaTest,this.alphaToCoverage=e.alphaToCoverage,this._blendState.copy(e._blendState),this._depthState.copy(e._depthState),this.cull=e.cull,this.stencilFront=e.stencilFront?.clone(),e.stencilBack&&(this.stencilBack=e.stencilFront===e.stencilBack?this.stencilFront:e.stencilBack.clone()),this.clearParameters(),e.parameters)e.parameters.hasOwnProperty(t)&&this._setParameterSimple(t,e.parameters[t].data);return this.defines.clear(),e.defines.forEach((e,t)=>this.defines.set(t,e)),this._shaderChunks=e.hasShaderChunks?new mr:null,this._shaderChunks?.copy(e._shaderChunks),this}clone(){return new this.constructor().copy(this)}_updateMeshInstanceKeys(){let e=this.meshInstances;for(let t=0;t<e.length;t++)e[t].updateKey();}updateUniforms(e,t){this._dirtyShader&&this.clearVariants();}getShaderVariant(e){}update(){if(Object.keys(this._oldChunks).length>0)for(let[e,t]of Object.entries(this._oldChunks))this.shaderChunks.glsl.set(e,t),delete this._oldChunks[e];(this._definesDirty||this._shaderChunks?.isDirty())&&(this._definesDirty=false,this._shaderChunks?.resetDirty(),this.clearVariants()),this.dirty=true;}clearParameters(){this.parameters={};}getParameters(){return this.parameters}clearVariants(){this.variants.clear();let e=this.meshInstances,t=e.length;for(let i=0;i<t;i++)e[i].clearShaders();}getParameter(e){return this.parameters[e]}_setParameterSimple(e,t){let i=this.parameters[e];i?i.data=t:this.parameters[e]={scopeId:null,data:t};}setParameter(e,t){if(void 0===t&&"object"==typeof e){let i=e;if(i.length){for(let e=0;e<i.length;e++)this.setParameter(i[e]);return}e=i.name,t=i.value;}this._setParameterSimple(e,t);}deleteParameter(e){this.parameters[e]&&delete this.parameters[e];}setParameters(e,t){let i=this.parameters;for(let s in void 0===t&&(t=i),t){let t=i[s];t&&(t.scopeId||(t.scopeId=e.scope.resolve(s)),t.scopeId.setValue(t.data));}}setDefine(e,t){let i=false,{defines:s}=this;void 0!==t&&false!==t?(i=!s.has(e)||s.get(e)!==t,s.set(e,t)):(i=s.has(e),s.delete(e)),this._definesDirty||=i;}getDefine(e){return this.defines.has(e)}destroy(){this.variants.clear();for(let e=0;e<this.meshInstances.length;e++){let t=this.meshInstances[e];if(t.clearShaders(),t._material=null,t.mesh){let e=mP(t.mesh.device);this!==e&&(t.material=e);}}this.meshInstances.length=0;}addMeshInstanceRef(e){this.meshInstances.push(e);}removeMeshInstanceRef(e){let t=this.meshInstances,i=t.indexOf(e);-1!==i&&t.splice(i,1);}}class _j{constructor(){this.cache=new Map;}destroy(){this.clear(),this.cache=null;}clear(){this.cache.forEach(e=>{e.forEach(e=>{e.destroy();});}),this.cache.clear();}getKey(e){let t=e._type===uD,i=e._shadowType,s=e._shadowResolution;return `${t}-${i}-${s}`}get(e,t){let i=this.getKey(t),s=this.cache.get(i);if(s&&s.length)return s.pop();let r=_k.create(e,t);return r.cached=true,r}add(e,t){let i=this.getKey(e),s=this.cache.get(i);s?s.push(t):this.cache.set(i,[t]);}}class _K extends l2{constructor(e,t,i,s,r){super(e),this.requiresCubemaps=false,this.shadowRenderer=t,this.light=i,this.face=s,this.applyVsm=r,this.shadowCamera=t.prepareFace(i,null,s),t.setupRenderPass(this,this.shadowCamera,true);}execute(){this.shadowRenderer.renderFace(this.light,null,this.face,false);}after(){this.applyVsm&&this.shadowRenderer.renderVsm(this.light,this.shadowCamera);}}class _Z{constructor(e,t){this.shadowLights=[],this.renderer=e,this.shadowRenderer=t,this.device=e.device;}cull(e,t,i=null){let s=this.renderer.scene.clusteredLightingEnabled;e.visibleThisFrame=true,s||e._shadowMap||(e._shadowMap=_k.create(this.device,e));let r=e._type,a=r===uM?1:6;for(let n=0;n<a;n++){let a=e.getRenderData(null,n),o=a.shadowCamera;o.nearClip=e.attenuationEnd/1e3,o.farClip=e.attenuationEnd;let l=o._node,h=e._node;l.setPosition(h.getPosition()),r===uM?(o.fov=2*e._outerConeAngle,l.setRotation(h.getRotation()),l.rotateLocal(-90,0,0)):r===uD&&(s?o.fov=Math.atan(1+2/(this.shadowRenderer.lightTextureAtlas.shadowAtlasResolution*e.atlasViewport.z/3)*this.shadowRenderer.lightTextureAtlas.shadowEdgePixels)*eA.RAD_TO_DEG*2:o.fov=90),this.renderer.updateCameraFrustum(o),this.shadowRenderer.cullShadowCasters(t,e,a.visibleCasters,o,i);}}prepareLights(e,t){let i;for(let s=0;s<t.length;s++){let r=t[s];if(this.shadowRenderer.needsShadowRendering(r)&&r.atlasViewportAllocated){e.push(r);for(let e=0;e<r.numShadowFaces;e++)i=this.shadowRenderer.prepareFace(r,null,e);}}return i}buildNonClusteredRenderPasses(e,t){for(let i=0;i<t.length;i++){let s=t[i];if(this.shadowRenderer.needsShadowRendering(s)){let t=s._type===uM,i=s.numShadowFaces;for(let r=0;r<i;r++){let i=new _K(this.device,this.shadowRenderer,s,r,t);e.addRenderPass(i);}}}}}class _Q extends l2{constructor(e,t,i,s,r){super(e),this.shadowRenderer=t,this.light=i,this.camera=s,this.allCascadesRendering=r;}execute(){let{light:e,camera:t,shadowRenderer:i,allCascadesRendering:s}=this,r=e.numShadowFaces,a=e.shadowUpdateOverrides;for(let n=0;n<r;n++)a?.[n]!==pr&&i.renderFace(e,t,n,!s),a?.[n]===pa&&(a[n]=pr);}after(){this.shadowRenderer.renderVsm(this.light,this.camera);}}let _J=new ej,_0=new eM,_1=new eG,_2=[new eM,new eM,new eM,new eM,new eM,new eM,new eM,new eM],_3={min:0,max:0};class _4{constructor(e,t){this.renderer=e,this.shadowRenderer=t,this.device=e.device;}cull(e,t,i,s=null){e.visibleThisFrame=true,e._shadowMap||(e._shadowMap=_k.create(this.device,e));let r=i._nearClip;this.generateSplitDistances(e,r,Math.min(i._farClip,e.shadowDistance));let a=e.shadowUpdateOverrides;for(let n=0;n<e.numCascades&&a?.[n]!==pr;n++){let a=e.getRenderData(i,n),o=a.shadowCamera;o.renderTarget=e._shadowMap.renderTargets[0],a.shadowViewport.copy(e.cascades[n]),a.shadowScissor.copy(e.cascades[n]);let l=o._node,h=e._node;l.setPosition(h.getPosition()),l.setRotation(h.getRotation()),l.rotateLocal(-90,0,0);let c=0===n?r:e._shadowCascadeDistances[n-1],d=e._shadowCascadeDistances[n],u=i.getFrustumCorners(c,d);_0.set(0,0,0);let f=i.node.getWorldTransform();for(let e=0;e<8;e++)f.transformPoint(u[e],u[e]),_0.add(u[e]);_0.mulScalar(1/8);let p=0;for(let e=0;e<8;e++){let t=u[e].sub(_0).length();t>p&&(p=t);}let m=l.right,_=l.up,g=l.forward,v=.25*e._shadowResolution/p,S=Math.ceil(_0.dot(_)*v)/v,y=Math.ceil(_0.dot(m)*v)/v,x=_.mulScalar(S),T=m.mulScalar(y),E=_0.dot(g),A=g.mulScalar(E);_0.add2(x,T).add(A),l.setPosition(_0),l.translateLocal(0,0,1e6),o.nearClip=.01,o.farClip=2e6,o.orthoHeight=p,this.renderer.updateCameraFrustum(o),this.shadowRenderer.cullShadowCasters(t,e,a.visibleCasters,o,s);let b=1<<n,w=a.visibleCasters,C=w.length,P=0;for(let e=0;e<C;e++){let t=w[e];t.shadowCascadeMask&b&&(w[P++]=t,1===P?_J.copy(t.aabb):_J.add(t.aabb));}C!==P&&(w.length=P),_1.copy(l.getWorldTransform()).invert();let L=function(e,t,i){_2[0].x=_2[1].x=_2[2].x=_2[3].x=t.x,_2[1].y=_2[3].y=_2[7].y=_2[5].y=t.y,_2[2].z=_2[3].z=_2[6].z=_2[7].z=t.z,_2[4].x=_2[5].x=_2[6].x=_2[7].x=i.x,_2[0].y=_2[2].y=_2[4].y=_2[6].y=i.y,_2[0].z=_2[1].z=_2[4].z=_2[5].z=i.z;let s=0x2540be3ff,r=-9999999999;for(let t=0;t<8;++t){e.transformPoint(_2[t],_2[t]);let i=_2[t].z;i<s&&(s=i),i>r&&(r=i);}return _3.min=s,_3.max=r,_3}(_1,_J.getMin(),_J.getMax());l.translateLocal(0,0,L.max+.1),o.farClip=L.max-L.min+.2,a.projectionCompensation=p;}}generateSplitDistances(e,t,i){e._shadowCascadeDistances.fill(i);for(let s=1;s<e.numCascades;s++){let r=s/e.numCascades,a=t+(i-t)*r,n=t*(i/t)**r,o=eA.lerp(a,n,e.cascadeDistribution);e._shadowCascadeDistances[s-1]=o;}}getLightRenderPass(e,t){let i=null;if(this.shadowRenderer.needsShadowRendering(e)){let s,r=e.numShadowFaces,a=e.shadowUpdateOverrides,n=true;for(let i=0;i<r;i++)a?.[i]===pr&&(n=false),s=this.shadowRenderer.prepareFace(e,t,i);i=new _Q(this.device,this.shadowRenderer,e,t,n),this.shadowRenderer.setupRenderPass(i,s,n);}return i}}let _5=new Set,_8=new eG,_6=new eG,_9=new Float32Array(2),_7=new eF(1,1,0,0),ge=new eG;class gt{constructor(e,t){this.shadowPassCache=[],this.device=e.device,this.renderer=e,this.lightTextureAtlas=t;let i=this.device.scope;this.sourceId=i.resolve("source"),this.pixelOffsetId=i.resolve("pixelOffset"),this.weightId=i.resolve("weight[0]"),this.blurVsmShader=[{},{}],this.blurVsmWeights={},this.shadowMapLightRadiusId=i.resolve("light_radius"),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this.blendStateWrite=new nu,this.blendStateNoWrite=new nu,this.blendStateNoWrite.setColorWrite(false,false,false,false);}static createShadowCamera(e,t,i){let s=_p.create("ShadowCamera",t,i),r=u5.get(e),a=r?.vsm??false,n=r?.pcf??false;return a?s.clearColor=new eb(0,0,0,0):s.clearColor=new eb(1,1,1,1),s.clearDepthBuffer=true,s.clearStencilBuffer=false,s.clearColorBuffer=!n,s}_cullShadowCastersInternal(e,t,i){let s=e.length;for(let r=0;r<s;r++){let s=e[r];s.castShadow&&(!s.cull||s._isVisible(i))&&(s.visibleThisFrame=true,t.push(s));}}cullShadowCasters(e,t,i,s,r){if(this.renderer.scene?.fire(p2,s),i.length=0,r)this._cullShadowCastersInternal(r,i,s);else {let r=e.layerList,a=r.length;for(let e=0;e<a;e++){let a=r[e];a._lightsSet.has(t)&&!_5.has(a)&&(_5.add(a),this._cullShadowCastersInternal(a.shadowCasters,i,s));}_5.clear();}i.sort(this.sortCompareShader),this.renderer.scene?.fire(p3,s);}sortCompareShader(e,t){let i=e._sortKeyShadow,s=t._sortKeyShadow;return i===s?t.mesh.id-e.mesh.id:s-i}setupRenderState(e,t){let i=this.renderer.scene.clusteredLightingEnabled?t._isPcf:t._isPcf&&t._type!==uD;e.setBlendState(i?this.blendStateNoWrite:this.blendStateWrite),e.setDepthState(t.shadowDepthState),e.setStencilState(null,null);}dispatchUniforms(e,t,i,s){let r=t._node;e._type!==uI&&(this.renderer.dispatchViewPos(r.getPosition()),this.shadowMapLightRadiusId.setValue(e.attenuationEnd)),_8.setTRS(r.getPosition(),r.getRotation(),eM.ONE).invert(),_6.mul2(t.projectionMatrix,_8);let a=i.shadowViewport;t.rect=a,t.scissorRect=i.shadowScissor,ge.setViewport(a.x,a.y,a.z,a.w),i.shadowMatrix.mul2(ge,_6),e._type===uI&&e._shadowMatrixPalette.set(i.shadowMatrix.data,16*s);}getShadowPass(e){let t=e._type,i=e._shadowType,s=this.shadowPassCache[t]?.[i];if(!s){let e=`ShadowPass_${t}_${i}`;s=mt.get(this.device).allocate(e,{isShadow:true,lightType:t,shadowType:i}),this.shadowPassCache[t]||(this.shadowPassCache[t]=[]),this.shadowPassCache[t][i]=s;}return s.index}submitCasters(e,t,i){let s=this.device,r=this.renderer,a=r.scene,n=1<<pu,o=this.getShadowPass(t),l=i.shaderParams,h=i.renderTarget.flipY?-1:1,c=e.length;for(let t=0;t<c;t++){let c=e[t],d=c.mesh,u=c.instancingData;if(u&&u.count<=0)continue;c.ensureMaterial(s);let f=c.material;r.setBaseConstants(s,f),r.setSkinning(s,c),f.dirty&&(f.updateUniforms(s,a),f.dirty=false),r.setupCullMode(true,h,c),f.setParameters(s),c.setParameters(s,n);let p=c.getShaderInstance(o,0,a,l,this.viewUniformFormat,this.viewBindGroupFormat),m=p.shader;if(m.failed)continue;c._sortKeyShadow=m.id,s.setShader(m),r.setVertexBuffers(s,d),r.setMorphing(s,c.morphInstance),u&&s.setVertexBuffer(u.vertexBuffer),r.setMeshInstanceMatrices(c),r.setupMeshUniformBuffers(p);let _=c.renderStyle,g=c.indirectData?.get(i);s.draw(d.primitive[_],d.indexBuffer[_],u?.count,g),r._shadowDrawCalls++,u&&r._instancedDrawCalls++;}}needsShadowRendering(e){let t=e.enabled&&e.castShadows&&e.shadowUpdateMode!==pr&&e.visibleThisFrame;return e.shadowUpdateMode===pa&&(e.shadowUpdateMode=pr),t&&(this.renderer._shadowMapUpdates+=e.numShadowFaces),t}getLightRenderData(e,t,i){return e.getRenderData(e._type===uI?t:null,i)}setupRenderPass(e,t,i){let s=t.renderTarget;e.init(s),e.depthStencilOps.clearDepthValue=1,e.depthStencilOps.clearDepth=i,s.depthBuffer?e.depthStencilOps.storeDepth=true:(e.colorOps.clearValue.copy(t.clearColor),e.colorOps.clear=i,e.depthStencilOps.storeDepth=false),e.requiresCubemaps=false;}prepareFace(e,t,i){let s=e._type,r=this.getLightRenderData(e,t,i).shadowCamera,a=s===uI?0:i;return r.renderTarget=e._shadowMap.renderTargets[a],r}renderFace(e,t,i,s,r=true){let a=this.device,n=this.getLightRenderData(e,t,i),o=n.shadowCamera;this.dispatchUniforms(e,o,n,i);let l=o.renderTarget,h=this.renderer;h.setCameraUniforms(o,l),a.supportsUniformBuffers&&h.setupViewUniformBuffers(n.viewBindGroups,this.viewUniformFormat,this.viewBindGroupFormat,null),r?(h.setupViewport(o,l),s&&h.clear(o)):h.clearView(o,l,true,false),this.setupRenderState(a,e),this.submitCasters(n.visibleCasters,e,o);}render(e,t,i=true){if(this.needsShadowRendering(e)){let s=e.numShadowFaces;for(let r=0;r<s;r++)this.prepareFace(e,t,r),this.renderFace(e,t,r,true,i);this.renderVsm(e,t);}}renderVsm(e,t){e._isVsm&&e._vsmBlurSize>1&&(this.renderer.scene.clusteredLightingEnabled&&e._type!==uI||this.applyVsmBlur(e,t));}getVsmBlurShader(e,t){let i=this.blurVsmShader,s=i[e][t];if(!s){this.blurVsmWeights[t]=function(e){let t=(e-1)/6,i=(e-1)*.5,s=Array(e),r=0;for(let n=0;n<e;++n){var a;s[n]=Math.exp(-((a=n-i)*a)/(2*t*t)),r+=s[n];}for(let t=0;t<e;++t)s[t]/=r;return s}(t);let r=new Map;r.set("{SAMPLES}",t),1===e&&r.set("GAUSS",""),s=mo.createShader(this.device,{uniqueName:`blurVsm${e}${t}`,attributes:{vertex_position:sT},vertexChunk:"fullscreenQuadVS",fragmentChunk:"blurVSMPS",fragmentDefines:r}),i[e][t]=s;}return s}applyVsmBlur(e,t){let i=this.device;i.setBlendState(nu.NOBLEND);let s=e.getRenderData(e._type===uI?t:null,0).shadowCamera.renderTarget,r=this.renderer.shadowMapCache.get(i,e),a=r.renderTargets[0],n=e.vsmBlurMode,o=e._vsmBlurSize,l=this.getVsmBlurShader(n,o);_7.z=e._shadowResolution-2,_7.w=_7.z,this.sourceId.setValue(s.colorBuffer),_9[0]=1/e._shadowResolution,_9[1]=0,this.pixelOffsetId.setValue(_9),n===fi&&this.weightId.setValue(this.blurVsmWeights[o]),mg(i,a,l,null,_7),this.sourceId.setValue(a.colorBuffer),_9[1]=_9[0],_9[0]=0,this.pixelOffsetId.setValue(_9),mg(i,s,l,null,_7),this.renderer.shadowMapCache.add(e,r);}initViewBindGroupFormat(){this.device.supportsUniformBuffers&&!this.viewUniformFormat&&(this.viewUniformFormat=new on(this.device,[new oa("matrix_viewProjection",rj)]),this.viewBindGroupFormat=new a7(this.device,[new a5(aq,aP|aL)]));}frameUpdate(){this.initViewBindGroupFormat();}}let gi=[];class gs{constructor(e){this._empty=null,this._allocated=[],this._clusters=new Map,this.device=e;}destroy(){this._empty&&(this._empty.destroy(),this._empty=null),this._allocated.forEach(e=>{e.destroy();}),this._allocated.length=0;}get count(){return this._allocated.length}get empty(){if(!this._empty){let e=new _L(this.device);e.name="ClusterEmpty",e.update([]),this._empty=e;}return this._empty}assign(e){let t=this.empty;gi.push(...this._allocated),this._allocated.length=0,this._clusters.clear();let i=e.length;for(let s=0;s<i;s++){let i=e[s].renderActions;if(i){let e=i.length;for(let s=0;s<e;s++){let e=i[s];e.lightClusters=null;let r=e.layer;if(r.hasClusteredLights&&r.meshInstances.length){let t=r.getLightIdHash(),i=this._clusters.get(t),s=i?.lightClusters;s||(s=gi.pop()??new _L(this.device),this._allocated.push(s),this._clusters.set(t,e)),e.lightClusters=s;}e.lightClusters||(e.lightClusters=t);}}}gi.forEach(e=>e.destroy()),gi.length=0;}update(e,t){this.assign(e),this._clusters.forEach(e=>{let i=e.layer;e.lightClusters.update(i.clusteredLightsSet,t);});}}let gr=new eF,ga=[];class gn extends l2{constructor(e,t){super(e),this._quadRenderer2D=null,this._quadRendererCube=null,this._filteredLights=[],this._forceCopy=false,this._evtDeviceRestored=null,this._cubeSlotsOffsets=t,this.requiresCubemaps=false,this.blitTextureId=e.scope.resolve("blitTexture"),this.invViewProjId=e.scope.resolve("invViewProj"),this._evtDeviceRestored=e.on("devicerestored",this.onDeviceRestored,this);}destroy(){this._quadRenderer2D?.destroy(),this._quadRenderer2D=null,this._quadRendererCube?.destroy(),this._quadRendererCube=null,this._evtDeviceRestored?.off(),this._evtDeviceRestored=null;}static create(e,t){let i=new gn(e.device,t);return i.init(e),i.colorOps.clear=false,i.depthStencilOps.clearDepth=false,i}onDeviceRestored(){this._forceCopy=true;}update(e){let t=this._filteredLights;this.filter(e,t),this.executeEnabled=t.length>0;}filter(e,t){for(let i=0;i<e.length;i++){let s=e[i];s._type!==uI&&s.atlasViewportAllocated&&(s.atlasSlotUpdated||this._forceCopy)&&s.enabled&&s.cookie&&s.visibleThisFrame&&t.push(s);}this._forceCopy=false;}initInvViewProjMatrices(){if(!ga.length)for(let e=0;e<6;e++){let t=_p.create(null,uD,e),i=t.projectionMatrix,s=t.node.getLocalTransform().clone().invert();ga[e]=new eG().mul2(i,s).invert();}}get quadRenderer2D(){if(!this._quadRenderer2D){let e=mo.createShader(this.device,{uniqueName:"cookieRenderer2d",attributes:{vertex_position:sT},vertexChunk:"cookieBlitVS",fragmentChunk:"cookieBlit2DPS"});this._quadRenderer2D=new mp(e);}return this._quadRenderer2D}get quadRendererCube(){if(!this._quadRendererCube){let e=mo.createShader(this.device,{uniqueName:"cookieRendererCube",attributes:{vertex_position:sT},vertexChunk:"cookieBlitVS",fragmentChunk:"cookieBlitCubePS"});this._quadRendererCube=new mp(e);}return this._quadRendererCube}execute(){let e=this.device;e.setBlendState(nu.NOBLEND),e.setCullMode(tY),e.setDepthState(nm.NODEPTH),e.setStencilState();let t=this.renderTarget.colorBuffer.width,i=this._cubeSlotsOffsets,s=this._filteredLights;for(let e=0;e<s.length;e++){let r=s[e],a=r.numShadowFaces,n=a>1?this.quadRendererCube:this.quadRenderer2D;a>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(r.cookie);for(let e=0;e<a;e++){if(gr.copy(r.atlasViewport),a>1){let t=gr.z/3,s=i[e];gr.x+=t*s.x,gr.y+=t*s.y,gr.z=t,gr.w=t,this.invViewProjId.setValue(ga[e].data);}gr.mulScalar(t),n.render(gr);}}s.length=0;}}class go extends l2{constructor(e,t,i){super(e),this.requiresCubemaps=false,this.shadowRenderer=t,this.shadowRendererLocal=i;}update(e){let t=this.shadowRendererLocal.shadowLights,i=this.shadowRendererLocal.prepareLights(t,e),s=t.length;this.enabled=s>0,s&&this.shadowRenderer.setupRenderPass(this,i,false);}execute(){let e=this.shadowRendererLocal.shadowLights,t=e.length;for(let i=0;i<t;i++){let t=e[i];for(let e=0;e<t.numShadowFaces;e++)this.shadowRenderer.renderFace(t,null,e,true);}e.length=0;}}class gl extends l2{constructor(e,t,i,s,r){super(e),this.renderer=t,this.frameGraph=null,this.cookiesRenderPass=gn.create(r.cookieRenderTarget,r.cubeSlotsOffsets),this.beforePasses.push(this.cookiesRenderPass),this.shadowRenderPass=new go(e,i,s),this.beforePasses.push(this.shadowRenderPass);}update(e,t,i,s,r){this.frameGraph=e,this.cookiesRenderPass.enabled=i,i&&this.cookiesRenderPass.update(s),this.shadowRenderPass.enabled=t,t&&this.shadowRenderPass.update(r);}destroy(){this.cookiesRenderPass.destroy(),this.cookiesRenderPass=null;}execute(){let{renderer:e}=this,{scene:t}=e;e.worldClustersAllocator.update(this.frameGraph.renderPasses,t.lighting);}}let gh=0,gc=new eG,gd=new eG,gu=new eG,gf=new eO,gp=new eQ,gm=new eG().setScale(1,-1,1),g_=new Set,gg=new Set,gv=new nh,gS=new eG().set([1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1]),gy=[new eN(.5,.333333),new eN(.25,.666667),new eN(.75,.111111),new eN(.125,.444444),new eN(.625,.777778),new eN(.375,.222222),new eN(.875,.555556),new eN(.0625,.888889),new eN(.5625,.037037),new eN(.3125,.37037),new eN(.8125,.703704),new eN(.1875,.148148),new eN(.6875,.481481),new eN(.4375,.814815),new eN(.9375,.259259),new eN(.03125,.592593)],gx=new eG,gT=new eG,gE=new eG,gA=new eG,gb=new eG,gw=new eG,gC=new Set,gP=[],gL=[];class gI{constructor(e){this.clustersDebugRendered=false,this.processingMeshInstances=new Set,this.lights=[],this.localLights=[],this.cameraDirShadowLights=new Map,this.dirLightShadows=new Map,this.blueNoise=new _M(123),this.device=e,this.scene=null,this.worldClustersAllocator=new gs(e),this.lightTextureAtlas=new _X(e),this.shadowMapCache=new _j,this.shadowRenderer=new gt(this,this.lightTextureAtlas),this._shadowRendererLocal=new _Z(this,this.shadowRenderer),this._shadowRendererDirectional=new _4(this,this.shadowRenderer),this._renderPassUpdateClustered=new gl(this.device,this,this.shadowRenderer,this._shadowRendererLocal,this.lightTextureAtlas),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this._skinTime=0,this._morphTime=0,this._cullTime=0,this._shadowMapTime=0,this._lightClustersTime=0,this._layerCompositionUpdateTime=0,this._shadowDrawCalls=0,this._skinDrawCalls=0,this._instancedDrawCalls=0,this._shadowMapUpdates=0,this._numDrawCallsCulled=0,this._camerasRendered=0,this._lightClusters=0;let t=e.scope;this.boneTextureId=t.resolve("texture_poseMap"),this.modelMatrixId=t.resolve("matrix_model"),this.normalMatrixId=t.resolve("matrix_normal"),this.viewInvId=t.resolve("matrix_viewInverse"),this.viewPos=new Float32Array(3),this.viewPosId=t.resolve("view_position"),this.projId=t.resolve("matrix_projection"),this.projSkyboxId=t.resolve("matrix_projectionSkybox"),this.viewId=t.resolve("matrix_view"),this.viewId3=t.resolve("matrix_view3"),this.viewProjId=t.resolve("matrix_viewProjection"),this.flipYId=t.resolve("projectionFlipY"),this.tbnBasis=t.resolve("tbnBasis"),this.nearClipId=t.resolve("camera_near"),this.farClipId=t.resolve("camera_far"),this.cameraParams=new Float32Array(4),this.cameraParamsId=t.resolve("camera_params"),this.viewIndexId=t.resolve("view_index"),this.viewIndexId.setValue(0),this.blueNoiseJitterVersion=0,this.blueNoiseJitterVec=new eF,this.blueNoiseJitterData=new Float32Array(4),this.blueNoiseJitterId=t.resolve("blueNoiseJitter"),this.blueNoiseTextureId=t.resolve("blueNoiseTex32"),this.alphaTestId=t.resolve("alpha_ref"),this.opacityMapId=t.resolve("texture_opacityMap"),this.exposureId=t.resolve("exposure"),this.twoSidedLightingNegScaleFactorId=t.resolve("twoSidedLightingNegScaleFactor"),this.twoSidedLightingNegScaleFactorId.setValue(0),this.morphPositionTex=t.resolve("morphPositionTex"),this.morphNormalTex=t.resolve("morphNormalTex"),this.morphTexParams=t.resolve("morph_tex_params"),this.lightCube=new _N,this.constantLightCube=t.resolve("lightCube[0]");}destroy(){this.shadowRenderer=null,this._shadowRendererLocal=null,this._shadowRendererDirectional=null,this.shadowMapCache.destroy(),this.shadowMapCache=null,this._renderPassUpdateClustered.destroy(),this._renderPassUpdateClustered=null,this.lightTextureAtlas.destroy(),this.lightTextureAtlas=null;}setupViewport(e,t){let i=this.device,s=t?t.width:i.width,r=t?t.height:i.height,a=e.rect,n=Math.floor(a.x*s),o=Math.floor(a.y*r),l=Math.floor(a.z*s),h=Math.floor(a.w*r);if(i.setViewport(n,o,l,h),e._scissorRectClear){let t=e.scissorRect;n=Math.floor(t.x*s),o=Math.floor(t.y*r),l=Math.floor(t.z*s),h=Math.floor(t.w*r);}i.setScissor(n,o,l,h);}setCameraUniforms(e,t){let i=t?.flipY,s=null;if(e.xr&&e.xr.session){let t=e._node?.parent?.getWorldTransform()||null;s=e.xr.views.list;for(let i=0;i<s.length;i++){let r=s[i];r.updateTransforms(t),e.frustum.setFromMat4(r.projViewOffMat);}}else {let s=e.projectionMatrix;e.calculateProjection&&e.calculateProjection(s,pD);let r=e.getProjectionMatrixSkybox();i&&(s=gx.mul2(gm,s),r=gT.mul2(gm,r)),this.device.isWebGPU&&(s=gE.mul2(gS,s),r=gA.mul2(gS,r));let{jitter:a}=e,n=0,o=0;if(a>0){let e=t?t.width:this.device.width,i=t?t.height:this.device.height,l=gy[this.device.renderVersion%gy.length];n=a*(2*l.x-1)/e,o=a*(2*l.y-1)/i,(s=gb.copy(s)).data[8]=n,s.data[9]=o,(r=gw.copy(r)).data[8]=n,r.data[9]=o,this.blueNoiseJitterVersion!==this.device.renderVersion&&(this.blueNoiseJitterVersion=this.device.renderVersion,this.blueNoise.vec4(this.blueNoiseJitterVec));}let l=a>0?this.blueNoiseJitterVec:eF.ZERO;if(this.blueNoiseJitterData[0]=l.x,this.blueNoiseJitterData[1]=l.y,this.blueNoiseJitterData[2]=l.z,this.blueNoiseJitterData[3]=l.w,this.blueNoiseJitterId.setValue(this.blueNoiseJitterData),this.projId.setValue(s.data),this.projSkyboxId.setValue(r.data),e.calculateTransform)e.calculateTransform(gd,pD);else {let t=e._node.getPosition(),i=e._node.getRotation();gd.setTRS(t,i,eM.ONE);}this.viewInvId.setValue(gd.data),gu.copy(gd).invert(),this.viewId.setValue(gu.data),gf.setFromMat4(gu),this.viewId3.setValue(gf.data),gc.mul2(s,gu),this.viewProjId.setValue(gc.data),e._storeShaderMatrices(gc,n,o,this.device.renderVersion),this.flipYId.setValue(i?-1:1),this.dispatchViewPos(e._node.getPosition()),e.frustum.setFromMat4(gc);}this.tbnBasis.setValue(i?-1:1);let r=e._nearClip,a=e._farClip;return this.nearClipId.setValue(r),this.farClipId.setValue(a),this.cameraParams[0]=1/a,this.cameraParams[1]=a,this.cameraParams[2]=r,this.cameraParams[3]=+(e.projection===fm),this.cameraParamsId.setValue(this.cameraParams),this.exposureId.setValue(this.scene.physicalUnits?e.getExposure():this.scene.exposure),s}clear(e,t,i,s){let r=(t??e._clearColorBuffer?tB:0)|(i??e._clearDepthBuffer?tU:0)|(s??e._clearStencilBuffer?tk:0);r&&this.device.clear({color:[e._clearColor.r,e._clearColor.g,e._clearColor.b,e._clearColor.a],depth:e._clearDepth,stencil:e._clearStencil,flags:r});}setCamera(e,t,i,s=null){this.setCameraUniforms(e,t),this.clearView(e,t,i,false);}clearView(e,t,i,s){let r=this.device;if(r.setRenderTarget(t),r.updateBegin(),s&&(r.setColorWrite(true,true,true,true),r.setDepthWrite(true)),this.setupViewport(e,t),i){let t=e._clearOptions;r.clear(t||{color:[e._clearColor.r,e._clearColor.g,e._clearColor.b,e._clearColor.a],depth:e._clearDepth,flags:(e._clearColorBuffer?tB:0)|(e._clearDepthBuffer?tU:0)|(e._clearStencilBuffer?tk:0),stencil:e._clearStencil});}}setupCullMode(e,t,i){let s=i.material,r=tY;if(e){let e=1;(s.cull===t$||s.cull===tq)&&(e=t*i.flipFacesFactor*i.node.worldScaleSign),r=e<0?s.cull===t$?tq:t$:s.cull;}this.device.setCullMode(r),r===tY&&s.cull===tY&&this.twoSidedLightingNegScaleFactorId.setValue(i.node.worldScaleSign);}updateCameraFrustum(e){if(e.xr&&e.xr.views.list.length){let t=e.xr.views.list[0];gc.mul2(t.projMat,t.viewOffMat),e.frustum.setFromMat4(gc);return}let t=e.projectionMatrix;if(e.calculateProjection&&e.calculateProjection(t,pD),e.calculateTransform)e.calculateTransform(gd,pD);else {let t=e._node.getPosition(),i=e._node.getRotation();gd.setTRS(t,i,eM.ONE),this.viewInvId.setValue(gd.data);}gu.copy(gd).invert(),gc.mul2(t,gu),e.frustum.setFromMat4(gc);}setBaseConstants(e,t){e.setCullMode(t.cull),t.opacityMap&&this.opacityMapId.setValue(t.opacityMap),(t.opacityMap||t.alphaTest>0)&&this.alphaTestId.setValue(t.alphaTest);}updateCpuSkinMatrices(e){gh++;let t=e.length;if(0!==t)for(let i=0;i<t;i++){let t=e[i].skinInstance;t&&(t.updateMatrices(e[i].node,gh),t._dirty=true);}}updateGpuSkinMatrices(e){for(let t of e){let e=t.skinInstance;e&&e._dirty&&(e.updateMatrixPalette(t.node,gh),e._dirty=false);}}updateMorphing(e){for(let t of e){let e=t.morphInstance;e&&e._dirty&&e.update();}}updateGSplats(e){for(let t of e)t.gsplatInstance?.update();}gpuUpdate(e){this.updateGpuSkinMatrices(e),this.updateMorphing(e),this.updateGSplats(e);}setVertexBuffers(e,t){e.setVertexBuffer(t.vertexBuffer);}setMorphing(e,t){t&&(t.prepareRendering(e),e.setVertexBuffer(t.morph.vertexBufferIds),this.morphPositionTex.setValue(t.texturePositions),this.morphNormalTex.setValue(t.textureNormals),this.morphTexParams.setValue(t._textureParams));}setSkinning(e,t){let i=t.skinInstance;if(i){this._skinDrawCalls++;let e=i.boneTexture;this.boneTextureId.setValue(e);}}dispatchViewPos(e){let t=this.viewPos;t[0]=e.x,t[1]=e.y,t[2]=e.z,this.viewPosId.setValue(t);}initViewBindGroupFormat(e){if(this.device.supportsUniformBuffers&&!this.viewUniformFormat){let t=[new oa("matrix_view",rj),new oa("matrix_viewInverse",rj),new oa("matrix_projection",rj),new oa("matrix_projectionSkybox",rj),new oa("matrix_viewProjection",rj),new oa("matrix_view3",r$),new oa("cubeMapRotationMatrix",r$),new oa("view_position",rk),new oa("skyboxIntensity",rB),new oa("exposure",rB),new oa("textureBias",rB),new oa("view_index",rB)];e&&t.push(new oa("clusterCellsCountByBoundsSize",rk),new oa("clusterTextureSize",rk),new oa("clusterBoundsMin",rk),new oa("clusterBoundsDelta",rk),new oa("clusterCellsDot",rk),new oa("clusterCellsMax",rk),new oa("shadowAtlasParams",rU),new oa("clusterMaxCells",rF),new oa("clusterSkip",rB)),this.viewUniformFormat=new on(this.device,t);let i=[new a5(aq,aP|aL)];this.viewBindGroupFormat=new a7(this.device,i);}}setupViewUniforms(e,t){this.projId.setValue(e.projMat.data),this.projSkyboxId.setValue(e.projMat.data),this.viewId.setValue(e.viewOffMat.data),this.viewInvId.setValue(e.viewInvOffMat.data),this.viewId3.setValue(e.viewMat3.data),this.viewProjId.setValue(e.projViewOffMat.data),this.viewPosId.setValue(e.positionData),this.viewIndexId.setValue(t);}setupViewUniformBuffers(e,t,i,s){let{device:r}=this,a=s?.length??1;for(;e.length<a;){let s=new lc(r,t,false),a=new nc(r,i,s);e.push(a);}if(s)for(let t=0;t<a;t++){let i=s[t];this.setupViewUniforms(i,t);let r=e[t];r.defaultUniformBuffer.update(),r.update();}else {let t=e[0];t.defaultUniformBuffer.update(),t.update();}s||r.setBindGroup(aH,e[0]);}setupMeshUniformBuffers(e){let t=this.device;if(t.supportsUniformBuffers){let i=e.getBindGroup(t);i.update(),t.setBindGroup(aW,i),e.getUniformBuffer(t).update(gv),t.setBindGroup(aX,gv.bindGroup,gv.offsets);}}setMeshInstanceMatrices(e,t=false){let i=e.node.worldTransform;this.modelMatrixId.setValue(i.data),t&&this.normalMatrixId.setValue(e.node.normalMatrix.data);}cull(e,t,i){let s=i.opaque;s.length=0;let r=i.transparent;r.length=0;let a=e.frustumCulling,n=t.length;for(let i=0;i<n;i++){let n=t[i];n.visible&&(!a||!n.cull||n._isVisible(e))&&(n.visibleThisFrame=true,(n.transparent?r:s).push(n),(n.skinInstance||n.morphInstance||n.gsplatInstance)&&(this.processingMeshInstances.add(n),n.gsplatInstance&&n.gsplatInstance.cameras.push(e)));}}collectLights(e){this.lights.length=0,this.localLights.length=0;let t=this.scene._stats,i=e.layerList.length;for(let t=0;t<i;t++){let i=e.layerList[t];if(!gg.has(i)){gg.add(i);let e=i._lights;for(let t=0;t<e.length;t++){let i=e[t];g_.has(i)||(g_.add(i),this.lights.push(i),i._type!==uI&&this.localLights.push(i));}}}t.lights=this.lights.length,g_.clear(),gg.clear();}cullLights(e,t){let i=this.scene.clusteredLightingEnabled,s=this.scene.physicalUnits;for(let r=0;r<t.length;r++){let a=t[r];if(a.enabled)if(a._type!==uI)if(a.getBoundingSphere(gp),e.frustum.containsSphere(gp)){a.visibleThisFrame=true,a.usePhysicalUnits=s;let t=e.getScreenSize(gp);a.maxScreenSize=Math.max(a.maxScreenSize,t);}else i||!a.castShadows||a.shadowMap||(a.visibleThisFrame=true);else a.usePhysicalUnits=this.scene.physicalUnits;}}cullShadowmaps(e){let t=this.scene.clusteredLightingEnabled;for(let i=0;i<this.localLights.length;i++){let s=this.localLights[i];s._type!==uI&&(t?s.atlasSlotUpdated&&s.shadowUpdateMode===pr&&(s.shadowUpdateMode=pa):s.shadowUpdateMode===pr&&s.castShadows&&!s.getRenderData(null,0).shadowCamera.renderTarget&&(s.shadowUpdateMode=pa),s.visibleThisFrame&&s.castShadows&&s.shadowUpdateMode!==pr&&this._shadowRendererLocal.cull(s,e));}this.cameraDirShadowLights.clear();let i=e.cameras;for(let t=0;t<i.length;t++){let s=i[t];if(s.enabled){let t,i=s.camera,r=i.layers;for(let s=0;s<r.length;s++){let a=e.getLayerById(r[s]);if(a){let s=a.splitLights[uI];for(let r=0;r<s.length;r++){let a=s[r];a.castShadows&&!gC.has(a)&&(gC.add(a),(t=t??[]).push(a),this._shadowRendererDirectional.cull(a,e,i));}}}t&&this.cameraDirShadowLights.set(i,t),gC.clear();}}}cullComposition(e){let{scene:t}=this;this.processingMeshInstances.clear();let i=e.cameras.length;this._camerasRendered+=i;for(let s=0;s<i;s++){let i=e.cameras[s];t?.fire(p2,i);let r=i.renderTarget;i.frameUpdate(r),this.updateCameraFrustum(i.camera);let a=i.layers;for(let t=0;t<a.length;t++){let s=e.getLayerById(a[t]);if(s&&s.enabled){this.cullLights(i.camera,s._lights);let e=s.getCulledInstances(i.camera);this.cull(i.camera,s.meshInstances,e);}}t?.fire(p3,i);}t.clusteredLightingEnabled&&this.updateLightTextureAtlas(),this.cullShadowmaps(e),t?.fire(p4);}updateShaders(e,t){let i=e.length;for(let s=0;s<i;s++){let i=e[s].material;if(i&&!gC.has(i)&&(gC.add(i),i.getShaderVariant!==_$.prototype.getShaderVariant)){if(t&&(!i.useLighting||i.emitter&&!i.emitter.lighting))continue;i.clearVariants();}}gC.clear();}updateFrameUniforms(){this.blueNoiseTextureId.setValue(_U(this.device));}beginFrame(e){let t=this.scene,i=t.updateShaders||this.device._shadersDirty,s=e.layerList,r=s.length;for(let e=0;e<r;e++){let t=s[e].meshInstances,r=t.length;for(let e=0;e<r;e++){let s=t[e];s.visibleThisFrame=false,i&&gP.push(s),s.skinInstance&&gL.push(s);}}if(i){let e=!t.updateShaders||!this.device._shadersDirty;this.updateShaders(gP,e),t.updateShaders=false,this.device._shadersDirty=false,t._shaderVersion++;}this.updateFrameUniforms(),this.updateCpuSkinMatrices(gL),gP.length=0,gL.length=0;let a=this.lights,n=a.length;for(let e=0;e<n;e++)a[e].beginFrame();}updateLightTextureAtlas(){this.lightTextureAtlas.update(this.localLights,this.scene.lighting);}updateLayerComposition(e){let t=e.layerList.length,i=this.scene._shaderVersion;for(let s=0;s<t;s++)e.layerList[s]._shaderVersion=i;e._update();}frameUpdate(){this.clustersDebugRendered=false,this.initViewBindGroupFormat(this.scene.clusteredLightingEnabled),this.dirLightShadows.clear();}}class gD{constructor(){this.camera=null,this.layer=null,this.transparent=false,this.renderTarget=null,this.lightClusters=null,this.clearColor=false,this.clearDepth=false,this.clearStencil=false,this.triggerPostprocess=false,this.firstCameraUse=false,this.lastCameraUse=false,this.viewBindGroups=[],this.useCameraPasses=false;}destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;}setupClears(e,t){this.clearColor=e?.clearColorBuffer||t.clearColorBuffer,this.clearDepth=e?.clearDepthBuffer||t.clearDepthBuffer,this.clearStencil=e?.clearStencilBuffer||t.clearStencilBuffer;}}class gR extends l2{constructor(e,t,i,s){super(e),this.renderActions=[],this.noDepthClear=false,this.layerComposition=t,this.scene=i,this.renderer=s;}get rendersAnything(){return this.renderActions.length>0}addRenderAction(e){this.renderActions.push(e);}addLayer(e,t,i,s=true){let r=new gD;if(r.renderTarget=this.renderTarget,r.camera=e,r.layer=t,r.transparent=i,s){let i=0===this.renderActions.length;r.setupClears(i?e:void 0,t);}this.addRenderAction(r);}addLayers(e,t,i,s,r,a=true){let{layerList:n,subLayerList:o}=e,l=s,h=i;for(;h<n.length;){let e=n[h],i=o[h];if(t.camera.layersSet.has(e.id)&&(this.addLayer(t,e,i,l),l=false),h++,e.id===r&&i===a)break}return h}updateDirectionalShadows(){let{renderer:e,renderActions:t}=this;for(let i=0;i<t.length;i++){let s=t[i].camera.camera,r=this.renderer.cameraDirShadowLights.get(s);if(r)for(let t=0;t<r.length;t++){let i=r[t];if(e.dirLightShadows.get(i)!==s){e.dirLightShadows.set(i,s);let t=e._shadowRendererDirectional.getLightRenderPass(i,s);t&&this.beforePasses.push(t);}}}}updateClears(){let e=this.renderActions[0];if(e){let t=e.camera.camera,i=t.fullSizeClearRect;this.setClearColor(i&&e.clearColor?t.clearColor:void 0),this.setClearDepth(i&&e.clearDepth&&!this.noDepthClear?t.clearDepth:void 0),this.setClearStencil(i&&e.clearStencil?t.clearStencil:void 0);}}frameUpdate(){super.frameUpdate(),this.updateDirectionalShadows(),this.updateClears();}before(){let{renderActions:e}=this;for(let t=0;t<e.length;t++){let i=e[t];i.firstCameraUse&&this.scene.fire(pQ,i.camera);}}execute(){let{layerComposition:e,renderActions:t}=this;for(let i=0;i<t.length;i++){let s=t[i],r=s.layer;e.isEnabled(r,s.transparent)&&this.renderRenderAction(s,0===i);}}after(){for(let e=0;e<this.renderActions.length;e++){let t=this.renderActions[e];t.lastCameraUse&&this.scene.fire(pJ,t.camera);}this.beforePasses.length=0;}renderRenderAction(e,t){let{renderer:i,scene:s}=this,r=i.device,{layer:a,transparent:n,camera:o}=e;if(o){let l=o.gammaCorrection,h=o.toneMapping;void 0!==this.gammaCorrection&&(o.gammaCorrection=this.gammaCorrection),void 0!==this.toneMapping&&(o.toneMapping=this.toneMapping),s.fire(p0,o,a,n);let c={lightClusters:e.lightClusters},d=o.camera.shaderPassInfo?.index??pc;t&&o.camera.fullSizeClearRect||(c.clearColor=e.clearColor,c.clearDepth=e.clearDepth,c.clearStencil=e.clearStencil);let u=e.renderTarget??r.backBuffer;i.renderForwardLayer(o.camera,u,a,n,d,e.viewBindGroups,c),r.setBlendState(nu.NOBLEND),r.setStencilState(null,null),r.setAlphaToCoverage(false),s.fire(p1,o,a,n),void 0!==this.gammaCorrection&&(o.gammaCorrection=l),void 0!==this.toneMapping&&(o.toneMapping=h);}}}class gM extends l2{constructor(e,t,i){super(e),this.renderer=t,this.renderAction=i,this.requiresCubemaps=false;}execute(){this.renderAction.camera.onPostprocessing();}}let gO=[[],[],[]],gN=new eb,gF={drawCalls:[],shaderInstances:[],isNewMaterial:[],lightMaskChanged:[],clear:function(){this.drawCalls.length=0,this.shaderInstances.length=0,this.isNewMaterial.length=0,this.lightMaskChanged.length=0;}};class gB extends gI{constructor(e){super(e);let t=this.device;this._forwardDrawCalls=0,this._materialSwitches=0,this._depthMapTime=0,this._forwardTime=0,this._sortTime=0;let i=t.scope;this.fogColorId=i.resolve("fog_color"),this.fogStartId=i.resolve("fog_start"),this.fogEndId=i.resolve("fog_end"),this.fogDensityId=i.resolve("fog_density"),this.ambientId=i.resolve("light_globalAmbient"),this.skyboxIntensityId=i.resolve("skyboxIntensity"),this.cubeMapRotationMatrixId=i.resolve("cubeMapRotationMatrix"),this.pcssDiskSamplesId=i.resolve("pcssDiskSamples[0]"),this.pcssSphereSamplesId=i.resolve("pcssSphereSamples[0]"),this.lightColorId=[],this.lightDir=[],this.lightDirId=[],this.lightShadowMapId=[],this.lightShadowMatrixId=[],this.lightShadowParamsId=[],this.lightShadowIntensity=[],this.lightRadiusId=[],this.lightPos=[],this.lightPosId=[],this.lightWidth=[],this.lightWidthId=[],this.lightHeight=[],this.lightHeightId=[],this.lightInAngleId=[],this.lightOutAngleId=[],this.lightCookieId=[],this.lightCookieIntId=[],this.lightCookieMatrixId=[],this.lightCookieOffsetId=[],this.lightShadowSearchAreaId=[],this.lightCameraParamsId=[],this.lightSoftShadowParamsId=[],this.shadowMatrixPaletteId=[],this.shadowCascadeDistancesId=[],this.shadowCascadeCountId=[],this.shadowCascadeBlendId=[],this.screenSizeId=i.resolve("uScreenSize"),this._screenSize=new Float32Array(4),this.fogColor=new Float32Array(3),this.ambientColor=new Float32Array(3),this.pcssDiskSamples=function(e){let t=[];for(let e=0;e<16;++e){let i=Math.sqrt(e+.5)/Math.sqrt(16);t.push(i);}return t}(),this.pcssSphereSamples=function(e){let t=[];for(let e=0;e<16;e++){let i=e/16,s=Math.sqrt(i*i);t.push(s);}return t}();}destroy(){super.destroy();}dispatchGlobalLights(e){let t=this.ambientColor;if(gN.linear(e.ambientLight),t[0]=gN.r,t[1]=gN.g,t[2]=gN.b,e.physicalUnits)for(let i=0;i<3;i++)t[i]*=e.ambientLuminance;this.ambientId.setValue(t),this.skyboxIntensityId.setValue(e.physicalUnits?e.skyboxLuminance:e.skyboxIntensity),this.cubeMapRotationMatrixId.setValue(e._skyboxRotationMat3.data);}_resolveLight(e,t){let i=`light${t}`;this.lightColorId[t]=e.resolve(`${i}_color`),this.lightDir[t]=new Float32Array(3),this.lightDirId[t]=e.resolve(`${i}_direction`),this.lightShadowMapId[t]=e.resolve(`${i}_shadowMap`),this.lightShadowMatrixId[t]=e.resolve(`${i}_shadowMatrix`),this.lightShadowParamsId[t]=e.resolve(`${i}_shadowParams`),this.lightShadowIntensity[t]=e.resolve(`${i}_shadowIntensity`),this.lightShadowSearchAreaId[t]=e.resolve(`${i}_shadowSearchArea`),this.lightRadiusId[t]=e.resolve(`${i}_radius`),this.lightPos[t]=new Float32Array(3),this.lightPosId[t]=e.resolve(`${i}_position`),this.lightWidth[t]=new Float32Array(3),this.lightWidthId[t]=e.resolve(`${i}_halfWidth`),this.lightHeight[t]=new Float32Array(3),this.lightHeightId[t]=e.resolve(`${i}_halfHeight`),this.lightInAngleId[t]=e.resolve(`${i}_innerConeAngle`),this.lightOutAngleId[t]=e.resolve(`${i}_outerConeAngle`),this.lightCookieId[t]=e.resolve(`${i}_cookie`),this.lightCookieIntId[t]=e.resolve(`${i}_cookieIntensity`),this.lightCookieMatrixId[t]=e.resolve(`${i}_cookieMatrix`),this.lightCookieOffsetId[t]=e.resolve(`${i}_cookieOffset`),this.lightCameraParamsId[t]=e.resolve(`${i}_cameraParams`),this.lightSoftShadowParamsId[t]=e.resolve(`${i}_softShadowParams`),this.shadowMatrixPaletteId[t]=e.resolve(`${i}_shadowMatrixPalette[0]`),this.shadowCascadeDistancesId[t]=e.resolve(`${i}_shadowCascadeDistances`),this.shadowCascadeCountId[t]=e.resolve(`${i}_shadowCascadeCount`),this.shadowCascadeBlendId[t]=e.resolve(`${i}_shadowCascadeBlend`);}setLTCDirectionalLight(e,t,i,s,r){this.lightPos[t][0]=s.x-i.x*r,this.lightPos[t][1]=s.y-i.y*r,this.lightPos[t][2]=s.z-i.z*r,this.lightPosId[t].setValue(this.lightPos[t]);let a=e.transformVector(new eM(-0.5,0,0));this.lightWidth[t][0]=a.x*r,this.lightWidth[t][1]=a.y*r,this.lightWidth[t][2]=a.z*r,this.lightWidthId[t].setValue(this.lightWidth[t]);let n=e.transformVector(new eM(0,0,.5));this.lightHeight[t][0]=n.x*r,this.lightHeight[t][1]=n.y*r,this.lightHeight[t][2]=n.z*r,this.lightHeightId[t].setValue(this.lightHeight[t]);}dispatchDirectLights(e,t,i){let s=0,r=this.device.scope;for(let a=0;a<e.length;a++){if(!(e[a].mask&t))continue;let n=e[a],o=n._node.getWorldTransform();if(this.lightColorId[s]||this._resolveLight(r,s),this.lightColorId[s].setValue(n._colorLinear),o.getY(n._direction).mulScalar(-1),n._direction.normalize(),this.lightDir[s][0]=n._direction.x,this.lightDir[s][1]=n._direction.y,this.lightDir[s][2]=n._direction.z,this.lightDirId[s].setValue(this.lightDir[s]),n.shape!==uB&&this.setLTCDirectionalLight(o,s,n._direction,i._node.getPosition(),i.farClip),n.castShadows){let e=n.getRenderData(i,0),t=n._getUniformBiasValues(e);this.lightShadowMapId[s].setValue(e.shadowBuffer),this.lightShadowMatrixId[s].setValue(e.shadowMatrix.data),this.shadowMatrixPaletteId[s].setValue(n._shadowMatrixPalette),this.shadowCascadeDistancesId[s].setValue(n._shadowCascadeDistances),this.shadowCascadeCountId[s].setValue(n.numCascades),this.shadowCascadeBlendId[s].setValue(1-n.cascadeBlend),this.lightShadowIntensity[s].setValue(n.shadowIntensity),this.lightSoftShadowParamsId[s].setValue(n._softShadowParams),e.shadowCamera.renderTarget&&this.lightShadowSearchAreaId[s].setValue(n.penumbraSize/e.shadowCamera.renderTarget.width*e.projectionCompensation);let r=n._shadowCameraParams;r.length=4,r[0]=0,r[1]=e.shadowCamera._farClip,r[2]=e.shadowCamera._nearClip,r[3]=1,this.lightCameraParamsId[s].setValue(r);let a=n._shadowRenderParams;a.length=4,a[0]=n._shadowResolution,a[1]=t.normalBias,a[2]=t.bias,a[3]=0,this.lightShadowParamsId[s].setValue(a);}s++;}return s}setLTCPositionalLight(e,t){let i=e.transformVector(new eM(-0.5,0,0));this.lightWidth[t][0]=i.x,this.lightWidth[t][1]=i.y,this.lightWidth[t][2]=i.z,this.lightWidthId[t].setValue(this.lightWidth[t]);let s=e.transformVector(new eM(0,0,.5));this.lightHeight[t][0]=s.x,this.lightHeight[t][1]=s.y,this.lightHeight[t][2]=s.z,this.lightHeightId[t].setValue(this.lightHeight[t]);}dispatchOmniLight(e,t,i){let s=t._node.getWorldTransform();if(this.lightColorId[i]||this._resolveLight(e,i),this.lightRadiusId[i].setValue(t.attenuationEnd),this.lightColorId[i].setValue(t._colorLinear),s.getTranslation(t._position),this.lightPos[i][0]=t._position.x,this.lightPos[i][1]=t._position.y,this.lightPos[i][2]=t._position.z,this.lightPosId[i].setValue(this.lightPos[i]),t.shape!==uB&&this.setLTCPositionalLight(s,i),t.castShadows){let e=t.getRenderData(null,0);this.lightShadowMapId[i].setValue(e.shadowBuffer);let s=t._getUniformBiasValues(e),r=t._shadowRenderParams;r.length=4,r[0]=t._shadowResolution,r[1]=s.normalBias,r[2]=s.bias,r[3]=1/t.attenuationEnd,this.lightShadowParamsId[i].setValue(r),this.lightShadowIntensity[i].setValue(t.shadowIntensity);let a=t.penumbraSize/e.shadowCamera.renderTarget.width;this.lightShadowSearchAreaId[i].setValue(a);let n=t._shadowCameraParams;n.length=4,n[0]=0,n[1]=e.shadowCamera._farClip,n[2]=e.shadowCamera._nearClip,n[3]=0,this.lightCameraParamsId[i].setValue(n);}t._cookie&&(this.lightCookieId[i].setValue(t._cookie),this.lightShadowMatrixId[i].setValue(s.data),this.lightCookieIntId[i].setValue(t.cookieIntensity));}dispatchSpotLight(e,t,i){let s=t._node.getWorldTransform();if(this.lightColorId[i]||this._resolveLight(e,i),this.lightInAngleId[i].setValue(t._innerConeAngleCos),this.lightOutAngleId[i].setValue(t._outerConeAngleCos),this.lightRadiusId[i].setValue(t.attenuationEnd),this.lightColorId[i].setValue(t._colorLinear),s.getTranslation(t._position),this.lightPos[i][0]=t._position.x,this.lightPos[i][1]=t._position.y,this.lightPos[i][2]=t._position.z,this.lightPosId[i].setValue(this.lightPos[i]),t.shape!==uB&&this.setLTCPositionalLight(s,i),s.getY(t._direction).mulScalar(-1),t._direction.normalize(),this.lightDir[i][0]=t._direction.x,this.lightDir[i][1]=t._direction.y,this.lightDir[i][2]=t._direction.z,this.lightDirId[i].setValue(this.lightDir[i]),t.castShadows){let e=t.getRenderData(null,0);this.lightShadowMapId[i].setValue(e.shadowBuffer),this.lightShadowMatrixId[i].setValue(e.shadowMatrix.data);let s=t._getUniformBiasValues(e),r=t._shadowRenderParams;r.length=4,r[0]=t._shadowResolution,r[1]=s.normalBias,r[2]=s.bias,r[3]=1/t.attenuationEnd,this.lightShadowParamsId[i].setValue(r),this.lightShadowIntensity[i].setValue(t.shadowIntensity);let a=t.penumbraSize/e.shadowCamera.renderTarget.width,n=1/Math.tan(e.shadowCamera._fov*Math.PI/180/2);this.lightShadowSearchAreaId[i].setValue(a*n);let o=t._shadowCameraParams;o.length=4,o[0]=0,o[1]=e.shadowCamera._farClip,o[2]=e.shadowCamera._nearClip,o[3]=0,this.lightCameraParamsId[i].setValue(o);}if(t._cookie){if(!t.castShadows){let e=_p.evalSpotCookieMatrix(t);this.lightShadowMatrixId[i].setValue(e.data);}this.lightCookieId[i].setValue(t._cookie),this.lightCookieIntId[i].setValue(t.cookieIntensity),t._cookieTransform&&(t._cookieTransformUniform[0]=t._cookieTransform.x,t._cookieTransformUniform[1]=t._cookieTransform.y,t._cookieTransformUniform[2]=t._cookieTransform.z,t._cookieTransformUniform[3]=t._cookieTransform.w,this.lightCookieMatrixId[i].setValue(t._cookieTransformUniform),t._cookieOffsetUniform[0]=t._cookieOffset.x,t._cookieOffsetUniform[1]=t._cookieOffset.y,this.lightCookieOffsetId[i].setValue(t._cookieOffsetUniform));}}dispatchLocalLights(e,t,i){let s=i,r=this.device.scope,a=e[uD],n=a.length;for(let e=0;e<n;e++){let i=a[e];i.mask&t&&(this.dispatchOmniLight(r,i,s),s++);}let o=e[uM],l=o.length;for(let e=0;e<l;e++){let i=o[e];i.mask&t&&(this.dispatchSpotLight(r,i,s),s++);}}renderForwardPrepareMaterials(e,t,i,s,r,a){let n=e.fogParams??this.scene.fog,o=e.shaderParams;o.fog=n.type,o.srgbRenderTarget=t?.isColorBufferSrgb(0)??false;let l=(e,t,i,s)=>{gF.drawCalls.push(e),gF.shaderInstances.push(t),gF.isNewMaterial.push(i),gF.lightMaskChanged.push(s);};gF.clear();let h=this.device,c=this.scene,d=c.clusteredLightingEnabled,u=r?.getLightHash(d)??0,f=null,p,m,_=i.length;for(let e=0;e<_;e++){let t=i[e],r=t.instancingData;if(r&&r.count<=0)continue;t.ensureMaterial(h);let n=t.material,d=t._shaderDefs,_=t.mask;n&&n===f&&d!==p&&(f=null),n!==f&&(this._materialSwitches++,n._scene=c,n.dirty&&(n.updateUniforms(h,c),n.dirty=false));let g=t.getShaderInstance(a,u,c,o,this.viewUniformFormat,this.viewBindGroupFormat,s);l(t,g,n!==f,!f||_!==m),f=n,p=d,m=_;}return gF}renderForwardInternal(e,t,i,s,r,a,n){let o=this.device,l=this.scene,h=1<<s,c=a?-1:1,d=l.clusteredLightingEnabled,u=e.xr?.session&&e.xr.views.list.length?e.xr.views.list:null,f=t.drawCalls.length;for(let s=0;s<f;s++){let a=t.drawCalls[s],l=t.isNewMaterial[s],p=t.lightMaskChanged[s],m=t.shaderInstances[s],_=a.material,g=a.mask;if(m.shader.failed)continue;if(l){if(o.setShader(m.shader,false),_.setParameters(o),p){let t=this.dispatchDirectLights(i[uI],g,e);d||this.dispatchLocalLights(i,g,t);}this.alphaTestId.setValue(_.alphaTest),o.setBlendState(_.blendState),o.setDepthState(_.depthState),o.setAlphaToCoverage(_.alphaToCoverage);}this.setupCullMode(e._cullFaces,c,a);let v=a.stencilFront??_.stencilFront,S=a.stencilBack??_.stencilBack;o.setStencilState(v,S),a.setParameters(o,h),o.scope.resolve("meshInstanceId").setValue(a.id);let y=a.mesh;this.setVertexBuffers(o,y),this.setMorphing(o,a.morphInstance),this.setSkinning(o,a);let x=a.instancingData;x&&o.setVertexBuffer(x.vertexBuffer),this.setMeshInstanceMatrices(a,true),this.setupMeshUniformBuffers(m);let T=a.renderStyle,E=y.indexBuffer[T];r?.(a,s);let A=a.indirectData?.get(e);if(u)for(let e=0;e<u.length;e++){let t=u[e];if(o.setViewport(t.viewport.x,t.viewport.y,t.viewport.z,t.viewport.w),o.supportsUniformBuffers){let t=n[e];o.setBindGroup(aH,t);}else this.setupViewUniforms(t,e);let i=0===e,s=e===u.length-1;o.draw(y.primitive[T],E,x?.count,A,i,s),this._forwardDrawCalls++,a.instancingData&&this._instancedDrawCalls++;}else o.draw(y.primitive[T],E,x?.count,A),this._forwardDrawCalls++,a.instancingData&&this._instancedDrawCalls++;s<f-1&&!t.isNewMaterial[s+1]&&_.setParameters(o,a.parameters);}}renderForward(e,t,i,s,r,a,n,o,l){let h=this.renderForwardPrepareMaterials(e,t,i,s,n,r);this.renderForwardInternal(e,h,s,r,a,o,l),gF.clear();}renderForwardLayer(e,t,i,s,r,a,n={}){let o,l,{scene:h,device:c}=this,d=h.clusteredLightingEnabled;if(this.setupViewport(e,t),i){i.sortVisible(e,s);let t=i.getCulledInstances(e);o=s?t.transparent:t.opaque,h.immediate.onPreRenderLayer(i,o,s),i.requiresLightCube&&(this.lightCube.update(h.ambientLight,i._lights),this.constantLightCube.setValue(this.lightCube.colors)),l=i.splitLights;}else o=n.meshInstances,l=n.splitLights??gO;d&&((n.lightClusters??this.worldClustersAllocator.empty).activate(),i&&!this.clustersDebugRendered&&h.lighting.debugLayer===i.id&&(this.clustersDebugRendered=true)),h._activeCamera=e;let u=e.fogParams??this.scene.fog;this.setFogConstants(u);let f=this.setCameraUniforms(e,t);c.supportsUniformBuffers&&this.setupViewUniformBuffers(a,this.viewUniformFormat,this.viewBindGroupFormat,f);let p=n.clearColor??false,m=n.clearDepth??false,_=n.clearStencil??false;(p||m||_)&&this.clear(e,p,m,_);let g=!!(e._flipFaces^t?.flipY),v=this._forwardDrawCalls;this.renderForward(e,t,o,l,r,null,i,g,a),i&&(i._forwardDrawCalls+=this._forwardDrawCalls-v);}setFogConstants(e){if(e.type!==um){gN.linear(e.color);let t=this.fogColor;t[0]=gN.r,t[1]=gN.g,t[2]=gN.b,this.fogColorId.setValue(t),e.type===u_?(this.fogStartId.setValue(e.start),this.fogEndId.setValue(e.end)):this.fogDensityId.setValue(e.density);}}setSceneConstants(){let e=this.scene;this.dispatchGlobalLights(e);let t=this.device;this._screenSize[0]=t.width,this._screenSize[1]=t.height,this._screenSize[2]=1/t.width,this._screenSize[3]=1/t.height,this.screenSizeId.setValue(this._screenSize),this.pcssDiskSamplesId.setValue(this.pcssDiskSamples),this.pcssSphereSamplesId.setValue(this.pcssSphereSamples);}buildFrameGraph(e,t){let i=this.scene;if(e.reset(),i.clusteredLightingEnabled){let{shadowsEnabled:t,cookiesEnabled:s}=i.lighting;this._renderPassUpdateClustered.update(e,t,s,this.lights,this.localLights),e.addRenderPass(this._renderPassUpdateClustered);}else this._shadowRendererLocal.buildNonClusteredRenderPasses(e,this.localLights);let s=0,r=true,a=null,n=t._renderActions;for(let i=s;i<n.length;i++){let o=n[i],{layer:l,camera:h}=o;if(o.useCameraPasses)h.camera.renderPasses.forEach(t=>{e.addRenderPass(t);});else {let c=l.id===uw,d=c&&(h.renderSceneColorMap||h.renderSceneDepthMap);r&&(r=false,s=i,a=o.renderTarget);let u=n[i+1],f=!!u&&!u.useCameraPasses&&u.layer.id===uw&&(h.renderSceneColorMap||h.renderSceneDepthMap),p=!!u&&u.firstCameraUse&&this.cameraDirShadowLights.has(u.camera.camera);if(!u||u.renderTarget!==a||p||f||d){if(c&&s===i||this.addMainRenderPass(e,t,a,s,i),c){if(h.renderSceneColorMap){let t=h.camera.renderPassColorGrab;t.source=h.renderTarget,e.addRenderPass(t);}h.renderSceneDepthMap&&e.addRenderPass(h.camera.renderPassDepthGrab);}if(o.triggerPostprocess&&h?.onPostprocessing){let t=new gM(this.device,this,o);e.addRenderPass(t);}r=true;}}}}addMainRenderPass(e,t,i,s,r){let a=new gR(this.device,t,this.scene,this);a.init(i);let n=t._renderActions;for(let e=s;e<=r;e++)a.addRenderAction(n[e]);e.addRenderPass(a);}update(e){this.frameUpdate(),this.shadowRenderer.frameUpdate(),this.scene._updateSkyMesh(),this.updateLayerComposition(e),this.collectLights(e),this.beginFrame(e),this.setSceneConstants(),this.cullComposition(e),this.gpuUpdate(this.processingMeshInstances);}}let gU=0,gk=[],gV=new Set,gz=[null,function(e,t){return e.drawOrder-t.drawOrder},function(e,t){let i=e._sortKeyForward,s=t._sortKeyForward;return i===s?t.mesh.id-e.mesh.id:s-i},function(e,t){return t._sortKeyDynamic-e._sortKeyDynamic},function(e,t){return e._sortKeyDynamic-t._sortKeyDynamic}];class gG{constructor(){this.opaque=[],this.transparent=[];}}class gH{constructor(e={}){this.meshInstances=[],this.meshInstancesSet=new Set,this.shadowCasters=[],this.shadowCastersSet=new Set,this._visibleInstances=new WeakMap,this._lights=[],this._lightsSet=new Set,this._clusteredLightsSet=new Set,this._splitLights=[[],[],[]],this._splitLightsDirty=true,this.requiresLightCube=false,this.cameras=[],this.camerasSet=new Set,this._dirtyComposition=false,void 0!==e.id?(this.id=e.id,gU=Math.max(this.id+1,gU)):this.id=gU++,this.name=e.name,this._enabled=e.enabled??true,this._refCounter=+!!this._enabled,this.opaqueSortMode=e.opaqueSortMode??pF,this.transparentSortMode=e.transparentSortMode??pB,e.renderTarget&&(this.renderTarget=e.renderTarget),this._clearColorBuffer=!!e.clearColorBuffer,this._clearDepthBuffer=!!e.clearDepthBuffer,this._clearStencilBuffer=!!e.clearStencilBuffer,this.onEnable=e.onEnable,this.onDisable=e.onDisable,this._enabled&&this.onEnable&&this.onEnable(),this.customSortCallback=null,this.customCalculateSortValues=null,this._lightHash=0,this._lightHashDirty=false,this._lightIdHash=0,this._lightIdHashDirty=false,this._shaderVersion=-1;}set enabled(e){e!==this._enabled&&(this._dirtyComposition=true,this._enabled=e,e?(this.incrementCounter(),this.onEnable&&this.onEnable()):(this.decrementCounter(),this.onDisable&&this.onDisable()));}get enabled(){return this._enabled}set clearColorBuffer(e){this._clearColorBuffer=e,this._dirtyComposition=true;}get clearColorBuffer(){return this._clearColorBuffer}set clearDepthBuffer(e){this._clearDepthBuffer=e,this._dirtyComposition=true;}get clearDepthBuffer(){return this._clearDepthBuffer}set clearStencilBuffer(e){this._clearStencilBuffer=e,this._dirtyComposition=true;}get clearStencilBuffer(){return this._clearStencilBuffer}get hasClusteredLights(){return this._clusteredLightsSet.size>0}get clusteredLightsSet(){return this._clusteredLightsSet}incrementCounter(){0===this._refCounter&&(this._enabled=true,this.onEnable&&this.onEnable()),this._refCounter++;}decrementCounter(){if(1===this._refCounter)this._enabled=false,this.onDisable&&this.onDisable();else if(0===this._refCounter)return;this._refCounter--;}addMeshInstances(e,t){let i=this.meshInstances,s=this.meshInstancesSet;for(let t=0;t<e.length;t++){let r=e[t];s.has(r)||(i.push(r),s.add(r),gV.add(r.material));}if(t||this.addShadowCasters(e),gV.size>0){let e=this._shaderVersion;gV.forEach(t=>{e>=0&&t._shaderVersion!==e&&(t.getShaderVariant!==_$.prototype.getShaderVariant&&t.clearVariants(),t._shaderVersion=e);}),gV.clear();}}removeMeshInstances(e,t){let i=this.meshInstances,s=this.meshInstancesSet;for(let t=0;t<e.length;t++){let r=e[t];if(s.has(r)){s.delete(r);let e=i.indexOf(r);e>=0&&i.splice(e,1);}}t||this.removeShadowCasters(e);}addShadowCasters(e){let t=this.shadowCasters,i=this.shadowCastersSet;for(let s=0;s<e.length;s++){let r=e[s];r.castShadow&&!i.has(r)&&(i.add(r),t.push(r));}}removeShadowCasters(e){let t=this.shadowCasters,i=this.shadowCastersSet;for(let s=0;s<e.length;s++){let r=e[s];if(i.has(r)){i.delete(r);let e=t.indexOf(r);e>=0&&t.splice(e,1);}}}clearMeshInstances(e=false){this.meshInstances.length=0,this.meshInstancesSet.clear(),e||(this.shadowCasters.length=0,this.shadowCastersSet.clear());}markLightsDirty(){this._lightHashDirty=true,this._lightIdHashDirty=true,this._splitLightsDirty=true;}hasLight(e){return this._lightsSet.has(e)}addLight(e){let t=e.light;this._lightsSet.has(t)||(this._lightsSet.add(t),this._lights.push(t),this.markLightsDirty()),t.type!==uI&&this._clusteredLightsSet.add(t);}removeLight(e){let t=e.light;this._lightsSet.has(t)&&(this._lightsSet.delete(t),this._lights.splice(this._lights.indexOf(t),1),this.markLightsDirty()),t.type!==uI&&this._clusteredLightsSet.delete(t);}clearLights(){this._lightsSet.forEach(e=>e.removeLayer(this)),this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this.markLightsDirty();}get splitLights(){if(this._splitLightsDirty){this._splitLightsDirty=false;let e=this._splitLights;for(let t=0;t<e.length;t++)e[t].length=0;let t=this._lights;for(let i=0;i<t.length;i++){let s=t[i];s.enabled&&e[s._type].push(s);}for(let t=0;t<e.length;t++)e[t].sort((e,t)=>e.key-t.key);}return this._splitLights}evaluateLightHash(e,t,i){let s=0,r=this._lights;for(let s=0;s<r.length;s++){let a=r[s].type!==uI;(e&&a||t&&!a)&&gk.push(i?r[s].id:r[s].key);}return gk.length>0&&(gk.sort(),s=nA(gk),gk.length=0),s}getLightHash(e){return this._lightHashDirty&&(this._lightHashDirty=false,this._lightHash=this.evaluateLightHash(!e,true,false)),this._lightHash}getLightIdHash(){return this._lightIdHashDirty&&(this._lightIdHashDirty=false,this._lightIdHash=this.evaluateLightHash(true,false,true)),this._lightIdHash}addCamera(e){this.camerasSet.has(e.camera)||(this.camerasSet.add(e.camera),this.cameras.push(e),this._dirtyComposition=true);}removeCamera(e){if(this.camerasSet.has(e.camera)){this.camerasSet.delete(e.camera);let t=this.cameras.indexOf(e);this.cameras.splice(t,1),this._dirtyComposition=true;}}clearCameras(){this.cameras.length=0,this.camerasSet.clear(),this._dirtyComposition=true;}_calculateSortDistances(e,t,i){let s=e.length,{x:r,y:a,z:n}=t,{x:o,y:l,z:h}=i;for(let c=0;c<s;c++){let s,d=e[c];if(d.calculateSortDistance)s=d.calculateSortDistance(d,t,i);else {let e=d.aabb.center;s=(e.x-r)*o+(e.y-a)*l+(e.z-n)*h;}let u=1e9*d._drawBucket;d._sortKeyDynamic=u+s;}}getCulledInstances(e){let t=this._visibleInstances.get(e);return t||(t=new gG,this._visibleInstances.set(e,t)),t}sortVisible(e,t){let i=t?this.transparentSortMode:this.opaqueSortMode;if(i===pO)return;let s=this.getCulledInstances(e),r=t?s.transparent:s.opaque,a=e.node;if(i===pk){let e=a.getPosition(),t=a.forward;this.customCalculateSortValues&&this.customCalculateSortValues(r,r.length,e,t),this.customSortCallback&&r.sort(this.customSortCallback);}else {if(i===pB||i===pU){let e=a.getPosition(),t=a.forward;this._calculateSortDistances(r,e,t);}r.sort(gz[i]);}}}let gW=(e,t)=>e.priority-t.priority,gX=e=>e.sort(gW);class gY extends eo{constructor(e="Untitled"){super(),this.layerList=[],this.layerIdMap=new Map,this.layerNameMap=new Map,this.layerOpaqueIndexMap=new Map,this.layerTransparentIndexMap=new Map,this.subLayerList=[],this.subLayerEnabled=[],this.cameras=[],this._renderActions=[],this._dirty=false,this.name=e,this._opaqueOrder={},this._transparentOrder={};}destroy(){this.destroyRenderActions();}destroyRenderActions(){this._renderActions.forEach(e=>e.destroy()),this._renderActions.length=0;}markDirty(){this._dirty=true;}_update(){let e=this.layerList.length;if(!this._dirty){for(let t=0;t<e;t++)if(this.layerList[t]._dirtyComposition){this._dirty=true;break}}if(this._dirty){this._dirty=false,this.cameras.length=0;for(let t=0;t<e;t++){let e=this.layerList[t];e._dirtyComposition=false;for(let t=0;t<e.cameras.length;t++){let i=e.cameras[t];0>this.cameras.indexOf(i)&&this.cameras.push(i);}}this.cameras.length>1&&gX(this.cameras);let t=0;this.destroyRenderActions();for(let i=0;i<this.cameras.length;i++){let s=this.cameras[i];if(s.camera.renderPasses.length>0){this.addDummyRenderAction(t,s),t++;continue}let r=true,a=t,n=null,o=false;for(let i=0;i<e;i++){let e=this.layerList[i];if(e.enabled&&this.subLayerEnabled[i]&&e.cameras.length>0&&s.layers.indexOf(e.id)>=0){!o&&e.id===s.disablePostEffectsLayer&&(o=true,n&&(n.triggerPostprocess=true));let a=this.subLayerList[i];n=this.addRenderAction(t,e,a,s,r,o),t++,r=false;}}a<t&&(n.lastCameraUse=true),!o&&n&&(n.triggerPostprocess=true),s.renderTarget&&s.postEffectsEnabled&&this.propagateRenderTarget(a-1,s);}this._logRenderActions();}}getNextRenderAction(e){let t=new gD;return this._renderActions.push(t),t}addDummyRenderAction(e,t){let i=this.getNextRenderAction(e);i.camera=t,i.useCameraPasses=true;}addRenderAction(e,t,i,s,r,a){let n=t.id!==uw?s.renderTarget:null,o=false,l=this._renderActions;for(let t=e-1;t>=0;t--)if(l[t].camera===s&&l[t].renderTarget===n){o=true;break}a&&s.postEffectsEnabled&&(n=null);let h=this.getNextRenderAction(e);h.triggerPostprocess=false,h.layer=t,h.transparent=i,h.camera=s,h.renderTarget=n,h.firstCameraUse=r,h.lastCameraUse=false;let c=r||!o,d=t.clearColorBuffer||t.clearDepthBuffer||t.clearStencilBuffer;return (c||d)&&h.setupClears(c?s:void 0,t),h}propagateRenderTarget(e,t){for(let i=e;i>=0;i--){let e=this._renderActions[i],s=e.layer;if(e.renderTarget&&s.id!==uw)break;if(s.id===uw)continue;if(e.useCameraPasses)break;let r=e?.camera.camera;if(r&&(!t.camera.rect.equals(r.rect)||!t.camera.scissorRect.equals(r.scissorRect)))break;e.renderTarget=t.renderTarget;}}_logRenderActions(){}_isLayerAdded(e){return this.layerIdMap.get(e.id)===e}_isSublayerAdded(e,t){return void 0!==(t?this.layerTransparentIndexMap:this.layerOpaqueIndexMap).get(e)}push(e){this._isLayerAdded(e)||(this.layerList.push(e),this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(false)-1,this._transparentOrder[e.id]=this.subLayerList.push(true)-1,this.subLayerEnabled.push(true),this.subLayerEnabled.push(true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e));}insert(e,t){if(this._isLayerAdded(e))return;this.layerList.splice(t,0,e,e),this.subLayerList.splice(t,0,false,true);let i=this.layerList.length;this._updateOpaqueOrder(t,i-1),this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,0,true,true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e);}remove(e){let t=this.layerList.indexOf(e);for(delete this._opaqueOrder[t],delete this._transparentOrder[t];t>=0;)this.layerList.splice(t,1),this.subLayerList.splice(t,1),this.subLayerEnabled.splice(t,1),t=this.layerList.indexOf(e),this._dirty=true,this.fire("remove",e);let i=this.layerList.length;this._updateOpaqueOrder(0,i-1),this._updateTransparentOrder(0,i-1),this._updateLayerMaps();}pushOpaque(e){this._isSublayerAdded(e,false)||(this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(false)-1,this.subLayerEnabled.push(true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e));}insertOpaque(e,t){if(this._isSublayerAdded(e,false))return;this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,false);let i=this.subLayerList.length;this._updateOpaqueOrder(t,i-1),this.subLayerEnabled.splice(t,0,true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e);}removeOpaque(e){for(let t=0,i=this.layerList.length;t<i;t++)if(this.layerList[t]===e&&!this.subLayerList[t]){this.layerList.splice(t,1),this.subLayerList.splice(t,1),i--,this._updateOpaqueOrder(t,i-1),this.subLayerEnabled.splice(t,1),this._dirty=true,0>this.layerList.indexOf(e)&&this.fire("remove",e);break}this._updateLayerMaps();}pushTransparent(e){this._isSublayerAdded(e,true)||(this.layerList.push(e),this._transparentOrder[e.id]=this.subLayerList.push(true)-1,this.subLayerEnabled.push(true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e));}insertTransparent(e,t){if(this._isSublayerAdded(e,true))return;this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,true);let i=this.subLayerList.length;this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,0,true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e);}removeTransparent(e){for(let t=0,i=this.layerList.length;t<i;t++)if(this.layerList[t]===e&&this.subLayerList[t]){this.layerList.splice(t,1),this.subLayerList.splice(t,1),i--,this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,1),this._dirty=true,0>this.layerList.indexOf(e)&&this.fire("remove",e);break}this._updateLayerMaps();}getOpaqueIndex(e){return this.layerOpaqueIndexMap.get(e)??-1}getTransparentIndex(e){return this.layerTransparentIndexMap.get(e)??-1}isEnabled(e,t){if(e.enabled){let i=t?this.getTransparentIndex(e):this.getOpaqueIndex(e);if(i>=0)return this.subLayerEnabled[i]}return false}_updateLayerMaps(){this.layerIdMap.clear(),this.layerNameMap.clear(),this.layerOpaqueIndexMap.clear(),this.layerTransparentIndexMap.clear();for(let e=0;e<this.layerList.length;e++){let t=this.layerList[e];this.layerIdMap.set(t.id,t),this.layerNameMap.set(t.name,t),(this.subLayerList[e]?this.layerTransparentIndexMap:this.layerOpaqueIndexMap).set(t,e);}}getLayerById(e){return this.layerIdMap.get(e)??null}getLayerByName(e){return this.layerNameMap.get(e)??null}_updateOpaqueOrder(e,t){for(let i=e;i<=t;i++) false===this.subLayerList[i]&&(this._opaqueOrder[this.layerList[i].id]=i);}_updateTransparentOrder(e,t){for(let i=e;i<=t;i++) true===this.subLayerList[i]&&(this._transparentOrder[this.layerList[i].id]=i);}_sortLayersDescending(e,t,i){let s=-1,r=-1;for(let t=0,r=e.length;t<r;t++){let r=e[t];i.hasOwnProperty(r)&&(s=Math.max(s,i[r]));}for(let e=0,s=t.length;e<s;e++){let s=t[e];i.hasOwnProperty(s)&&(r=Math.max(r,i[s]));}return -1===s&&-1!==r?1:-1===r&&-1!==s?-1:r-s}sortTransparentLayers(e,t){return this._sortLayersDescending(e,t,this._transparentOrder)}sortOpaqueLayers(e,t){return this._sortLayersDescending(e,t,this._opaqueOrder)}}let gq=new eM,g$={bias:0,normalBias:0},gj=new eb,gK={r:0,g:1,b:2,a:3},gZ={directional:uI,omni:uD,point:uD,spot:uM},gQ=[[new eF(0,0,1,1)],[new eF(0,0,.5,.5),new eF(0,.5,.5,.5)],[new eF(0,0,.5,.5),new eF(0,.5,.5,.5),new eF(.5,0,.5,.5)],[new eF(0,0,.5,.5),new eF(0,.5,.5,.5),new eF(.5,0,.5,.5),new eF(.5,.5,.5,.5)]],gJ={rrr:1,ggg:2,bbb:4,aaa:8,rgb:7},g0=0;class g1{constructor(e,t,i){this.light=i,this.camera=e,this.shadowCamera=gt.createShadowCamera(i._shadowType,i._type,t),this.shadowMatrix=new eG,this.shadowViewport=new eF(0,0,1,1),this.shadowScissor=new eF(0,0,1,1),this.projectionCompensation=0,this.face=t,this.visibleCasters=[],this.viewBindGroups=[];}destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;}get shadowBuffer(){let e=this.shadowCamera.renderTarget;return e?this.light._isPcf?e.depthBuffer:e.colorBuffer:null}}class g2{constructor(e,t){this.layers=new Set,this.shadowDepthState=nm.DEFAULT.clone(),this.clusteredFlags=0,this.clusteredData=new Uint32Array(3),this.clusteredData16=new Uint16Array(this.clusteredData.buffer),this._evtDeviceRestored=null,this.device=e,this.clusteredLighting=t,this.id=g0++,this._evtDeviceRestored=e.on("devicerestored",this.onDeviceRestored,this),this._type=uI,this._color=new eb(.8,.8,.8),this._intensity=1,this._affectSpecularity=true,this._luminance=0,this._castShadows=false,this._enabled=false,this._mask=po,this.isStatic=false,this.key=0,this.bakeDir=true,this.bakeNumSamples=1,this.bakeArea=0,this.attenuationStart=10,this.attenuationEnd=10,this._falloffMode=uG,this._shadowType=uX,this._vsmBlurSize=11,this.vsmBlurMode=fi,this.vsmBias=.0025,this._cookie=null,this.cookieIntensity=1,this._cookieFalloff=true,this._cookieChannel="rgb",this._cookieTransform=null,this._cookieTransformUniform=new Float32Array(4),this._cookieOffset=null,this._cookieOffsetUniform=new Float32Array(2),this._cookieTransformSet=false,this._cookieOffsetSet=false,this._innerConeAngle=40,this._outerConeAngle=45,this.cascades=null,this._shadowMatrixPalette=null,this._shadowCascadeDistances=null,this.numCascades=1,this._cascadeBlend=0,this.cascadeDistribution=.5,this._shape=uB,this._colorLinear=new Float32Array(3),this._updateLinearColor(),this._position=new eM(0,0,0),this._direction=new eM(0,0,0),this._innerConeAngleCos=Math.cos(this._innerConeAngle*Math.PI/180),this._updateOuterAngle(this._outerConeAngle),this._usePhysicalUnits=void 0,this._shadowMap=null,this._shadowRenderParams=[],this._shadowCameraParams=[],this.shadowDistance=40,this._shadowResolution=1024,this._shadowBias=-5e-4,this._shadowIntensity=1,this._normalOffsetBias=0,this.shadowUpdateMode=pn,this.shadowUpdateOverrides=null,this._isVsm=false,this._isPcf=true,this._softShadowParams=new Float32Array(4),this.shadowSamples=16,this.shadowBlockerSamples=16,this.penumbraSize=1,this.penumbraFalloff=1,this._cookieMatrix=null,this._atlasViewport=null,this.atlasViewportAllocated=false,this.atlasVersion=0,this.atlasSlotIndex=0,this.atlasSlotUpdated=false,this._node=null,this._renderData=[],this.visibleThisFrame=false,this.maxScreenSize=0,this._updateShadowBias();}destroy(){this._evtDeviceRestored?.off(),this._evtDeviceRestored=null,this._destroyShadowMap(),this.releaseRenderData(),this._renderData=null;}onDeviceRestored(){this.shadowUpdateMode===pr&&(this.shadowUpdateMode=pa);}releaseRenderData(){if(this._renderData){for(let e=0;e<this._renderData.length;e++)this._renderData[e].destroy();this._renderData.length=0;}}addLayer(e){this.layers.add(e);}removeLayer(e){this.layers.delete(e);}set shadowSamples(e){this._softShadowParams[0]=e;}get shadowSamples(){return this._softShadowParams[0]}set shadowBlockerSamples(e){this._softShadowParams[1]=e;}get shadowBlockerSamples(){return this._softShadowParams[1]}set shadowBias(e){this._shadowBias!==e&&(this._shadowBias=e,this._updateShadowBias());}get shadowBias(){return this._shadowBias}set numCascades(e){this.cascades&&this.numCascades===e||(this.cascades=gQ[e-1],this._shadowMatrixPalette=new Float32Array(64),this._shadowCascadeDistances=new Float32Array(4),this._destroyShadowMap(),this.updateKey());}get numCascades(){return this.cascades.length}set cascadeBlend(e){this._cascadeBlend!==e&&(this._cascadeBlend=e,this.updateKey());}get cascadeBlend(){return this._cascadeBlend}set shadowMap(e){this._shadowMap!==e&&(this._destroyShadowMap(),this._shadowMap=e);}get shadowMap(){return this._shadowMap}set mask(e){this._mask!==e&&(this._mask=e,this.updateKey(),this.updateClusteredFlags());}get mask(){return this._mask}get numShadowFaces(){let e=this._type;return e===uI?this.numCascades:e===uD?6:1}set type(e){if(this._type===e)return;this._type=e,this._destroyShadowMap(),this._updateShadowBias(),this.updateKey(),this.updateClusteredFlags();let t=this._shadowType;this._shadowType=null,this.shadowUpdateOverrides=null,this.shadowType=t;}get type(){return this._type}set shape(e){if(this._shape===e)return;this._shape=e,this._destroyShadowMap(),this.updateKey(),this.updateClusteredFlags();let t=this._shadowType;this._shadowType=null,this.shadowType=t;}get shape(){return this._shape}set usePhysicalUnits(e){this._usePhysicalUnits!==e&&(this._usePhysicalUnits=e,this._updateLinearColor());}get usePhysicalUnits(){return this._usePhysicalUnits}set shadowType(e){if(this._shadowType===e)return;let t=u5.get(e);t||(e=uX);let i=this.device;e!==u1||i.textureFloatRenderable||i.textureHalfFloatRenderable||(e=uX),this._type===uD&&e!==uJ&&e!==uX&&e!==u2&&e!==u3&&e!==u1&&(e=uX),e!==uj||i.textureFloatRenderable&&i.textureFloatFilterable||(e=uq),e!==uq||i.textureHalfFloatRenderable||(e=uX),t=u5.get(e),this._isVsm=t?.vsm??false,this._isPcf=t?.pcf??false,this._shadowType=e,this._destroyShadowMap(),this.updateKey();}get shadowType(){return this._shadowType}set enabled(e){this._enabled!==e&&(this._enabled=e,this.layersDirty());}get enabled(){return this._enabled}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this._destroyShadowMap(),this.layersDirty(),this.updateKey());}get castShadows(){return this._castShadows&&this._mask!==ph&&0!==this._mask}set shadowIntensity(e){this._shadowIntensity!==e&&(this._shadowIntensity=e,this.updateKey());}get shadowIntensity(){return this._shadowIntensity}get bakeShadows(){return this._castShadows&&this._mask===ph}set shadowResolution(e){this._shadowResolution!==e&&(e=this._type===uD?Math.min(e,this.device.maxCubeMapSize):Math.min(e,this.device.maxTextureSize),this._shadowResolution=e,this._destroyShadowMap());}get shadowResolution(){return this._shadowResolution}set vsmBlurSize(e){this._vsmBlurSize!==e&&(e%2==0&&e++,this._vsmBlurSize=e);}get vsmBlurSize(){return this._vsmBlurSize}set normalOffsetBias(e){if(this._normalOffsetBias!==e){let t=!this._normalOffsetBias&&e||this._normalOffsetBias&&!e;this._normalOffsetBias=e,t&&this.updateKey();}}get normalOffsetBias(){return this._normalOffsetBias}set falloffMode(e){this._falloffMode!==e&&(this._falloffMode=e,this.updateKey(),this.updateClusteredFlags());}get falloffMode(){return this._falloffMode}set innerConeAngle(e){this._innerConeAngle!==e&&(this._innerConeAngle=e,this._innerConeAngleCos=Math.cos(e*Math.PI/180),this.updateClusterData(false,true),this._usePhysicalUnits&&this._updateLinearColor());}get innerConeAngle(){return this._innerConeAngle}set outerConeAngle(e){this._outerConeAngle!==e&&(this._outerConeAngle=e,this._updateOuterAngle(e),this._usePhysicalUnits&&this._updateLinearColor());}get outerConeAngle(){return this._outerConeAngle}set penumbraSize(e){this._penumbraSize=e,this._softShadowParams[2]=e;}get penumbraSize(){return this._penumbraSize}set penumbraFalloff(e){this._softShadowParams[3]=e;}get penumbraFalloff(){return this._softShadowParams[3]}_updateOuterAngle(e){let t=e*Math.PI/180;this._outerConeAngleCos=Math.cos(t),this._outerConeAngleSin=Math.sin(t),this.updateClusterData(false,true);}set intensity(e){this._intensity!==e&&(this._intensity=e,this._updateLinearColor());}get intensity(){return this._intensity}set affectSpecularity(e){this._type===uI&&(this._affectSpecularity=e,this.updateKey());}get affectSpecularity(){return this._affectSpecularity}set luminance(e){this._luminance!==e&&(this._luminance=e,this._updateLinearColor());}get luminance(){return this._luminance}get cookieMatrix(){return this._cookieMatrix||(this._cookieMatrix=new eG),this._cookieMatrix}get atlasViewport(){return this._atlasViewport||(this._atlasViewport=new eF(0,0,1,1)),this._atlasViewport}set cookie(e){this._cookie!==e&&(this._cookie=e,this.updateKey());}get cookie(){return this._cookie}set cookieFalloff(e){this._cookieFalloff!==e&&(this._cookieFalloff=e,this.updateKey());}get cookieFalloff(){return this._cookieFalloff}set cookieChannel(e){if(this._cookieChannel!==e){if(e.length<3){let t=e.charAt(e.length-1),i=3-e.length;for(let s=0;s<i;s++)e+=t;}this._cookieChannel=e,this.updateKey(),this.updateClusteredFlags();}}get cookieChannel(){return this._cookieChannel}set cookieTransform(e){this._cookieTransform!==e&&(this._cookieTransform=e,this._cookieTransformSet=!!e,e&&!this._cookieOffset&&(this.cookieOffset=new eN,this._cookieOffsetSet=false),this.updateKey());}get cookieTransform(){return this._cookieTransform}set cookieOffset(e){this._cookieOffset!==e&&((this._cookieTransformSet||e)&&!e&&this._cookieOffset?this._cookieOffset.set(0,0):this._cookieOffset=e,this._cookieOffsetSet=!!e,e&&!this._cookieTransform&&(this.cookieTransform=new eF(1,1,0,0),this._cookieTransformSet=false),this.updateKey());}get cookieOffset(){return this._cookieOffset}beginFrame(){this.visibleThisFrame=this._type===uI&&this._enabled,this.maxScreenSize=0,this.atlasViewportAllocated=false,this.atlasSlotUpdated=false;}_destroyShadowMap(){if(this.releaseRenderData(),this._shadowMap&&(this._shadowMap.cached||this._shadowMap.destroy(),this._shadowMap=null),this.shadowUpdateMode===pr&&(this.shadowUpdateMode=pa),this.shadowUpdateOverrides)for(let e=0;e<this.shadowUpdateOverrides.length;e++)this.shadowUpdateOverrides[e]===pr&&(this.shadowUpdateOverrides[e]=pa);}getRenderData(e,t){for(let i=0;i<this._renderData.length;i++){let s=this._renderData[i];if(s.camera===e&&s.face===t)return s}let i=new g1(e,t,this);return this._renderData.push(i),i}clone(){let e=new g2(this.device,this.clusteredLighting);return e.type=this._type,e.setColor(this._color),e.intensity=this._intensity,e.affectSpecularity=this._affectSpecularity,e.luminance=this._luminance,e.castShadows=this.castShadows,e._enabled=this._enabled,e.attenuationStart=this.attenuationStart,e.attenuationEnd=this.attenuationEnd,e.falloffMode=this._falloffMode,e.shadowType=this._shadowType,e.vsmBlurSize=this._vsmBlurSize,e.vsmBlurMode=this.vsmBlurMode,e.vsmBias=this.vsmBias,e.shadowUpdateMode=this.shadowUpdateMode,e.mask=this.mask,this.shadowUpdateOverrides&&(e.shadowUpdateOverrides=this.shadowUpdateOverrides.slice()),e.innerConeAngle=this._innerConeAngle,e.outerConeAngle=this._outerConeAngle,e.numCascades=this.numCascades,e.cascadeDistribution=this.cascadeDistribution,e.cascadeBlend=this._cascadeBlend,e.shape=this._shape,e.shadowDepthState.copy(this.shadowDepthState),e.shadowBias=this.shadowBias,e.normalOffsetBias=this._normalOffsetBias,e.shadowResolution=this._shadowResolution,e.shadowDistance=this.shadowDistance,e.shadowIntensity=this.shadowIntensity,e.shadowSamples=this.shadowSamples,e.shadowBlockerSamples=this.shadowBlockerSamples,e.penumbraSize=this.penumbraSize,e.penumbraFalloff=this.penumbraFalloff,e}static getLightUnitConversion(e,t=Math.PI/4,i=0){switch(e){case uM:{let e=Math.cos(i);return 2*Math.PI*(1-e+(e-Math.cos(t))/2)}case uD:return 4*Math.PI;case uI:return 1}}_getUniformBiasValues(e){let t=e.shadowCamera._farClip;switch(this._type){case uD:g$.bias=this.shadowBias,g$.normalBias=this._normalOffsetBias;break;case uM:this._isVsm?g$.bias=-2e-4:g$.bias=20*this.shadowBias,g$.normalBias=this._isVsm?this.vsmBias/(this.attenuationEnd/7):this._normalOffsetBias;break;case uI:this._isVsm?g$.bias=-2e-4:g$.bias=this.shadowBias/t*100,g$.normalBias=this._isVsm?this.vsmBias/(t/7):this._normalOffsetBias;}return g$}getColor(){return this._color}getBoundingSphere(e){if(this._type===uM){let t=this.attenuationEnd,i=this._outerConeAngle,s=this._outerConeAngleCos,r=this._node;gq.copy(r.up),i>45?(e.radius=t*this._outerConeAngleSin,gq.mulScalar(-t*s)):(e.radius=t/(2*s),gq.mulScalar(-e.radius)),e.center.add2(r.getPosition(),gq);}else this._type===uD&&(e.center=this._node.getPosition(),e.radius=this.attenuationEnd);}getBoundingBox(e){if(this._type===uM){let t=this.attenuationEnd,i=this._outerConeAngle,s=this._node,r=Math.abs(Math.sin(i*eA.DEG_TO_RAD)*t);e.center.set(0,-(.5*t),0),e.halfExtents.set(r,.5*t,r),e.setFromTransformedAabb(e,s.getWorldTransform(),true);}else this._type===uD&&(e.center.copy(this._node.getPosition()),e.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd));}_updateShadowBias(){if(this._type!==uD||this.clusteredLighting){let e=-1e3*this.shadowBias;this.shadowDepthState.depthBias=e,this.shadowDepthState.depthBiasSlope=e;}else this.shadowDepthState.depthBias=0,this.shadowDepthState.depthBiasSlope=0;}_updateLinearColor(){let e=this._intensity;this._usePhysicalUnits&&(e=this._luminance/g2.getLightUnitConversion(this._type,this._outerConeAngle*eA.DEG_TO_RAD,this._innerConeAngle*eA.DEG_TO_RAD));let t=this._color,i=this._colorLinear;e>=1?gj.linear(t).mulScalar(e):gj.copy(t).mulScalar(e).linear(),i[0]=gj.r,i[1]=gj.g,i[2]=gj.b,this.updateClusterData(true);}setColor(){1==arguments.length?this._color.set(arguments[0].r,arguments[0].g,arguments[0].b):3==arguments.length&&this._color.set(arguments[0],arguments[1],arguments[2]),this._updateLinearColor();}layersDirty(){this.layers.forEach(e=>{e.hasLight(this)&&e.markLightsDirty();});}updateKey(){let e=this._type<<29|this._shadowType<<25|this._falloffMode<<23|(0!==this._normalOffsetBias)<<22|!!this._cookie<<21|!!this._cookieFalloff<<20|gK[this._cookieChannel.charAt(0)]<<18|!!this._cookieTransform<<12|this._shape<<10|(this.numCascades>0)<<9|(this._cascadeBlend>0)<<8|!!this.affectSpecularity<<7|this.mask<<6|!!this._castShadows<<3;3===this._cookieChannel.length&&(e|=gK[this._cookieChannel.charAt(1)]<<16,e|=gK[this._cookieChannel.charAt(2)]<<14),e!==this.key&&this.layersDirty(),this.key=e;}updateClusteredFlags(){let e=!!(this.mask&po),t=!!(this.mask&pl);this.clusteredFlags=(this.type===uM)<<30|(3&this._shape)<<28|(1&this._falloffMode)<<27|(gJ[this._cookieChannel]??0)<<23|!!e<<22|!!t<<21;}getClusteredFlags(e,t){return this.clusteredFlags|(e?Math.floor(255*this.shadowIntensity):0)&255|((t?Math.floor(255*this.cookieIntensity):0)&255)<<8}updateClusterData(e,t){let{clusteredData16:i}=this,s=eD.float2Half;e&&(i[0]=s(eA.clamp(this._colorLinear[0]/uF,0,65504)),i[1]=s(eA.clamp(this._colorLinear[1]/uF,0,65504)),i[2]=s(eA.clamp(this._colorLinear[2]/uF,0,65504))),t&&(i[4]=s(this._innerConeAngleCos),i[5]=s(this._outerConeAngleCos));}}class g3{constructor(e,t,i){this._areaLightsEnabled=false,this._cells=new eM(10,3,10),this._maxLightsPerCell=255,this._shadowsEnabled=true,this._shadowType=uX,this._shadowAtlasResolution=2048,this._cookiesEnabled=false,this._cookieAtlasResolution=2048,this.atlasSplit=null,this._supportsAreaLights=e,this._maxTextureSize=t,this._dirtyLightsFnc=i;}applySettings(e){this.shadowsEnabled=e.lightingShadowsEnabled??this.shadowsEnabled,this.cookiesEnabled=e.lightingCookiesEnabled??this.cookiesEnabled,this.areaLightsEnabled=e.lightingAreaLightsEnabled??this.areaLightsEnabled,this.shadowAtlasResolution=e.lightingShadowAtlasResolution??this.shadowAtlasResolution,this.cookieAtlasResolution=e.lightingCookieAtlasResolution??this.cookieAtlasResolution,this.maxLightsPerCell=e.lightingMaxLightsPerCell??this.maxLightsPerCell,this.shadowType=e.lightingShadowType??this.shadowType,e.lightingCells&&(this.cells=new eM(e.lightingCells));}set cells(e){this._cells.copy(e);}get cells(){return this._cells}set maxLightsPerCell(e){this._maxLightsPerCell=eA.clamp(e,1,255);}get maxLightsPerCell(){return this._maxLightsPerCell}set cookieAtlasResolution(e){this._cookieAtlasResolution=eA.clamp(e,32,this._maxTextureSize);}get cookieAtlasResolution(){return this._cookieAtlasResolution}set shadowAtlasResolution(e){this._shadowAtlasResolution=eA.clamp(e,32,this._maxTextureSize);}get shadowAtlasResolution(){return this._shadowAtlasResolution}set shadowType(e){this._shadowType!==e&&(this._shadowType=e,this._dirtyLightsFnc());}get shadowType(){return this._shadowType}set cookiesEnabled(e){this._cookiesEnabled!==e&&(this._cookiesEnabled=e,this._dirtyLightsFnc());}get cookiesEnabled(){return this._cookiesEnabled}set areaLightsEnabled(e){this._supportsAreaLights&&this._areaLightsEnabled!==e&&(this._areaLightsEnabled=e,this._dirtyLightsFnc());}get areaLightsEnabled(){return this._areaLightsEnabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this._dirtyLightsFnc());}get shadowsEnabled(){return this._shadowsEnabled}}class g4{constructor(e){this.morph=e,e.incRefCount(),this.device=e.device;let t=e._targets.length;this.shader=this._createShader(t),this._weights=[],this._weightMap=new Map;for(let t=0;t<e._targets.length;t++){let i=e._targets[t];i.name&&this._weightMap.set(i.name,t),this.setWeight(t,i.defaultWeight);}this._shaderMorphWeights=new Float32Array(t),this._shaderMorphIndex=new Uint32Array(t);let i=(t,i)=>(this[i]=e._createTexture(t,e._renderTextureFormat),new nM({colorBuffer:this[i],depth:false}));e.morphPositions&&(this.rtPositions=i("MorphRTPos","texturePositions")),e.morphNormals&&(this.rtNormals=i("MorphRTNrm","textureNormals")),this._textureParams=new Float32Array([e.morphTextureWidth,e.morphTextureHeight]);let s=e.aabb.halfExtents;this._aabbSize=new Float32Array([4*s.x,4*s.y,4*s.z]);let r=e.aabb.getMin();this._aabbMin=new Float32Array([2*r.x,2*r.y,2*r.z]),this._aabbNrmSize=new Float32Array([2,2,2]),this._aabbNrmMin=new Float32Array([-1,-1,-1]),this.aabbSizeId=this.device.scope.resolve("aabbSize"),this.aabbMinId=this.device.scope.resolve("aabbMin"),this.morphTextureId=this.device.scope.resolve("morphTexture"),this.morphFactor=this.device.scope.resolve("morphFactor[0]"),this.morphIndex=this.device.scope.resolve("morphIndex[0]"),this.countId=this.device.scope.resolve("count"),this.zeroTextures=false;}destroy(){this.shader=null;let e=this.morph;e&&(this.morph=null,e.decRefCount(),e.refCount<1&&e.destroy()),this.rtPositions?.destroy(),this.rtPositions=null,this.texturePositions?.destroy(),this.texturePositions=null,this.rtNormals?.destroy(),this.rtNormals=null,this.textureNormals?.destroy(),this.textureNormals=null;}clone(){return new g4(this.morph)}_getWeightIndex(e){return "string"==typeof e?this._weightMap.get(e):e}getWeight(e){let t=this._getWeightIndex(e);return this._weights[t]}setWeight(e,t){let i=this._getWeightIndex(e);this._weights[i]=t,this._dirty=true;}_createShader(e){let t=new Map;t.set("{MORPH_TEXTURE_MAX_COUNT}",e),this.morph.intRenderFormat&&t.set("MORPH_INT","");let i=this.morph.intRenderFormat?"uvec4":"vec4";return mo.createShader(this.device,{uniqueName:`TextureMorphShader_${e}-${this.morph.intRenderFormat?"int":"float"}`,attributes:{vertex_position:sT},vertexChunk:"morphVS",fragmentChunk:"morphPS",fragmentDefines:t,fragmentOutputTypes:[i]})}_updateTextureRenderTarget(e,t,i){let{morph:s,device:r}=this;this.setAabbUniforms(i),this.morphTextureId.setValue(i?s.targetsTexturePositions:s.targetsTextureNormals),r.setBlendState(nu.NOBLEND),this.countId.setValue(t),this.morphFactor.setValue(this._shaderMorphWeights),this.morphIndex.setValue(this._shaderMorphIndex),mg(r,e,this.shader);}_updateTextureMorph(e){this.device,(e>0||!this.zeroTextures)&&(this.rtPositions&&this._updateTextureRenderTarget(this.rtPositions,e,true),this.rtNormals&&this._updateTextureRenderTarget(this.rtNormals,e,false),this.zeroTextures=0===e);}setAabbUniforms(e=true){this.aabbSizeId.setValue(e?this._aabbSize:this._aabbNrmSize),this.aabbMinId.setValue(e?this._aabbMin:this._aabbNrmMin);}prepareRendering(e){this.setAabbUniforms();}update(){this._dirty=false;let e=this.morph._targets,t=this._shaderMorphWeights,i=this._shaderMorphIndex,s=0;for(let r=0;r<e.length;r++)Math.abs(this.getWeight(r))>1e-5&&(t[s]=this.getWeight(r),i[s]=r,s++);this._updateTextureMorph(s);}}class g5{constructor(){this.graph=null,this.meshInstances=[],this.skinInstances=[],this.morphInstances=[],this.cameras=[],this.lights=[],this._shadersVersion=0,this._immutable=false;}getGraph(){return this.graph}setGraph(e){this.graph=e;}getCameras(){return this.cameras}setCameras(e){this.cameras=e;}getLights(){return this.lights}setLights(e){this.lights=e;}getMaterials(){let e=[];for(let t=0;t<this.meshInstances.length;t++){let i=this.meshInstances[t];-1===e.indexOf(i.material)&&e.push(i.material);}return e}clone(){let e=[],t=[],i=function(s){let r=s.clone();e.push(s),t.push(r);for(let e=0;e<s._children.length;e++)r.addChild(i(s._children[e]));return r},s=i(this.graph),r=[],a=[],n=[];for(let e=0;e<this.skinInstances.length;e++){let t=this.skinInstances[e].skin,i=new mx(t),r=[];for(let e=0;e<t.boneNames.length;e++){let i=t.boneNames[e],a=s.findByName(i);r.push(a);}i.bones=r,a.push(i);}for(let e=0;e<this.morphInstances.length;e++){let t=new g4(this.morphInstances[e].morph);n.push(t);}for(let i=0;i<this.meshInstances.length;i++){let s=this.meshInstances[i],o=e.indexOf(s.node),l=new mV(s.mesh,s.material,t[o]);s.skinInstance&&(l.skinInstance=a[this.skinInstances.indexOf(s.skinInstance)]),s.morphInstance&&(l.morphInstance=n[this.morphInstances.indexOf(s.morphInstance)]),r.push(l);}let o=new g5;return o.graph=s,o.meshInstances=r,o.skinInstances=a,o.morphInstances=n,o.getGraph().syncHierarchy(),o}destroy(){let e=this.meshInstances;for(let t=0;t<e.length;t++)e[t].destroy();this.meshInstances.length=0;}generateWireframe(){mV._prepareRenderStyleForArray(this.meshInstances,fg);}}class g8 extends n4{constructor(e,t,{preferHighPrecision:i=false}={}){super(),this.device=t,this.preferHighPrecision=i,this._targets=e.slice();let s=t.textureHalfFloatRenderable?ig:void 0,r=t.textureFloatRenderable?iS:void 0;this._renderTextureFormat=this.preferHighPrecision?r??s:s??r,this._renderTextureFormat=this._renderTextureFormat??iQ,this.intRenderFormat=sc(this._renderTextureFormat),this._textureFormat=this.preferHighPrecision?iS:ig,this._init(),this._updateMorphFlags();}destroy(){this.vertexBufferIds?.destroy(),this.vertexBufferIds=null,this.targetsTexturePositions?.destroy(),this.targetsTexturePositions=null,this.targetsTextureNormals?.destroy(),this.targetsTextureNormals=null;}get aabb(){if(!this._aabb){let e=new eM,t=new eM;for(let i=0;i<this._targets.length;i++){let s=this._targets[i].aabb;e.min(s.getMin()),t.max(s.getMax());}this._aabb=new ej,this._aabb.setMinMax(e,t);}return this._aabb}get morphPositions(){return this._morphPositions}get morphNormals(){return this._morphNormals}_init(){this._initTextureBased();for(let e=0;e<this._targets.length;e++)this._targets[e]._postInit();}_findSparseSet(e,t,i){let s=1,r=e[0].length;for(let a=0;a<r;a+=3){let r=false;for(let t=0;t<e.length;t++){let i=e[t];if(0!==i[a]||0!==i[a+1]||0!==i[a+2]){r=true;break}}r?(t.push(s),i.push(a/3),s++):t.push(0);}return s}_initTextureBased(){let e=[],t=[],i=this._targets;for(let s=0;s<i.length;s++){let r=i[s];r.options.deltaPositions&&(e.push(r.options.deltaPositions),t.push(true)),r.options.deltaNormals&&(e.push(r.options.deltaNormals),t.push(false));}let s=[],r=[],a=this._findSparseSet(e,s,r),n=this.device.maxTextureSize,o=Math.ceil(Math.sqrt(a)),l=Math.ceil(a/(o=Math.min(o,n)));if(l>n)return;this.morphTextureWidth=o,this.morphTextureHeight=l;let h=false,c=eD.float2Half;this._textureFormat===ig&&(h=true);let d=[],u=[],f=o*l*4;for(let i=0;i<e.length;i++){let s=e[i],a=this._textureFormat===ig?new Uint16Array(f):new Float32Array(f);if((t[i]?d:u).push(a),h)for(let e=0;e<r.length;e++){let t=3*r[e],i=4*e+4;a[i]=c(s[t]),a[i+1]=c(s[t+1]),a[i+2]=c(s[t+2]);}else for(let e=0;e<r.length;e++){let t=3*r[e],i=4*e+4;a[i]=s[t],a[i+1]=s[t+1],a[i+2]=s[t+2];}}d.length>0&&(this.targetsTexturePositions=this._createTexture("MorphPositionsTexture",this._textureFormat,i.length,[d]),this.targetsTexturePositions.upload()),u.length>0&&(this.targetsTextureNormals=this._createTexture("MorphNormalsTexture",this._textureFormat,i.length,[u]),this.targetsTextureNormals.upload());let p=[{semantic:sQ,components:1,type:rR,asInt:true}];return this.vertexBufferIds=new nT(this.device,new nP(this.device,p,s.length),s.length,{data:new Uint32Array(s)}),true}get targets(){return this._targets}_updateMorphFlags(){this._morphPositions=false,this._morphNormals=false;for(let e=0;e<this._targets.length;e++){let t=this._targets[e];t.morphPositions&&(this._morphPositions=true),t.morphNormals&&(this._morphNormals=true);}}_createTexture(e,t,i,s){return new ns(this.device,{levels:s,arrayLength:i,width:this.morphTextureWidth,height:this.morphTextureHeight,format:t,cubemap:false,mipmaps:false,minFilter:tK,magFilter:tK,addressU:tr,addressV:tr,name:e})}}class g6{constructor(e){this.used=false,this.options=e,this._name=e.name,this._defaultWeight=e.defaultWeight||0,this._aabb=e.aabb,this.deltaPositions=e.deltaPositions,this.morphPositions=!!e.deltaPositions,this.morphNormals=!!e.deltaNormals;}get name(){return this._name}get defaultWeight(){return this._defaultWeight}get aabb(){return !this._aabb&&(this._aabb=new ej,this.deltaPositions&&this._aabb.compute(this.deltaPositions)),this._aabb}clone(){return new g6(this.options)}_postInit(){this.options.preserveData||(this.options=null),this.used=true;}}let g9=1,g7=new eG,ve=new eG,vt=new eM,vi=new eM,vs=new eM,vr=new eM,va=new eM,vn=new eM,vo=new eM,vl=new eM,vh=new eM,vc=new eM,vd=new eM,vu=new eM,vf=new eM;function vp(e){return e-Math.floor(e)}function vm(e,t){return e-t*Math.floor(e/t)}function v_(e){let t=vp(e),i=vp(255*e);return [t-=i/255,i-=i/255]}class vg{constructor(e){this._emitter=e;}calcSpawnPosition(e,t,i,s,r){let a=this._emitter,n=Math.random(),o=Math.random(),l=Math.random(),h=Math.random();if(a.useCpu&&(e[4*r+0+2*a.numParticlesPot*4]=n,e[4*r+1+2*a.numParticlesPot*4]=o,e[4*r+2+2*a.numParticlesPot*4]=l),vi.x=n-.5,vi.y=o-.5,vi.z=l-.5,a.emitterShape===fh){let e=Math.max(Math.abs(vi.x),Math.max(Math.abs(vi.y),Math.abs(vi.z))),r=e+(.5-e)*i[0],n=e+(.5-e)*i[1],o=e+(.5-e)*i[2];vi.x=r*(e===Math.abs(vi.x)?Math.sign(vi.x):2*vi.x),vi.y=n*(e===Math.abs(vi.y)?Math.sign(vi.y):2*vi.y),vi.z=o*(e===Math.abs(vi.z)?Math.sign(vi.z):2*vi.z),a.localSpace?vt.copy(t.transformPoint(vi)):vt.copy(s).add(t.transformPoint(vi));}else {vi.normalize();let e=0===a.emitterRadius?0:a.emitterRadiusInner/a.emitterRadius,t=h*(1-e)+e;a.localSpace?vt.copy(vi.mulScalar(t*a.emitterRadius)):vt.copy(s).add(vi.mulScalar(t*a.emitterRadius));}let c=-eA.lerp(a.rate,a.rate2,n)*r;if(a.pack8){var d;let t,i,s,o,l=(vt.x-a.worldBounds.center.x)/a.worldBoundsSize.x+.5,h=(vt.y-a.worldBounds.center.y)/a.worldBoundsSize.y+.5,u=(vt.z-a.worldBounds.center.z)/a.worldBoundsSize.z+.5,f=eA.lerp(a.startAngle*eA.DEG_TO_RAD,a.startAngle2*eA.DEG_TO_RAD,n);f=f%(2*Math.PI)/(2*Math.PI);let p=v_(l);e[4*r]=p[0],e[4*r+1]=p[1];let m=v_(h);e[4*r+2]=m[0],e[4*r+3]=m[1];let _=v_(u);e[4*r+0+4*a.numParticlesPot]=_[0],e[4*r+1+4*a.numParticlesPot]=_[1];let g=v_(f);e[4*r+2+4*a.numParticlesPot]=g[0],e[4*r+3+4*a.numParticlesPot]=g[1],e[4*r+3+4*a.numParticlesPot*2]=1;let v=Math.max(a.lifetime,(a.numParticles-1)*Math.max(a.rate,a.rate2)),S=(t=vp(d=c=(c+v)/(v+(a.lifetime+1))),i=vp(255*d),s=vp(65025*d),o=vp(0x99246ff*d),[t-=i/255,i-=s/255,s-=o/255,o-=o/255]);e[4*r+0+4*a.numParticlesPot*3]=S[0],e[4*r+1+4*a.numParticlesPot*3]=S[1],e[4*r+2+4*a.numParticlesPot*3]=S[2],e[4*r+3+4*a.numParticlesPot*3]=S[3];}else e[4*r]=vt.x,e[4*r+1]=vt.y,e[4*r+2]=vt.z,e[4*r+3]=eA.lerp(a.startAngle*eA.DEG_TO_RAD,a.startAngle2*eA.DEG_TO_RAD,n),e[4*r+3+4*a.numParticlesPot]=c;}update(t,i,s,r,a,n,o,l){let h,c,d,u,f,p,m,_,g,v,S,y,x=this._emitter;if(x.meshInstance.node){let t=x.meshInstance.node.worldTransform;for(let e=0;e<12;e++)g7.data[e]=t.data[e];ve.copy(g7),ve.invert(),g9=Math.max(Math.max((e=x.meshInstance.node.localScale).x,e.y),e.z);}n=null===x.meshInstance.node||x.localSpace?eM.ZERO:x.meshInstance.node.getPosition();let T=x.camera?x.camera._node.getPosition():eM.ZERO,E=x.useMesh?17:15,A=x.precision-1;for(let i=0;i<x.numParticles;i++){let b=Math.floor(x.vbCPU[i*x.numParticleVerts*(x.useMesh?6:4)+3]),w=s[4*b+0+2*x.numParticlesPot*4];vs.x=w,vs.y=s[4*b+1+2*x.numParticlesPot*4],vs.z=s[4*b+2+2*x.numParticlesPot*4];let C=x.rate+(x.rate2-x.rate)*w,P=x.lifetime,L=s[4*b+3+4*x.numParticlesPot]+o,I=Math.max(Math.min(L/P,1),0),D=0,R=0;(L-o<=0||L>=P)&&this.calcSpawnPosition(s,r,a,n,b);let M=L>0&&L<P;M&&(u=Math.floor(d=I*A),f=Math.ceil(d),d%=1,p=(h=x.qRotSpeed[u])+((c=x.qRotSpeed[f])-h)*d,m=(h=x.qRotSpeed2[u])+((c=x.qRotSpeed2[f])-h)*d,D=(h=x.qScale[u])+((c=x.qScale[f])-h)*d,_=(h=x.qScale2[u])+((c=x.qScale2[f])-h)*d,g=(h=x.qAlpha[u])+((c=x.qAlpha[f])-h)*d,v=(h=x.qAlpha2[u])+((c=x.qAlpha2[f])-h)*d,S=(h=x.qRadialSpeed[u])+((c=x.qRadialSpeed[f])-h)*d,y=(h=x.qRadialSpeed2[u])+((c=x.qRadialSpeed2[f])-h)*d,S+=100*w%1*(y-S),vr.x=s[4*b],vr.y=s[4*b+1],vr.z=s[4*b+2],x.localSpace?vh.copy(vr):vh.copy(vr).sub(n),vh.normalize().mulScalar(S),u*=3,f*=3,h=x.qLocalVelocity[u],c=x.qLocalVelocity[f],vn.x=h+(c-h)*d,h=x.qLocalVelocity[u+1],c=x.qLocalVelocity[f+1],vn.y=h+(c-h)*d,h=x.qLocalVelocity[u+2],c=x.qLocalVelocity[f+2],vn.z=h+(c-h)*d,h=x.qLocalVelocity2[u],c=x.qLocalVelocity2[f],vl.x=h+(c-h)*d,h=x.qLocalVelocity2[u+1],c=x.qLocalVelocity2[f+1],vl.y=h+(c-h)*d,h=x.qLocalVelocity2[u+2],c=x.qLocalVelocity2[f+2],vl.z=h+(c-h)*d,h=x.qVelocity[u],c=x.qVelocity[f],va.x=h+(c-h)*d,h=x.qVelocity[u+1],c=x.qVelocity[f+1],va.y=h+(c-h)*d,h=x.qVelocity[u+2],c=x.qVelocity[f+2],va.z=h+(c-h)*d,h=x.qVelocity2[u],c=x.qVelocity2[f],vo.x=h+(c-h)*d,h=x.qVelocity2[u+1],c=x.qVelocity2[f+1],vo.y=h+(c-h)*d,h=x.qVelocity2[u+2],c=x.qVelocity2[f+2],vo.z=h+(c-h)*d,vn.x+=(vl.x-vn.x)*vs.x,vn.y+=(vl.y-vn.y)*vs.y,vn.z+=(vl.z-vn.z)*vs.z,x.initialVelocity>0&&(x.emitterShape===fc?(vi.copy(vs).mulScalar(2).sub(eM.ONE).normalize(),vn.add(vi.mulScalar(x.initialVelocity))):vn.add(eM.FORWARD.mulScalar(x.initialVelocity))),va.x+=(vo.x-va.x)*vs.x,va.y+=(vo.y-va.y)*vs.y,va.z+=(vo.z-va.z)*vs.z,p+=(m-p)*vs.y,D=(D+1e4*w%1*(_-D))*g9,R=1e3*w%1*(v-g),x.meshInstance.node&&(x.localSpace?(vn.x/=e.x,vn.y/=e.y,vn.z/=e.z):g7.transformPoint(vn,vn)),x.localSpace?(ve.transformPoint(va,va),vn.add(va).add(vh)):(vn.add(va.mul(e)),vn.add(vh.mul(e))),vu.copy(vn),vc.copy(vr).add(vn.mulScalar(o)),vd.copy(vc),s[4*b]=vd.x,s[4*b+1]=vd.y,s[4*b+2]=vd.z,s[4*b+3]+=p*o,x.wrap&&x.wrapBounds&&(x.localSpace||vd.sub(n),vd.x=vm(vd.x,x.wrapBounds.x)-.5*x.wrapBounds.x,vd.y=vm(vd.y,x.wrapBounds.y)-.5*x.wrapBounds.y,vd.z=vm(vd.z,x.wrapBounds.z)-.5*x.wrapBounds.z,x.localSpace||vd.add(n)),x.sort>0&&(1===x.sort?(vf.copy(vd).sub(T),x.particleDistance[b]=-(vf.x*vf.x+vf.y*vf.y+vf.z*vf.z)):2===x.sort?x.particleDistance[b]=L:3===x.sort&&(x.particleDistance[b]=-L))),l?L<0&&(s[4*b+3+2*x.numParticlesPot*4]=-1):(L>=P&&(L-=Math.max(P,(x.numParticles-1)*C),s[4*b+3+2*x.numParticlesPot*4]=x.loop?1:-1),L<0&&x.loop&&(s[4*b+3+2*x.numParticlesPot*4]=1)),s[4*b+3+2*x.numParticlesPot*4]<0&&(M=false),s[4*b+3+4*x.numParticlesPot]=L;for(let e=0;e<x.numParticleVerts;e++){let r=(i*x.numParticleVerts+e)*(x.useMesh?6:4),a=x.vbCPU[r],n=x.vbCPU[r+1],o=x.vbCPU[r+2];M||(a=n=o=0);let l=i*x.numParticleVerts*E+e*E;t[l]=vd.x,t[l+1]=vd.y,t[l+2]=vd.z,t[l+3]=I,t[l+4]=x.alignToMotion?0:s[4*b+3],t[l+5]=D,t[l+6]=R,t[l+7]=vu.x,t[l+8]=a,t[l+9]=n,t[l+10]=o,t[l+11]=vu.y,t[l+12]=b,t[l+13]=vu.z,t[l+14]=x.vbCPU[r+3],x.useMesh&&(t[l+15]=x.vbCPU[r+4],t[l+16]=x.vbCPU[r+5]);}}if(x.sort>fs&&x.camera){let e=x.useMesh?6:4,t=x.particleDistance;for(let s=0;s<x.numParticles;s++)i[s][0]=s,i[s][1]=t[Math.floor(x.vbCPU[s*x.numParticleVerts*e+3])];x.vbOld.set(x.vbCPU),i.sort((e,t)=>e[1]-t[1]);for(let t=0;t<x.numParticles;t++){let s=i[t][0]*x.numParticleVerts*e,r=t*x.numParticleVerts*e;for(let t=0;t<x.numParticleVerts*e;t++)x.vbCPU[r+t]=x.vbOld[s+t];}}}}let vv=new eO,vS=new eO,vy=new eO;class vx{constructor(e,t){this._emitter=e,this.frameRandomUniform=new Float32Array(3),this.emitterPosUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),this.worldBoundsMulUniform=new Float32Array(3),this.worldBoundsAddUniform=new Float32Array(3),this.inBoundsSizeUniform=new Float32Array(3),this.inBoundsCenterUniform=new Float32Array(3),this.constantParticleTexIN=t.scope.resolve("particleTexIN"),this.constantParticleTexOUT=t.scope.resolve("particleTexOUT"),this.constantEmitterPos=t.scope.resolve("emitterPos"),this.constantEmitterScale=t.scope.resolve("emitterScale"),this.constantSpawnBounds=t.scope.resolve("spawnBounds"),this.constantSpawnPosInnerRatio=t.scope.resolve("spawnPosInnerRatio"),this.constantSpawnBoundsSphere=t.scope.resolve("spawnBoundsSphere"),this.constantSpawnBoundsSphereInnerRatio=t.scope.resolve("spawnBoundsSphereInnerRatio"),this.constantInitialVelocity=t.scope.resolve("initialVelocity"),this.constantFrameRandom=t.scope.resolve("frameRandom"),this.constantDelta=t.scope.resolve("delta"),this.constantRate=t.scope.resolve("rate"),this.constantRateDiv=t.scope.resolve("rateDiv"),this.constantLifetime=t.scope.resolve("lifetime"),this.constantGraphSampleSize=t.scope.resolve("graphSampleSize"),this.constantGraphNumSamples=t.scope.resolve("graphNumSamples"),this.constantInternalTex0=t.scope.resolve("internalTex0"),this.constantInternalTex1=t.scope.resolve("internalTex1"),this.constantInternalTex2=t.scope.resolve("internalTex2"),this.constantInternalTex3=t.scope.resolve("internalTex3"),this.constantEmitterMatrix=t.scope.resolve("emitterMatrix"),this.constantEmitterMatrixInv=t.scope.resolve("emitterMatrixInv"),this.constantNumParticles=t.scope.resolve("numParticles"),this.constantNumParticlesPot=t.scope.resolve("numParticlesPot"),this.constantLocalVelocityDivMult=t.scope.resolve("localVelocityDivMult"),this.constantVelocityDivMult=t.scope.resolve("velocityDivMult"),this.constantRotSpeedDivMult=t.scope.resolve("rotSpeedDivMult"),this.constantSeed=t.scope.resolve("seed"),this.constantStartAngle=t.scope.resolve("startAngle"),this.constantStartAngle2=t.scope.resolve("startAngle2"),this.constantOutBoundsMul=t.scope.resolve("outBoundsMul"),this.constantOutBoundsAdd=t.scope.resolve("outBoundsAdd"),this.constantInBoundsSize=t.scope.resolve("inBoundsSize"),this.constantInBoundsCenter=t.scope.resolve("inBoundsCenter"),this.constantMaxVel=t.scope.resolve("maxVel"),this.constantFaceTangent=t.scope.resolve("faceTangent"),this.constantFaceBinorm=t.scope.resolve("faceBinorm");}_setInputBounds(){this.inBoundsSizeUniform[0]=this._emitter.prevWorldBoundsSize.x,this.inBoundsSizeUniform[1]=this._emitter.prevWorldBoundsSize.y,this.inBoundsSizeUniform[2]=this._emitter.prevWorldBoundsSize.z,this.constantInBoundsSize.setValue(this.inBoundsSizeUniform),this.inBoundsCenterUniform[0]=this._emitter.prevWorldBoundsCenter.x,this.inBoundsCenterUniform[1]=this._emitter.prevWorldBoundsCenter.y,this.inBoundsCenterUniform[2]=this._emitter.prevWorldBoundsCenter.z,this.constantInBoundsCenter.setValue(this.inBoundsCenterUniform);}randomize(){this.frameRandomUniform[0]=Math.random(),this.frameRandomUniform[1]=Math.random(),this.frameRandomUniform[2]=Math.random();}update(e,t,i,s,r){let a=this._emitter;e.setBlendState(nu.NOBLEND),e.setDepthState(nm.NODEPTH),e.setCullMode(tY),this.randomize(),this.constantGraphSampleSize.setValue(1/a.precision),this.constantGraphNumSamples.setValue(a.precision),this.constantNumParticles.setValue(a.numParticles),this.constantNumParticlesPot.setValue(a.numParticlesPot),this.constantInternalTex0.setValue(a.internalTex0),this.constantInternalTex1.setValue(a.internalTex1),this.constantInternalTex2.setValue(a.internalTex2),this.constantInternalTex3.setValue(a.internalTex3);let n=a.meshInstance.node,o=null===n?eM.ONE:n.localScale;if(a.pack8){this.worldBoundsMulUniform[0]=a.worldBoundsMul.x,this.worldBoundsMulUniform[1]=a.worldBoundsMul.y,this.worldBoundsMulUniform[2]=a.worldBoundsMul.z,this.constantOutBoundsMul.setValue(this.worldBoundsMulUniform),this.worldBoundsAddUniform[0]=a.worldBoundsAdd.x,this.worldBoundsAddUniform[1]=a.worldBoundsAdd.y,this.worldBoundsAddUniform[2]=a.worldBoundsAdd.z,this.constantOutBoundsAdd.setValue(this.worldBoundsAddUniform),this._setInputBounds();let e=a.maxVel*Math.max(Math.max(o.x,o.y),o.z);e=Math.max(e,1),this.constantMaxVel.setValue(e);}let l=null===n||a.localSpace?eM.ZERO:n.getPosition(),h=null===n?eG.IDENTITY:n.getWorldTransform();a.emitterShape===fh?(vv.setFromMat4(t),this.constantSpawnBounds.setValue(vv.data),this.constantSpawnPosInnerRatio.setValue(i)):(this.constantSpawnBoundsSphere.setValue(a.emitterRadius),this.constantSpawnBoundsSphereInnerRatio.setValue(0===a.emitterRadius?0:a.emitterRadiusInner/a.emitterRadius)),this.constantInitialVelocity.setValue(a.initialVelocity),vS.setFromMat4(h),vy.invertMat4(h),this.emitterPosUniform[0]=l.x,this.emitterPosUniform[1]=l.y,this.emitterPosUniform[2]=l.z,this.constantEmitterPos.setValue(this.emitterPosUniform),this.constantFrameRandom.setValue(this.frameRandomUniform),this.constantDelta.setValue(s),this.constantRate.setValue(a.rate),this.constantRateDiv.setValue(a.rate2-a.rate),this.constantStartAngle.setValue(a.startAngle*eA.DEG_TO_RAD),this.constantStartAngle2.setValue(a.startAngle2*eA.DEG_TO_RAD),this.constantSeed.setValue(a.seed),this.constantLifetime.setValue(a.lifetime),this.emitterScaleUniform[0]=o.x,this.emitterScaleUniform[1]=o.y,this.emitterScaleUniform[2]=o.z,this.constantEmitterScale.setValue(this.emitterScaleUniform),this.constantEmitterMatrix.setValue(vS.data),this.constantEmitterMatrixInv.setValue(vy.data),this.constantLocalVelocityDivMult.setValue(a.localVelocityUMax),this.constantVelocityDivMult.setValue(a.velocityUMax),this.constantRotSpeedDivMult.setValue(a.rotSpeedUMax[0]);let c=a.swapTex?a.particleTexOUT:a.particleTexIN;c=a.beenReset?a.particleTexStart:c;let d=a.swapTex?a.particleTexIN:a.particleTexOUT;this.constantParticleTexIN.setValue(c),mg(e,a.swapTex?a.rtParticleTexIN:a.rtParticleTexOUT,r?a.shaderParticleUpdateOnStop:a.loop?a.shaderParticleUpdateRespawn:a.shaderParticleUpdateNoRespawn),a.material.setParameter("particleTexOUT",c),a.material.setParameter("particleTexIN",d),a.beenReset=false,a.swapTex=!a.swapTex,a.prevWorldBoundsSize.copy(a.worldBoundsSize),a.prevWorldBoundsCenter.copy(a.worldBounds.center),a.pack8&&this._setInputBounds();}}let vT=["NONE","VERTEX","MAP"],vE=new class extends p9{generateKey(e){let t=p9.definesHash(e.defines),i=`particle_${t}_`;for(let t in e)e.hasOwnProperty(t)&&(i+=e[t]);return i}createVertexDefines(e,t){let i=new Map(e.defines);return e.mesh&&i.set("USE_MESH",""),e.meshUv&&i.set("USE_MESH_UV",""),e.localSpace&&i.set("LOCAL_SPACE",""),e.screenSpace&&i.set("SCREEN_SPACE",""),e.animTex&&i.set("ANIMTEX",""),e.soft>0&&i.set("SOFT",""),e.stretch>0&&i.set("STRETCH",""),e.customFace&&i.set("CUSTOM_FACE",""),e.pack8&&i.set("PACK8",""),e.localSpace&&i.set("LOCAL_SPACE",""),e.animTexLoop&&i.set("ANIMTEX_LOOP",""),e.wrap&&i.set("WRAP",""),e.alignToMotion&&i.set("ALIGN_TO_MOTION",""),i.set("NORMAL",vT[e.normal]),t.particle_vertexData=sT,e.mesh&&e.meshUv&&(t.particle_uv=sL),e.useCpu&&(t.particle_vertexData2=sU,t.particle_vertexData3=sk,t.particle_vertexData4=sV,t.particle_vertexData5=sz),i}createFragmentDefines(e){let t=new Map(e.defines);return e.soft>0&&t.set("SOFT",""),e.halflambert&&t.set("HALF_LAMBERT",""),t.set("NORMAL",vT[e.normal]),t.set("BLEND",up[e.blend]),t}createShaderDefinition(e,t){let i=e.isWebGPU?rw:rb,s=mr.get(e,i),r={},a=this.createVertexDefines(t,r),n=this.createFragmentDefines(t),o=`PARTICLE_${t.useCpu?"CPU":"GPU"}
`;a.set(o,""),n.set(o,"");let l=new Map(s);return ls.createDefinition(e,{name:"ParticleShader",shaderLanguage:i,attributes:r,vertexCode:s.get("particle_shaderVS"),fragmentCode:s.get("particle_shaderPS"),fragmentDefines:n,fragmentIncludes:l,vertexIncludes:l,vertexDefines:a})}};class vA extends _${constructor(e){super(),this.emitter=null,this.emitter=e;}getShaderVariant(e){let{device:t,scene:i,cameraShaderParams:s,objDefs:r}=e,{emitter:a}=this,n={defines:mo.getCoreDefines(this,e),pass:pc,useCpu:this.emitter.useCpu,normal:a.lighting?null!==a.normalMap?2:1:0,halflambert:this.emitter.halfLambert,stretch:this.emitter.stretch,alignToMotion:this.emitter.alignToMotion,soft:this.emitter.depthSoftening,mesh:this.emitter.useMesh,meshUv:r&f1,gamma:s?.shaderOutputGamma??fP,toneMap:s?.toneMapping??fD,fog:i&&!this.emitter.noFog?i.fog.type:"none",wrap:this.emitter.wrap&&this.emitter.wrapBounds,localSpace:this.emitter.localSpace,screenSpace:!a.inTools&&this.emitter.screenSpace,blend:this.emitter.blendType,animTex:this.emitter._isAnimated(),animTexLoop:this.emitter.animLoop,pack8:this.emitter.pack8,customFace:this.emitter.orientation!==fd},o=new p5(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),l=p6(t);return l.register("particle",vE),l.getProgram("particle",n,o,this.userId)}}let vb=[[-1,-1],[1,-1],[1,1],[-1,1]];function vw(e,t,i,s,r=iS,a,n){let o=tK;n&&(r===id||r===ib)&&(o=tZ);let l=new ns(e,{width:t,height:i,format:r,cubemap:false,mipmaps:false,minFilter:o,magFilter:o,addressU:tr,addressV:tr,name:"ParticleSystemTexture"}),h=l.lock();if(r===id||r===ib){let e=new Uint8Array(s.length);for(let t=0;t<s.length;t++)e[t]=s[t]*a*255;s=e;}return h.set(s),l.unlock(),l}function vC(e){return Math.max(Math.min(e,1),0)}let vP=new eC([0,0,1,0]),vL=new eC([0,1,1,1]),vI=new eP([0,0,1,0],[0,0,1,0],[0,0,1,0]),vD=new eP([0,1,1,1],[0,1,1,1],[0,1,1,1]),vR=2,vM=new Float32Array(3),vO=new eG,vN=new eM,vF=new eM,vB=new eM;function vU(e,s){ void 0!==i[e]&&null!==i[e]?t[e]=i[e]:t[e]=s;}function vk(e,t,i){return (255*e<<16|255*t<<8|255*i)/0x1000000}function vV(e,t){let i=e.length/3,s=Array(4*i);for(let r=0;r<i;r++)s[4*r]=e[3*r],s[4*r+1]=e[3*r+1],s[4*r+2]=e[3*r+2],s[4*r+3]=vk(t[3*r],t[3*r+1],t[3*r+2]);return s}function vz(e,t){let i=t.length,s=e.length/i;for(let r=0;r<s;r++)for(let s=0;s<i;s++){let a=Math.abs(e[r*i+s]);t[s]=Math.max(t[s],a);}}function vG(e,t,i){let s=function(e,t){let i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]-t[s];return i}(t,e);vz(s,i);let r=i.length,a=s.length/r;for(let e=0;e<a;e++)for(let t=0;t<r;t++)s[e*r+t]/=0===i[t]?1:i[t],s[e*r+t]*=.5,s[e*r+t]+=.5;return s}let vH=new ne;class vW{constructor(e,s){this.material=null,this.internalTex0=null,this.internalTex1=null,this.internalTex2=null,this.colorParam=null,this.graphicsDevice=e,this.precision=32,this._addTimeTime=0,t=this,i=s,vU("numParticles",1),this.numParticles>e.maxTextureSize&&(this.numParticles=e.maxTextureSize),vU("rate",1),vU("rate2",this.rate),vU("lifetime",50),vU("emitterExtents",new eM(0,0,0)),vU("emitterExtentsInner",new eM(0,0,0)),vU("emitterRadius",0),vU("emitterRadiusInner",0),vU("emitterShape",fh),vU("initialVelocity",1),vU("wrap",false),vU("localSpace",false),vU("screenSpace",false),vU("wrapBounds",null),vU("colorMap",this.defaultParamTexture),vU("normalMap",null),vU("loop",true),vU("preWarm",false),vU("sort",fs),vU("mode",fo),vU("scene",null),vU("lighting",false),vU("halfLambert",false),vU("intensity",1),vU("stretch",0),vU("alignToMotion",false),vU("depthSoftening",0),vU("mesh",null),vU("particleNormal",new eM(0,1,0)),vU("orientation",fd),vU("depthWrite",false),vU("noFog",false),vU("blendType",ua),vU("node",null),vU("startAngle",0),vU("startAngle2",this.startAngle),vU("animTilesX",1),vU("animTilesY",1),vU("animStartFrame",0),vU("animNumFrames",1),vU("animNumAnimations",1),vU("animIndex",0),vU("randomizeAnimIndex",false),vU("animSpeed",1),vU("animLoop",true),this._gpuUpdater=new vx(this,e),this._cpuUpdater=new vg(this),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),vU("colorGraph",vD),vU("colorGraph2",this.colorGraph),vU("scaleGraph",vL),vU("scaleGraph2",this.scaleGraph),vU("alphaGraph",vL),vU("alphaGraph2",this.alphaGraph),vU("localVelocityGraph",vI),vU("localVelocityGraph2",this.localVelocityGraph),vU("velocityGraph",vI),vU("velocityGraph2",this.velocityGraph),vU("rotationSpeedGraph",vP),vU("rotationSpeedGraph2",this.rotationSpeedGraph),vU("radialSpeedGraph",vP),vU("radialSpeedGraph2",this.radialSpeedGraph),this.animTilesParams=new Float32Array(2),this.animParams=new Float32Array(4),this.animIndexParams=new Float32Array(2),this.vbToSort=null,this.vbOld=null,this.particleDistance=null,this.camera=null,this.swapTex=false,this.useMesh=true,this.useCpu=!e.supportsGpuParticles,this.pack8=true,this.localBounds=new ej,this.worldBoundsNoTrail=new ej,this.worldBoundsTrail=[new ej,new ej],this.worldBounds=new ej,this.worldBoundsSize=new eM,this.prevWorldBoundsSize=new eM,this.prevWorldBoundsCenter=new eM,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new eM,this.worldBoundsAdd=new eM,this.timeToSwitchBounds=0,this.shaderParticleUpdateRespawn=null,this.shaderParticleUpdateNoRespawn=null,this.shaderParticleUpdateOnStop=null,this.numParticleVerts=0,this.numParticleIndices=0,this.material=null,this.meshInstance=null,this.drawOrder=0,this.seed=Math.random(),this.fixedTimeStep=1/60,this.maxSubSteps=10,this.simTime=0,this.simTimeTotal=0,this.beenReset=false,this._layer=null,this.rebuild();}get defaultParamTexture(){return vH.get(this.graphicsDevice,()=>{let e=new Float32Array(1024);for(let t=0;t<16;t++)for(let i=0;i<16;i++){let s=i+1-8.5,r=t+1-8.5,a=vC(1-vC(Math.sqrt(s*s+r*r)/16)-.5),n=16*t+i;e[4*n]=1,e[4*n+1]=1,e[4*n+2]=1,e[4*n+3]=a;}let t=vw(this.graphicsDevice,16,16,e,ib,1,true);return t.minFilter=tZ,t.magFilter=tZ,t})}onChangeCamera(){this.resetMaterial();}calculateBoundsMad(){this.worldBoundsMul.x=1/this.worldBoundsSize.x,this.worldBoundsMul.y=1/this.worldBoundsSize.y,this.worldBoundsMul.z=1/this.worldBoundsSize.z,this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).mulScalar(-1),this.worldBoundsAdd.x+=.5,this.worldBoundsAdd.y+=.5,this.worldBoundsAdd.z+=.5;}calculateWorldBounds(){if(!this.node)return;if(this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),!this.useCpu){(this.emitterShape===fh?this.emitterExtents.equals(this.prevEmitterExtents):this.emitterRadius===this.prevEmitterRadius)||this.calculateLocalBounds();}let e=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,e),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);let t=this.simTimeTotal;t>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=t+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,e),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,e)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad();}resetWorldBounds(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?eG.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBoundsNoTrail),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.simTimeTotal=0,this.timeToSwitchBounds=0);}calculateLocalBounds(){let e,t,i,s=Number.MAX_VALUE,r=Number.MAX_VALUE,a=Number.MAX_VALUE,n=-Number.MAX_VALUE,o=-Number.MAX_VALUE,l=-Number.MAX_VALUE,h=0,c=0,d=this.lifetime/this.precision,u=[this.qVelocity,this.qVelocity2],f=[this.qLocalVelocity,this.qLocalVelocity2],p=[0,0],m=[0,0],_=[0,0],g=[0,0],v=[0,0];for(let S=0;S<this.precision+1;S++){let y=Math.min(S,this.precision-1);for(let h=0;h<2;h++)e=f[h][3*y+0]*d+p[h],t=f[h][3*y+1]*d+m[h],i=f[h][3*y+2]*d+_[h],s=Math.min(e,s),r=Math.min(t,r),a=Math.min(i,a),n=Math.max(e,n),o=Math.max(t,o),l=Math.max(i,l),p[h]=e,m[h]=t,_[h]=i;for(let e=0;e<2;e++)v[e]+=d*Math.sqrt(u[e][3*y+0]*u[e][3*y+0]+u[e][3*y+1]*u[e][3*y+1]+u[e][3*y+2]*u[e][3*y+2]);g[0]+=this.qRadialSpeed[y]*d,g[1]+=this.qRadialSpeed2[y]*d,h=Math.max(h,Math.max(Math.abs(g[0]),Math.abs(g[1]))),c=Math.max(c,this.qScale[y]);}this.emitterShape===fh?(e=.5*this.emitterExtents.x,t=.5*this.emitterExtents.y,i=.5*this.emitterExtents.z):(e=this.emitterRadius,t=this.emitterRadius,i=this.emitterRadius);let S=Math.max(v[0],v[1]);vF.x=s-c-e-h-S,vF.y=r-c-t-h-S,vF.z=a-c-i-h-S,vB.x=n+c+e+h+S,vB.y=o+c+t+h+S,vB.z=l+c+i+h+S,this.localBounds.setMinMax(vF,vB);}rebuild(){let e=this.graphicsDevice;null===this.colorMap&&(this.colorMap=this.defaultParamTexture),this.spawnBounds=this.emitterShape===fh?this.emitterExtents:this.emitterRadius,this.useCpu=this.useCpu||this.sort>fs||e.maxVertexTextures<=1||e.fragmentUniformsCount<64||e.forceCpuParticles,this._destroyResources(),this.pack8=(this.pack8||!e.textureFloatRenderable)&&!this.useCpu,vR=this.useCpu||this.pack8?4:2,this.useMesh=!!this.mesh,this.numParticlesPot=eA.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?eG.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBounds),this.worldBoundsTrail[1].copy(this.worldBounds),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&this.calculateBoundsMad()),this.vbToSort=Array(this.numParticles);for(let e=0;e<this.numParticles;e++)this.vbToSort[e]=[0,0];this.particleDistance=new Float32Array(this.numParticles),this._gpuUpdater.randomize(),this.particleTex=new Float32Array(this.numParticlesPot*vR*4);let t=null===this.node||this.localSpace?eM.ZERO:this.node.getPosition();this.emitterShape===fh&&(null===this.node||this.localSpace?vO.setTRS(eM.ZERO,eH.IDENTITY,this.spawnBounds):vO.setTRS(eM.ZERO,this.node.getRotation(),vN.copy(this.spawnBounds).mul(this.node.localScale)),vM[0]=0!==this.emitterExtents.x?this.emitterExtentsInner.x/this.emitterExtents.x:0,vM[1]=0!==this.emitterExtents.y?this.emitterExtentsInner.y/this.emitterExtents.y:0,vM[2]=0!==this.emitterExtents.z?this.emitterExtentsInner.z/this.emitterExtents.z:0);for(let e=0;e<this.numParticles;e++)this._cpuUpdater.calcSpawnPosition(this.particleTex,vO,vM,t,e),this.useCpu&&(this.particleTex[4*e+3+2*this.numParticlesPot*4]=1);this.particleTexStart=new Float32Array(this.numParticlesPot*vR*4);for(let e=0;e<this.particleTexStart.length;e++)this.particleTexStart[e]=this.particleTex[e];this.useCpu||(this.pack8?(this.particleTexIN=vw(e,this.numParticlesPot,vR,this.particleTex,id,1,false),this.particleTexOUT=vw(e,this.numParticlesPot,vR,this.particleTex,id,1,false),this.particleTexStart=vw(e,this.numParticlesPot,vR,this.particleTexStart,id,1,false)):(this.particleTexIN=vw(e,this.numParticlesPot,vR,this.particleTex),this.particleTexOUT=vw(e,this.numParticlesPot,vR,this.particleTex),this.particleTexStart=vw(e,this.numParticlesPot,vR,this.particleTexStart)),this.rtParticleTexIN=new nM({colorBuffer:this.particleTexIN,depth:false}),this.rtParticleTexOUT=new nM({colorBuffer:this.particleTexOUT,depth:false}),this.swapTex=false);let i=new Map;this.localSpace&&i.set("LOCAL_SPACE",""),this.pack8&&i.set("PACK8",""),this.emitterShape===fh&&i.set("EMITTERSHAPE_BOX","");let s=`Shape:${this.emitterShape}-Pack:${this.pack8}-Local:${this.localSpace}`,r={attributes:{vertex_position:sT},vertexChunk:"fullscreenQuadVS",fragmentChunk:"particle_simulationPS",fragmentDefines:i,fragmentIncludes:new Map(mr.get(e,e.isWebGPU?rw:rb))};r.uniqueName=`ParticleUpdateRespawn-${s}`,i.set("RESPAWN",""),this.shaderParticleUpdateRespawn=mo.createShader(e,r),i.delete("RESPAWN"),r.uniqueName=`ParticleUpdateNoRespawn-${s}`,i.set("NO_RESPAWN",""),this.shaderParticleUpdateNoRespawn=mo.createShader(e,r),i.delete("NO_RESPAWN"),r.uniqueName=`ParticleUpdateStop-${s}`,i.set("ON_STOP",""),this.shaderParticleUpdateOnStop=mo.createShader(e,r),this.numParticleVerts=this.useMesh?this.mesh.vertexBuffer.numVertices:4,this.numParticleIndices=this.useMesh?this.mesh.indexBuffer[0].numIndices:6,this._allocate(this.numParticles);let a=new mw(e);a.vertexBuffer=this.vertexBuffer,a.indexBuffer[0]=this.indexBuffer,a.primitive[0].type=sS,a.primitive[0].base=0,a.primitive[0].count=this.numParticles*this.numParticleIndices,a.primitive[0].indexed=true,this.material=this._createMaterial(),this.resetMaterial();let n=!this.meshInstance||this.meshInstance.visible;this.meshInstance=new mV(a,this.material,this.node),this.meshInstance.pick=false,this.meshInstance.updateKey(),this.meshInstance.cull=true,this.localSpace?this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,this.node.getWorldTransform()):this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance._updateAabb=false,this.meshInstance.visible=n,this._setMaterialTextures(),this.resetTime(),this.addTime(0,false),this.preWarm&&this.prewarm(this.lifetime);}_isAnimated(){return this.animNumFrames>=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)}rebuildGraphs(){let e=this.precision,t=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(e),this.qVelocity=this.velocityGraph.quantize(e),this.qColor=this.colorGraph.quantizeClamped(e,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(e),this.qScale=this.scaleGraph.quantize(e),this.qAlpha=this.alphaGraph.quantize(e),this.qRadialSpeed=this.radialSpeedGraph.quantize(e),this.qLocalVelocity2=this.localVelocityGraph2.quantize(e),this.qVelocity2=this.velocityGraph2.quantize(e),this.qColor2=this.colorGraph2.quantizeClamped(e,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(e),this.qScale2=this.scaleGraph2.quantize(e),this.qAlpha2=this.alphaGraph2.quantize(e),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(e);for(let t=0;t<e;t++)this.qRotSpeed[t]*=eA.DEG_TO_RAD,this.qRotSpeed2[t]*=eA.DEG_TO_RAD;if(this.localVelocityUMax=new Float32Array(3),this.velocityUMax=new Float32Array(3),this.colorUMax=new Float32Array(3),this.rotSpeedUMax=[0],this.scaleUMax=[0],this.alphaUMax=[0],this.radialSpeedUMax=[0],this.qLocalVelocityDiv=vG(this.qLocalVelocity,this.qLocalVelocity2,this.localVelocityUMax),this.qVelocityDiv=vG(this.qVelocity,this.qVelocity2,this.velocityUMax),this.qColorDiv=vG(this.qColor,this.qColor2,this.colorUMax),this.qRotSpeedDiv=vG(this.qRotSpeed,this.qRotSpeed2,this.rotSpeedUMax),this.qScaleDiv=vG(this.qScale,this.qScale2,this.scaleUMax),this.qAlphaDiv=vG(this.qAlpha,this.qAlpha2,this.alphaUMax),this.qRadialSpeedDiv=vG(this.qRadialSpeed,this.qRadialSpeed2,this.radialSpeedUMax),this.pack8){let e=[0,0,0];vz(this.qVelocity,e);let t=[0,0,0];vz(this.qVelocity2,t);let i=[0,0,0];vz(this.qLocalVelocity,i);let s=[0,0,0];vz(this.qLocalVelocity2,s);let r=[0];vz(this.qRadialSpeed,r);let a=[0];vz(this.qRadialSpeed2,a);let n=Math.max(e[0],t[0]);n=Math.max(n=Math.max(n=Math.max(n=Math.max(n,e[1]),t[1]),e[2]),t[2]);let o=Math.max(i[0],s[0]);o=Math.max(o=Math.max(o=Math.max(o=Math.max(o,i[1]),s[1]),i[2]),s[2]);let l=Math.max(r[0],a[0]);this.maxVel=n+o+l;}this.useCpu||(this.internalTex0=vw(t,e,1,vV(this.qLocalVelocity,this.qLocalVelocityDiv)),this.internalTex1=vw(t,e,1,vV(this.qVelocity,this.qVelocityDiv)),this.internalTex2=vw(t,e,1,function(e,t,i,s,r){let a=Array(4*e.length);for(let n=0;n<e.length;n++)a[4*n]=e[n],a[4*n+1]=t[n],a[4*n+2]=0,a[4*n+3]=vk(i[n],s[n],r[n]);return a}(this.qRotSpeed,this.qScale,this.qScaleDiv,this.qRotSpeedDiv,this.qAlphaDiv)),this.internalTex3=vw(t,e,1,function(e,t){let i=Array(4*e.length);for(let s=0;s<e.length;s++)i[4*s]=e[s],i[4*s+1]=t[s],i[4*s+2]=0,i[4*s+3]=0;return i}(this.qRadialSpeed,this.qRadialSpeedDiv))),this.colorParam=vw(t,e,1,function(e,t){let i=Array(4*t.length);for(let s=0;s<t.length;s++)i[4*s]=e[3*s],i[4*s+1]=e[3*s+1],i[4*s+2]=e[3*s+2],i[4*s+3]=t[s];return i}(this.qColor,this.qAlpha),ib,1,true);}_setMaterialTextures(){this.colorMap&&(this.material.setParameter("colorMap",this.colorMap),this.lighting&&this.normalMap&&this.material.setParameter("normalMap",this.normalMap));}_createMaterial(){let e=new vA(this);return e.name=`EmitterMaterial:${this.node.name}`,e.cull=tY,e.alphaWrite=false,e.blendType=this.blendType,e.depthWrite=this.depthWrite,e}resetMaterial(){let e=this.material;e.setParameter("stretch",this.stretch),this._isAnimated()&&(e.setParameter("animTexTilesParams",this.animTilesParams),e.setParameter("animTexParams",this.animParams),e.setParameter("animTexIndexParams",this.animIndexParams)),e.setParameter("colorMult",this.intensity),this.useCpu||(e.setParameter("internalTex0",this.internalTex0),e.setParameter("internalTex1",this.internalTex1),e.setParameter("internalTex2",this.internalTex2),e.setParameter("internalTex3",this.internalTex3)),e.setParameter("colorParam",this.colorParam),e.setParameter("numParticles",this.numParticles),e.setParameter("numParticlesPot",this.numParticlesPot),e.setParameter("lifetime",this.lifetime),e.setParameter("rate",this.rate),e.setParameter("rateDiv",this.rate2-this.rate),e.setParameter("seed",this.seed),e.setParameter("scaleDivMult",this.scaleUMax[0]),e.setParameter("alphaDivMult",this.alphaUMax[0]),e.setParameter("radialSpeedDivMult",this.radialSpeedUMax[0]),e.setParameter("graphNumSamples",this.precision),e.setParameter("graphSampleSize",1/this.precision),e.setParameter("emitterScale",new Float32Array([1,1,1])),this.pack8&&(this._gpuUpdater._setInputBounds(),e.setParameter("inBoundsSize",this._gpuUpdater.inBoundsSizeUniform),e.setParameter("inBoundsCenter",this._gpuUpdater.inBoundsCenterUniform),e.setParameter("maxVel",this.maxVel)),this.wrap&&this.wrapBounds&&(this.wrapBoundsUniform[0]=this.wrapBounds.x,this.wrapBoundsUniform[1]=this.wrapBounds.y,this.wrapBoundsUniform[2]=this.wrapBounds.z,e.setParameter("wrapBounds",this.wrapBoundsUniform)),this._setMaterialTextures(),this.depthSoftening>0&&e.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(e.cull=tY),this._compParticleFaceParams();}_compParticleFaceParams(){let e,t;if(this.orientation===fd)e=new Float32Array([1,0,0]),t=new Float32Array([0,0,1]);else {let i;i=this.orientation===fu?this.particleNormal.normalize():(null===this.node?eG.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();let s=new eM(1,0,0);1===Math.abs(s.dot(i))&&s.set(0,0,1);let r=new eM().cross(i,s).normalize();s.cross(r,i).normalize(),e=new Float32Array([s.x,s.y,s.z]),t=new Float32Array([r.x,r.y,r.z]);}this.material.setParameter("faceTangent",e),this.material.setParameter("faceBinorm",t);}getVertexInfo(){let e=[];return this.useCpu?e.push({semantic:sB,components:4,type:rM},{semantic:sU,components:4,type:rM},{semantic:sk,components:4,type:rM},{semantic:sV,components:1,type:rM},{semantic:sz,components:this.useMesh?4:2,type:rM}):(e.push({semantic:sB,components:4,type:rM}),this.useMesh&&e.push({semantic:sU,components:2,type:rM})),e}_allocate(e){let t=e*this.numParticleVerts,i=e*this.numParticleIndices;if(void 0===this.vertexBuffer||this.vertexBuffer.getNumVertices()!==t){let s,r,a,n=this.getVertexInfo(),o=new nP(this.graphicsDevice,n);this.vertexBuffer=new nT(this.graphicsDevice,o,t,{usage:tO}),this.indexBuffer=new lJ(this.graphicsDevice,ii,i);let l=new Float32Array(this.vertexBuffer.lock());if(this.useMesh){r=(s=new Float32Array(this.mesh.vertexBuffer.lock())).length/this.mesh.vertexBuffer.numVertices;for(let e=0;e<this.mesh.vertexBuffer.format.elements.length;e++)if(this.mesh.vertexBuffer.format.elements[e].name===sL){a=this.mesh.vertexBuffer.format.elements[e].offset/4;break}}for(let e=0;e<t;e++){let t=Math.floor(e/this.numParticleVerts);if(this.useMesh){let i=e%this.numParticleVerts;l[6*e]=s[i*r],l[6*e+1]=s[i*r+1],l[6*e+2]=s[i*r+2],l[6*e+3]=t,l[6*e+4]=s[i*r+a+0],l[6*e+5]=1-s[i*r+a+1];}else {let i=e%4;l[4*e]=vb[i][0],l[4*e+1]=vb[i][1],l[4*e+2]=0,l[4*e+3]=t;}}this.useCpu&&(this.vbCPU=new Float32Array(l),this.vbOld=new Float32Array(this.vbCPU.length)),this.vertexBuffer.unlock(),this.useMesh&&this.mesh.vertexBuffer.unlock();let h=0,c=new Uint32Array(this.indexBuffer.lock());if(this.useMesh){let e=this.mesh.indexBuffer[0];s=new aJ[e.format](e.lock());}for(let t=0;t<e;t++)if(this.useMesh)for(let e=0;e<this.numParticleIndices;e++)c[t*this.numParticleIndices+e]=s[e]+t*this.numParticleVerts;else {let e=4*t;c[h++]=e,c[h++]=e+1,c[h++]=e+2,c[h++]=e,c[h++]=e+2,c[h++]=e+3;}this.indexBuffer.unlock(),this.useMesh&&this.mesh.indexBuffer[0].unlock();}}reset(){if(this.beenReset=true,this.seed=Math.random(),this.material.setParameter("seed",this.seed),this.useCpu)for(let e=0;e<this.particleTexStart.length;e++)this.particleTex[e]=this.particleTexStart[e];else this._setMaterialTextures();this.resetWorldBounds(),this.resetTime();let e=this.loop;this.loop=true,this.addTime(0,false),this.loop=e,this.preWarm&&this.prewarm(this.lifetime);}prewarm(e){let t=Math.min(Math.floor(e/this.lifetime*this.precision),this.precision),i=e/t;for(let e=0;e<t;e++)this.addTime(i,false);}resetTime(){this.endTime=function(e){let t=Math.max(e.rate,e.rate2)*e.numParticles+e.lifetime;return Date.now()+1e3*t}(this);}finishFrame(){this.useCpu&&this.vertexBuffer.unlock();}addTime(e,t){let i,s=this.graphicsDevice;if(this.simTimeTotal+=e,this.calculateWorldBounds(),this._isAnimated()){let e=this.animTilesParams;e[0]=1/this.animTilesX,e[1]=1/this.animTilesY;let t=this.animParams;t[0]=this.animStartFrame,t[1]=this.animNumFrames*this.animSpeed,t[2]=this.animNumFrames-1,t[3]=this.animNumAnimations-1;let i=this.animIndexParams;i[0]=this.animIndex,i[1]=this.randomizeAnimIndex;}this.scene&&this.camera!==this.scene._activeCamera&&(this.camera=this.scene._activeCamera,this.onChangeCamera()),this.emitterShape===fh&&(vM[0]=0!==this.emitterExtents.x?this.emitterExtentsInner.x/this.emitterExtents.x:0,vM[1]=0!==this.emitterExtents.y?this.emitterExtentsInner.y/this.emitterExtents.y:0,vM[2]=0!==this.emitterExtents.z?this.emitterExtentsInner.z/this.emitterExtents.z:0,null===this.meshInstance.node?vO.setTRS(eM.ZERO,eH.IDENTITY,this.emitterExtents):vO.setTRS(eM.ZERO,this.meshInstance.node.getRotation(),vN.copy(this.emitterExtents).mul(this.meshInstance.node.localScale)));let r=null===this.meshInstance.node?eM.ONE:this.meshInstance.node.localScale;if(this.emitterScaleUniform[0]=r.x,this.emitterScaleUniform[1]=r.y,this.emitterScaleUniform[2]=r.z,this.material.setParameter("emitterScale",this.emitterScaleUniform),this.localSpace&&this.meshInstance.node&&(i=this.meshInstance.node.getPosition(),this.emitterPosUniform[0]=i.x,this.emitterPosUniform[1]=i.y,this.emitterPosUniform[2]=i.z,this.material.setParameter("emitterPos",this.emitterPosUniform)),this._compParticleFaceParams(),this.useCpu){let s=new Float32Array(this.vertexBuffer.lock());this._cpuUpdater.update(s,this.vbToSort,this.particleTex,vO,vM,i,e,t);}else this._gpuUpdater.update(s,vO,vM,e,t);!this.loop&&Date.now()>this.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=false),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder);}_destroyResources(){this.particleTexIN?.destroy(),this.particleTexIN=null,this.particleTexOUT?.destroy(),this.particleTexOUT=null,this.particleTexStart&&this.particleTexStart.destroy&&(this.particleTexStart.destroy(),this.particleTexStart=null),this.rtParticleTexIN?.destroy(),this.rtParticleTexIN=null,this.rtParticleTexOUT?.destroy(),this.rtParticleTexOUT=null,this.internalTex0?.destroy(),this.internalTex0=null,this.internalTex1?.destroy(),this.internalTex1=null,this.internalTex2?.destroy(),this.internalTex2=null,this.internalTex3?.destroy(),this.internalTex3=null,this.colorParam?.destroy(),this.colorParam=null,this.vertexBuffer?.destroy(),this.vertexBuffer=void 0,this.indexBuffer?.destroy(),this.indexBuffer=void 0,this.material?.destroy(),this.material=null;}destroy(){this.camera=null,this._destroyResources();}}let vX=new class extends p9{generateKey(e){let t=e.shaderDesc,i=t.vertexGLSL?nE(t.vertexGLSL):0,s=t.fragmentGLSL?nE(t.fragmentGLSL):0,r=t.vertexWGSL?nE(t.vertexWGSL):0,a=t.fragmentWGSL?nE(t.fragmentWGSL):0,n=p9.definesHash(e.defines),o=e.shaderChunks?.key??"",l=`${t.uniqueName}_${n}_${i}_${s}_${r}_${a}_${o}`;return e.skin&&(l+="_skin"),e.useInstancing&&(l+="_inst"),e.useMorphPosition&&(l+="_morphp"),e.useMorphNormal&&(l+="_morphn"),e.useMorphTextureBasedInt&&(l+="_morphi"),l}createAttributesDefinition(e,t){let i=t.shaderDesc.attributes,s=i?{...i}:void 0;t.skin&&(s.vertex_boneWeights=sb,s.vertex_boneIndices=sw),(t.useMorphPosition||t.useMorphNormal)&&(s.morph_vertex_id=sQ),e.attributes=s;}createVertexDefinition(e,t,i,s){let r=t.shaderDesc,a=new Map(i);a.set("transformInstancingVS","");let n=new Map(t.defines);t.skin&&n.set("SKIN",true),t.useInstancing&&n.set("INSTANCING",true),(t.useMorphPosition||t.useMorphNormal)&&(n.set("MORPHING",true),t.useMorphTextureBasedInt&&n.set("MORPHING_INT",true),t.useMorphPosition&&n.set("MORPHING_POSITION",true),t.useMorphNormal&&n.set("MORPHING_NORMAL",true)),e.vertexCode=s?r.vertexWGSL:r.vertexGLSL,e.vertexIncludes=a,e.vertexDefines=n;}createFragmentDefinition(e,t,i,s){let r=t.shaderDesc,a=new Map(i),n=new Map(t.defines);e.fragmentCode=s?r.fragmentWGSL:r.fragmentGLSL,e.fragmentIncludes=a,e.fragmentDefines=n;}createShaderDefinition(e,t){let i=t.shaderDesc,s=e.isWebGPU&&!!i.vertexWGSL&&!!i.fragmentWGSL&&(t.shaderChunks?.useWGSL??true),r={name:`ShaderMaterial-${i.uniqueName}`,shaderLanguage:s?rw:rb,fragmentOutputTypes:i.fragmentOutputTypes,meshUniformBufferFormat:i.meshUniformBufferFormat,meshBindGroupFormat:i.meshBindGroupFormat},a=s?rw:rb,n=ma.merge(mr.get(e,a),t.shaderChunks[a]);return this.createAttributesDefinition(r,t),this.createVertexDefinition(r,t,n,s),this.createFragmentDefinition(r,t,n,s),ls.createDefinition(e,r)}};class vY extends _${constructor(e){super(),this.shaderDesc=e;}set shaderDesc(e){if(this._shaderDesc=void 0,e&&(this._shaderDesc={uniqueName:e.uniqueName,attributes:e.attributes,fragmentOutputTypes:e.fragmentOutputTypes,vertexGLSL:e.vertexGLSL,fragmentGLSL:e.fragmentGLSL,vertexWGSL:e.vertexWGSL,fragmentWGSL:e.fragmentWGSL},e.vertexCode||e.fragmentCode||e.shaderLanguage)){let t=e.shaderLanguage??rb;t===rb?(this._shaderDesc.vertexGLSL=e.vertexCode,this._shaderDesc.fragmentGLSL=e.fragmentCode):t===rw&&(this._shaderDesc.vertexWGSL=e.vertexCode,this._shaderDesc.fragmentWGSL=e.fragmentCode);}this.clearVariants();}get shaderDesc(){return this._shaderDesc}copy(e){return super.copy(e),this.shaderDesc=e.shaderDesc,this}getShaderVariant(e){let{objDefs:t}=e,i={defines:mo.getCoreDefines(this,e),skin:(t&f0)!=0,useInstancing:(t&f4)!=0,useMorphPosition:(t&f7)!=0,useMorphNormal:(t&pe)!=0,useMorphTextureBasedInt:(t&pi)!=0,pass:e.pass,gamma:e.cameraShaderParams.shaderOutputGamma,toneMapping:e.cameraShaderParams.toneMapping,fog:e.cameraShaderParams.fog,shaderDesc:this.shaderDesc,shaderChunks:this.shaderChunks},s=new p5(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),r=p6(e.device);return r.register("shader-material",vX),r.getProgram("shader-material",i,s,this.userId)}}let vq={linear:"decodeLinear",srgb:"decodeGamma",rgbm:"decodeRGBM",rgbe:"decodeRGBE",rgbp:"decodeRGBP",xy:"unpackNormalXY",xyz:"unpackNormalXYZ"},v$={linear:"encodeLinear",srgb:"encodeGamma",rgbm:"encodeRGBM",rgbe:"encodeRGBE",rgbp:"encodeRGBP"};class vj{static decodeFunc(e){return vq[e]??"decodeGamma"}static encodeFunc(e){return v$[e]??"encodeGamma"}}let vK=(e,t)=>{let i=t.length/3,s=e.length/3,r=new eM,a=new eM,n=new eM,o=new eM,l=new eM,h=new eM,c=[];for(let t=0;t<e.length;t++)c[t]=0;for(let s=0;s<i;s++){let i=t[3*s],d=t[3*s+1],u=t[3*s+2];r.set(e[3*i],e[3*i+1],e[3*i+2]),a.set(e[3*d],e[3*d+1],e[3*d+2]),n.set(e[3*u],e[3*u+1],e[3*u+2]),o.sub2(a,r),l.sub2(n,r),h.cross(o,l).normalize(),c[3*i]+=h.x,c[3*i+1]+=h.y,c[3*i+2]+=h.z,c[3*d]+=h.x,c[3*d+1]+=h.y,c[3*d+2]+=h.z,c[3*u]+=h.x,c[3*u+1]+=h.y,c[3*u+2]+=h.z;}for(let e=0;e<s;e++){let t=c[3*e],i=c[3*e+1],s=c[3*e+2],r=1/Math.sqrt(t*t+i*i+s*s);c[3*e]*=r,c[3*e+1]*=r,c[3*e+2]*=r;}return c},vZ=(e,t,i,s)=>{let r=s.length/3,a=e.length/3,n=new eM,o=new eM,l=new eM,h=new eN,c=new eN,d=new eN,u=new eM,f=new eM,p=new Float32Array(3*a),m=new Float32Array(3*a),_=[];for(let t=0;t<r;t++){let r=s[3*t],a=s[3*t+1],_=s[3*t+2];n.set(e[3*r],e[3*r+1],e[3*r+2]),o.set(e[3*a],e[3*a+1],e[3*a+2]),l.set(e[3*_],e[3*_+1],e[3*_+2]),h.set(i[2*r],i[2*r+1]),c.set(i[2*a],i[2*a+1]),d.set(i[2*_],i[2*_+1]);let g=o.x-n.x,v=l.x-n.x,S=o.y-n.y,y=l.y-n.y,x=o.z-n.z,T=l.z-n.z,E=c.x-h.x,A=d.x-h.x,b=c.y-h.y,w=d.y-h.y,C=E*w-A*b;if(0===C)u.set(0,1,0),f.set(1,0,0);else {let e=1/C;u.set((w*g-b*v)*e,(w*S-b*y)*e,(w*x-b*T)*e),f.set((E*v-A*g)*e,(E*y-A*S)*e,(E*T-A*x)*e);}p[3*r+0]+=u.x,p[3*r+1]+=u.y,p[3*r+2]+=u.z,p[3*a+0]+=u.x,p[3*a+1]+=u.y,p[3*a+2]+=u.z,p[3*_+0]+=u.x,p[3*_+1]+=u.y,p[3*_+2]+=u.z,m[3*r+0]+=f.x,m[3*r+1]+=f.y,m[3*r+2]+=f.z,m[3*a+0]+=f.x,m[3*a+1]+=f.y,m[3*a+2]+=f.z,m[3*_+0]+=f.x,m[3*_+1]+=f.y,m[3*_+2]+=f.z;}let g=new eM,v=new eM,S=new eM,y=new eM;for(let e=0;e<a;e++){S.set(t[3*e],t[3*e+1],t[3*e+2]),g.set(p[3*e],p[3*e+1],p[3*e+2]),v.set(m[3*e],m[3*e+1],m[3*e+2]);let i=S.dot(g);y.copy(S).mulScalar(i),y.sub2(g,y).normalize(),_[4*e]=y.x,_[4*e+1]=y.y,_[4*e+2]=y.z,y.cross(S,g),_[4*e+3]=0>y.dot(v)?-1:1;}return _};class vQ{calculateNormals(){this.normals=vK(this.positions,this.indices);}calculateTangents(){this.tangents=vZ(this.positions,this.normals,this.uvs,this.indices);}}class vJ extends vQ{constructor(e={}){super();let t=e.halfExtents??new eM(.5,.5,.5),i=e.widthSegments??1,s=e.lengthSegments??1,r=e.heightSegments??1,a=e.yOffset??0,n=-t.y+a,o=t.y+a,l=[new eM(-t.x,n,t.z),new eM(t.x,n,t.z),new eM(t.x,o,t.z),new eM(-t.x,o,t.z),new eM(t.x,n,-t.z),new eM(-t.x,n,-t.z),new eM(-t.x,o,-t.z),new eM(t.x,o,-t.z)],h=[[0,1,3],[4,5,7],[3,2,6],[1,0,4],[1,4,2],[5,0,6]],c=[[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]],d=[],u=[],f=[],p=[],m=0,_=(e,t,i)=>{let s=new eM,r=new eM,a=new eM,n=new eM;for(let o=0;o<=t;o++)for(let _=0;_<=i;_++){s.lerp(l[h[e][0]],l[h[e][1]],o/t),r.lerp(l[h[e][0]],l[h[e][2]],_/i),a.sub2(r,l[h[e][0]]),n.add2(s,a);let g=o/t,v=_/i;d.push(n.x,n.y,n.z),u.push(c[e][0],c[e][1],c[e][2]),f.push(g,1-v),v=(.875*v+.0625)/3,g=(.875*g+.0625)/3+e%3/3,v+=Math.floor(e/3)/3,o<t&&_<i&&(p.push(m+i+1,m+1,m),p.push(m+i+1,m+i+2,m+1)),m++;}};_(0,i,r),_(1,i,r),_(2,i,s),_(3,i,s),_(4,s,r),_(5,s,r),this.positions=d,this.normals=u,this.uvs=f,this.uvs1=f,this.indices=p,e.calculateTangents&&(this.tangents=vZ(d,u,f,p));}}class v0 extends vQ{constructor(e={}){super();let t=e.radius??.5,i=e.latitudeBands??16,s=e.longitudeBands??16,r=[],a=[],n=[],o=[];for(let e=0;e<=i;e++){let o=e*Math.PI/i,l=Math.sin(o),h=Math.cos(o);for(let o=0;o<=s;o++){let c=2*o*Math.PI/s-Math.PI/2,d=Math.sin(c),u=Math.cos(c)*l,f=d*l,p=1-o/s,m=1-e/i;r.push(u*t,h*t,f*t),a.push(u,h,f),n.push(p,1-m);}}for(let e=0;e<i;++e)for(let t=0;t<s;++t){let i=e*(s+1)+t,r=i+s+1;o.push(i+1,r,i),o.push(i+1,r+1,r);}this.positions=r,this.normals=a,this.uvs=n,this.uvs1=n,this.indices=o,e.calculateTangents&&(this.tangents=vZ(r,a,n,o));}}class v1 extends v0{constructor(e={}){super({radius:.5,latitudeBands:e.latitudeBands??16,longitudeBands:e.longitudeBands??16});let t=this.positions;for(let e=0;e<t.length;e+=3){let i=t[e]/.5,s=t[e+1]/.5,r=t[e+2]/.5;s<0&&(s*=.3,i*i+r*r<.9025&&(s=-0.1)),s+=.1,s*=.5,t[e+1]=s;}}}class v2{static create(e,t){switch(t){case pX:return v2.box(e);case pY:return v2.dome(e)}return v2.infinite(e)}static infinite(e){return mw.fromGeometry(e,new vJ(e))}static box(e){return mw.fromGeometry(e,new vJ({yOffset:.5}))}static dome(e){let t=new v1({latitudeBands:50,longitudeBands:50});return t.normals=void 0,t.uvs=void 0,mw.fromGeometry(e,t)}}class v3{constructor(e,t,i,s,r){this.meshInstance=null,this._depthWrite=false;let a=new vY({uniqueName:"SkyMaterial",vertexGLSL:mr.get(e,rb).get("skyboxVS"),fragmentGLSL:mr.get(e,rb).get("skyboxPS"),vertexWGSL:mr.get(e,rw).get("skyboxVS"),fragmentWGSL:mr.get(e,rw).get("skyboxPS"),attributes:{aPosition:sT}});a.setDefine("{SKYBOX_DECODE_FNC}",vj.decodeFunc(s.encoding)),r!==pW&&a.setDefine("SKYMESH",""),s.cubemap&&a.setDefine("SKY_CUBEMAP",""),a.setParameter("skyboxHighlightMultiplier",t.skyboxHighlightMultiplier),s.cubemap?a.setParameter("texture_cubeMap",s):(a.setParameter("texture_envAtlas",s),a.setParameter("mipLevel",t.skyboxMip)),a.cull=t$,a.depthWrite=this._depthWrite;let n=t.layers.getLayerById(uC);if(n){let t=new mV(v2.create(e,r),a,i);this.meshInstance=t,t.cull=false,t.pick=false,n.addMeshInstances([t]),this.skyLayer=n;}}destroy(){this.meshInstance&&(this.skyLayer&&this.skyLayer.removeMeshInstances([this.meshInstance]),this.meshInstance.destroy(),this.meshInstance=null);}set depthWrite(e){this._depthWrite=e,this.meshInstance&&(this.meshInstance.material.depthWrite=e);}get depthWrite(){return this._depthWrite}}class v4{constructor(e){this._type=pW,this._center=new eM(0,1,0),this.skyMesh=null,this._depthWrite=false,this.node=new _c("SkyMeshNode"),this.device=e.device,this.scene=e,this.center=new eM(0,1,0),this.centerArray=new Float32Array(3),this.projectedSkydomeCenterId=this.device.scope.resolve("projectedSkydomeCenter");}applySettings(e){this.type=e.skyType??pW,this.node.setLocalPosition(new eM(e.skyMeshPosition??[0,0,0])),this.node.setLocalEulerAngles(new eM(e.skyMeshRotation??[0,0,0])),this.node.setLocalScale(new eM(e.skyMeshScale??[1,1,1])),e.skyCenter&&(this._center=new eM(e.skyCenter));}set type(e){this._type!==e&&(this._type=e,this.scene.updateShaders=true,this.updateSkyMesh());}get type(){return this._type}set center(e){this._center.copy(e);}get center(){return this._center}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.skyMesh&&(this.skyMesh.depthWrite=e));}get depthWrite(){return this._depthWrite}updateSkyMesh(){let e=this.scene._getSkyboxTex();e&&(this.resetSkyMesh(),this.skyMesh=new v3(this.device,this.scene,this.node,e,this.type),this.skyMesh.depthWrite=this._depthWrite,this.scene.fire("set:skybox",e));}resetSkyMesh(){this.skyMesh?.destroy(),this.skyMesh=null;}update(){if(this.type!==pW){let{center:e,centerArray:t}=this,i=new eM;this.node.getWorldTransform().transformPoint(e,i),t[0]=i.x,t[1]=i.y,t[2]=i.z,this.projectedSkydomeCenterId.setValue(t);}}}let v5=new _c;v5.worldTransform=eG.IDENTITY,v5._dirtyWorld=v5._dirtyNormal=false;class v8{constructor(e,t,i){this.material=t,this.layer=i,this.positions=[],this.colors=[],this.mesh=new mw(e),this.meshInstance=null;}addLines(e,t){let i=this.positions,s=e.length;for(let t=0;t<s;t++){let s=e[t];i.push(s.x,s.y,s.z);}let r=this.colors;if(t.length)for(let e=0;e<s;e++){let i=t[e];r.push(i.r,i.g,i.b,i.a);}else for(let e=0;e<s;e++)r.push(t.r,t.g,t.b,t.a);}addLinesArrays(e,t){let i=this.positions;for(let t=0;t<e.length;t+=3)i.push(e[t],e[t+1],e[t+2]);let s=this.colors;if(t.length)for(let e=0;e<t.length;e+=4)s.push(t[e],t[e+1],t[e+2],t[e+3]);else {let i=e.length/3;for(let e=0;e<i;e++)s.push(t.r,t.g,t.b,t.a);}}onPreRender(e,t){this.positions.length>0&&this.material.transparent===t&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(s_,false),this.meshInstance||(this.meshInstance=new mV(this.mesh,this.material,v5)),e.push(this.meshInstance));}clear(){this.positions.length=0,this.colors.length=0;}}class v6{constructor(e){this.device=e,this.map=new Map;}getBatch(e,t){let i=this.map.get(e);return i||(i=new v8(this.device,e,t),this.map.set(e,i)),i}onPreRender(e,t){this.map.forEach(i=>{i.onPreRender(e,t);});}clear(){this.map.forEach(e=>e.clear());}}let v9=[],v7=new eM;class Se{constructor(e){this.shaderDescs=new Map,this.device=e,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.batchesMap=new Map,this.allBatches=new Set,this.updatedLayers=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map;}createMaterial(e){let t=new vY({uniqueName:"ImmediateLine",vertexGLSL:mr.get(this.device,rb).get("immediateLineVS"),fragmentGLSL:mr.get(this.device,rb).get("immediateLinePS"),vertexWGSL:mr.get(this.device,rw).get("immediateLineVS"),fragmentWGSL:mr.get(this.device,rw).get("immediateLinePS"),attributes:{vertex_position:sT,vertex_color:sC}});return t.blendType=ua,t.depthTest=e,t.update(),t}get materialDepth(){return this._materialDepth||(this._materialDepth=this.createMaterial(true)),this._materialDepth}get materialNoDepth(){return this._materialNoDepth||(this._materialNoDepth=this.createMaterial(false)),this._materialNoDepth}getBatch(e,t){let i=this.batchesMap.get(e);i||(i=new v6(this.device),this.batchesMap.set(e,i)),this.allBatches.add(i);let s=t?this.materialDepth:this.materialNoDepth;return i.getBatch(s,e)}getShaderDesc(e,t,i){return this.shaderDescs.has(e)||this.shaderDescs.set(e,{uniqueName:`DebugShader:${e}`,vertexGLSL:`
attribute vec2 vertex_position;
uniform mat4 matrix_model;
varying vec2 uv0;
void main(void) {
gl_Position = matrix_model * vec4(vertex_position, 0, 1);
uv0 = vertex_position.xy + 0.5;
}
`,vertexWGSL:`
attribute vertex_position: vec2f;
uniform matrix_model: mat4x4f;
varying uv0: vec2f;
@vertex fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = uniform.matrix_model * vec4f(input.vertex_position, 0.0, 1.0);
output.uv0 = input.vertex_position.xy + vec2f(0.5);
return output;
}
`,fragmentGLSL:t,fragmentWGSL:i,attributes:{vertex_position:sT}}),this.shaderDescs.get(e)}getTextureShaderDesc(e){let t=vj.decodeFunc(e);return this.getShaderDesc(`textureShader-${e}`,`
#include "gammaPS"
varying vec2 uv0;
uniform sampler2D colorMap;
void main (void) {
vec3 linearColor = ${t}(texture2D(colorMap, uv0));
gl_FragColor = vec4(gammaCorrectOutput(linearColor), 1);
}
`,`
#include "gammaPS"
varying uv0: vec2f;
var colorMap: texture_2d<f32>;
var colorMapSampler: sampler;
@fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let sampledTex = textureSample(colorMap, colorMapSampler, input.uv0);
let linearColor: vec3f = ${t}(sampledTex);
output.color = vec4f(gammaCorrectOutput(linearColor), 1.0);
return output;
}
`)}getUnfilterableTextureShaderDesc(){return this.getShaderDesc("textureShaderUnfilterable",`
varying vec2 uv0;
uniform highp sampler2D colorMap;
void main (void) {
ivec2 uv = ivec2(uv0 * textureSize(colorMap, 0));
gl_FragColor = vec4(texelFetch(colorMap, uv, 0).xyz, 1);
}
`,`
varying uv0: vec2f;
var colorMap: texture_2d<uff>;
@fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let uv : vec2<i32> = vec2<i32>(input.uv0 * vec2f(textureDimensions(colorMap, 0)));
let fetchedColor : vec4f = textureLoad(colorMap, uv, 0);
output.color = vec4f(fetchedColor.xyz, 1.0);
return output;
}
`)}getDepthTextureShaderDesc(){return this.getShaderDesc("depthTextureShader",`
#include "screenDepthPS"
#include "gammaPS"
varying vec2 uv0;
void main() {
float depth = getLinearScreenDepth(getImageEffectUV(uv0)) * camera_params.x;
gl_FragColor = vec4(gammaCorrectOutput(vec3(depth)), 1.0);
}
`,`
#include "screenDepthPS"
#include "gammaPS"
varying uv0: vec2f;
@fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let depth: f32 = getLinearScreenDepth(getImageEffectUV(input.uv0)) * uniform.camera_params.x;
output.color = vec4f(gammaCorrectOutput(vec3f(depth)), 1.0);
return output;
}
`)}getQuadMesh(){return this.quadMesh||(this.quadMesh=new mw(this.device),this.quadMesh.setPositions([-0.5,-0.5,0,.5,-0.5,0,-0.5,.5,0,.5,.5,0]),this.quadMesh.update(sy)),this.quadMesh}drawMesh(e,t,i,s,r){s||(s=new mV(i,e,this.getGraphNode(t)));let a=this.layerMeshInstances.get(r);a||(a=[],this.layerMeshInstances.set(r,a)),a.push(s);}drawWireAlignedBox(e,t,i,s,r,a){if(a){let i=(e,t,i)=>{v7.set(e,t,i),a.transformPoint(v7,v7),v9.push(v7.x,v7.y,v7.z);};i(e.x,e.y,e.z),i(e.x,t.y,e.z),i(e.x,t.y,e.z),i(t.x,t.y,e.z),i(t.x,t.y,e.z),i(t.x,e.y,e.z),i(t.x,e.y,e.z),i(e.x,e.y,e.z),i(e.x,e.y,t.z),i(e.x,t.y,t.z),i(e.x,t.y,t.z),i(t.x,t.y,t.z),i(t.x,t.y,t.z),i(t.x,e.y,t.z),i(t.x,e.y,t.z),i(e.x,e.y,t.z),i(e.x,e.y,e.z),i(e.x,e.y,t.z),i(e.x,t.y,e.z),i(e.x,t.y,t.z),i(t.x,t.y,e.z),i(t.x,t.y,t.z),i(t.x,e.y,e.z),i(t.x,e.y,t.z);}else v9.push(e.x,e.y,e.z,e.x,t.y,e.z,e.x,t.y,e.z,t.x,t.y,e.z,t.x,t.y,e.z,t.x,e.y,e.z,t.x,e.y,e.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,t.z,e.x,t.y,t.z,t.x,t.y,t.z,t.x,t.y,t.z,t.x,e.y,t.z,t.x,e.y,t.z,e.x,e.y,t.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,e.z,e.x,t.y,t.z,t.x,t.y,e.z,t.x,t.y,t.z,t.x,e.y,e.z,t.x,e.y,t.z);this.getBatch(r,s).addLinesArrays(v9,i),v9.length=0;}drawWireSphere(e,t,i,s,r,a){let n=2*Math.PI/s,o=0;for(let i=0;i<s;i++){let i=Math.sin(o),s=Math.cos(o),r=Math.sin(o+=n),a=Math.cos(o);v9.push(e.x+t*i,e.y,e.z+t*s),v9.push(e.x+t*r,e.y,e.z+t*a),v9.push(e.x+t*i,e.y+t*s,e.z),v9.push(e.x+t*r,e.y+t*a,e.z),v9.push(e.x,e.y+t*i,e.z+t*s),v9.push(e.x,e.y+t*r,e.z+t*a);}this.getBatch(a,r).addLinesArrays(v9,i),v9.length=0;}getGraphNode(e){let t=new _c("ImmediateDebug");return t.worldTransform=e,t._dirtyWorld=t._dirtyNormal=false,t}onPreRenderLayer(e,t,i){if(this.batchesMap.forEach((s,r)=>{r===e&&s.onPreRender(t,i);}),!this.updatedLayers.has(e)){this.updatedLayers.add(e);let i=this.layerMeshInstances.get(e);if(i){for(let e=0;e<i.length;e++)t.push(i[e]);i.length=0;}}}onPostRender(){this.allBatches.forEach(e=>e.clear()),this.allBatches.clear(),this.updatedLayers.clear();}}let St={circlePoint(e){let t=Math.sqrt(Math.random()),i=2*Math.random()*Math.PI;e.x=t*Math.cos(i),e.y=t*Math.sin(i);},circlePointDeterministic(e,t,i){let s=2.399963229728653*t,r=Math.sqrt(t)/Math.sqrt(i);e.x=r*Math.cos(s),e.y=r*Math.sin(s);},spherePointDeterministic(e,t,i,s=0,r=1){s=1-2*s,r=1-2*r;let a=eA.lerp(s,r,t/i),n=Math.sqrt(1-a*a),o=2.399963229728653*t;e.x=Math.cos(o)*n,e.y=a,e.z=Math.sin(o)*n;},radicalInverse(e){let t=(e<<16|e>>>16)>>>0;return 23283064365386963e-26*(t=((0xff00ff&(t=((0xf0f0f0f&(t=((0x33333333&(t=((0x55555555&t)<<1|(0xaaaaaaaa&t)>>>1)>>>0))<<2|(0xcccccccc&t)>>>2)>>>0))<<4|(0xf0f0f0f0&t)>>>4)>>>0))<<8|(0xff00ff00&t)>>>8)>>>0)}},Si=e=>{switch(e){case rT:return "Cubemap";case rA:return "Octahedral";default:return "Equirect"}},Ss=(e,t,i)=>{if(e<=0)t[i+0]=0,t[i+1]=0,t[i+2]=0,t[i+3]=0;else if(e>=1)t[i+0]=255,t[i+1]=0,t[i+2]=0,t[i+3]=0;else {let s=e%1,r=255*e%1,a=65025*e%1,n=0xfd02ff*e%1;s-=r/255,r-=a/255,a-=n/255,t[i+0]=Math.min(255,Math.floor(256*s)),t[i+1]=Math.min(255,Math.floor(256*r)),t[i+2]=Math.min(255,Math.floor(256*a)),t[i+3]=Math.min(255,Math.floor(256*n));}},Sr=e=>{let t=e.length,i=Math.min(t,512),s=Math.ceil(t/i),r=new Uint8Array(i*s*4),a=0;for(let i=0;i<t;i+=4)Ss(.5*e[i+0]+.5,r,a+0),Ss(.5*e[i+1]+.5,r,a+4),Ss(.5*e[i+2]+.5,r,a+8),Ss(e[i+3]/8,r,a+12),a+=16;return {width:i,height:s,data:r}},Sa=(e,t,i,s)=>{let r=2*i*Math.PI,a=Math.pow(1-t,1/(s+1)),n=Math.sqrt(1-a*a);e.set(Math.cos(r)*n,Math.sin(r)*n,a).normalize();},Sn=(e,t,i)=>{let s=2*i*Math.PI,r=Math.sqrt(1-t),a=Math.sqrt(t);e.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize();},So=(e,t,i,s)=>{let r=2*i*Math.PI,a=Math.sqrt((1-t)/(1+(s*s-1)*t)),n=Math.sqrt(1-a*a);e.set(Math.cos(r)*n,Math.sin(r)*n,a).normalize();},Sl=(e,t)=>{let i=e*t,s=t/(1-e*e+i*i);return s*s*(1/Math.PI)},Sh=(e,t)=>{let i=new eM,s=[];for(let r=0;r<e;++r)Sa(i,r/e,St.radicalInverse(r),t),s.push(i.x,i.y,i.z,0);return s},Sc=(e,t)=>{let i=t/e,s=new eM,r=[];for(let t=0;t<e;++t){Sn(s,t/e,St.radicalInverse(t));let a=.5*Math.log2(i/(s.z/Math.PI));r.push(s.x,s.y,s.z,a);}return r},Sd={16:{2:26,8:20,32:17,128:16,512:16},32:{2:53,8:40,32:34,128:32,512:32},128:{2:214,8:163,32:139,128:130,512:128},1024:{2:1722,8:1310,32:1114,128:1041,512:1025}},Su=(e,t)=>{let i=Sd[e];return i&&i[t]||e},Sf=(e,t,i)=>{let s=i/e,r=1-Math.log2(t)/11,a=r*r,n=new eM,o=new eM,l=new eM(0,0,1),h=[],c=Su(e,t);for(let e=0;e<c;++e){So(n,e/c,St.radicalInverse(e),a);let t=n.z;if(o.set(n.x,n.y,n.z).mulScalar(2*t).sub(l),o.z>0){let e=.5*Math.log2(s/(Sl(Math.min(1,t),a)/4+.001));h.push(o.x,o.y,o.z,e);}}for(;h.length<4*e;)h.push(0,0,0,0);return h},Sp=(e,t,i)=>{let s=Sr(i);return new ns(e,{name:t,width:s.width,height:s.height,mipmaps:false,minFilter:tK,magFilter:tK,levels:[s.data]})};class Sm{constructor(e=true){this.map=new Map,this.destroyContent=e;}destroy(){this.destroyContent&&this.map.forEach((e,t)=>{e.destroy();});}get(e,t){if(!this.map.has(e)){let i=t();return this.map.set(e,i),i}return this.map.get(e)}}let S_=new Sm(false),Sg=new ne,Sv=(e,t,i)=>Sg.get(e,()=>new Sm).get(t,()=>Sp(e,t,S_.get(t,i))),SS=(e,t,i)=>Sv(e,`lambert-samples-${t}-${i}`,()=>Sc(t,i)),Sy=(e,t,i)=>Sv(e,`phong-samples-${t}-${i}`,()=>Sh(t,i)),Sx=(e,t,i,s)=>Sv(e,`ggx-samples-${t}-${i}-${s}`,()=>Sf(t,i,s));function ST(e,t,i={}){let s=i.seamPixels??0,r=(i.rect?.z??t.width)-2*s,a=(i.rect?.w??t.height)-2*s;if(r<1||a<1)return false;let n=i.hasOwnProperty("specularPower")?i.specularPower:1,o=i.hasOwnProperty("face")?i.face:null,l=i.hasOwnProperty("distribution")?i.distribution:1===n?"none":"phong",h={none:"reproject",lambert:"prefilterSamplesUnweighted",phong:"prefilterSamplesUnweighted",ggx:"prefilterSamples"}[l]||"reproject",c=h.startsWith("prefilterSamples"),d=vj.decodeFunc(e.encoding),u=vj.encodeFunc(t.encoding),f=`sample${Si(e.projection)}`,p=`getDirection${Si(t.projection)}`,m=i.hasOwnProperty("numSamples")?i.numSamples:1024,_=`ReprojectShader:${h}_${d}_${u}_${f}_${p}_${m}`,g=e.device,v=p6(g).getCachedShader(_);if(!v){let t=new Map;c&&t.set("USE_SAMPLES_TEX",""),e.cubemap&&t.set("CUBEMAP_SOURCE",""),t.set("{PROCESS_FUNC}",h),t.set("{DECODE_FUNC}",d),t.set("{ENCODE_FUNC}",u),t.set("{SOURCE_FUNC}",f),t.set("{TARGET_FUNC}",p),t.set("{NUM_SAMPLES}",m),t.set("{NUM_SAMPLES_SQRT}",Math.round(Math.sqrt(m)).toFixed(1));let i=g.isWebGPU,s=mr.get(g,i?rw:rb),r=new Map;r.set("decodePS",s.get("decodePS")),r.set("encodePS",s.get("encodePS")),v=mo.createShader(g,{uniqueName:_,attributes:{vertex_position:sT},vertexChunk:"reprojectVS",fragmentChunk:"reprojectPS",fragmentIncludes:r,fragmentDefines:t});}g.setBlendState(nu.NOBLEND),g.scope.resolve(e.cubemap?"sourceCube":"sourceTex").setValue(e);let S=g.scope.resolve("params"),y=g.scope.resolve("uvMod");s>0?y.setValue([(r+2*s)/r,(a+2*s)/a,-s/r,-s/a]):y.setValue([1,1,0,0]);let x=[0,t.width*t.height*(t.cubemap?6:1),e.width*e.height*(e.cubemap?6:1)];if(c){let t=e.width*e.height*(e.cubemap?6:1),i="ggx"===l?Sx(g,m,n,t):"lambert"===l?SS(g,m,t):Sy(g,m,n);g.scope.resolve("samplesTex").setValue(i),g.scope.resolve("samplesTexInverseSize").setValue([1/i.width,1/i.height]);}for(let e=0;e<(t.cubemap?6:1);e++)if(null===o||e===o){let s=new nM({colorBuffer:t,face:e,depth:false,flipY:g.isWebGPU});x[0]=e,S.setValue(x),mg(g,s,v,i?.rect),s.destroy();}return true}let SE=(e,t=0)=>1+Math.floor(Math.log2(Math.max(e,t))),SA=e=>e.textureHalfFloatRenderable,Sb=e=>e.textureFloatRenderable,Sw=e=>SA(e)?ig:Sb(e)?iS:id,SC=e=>id,SP=(e,t,i,s)=>new ns(e,{name:`lighting-${t}`,cubemap:true,width:t,height:t,format:i,type:rr,addressU:tr,addressV:tr,mipmaps:false});class SL{static generateSkyboxCubemap(e,t){let i=SP(e.device,t||(e.cubemap?e.width:e.width/4),id);return ST(e,i,{numSamples:1024}),i}static generateLightingSource(e,t){let i=e.device,s=Sw(i),r=t?.target||new ns(i,{name:"lighting-source",cubemap:true,width:t?.size||128,height:t?.size||128,format:s,type:s===id?rr:rt,addressU:tr,addressV:tr,mipmaps:true});return ST(e,r,{numSamples:e.mipmaps?1:1024}),r}static generateAtlas(e,t){let i=e.device,s=SC(),r=t?.target||new ns(i,{name:"envAtlas",width:t?.size||512,height:t?.size||512,format:s,type:rr,projection:rE,addressU:tr,addressV:tr,mipmaps:false}),a=r.width/512,n=new eF(0,0,512*a,256*a),o=SE(256)-SE(4);for(let t=0;t<o;++t)ST(e,r,{numSamples:1,rect:n,seamPixels:a}),n.x+=n.w,n.y+=n.w,n.z=Math.max(1,Math.floor(.5*n.z)),n.w=Math.max(1,Math.floor(.5*n.w));n.set(0,256*a,256*a,128*a);for(let i=1;i<7;++i)ST(e,r,{numSamples:t?.numReflectionSamples||1024,distribution:t?.distribution||"ggx",specularPower:Math.max(1,2048>>2*i),rect:n,seamPixels:a}),n.y+=n.w,n.z=Math.max(1,Math.floor(.5*n.z)),n.w=Math.max(1,Math.floor(.5*n.w));return n.set(128*a,384*a,64*a,32*a),ST(e,r,{numSamples:t?.numAmbientSamples||2048,distribution:"lambert",rect:n,seamPixels:a}),r}static generatePrefilteredAtlas(e,t){let i=e[0].device,s=e[0].format,r=e[0].type,a=t?.target||new ns(i,{name:"envPrefilteredAtlas",width:t?.size||512,height:t?.size||512,format:s,type:r,projection:rE,addressU:tr,addressV:tr,mipmaps:false}),n=a.width/512,o=new eF(0,0,512*n,256*n),l=SE(512);for(let t=0;t<l;++t)ST(e[0],a,{numSamples:1,rect:o,seamPixels:n}),o.x+=o.w,o.y+=o.w,o.z=Math.max(1,Math.floor(.5*o.z)),o.w=Math.max(1,Math.floor(.5*o.w));o.set(0,256*n,256*n,128*n);for(let t=1;t<e.length;++t)ST(e[t],a,{numSamples:1,rect:o,seamPixels:n}),o.y+=o.w,o.z=Math.max(1,Math.floor(.5*o.z)),o.w=Math.max(1,Math.floor(.5*o.w));return o.set(128*n,384*n,64*n,32*n),t?.legacyAmbient?ST(e[5],a,{numSamples:1,rect:o,seamPixels:n}):ST(e[0],a,{numSamples:t?.numSamples||2048,distribution:"lambert",rect:o,seamPixels:n}),a}}class SI{constructor(){this.type=um,this.color=new eb(0,0,0),this.density=0,this.start=1,this.end=1e3;}}class SD extends eo{static{this.EVENT_SETLAYERS="set:layers";}static{this.EVENT_SETSKYBOX="set:skybox";}static{this.EVENT_PRERENDER="prerender";}static{this.EVENT_POSTRENDER="postrender";}static{this.EVENT_PRERENDER_LAYER="prerender:layer";}static{this.EVENT_POSTRENDER_LAYER="postrender:layer";}static{this.EVENT_PRECULL="precull";}static{this.EVENT_POSTCULL="postcull";}constructor(e){super(),this.ambientBake=false,this.ambientBakeOcclusionBrightness=0,this.ambientBakeOcclusionContrast=0,this.ambientLight=new eb(0,0,0),this.ambientLuminance=0,this.exposure=1,this.lightmapSizeMultiplier=1,this.lightmapMaxResolution=2048,this.lightmapMode=pI,this.lightmapFilterEnabled=false,this.lightmapHDR=false,this.root=null,this.physicalUnits=false,this._envAtlas=null,this._skyboxCubeMap=null,this._fogParams=new SI,this.forcePassThroughSpecular=false,this.device=e,this._gravity=new eM(0,-9.8,0),this._layers=null,this._prefilteredCubemaps=[],this._internalEnvAtlas=null,this._skyboxIntensity=1,this._skyboxLuminance=0,this._skyboxMip=0,this._skyboxHighlightMultiplier=1,this._skyboxRotationShaderInclude=false,this._skyboxRotation=new eH,this._skyboxRotationMat3=new eO,this._skyboxRotationMat4=new eG,this._ambientBakeNumSamples=1,this._ambientBakeSpherePart=.4,this._lightmapFilterRange=10,this._lightmapFilterSmoothness=.2,this._clusteredLightingEnabled=true,this._lightingParams=new g3(this.device.supportsAreaLights,this.device.maxTextureSize,()=>{this.updateShaders=true;}),this._sky=new v4(this),this._stats={meshInstances:0,lights:0,dynamicLights:0,bakedLights:0,updateShadersTime:0},this.updateShaders=true,this._shaderVersion=0,this.immediate=new Se(this.device);}get defaultDrawLayer(){return this.layers.getLayerById(uP)}set ambientBakeNumSamples(e){this._ambientBakeNumSamples=eA.clamp(Math.floor(e),1,255);}get ambientBakeNumSamples(){return this._ambientBakeNumSamples}set ambientBakeSpherePart(e){this._ambientBakeSpherePart=eA.clamp(e,.001,1);}get ambientBakeSpherePart(){return this._ambientBakeSpherePart}set clusteredLightingEnabled(e){(!this.device.isWebGPU||e)&&(this._clusteredLightingEnabled||!e)&&(this._clusteredLightingEnabled=e);}get clusteredLightingEnabled(){return this._clusteredLightingEnabled}set envAtlas(e){e!==this._envAtlas&&(this._envAtlas=e,e&&(e.addressU=tr,e.addressV=tr,e.minFilter=tZ,e.magFilter=tZ,e.mipmaps=false),this._prefilteredCubemaps=[],this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._resetSkyMesh());}get envAtlas(){return this._envAtlas}set layers(e){let t=this._layers;this._layers=e,this.fire("set:layers",t,e);}get layers(){return this._layers}get sky(){return this._sky}get lighting(){return this._lightingParams}get fog(){return this._fogParams}set lightmapFilterRange(e){this._lightmapFilterRange=Math.max(e,.001);}get lightmapFilterRange(){return this._lightmapFilterRange}set lightmapFilterSmoothness(e){this._lightmapFilterSmoothness=Math.max(e,.001);}get lightmapFilterSmoothness(){return this._lightmapFilterSmoothness}set prefilteredCubemaps(e){e=e||[];let t=this._prefilteredCubemaps;(t.length!==e.length||t.some((t,i)=>t!==e[i]))&&(6===e.length&&e.every(e=>!!e)?(this._internalEnvAtlas=SL.generatePrefilteredAtlas(e,{target:this._internalEnvAtlas}),this._envAtlas=this._internalEnvAtlas):(this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._envAtlas=null),this._prefilteredCubemaps=e.slice(),this._resetSkyMesh());}get prefilteredCubemaps(){return this._prefilteredCubemaps}set skybox(e){e!==this._skyboxCubeMap&&(this._skyboxCubeMap=e,this._resetSkyMesh());}get skybox(){return this._skyboxCubeMap}set skyboxIntensity(e){e!==this._skyboxIntensity&&(this._skyboxIntensity=e,this._resetSkyMesh());}get skyboxIntensity(){return this._skyboxIntensity}set skyboxLuminance(e){e!==this._skyboxLuminance&&(this._skyboxLuminance=e,this._resetSkyMesh());}get skyboxLuminance(){return this._skyboxLuminance}set skyboxMip(e){e!==this._skyboxMip&&(this._skyboxMip=e,this._resetSkyMesh());}get skyboxMip(){return this._skyboxMip}set skyboxHighlightMultiplier(e){e!==this._skyboxHighlightMultiplier&&(this._skyboxHighlightMultiplier=e,this._resetSkyMesh());}get skyboxHighlightMultiplier(){return this._skyboxHighlightMultiplier}set skyboxRotation(e){if(!this._skyboxRotation.equals(e)){let t=e.equals(eH.IDENTITY);this._skyboxRotation.copy(e),t?this._skyboxRotationMat3.setIdentity():(this._skyboxRotationMat4.setTRS(eM.ZERO,e,eM.ONE),this._skyboxRotationMat3.invertMat4(this._skyboxRotationMat4)),this._skyboxRotationShaderInclude||t||(this._skyboxRotationShaderInclude=true,this._resetSkyMesh());}}get skyboxRotation(){return this._skyboxRotation}destroy(){this._resetSkyMesh(),this.root=null,this.off();}drawLine(e,t,i=eb.WHITE,s=true,r=this.defaultDrawLayer){this.immediate.getBatch(r,s).addLines([e,t],[i,i]);}drawLines(e,t,i=true,s=this.defaultDrawLayer){this.immediate.getBatch(s,i).addLines(e,t);}drawLineArrays(e,t,i=true,s=this.defaultDrawLayer){this.immediate.getBatch(s,i).addLinesArrays(e,t);}applySettings(e){let t=e.physics,i=e.render;this._gravity.set(t.gravity[0],t.gravity[1],t.gravity[2]),this.ambientLight.set(i.global_ambient[0],i.global_ambient[1],i.global_ambient[2]),this.ambientLuminance=i.ambientLuminance,this.fog.type=i.fog,this.fog.color.set(i.fog_color[0],i.fog_color[1],i.fog_color[2]),this.fog.start=i.fog_start,this.fog.end=i.fog_end,this.fog.density=i.fog_density,this.lightmapSizeMultiplier=i.lightmapSizeMultiplier,this.lightmapMaxResolution=i.lightmapMaxResolution,this.lightmapMode=i.lightmapMode,this.exposure=i.exposure,this._skyboxIntensity=i.skyboxIntensity??1,this._skyboxLuminance=i.skyboxLuminance??2e4,this._skyboxMip=i.skyboxMip??0,i.skyboxRotation&&(this.skyboxRotation=new eH().setFromEulerAngles(i.skyboxRotation[0],i.skyboxRotation[1],i.skyboxRotation[2])),this.sky.applySettings(i),this.clusteredLightingEnabled=i.clusteredLightingEnabled??false,this.lighting.applySettings(i),["lightmapFilterEnabled","lightmapFilterRange","lightmapFilterSmoothness","ambientBake","ambientBakeNumSamples","ambientBakeSpherePart","ambientBakeOcclusionBrightness","ambientBakeOcclusionContrast"].forEach(e=>{i.hasOwnProperty(e)&&(this[e]=i[e]);}),this._resetSkyMesh();}_getSkyboxTex(){let e=this._prefilteredCubemaps;return this._skyboxMip?e[[0,1,3,4,5,6][this._skyboxMip]]||this._envAtlas||e[0]||this._skyboxCubeMap:this._skyboxCubeMap||e[0]||this._envAtlas}_updateSkyMesh(){this.sky.skyMesh||this.sky.updateSkyMesh(),this.sky.update();}_resetSkyMesh(){this.sky.resetSkyMesh(),this.updateShaders=true;}setSkybox(e){e?(this.skybox=e[0]||null,e[1]&&!e[1].cubemap?this.envAtlas=e[1]:this.prefilteredCubemaps=e.slice(1)):(this.skybox=null,this.envAtlas=null);}get lightmapPixelFormat(){return this.lightmapHDR&&this.device.getRenderableHdrFormat()||id}}class SR{constructor(e,t,i){this.device=e,this.inverseBindPose=t,this.boneNames=i;}}let SM=[0,0,1,0,0,1,0,0,1,0,0,1],SO=[0,1,3,2,3,1];class SN extends eo{constructor(e,t){super(),this._device=e,this._pixelsPerUnit=t&&void 0!==t.pixelsPerUnit?t.pixelsPerUnit:1,this._renderMode=t&&void 0!==t.renderMode?t.renderMode:pb,this._atlas=t&&void 0!==t.atlas?t.atlas:null,this._frameKeys=t&&void 0!==t.frameKeys?t.frameKeys:null,this._meshes=[],this._updatingProperties=false,this._meshesDirty=false,this._atlas&&this._frameKeys&&this._createMeshes();}set frameKeys(e){this._frameKeys=e,this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=true:this._createMeshes()),this.fire("set:frameKeys",e);}get frameKeys(){return this._frameKeys}set atlas(e){e!==this._atlas&&(this._atlas&&(this._atlas.off("set:frames",this._onSetFrames,this),this._atlas.off("set:frame",this._onFrameChanged,this),this._atlas.off("remove:frame",this._onFrameRemoved,this)),this._atlas=e,this._atlas&&this._frameKeys&&(this._atlas.on("set:frames",this._onSetFrames,this),this._atlas.on("set:frame",this._onFrameChanged,this),this._atlas.on("remove:frame",this._onFrameRemoved,this),this._updatingProperties?this._meshesDirty=true:this._createMeshes()),this.fire("set:atlas",e));}get atlas(){return this._atlas}set pixelsPerUnit(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,this.fire("set:pixelsPerUnit",e),this._atlas&&this._frameKeys&&this.renderMode===pb&&(this._updatingProperties?this._meshesDirty=true:this._createMeshes()));}get pixelsPerUnit(){return this._pixelsPerUnit}set renderMode(e){if(this._renderMode===e)return;let t=this._renderMode;this._renderMode=e,this.fire("set:renderMode",e),(t===pb||e===pb)&&this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=true:this._createMeshes());}get renderMode(){return this._renderMode}get meshes(){return this._meshes}_createMeshes(){let e=this._meshes.length;for(let t=0;t<e;t++){let e=this._meshes[t];e&&e.destroy();}let t=this._frameKeys.length;this._meshes=Array(t);let i=this.renderMode===pw||this._renderMode===pC?this._create9SliceMesh:this._createSimpleMesh;for(let e=0;e<t;e++){let t=this._atlas.frames[this._frameKeys[e]];this._meshes[e]=t?i.call(this,t):null;}this.fire("set:meshes");}_createSimpleMesh(e){let t=e.rect,i=this._atlas.texture.width,s=this._atlas.texture.height,r=t.z/this._pixelsPerUnit,a=t.w/this._pixelsPerUnit,n=e.pivot.x,o=e.pivot.y,l=t.x/i,h=1-t.y/s,c=(t.x+t.z)/i,d=1-(t.y+t.w)/s,u=new vQ;return u.positions=[-n*r,-o*a,0,(1-n)*r,-o*a,0,(1-n)*r,(1-o)*a,0,-n*r,(1-o)*a,0],u.normals=SM,u.uvs=[l,h,c,h,c,d,l,d],u.indices=SO,mw.fromGeometry(this._device,u)}_create9SliceMesh(){let e=eN.ONE,t=[],i=[],s=[],r=[],a=0;for(let n=0;n<=3;n++){let o=+(0!==n&&3!==n);for(let l=0;l<=3;l++){let h=-e.x+2*e.x*(n<=1?0:3)/3,c=-(-e.y+2*e.y*(l<=1?0:3)/3),d=+(0!==l&&3!==l);t.push(-h,0,c),i.push(0,1,0),s.push(o,d),n<3&&l<3&&(r.push(a+3+1,a+1,a),r.push(a+3+1,a+3+2,a+1)),a++;}}let n=new vQ;return n.positions=t,n.normals=i,n.uvs=s,n.indices=r,mw.fromGeometry(this._device,n)}_onSetFrames(e){this._updatingProperties?this._meshesDirty=true:this._createMeshes();}_onFrameChanged(e,t){let i=this._frameKeys.indexOf(e);i<0||(t?this.renderMode===pb&&(this._meshes[i]=this._createSimpleMesh(t)):this._meshes[i]=null,this.fire("set:meshes"));}_onFrameRemoved(e){let t=this._frameKeys.indexOf(e);t<0||(this._meshes[t]=null,this.fire("set:meshes"));}startUpdate(){this._updatingProperties=true,this._meshesDirty=false;}endUpdate(){this._updatingProperties=false,this._meshesDirty&&this._atlas&&this._frameKeys&&this._createMeshes(),this._meshesDirty=false;}destroy(){for(let e of this._meshes)e&&e.destroy();this._meshes.length=0;}}class SF extends eo{constructor(){super(),this._texture=null,this._frames=null;}set texture(e){this._texture=e,this.fire("set:texture",e);}get texture(){return this._texture}set frames(e){this._frames=e,this.fire("set:frames",e);}get frames(){return this._frames}setFrame(e,t){let i=this._frames[e];i?(i.rect.copy(t.rect),i.pivot.copy(t.pivot),i.border.copy(t.border)):(i={rect:t.rect.clone(),pivot:t.pivot.clone(),border:t.border.clone()},this._frames[e]=i),this.fire("set:frame",e.toString(),i);}removeFrame(e){let t=this._frames[e];t&&(delete this._frames[e],this.fire("remove:frame",e.toString(),t));}destroy(){this._texture&&this._texture.destroy();}}class SB{constructor(e,t,i,s){this.time=e,this.position=t,this.rotation=i,this.scale=s;}}class SU{constructor(){this._name="",this._keys=[];}}class Sk{constructor(){this.name="",this.duration=0,this._nodes=[],this._nodeDict={};}getNode(e){return this._nodeDict[e]}addNode(e){this._nodes.push(e),this._nodeDict[e._name]=e;}get nodes(){return this._nodes}}class SV{constructor(){this._written=false,this._name="",this._keyFrames=[],this._quat=new eH,this._pos=new eM,this._scale=new eM,this._targetNode=null;}getTarget(){return this._targetNode}setTarget(e){this._targetNode=e;}}class Sz{constructor(e){this.looping=true,this._animation=null,this._time=0,this._interpolatedKeys=[],this._interpolatedKeyDict={},this._currKeyIndices={},this.graph=null;let t=e=>{let i=new SV;i._name=e.name,this._interpolatedKeys.push(i),this._interpolatedKeyDict[e.name]=i,this._currKeyIndices[e.name]=0;for(let i=0;i<e._children.length;i++)t(e._children[i]);};t(e);}set animation(e){this._animation=e,this.currentTime=0;}get animation(){return this._animation}set currentTime(e){this._time=e;let t=this._interpolatedKeys.length;for(let e=0;e<t;e++){let t=this._interpolatedKeys[e]._name;this._currKeyIndices[t]=0;}this.addTime(0),this.updateGraph();}get currentTime(){return this._time}get numNodes(){return this._interpolatedKeys.length}addTime(e){if(null!==this._animation){let t=this._animation._nodes,i=this._animation.duration;if(this._time===i&&!this.looping)return;if(this._time+=e,this._time>i){this._time=this.looping?0:i;for(let e=0;e<t.length;e++){let i=t[e]._name;this._currKeyIndices[i]=0;}}else if(this._time<0){this._time=this.looping?i:0;for(let e=0;e<t.length;e++){let i=t[e],s=i._name;this._currKeyIndices[s]=i._keys.length-2;}}let s=e>=0?1:-1;for(let e=0;e<t.length;e++){let i=t[e],r=i._name,a=i._keys,n=this._interpolatedKeyDict[r];if(void 0===n)continue;let o=false;if(1!==a.length)for(let e=this._currKeyIndices[r];e<a.length-1&&e>=0;e+=s){let t=a[e],i=a[e+1];if(t.time<=this._time&&i.time>=this._time){let s=(this._time-t.time)/(i.time-t.time);n._pos.lerp(t.position,i.position,s),n._quat.slerp(t.rotation,i.rotation,s),n._scale.lerp(t.scale,i.scale,s),n._written=true,this._currKeyIndices[r]=e,o=true;break}}(1===a.length||!o&&0===this._time&&this.looping)&&(n._pos.copy(a[0].position),n._quat.copy(a[0].rotation),n._scale.copy(a[0].scale),n._written=true);}}}blend(e,t,i){let s=this._interpolatedKeys.length;for(let r=0;r<s;r++){let s=e._interpolatedKeys[r],a=t._interpolatedKeys[r],n=this._interpolatedKeys[r];s._written&&a._written?(n._quat.slerp(s._quat,t._interpolatedKeys[r]._quat,i),n._pos.lerp(s._pos,t._interpolatedKeys[r]._pos,i),n._scale.lerp(s._scale,a._scale,i),n._written=true):s._written?(n._quat.copy(s._quat),n._pos.copy(s._pos),n._scale.copy(s._scale),n._written=true):a._written&&(n._quat.copy(a._quat),n._pos.copy(a._pos),n._scale.copy(a._scale),n._written=true);}}setGraph(e){if(this.graph=e,e)for(let t=0;t<this._interpolatedKeys.length;t++){let i=this._interpolatedKeys[t],s=e.findByName(i._name);this._interpolatedKeys[t].setTarget(s);}else for(let e=0;e<this._interpolatedKeys.length;e++)this._interpolatedKeys[e].setTarget(null);}updateGraph(){if(this.graph)for(let e=0;e<this._interpolatedKeys.length;e++){let t=this._interpolatedKeys[e];if(t._written){let e=t.getTarget();e.localPosition.copy(t._pos),e.localRotation.copy(t._quat),e.localScale.copy(t._scale),e._dirtyLocal||e._dirtifyLocal(),t._written=false;}}}}let SG=new eF;class SH{constructor(e){this.device=e,this.needsDepthBuffer=false;}static{this.quadVertexShader=`
attribute vec2 aPosition;
varying vec2 vUv0;
void main(void)
{
gl_Position = vec4(aPosition, 0.0, 1.0);
vUv0 = getImageEffectUV((aPosition.xy + 1.0) * 0.5);
}
`;}render(e,t,i){}drawQuad(e,t,i){let s;if(i){let t=e?e.width:this.device.width,r=e?e.height:this.device.height;s=SG.set(i.x*t,i.y*r,i.z*t,i.w*r);}this.device.setBlendState(nu.NOBLEND),mg(this.device,e,t,s);}}class SW extends l2{set shader(e){this.quadRender?.destroy(),this.quadRender=null,this._shader=e,e&&(this.quadRender=new mp(e));}get shader(){return this._shader}execute(){let e=this.device;e.setBlendState(this.blendState),e.setCullMode(this.cullMode),e.setDepthState(this.depthState),e.setStencilState(this.stencilFront,this.stencilBack),this.quadRender.render();}constructor(...e){super(...e),this._shader=null,this.quadRender=null,this.cullMode=tY,this.blendState=nu.NOBLEND,this.depthState=nm.NODEPTH,this.stencilFront=null,this.stencilBack=null;}}class SX{constructor(){this.hasTangents=false,this.shaderChunks=null,this.pass=0,this.alphaTest=false,this.blendType=un,this.separateAmbient=false,this.screenSpace=false,this.skin=false,this.batch=false,this.useInstancing=false,this.useMorphPosition=false,this.useMorphNormal=false,this.useMorphTextureBasedInt=false,this.nineSlicedMode=0,this.clusteredLightingEnabled=true,this.clusteredLightingCookiesEnabled=false,this.clusteredLightingShadowsEnabled=false,this.clusteredLightingShadowType=0,this.clusteredLightingAreaLightsEnabled=false,this.vertexColors=false,this.lightMapEnabled=false,this.dirLightMapEnabled=false,this.useHeights=false,this.useNormals=false,this.useClearCoatNormals=false,this.useAo=false,this.diffuseMapEnabled=false,this.pixelSnap=false,this.ambientSH=false,this.ssao=false,this.twoSidedLighting=false,this.occludeDirect=false,this.occludeSpecular=0,this.occludeSpecularFloat=false,this.useMsdf=false,this.msdfTextAttribute=false,this.alphaToCoverage=false,this.opacityFadesSpecular=false,this.opacityDither=pq,this.opacityShadowDither=pq,this.cubeMapProjection=0,this.useSpecular=false,this.useSpecularityFactor=false,this.enableGGXSpecular=false,this.fresnelModel=0,this.useRefraction=false,this.useClearCoat=false,this.useSheen=false,this.useIridescence=false,this.useMetalness=false,this.useDynamicRefraction=false,this.dispersion=false,this.fog=um,this.gamma=fP,this.toneMap=-1,this.reflectionSource=fH,this.reflectionEncoding=null,this.reflectionCubemapEncoding=null,this.ambientSource="constant",this.ambientEncoding=null,this.skyboxIntensity=1,this.useCubeMapRotation=false,this.lightMapWithoutAmbient=false,this.lights=[],this.noShadow=false,this.lightMaskDynamic=0,this.userAttributes={},this.linearDepth=false,this.shadowCatcher=false;}}class SY{static update(e,t,i,s,r,a,n){SY.updateSharedOptions(e,t,i,r,a),SY.updateMaterialOptions(e,t),SY.updateEnvOptions(e,t,i,s),SY.updateLightingOptions(e,t,i,r,n);}static updateSharedOptions(e,t,i,s,r){e.shaderChunks=t.shaderChunks,e.pass=r,e.alphaTest=t.alphaTest>0,e.blendType=t.blendType,e.screenSpace=s&&(s&f6)!=0,e.skin=s&&(s&f0)!=0,e.useInstancing=s&&(s&f4)!=0,e.useMorphPosition=s&&(s&f7)!=0,e.useMorphNormal=s&&(s&pe)!=0,e.useMorphTextureBasedInt=s&&(s&pi)!=0,e.hasTangents=s&&(s&f9)!=0,e.nineSlicedMode=t.nineSlicedMode||pb,t.useLighting&&i.clusteredLightingEnabled?(e.clusteredLightingEnabled=true,e.clusteredLightingCookiesEnabled=i.lighting.cookiesEnabled,e.clusteredLightingShadowsEnabled=i.lighting.shadowsEnabled,e.clusteredLightingShadowType=i.lighting.shadowType,e.clusteredLightingAreaLightsEnabled=i.lighting.areaLightsEnabled):(e.clusteredLightingEnabled=false,e.clusteredLightingCookiesEnabled=false,e.clusteredLightingShadowsEnabled=false,e.clusteredLightingAreaLightsEnabled=false);}static updateMaterialOptions(e,t){e.separateAmbient=false,e.pixelSnap=t.pixelSnap,e.ambientSH=t.ambientSH,e.twoSidedLighting=t.twoSidedLighting,e.occludeDirect=t.occludeDirect,e.occludeSpecular=t.occludeSpecular,e.occludeSpecularFloat=1!==t.occludeSpecularIntensity,e.useMsdf=false,e.msdfTextAttribute=false,e.alphaToCoverage=t.alphaToCoverage,e.opacityFadesSpecular=t.opacityFadesSpecular,e.opacityDither=t.opacityDither,e.cubeMapProjection=fS,e.useSpecular=t.hasSpecular,e.useSpecularityFactor=t.hasSpecularityFactor,e.enableGGXSpecular=t.ggxSpecular,e.fresnelModel=t.fresnelModel,e.useRefraction=t.hasRefraction,e.useClearCoat=t.hasClearCoat,e.useSheen=t.hasSheen,e.useIridescence=t.hasIrridescence,e.useMetalness=t.hasMetalness,e.useDynamicRefraction=t.dynamicRefraction,e.dispersion=t.dispersion>0,e.vertexColors=false,e.lightMapEnabled=t.hasLighting,e.dirLightMapEnabled=t.dirLightMap,e.useHeights=t.hasHeights,e.useNormals=t.hasNormals,e.useClearCoatNormals=t.hasClearCoatNormals,e.useAo=t.hasAo,e.diffuseMapEnabled=t.hasDiffuseMap;}static updateEnvOptions(e,t,i,s){e.fog=t.useFog?s.fog:um,e.gamma=s.shaderOutputGamma,e.toneMap=t.useTonemap?s.toneMapping:fB,t.useSkybox&&i.envAtlas&&i.skybox?(e.reflectionSource=fX,e.reflectionEncoding=i.envAtlas.encoding,e.reflectionCubemapEncoding=i.skybox.encoding):t.useSkybox&&i.envAtlas?(e.reflectionSource=fW,e.reflectionEncoding=i.envAtlas.encoding):t.useSkybox&&i.skybox?(e.reflectionSource=fY,e.reflectionEncoding=i.skybox.encoding):(e.reflectionSource=fH,e.reflectionEncoding=null),t.ambientSH?(e.ambientSource=fj,e.ambientEncoding=null):e.reflectionSource!==fH&&i.envAtlas?(e.ambientSource=fK,e.ambientEncoding=i.envAtlas.encoding):(e.ambientSource=fZ,e.ambientEncoding=null);let r=e.reflectionSource!==fH;e.skyboxIntensity=r,e.useCubeMapRotation=r&&i._skyboxRotationShaderInclude;}static updateLightingOptions(e,t,i,s,r){if(e.lightMapWithoutAmbient=false,t.useLighting){let t=[],a=s?s>>16:po;e.lightMaskDynamic=!!(a&po),e.lightMapWithoutAmbient=false,r&&(SY.collectLights(uI,r[uI],t,a),i.clusteredLightingEnabled||(SY.collectLights(uD,r[uD],t,a),SY.collectLights(uM,r[uM],t,a))),e.lights=t;}else e.lights=[];(0!==e.lights.length||i.clusteredLightingEnabled)&&(s&fJ)==0||(e.noShadow=true);}static collectLights(e,t,i,s){for(let e=0;e<t.length;e++){let r=t[e];r.enabled&&r.mask&s&&i.push(r);}}}let Sq={vertex_normal:sE,vertex_tangent:sA,vertex_texCoord0:sL,vertex_texCoord1:sI,vertex_color:sC,vertex_boneWeights:sb,vertex_boneIndices:sw};class S${constructor(e,t,i=true){this.varyingsCode="",this.vDefines=new Map,this.fDefines=new Map,this.includes=new Map,this.chunks=null,this.device=e,this.options=t;let s=t.shaderChunks;if(this.shaderLanguage=e.isWebGPU&&i&&s?.useWGSL?rw:rb,this.attributes={vertex_position:sT},t.userAttributes)for(let[e,i]of Object.entries(t.userAttributes))this.attributes[i]=e;let r=mr.get(e,this.shaderLanguage);this.chunks=new Map(r),s&&(this.shaderLanguage===rb?s.glsl:s.wgsl).forEach((e,t)=>{for(let t in Sq)Sq.hasOwnProperty(t)&&e.indexOf(t)>=0&&(this.attributes[t]=Sq[t]);this.chunks.set(t,e);}),this.shaderPassInfo=mt.get(this.device).getByIndex(t.pass),this.shadowPass=this.shaderPassInfo.isShadow,this.lighting=t.lights.length>0||t.dirLightMapEnabled||t.clusteredLightingEnabled,this.reflections=t.reflectionSource!==fH,this.needsNormal=this.lighting||this.reflections||t.useSpecular||t.ambientSH||t.useHeights||t.enableGGXSpecular||t.clusteredLightingEnabled&&!this.shadowPass||t.useClearCoatNormals,this.needsNormal=this.needsNormal&&!this.shadowPass,this.needsSceneColor=t.useDynamicRefraction,this.needsScreenSize=t.useDynamicRefraction,this.needsTransforms=t.useDynamicRefraction,this.vshader=null,this.fshader=null;}fDefineSet(e,t,i=""){e&&this.fDefines.set(t,i);}generateVertexShader(e,t,i){let{options:s,vDefines:r,attributes:a}=this,n=new Map;if(n.set("vPositionW","vec3"),(s.nineSlicedMode===pw||s.nineSlicedMode===pC)&&r.set("NINESLICED",true),this.options.linearDepth&&(r.set("LINEAR_DEPTH",true),n.set("vLinearDepth","float")),this.needsNormal&&r.set("NORMALS",true),this.options.useInstancing){let e=mr.get(this.device,this.shaderLanguage);this.chunks.get("transformInstancingVS")===e.get("transformInstancingVS")&&(a.instance_line1=s$,a.instance_line2=sj,a.instance_line3=sZ,a.instance_line4=sQ);}this.needsNormal&&(a.vertex_normal=sE,n.set("vNormalW","vec3"),s.hasTangents&&(s.useHeights||s.useNormals||s.useClearCoatNormals||s.enableGGXSpecular)?(r.set("TANGENTS",true),a.vertex_tangent=sA,n.set("vTangentW","vec3"),n.set("vBinormalW","vec3")):s.enableGGXSpecular&&(r.set("GGX_SPECULAR",true),n.set("vObjectSpaceUpW","vec3")));for(let i=0;i<2;i++)e[i]&&(r.set(`UV${i}`,true),a[`vertex_texCoord${i}`]=`TEXCOORD${i}`),t[i]&&(r.set(`UV${i}_UNMODIFIED`,true),n.set(`vUv${i}`,"vec2"));let o=0,l=new Set;i.forEach(e=>{let{id:t,uv:i,name:s}=e,a=t+100*i;if(!l.has(a)){l.add(a),n.set(`vUV${i}_${t}`,"vec2");let e=`texture_${s}MapTransform`;r.set(`{TRANSFORM_NAME_${o}}`,e),r.set(`{TRANSFORM_UV_${o}}`,i),r.set(`{TRANSFORM_ID_${o}}`,t),o++;}}),r.set("UV_TRANSFORMS_COUNT",o),s.vertexColors&&(a.vertex_color=sC,r.set("VERTEX_COLOR",true),n.set("vVertexColor","vec4")),s.useMsdf&&s.msdfTextAttribute&&(a.vertex_outlineParameters=sX,a.vertex_shadowParameters=sY,r.set("MSDF",true)),(s.useMorphPosition||s.useMorphNormal)&&(r.set("MORPHING",true),s.useMorphTextureBasedInt&&r.set("MORPHING_INT",true),s.useMorphPosition&&r.set("MORPHING_POSITION",true),s.useMorphNormal&&r.set("MORPHING_NORMAL",true),a.morph_vertex_id=sQ),s.skin&&(a.vertex_boneIndices=sw,s.batch?r.set("BATCH",true):(a.vertex_boneWeights=sb,r.set("SKIN",true))),s.useInstancing&&r.set("INSTANCING",true),s.screenSpace&&r.set("SCREENSPACE",true),s.pixelSnap&&r.set("PIXELSNAP",true),n.forEach((e,t)=>{this.varyingsCode+=`#define VARYING_${t.toUpperCase()}
`,this.varyingsCode+=this.shaderLanguage===rw?`varying ${t}: ${a1.get(e)};
`:`varying ${e} ${t};
`;}),this.includes.set("varyingsVS",this.varyingsCode),this.includes.set("varyingsPS",this.varyingsCode),this.vshader=`
#include "litMainVS"
`;}_setupLightingDefines(e,t){let i=this.fDefines,s=this.options;if(this.fDefines.set("LIGHT_COUNT",s.lights.length),e&&i.set("AREA_LIGHTS",true),t&&this.lighting&&(i.set("LIT_CLUSTERED_LIGHTS",true),s.clusteredLightingCookiesEnabled&&i.set("CLUSTER_COOKIES",true),s.clusteredLightingAreaLightsEnabled&&i.set("CLUSTER_AREALIGHTS",true),s.lightMaskDynamic&&i.set("CLUSTER_MESH_DYNAMIC_LIGHTS",true),s.clusteredLightingShadowsEnabled&&!s.noShadow)){let e=u5.get(s.clusteredLightingShadowType);i.set("CLUSTER_SHADOWS",true),i.set(`SHADOW_KIND_${e.kind}`,true),i.set(`CLUSTER_SHADOW_TYPE_${e.kind}`,true);}for(let r=0;r<s.lights.length;r++){let a=s.lights[r],n=a._type;if(t&&n!==uI)continue;let o=e&&a._shape?a._shape:uB,l=a._shadowType,h=a.castShadows&&!s.noShadow,c=u5.get(l);i.set(`LIGHT${r}`,true),i.set(`LIGHT${r}TYPE`,`${uN[n]}`),i.set(`LIGHT${r}SHADOWTYPE`,`${c.name}`),i.set(`LIGHT${r}SHAPE`,`${uz[o]}`),i.set(`LIGHT${r}FALLOFF`,`${uW[a._falloffMode]}`),a.affectSpecularity&&i.set(`LIGHT${r}AFFECT_SPECULARITY`,true),a._cookie&&(n===uM&&!a._cookie._cubemap||n===uD&&a._cookie._cubemap)&&(i.set(`LIGHT${r}COOKIE`,true),i.set(`{LIGHT${r}COOKIE_CHANNEL}`,a._cookieChannel),n===uM&&(a._cookieTransform&&i.set(`LIGHT${r}COOKIE_TRANSFORM`,true),a._cookieFalloff&&i.set(`LIGHT${r}COOKIE_FALLOFF`,true))),h&&(i.set(`LIGHT${r}CASTSHADOW`,true),c.pcf&&i.set(`LIGHT${r}SHADOW_PCF`,true),a._normalOffsetBias&&!a._isVsm&&i.set(`LIGHT${r}_SHADOW_SAMPLE_NORMAL_OFFSET`,true),n===uI&&(i.set(`LIGHT${r}_SHADOW_SAMPLE_ORTHO`,true),a.cascadeBlend>0&&i.set(`LIGHT${r}_SHADOW_CASCADE_BLEND`,true),a.numCascades>1&&i.set(`LIGHT${r}_SHADOW_CASCADES`,true)),(c.pcf||c.pcss||this.device.isWebGPU)&&i.set(`LIGHT${r}_SHADOW_SAMPLE_SOURCE_ZBUFFER`,true),n===uD&&i.set(`LIGHT${r}_SHADOW_SAMPLE_POINT`,true)),h&&(i.set(`SHADOW_KIND_${c.kind}`,true),n===uI&&i.set("SHADOW_DIRECTIONAL",true));}}prepareForwardPass(e){let{options:t}=this,i=t.clusteredLightingEnabled&&t.clusteredLightingAreaLightsEnabled||t.lights.some(e=>e._shape&&e._shape!==uB),s=!t.lightMapEnabled||t.lightMapWithoutAmbient,r=this.needsNormal&&(t.useNormals||t.useClearCoatNormals||t.enableGGXSpecular&&!t.useHeights);t.useSpecular&&(this.fDefineSet(true,"LIT_SPECULAR"),this.fDefineSet(this.reflections,"LIT_REFLECTIONS"),this.fDefineSet(t.useClearCoat,"LIT_CLEARCOAT"),this.fDefineSet(t.fresnelModel>0,"LIT_SPECULAR_FRESNEL"),this.fDefineSet(t.useSheen,"LIT_SHEEN"),this.fDefineSet(t.useIridescence,"LIT_IRIDESCENCE")),this.fDefineSet(this.lighting&&t.useSpecular||this.reflections,"LIT_SPECULAR_OR_REFLECTION"),this.fDefineSet(this.needsSceneColor,"LIT_SCENE_COLOR"),this.fDefineSet(this.needsScreenSize,"LIT_SCREEN_SIZE"),this.fDefineSet(this.needsTransforms,"LIT_TRANSFORMS"),this.fDefineSet(this.needsNormal,"LIT_NEEDS_NORMAL"),this.fDefineSet(this.lighting,"LIT_LIGHTING"),this.fDefineSet(t.useMetalness,"LIT_METALNESS"),this.fDefineSet(t.enableGGXSpecular,"LIT_GGX_SPECULAR"),this.fDefineSet(t.useSpecularityFactor,"LIT_SPECULARITY_FACTOR"),this.fDefineSet(t.useCubeMapRotation,"CUBEMAP_ROTATION"),this.fDefineSet(t.occludeSpecularFloat,"LIT_OCCLUDE_SPECULAR_FLOAT"),this.fDefineSet(t.separateAmbient,"LIT_SEPARATE_AMBIENT"),this.fDefineSet(t.twoSidedLighting,"LIT_TWO_SIDED_LIGHTING"),this.fDefineSet(t.lightMapEnabled,"LIT_LIGHTMAP"),this.fDefineSet(t.dirLightMapEnabled,"LIT_DIR_LIGHTMAP"),this.fDefineSet(t.skyboxIntensity>0,"LIT_SKYBOX_INTENSITY"),this.fDefineSet(t.clusteredLightingShadowsEnabled,"LIT_CLUSTERED_SHADOWS"),this.fDefineSet(t.clusteredLightingAreaLightsEnabled,"LIT_CLUSTERED_AREA_LIGHTS"),this.fDefineSet(r,"LIT_TBN"),this.fDefineSet(s,"LIT_ADD_AMBIENT"),this.fDefineSet(t.hasTangents,"LIT_TANGENTS"),this.fDefineSet(t.useNormals,"LIT_USE_NORMALS"),this.fDefineSet(t.useClearCoatNormals,"LIT_USE_CLEARCOAT_NORMALS"),this.fDefineSet(t.useRefraction,"LIT_REFRACTION"),this.fDefineSet(t.useDynamicRefraction,"LIT_DYNAMIC_REFRACTION"),this.fDefineSet(t.dispersion,"LIT_DISPERSION"),this.fDefineSet(t.useHeights,"LIT_HEIGHTS"),this.fDefineSet(t.opacityFadesSpecular,"LIT_OPACITY_FADES_SPECULAR"),this.fDefineSet(t.alphaToCoverage,"LIT_ALPHA_TO_COVERAGE"),this.fDefineSet(t.alphaTest,"LIT_ALPHA_TEST"),this.fDefineSet(t.useMsdf,"LIT_MSDF"),this.fDefineSet(t.ssao,"LIT_SSAO"),this.fDefineSet(t.useAo,"LIT_AO"),this.fDefineSet(t.occludeDirect,"LIT_OCCLUDE_DIRECT"),this.fDefineSet(t.msdfTextAttribute,"LIT_MSDF_TEXT_ATTRIBUTE"),this.fDefineSet(t.diffuseMapEnabled,"LIT_DIFFUSE_MAP"),this.fDefineSet(t.shadowCatcher,"LIT_SHADOW_CATCHER"),this.fDefineSet(true,"LIT_FRESNEL_MODEL",ux[t.fresnelModel]),this.fDefineSet(true,"LIT_NONE_SLICE_MODE",pP[t.nineSlicedMode]),this.fDefineSet(true,"LIT_BLEND_TYPE",up[t.blendType]),this.fDefineSet(true,"LIT_CUBEMAP_PROJECTION",fx[t.cubeMapProjection]),this.fDefineSet(true,"LIT_OCCLUDE_SPECULAR",fG[t.occludeSpecular]),this.fDefineSet(true,"LIT_REFLECTION_SOURCE",f$[t.reflectionSource]),this.fDefineSet(true,"LIT_AMBIENT_SOURCE",fQ[t.ambientSource]),this.fDefineSet(true,"{lightingUv}",e??""),this.fDefineSet(true,"{reflectionDecode}",vj.decodeFunc(t.reflectionEncoding)),this.fDefineSet(true,"{reflectionCubemapDecode}",vj.decodeFunc(t.reflectionCubemapEncoding)),this.fDefineSet(true,"{ambientDecode}",vj.decodeFunc(t.ambientEncoding)),this._setupLightingDefines(i,t.clusteredLightingEnabled);}prepareShadowPass(){let{options:e}=this,t=this.shaderPassInfo.lightType,i=this.shaderPassInfo.shadowType,s=u5.get(i),r=t===uI||!s.vsm&&t===uM;this.fDefineSet(r,"PERSPECTIVE_DEPTH"),this.fDefineSet(true,"LIGHT_TYPE",`${uN[t]}`),this.fDefineSet(true,"SHADOW_TYPE",`${s.name}`),this.fDefineSet(e.alphaTest,"LIT_ALPHA_TEST");}generateFragmentShader(e,t,i){let s=this.options;this.includes.set("frontendDeclPS",e??""),this.includes.set("frontendCodePS",t??""),s.pass===pf||s.pass===pd||(this.shadowPass?this.prepareShadowPass():this.prepareForwardPass(i)),this.fshader=`
#include "litMainPS"
`;}}let Sj={generateKey:e=>`lit${Object.keys(e).sort().map(t=>"shaderChunks"===t?e.shaderChunks?.key??"":"lights"===t?Sj.generateLightsKey(e):t+e[t]).join("\n")}`,generateLightsKey:e=>`lights:${e.lights.map(t=>e.clusteredLightingEnabled&&t._type!==uI?"":`${t.key},`).join("")}`},SK=[0,1,2,3,4,5,6,7],SZ=new class extends p9{generateKey(e){let t=p9.definesHash(e.defines),i=nE(e.shaderChunkGLSL??""),s=nE(e.shaderChunkWGSL??""),r=Sj.generateKey(e.litOptions),a=`${SK.map((t,i)=>e.usedUvs[i]?"1":"0").join("")}`;return `lit_${t}_${a}_${i}_${s}_${r}`}createShaderDefinition(e,t){let i=!!t.shaderChunkWGSL,s=new S$(e,t.litOptions,i),r={name:"LitShader",shaderLanguage:s.shaderLanguage,tag:s.shaderPassInfo.isForward?sJ:void 0},a=t.usedUvs||[true];s.generateVertexShader(a,a,[]),s.generateFragmentShader("",s.shaderLanguage===rw?t.shaderChunkWGSL:t.shaderChunkGLSL,"vUv0");let n=ma.merge(s.chunks,s.includes),o=s.vDefines;t.defines.forEach((e,t)=>o.set(t,e));let l=s.fDefines;return t.defines.forEach((e,t)=>l.set(t,e)),r.attributes=s.attributes,r.vertexCode=s.vshader,r.vertexIncludes=n,r.vertexDefines=o,r.fragmentCode=s.fshader,r.fragmentIncludes=n,r.fragmentDefines=l,ls.createDefinition(e,r)}},SQ=new class{constructor(){this.litOptions=new SX;}};class SJ extends _${getShaderVariant(e){SQ.usedUvs=this.usedUvs.slice(),SQ.shaderChunkGLSL=this.shaderChunkGLSL,SQ.shaderChunkWGSL=this.shaderChunkWGSL,SQ.defines=mo.getCoreDefines(this,e),SY.update(SQ.litOptions,this,e.scene,e.cameraShaderParams,e.objDefs,e.pass,e.sortedLights);let t=new p5(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),i=p6(e.device);return i.register("lit",SZ),i.getProgram("lit",SQ,t,this.userId)}constructor(...e){super(...e),this.usedUvs=[true],this.shaderChunkGLSL=null,this.shaderChunkWGSL=null,this.useLighting=true,this.useFog=true,this.useTonemap=true,this.useSkybox=true,this.ambientSH=null,this.pixelSnap=false,this.nineSlicedMode=null,this.twoSidedLighting=false,this.occludeDirect=false,this.occludeSpecular=fV,this.occludeSpecularIntensity=1,this.opacityFadesSpecular=true,this.opacityDither=pq,this.opacityShadowDither=pq,this.shadowCatcher=false,this.ggxSpecular=false,this.fresnelModel=uy,this.dynamicRefraction=false,this.hasAo=false,this.hasSpecular=false,this.hasSpecularityFactor=false,this.hasLighting=false,this.hasHeights=false,this.hasNormals=false,this.hasSheen=false,this.hasRefraction=false,this.hasIrridescence=false,this.hasMetalness=false,this.hasClearCoat=false,this.hasClearCoatNormals=false;}}class S0{get pass(){return this.litOptions.pass}constructor(){this.defines=new Map,this.forceUv1=false,this.specularTint=false,this.metalnessTint=false,this.glossTint=false,this.emissiveEncoding="linear",this.lightMapEncoding="linear",this.packedNormal=false,this.normalDetailPackedNormal=false,this.clearCoatPackedNormal=false,this.glossInvert=false,this.sheenGlossInvert=false,this.clearCoatGlossInvert=false,this.useAO=false,this.litOptions=new SX;}}let S1=[],S2=e=>Object.keys(e).filter(e=>"litOptions"!==e).sort(),S3=new class extends p9{generateKey(e){let t;e===this.optionsContextMin?(this.propsMin||(this.propsMin=S2(e)),t=this.propsMin):e===this.optionsContext?(this.props||(this.props=S2(e)),t=this.props):t=S2(e);let i=p9.definesHash(e.defines);return `standard:
${i}
${t.map(t=>t+e[t]).join("\n")}${Sj.generateKey(e.litOptions)}`}_getUvSourceExpression(e,t,i){let s,r=i[e],a=i[t],n=i.litOptions.pass===pc;return n&&i.litOptions.nineSlicedMode===pw||n&&i.litOptions.nineSlicedMode===pC?s="nineSlicedUv":(s=0===r?`vUv${a}`:`vUV${a}_${r}`,i.heightMap&&"heightMapTransform"!==e&&(s+=" + dUvOffset")),s}_validateMapChunk(e,t,i){}_addMapDefines(e,t,i,s,r,a,n=null){let o=`${t}Map`,l=t.toUpperCase(),h=`${o}Uv`,c=`${o}Identifier`,d=`${o}Transform`,u=`${o}Channel`,f=`${t}VertexColorChannel`,p=`${t}Tint`,m=`${t}VertexColor`,_=`${t}Mode`,g=`${t}Invert`,v=s[p],S=s[m],y=s[o],x=s[c],T=s[_],E=r.get(i);if(y){e.set(`STD_${l}_TEXTURE`,"");let t=this._getUvSourceExpression(d,h,s);e.set(`{STD_${l}_TEXTURE_UV}`,t),e.set(`{STD_${l}_TEXTURE_CHANNEL}`,s[u]);let i=`{STD_${l}_TEXTURE_NAME}`;if(E.includes(i)){let t=`texture_${o}`,s=a[x];s?t=s:(a[x]=t,e.set(`STD_${l}_TEXTURE_ALLOCATE`,"")),e.set(i,t);}if(n){let t="aaa"===s[u]?"passThrough":vj.decodeFunc(n);e.set(`{STD_${l}_TEXTURE_DECODE}`,t);}}S&&(e.set(`STD_${l}_VERTEX`,""),e.set(`{STD_${l}_VERTEX_CHANNEL}`,s[f])),T&&e.set(`{STD_${l}_DETAILMODE}`,T),v&&e.set(`STD_${l}_CONSTANT`,""),s[g]&&e.set(`STD_${l}_INVERT`,"");}_correctChannel(e,t,i){if(i[e]>0){if(i[e]<t.length)return t.substring(0,i[e]);if(i[e]>t.length){let s=t,r=s.charAt(s.length-1),a=i[e]-s.length;for(let e=0;e<a;e++)s+=r;return s}return t}}createVertexShader(e,t){let i=[],s=[],r=[];for(let e in S1){let a=`${e}Map`;if(t[`${e}VertexColor`]){let i=`${e}VertexColorChannel`;t[i]=this._correctChannel(e,t[i],S1);}if(t[a]){let n=`${a}Channel`,o=`${a}Transform`,l=`${a}Uv`;t[l]=Math.min(t[l],1),t[n]=this._correctChannel(e,t[n],S1);let h=t[l];i[h]=true,s[h]=s[h]||t[a]&&!t[o],t[o]&&r.push({name:e,id:t[o],uv:t[l]});}}t.forceUv1&&(i[1]=true,s[1]=void 0===s[1]||s[1]),e.generateVertexShader(i,s,r);}prepareFragmentDefines(e,t,i){let s=(e,i,s="")=>{e&&t.set(i,s);};s(e.lightMap,"STD_LIGHTMAP",""),s(e.lightVertexColor,"STD_LIGHT_VERTEX_COLOR",""),s(e.dirLightMap&&e.litOptions.useSpecular,"STD_LIGHTMAP_DIR",""),s(e.heightMap,"STD_HEIGHT_MAP",""),s(e.useSpecularColor,"STD_SPECULAR_COLOR",""),s(e.aoMap||e.aoVertexColor||e.useAO,"STD_AO",""),s(true,"STD_OPACITY_DITHER",pZ[i.isForward?e.litOptions.opacityDither:e.litOptions.opacityShadowDither]);}createShaderDefinition(e,t){let i=mt.get(e).getByIndex(t.litOptions.pass),s=i.isForward,r=new S$(e,t.litOptions);this.createVertexShader(r,t);let a={};t.litOptions.fresnelModel=0===t.litOptions.fresnelModel?uy:t.litOptions.fresnelModel;let n=r.fDefines;this.prepareFragmentDefines(t,n,i);let o="";if(s){if(t.heightMap&&this._addMapDefines(n,"height","parallaxPS",t,r.chunks,a),(t.litOptions.blendType!==un||t.litOptions.alphaTest||t.litOptions.alphaToCoverage||t.litOptions.opacityDither!==pq)&&this._addMapDefines(n,"opacity","opacityPS",t,r.chunks,a),r.needsNormal){if((t.normalMap||t.clearCoatNormalMap)&&!t.litOptions.hasTangents){let e=t.normalMap?"normalMap":"clearCoatNormalMap";o=this._getUvSourceExpression(`${e}Transform`,`${e}Uv`,t);}this._addMapDefines(n,"normalDetail","normalMapPS",t,r.chunks,a,t.normalDetailPackedNormal?"xy":"xyz"),this._addMapDefines(n,"normal","normalMapPS",t,r.chunks,a,t.packedNormal?"xy":"xyz");}t.diffuseDetail&&this._addMapDefines(n,"diffuseDetail","diffusePS",t,r.chunks,a,t.diffuseDetailEncoding),this._addMapDefines(n,"diffuse","diffusePS",t,r.chunks,a,t.diffuseEncoding),t.litOptions.useRefraction&&(this._addMapDefines(n,"refraction","transmissionPS",t,r.chunks,a),this._addMapDefines(n,"thickness","thicknessPS",t,r.chunks,a)),t.litOptions.useIridescence&&(this._addMapDefines(n,"iridescence","iridescencePS",t,r.chunks,a),this._addMapDefines(n,"iridescenceThickness","iridescenceThicknessPS",t,r.chunks,a)),(r.lighting&&t.litOptions.useSpecular||r.reflections)&&(t.litOptions.useSheen&&(this._addMapDefines(n,"sheen","sheenPS",t,r.chunks,a,t.sheenEncoding),this._addMapDefines(n,"sheenGloss","sheenGlossPS",t,r.chunks,a)),t.litOptions.useMetalness&&(this._addMapDefines(n,"metalness","metalnessPS",t,r.chunks,a),this._addMapDefines(n,"ior","iorPS",t,r.chunks,a)),t.litOptions.useSpecularityFactor&&this._addMapDefines(n,"specularityFactor","specularityFactorPS",t,r.chunks,a),t.useSpecularColor&&this._addMapDefines(n,"specular","specularPS",t,r.chunks,a,t.specularEncoding),this._addMapDefines(n,"gloss","glossPS",t,r.chunks,a)),t.aoDetail&&this._addMapDefines(n,"aoDetail","aoPS",t,r.chunks,a),(t.aoMap||t.aoVertexColor||t.useAO)&&this._addMapDefines(n,"ao","aoPS",t,r.chunks,a),this._addMapDefines(n,"emissive","emissivePS",t,r.chunks,a,t.emissiveEncoding),t.litOptions.useClearCoat&&(this._addMapDefines(n,"clearCoat","clearCoatPS",t,r.chunks,a),this._addMapDefines(n,"clearCoatGloss","clearCoatGlossPS",t,r.chunks,a),this._addMapDefines(n,"clearCoatNormal","clearCoatNormalPS",t,r.chunks,a,t.clearCoatPackedNormal?"xy":"xyz")),t.litOptions.enableGGXSpecular&&this._addMapDefines(n,"anisotropy","anisotropyPS",t,r.chunks,a),(t.lightMap||t.lightVertexColor)&&this._addMapDefines(n,"light","lightmapPS",t,r.chunks,a,t.lightMapEncoding);}else {let e=t.litOptions.opacityShadowDither;(t.litOptions.alphaTest||e)&&this._addMapDefines(n,"opacity","opacityPS",t,r.chunks,a);}r.generateFragmentShader(r.chunks.get("stdDeclarationPS"),r.chunks.get("stdFrontEndPS"),o);let l=ma.merge(r.chunks,r.includes),h=r.vDefines;t.defines.forEach((e,t)=>h.set(t,e)),t.defines.forEach((e,t)=>n.set(t,e));let c=ls.createDefinition(e,{name:"StandardShader",attributes:r.attributes,shaderLanguage:r.shaderLanguage,vertexCode:r.vshader,fragmentCode:r.fshader,vertexIncludes:l,fragmentIncludes:l,fragmentDefines:n,vertexDefines:h});return r.shaderPassInfo.isForward&&(c.tag=sJ),c}constructor(...e){super(...e),this.optionsContext=new S0,this.optionsContextMin=new S0;}},S4=(e,t)=>{if(e.length!==t.length)return false;for(let i=0;i<e.length;++i)if(e[i]!==t[i])return false;return true},S5=e=>1!==e.r||1!==e.g||1!==e.b,S8=e=>0!==e.r||0!==e.g||0!==e.b;class S6{constructor(){this._mapXForms=null;}updateMinRef(e,t,i,s,r,a){this._updateSharedOptions(e,t,i,s,r),this._updateMinOptions(e,i,r),this._updateUVOptions(e,i,s,true);}updateRef(e,t,i,s,r,a,n){this._updateSharedOptions(e,t,s,r,a),this._updateEnvOptions(e,s,t,i),this._updateMaterialOptions(e,s,t),e.litOptions.hasTangents=r&&(r&f9)!=0,this._updateLightOptions(e,t,s,r,n),this._updateUVOptions(e,s,r,false,i);}_updateSharedOptions(e,t,i,s,r){e.forceUv1=i.forceUv1,i.userAttributes&&(e.litOptions.userAttributes=Object.fromEntries(i.userAttributes.entries())),e.litOptions.shaderChunks=i.shaderChunks,e.litOptions.pass=r,e.litOptions.alphaTest=i.alphaTest>0,e.litOptions.blendType=i.blendType,e.litOptions.screenSpace=s&&(s&f6)!=0,e.litOptions.skin=s&&(s&f0)!=0,e.litOptions.batch=s&&(s&ps)!=0,e.litOptions.useInstancing=s&&(s&f4)!=0,e.litOptions.useMorphPosition=s&&(s&f7)!=0,e.litOptions.useMorphNormal=s&&(s&pe)!=0,e.litOptions.useMorphTextureBasedInt=s&&(s&pi)!=0,e.litOptions.nineSlicedMode=i.nineSlicedMode||0,t.clusteredLightingEnabled&&i.useLighting?(e.litOptions.clusteredLightingEnabled=true,e.litOptions.clusteredLightingCookiesEnabled=t.lighting.cookiesEnabled,e.litOptions.clusteredLightingShadowsEnabled=t.lighting.shadowsEnabled,e.litOptions.clusteredLightingShadowType=t.lighting.shadowType,e.litOptions.clusteredLightingAreaLightsEnabled=t.lighting.areaLightsEnabled):(e.litOptions.clusteredLightingEnabled=false,e.litOptions.clusteredLightingCookiesEnabled=false,e.litOptions.clusteredLightingShadowsEnabled=false,e.litOptions.clusteredLightingAreaLightsEnabled=false);}_updateUVOptions(e,t,i,s,r){let a=false,n=false,o=false;i&&(a=(i&f1)!=0,n=(i&f2)!=0,o=(i&f3)!=0),e.litOptions.vertexColors=false,this._mapXForms=[];let l={};for(let i in S1)this._updateTexOptions(e,t,i,a,n,o,s,l);this._mapXForms=null,e.litOptions.ssao=r?.ssaoEnabled,e.useAO=e.litOptions.ssao,e.litOptions.lightMapEnabled=e.lightMap,e.litOptions.dirLightMapEnabled=e.dirLightMap,e.litOptions.useHeights=e.heightMap,e.litOptions.useNormals=e.normalMap,e.litOptions.useClearCoatNormals=e.clearCoatNormalMap,e.litOptions.useAo=e.aoMap||e.aoVertexColor||e.litOptions.ssao,e.litOptions.diffuseMapEnabled=e.diffuseMap;}_updateTexOptions(e,t,i,s,r,a,n,o){let l="opacity"===i;if(!n||l){let n=`${i}Map`,h=`${i}VertexColor`,c=`${i}VertexColorChannel`,d=`${n}Channel`,u=`${n}Transform`,f=`${n}Uv`,p=`${n}Identifier`;if("light"!==i&&(e[n]=false,e[p]=void 0,e[d]="",e[u]=0,e[f]=0),e[h]=false,e[c]="",l&&t.blendType===un&&0===t.alphaTest&&!t.alphaToCoverage&&t.opacityDither===pq)return;if("height"!==i&&t[h]&&a&&(e[h]=t[h],e[c]=t[c],e.litOptions.vertexColors=true),t[n]){let a=true;if(0!==t[f]||s||(a=false),1!==t[f]||r||(a=false),a){let s=t[n].id,r=o[s];void 0===r&&(o[s]=i,r=i),e[n]=!!t[n],e[p]=r,e[u]=this._getMapTransformID(t.getUniform(u),t[f]),e[d]=t[d],e[f]=t[f];}}}}_updateMinOptions(e,t,i){let s=i===pd;e.litOptions.opacityShadowDither=s?t.opacityDither:t.opacityShadowDither,e.litOptions.linearDepth=s,e.litOptions.lights=[];}_updateMaterialOptions(e,t,i){let s=!!(t.useMetalness||t.specularMap||t.sphereMap||t.cubeMap||S8(t.specular)||t.specularityFactor>0&&t.useMetalness||t.enableGGXSpecular||t.clearCoat>0),r=!t.useMetalness||t.useMetalnessSpecularColor,a=s&&(t.specularTint||!t.specularMap&&!t.specularVertexColor)&&S5(t.specular),n=s&&t.useMetalnessSpecularColor&&(t.specularityFactorTint||t.specularityFactor<1&&!t.specularityFactorMap),o=e=>!!e&&(e.format===im||e.type===ra),l=(e,t)=>1e-4>Math.abs(e-t);e.specularTint=a,e.specularityFactorTint=n,e.metalnessTint=t.useMetalness&&t.metalness<1,e.glossTint=true,e.diffuseEncoding=t.diffuseMap?.encoding,e.diffuseDetailEncoding=t.diffuseDetailMap?.encoding,e.emissiveEncoding=t.emissiveMap?.encoding,e.lightMapEncoding=t.lightMap?.encoding,e.packedNormal=o(t.normalMap),e.refractionTint=l(t.refraction,1),e.refractionIndexTint=l(t.refractionIndex,1/1.5),e.thicknessTint=t.useDynamicRefraction&&1!==t.thickness,e.specularEncoding=t.specularMap?.encoding,e.sheenEncoding=t.sheenMap?.encoding,e.aoMapUv=t.aoUvSet,e.aoDetail=!!t.aoDetailMap,e.diffuseDetail=!!t.diffuseDetailMap,e.normalDetail=!!t.normalMap,e.normalDetailPackedNormal=o(t.normalDetailMap),e.diffuseDetailMode=t.diffuseDetailMode,e.aoDetailMode=t.aoDetailMode,e.clearCoatGloss=!!t.clearCoatGloss,e.clearCoatPackedNormal=o(t.clearCoatNormalMap),e.iorTint=l(t.refractionIndex,1/1.5),i.forcePassThroughSpecular&&(e.specularEncoding="linear",e.sheenEncoding="linear"),e.iridescenceTint=1!==t.iridescence,e.glossInvert=t.glossInvert,e.sheenGlossInvert=t.sheenGlossInvert,e.clearCoatGlossInvert=t.clearCoatGlossInvert,e.useSpecularColor=r,e.litOptions.separateAmbient=false,e.litOptions.pixelSnap=t.pixelSnap,e.litOptions.ambientSH=!!t.ambientSH,e.litOptions.twoSidedLighting=t.twoSidedLighting,e.litOptions.occludeSpecular=t.occludeSpecular,e.litOptions.occludeSpecularFloat=1!==t.occludeSpecularIntensity,e.litOptions.useMsdf=!!t.msdfMap,e.litOptions.msdfTextAttribute=!!t.msdfTextAttribute,e.litOptions.alphaToCoverage=t.alphaToCoverage,e.litOptions.opacityFadesSpecular=t.opacityFadesSpecular,e.litOptions.opacityDither=t.opacityDither,e.litOptions.cubeMapProjection=t.cubeMapProjection,e.litOptions.occludeDirect=t.occludeDirect,e.litOptions.useSpecular=s,e.litOptions.useSpecularityFactor=(n||!!t.specularityFactorMap)&&t.useMetalnessSpecularColor,e.litOptions.enableGGXSpecular=t.enableGGXSpecular,e.litOptions.fresnelModel=t.fresnelModel,e.litOptions.useRefraction=(t.refraction||!!t.refractionMap)&&(t.useDynamicRefraction||e.litOptions.reflectionSource!==fH),e.litOptions.useClearCoat=!!t.clearCoat,e.litOptions.useSheen=t.useSheen,e.litOptions.useIridescence=t.useIridescence&&0!==t.iridescence,e.litOptions.useMetalness=t.useMetalness,e.litOptions.useDynamicRefraction=t.useDynamicRefraction,e.litOptions.dispersion=t.dispersion>0,e.litOptions.shadowCatcher=t.shadowCatcher;}_updateEnvOptions(e,t,i,s){e.litOptions.fog=t.useFog?s.fog:um,e.litOptions.gamma=s.shaderOutputGamma,e.litOptions.toneMap=t.useTonemap?s.toneMapping:fB;let r=false;if(t.envAtlas&&t.cubeMap?(e.litOptions.reflectionSource=fX,e.litOptions.reflectionEncoding=t.envAtlas.encoding,e.litOptions.reflectionCubemapEncoding=t.cubeMap.encoding):t.envAtlas?(e.litOptions.reflectionSource=fW,e.litOptions.reflectionEncoding=t.envAtlas.encoding):t.cubeMap?(e.litOptions.reflectionSource=fY,e.litOptions.reflectionEncoding=t.cubeMap.encoding):t.sphereMap?(e.litOptions.reflectionSource=fq,e.litOptions.reflectionEncoding=t.sphereMap.encoding):t.useSkybox&&i.envAtlas&&i.skybox?(e.litOptions.reflectionSource=fX,e.litOptions.reflectionEncoding=i.envAtlas.encoding,e.litOptions.reflectionCubemapEncoding=i.skybox.encoding,r=true):t.useSkybox&&i.envAtlas?(e.litOptions.reflectionSource=fW,e.litOptions.reflectionEncoding=i.envAtlas.encoding,r=true):t.useSkybox&&i.skybox?(e.litOptions.reflectionSource=fY,e.litOptions.reflectionEncoding=i.skybox.encoding,r=true):(e.litOptions.reflectionSource=fH,e.litOptions.reflectionEncoding=null),t.ambientSH)e.litOptions.ambientSource=fj,e.litOptions.ambientEncoding=null;else {let s=t.envAtlas||(t.useSkybox&&i.envAtlas?i.envAtlas:null);s&&!t.sphereMap?(e.litOptions.ambientSource=fK,e.litOptions.ambientEncoding=s.encoding):(e.litOptions.ambientSource=fZ,e.litOptions.ambientEncoding=null);}e.litOptions.skyboxIntensity=r,e.litOptions.useCubeMapRotation=r&&i._skyboxRotationShaderInclude;}_updateLightOptions(e,t,i,s,r){if(e.lightMap=false,e.lightMapChannel="",e.lightMapUv=0,e.lightMapTransform=0,e.litOptions.lightMapWithoutAmbient=false,e.dirLightMap=false,s&&(e.litOptions.noShadow=(s&fJ)!=0,(s&f5)!=0&&(e.lightMapEncoding=t.lightmapPixelFormat===id?"rgbm":"linear",e.lightMap=true,e.lightMapChannel="rgb",e.lightMapUv=1,e.lightMapTransform=0,e.litOptions.lightMapWithoutAmbient=!i.lightMap,(s&f8)!=0&&(e.dirLightMap=true),(s&pt)!=0&&(e.litOptions.lightMapWithoutAmbient=false))),i.useLighting){let i=[],a=s?s>>16:po;e.litOptions.lightMaskDynamic=!!(a&po),r&&(SY.collectLights(uI,r[uI],i,a),t.clusteredLightingEnabled||(SY.collectLights(uD,r[uD],i,a),SY.collectLights(uM,r[uM],i,a))),e.litOptions.lights=i;}else e.litOptions.lights=[];0!==e.litOptions.lights.length||t.clusteredLightingEnabled||(e.litOptions.noShadow=true);}_getMapTransformID(e,t){if(!e)return 0;let i=this._mapXForms[t];i||(i=[],this._mapXForms[t]=i);for(let t=0;t<i.length;t++)if(S4(i[t][0].value,e[0].value)&&S4(i[t][1].value,e[1].value))return t+1;return i.push(e)}}function S9(e,t=true,i=true){let s={};return s[`${e}Map`]="texture",s[`${e}MapTiling`]="vec2",s[`${e}MapOffset`]="vec2",s[`${e}MapRotation`]="number",s[`${e}MapUv`]="number",t&&(s[`${e}MapChannel`]="string",i&&(s[`${e}VertexColor`]="boolean",s[`${e}VertexColorChannel`]="string")),s}let S7={name:"string",chunks:"chunks",mappingFormat:"string",_engine:"boolean",ambient:"rgb",...S9("ao"),...S9("aoDetail",true,false),aoDetailMode:"string",aoIntensity:"number",diffuse:"rgb",...S9("diffuse"),...S9("diffuseDetail",true,false),diffuseDetailMode:"string",specular:"rgb",specularTint:"boolean",...S9("specular"),occludeSpecular:"enum:occludeSpecular",specularityFactor:"number",specularityFactorTint:"boolean",...S9("specularityFactor"),useMetalness:"boolean",metalness:"number",enableGGXSpecular:"boolean",metalnessTint:"boolean",...S9("metalness"),useMetalnessSpecularColor:"boolean",anisotropyIntensity:"number",anisotropyRotation:"number",...S9("anisotropy"),shininess:"number",gloss:"number",glossInvert:"boolean",...S9("gloss"),clearCoat:"number",...S9("clearCoat"),clearCoatGloss:"number",clearCoatGlossInvert:"boolean",...S9("clearCoatGloss"),clearCoatBumpiness:"number",...S9("clearCoatNormal",false),useSheen:"boolean",sheen:"rgb",...S9("sheen"),sheenGloss:"number",sheenGlossInvert:"boolean",...S9("sheenGloss"),fresnelModel:"number",emissive:"rgb",...S9("emissive"),emissiveIntensity:"number",...S9("normal",false),bumpiness:"number",...S9("normalDetail",false),normalDetailMapBumpiness:"number",...S9("height",true,false),heightMapFactor:"number",alphaToCoverage:"boolean",alphaTest:"number",alphaFade:"number",opacity:"number",...S9("opacity"),opacityFadesSpecular:"boolean",opacityDither:"string",opacityShadowDither:"string",reflectivity:"number",refraction:"number",refractionTint:"boolean",...S9("refraction"),refractionIndex:"number",dispersion:"number",thickness:"number",thicknessTint:"boolean",...S9("thickness"),attenuation:"rgb",attenuationDistance:"number",useDynamicRefraction:"boolean",sphereMap:"texture",cubeMap:"cubemap",cubeMapProjection:"number",cubeMapProjectionBox:"boundingbox",useIridescence:"boolean",iridescence:"number",iridescenceTint:"boolean",...S9("iridescence"),iridescenceThicknessTint:"boolean",iridescenceThicknessMin:"number",iridescenceThicknessMax:"number",iridescenceRefractionIndex:"number",...S9("iridescenceThickness"),...S9("light"),depthTest:"boolean",depthFunc:"enum:depthFunc",depthWrite:"boolean",depthBias:"number",slopeDepthBias:"number",cull:"enum:cull",blendType:"enum:blendType",useFog:"boolean",useLighting:"boolean",useSkybox:"boolean",useTonemap:"boolean",envAtlas:"texture",twoSidedLighting:"boolean",shadowCatcher:"boolean"},ye=[];for(let e in S7)"texture"===S7[e]&&ye.push(e);let yt=[];for(let e in S7)"cubemap"===S7[e]&&yt.push(e);let yi={aoMapVertexColor:"boolean",diffuseMapTint:"boolean",diffuseMapVertexColor:"boolean",emissiveMapTint:"boolean",emissiveMapVertexColor:"boolean",glossMapVertexColor:"boolean",metalnessMapVertexColor:"boolean",opacityMapVertexColor:"boolean",specularAntialias:"boolean",specularMapTint:"boolean",specularMapVertexColor:"boolean",ambientTint:"boolean",emissiveTint:"boolean",diffuseTint:"boolean",sheenTint:"boolean",conserveEnergy:"boolean",useGamma:"boolean",useGammaTonemap:"boolean",sheenGlossTint:"boolean",anisotropy:"boolean"},ys={},yr={},ya=new Set,yn=new eb;class yo extends _${static{this.TEXTURE_PARAMETERS=ye;}static{this.CUBEMAP_PARAMETERS=yt;}constructor(){super(),this.userAttributes=new Map,this._assetReferences={},this._activeParams=new Set,this._activeLightingParams=new Set,this.shaderOptBuilder=new S6,this.reset();}reset(){Object.keys(ys).forEach(e=>{this[`_${e}`]=ys[e].value();}),this._uniformCache={};}copy(e){return super.copy(e),Object.keys(ys).forEach(t=>{this[t]=e[t];}),this.userAttributes=new Map(e.userAttributes),this}setAttribute(e,t){this.userAttributes.set(t,e);}_setParameter(e,t){ya.add(e),this.setParameter(e,t);}_setParameters(e){e.forEach(e=>{this._setParameter(e.name,e.value);});}_processParameters(e){let t=this[e];t.forEach(e=>{ya.has(e)||delete this.parameters[e];}),this[e]=ya,(ya=t).clear();}_updateMap(e){let t=`${e}Map`,i=this[t];if(i){this._setParameter(`texture_${t}`,i);let e=`${t}Transform`,s=this.getUniform(e);s&&this._setParameters(s);}}_allocUniform(e,t){let i=this._uniformCache[e];return i||(i=t(),this._uniformCache[e]=i),i}getUniform(e,t,i){return yr[e](this,t,i)}updateUniforms(e,t){let i=i=>this.getUniform(i,e,t);for(let e in this._setParameter("material_ambient",i("ambient")),this._setParameter("material_diffuse",i("diffuse")),this._setParameter("material_aoIntensity",this.aoIntensity),this.useMetalness?((!this.metalnessMap||this.metalness<1)&&this._setParameter("material_metalness",this.metalness),(!this.specularMap||this.specularTint)&&this._setParameter("material_specular",i("specular")),(!this.specularityFactorMap||this.specularityFactorTint)&&this._setParameter("material_specularityFactor",this.specularityFactor),this._setParameter("material_sheen",i("sheen")),this._setParameter("material_sheenGloss",this.sheenGloss),this._setParameter("material_refractionIndex",this.refractionIndex)):(!this.specularMap||this.specularTint)&&this._setParameter("material_specular",i("specular")),this.enableGGXSpecular&&(this._setParameter("material_anisotropyIntensity",this.anisotropyIntensity),this._setParameter("material_anisotropyRotation",[Math.cos(this.anisotropyRotation*eA.DEG_TO_RAD),Math.sin(this.anisotropyRotation*eA.DEG_TO_RAD)])),this.clearCoat>0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGloss",this.clearCoatGloss),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_gloss",this.gloss),this._setParameter("material_emissive",i("emissive")),this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&this._setParameter("material_refraction",this.refraction),this.dispersion>0&&this._setParameter("material_dispersion",this.dispersion),this.useDynamicRefraction&&(this._setParameter("material_thickness",this.thickness),this._setParameter("material_attenuation",i("attenuation")),this._setParameter("material_invAttenuationDistance",0===this.attenuationDistance?0:1/this.attenuationDistance)),this.useIridescence&&(this._setParameter("material_iridescence",this.iridescence),this._setParameter("material_iridescenceRefractionIndex",this.iridescenceRefractionIndex),this._setParameter("material_iridescenceThicknessMin",this.iridescenceThicknessMin),this._setParameter("material_iridescenceThicknessMax",this.iridescenceThicknessMax)),this._setParameter("material_opacity",this.opacity),false===this.opacityFadesSpecular&&this._setParameter("material_alphaFade",this.alphaFade),this.occludeSpecular&&this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity),this.cubeMapProjection===fy&&this._setParameter(i("cubeMapProjectionBox")),S1)this._updateMap(e);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH),this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness),this.normalMap&&this.normalDetailMap&&this._setParameter("material_normalDetailMapBumpiness",this.normalDetailMapBumpiness),this.heightMap&&this._setParameter("material_heightMapFactor",i("heightMapFactor")),this.envAtlas&&this.cubeMap?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas?this._setParameter("texture_envAtlas",this.envAtlas):this.cubeMap?this._setParameter("texture_cubeMap",this.cubeMap):this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),super.updateUniforms(e,t);}updateEnvUniforms(e,t){!(this.envAtlas||this.cubeMap||this.sphereMap)&&this.useSkybox&&(t.envAtlas&&t.skybox?(this._setParameter("texture_envAtlas",t.envAtlas),this._setParameter("texture_cubeMap",t.skybox)):t.envAtlas?this._setParameter("texture_envAtlas",t.envAtlas):t.skybox&&this._setParameter("texture_cubeMap",t.skybox)),this._processParameters("_activeLightingParams");}getShaderVariant(e){let{device:t,scene:i,pass:s,objDefs:r,sortedLights:a,cameraShaderParams:n}=e;this.updateEnvUniforms(t,i);let o=mt.get(t).getByIndex(s),l=s===pf||s===pd||o.isShadow,h=l?S3.optionsContextMin:S3.optionsContext;h.defines=mo.getCoreDefines(this,e),l?this.shaderOptBuilder.updateMinRef(h,i,this,r,s,a):this.shaderOptBuilder.updateRef(h,i,n,this,r,s,a),this.useFog||h.defines.set("FOG","NONE"),h.defines.set("TONEMAP",fU[h.litOptions.toneMap]),this.onUpdateShader&&(h=this.onUpdateShader(h));let c=new p5(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),d=p6(t);d.register("standard",S3);let u=d.getProgram("standard",h,c,this.userId);return this._dirtyShader=false,u}destroy(){for(let e in this._assetReferences)this._assetReferences[e]._unbind();this._assetReferences=null,super.destroy();}}let yl=(e,t)=>{yr[e]=t;},yh=(e,t,i,s)=>{Object.defineProperty(yo.prototype,e,{get:s||function(){return this[`_${e}`]},set:i}),ys[e]={value:t};},yc=e=>{let t=`_${e.name}`,i=e.dirtyShaderFunc||(()=>true);yh(e.name,()=>e.defaultValue,function(e){let s=this[t];s!==e&&(this._dirtyShader=this._dirtyShader||i(s,e),this[t]=e);},e.getterFunc);},yd=e=>{let t=`_${e.name}`,i=e.dirtyShaderFunc||(()=>true);yh(e.name,()=>e.defaultValue.clone(),function(e){let s=this[t];s.equals(e)||(this._dirtyShader=this._dirtyShader||i(s,e),this[t]=s.copy(e));},e.getterFunc);},yu=e=>e.defaultValue&&e.defaultValue.clone?yd(e):yc(e);function yf(e,t="rgb",i=true,s=0){S1[e]=t.length||-1,yu({name:`${e}Map`,defaultValue:null,dirtyShaderFunc:(e,t)=>!!e!=!!t||e&&(e.type!==t.type||e.format!==t.format)}),yu({name:`${e}MapTiling`,defaultValue:new eN(1,1)}),yu({name:`${e}MapOffset`,defaultValue:new eN(0,0)}),yu({name:`${e}MapRotation`,defaultValue:0}),yu({name:`${e}MapUv`,defaultValue:s}),t&&(yu({name:`${e}MapChannel`,defaultValue:t}),i&&(yu({name:`${e}VertexColor`,defaultValue:false}),yu({name:`${e}VertexColorChannel`,defaultValue:t})));let r=`${e}MapTiling`,a=`${e}MapOffset`,n=`${e}MapRotation`,o=`${e}MapTransform`;yl(o,(e,t,i)=>{let s=e[r],l=e[a],h=e[n];if(1===s.x&&1===s.y&&0===l.x&&0===l.y&&0===h)return null;let c=e._allocUniform(o,()=>[{name:`texture_${o}0`,value:new Float32Array(3)},{name:`texture_${o}1`,value:new Float32Array(3)}]),d=Math.cos(h*eA.DEG_TO_RAD),u=Math.sin(h*eA.DEG_TO_RAD),f=c[0].value;f[0]=d*s.x,f[1]=-u*s.y,f[2]=l.x;let p=c[1].value;return p[0]=u*s.x,p[1]=d*s.y,p[2]=1-s.y-l.y,c});}function yp(e,t){yu({name:e,defaultValue:t,getterFunc:function(){return this._dirtyShader=true,this[`_${e}`]}}),yl(e,(t,i,s)=>{let r=t._allocUniform(e,()=>new Float32Array(3)),a=t[e];return yn.linear(a),r[0]=yn.r,r[1]=yn.g,r[2]=yn.b,r});}function ym(e,t,i){yu({name:e,defaultValue:t,dirtyShaderFunc:(e,t)=>(0===e||1===e)!=(0===t||1===t)}),yl(e,i);}function y_(e,t){yu({name:e,defaultValue:null,dirtyShaderFunc:(e,t)=>!!e==!!t}),yl(e,t);}function yg(e,t){yu({name:e,defaultValue:t});}yp("ambient",new eb(1,1,1)),yp("diffuse",new eb(1,1,1)),yp("specular",new eb(0,0,0)),yp("emissive",new eb(0,0,0)),yp("sheen",new eb(1,1,1)),yp("attenuation",new eb(1,1,1)),ym("emissiveIntensity",1),ym("specularityFactor",1),ym("sheenGloss",0),ym("gloss",.25),ym("aoIntensity",1),ym("heightMapFactor",1,(e,t,i)=>.025*e.heightMapFactor),ym("opacity",1),ym("alphaFade",1),ym("alphaTest",0),ym("bumpiness",1),ym("normalDetailMapBumpiness",1),ym("reflectivity",1),ym("occludeSpecularIntensity",1),ym("refraction",0),ym("refractionIndex",1/1.5),ym("dispersion",0),ym("thickness",0),ym("attenuationDistance",0),ym("metalness",1),ym("anisotropyIntensity",0),ym("anisotropyRotation",0),ym("clearCoat",0),ym("clearCoatGloss",1),ym("clearCoatBumpiness",1),ym("aoUvSet",0,null),ym("iridescence",0),ym("iridescenceRefractionIndex",1/1.5),ym("iridescenceThicknessMin",0),ym("iridescenceThicknessMax",0),y_("ambientSH"),y_("cubeMapProjectionBox",(e,t,i)=>{let s=e._allocUniform("cubeMapProjectionBox",()=>[{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]),r=e.cubeMapProjectionBox.getMin(),a=s[0].value;a[0]=r.x,a[1]=r.y,a[2]=r.z;let n=e.cubeMapProjectionBox.getMax(),o=s[1].value;return o[0]=n.x,o[1]=n.y,o[2]=n.z,s}),yg("specularTint",false),yg("specularityFactorTint",false),yg("useMetalness",false),yg("useMetalnessSpecularColor",false),yg("useSheen",false),yg("enableGGXSpecular",false),yg("occludeDirect",false),yg("opacityFadesSpecular",true),yg("occludeSpecular",fV),yg("fresnelModel",uy),yg("useDynamicRefraction",false),yg("cubeMapProjection",fS),yg("useFog",true),yg("useLighting",true),yg("useTonemap",true),yg("useSkybox",true),yg("forceUv1",false),yg("pixelSnap",false),yg("twoSidedLighting",false),yg("nineSlicedMode",void 0),yg("msdfTextAttribute",false),yg("useIridescence",false),yg("glossInvert",false),yg("sheenGlossInvert",false),yg("clearCoatGlossInvert",false),yg("opacityDither",pq),yg("opacityShadowDither",pq),yg("shadowCatcher",false),yf("diffuse"),yf("specular"),yf("emissive"),yf("thickness","g"),yf("specularityFactor","g"),yf("normal",""),yf("metalness","g"),yf("gloss","g"),yf("opacity","a"),yf("refraction","g"),yf("height","g",false),yf("ao","g"),yf("light","rgb",true,1),yf("msdf",""),yf("diffuseDetail","rgb",false),yf("normalDetail",""),yf("aoDetail","g",false),yf("clearCoat","g"),yf("clearCoatGloss","g"),yf("clearCoatNormal",""),yf("sheen","rgb"),yf("sheenGloss","g"),yf("iridescence","g"),yf("iridescenceThickness","g"),yf("anisotropy",""),yg("diffuseDetailMode",fT),yg("aoDetailMode",fT),y_("cubeMap"),y_("sphereMap"),y_("envAtlas");let yv=[null,null,null,null,null,null];yh("prefilteredCubemaps",()=>yv.slice(),function(e){let t=this._prefilteredCubemaps;e=e||[];let i=false,s=true;for(let r=0;r<6;++r){let a=e[r]||null;t[r]!==a&&(t[r]=a,i=true),s=s&&!!t[r];}i&&(s?this.envAtlas=SL.generatePrefilteredAtlas(t,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=true);},function(){return this._prefilteredCubemaps});class yS extends vQ{constructor(e,t,i,s,r,a){let n;super();let o=new eM,l=new eM,h=new eM,c=new eM,d=new eM,u=new eM,f=[],p=[],m=[],_=[],g=[];if(i>0)for(let a=0;a<=s;a++)for(let n=0;n<=r;n++){let v=n/r*2*Math.PI-Math.PI,S=Math.sin(v),y=Math.cos(v);d.set(S*e,-i/2,y*e),c.set(S*t,i/2,y*t),o.lerp(d,c,a/s),l.sub2(c,d).normalize(),u.set(y,0,-S),h.cross(u,l).normalize(),f.push(o.x,o.y,o.z),p.push(h.x,h.y,h.z);let x=n/r,T=a/s;m.push(x,1-T);let E=T;if(T=x,x=.875*(x=E)+.0625,T=.875*T+.0625,x/=3,_.push(x,1-T),a<s&&n<r){let e=a*(r+1)+n,t=a*(r+1)+(n+1),i=(a+1)*(r+1)+n,s=(a+1)*(r+1)+(n+1);g.push(e,t,i),g.push(t,s,i);}}if(a){let e=Math.floor(r/2),a=i/2;for(let i=0;i<=e;i++){let s=i*Math.PI*.5/e,n=Math.sin(s),o=Math.cos(s);for(let s=0;s<=r;s++){let l=2*s*Math.PI/r-Math.PI/2,h=Math.sin(l),c=Math.cos(l)*n,d=h*n,u=1-s/r,g=1-i/e;f.push(c*t,o*t+a,d*t),p.push(c,o,d),m.push(u,1-g),g=(.875*g+.0625)/3,u=(.875*u+.0625)/3+1/3,_.push(u,1-g);}}n=(s+1)*(r+1);for(let t=0;t<e;++t)for(let e=0;e<r;++e){let i=t*(r+1)+e,s=i+r+1;g.push(n+i+1,n+s,n+i),g.push(n+i+1,n+s+1,n+s);}for(let i=0;i<=e;i++){let s=.5*Math.PI+i*Math.PI*.5/e,n=Math.sin(s),o=Math.cos(s);for(let s=0;s<=r;s++){let l=2*s*Math.PI/r-Math.PI/2,h=Math.sin(l),c=Math.cos(l)*n,d=h*n,u=1-s/r,g=1-i/e;f.push(c*t,o*t-a,d*t),p.push(c,o,d),m.push(u,1-g),g=(.875*g+.0625)/3,u=(.875*u+.0625)/3+2/3,_.push(u,1-g);}}n=(s+1)*(r+1)+(r+1)*(e+1);for(let t=0;t<e;++t)for(let e=0;e<r;++e){let i=t*(r+1)+e,s=i+r+1;g.push(n+i+1,n+s,n+i),g.push(n+i+1,n+s+1,n+s);}}else {if(n=(s+1)*(r+1),e>0)for(let t=0;t<r;t++){let s=t/r*2*Math.PI,a=Math.sin(s),o=-i/2,l=Math.cos(s),h=1-(a+1)/2,c=(l+1)/2;f.push(a*e,o,l*e),p.push(0,-1,0),m.push(h,1-c),c=(.875*c+.0625)/3,h=(.875*h+.0625)/3+1/3,_.push(h,1-c),t>1&&g.push(n,n+t,n+t-1);}if(n+=r,t>0)for(let e=0;e<r;e++){let s=e/r*2*Math.PI,a=Math.sin(s),o=i/2,l=Math.cos(s),h=1-(a+1)/2,c=(l+1)/2;f.push(a*t,o,l*t),p.push(0,1,0),m.push(h,1-c),c=(.875*c+.0625)/3,h=(.875*h+.0625)/3+2/3,_.push(h,1-c),e>1&&g.push(n,n+e-1,n+e);}}this.positions=f,this.normals=p,this.uvs=m,this.uvs1=_,this.indices=g;}}class yy extends yS{constructor(e={}){let t=e.radius??.3,i=e.height??1;super(t,t,i-2*t,e.heightSegments??1,e.sides??20,true),e.calculateTangents&&(this.tangents=vZ(this.positions,this.normals,this.uvs,this.indices));}}class yx extends yS{constructor(e={}){let t=e.baseRadius??.5,i=e.peakRadius??0,s=e.height??1;super(t,i,s,e.heightSegments??5,e.capSegments??18,false),e.calculateTangents&&(this.tangents=vZ(this.positions,this.normals,this.uvs,this.indices));}}class yT extends yS{constructor(e={}){let t=e.radius??.5,i=e.height??1;super(t,t,i,e.heightSegments??5,e.capSegments??20,false),e.calculateTangents&&(this.tangents=vZ(this.positions,this.normals,this.uvs,this.indices));}}class yE extends vQ{constructor(e={}){super();let t=e.halfExtents??new eN(.5,.5),i=e.widthSegments??5,s=e.lengthSegments??5,r=[],a=[],n=[],o=[],l=0;for(let e=0;e<=i;e++)for(let h=0;h<=s;h++){let c=-t.x+2*t.x*e/i,d=-(-t.y+2*t.y*h/s),u=e/i,f=h/s;r.push(c,0,d),a.push(0,1,0),n.push(u,1-f),e<i&&h<s&&(o.push(l+s+1,l+1,l),o.push(l+s+1,l+s+2,l+1)),l++;}this.positions=r,this.normals=a,this.uvs=n,this.uvs1=n,this.indices=o,e.calculateTangents&&(this.tangents=vZ(r,a,n,o));}}class yA extends vQ{constructor(e={}){super();let t=e.tubeRadius??.2,i=e.ringRadius??.3,s=(e.sectorAngle??360)*eA.DEG_TO_RAD,r=e.segments??30,a=e.sides??20,n=[],o=[],l=[],h=[];for(let e=0;e<=a;e++)for(let c=0;c<=r;c++){let d=Math.cos(s*c/r)*(i+t*Math.cos(2*Math.PI*e/a)),u=Math.sin(2*Math.PI*e/a)*t,f=Math.sin(s*c/r)*(i+t*Math.cos(2*Math.PI*e/a)),p=Math.cos(s*c/r)*Math.cos(2*Math.PI*e/a),m=Math.sin(2*Math.PI*e/a),_=Math.sin(s*c/r)*Math.cos(2*Math.PI*e/a),g=e/a,v=1-c/r;if(n.push(d,u,f),o.push(p,m,_),l.push(g,1-v),e<a&&c<r){let t=e*(r+1)+c,i=(e+1)*(r+1)+c,s=e*(r+1)+(c+1),a=(e+1)*(r+1)+(c+1);h.push(t,i,s),h.push(i,a,s);}}this.positions=n,this.normals=o,this.uvs=l,this.uvs1=l,this.indices=h,e.calculateTangents&&(this.tangents=vZ(n,o,l,h));}}class yb{constructor(e,t){this.processedCache=new Map,this.definitionsCache=new Map,this._generators=new Map,this._device=e,this._isClearingCache=false,this._precached=false,this._programsCollection=[],this._defaultStdMatOption=new S0,this._defaultStdMatOptionMin=new S0;let i=new mZ;t.shaderOptBuilder.updateRef(this._defaultStdMatOption,{},i,t,null,[],pc,null),t.shaderOptBuilder.updateMinRef(this._defaultStdMatOptionMin,{},t,null,pu,null),e.on("destroy:shader",e=>{this.removeFromCache(e);});}destroy(){this.clearCache();}register(e,t){this._generators.has(e)||this._generators.set(e,t);}unregister(e){this._generators.has(e)&&this._generators.delete(e);}isRegistered(e){return this._generators.has(e)}generateShaderDefinition(e,t,i,s){let r=this.definitionsCache.get(i);if(!r){let a;s.litOptions?.lights&&(a=s.litOptions.lights,s.litOptions.lights=a.map(e=>{let t=e.clone?e.clone():e;return t.key=e.key,t})),this.storeNewProgram(t,s),s.litOptions?.lights&&(s.litOptions.lights=a),this._precached;let n=this._device;(r=e.createShaderDefinition(n,s)).name=r.name??(s.pass?`${t}-pass:${s.pass}`:t),this.definitionsCache.set(i,r);}return r}getCachedShader(e){return this.processedCache.get(e)}setCachedShader(e,t){this.processedCache.set(e,t);}getProgram(e,t,i,s){let r=this._generators.get(e);if(!r)return null;let a=nE(r.generateKey(t)),n=nE(i.generateKey(this._device)),o=`${a}#${n}`,l=this.getCachedShader(o);if(!l){let n,h=this.generateShaderDefinition(r,e,a,t),c="";void 0!==t.pass&&(n=mt.get(this._device).getByIndex(t.pass),c=`-${n.name}`),this._device.fire("shader:generate",{userMaterialId:s,shaderPassInfo:n,definition:h});let d={name:`${h.name}${c}-proc`,attributes:h.attributes,vshader:h.vshader,vincludes:h.vincludes,fincludes:h.fincludes,fshader:h.fshader,processingOptions:i,shaderLanguage:h.shaderLanguage,meshUniformBufferFormat:h.meshUniformBufferFormat,meshBindGroupFormat:h.meshBindGroupFormat};l=new la(this._device,d),this.setCachedShader(o,l);}return l}storeNewProgram(e,t){let i={};if("standard"===e){let e=this._getDefaultStdMatOptions(t.pass);for(let s in t)(t.hasOwnProperty(s)&&e[s]!==t[s]||"pass"===s)&&(i[s]=t[s]);for(let e in t.litOptions)i[e]=t.litOptions[e];}else i=t;this._programsCollection.push(JSON.stringify({name:e,options:i}));}dumpPrograms(){let e="let device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice;\n";e+="let shaders = [",this._programsCollection[0]&&(e+=`
${this._programsCollection[0]}`);for(let t=1;t<this._programsCollection.length;++t)e+=`,
${this._programsCollection[t]}`;e+=`
];
pc.getProgramLibrary(device).precompile(shaders);
if (pc.version != "${V}" || pc.revision != "${z}")
console.warn("precompile-shaders.js: engine version mismatch, rebuild shaders lib with current engine");`;let t=document.createElement("a");t.setAttribute("href",`data:text/plain;charset=utf-8,${encodeURIComponent(e)}`),t.setAttribute("download","precompile-shaders.js"),t.style.display="none",document.body.appendChild(t),t.click(),document.body.removeChild(t);}clearCache(){this._isClearingCache=true,this.processedCache.forEach(e=>{e.destroy();}),this.processedCache.clear(),this._isClearingCache=false;}removeFromCache(e){this._isClearingCache||this.processedCache.forEach((t,i)=>{e===t&&this.processedCache.delete(i);});}_getDefaultStdMatOptions(e){let t=mt.get(this._device).getByIndex(e);return e===pf||e===pd||t.isShadow?this._defaultStdMatOptionMin:this._defaultStdMatOption}precompile(e){if(e){let t=Array(e.length);for(let i=0;i<e.length;i++){if("standard"===e[i].name){let t=e[i].options,s=this._getDefaultStdMatOptions(t.pass);for(let e in s)s.hasOwnProperty(e)&&void 0===t[e]&&(t[e]=s[e]);}t[i]=this.getProgram(e[i].name,e[i].options);}}this._precached=true;}}let yw=new eG,yC=new eH,yP=new ej,yL=new ej,yI=new eb(1,1,0,.4);class yD{constructor(e,t,i,s,r){let a=e.getProp("x"),n=e.getProp("y"),o=e.getProp("z"),l=e.getProp("rot_1"),h=e.getProp("rot_2"),c=e.getProp("rot_3"),d=e.getProp("rot_0"),u=e.getProp("scale_0"),f=e.getProp("scale_1"),p=e.getProp("scale_2"),m=e.getProp("f_dc_0"),_=e.getProp("f_dc_1"),g=e.getProp("f_dc_2"),v=e.getProp("opacity"),S=e=>{if(e>0)return 1/(1+Math.exp(-e));let t=Math.exp(e);return t/(1+t)};this.read=e=>{t&&(t.x=a[e],t.y=n[e],t.z=o[e]),i&&i.set(l[e],h[e],c[e],d[e]),s&&s.set(Math.exp(u[e]),Math.exp(f[e]),Math.exp(p[e])),r&&r.set(.5+.28209479177387814*m[e],.5+.28209479177387814*_[e],.5+.28209479177387814*g[e],S(v[e]));};}}let yR=(e,t,i)=>{yC.set(i.x,i.y,i.z,i.w).normalize(),e.setTRS(t,yC,eM.ONE);};class yM{constructor(e,t=[]){this.elements=e,this.numSplats=this.getElement("vertex").count,this.comments=t;}static calcSplatAabb(e,t,i,s){yR(yw,t,i),yP.center.set(0,0,0),yP.halfExtents.set(2*s.x,2*s.y,2*s.z),e.setFromTransformedAabb(yP,yw);}getProp(e,t="vertex"){return this.getElement(t)?.properties.find(t=>t.name===e)?.storage}getElement(e){return this.elements.find(t=>t.name===e)}addProp(e,t){this.getElement("vertex").properties.push({type:"float",name:e,storage:t,byteSize:4});}createIter(e,t,i,s){return new yD(this,e,t,i,s)}calcAabb(e,t){let i,s,r,a,n,o,l=true,h=this.getProp("x"),c=this.getProp("y"),d=this.getProp("z"),u=this.getProp("scale_0"),f=this.getProp("scale_1"),p=this.getProp("scale_2");for(let e=0;e<this.numSplats;++e){if(t&&!t(e))continue;let m=h[e],_=c[e],g=d[e],v=Math.max(u[e],f[e],p[e]);if(!isFinite(m)||!isFinite(_)||!isFinite(g)||!isFinite(v))continue;let S=2*Math.exp(v);l?(l=false,i=m-S,s=_-S,r=g-S,a=m+S,n=_+S,o=g+S):(i=Math.min(i,m-S),s=Math.min(s,_-S),r=Math.min(r,g-S),a=Math.max(a,m+S),n=Math.max(n,_+S),o=Math.max(o,g+S));}return l||(e.center.set((i+a)*.5,(s+n)*.5,(r+o)*.5),e.halfExtents.set((a-i)*.5,(n-s)*.5,(o-r)*.5)),!l}calcAabbExact(e,t){let i=new eM,s=new eH,r=new eM,a=this.createIter(i,s,r),n=true;for(let o=0;o<this.numSplats;++o)(!t||t(o))&&(a.read(o),n?(n=false,yM.calcSplatAabb(e,i,s,r)):(yM.calcSplatAabb(yL,i,s,r),e.add(yL)));return !n}getCenters(e){let t=this.getProp("x"),i=this.getProp("y"),s=this.getProp("z");for(let r=0;r<this.numSplats;++r)e[3*r+0]=t[r],e[3*r+1]=i[r],e[3*r+2]=s[r];}calcFocalPoint(e,t){let i=this.getProp("x"),s=this.getProp("y"),r=this.getProp("z"),a=this.getProp("scale_0"),n=this.getProp("scale_1"),o=this.getProp("scale_2");e.x=0,e.y=0,e.z=0;let l=0;for(let h=0;h<this.numSplats;++h){if(t&&!t(h))continue;let c=i[h],d=s[h],u=r[h];if(!isFinite(c)||!isFinite(d)||!isFinite(u))continue;let f=1/(1+Math.exp(Math.max(a[h],n[h],o[h])));e.x+=c*f,e.y+=d*f,e.z+=u*f,l+=f;}e.mulScalar(1/l);}renderWireframeBounds(e,t){let i=new eM,s=new eH,r=new eM,a=new eM,n=new eM,o=this.createIter(i,s,r);for(let l=0;l<this.numSplats;++l)o.read(l),yR(yw,i,s),yw.mul2(t,yw),a.set(-2*r.x,-2*r.y,-2*r.z),n.set(2*r.x,2*r.y,2*r.z),e.immediate.drawWireAlignedBox(a,n,yI,true,e.defaultDrawLayer,yw);}get isCompressed(){return false}get shBands(){return ({9:1,24:2,45:3})[(()=>{for(let e=0;e<45;++e)if(!this.getProp(`f_rest_${e}`))return e;return 45})()]??0}calcMortonOrder(){let e=e=>{let t=e[0],i=e[0];for(let s=1;s<e.length;s++)e[s]<t&&(t=e[s]),e[s]>i&&(i=e[s]);return {min:t,max:i}},t=(e,t,i)=>{let s=e=>(e&=1023,e=((e=((e=((e=(e^e<<16)&0xff0000ff)^e<<8)&0x300f00f)^e<<4)&0x30c30c3)^e<<2)&0x9249249);return (s(i)<<2)+(s(t)<<1)+s(e)},i=this.getProp("x"),s=this.getProp("y"),r=this.getProp("z"),{min:a,max:n}=e(i),{min:o,max:l}=e(s),{min:h,max:c}=e(r),d=a===n?0:1024/(n-a),u=o===l?0:1024/(l-o),f=h===c?0:1024/(c-h),p=new Map;for(let e=0;e<this.numSplats;e++){let n=Math.min(1023,Math.floor((i[e]-a)*d)),l=t(n,Math.min(1023,Math.floor((s[e]-o)*u)),Math.min(1023,Math.floor((r[e]-h)*f))),c=p.get(l);c?c.push(e):p.set(l,[e]);}let m=Array.from(p.keys()).sort((e,t)=>e-t),_=new Uint32Array(this.numSplats),g=0;for(let e=0;e<m.length;++e){let t=p.get(m[e]);for(let e=0;e<t.length;++e)_[g++]=t[e];}return _}reorder(e){let t=new Map,i=e=>{if(t.has(e)){let i=t.get(e);return t.delete(e),i}return new ArrayBuffer(e)},s=e=>{t.set(e.byteLength,e);},r=t=>{let r=new t.constructor(i(t.byteLength));for(let i=0;i<e.length;i++)r[i]=t[e[i]];return s(t.buffer),r};this.elements.forEach(e=>{e.properties.forEach(e=>{e.storage&&(e.storage=r(e.storage));});});}reorderData(){this.reorder(this.calcMortonOrder());}}class yO{constructor(e,t){this.device=e,this.gsplatData=t,this.centers=new Float32Array(3*t.numSplats),t.getCenters(this.centers),this.aabb=new ej,t.calcAabb(this.aabb);let i=128*Math.ceil(t.numSplats/128)/128,s=new Uint32Array(i);for(let e=0;e<i;++e)s[e]=128*e;let r=new nP(e,[{semantic:sK,components:1,type:rR,asInt:true}]),a=new Float32Array(1536),n=new Uint32Array(768);for(let e=0;e<128;++e){a.set([-1,-1,e,1,-1,e,1,1,e,-1,1,e],12*e);let t=4*e;n.set([0+t,1+t,2+t,0+t,2+t,3+t],6*e);}this.mesh=new mw(e),this.mesh.setPositions(a,3),this.mesh.setIndices(n),this.mesh.update(),this.mesh.incRefCount(),this.mesh.aabb.copy(this.aabb),this.instanceIndices=new nT(e,r,i,{usage:tM,data:s.buffer});}destroy(){this.mesh?.destroy(),this.instanceIndices?.destroy();}get instanceSize(){return 128}get numSplats(){return this.gsplatData.numSplats}configureMaterial(e){}evalTextureSize(e){return eN.ZERO}createTexture(e,t,i,s){return new ns(this.device,{name:e,width:i.x,height:i.y,format:t,cubemap:false,mipmaps:false,minFilter:tK,magFilter:tK,addressU:tr,addressV:tr,...s?{levels:[s]}:{}})}instantiate(){}}let yN=(e,t)=>{let i=[];for(let s=0;s<t;++s)i.push(e.getProp(`f_rest_${s}`));return i};class yF extends yO{constructor(e,t){super(e,t);let i=t.numSplats,s=this.evalTextureSize(i);this.colorTexture=this.createTexture("splatColor",ig,s),this.transformATexture=this.createTexture("transformA",i0,s),this.transformBTexture=this.createTexture("transformB",ig,s),this.updateColorData(t),this.updateTransformData(t),this.shBands=t.shBands,this.shBands>0&&(this.sh1to3Texture=this.createTexture("splatSH_1to3",i0,s),this.shBands>1&&(this.sh4to7Texture=this.createTexture("splatSH_4to7",i0,s),this.shBands>2?(this.sh8to11Texture=this.createTexture("splatSH_8to11",i0,s),this.sh12to15Texture=this.createTexture("splatSH_12to15",i0,s)):this.sh8to11Texture=this.createTexture("splatSH_8to11",iG,s)),this.updateSHData(t));}destroy(){this.colorTexture?.destroy(),this.transformATexture?.destroy(),this.transformBTexture?.destroy(),this.sh1to3Texture?.destroy(),this.sh4to7Texture?.destroy(),this.sh8to11Texture?.destroy(),this.sh12to15Texture?.destroy(),super.destroy();}configureMaterial(e){e.setParameter("splatColor",this.colorTexture),e.setParameter("transformA",this.transformATexture),e.setParameter("transformB",this.transformBTexture),e.setDefine("SH_BANDS",this.shBands),this.sh1to3Texture&&e.setParameter("splatSH_1to3",this.sh1to3Texture),this.sh4to7Texture&&e.setParameter("splatSH_4to7",this.sh4to7Texture),this.sh8to11Texture&&e.setParameter("splatSH_8to11",this.sh8to11Texture),this.sh12to15Texture&&e.setParameter("splatSH_12to15",this.sh12to15Texture);}evalTextureSize(e){let t=Math.ceil(Math.sqrt(e)),i=Math.ceil(e/t);return new eN(t,i)}updateColorData(e){let t=this.colorTexture;if(!t)return;let i=eD.float2Half,s=t.lock(),r=e.getProp("f_dc_0"),a=e.getProp("f_dc_1"),n=e.getProp("f_dc_2"),o=e.getProp("opacity");for(let e=0;e<this.numSplats;++e){let t=.28209479177387814*r[e]+.5,l=.28209479177387814*a[e]+.5,h=.28209479177387814*n[e]+.5,c=1/(1+Math.exp(-o[e]));s[4*e+0]=i(t),s[4*e+1]=i(l),s[4*e+2]=i(h),s[4*e+3]=i(c);}t.unlock();}updateTransformData(e){let t=eD.float2Half;if(!this.transformATexture)return;let i=this.transformATexture.lock(),s=new Float32Array(i.buffer),r=this.transformBTexture.lock(),a=new eM,n=new eH,o=new eM,l=e.createIter(a,n,o);for(let e=0;e<this.numSplats;e++)l.read(e),n.normalize(),n.w<0&&n.mulScalar(-1),s[4*e+0]=a.x,s[4*e+1]=a.y,s[4*e+2]=a.z,i[4*e+3]=t(n.x)|t(n.y)<<16,r[4*e+0]=t(o.x),r[4*e+1]=t(o.y),r[4*e+2]=t(o.z),r[4*e+3]=t(n.z);this.transformATexture.unlock(),this.transformBTexture.unlock();}updateSHData(e){let t=this.sh1to3Texture.lock(),i=this.sh4to7Texture?.lock(),s=this.sh8to11Texture?.lock(),r=this.sh12to15Texture?.lock(),a={1:3,2:8,3:15}[this.shBands],n=yN(e,3*a),o=new Float32Array(1),l=new Uint32Array(o.buffer),h=Array(3*a).fill(0);for(let c=0;c<e.numSplats;++c){for(let e=0;e<a;++e)h[3*e]=n[e][c],h[3*e+1]=n[e+a][c],h[3*e+2]=n[e+2*a][c];let e=h[0];for(let t=1;t<3*a;++t)e=Math.max(e,Math.abs(h[t]));if(0!==e){for(let t=0;t<a;++t)h[3*t+0]=Math.max(0,Math.min(2047,Math.floor((h[3*t+0]/e*.5+.5)*2047+.5))),h[3*t+1]=Math.max(0,Math.min(1023,Math.floor((h[3*t+1]/e*.5+.5)*1023+.5))),h[3*t+2]=Math.max(0,Math.min(2047,Math.floor((h[3*t+2]/e*.5+.5)*2047+.5)));o[0]=e,t[4*c+0]=l[0],t[4*c+1]=h[0]<<21|h[1]<<11|h[2],t[4*c+2]=h[3]<<21|h[4]<<11|h[5],t[4*c+3]=h[6]<<21|h[7]<<11|h[8],this.shBands>1&&(i[4*c+0]=h[9]<<21|h[10]<<11|h[11],i[4*c+1]=h[12]<<21|h[13]<<11|h[14],i[4*c+2]=h[15]<<21|h[16]<<11|h[17],i[4*c+3]=h[18]<<21|h[19]<<11|h[20],this.shBands>2?(s[4*c+0]=h[21]<<21|h[22]<<11|h[23],s[4*c+1]=h[24]<<21|h[25]<<11|h[26],s[4*c+2]=h[27]<<21|h[28]<<11|h[29],s[4*c+3]=h[30]<<21|h[31]<<11|h[32],r[4*c+0]=h[33]<<21|h[34]<<11|h[35],r[4*c+1]=h[36]<<21|h[37]<<11|h[38],r[4*c+2]=h[39]<<21|h[40]<<11|h[41],r[4*c+3]=h[42]<<21|h[43]<<11|h[44]):s[c]=h[21]<<21|h[22]<<11|h[23]);}}this.sh1to3Texture.unlock(),this.sh4to7Texture?.unlock(),this.sh8to11Texture?.unlock(),this.sh12to15Texture?.unlock();}}let yB=`
attribute vec2 vertex_position;
void main(void) {
gl_Position = vec4(vertex_position, 0.0, 1.0);
}
`,yU=`
#include "gsplatEvalSHVS"
vec4 packRgb(vec3 v) {
uvec3 vb = uvec3(clamp(v, vec3(0.0), vec3(1.0)) * vec3(2047.0, 2047.0, 1023.0));
uint bits = (vb.x << 21) | (vb.y << 10) | vb.z;
return vec4((uvec4(bits) >> uvec4(24, 16, 8, 0)) & uvec4(0xff)) / vec4(255.0);
}
uniform mediump vec3 dir;
uniform mediump sampler2D centroids;
uniform mediump float shN_mins;
uniform mediump float shN_maxs;
void main(void) {
ivec2 uv = ivec2(gl_FragCoord.xy) * ivec2(SH_COEFFS, 1);
mediump vec3 coefficients[SH_COEFFS];
for (int i = 0; i < SH_COEFFS; i++) {
vec3 s = texelFetch(centroids, ivec2(uv.x + i, uv.y), 0).xyz;
coefficients[i] = mix(vec3(shN_mins), vec3(shN_maxs), s);
}
gl_FragColor = packRgb(evalSH(coefficients, dir) * 0.25 + 0.5);
}
`,yk=`
attribute vertex_position: vec2f;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = vec4f(vertex_position, 0.0, 1.0);
return output;
}
`,yV=`
#include "gsplatEvalSHVS"
fn packRgb(v: vec3f) -> vec4f {
let vb = vec3u(clamp(v, vec3f(0.0), vec3f(1.0)) * vec3f(2047.0, 2047.0, 1023.0));
let bits = dot(vb, vec3u(1 << 21, 1 << 10, 1));
return vec4f((vec4u(bits) >> vec4u(24, 16, 8, 0)) & vec4u(0xff)) / vec4f(255.0);
}
uniform dir: vec3f;
uniform shN_mins: f32;
uniform shN_maxs: f32;
var centroids: texture_2d<f32>;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
var uv = vec2i(input.position.xy) * vec2i(SH_COEFFS, 1);
var coefficients: array<vec3f, SH_COEFFS>;
for (var i: i32 = 0; i < SH_COEFFS; i++) {
let s: vec3f = textureLoad(centroids, vec2i(uv.x + i, uv.y), 0).xyz;
coefficients[i] = mix(vec3f(uniform.shN_mins), vec3f(uniform.shN_maxs), s);
}
output.color = packRgb(evalSH(&coefficients, uniform.dir) * 0.25 + 0.5);
return output;
}
`,yz=`
uniform mediump sampler2D sh0;
uniform highp sampler2D sh_labels;
uniform mediump sampler2D sh_result;
uniform vec4 sh0_mins;
uniform vec4 sh0_maxs;
float SH_C0 = 0.28209479177387814;
vec3 unpackRgb(vec4 v) {
uvec4 uv = uvec4(v * 255.0);
uint bits = (uv.x << 24) | (uv.y << 16) | (uv.z << 8) | uv.w;
uvec3 vb = (uvec3(bits) >> uvec3(21, 10, 0)) & uvec3(0x7ffu, 0x7ffu, 0x3ffu);
return vec3(vb) / vec3(2047.0, 2047.0, 1023.0);
}
vec4 readColor(in SplatSource source) {
vec4 baseSample = mix(sh0_mins, sh0_maxs, texelFetch(sh0, source.uv, 0));
vec4 base = vec4(vec3(0.5) + baseSample.xyz * SH_C0, 1.0 / (1.0 + exp(-baseSample.w)));
ivec2 labelSample = ivec2(texelFetch(sh_labels, source.uv, 0).xy * 255.0);
int n = labelSample.x + labelSample.y * 256;
vec4 shSample = texelFetch(sh_result, ivec2(n % 64, n / 64), 0);
vec3 sh = (unpackRgb(shSample) - vec3(0.5)) * 4.0;
return vec4(base.xyz + sh, base.w);
}
`,yG=`
var sh0: texture_2d<f32>;
var sh_labels: texture_2d<f32>;
var sh_result: texture_2d<f32>;
uniform sh0_mins: vec4f;
uniform sh0_maxs: vec4f;
const SH_C0: f32 = 0.28209479177387814;
fn unpackRgb(v: vec4f) -> vec3f {
let bits = dot(vec4u(v * 255.0), vec4u(1u << 24, 1u << 16, 1u << 8, 1u));
let vb = (vec3u(bits) >> vec3u(21, 10, 0)) & vec3u(0x7ffu, 0x7ffu, 0x3ffu);
return vec3f(vb) / vec3f(2047.0, 2047.0, 1023.0);
}
fn readColor(source: ptr<function, SplatSource>) -> vec4f {
let baseSample: vec4f = mix(uniform.sh0_mins, uniform.sh0_maxs, textureLoad(sh0, source.uv, 0));
let base = vec4f(vec3f(0.5) + baseSample.xyz * SH_C0, 1.0 / (1.0 + exp(-baseSample.w)));
let labelSample: vec2i = vec2i(textureLoad(sh_labels, source.uv, 0).xy * 255.0);
let n = labelSample.x + labelSample.y * 256;
let shSample: vec4f = textureLoad(sh_result, vec2i(n % 64, n / 64), 0);
let sh: vec3f = (unpackRgb(shSample) - vec3f(0.5)) * 4.0;
return vec4f(base.xyz + sh, base.w);
}
`,yH=(e,t)=>{for(let i in t)e.resolve(i).setValue(t[i]);};class yW extends l2{execute(){this.executeCallback?.();}constructor(...e){super(...e),this.executeCallback=null;}}let yX=new eG,yY=new eM;class yq{constructor(e,t){this.prevDir=new eM,this.updateMode="enable",this.device=e,this.gsplatInstance=t;let{resource:i}=t,s=new Map(mr.get(e,e.isWebGPU?"wgsl":"glsl"));this.shader=mo.createShader(e,{uniqueName:"gsplatResolveSH",vertexGLSL:yB,fragmentGLSL:yU,vertexWGSL:yk,fragmentWGSL:yV,vertexIncludes:s,fragmentIncludes:s,fragmentDefines:new Map([["SH_BANDS",i.gsplatData.shBands.toString()]]),attributes:{vertex_position:sT}}),this.texture=i.createTexture("centroids",id,new eN(64,1024)),this.renderTarget=new nM({colorBuffer:this.texture,depth:false}),this.renderPass=new yW(e),this.renderPass.init(this.renderTarget,{}),this.renderPass.colorOps.clear=true,this.quadRender=new mp(this.shader);let{material:r}=t;r.setDefine("SH_BANDS","0");let{shaderChunks:a}=r;a.glsl.set("gsplatSogsColorVS",yz),a.wgsl.set("gsplatSogsColorVS",yG),r.update(),e.scope.resolve("sh_result").setValue(this.texture);}destroy(){let{gsplatInstance:e}=this,{material:t}=e;t.setDefine("SH_BANDS",e.resource.gsplatData.shBands.toString());let{shaderChunks:i}=t;i.glsl.delete("gsplatSogsColorVS"),i.wgsl.delete("gsplatSogsColorVS"),t.update(),this.quadRender.destroy(),this.renderPass.destroy(),this.renderTarget.destroy(),this.texture.destroy(),this.shader.destroy();}render(e,t){let{prevDir:i,updateMode:s}=this;if("disable"!==s)yX.invert(t),yX.transformVector(e.forward,yY),yY.normalize(),"enable"===s&&yY.equalsApprox(i,.001)||(i.copy(yY),this.renderPass.executeCallback=()=>{let{device:e}=this,{sh_centroids:t,meta:i}=this.gsplatInstance.resource.gsplatData;yH(e.scope,{dir:yY.toArray(),centroids:t,shN_mins:i.shN.mins,shN_maxs:i.shN.maxs}),e.setCullMode(tY),e.setDepthState(nm.NODEPTH),e.setStencilState(null,null),e.setBlendState(nu.NOBLEND),this.quadRender.render();},this.renderPass.render());}}function y$(){let e,t,i,s,r,a,n,o,l="undefined"!=typeof self&&self||require("node:worker_threads").parentPort,h=false,c={x:0,y:0,z:0},d={x:0,y:0,z:0},u={x:0,y:0,z:0},f={x:0,y:0,z:0},p=Array(32).fill(0),m=Array(32).fill(0),_=Array(32).fill(0),g=(e,t,i)=>{for(;e<=t;){let s=t+e>>1,r=i(s);if(r>0)e=s+1;else {if(!(r<0))return s;t=s-1;}}return ~e},v=()=>{let v,S;if(!e||!t||0===t.length||!r||!a)return;let y=r.x,x=r.y,T=r.z,E=a.x,A=a.y,b=a.z;if(!h&&.001>Math.abs(y-c.x)&&.001>Math.abs(x-c.y)&&.001>Math.abs(T-c.z)&&.001>Math.abs(E-d.x)&&.001>Math.abs(A-d.y)&&.001>Math.abs(b-d.z))return;h=false,c.x=y,c.y=x,c.z=T,d.x=E,d.y=A,d.z=b;for(let e=0;e<8;++e){let t=1&e?u.x:f.x,i=t*E+(2&e?u.y:f.y)*A+(4&e?u.z:f.z)*b;0===e?v=S=i:(v=Math.min(v,i),S=Math.max(S,i));}let w=t.length/3,C=Math.max(10,Math.min(20,Math.round(Math.log2(w/4)))),P=2**C+1;n?.length!==w&&(n=new Uint32Array(w)),o&&o.length===P?o.fill(0):o=new Uint32Array(P);let L=S-v;if(L<1e-6)for(let e=0;e<w;++e)n[e]=0,o[0]++;else {let e=i.length/4;p.fill(0);for(let t=0;t<e;++t){let e=i[4*t+0],s=i[4*t+1],r=i[4*t+2],a=i[4*t+3],n=e*E+s*A+r*b-v,o=Math.max(0,Math.floor((n-a)*32/L)),l=Math.min(32,Math.ceil((n+a)*32/L));for(let e=o;e<l;++e)p[e]++;}let s=p.reduce((e,t)=>e+t,0);for(let e=0;e<32;++e)_[e]=p[e]/s*P>>>0;for(let e=0;e<32;++e)m[e]=0===e?0:m[e-1]+_[e-1];let r=L/32,a=0;for(let e=0;e<w;++e){let i=t[a++],s=(i*E+t[a++]*A+t[a++]*b-v)/r,l=s>>>0,h=m[l]+_[l]*(s-l)>>>0;n[e]=h,o[h]++;}}for(let e=1;e<P;e++)o[e]+=o[e-1];for(let t=0;t<w;t++){let i=n[t];e[--o[i]]=t;}let I=y*E+x*A+T*b,D=i=>{let s=3*e[i];return t[s++]*E+t[s++]*A+t[s]*b-I},R=D(w-1)>=0?(()=>{let e=g(0,w-1,e=>-D(e));return Math.min(w,Math.abs(e))})():w;if(s)for(let t=0;t<w;++t)e[t]=s[e[t]];l.postMessage({order:e.buffer,count:R},[e.buffer]),e=null;};l.addEventListener("message",n=>{let o=n.data??n;if(o.order&&(e=new Uint32Array(o.order)),o.centers)if(t=new Float32Array(o.centers),h=true,o.chunks){let e=new Float32Array(o.chunks);i=new Float32Array(o.chunks,0,4*e.length/6),u.x=e[0],u.y=e[1],u.z=e[2],f.x=e[3],f.y=e[4],f.z=e[5];for(let t=0;t<e.length/6;++t){let s=e[6*t+0],r=e[6*t+1],a=e[6*t+2],n=e[6*t+3],o=e[6*t+4],l=e[6*t+5];i[4*t+0]=(s+n)*.5,i[4*t+1]=(r+o)*.5,i[4*t+2]=(a+l)*.5,i[4*t+3]=.5*Math.sqrt((n-s)**2+(o-r)**2+(l-a)**2),s<u.x&&(u.x=s),r<u.y&&(u.y=r),a<u.z&&(u.z=a),n>f.x&&(f.x=n),o>f.y&&(f.y=o),l>f.z&&(f.z=l);}}else {let e,s,r,a,n,o,l=t.length/3,h=Math.ceil(l/256);i=new Float32Array(4*h),u.x=u.y=u.z=1/0,f.x=f.y=f.z=-1/0;for(let c=0;c<h;++c){e=s=r=1/0,a=n=o=-1/0;let h=256*c,d=Math.min(l,(c+1)*256);for(let i=h;i<d;++i){let l=t[3*i+0],h=t[3*i+1],c=t[3*i+2],d=Number.isFinite(l),p=Number.isFinite(h),m=Number.isFinite(c);d||(t[3*i+0]=0),p||(t[3*i+1]=0),m||(t[3*i+2]=0),d&&p&&m&&(l<e?e=l:l>a&&(a=l),h<s?s=h:h>n&&(n=h),c<r?r=c:c>o&&(o=c),l<u.x?u.x=l:l>f.x&&(f.x=l),h<u.y?u.y=h:h>f.y&&(f.y=h),c<u.z?u.z=c:c>f.z&&(f.z=c));}i[4*c+0]=(e+a)*.5,i[4*c+1]=(s+n)*.5,i[4*c+2]=(r+o)*.5,i[4*c+3]=.5*Math.sqrt((a-e)**2+(n-s)**2+(o-r)**2);}}o.hasOwnProperty("mapping")&&(s=o.mapping?new Uint32Array(o.mapping):null,h=true),o.cameraPosition&&(r=o.cameraPosition),o.cameraDirection&&(a=o.cameraDirection),v();});}class yj extends eo{constructor(){super();let e=e=>{let t=e.data??e,i=t.order,s=this.orderTexture._levels[0].buffer;this.worker.postMessage({order:s},[s]),this.orderTexture._levels[0]=new Uint32Array(i),this.orderTexture.upload(),this.fire("updated",t.count);},t=`(${y$.toString()})()`;"node"===ee.environment?(this.worker=new Worker(t,{eval:true}),this.worker.on("message",e)):(this.worker=new Worker(URL.createObjectURL(new Blob([t],{type:"application/javascript"}))),this.worker.addEventListener("message",e));}destroy(){this.worker.terminate(),this.worker=null;}init(e,t,i){this.orderTexture=e,this.centers=t.slice();let s=this.orderTexture.lock({mode:s7}).slice();this.orderTexture.unlock();for(let e=0;e<s.length;++e)s[e]=e;let r={order:s.buffer,centers:t.buffer,chunks:i?.buffer},a=[s.buffer,t.buffer].concat(i?[i.buffer]:[]);this.worker.postMessage(r,a);}setMapping(e){if(e){let t=new Float32Array(3*e.length);for(let i=0;i<e.length;++i){let s=3*e[i],r=3*i;t[r+0]=this.centers[s+0],t[r+1]=this.centers[s+1],t[r+2]=this.centers[s+2];}this.worker.postMessage({centers:t.buffer,mapping:e.buffer},[t.buffer,e.buffer]);}else {let e=this.centers.slice();this.worker.postMessage({centers:e.buffer,mapping:null},[e.buffer]);}}setCamera(e,t){this.worker.postMessage({cameraPosition:{x:e.x,y:e.y,z:e.z},cameraDirection:{x:t.x,y:t.y,z:t.z}});}}var yK=`
uniform highp sampler2D means_l;
uniform highp sampler2D means_u;
uniform highp sampler2D quats;
uniform highp sampler2D scales;
uniform highp sampler2D sh_labels;
uniform highp uint numSplats;
uint packU32(vec4 v) {
return uint(v.x * 255.0) << 24u |
uint(v.y * 255.0) << 16u |
uint(v.z * 255.0) << 8u |
uint(v.w * 255.0);
}
uvec4 packU32(vec4 a, vec4 b, vec4 c, vec4 d) {
return uvec4(packU32(a), packU32(b), packU32(c), packU32(d));
}
void main(void) {
int w = int(textureSize(means_l, 0).x);
ivec2 uv = ivec2(gl_FragCoord.xy);
if (uint(uv.x + uv.y * w) >= numSplats) {
discard;
}
vec3 meansLSample = texelFetch(means_l, uv, 0).xyz;
vec3 meansUSample = texelFetch(means_u, uv, 0).xyz;
vec4 quatsSample = texelFetch(quats, uv, 0);
vec3 scalesSample = texelFetch(scales, uv, 0).xyz;
vec2 shLabelsSample = texelFetch(sh_labels, uv, 0).xy;
pcFragColor0 = packU32(
vec4(meansLSample, shLabelsSample.x),
vec4(meansUSample, shLabelsSample.y),
vec4(quatsSample),
vec4(scalesSample, 0.0)
);
}
`,yZ=`
var means_l: texture_2d<f32>;
var means_u: texture_2d<f32>;
var quats: texture_2d<f32>;
var scales: texture_2d<f32>;
var sh_labels: texture_2d<f32>;
uniform numSplats: u32;
fn packU32(v: vec4<f32>) -> u32 {
return (u32(v.x * 255.0) << 24u) |
(u32(v.y * 255.0) << 16u) |
(u32(v.z * 255.0) << 8u) |
u32(v.w * 255.0);
}
fn packUVec32(a: vec4<f32>, b: vec4<f32>, c: vec4<f32>, d: vec4<f32>) -> vec4<u32> {
return vec4<u32>(packU32(a), packU32(b), packU32(c), packU32(d));
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let w: u32 = textureDimensions(means_l, 0).x;
let uv: vec2<u32> = vec2<u32>(pcPosition.xy);
if (uv.x + uv.y * w >= uniform.numSplats) {
discard;
return output;
}
let meansLSample: vec3<f32> = textureLoad(means_l, uv, 0).xyz;
let meansUSample: vec3<f32> = textureLoad(means_u, uv, 0).xyz;
let quatsSample: vec4<f32> = textureLoad(quats, uv, 0);
let scalesSample: vec3<f32> = textureLoad(scales, uv, 0).xyz;
let shLabelsSample: vec2<f32> = textureLoad(sh_labels, uv, 0).xy;
output.color = packUVec32(
vec4(meansLSample, shLabelsSample.x),
vec4(meansUSample, shLabelsSample.y),
vec4(quatsSample),
vec4(scalesSample, 0.0)
);
return output;
}
`;let yQ=e=>e.read(0,0,e.width,e.height,{mipLevel:0,face:0,immediate:true}),yJ=(e,t)=>{for(let i in t)e.resolve(i).setValue(t[i]);};class y0{constructor(e,t,i,s,r,a){let n=(e,t,i)=>e*(1-i)+t*i,{meta:o}=e,{means:l,scales:h,sh0:c,shN:d}=o,u=t&&e.means_l._levels[0],f=t&&e.means_u._levels[0],p=i&&e.quats._levels[0],m=s&&e.scales._levels[0],_=r&&e.sh0._levels[0],g=a&&e.sh_labels._levels[0],v=a&&e.sh_centroids._levels[0],S=2/Math.sqrt(2);this.read=o=>{if(t){let e=n(l.mins[0],l.maxs[0],((f[4*o+0]<<8)+u[4*o+0])/65535),i=n(l.mins[1],l.maxs[1],((f[4*o+1]<<8)+u[4*o+1])/65535),s=n(l.mins[2],l.maxs[2],((f[4*o+2]<<8)+u[4*o+2])/65535);t.x=Math.sign(e)*(Math.exp(Math.abs(e))-1),t.y=Math.sign(i)*(Math.exp(Math.abs(i))-1),t.z=Math.sign(s)*(Math.exp(Math.abs(s))-1);}if(i){let e=(p[4*o+0]/255-.5)*S,t=(p[4*o+1]/255-.5)*S,s=(p[4*o+2]/255-.5)*S,r=Math.sqrt(Math.max(0,1-(e*e+t*t+s*s)));switch(p[4*o+3]-252){case 0:i.set(e,t,s,r);break;case 1:i.set(r,t,s,e);break;case 2:i.set(t,r,s,e);break;case 3:i.set(t,s,r,e);}}if(s){let e=n(h.mins[0],h.maxs[0],m[4*o+0]/255),t=n(h.mins[1],h.maxs[1],m[4*o+1]/255),i=n(h.mins[2],h.maxs[2],m[4*o+2]/255);s.set(e,t,i);}if(r){let e=n(c.mins[0],c.maxs[0],_[4*o+0]/255),t=n(c.mins[1],c.maxs[1],_[4*o+1]/255),i=n(c.mins[2],c.maxs[2],_[4*o+2]/255),s=n(c.mins[3],c.maxs[3],_[4*o+3]/255);r.set(.5+.28209479177387814*e,.5+.28209479177387814*t,.5+.28209479177387814*i,1/(1+Math.exp(-s)));}if(a){let t=g[4*o+0]+(g[4*o+1]<<8),i=t%64*15,s=Math.floor(t/64);for(let t=0;t<3;++t)for(let r=0;r<15;++r)a[15*t+r]=n(d.mins,d.maxs,v[(i+r)*4+t+s*e.sh_centroids.width*4]/255);}};}}class y1{destroy(){this.means_l?.destroy(),this.means_u?.destroy(),this.quats?.destroy(),this.scales?.destroy(),this.sh0?.destroy(),this.sh_centroids?.destroy(),this.sh_labels?.destroy(),this.packedTexture?.destroy();}createIter(e,t,i,s,r){return new y0(this,e,t,i,s,r)}calcAabb(e){let{mins:t,maxs:i}=this.meta.means,s=e=>Math.sign(e)*(Math.exp(Math.abs(e))-1);e.center.set((s(t[0])+s(i[0]))*.5,(s(t[1])+s(i[1]))*.5,(s(t[2])+s(i[2]))*.5),e.halfExtents.set((s(i[0])-s(t[0]))*.5,(s(i[1])-s(t[1]))*.5,(s(i[2])-s(t[2]))*.5);}getCenters(e){let{meta:t,means_l:i,means_u:s,numSplats:r}=this,{means:a}=t,n=new Uint32Array(s._levels[0].buffer),o=new Uint32Array(i._levels[0].buffer),l=a.mins[0]/65535,h=a.mins[1]/65535,c=a.mins[2]/65535,d=a.maxs[0]/65535,u=a.maxs[1]/65535,f=a.maxs[2]/65535;for(let t=0;t<r;t++){let i=t,s=n[i],r=o[i],a=s<<8&65280|255&r,p=65280&s|r>>>8&255,m=s>>>8&65280|r>>>16&255,_=l*(65535-a)+d*a,g=h*(65535-p)+u*p,v=c*(65535-m)+f*m,S=_<0?-_:_,y=g<0?-g:g,x=v<0?-v:v;e[3*t]=(_<0?-1:1)*(Math.exp(S)-1),e[3*t+1]=(g<0?-1:1)*(Math.exp(y)-1),e[3*t+2]=(v<0?-1:1)*(Math.exp(x)-1);}}calcFocalPoint(e,t){e.set(0,0,0);}get isSogs(){return true}get shBands(){return ({192:1,512:2,960:3})[this.sh_centroids?.width]??0}async decompress(){let e=["x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3"],{shBands:t}=this,{means_l:i,means_u:s,quats:r,scales:a,sh0:n,sh_labels:o,sh_centroids:l}=this;if(i._levels[0]=await yQ(i),s._levels[0]=await yQ(s),r._levels[0]=await yQ(r),a._levels[0]=await yQ(a),n._levels[0]=await yQ(n),t>0){o._levels[0]=await yQ(o),l._levels[0]=await yQ(l);let t=[];for(let e=0;e<45;++e)t.push(`f_rest_${e}`);e.splice(e.indexOf("f_dc_0")+1,0,...t);}let h={};e.forEach(e=>{h[e]=new Float32Array(this.numSplats);});let c=new eM,d=new eH,u=new eM,f=new eF,p=t>0?new Float32Array(45):null,m=this.createIter(c,d,u,f,p);for(let e=0;e<this.numSplats;++e)if(m.read(e),h.x[e]=c.x,h.y[e]=c.y,h.z[e]=c.z,h.rot_1[e]=d.x,h.rot_2[e]=d.y,h.rot_3[e]=d.z,h.rot_0[e]=d.w,h.scale_0[e]=u.x,h.scale_1[e]=u.y,h.scale_2[e]=u.z,h.f_dc_0[e]=(f.x-.5)/.28209479177387814,h.f_dc_1[e]=(f.y-.5)/.28209479177387814,h.f_dc_2[e]=(f.z-.5)/.28209479177387814,h.opacity[e]=f.w<=0?-40:f.w>=1?40:-Math.log(1/f.w-1),p)for(let t=0;t<45;++t)h[`f_rest_${t}`][e]=p[t];return new yM([{name:"vertex",count:this.numSplats,properties:e.map(e=>({name:e,type:"float",byteSize:4,storage:h[e]}))}])}packGpuMemory(){let{means_l:e,means_u:t,quats:i,scales:s,sh_labels:r,numSplats:a}=this,{device:n}=e,{scope:o}=n,l=mo.createShader(n,{uniqueName:"GsplatSogsReorderShader",attributes:{vertex_position:sT},vertexChunk:"fullscreenQuadVS",fragmentGLSL:yK,fragmentWGSL:yZ,fragmentOutputTypes:["uvec4"]}),h=new nM({colorBuffer:this.packedTexture,depth:false,mipLevel:0});n.setCullMode(tY),n.setBlendState(nu.NOBLEND),n.setDepthState(nm.NODEPTH),yJ(o,{means_l:e,means_u:t,quats:i,scales:s,sh_labels:r??e,numSplats:a}),mg(n,h,l),h.destroy(),l.destroy();}async prepareGpuData(){let{device:e,height:t,width:i}=this.means_l;this.means_l._levels[0]=await yQ(this.means_l),this.means_u._levels[0]=await yQ(this.means_u),this.packedTexture=new ns(e,{name:"sogsPackedTexture",width:i,height:t,format:i0,mipmaps:false}),e.on("devicerestored",()=>{this.packGpuMemory();}),this.packGpuMemory();}reorderData(){return this.prepareGpuData()}}let y2=new eG,y3=new eM,y4=new eM,y5=[0,0];class y8{constructor(e,t={}){this.options={},this.sorter=null,this.lastCameraPosition=new eM,this.lastCameraDirection=new eM,this.resolveSH=null,this.cameras=[],this.resource=e,this.orderTexture=e.createTexture("splatOrder",iG,e.evalTextureSize(e.numSplats)),t.material?(this._material=t.material,this._material.setParameter("splatOrder",this.orderTexture)):(this._material=new vY({uniqueName:"SplatMaterial",vertexGLSL:'#include "gsplatVS"',fragmentGLSL:'#include "gsplatPS"',vertexWGSL:'#include "gsplatVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:sT,vertex_id_attrib:sK}}),this.configureMaterial(this._material),this._material.update()),this.meshInstance=new mV(e.mesh,this._material),this.meshInstance.setInstancing(e.instanceIndices,true),this.meshInstance.gsplatInstance=this,this.meshInstance.instancingCount=0;let i=e.centers.slice(),s=e.chunks?.slice();this.sorter=new yj,this.sorter.init(this.orderTexture,i,s),this.sorter.on("updated",t=>{this.meshInstance.instancingCount=Math.ceil(t/e.instanceSize),this.material.setParameter("numSplats",t);}),this.setHighQualitySH(t.highQualitySH??false);}destroy(){this.resolveSH?.destroy(),this.material?.destroy(),this.meshInstance?.destroy(),this.sorter?.destroy();}set material(e){this._material!==e&&(this._material=e,this._material.setParameter("splatOrder",this.orderTexture),this.meshInstance&&(this.meshInstance.material=e));}get material(){return this._material}configureMaterial(e,t={}){this.resource.configureMaterial(e),e.setParameter("numSplats",0),e.setParameter("splatOrder",this.orderTexture),e.setParameter("alphaClip",.3),e.setDefine(`DITHER_${t.dither?"BLUENOISE":"NONE"}`,""),e.cull=tY,e.blendType=t.dither?un:uo,e.depthWrite=!!t.dither;}updateViewport(e){let t=e?.camera,{width:i,height:s}=t?.renderTarget??this.resource.device;y5[0]=i,y5[1]=s;let r=t?.camera?.xr;r?.active&&2===r.views.list.length&&(y5[0]*=.5),this.material.setParameter("viewport",y5);}sort(e){if(this.sorter){let t=e.getWorldTransform();t.getTranslation(y3),t.getZ(y4);let i=this.meshInstance.node.getWorldTransform(),s=y2.invert(i);s.transformPoint(y3,y3),s.transformVector(y4,y4),y3.equalsApprox(this.lastCameraPosition)&&y4.equalsApprox(this.lastCameraDirection)||(this.lastCameraPosition.copy(y3),this.lastCameraDirection.copy(y4),this.sorter.setCamera(y3,y4));}this.updateViewport(e);}update(){if(this.cameras.length>0){let e=this.cameras[0];this.sort(e._node),this.resolveSH?.render(e._node,this.meshInstance.node.getWorldTransform()),this.cameras.length=0;}}setHighQualitySH(e){let{resource:t}=this,{gsplatData:i}=t;i instanceof y1&&i.shBands>0&&!!this.resolveSH===e&&(this.resolveSH?(this.resolveSH.destroy(),this.resolveSH=null):this.resolveSH=new yq(t.device,this));}}class y6 extends yO{destroy(){this.gsplatData.destroy(),super.destroy();}configureMaterial(e){let{gsplatData:t}=this;e.setDefine("GSPLAT_SOGS_DATA",true),e.setDefine("SH_BANDS",this.gsplatData.shBands),["packedTexture","sh0","sh_centroids"].forEach(i=>{t[i]&&e.setParameter(i,t[i]);}),["means","scales","sh0","shN"].forEach(i=>{let s=t.meta[i];s&&(e.setParameter(`${i}_mins`,s.mins),e.setParameter(`${i}_maxs`,s.maxs));});}evalTextureSize(e){return new eN(this.gsplatData.means_l.width,this.gsplatData.means_l.height)}}let y9="NONE",y7="FILL_WINDOW",xe="KEEP_ASPECT",xt="AUTO",xi="FIXED",xs=false,xr={app:null,createLoadingScreen(e){xs||(xs=true,e(s));}};class xa{addRenderPass(e){e.frameUpdate();let t=e.beforePasses;for(let e=0;e<t.length;e++){let i=t[e];i.enabled&&this.addRenderPass(i);}e.enabled&&this.renderPasses.push(e);let i=e.afterPasses;for(let e=0;e<i.length;e++){let t=i[e];t.enabled&&this.addRenderPass(t);}}reset(){this.renderPasses.length=0;}compile(){let e=this.renderTargetMap,t=this.renderPasses;for(let i=0;i<t.length;i++){let s=t[i],r=s.renderTarget;if(void 0!==r){let t=e.get(r);if(t){let e=s.colorArrayOps.length;for(let i=0;i<e;i++)s.colorArrayOps[i].clear||(t.colorArrayOps[i].store=true);s.depthStencilOps.clearDepth||(t.depthStencilOps.storeDepth=true),s.depthStencilOps.clearStencil||(t.depthStencilOps.storeStencil=true);}e.set(r,s);}}for(let e=0;e<t.length-1;e++){let i=t[e],s=i.renderTarget,r=t[e+1];s!==r.renderTarget||void 0===s||r.depthStencilOps.clearDepth||r.depthStencilOps.clearStencil||r.colorArrayOps.some(e=>e.clear)||i.afterPasses.length>0||r.beforePasses.length>0||(i._skipEnd=true,r._skipStart=true);}let i=null,s=null;for(let e=0;e<t.length;e++){let r=t[e],a=r.renderTarget,n=a?.colorBuffer;if(n?.cubemap){if(i===n){let e=s.colorArrayOps.length;for(let t=0;t<e;t++)s.colorArrayOps[t].mipmaps=false;}i=a.colorBuffer,s=r;}else r.requiresCubemaps&&(i=null,s=null);}e.clear();}render(e){this.compile();let t=this.renderPasses;for(let e=0;e<t.length;e++)t[e].render();}constructor(){this.renderPasses=[],this.renderTargetMap=new Map;}}class xn{constructor(e,t){this.texture0=e,this.texture1=t;}destroy(){this.texture0?.destroy(),this.texture1?.destroy();}}let xo=new ne;class xl{static createTexture(e,t,i,s=""){return new ns(e,{name:`AreaLightLUT${s}`,width:i,height:i,format:t,addressU:tr,addressV:tr,type:rt,magFilter:tZ,minFilter:tK,anisotropy:1,mipmaps:false})}static applyTextures(e,t,i){xo.remove(e),xo.get(e,()=>new xn(t,t===i?null:i)),e.scope.resolve("areaLightsLutTex1").setValue(t),e.scope.resolve("areaLightsLutTex2").setValue(i);}static createPlaceholder(e){let t=xl.createTexture(e,ig,2,"placeholder");t.lock().fill(0),t.unlock(),xl.applyTextures(e,t,t);}static set(e,t,i){function s(e,t,i){let s=xl.createTexture(e,i,64);return s.lock().set(t),s.unlock(),s}function r(e){let t=e.length,i=new Uint16Array(t),s=eD.float2Half;for(let r=0;r<t;r++)i[r]=s(e[r]);return i}let a=r(t),n=r(i),o=s(e,a,ig),l=s(e,n,ig);xl.applyTextures(e,o,l);}}let xh="en-US",xc={en:"en-US",es:"en-ES",zh:"zh-CN","zh-HK":"zh-TW","zh-TW":"zh-HK","zh-MO":"zh-HK",fr:"fr-FR",de:"de-DE",it:"it-IT",ru:"ru-RU",ja:"ja-JP"},xd={};function xu(e,t){for(let i=0,s=e.length;i<s;i++)xd[e[i]]=t;}function xf(e){let t=e.indexOf("-");return -1!==t?e.substring(0,t):e}function xp(e,t){if(t[e])return e;let i=xc[e];if(i&&t[i])return i;let s=xf(e);return t[i=xc[s]]?i:t[s]?s:xh}xu(["ja","ko","th","vi","zh","id"],e=>0),xu(["fa","hi"],e=>e>=0&&e<=1?0:1),xu(["fr","pt"],e=>e>=0&&e<2?0:1),xu(["da"],e=>1===e||!Number.isInteger(e)&&e>=0&&e<=1?0:1),xu(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],e=>+(1!==e)),xu(["ru","uk"],e=>{if(Number.isInteger(e)){let t=e%10,i=e%100;if(1===t&&11!==i)return 0;if(t>=2&&t<=4&&(i<12||i>14))return 1;if(0===t||t>=5&&t<=9||i>=11&&i<=14)return 2}return 3}),xu(["pl"],e=>{if(Number.isInteger(e)){if(1===e)return 0;let t=e%10,i=e%100;if(t>=2&&t<=4&&(i<12||i>14))return 1;if(t>=0&&t<=1||t>=5&&t<=9||i>=12&&i<=14)return 2}return 3}),xu(["ar"],e=>{if(0===e)return 0;if(1===e)return 1;if(2===e)return 2;if(Number.isInteger(e)){let t=e%100;if(t>=3&&t<=10)return 3;if(t>=11&&t<=99)return 4}return 5});let xm=xd[xf(xh)],x_=RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-+.]*:)?//|data:|blob:)","i"),xg="animation",xv="audio",xS="image",xy="json",xx="model",xT="material",xE="text",xA="texture",xb="textureatlas",xw="cubemap",xC="shader",xP="css",xL="html",xI="script",xD="container";class xR{constructor(e="",t="",i=null,s=null,r=null,a=null){this.url=e,this.filename=t,this.hash=i,this.size=s,this.opt=r,this.contents=a;}equals(e){return this.url===e.url&&this.filename===e.filename&&this.hash===e.hash&&this.size===e.size&&this.opt===e.opt&&this.contents===e.contents}}let xM=-1,xO={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},xN=["pvr","dxt","etc2","etc1","basis"];class xF extends eo{static{this.EVENT_LOAD="load";}static{this.EVENT_UNLOAD="unload";}static{this.EVENT_REMOVE="remove";}static{this.EVENT_ERROR="error";}static{this.EVENT_CHANGE="change";}static{this.EVENT_PROGRESS="progress";}static{this.EVENT_ADDLOCALIZED="add:localized";}static{this.EVENT_REMOVELOCALIZED="remove:localized";}constructor(e,t,i,s={},r={}){super(),this._file=null,this._i18n={},this._preload=false,this._resources=[],this.id=xM--,this.loaded=false,this.loading=false,this.options={},this.registry=null,this.tags=new ep(this),this.urlObject=null,this._name=e||"",this.type=t,this._data=s||{},this.options=r||{},i&&(this.file=i);}set name(e){if(this._name===e)return;let t=this._name;this._name=e,this.fire("name",this,this._name,t);}get name(){return this._name}set file(e){if(e&&e.variants&&-1!==["texture","textureatlas","bundle"].indexOf(this.type)){let t=this.registry?._loader?._app||s,i=t?.graphicsDevice;if(i)for(let s=0,r=xN.length;s<r;s++){let r=xN[s];if(e.variants[r]&&i[xO[r]]){e=e.variants[r];break}if(t.enableBundles){let e=t.bundles.listBundlesForAsset(this);if(e&&e.find(e=>e?.file?.variants[r]))break}}}let t=this._file,i=e?new xR(e.url,e.filename,e.hash,e.size,e.opt,e.contents):null;(!!i!=!!t||i&&!i.equals(t))&&(this._file=i,this.fire("change",this,"file",i,t),this.reload());}get file(){return this._file}set data(e){let t=this._data;this._data=e,e!==t&&(this.fire("change",this,"data",e,t),this.loaded&&this.registry._loader.patch(this,this.registry));}get data(){return this._data}set resource(e){let t=this._resources[0];this._resources[0]=e,this.fire("change",this,"resource",e,t);}get resource(){return this._resources[0]}set resources(e){let t=this._resources;this._resources=e,this.fire("change",this,"resources",e,t);}get resources(){return this._resources}set preload(e){e=!!e,this._preload!==e&&(this._preload=e,this._preload&&!this.loaded&&!this.loading&&this.registry&&this.registry.load(this));}get preload(){return this._preload}set loadFaces(e){e=!!e,(!this.hasOwnProperty("_loadFaces")||e!==this._loadFaces)&&(this._loadFaces=e,this.loaded&&this.registry._loader.patch(this,this.registry));}get loadFaces(){return this._loadFaces}getFileUrl(){let e=this.file;if(!e||!e.url)return null;let t=e.url;if(this.registry&&this.registry.prefix&&!x_.test(t)&&(t=this.registry.prefix+t),"script"!==this.type&&e.hash){let i=-1!==t.indexOf("?")?"&":"?";t+=`${i}t=${e.hash}`;}return t}getAbsoluteUrl(e){if(e.startsWith("blob:")||e.startsWith("data:"))return e;let t=W.getDirectory(this.file.url);return W.join(t,e)}getLocalizedAssetId(e){return e=xp(e,this._i18n),this._i18n[e]||null}addLocalizedAssetId(e,t){this._i18n[e]=t,this.fire("add:localized",e,t);}removeLocalizedAssetId(e){let t=this._i18n[e];t&&(delete this._i18n[e],this.fire("remove:localized",e,t));}ready(e,t){t=t||this,this.loaded?e.call(t,this):this.once("load",i=>{e.call(t,i);});}reload(){this.loaded&&(this.loaded=false,this.registry.load(this));}unload(){if(!this.loaded&&0===this._resources.length)return;this.fire("unload",this),this.registry.fire(`unload:${this.id}`,this);let e=this._resources;this.urlObject&&(URL.revokeObjectURL(this.urlObject),this.urlObject=null),this.resources=[],this.loaded=false,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(let t=0;t<e.length;++t){let i=e[t];i&&i.destroy&&i.destroy();}}static fetchArrayBuffer(e,t,i,s=0){i?.file?.contents?setTimeout(()=>{t(null,i.file.contents);}):d1.get(e,{cache:true,responseType:"arraybuffer",retry:s>0,maxRetries:s},t);}}class xB{constructor(e=null){this._index={},this._key=e;}addItem(e){for(let t of e.tags._list)this.add(t,e);}removeItem(e){for(let t of e.tags._list)this.remove(t,e);}add(e,t){(!this._index[e]||-1===this._index[e].list.indexOf(t))&&(!this._index[e]&&(this._index[e]={list:[]},this._key&&(this._index[e].keys={})),this._index[e].list.push(t),this._key&&(this._index[e].keys[t[this._key]]=t));}remove(e,t){if(!this._index[e]||this._key&&!this._index[e].keys[t[this._key]])return;let i=this._index[e].list.indexOf(t);-1!==i&&(this._index[e].list.splice(i,1),this._key&&delete this._index[e].keys[t[this._key]],0===this._index[e].list.length&&delete this._index[e]);}find(e){let t,i,s,r,a,n={},o=[],l=(e,t)=>this._index[e].list.length-this._index[t].list.length;for(let h=0;h<e.length;h++){if((i=e[h])instanceof Array){if(0===i.length)continue;if(1===i.length)i=i[0];else {a=false;for(let e=0;e<i.length;e++)if(!this._index[i[e]]){a=true;break}if(a)continue;1===(r=(s=i.slice(0).sort(l)).slice(1)).length&&(r=r[0]);for(let e=0;e<this._index[s[0]].list.length;e++)t=this._index[s[0]].list[e],(this._key?!n[t[this._key]]:-1===o.indexOf(t))&&t.tags.has(r)&&(this._key&&(n[t[this._key]]=true),o.push(t));continue}}if(i&&"string"==typeof i&&this._index[i])for(let e=0;e<this._index[i].list.length;e++)t=this._index[i].list[e],this._key?n[t[this._key]]||(n[t[this._key]]=true,o.push(t)):-1===o.indexOf(t)&&o.push(t);}return o}}class xU extends eo{static{this.EVENT_LOAD="load";}static{this.EVENT_ADD="add";}static{this.EVENT_REMOVE="remove";}static{this.EVENT_ERROR="error";}constructor(e){super(),this._assets=new Set,this._idToAsset=new Map,this._urlToAsset=new Map,this._nameToAsset=new Map,this._tags=new xB("id"),this.prefix=null,this.bundles=null,this._loader=e;}list(e={}){let t=Array.from(this._assets);return void 0!==e.preload?t.filter(t=>t.preload===e.preload):t}add(e){!this._assets.has(e)&&(this._assets.add(e),this._idToAsset.set(e.id,e),e.file?.url&&this._urlToAsset.set(e.file.url,e),this._nameToAsset.has(e.name)||this._nameToAsset.set(e.name,new Set),this._nameToAsset.get(e.name).add(e),e.on("name",this._onNameChange,this),e.registry=this,this._tags.addItem(e),e.tags.on("add",this._onTagAdd,this),e.tags.on("remove",this._onTagRemove,this),this.fire("add",e),this.fire(`add:${e.id}`,e),e.file?.url&&this.fire(`add:url:${e.file.url}`,e),e.preload&&this.load(e));}remove(e){if(!this._assets.has(e))return false;if(this._assets.delete(e),this._idToAsset.delete(e.id),e.file?.url&&this._urlToAsset.delete(e.file.url),e.off("name",this._onNameChange,this),this._nameToAsset.has(e.name)){let t=this._nameToAsset.get(e.name);t.delete(e),0===t.size&&this._nameToAsset.delete(e.name);}return this._tags.removeItem(e),e.tags.off("add",this._onTagAdd,this),e.tags.off("remove",this._onTagRemove,this),e.fire("remove",e),this.fire("remove",e),this.fire(`remove:${e.id}`,e),e.file?.url&&this.fire(`remove:url:${e.file.url}`,e),true}get(e){return this._idToAsset.get(Number(e))}getByUrl(e){return this._urlToAsset.get(e)}load(e,t){if((e.loading||e.loaded)&&!t?.force)return;let i=e.file,s=()=>{this.fire("load",e),this.fire(`load:${e.id}`,e),i&&i.url&&this.fire(`load:url:${i.url}`,e),e.fire("load",e);},r=t=>{if(t instanceof Array?e.resources=t:e.resource=t,this._loader.patch(e,this),"bundle"===e.type){let t=e.data.assets;for(let e=0;e<t.length;e++){let i=this._idToAsset.get(t[e]);i&&!i.loaded&&this.load(i,{force:true});}e.resource.loaded?s():(this.fire("load:start",e),this.fire(`load:start:${e.id}`,e),i&&i.url&&this.fire(`load:start:url:${i.url}`,e),e.fire("load:start",e),e.resource.on("load",s));}else s();};if(i||"cubemap"===e.type){this.fire("load:start",e),this.fire(`load:${e.id}:start`,e),e.loading=true;let i=e.getFileUrl();if("bundle"===e.type){let t=e.data.assets;for(let e=0;e<t.length;e++){let i=this._idToAsset.get(t[e]);i&&(i.loaded||i.resource||i.loading||(i.loading=true));}}this._loader.load(i,e.type,(t,i,s)=>{if(e.loaded=true,e.loading=false,t)this.fire("error",t,e),this.fire(`error:${e.id}`,t,e),e.fire("error",t,e);else {if("script"===e.type){let t=this._loader.getHandler("script");t._cache[e.id]&&t._cache[e.id].parentNode===document.head&&document.head.removeChild(t._cache[e.id]),t._cache[e.id]=s;}r(i);}},e,t);}else {let t=this._loader.open(e.type,e.data);e.loaded=true,r(t);}}loadFromUrl(e,t,i){this.loadFromUrlAndFilename(e,null,t,i);}loadFromUrlAndFilename(e,t,i,s){let r=W.getBasename(t||e),a=this.getByUrl(e);if(a){if(a.loaded)return void s(a.loadFromUrlError||null,a)}else a=new xF(r,i,{filename:t||r,url:e}),this.add(a);let n=e=>{e.once("load",e=>{"material"===i?this._loadTextures(e,(t,i)=>{s(t,e);}):s(null,e);}),e.once("error",t=>{t&&(this.loadFromUrlError=t),s(t,e);}),this.load(e);};a.resource?s(null,a):"model"===i?this._loadModel(a,n):n(a);}_loadModel(e,t){let i=e.getFileUrl(),s=W.getExtension(i);if(".json"===s||".glb"===s){let r=W.getDirectory(i),a=W.getBasename(i),n=W.join(r,a.replace(s,".mapping.json"));this._loader.load(n,"json",(i,s)=>{i?(e.data={mapping:[]},t(e)):this._loadMaterials(e,s,(i,r)=>{e.data=s,t(e);});});}else t(e);}_loadMaterials(e,t,i){let s=[],r=0,a=(e,t)=>{this._loadTextures(t,(e,a)=>{s.push(t),s.length===r&&i(null,s);});};for(let i=0;i<t.mapping.length;i++){let s=t.mapping[i].path;if(s){r++;let t=e.getAbsoluteUrl(s);this.loadFromUrl(t,"material",a);}}0===r&&i(null,s);}_loadTextures(e,t){let i=[],s=0,r=e.data;if("path"!==r.mappingFormat)return void t(null,i);let a=(e,r)=>{i.push(r),i.length===s&&t(null,i);};for(let t=0;t<ye.length;t++){let i=r[ye[t]];if(i&&"string"==typeof i){s++;let t=e.getAbsoluteUrl(i);this.loadFromUrl(t,"texture",a);}}0===s&&t(null,i);}_onTagAdd(e,t){this._tags.add(e,t);}_onTagRemove(e,t){this._tags.remove(e,t);}_onNameChange(e,t,i){if(this._nameToAsset.has(i)){let t=this._nameToAsset.get(i);t.delete(e),0===t.size&&this._nameToAsset.delete(i);}this._nameToAsset.has(e.name)||this._nameToAsset.set(e.name,new Set),this._nameToAsset.get(e.name).add(e);}findByTag(...e){return this._tags.find(e)}filter(e){return Array.from(this._assets).filter(t=>e(t))}find(e,t){let i=this._nameToAsset.get(e);if(!i)return null;for(let e of i)if(!t||e.type===t)return e;return null}findAll(e,t){let i=this._nameToAsset.get(e);if(!i)return [];let s=Array.from(i);return t?s.filter(e=>e.type===t):s}}class xk{constructor(e){this._idToBundle=new Map,this._assetToBundles=new Map,this._urlsToBundles=new Map,this._fileRequests=new Map,this._assets=e,this._assets.bundles=this,this._assets.on("add",this._onAssetAdd,this),this._assets.on("remove",this._onAssetRemove,this);}_onAssetAdd(e){if("bundle"===e.type){this._idToBundle.set(e.id,e),this._assets.on(`load:start:${e.id}`,this._onBundleLoadStart,this),this._assets.on(`load:${e.id}`,this._onBundleLoad,this),this._assets.on(`error:${e.id}`,this._onBundleError,this);let t=e.data.assets;for(let i=0;i<t.length;i++)this._indexAssetInBundle(t[i],e);}else this._assetToBundles.has(e.id)&&this._indexAssetFileUrls(e);}_unbindAssetEvents(e){this._assets.off(`load:start:${e}`,this._onBundleLoadStart,this),this._assets.off(`load:${e}`,this._onBundleLoad,this),this._assets.off(`error:${e}`,this._onBundleError,this);}_indexAssetInBundle(e,t){let i=this._assetToBundles.get(e);i||(i=new Set,this._assetToBundles.set(e,i)),i.add(t);let s=this._assets.get(e);s&&this._indexAssetFileUrls(s);}_indexAssetFileUrls(e){let t=this._getAssetFileUrls(e);if(t)for(let i=0;i<t.length;i++){let s=this._assetToBundles.get(e.id);s&&this._urlsToBundles.set(t[i],s);}}_getAssetFileUrls(e){let t=e.getFileUrl();if(!t)return null;let i=[t=t.split("?")[0]];if("font"===e.type){let s=e.data.info.maps.length;for(let e=1;e<s;e++)i.push(t.replace(".png",`${e}.png`));}return i}_onAssetRemove(e){if("bundle"===e.type){this._idToBundle.delete(e.id),this._unbindAssetEvents(e.id);let t=e.data.assets;for(let i=0;i<t.length;i++){let s=this._assetToBundles.get(t[i]);if(s&&(s.delete(e),0===s.size))for(let[e,r]of(this._assetToBundles.delete(t[i]),this._urlsToBundles))r===s&&this._urlsToBundles.delete(e);}this._onBundleError(`Bundle ${e.id} was removed`);}else {if(!this._assetToBundles.get(e.id))return;this._assetToBundles.delete(e.id);let t=this._getAssetFileUrls(e);if(!t)return;for(let e=0;e<t.length;e++)this._urlsToBundles.delete(t[e]);}}_onBundleLoadStart(e){e.resource.on("add",(e,t)=>{let i=this._fileRequests.get(e);if(i){for(let e=0;e<i.length;e++)i[e](null,t);this._fileRequests.delete(e);}});}_onBundleLoad(e){if(!e.resource)return void this._onBundleError(`Bundle ${e.id} failed to load`);if(this._fileRequests)for(let[t,i]of this._fileRequests){let s,r,a=this._urlsToBundles.get(t);if(!a||!a.has(e))continue;let n=decodeURIComponent(t);if(e.resource.has(n))r=e.resource.get(n);else {if(!e.resource.loaded)continue;s=`Bundle ${e.id} does not contain URL ${t}`;}for(let e=0;e<i.length;e++)i[e](s,s||r);this._fileRequests.delete(t);}}_onBundleError(e){for(let[t,i]of this._fileRequests)if(!this._findLoadedOrLoadingBundleForUrl(t)){for(let t=0;t<i.length;t++)i[t](e);this._fileRequests.delete(t);}}_findLoadedOrLoadingBundleForUrl(e){let t=this._urlsToBundles.get(e);if(!t)return null;let i=null;for(let e of t)if(e.loaded&&e.resource)return e;else e.loading&&(i=e);return i}listBundlesForAsset(e){let t=this._assetToBundles.get(e.id);return t?Array.from(t):null}list(){return Array.from(this._idToBundle.values())}hasUrl(e){return this._urlsToBundles.has(e)}urlIsLoadedOrLoading(e){return !!this._findLoadedOrLoadingBundleForUrl(e)}loadUrl(e,t){let i=this._findLoadedOrLoadingBundleForUrl(e);if(!i)return void t(`URL ${e} not found in any bundles`);if(i.loaded){let s=decodeURIComponent(e);if(i.resource.has(s))return void t(null,i.resource.get(s));if(i.resource.loaded)return void t(`Bundle ${i.id} does not contain URL ${e}`)}let s=this._fileRequests.get(e);s||(s=[],this._fileRequests.set(e,s)),s.push(t);}destroy(){for(let e of(this._assets.off("add",this._onAssetAdd,this),this._assets.off("remove",this._onAssetRemove,this),this._idToBundle.keys()))this._unbindAssetEvents(e);this._assets=null,this._idToBundle.clear(),this._idToBundle=null,this._assetToBundles.clear(),this._assetToBundles=null,this._urlsToBundles.clear(),this._urlsToBundles=null,this._fileRequests.clear(),this._fileRequests=null;}}class xV extends eo{constructor(){super(),this.list=[];}add(e){let t=e.id;if(this[t])throw Error(`ComponentSystem name '${t}' already registered or not allowed`);this[t]=e,this.list.push(e);}remove(e){let t=e.id;if(!this[t])throw Error(`No ComponentSystem named '${t}' registered`);delete this[t];let i=this.list.indexOf(this[t]);-1!==i&&this.list.splice(i,1);}destroy(){this.off();for(let e=0;e<this.list.length;e++)this.list[e].destroy();}}class xz extends eo{static{this.EVENT_ADD="add";}static{this.EVENT_LOAD="load";}addFile(e,t){this._index.has(e)||(this._index.set(e,t),this.fire("add",e,t));}has(e){return this._index.has(e)}get(e){return this._index.get(e)||null}destroy(){this._index.clear();}set loaded(e){e&&!this._loaded&&(this._loaded=true,this.fire("load"));}get loaded(){return this._loaded}constructor(...e){super(...e),this._index=new Map,this._loaded=false;}}class xG extends eo{constructor(e,t=""){super(),this.headerSize=512,this.paddingSize=512,this.bytesRead=0,this.bytesReceived=0,this.headerRead=false,this.reader=null,this.data=new Uint8Array(0),this.decoder=null,this.prefix="",this.fileName="",this.fileSize=0,this.fileType="",this.ustarFormat="",this.prefix=t||"",this.reader=e.body.getReader(),this.reader.read().then(e=>{this.pump(e.done,e.value);}).catch(e=>{this.fire("error",e);});}pump(e,t){if(e)return this.fire("done"),null;this.bytesReceived+=t.byteLength;let i=new Uint8Array(this.data.length+t.length);for(i.set(this.data),i.set(t,this.data.length),this.data=i;this.readFile(););return this.reader.read().then(e=>{this.pump(e.done,e.value);}).catch(e=>{this.fire("error",e);})}readFile(){if(!this.headerRead&&this.bytesReceived>this.bytesRead+this.headerSize){this.headerRead=true;let e=new DataView(this.data.buffer,this.bytesRead,this.headerSize);this.decoder??=new TextDecoder("windows-1252");let t=this.decoder.decode(e);if(this.fileName=t.substring(0,100).replace(/\0/g,""),this.fileSize=parseInt(t.substring(124,136),8),this.fileType=t.substring(156,157),this.ustarFormat=t.substring(257,263),-1!==this.ustarFormat.indexOf("ustar")){let e=t.substring(345,500).replace(/\0/g,"");e.length>0&&(this.fileName=e.trim()+this.fileName.trim());}this.bytesRead+=512;}if(this.headerRead){if(this.bytesReceived<this.bytesRead+this.fileSize)return false;if(""===this.fileType||"0"===this.fileType){let e=new DataView(this.data.buffer,this.bytesRead,this.fileSize),t={name:this.prefix+this.fileName,size:this.fileSize,data:e};this.fire("file",t);}this.bytesRead+=this.fileSize,this.headerRead=false;let e=this.bytesRead%this.paddingSize;return 0!==e&&(this.bytesRead+=this.paddingSize-e),true}return false}}class xH{constructor(e,t){this.handlerType="",this._maxRetries=0,this._app=e,this.handlerType=t;}set maxRetries(e){this._maxRetries=e;}get maxRetries(){return this._maxRetries}load(e,t,i){}open(e,t,i){return t}patch(e,t){}}class xW extends xH{constructor(e){super(e,"bundle"),this._assets=e.assets;}_fetchRetries(e,t,i=0){return new Promise((s,r)=>{let a=()=>{fetch(e,t).then(s).catch(e=>{++i<this.maxRetries?a():r(e);});};a();})}load(e,t){"string"==typeof e&&(e={load:e,original:e}),this._fetchRetries(e.load,{mode:"cors"},this.maxRetries).then(e=>{let i=new xz;t(null,i);let s=new xG(e,this._assets.prefix);s.on("file",e=>{i.addFile(e.name,e.data);}),s.on("done",()=>{i.loaded=true;}),s.on("error",e=>{t(e);});}).catch(e=>{t(e);});}open(e,t){return t}}class xX{constructor(e){this._handlers={},this._requests={},this._cache={},this._app=e;}addHandler(e,t){this._handlers[e]=t,t._loader=this;}removeHandler(e){delete this._handlers[e];}getHandler(e){return this._handlers[e]}static makeKey(e,t){return `${e}-${t}`}load(e,t,i,s,r){let a=this._handlers[t];if(!a)return void i(`No resource handler for asset type: '${t}' when loading [${e}]`);if(!e)return void this._loadNull(a,i,s);let n=xX.makeKey(e,t);if(void 0!==this._cache[n])i(null,this._cache[n]);else if(this._requests[n])this._requests[n].push(i);else {this._requests[n]=[i];let t=this,o=function(e,i){if(e)return void t._onFailure(n,e);if(i.load instanceof DataView){if(a.openBinary){if(!t._requests[n])return;try{let e=a.openBinary(i.load);t._onSuccess(n,e);}catch(e){t._onFailure(n,e);}return}i.load=URL.createObjectURL(new Blob([i.load])),s&&(s.urlObject&&URL.revokeObjectURL(s.urlObject),s.urlObject=i.load);}a.load(i,(e,r,o)=>{if(t._requests[n]){if(e)return void t._onFailure(n,e);try{t._onSuccess(n,a.open(i.original,r,s),o);}catch(e){t._onFailure(n,e);}}},s);},l=e.split("?")[0];if(this._app.enableBundles&&this._app.bundles.hasUrl(l)&&!(r&&r.bundlesIgnore)){if(!this._app.bundles.urlIsLoadedOrLoading(l)){let e,t=this._app.bundles.listBundlesForAsset(s);r&&r.bundlesFilter&&(e=r.bundlesFilter(t)),e||(t?.sort((e,t)=>e.file.size-t.file.size),e=t?.[0]),e&&this._app.assets?.load(e);}this._app.bundles.loadUrl(l,(e,t)=>{o(e,{load:t,original:l});});}else o(null,{load:e,original:s&&s.file.filename||e});}}_loadNull(e,t,i){e.load(null,function(s,r,a){if(s)t(s);else try{t(null,e.open(null,r,i),a);}catch(e){t(e);}},i);}_onSuccess(e,t,i){null!==t?this._cache[e]=t:delete this._cache[e];for(let s=0;s<this._requests[e].length;s++)this._requests[e][s](null,t,i);delete this._requests[e];}_onFailure(e,t){if(this._requests[e]){for(let i=0;i<this._requests[e].length;i++)this._requests[e][i](t);delete this._requests[e];}}open(e,t){let i=this._handlers[e];return i?i.open(null,t):t}patch(e,t){let i=this._handlers[e.type];i&&i.patch&&i.patch(e,t);}clearCache(e,t){let i=xX.makeKey(e,t);delete this._cache[i];}getFromCache(e,t){let i=xX.makeKey(e,t);if(this._cache[i])return this._cache[i]}enableRetry(e=5){for(let t in e=Math.max(0,e)||0,this._handlers)this._handlers[t].maxRetries=e;}disableRetry(){for(let e in this._handlers)this._handlers[e].maxRetries=0;}destroy(){this._handlers={},this._requests={},this._cache={};}}class xY{_validate(e){if(!e.header)throw Error('pc.I18n#addData: Missing "header" field');if(!e.header.version)throw Error('pc.I18n#addData: Missing "header.version" field');if(1!==e.header.version)throw Error('pc.I18n#addData: Invalid "header.version" field');if(e.data){if(!Array.isArray(e.data))throw Error('pc.I18n#addData: "data" field must be an array')}else throw Error('pc.I18n#addData: Missing "data" field');for(let t=0,i=e.data.length;t<i;t++){let i=e.data[t];if(!i.info)throw Error(`pc.I18n#addData: missing "data[${t}].info" field`);if(!i.info.locale)throw Error(`pc.I18n#addData: missing "data[${t}].info.locale" field`);if("string"!=typeof i.info.locale)throw Error(`pc.I18n#addData: "data[${t}].info.locale" must be a string`);if(!i.messages)throw Error(`pc.I18n#addData: missing "data[${t}].messages" field`)}}parse(e){return e.data}}class xq extends eo{static{this.EVENT_CHANGE="change";}constructor(e){super(),this.locale=xh,this._translations={},this._availableLangs={},this._app=e,this._assets=[],this._parser=new xY;}set assets(e){let t={};for(let i=0,s=e.length;i<s;i++)t[e[i]instanceof xF?e[i].id:e[i]]=true;let i=this._assets.length;for(;i--;){let e=this._assets[i];if(!t[e]){this._app.assets.off(`add:${e}`,this._onAssetAdd,this);let t=this._app.assets.get(e);t&&this._onAssetRemove(t),this._assets.splice(i,1);}}for(let e in t){let t=parseInt(e,10);if(-1!==this._assets.indexOf(t))continue;this._assets.push(t);let i=this._app.assets.get(t);i?this._onAssetAdd(i):this._app.assets.once(`add:${t}`,this._onAssetAdd,this);}}get assets(){return this._assets}set locale(e){if(this._locale===e)return;let t=xf(e);if("in"===t&&(e=function(e,t){let i=e.indexOf("-");return -1!==i?t+e.substring(i):t}(e,t="id"),this._locale===e))return;let i=this._locale;this._locale=e,this._lang=t,this._pluralFn=xd[this._lang]||xm,this.fire(xq.EVENT_CHANGE,e,i);}get locale(){return this._locale}static findAvailableLocale(e,t){return xp(e,t)}findAvailableLocale(e){if(this._translations[e])return e;let t=xf(e);return this._findFallbackLocale(e,t)}getText(e,t){let i,s=e;t||(t=this._locale,i=this._lang);let r=this._translations[t];return r||(i||(i=xf(t)),t=this._findFallbackLocale(t,i),r=this._translations[t]),r&&r.hasOwnProperty(e)&&(Array.isArray(s=r[e])&&(s=s[0]),null==s&&(s=e)),s}getPluralText(e,t,i){let s,r,a=e;i?r=xd[s=xf(i)]||xm:(i=this._locale,s=this._lang,r=this._pluralFn);let n=this._translations[i];if(n||(r=xd[s=xf(i=this._findFallbackLocale(i,s))]||xm,n=this._translations[i]),n&&n[e]&&r){let i=r(t);null==(a=n[e][i])&&(a=e);}return a}addData(e){let t;try{t=this._parser.parse(e);}catch(e){return}for(let e=0,i=t.length;e<i;e++){let i=t[e],s=i.info.locale,r=i.messages;if(!this._translations[s]){this._translations[s]={};let e=xf(s);this._availableLangs[e]||(this._availableLangs[e]=s);}Object.assign(this._translations[s],r),this.fire("data:add",s,r);}}removeData(e){let t;try{t=this._parser.parse(e);}catch(e){return}for(let e=0,i=t.length;e<i;e++){let i=t[e],s=i.info.locale,r=this._translations[s];if(!r)continue;let a=i.messages;for(let e in a)delete r[e];0===Object.keys(r).length&&(delete this._translations[s],delete this._availableLangs[xf(s)]),this.fire("data:remove",s,a);}}destroy(){this._translations=null,this._availableLangs=null,this._assets=null,this._parser=null,this.off();}_findFallbackLocale(e,t){let i=xc[e];return i&&this._translations[i]||(i=xc[t])&&this._translations[i]||(i=this._availableLangs[t])&&this._translations[i]?i:xh}_onAssetAdd(e){e.on("load",this._onAssetLoad,this),e.on("change",this._onAssetChange,this),e.on("remove",this._onAssetRemove,this),e.on("unload",this._onAssetUnload,this),e.resource&&this._onAssetLoad(e);}_onAssetLoad(e){this.addData(e.resource);}_onAssetChange(e){e.resource&&this.addData(e.resource);}_onAssetRemove(e){e.off("load",this._onAssetLoad,this),e.off("change",this._onAssetChange,this),e.off("remove",this._onAssetRemove,this),e.off("unload",this._onAssetUnload,this),e.resource&&this.removeData(e.resource),this._app.assets.once(`add:${e.id}`,this._onAssetAdd,this);}_onAssetUnload(e){e.resource&&this.removeData(e.resource);}}class x$ extends eo{constructor(e){super(),this._scripts={},this._list=[],this._scriptSchemas=new Map,this.app=e;}destroy(){this.app=null,this.off();}addSchema(e,t){t&&this._scriptSchemas.set(e,t);}getSchema(e){return this._scriptSchemas.get(e)}add(e){let t=e.__name;return this._scripts.hasOwnProperty(t)?(setTimeout(()=>{if(e.prototype.swap){let i=this._scripts[t],s=this._list.indexOf(i);this._list[s]=e,this._scripts[t]=e,this.fire("swap",t,e),this.fire(`swap:${t}`,e);}}),false):(this._scripts[t]=e,this._list.push(e),this.fire("add",t,e),this.fire(`add:${t}`,e),setTimeout(()=>{let e;if(!this._scripts.hasOwnProperty(t)||!this.app||!this.app.systems||!this.app.systems.script)return;let i=this.app.systems.script._components,s=[],r=[];for(i.loopIndex=0;i.loopIndex<i.length;i.loopIndex++){let r=i.items[i.loopIndex];if(r._scriptsIndex[t]&&r._scriptsIndex[t].awaiting){r._scriptsData&&r._scriptsData[t]&&(e=r._scriptsData[t].attributes);let i=r.create(t,{preloading:true,ind:r._scriptsIndex[t].ind,attributes:e});for(let e of(i&&s.push(i),r.scripts))r.initializeAttributes(e);}}for(let e=0;e<s.length;e++)s[e].enabled&&(s[e]._initialized=true,r.push(s[e]),s[e].initialize&&s[e].initialize());for(let e=0;e<r.length;e++)r[e].enabled&&!r[e]._postInitialized&&(r[e]._postInitialized=true,r[e].postInitialize&&r[e].postInitialize());}),true)}remove(e){let t=e,i=e;if("string"!=typeof i?i=t.__name:t=this.get(i),this.get(i)!==t)return false;delete this._scripts[i];let s=this._list.indexOf(t);return this._list.splice(s,1),this.fire("remove",i,t),this.fire(`remove:${i}`,t),true}get(e){return this._scripts[e]||null}has(e){if("string"==typeof e)return this._scripts.hasOwnProperty(e);if(!e)return false;let t=e.__name;return this._scripts[t]===e}list(){return this._list}}let xj=(e,t)=>e.constructor.order-t.constructor.order,xK=e=>e.sort(xj),xZ=[],xQ=[],xJ=()=>xQ.pop()??[],x0=e=>{e.length=0,xQ.push(e);};class x1 extends _c{static{this.EVENT_DESTROY="destroy";}constructor(e,t=s){super(e),this.c={},this._destroying=false,this._guid=null,this._template=false,this._app=t;}addComponent(e,t){let i=this._app.systems[e];return !i||this.c[e]?null:i.addComponent(this,t)}removeComponent(e){let t=this._app.systems[e];t&&this.c[e]&&t.removeComponent(this);}findComponent(e){let t=this.findOne(t=>t.c?.[e]);return t&&t.c[e]}findComponents(e){return this.find(t=>t.c?.[e]).map(t=>t.c[e])}findScript(e){let t=this.findOne(t=>t.c?.script?.has(e));return t?.c.script.get(e)}findScripts(e){return this.find(t=>t.c?.script?.has(e)).map(t=>t.c.script.get(e))}getGuid(){return this._guid||this.setGuid(H.create()),this._guid}setGuid(e){let t=this._app._entityIndex;this._guid&&delete t[this._guid],this._guid=e,t[this._guid]=this;}_notifyHierarchyStateChanged(e,t){let i=false;e===this&&0===xZ.length&&(i=true),e._beingEnabled=true,e._onHierarchyStateChanged(t),e._onHierarchyStatePostChanged&&xZ.push(e);let s=e._children;for(let e=0,i=s.length;e<i;e++)s[e]._enabled&&this._notifyHierarchyStateChanged(s[e],t);if(e._beingEnabled=false,i){for(let e=0;e<xZ.length;e++)xZ[e]._onHierarchyStatePostChanged();xZ.length=0;}}_onHierarchyStateChanged(e){super._onHierarchyStateChanged(e);let t=this._getSortedComponents();for(let i=0;i<t.length;i++){let s=t[i];s.enabled&&(e?s.onEnable():s.onDisable());}x0(t);}_onHierarchyStatePostChanged(){let e=this._getSortedComponents();for(let t=0;t<e.length;t++)e[t].onPostStateChange();x0(e);}findByGuid(e){if(this._guid===e)return this;let t=this._app._entityIndex[e];return t&&(t===this||t.isDescendantOf(this))?t:null}destroy(){for(let e in this._destroying=true,this.c)this.c[e].enabled=false;for(let e in this.c)this.c[e].system.removeComponent(this);super.destroy(),this._guid&&delete this._app._entityIndex[this._guid],this._destroying=false;}clone(){let e={},t=this._cloneRecursively(e);return e[this.getGuid()]=t,function e(t,i,s,r){if(i instanceof x1){let a=i.c;for(let e in a){let i=a[e],n=i.system.getPropertiesOfType("entity");for(let a=0,o=n.length;a<o;a++){let o=n[a].name,l=i[o];if(t.findByGuid(l)){let t=r[l].getGuid();t&&(s.c[e][o]=t);}}}a.script&&s.script.resolveDuplicatedEntityReferenceProperties(a.script,r),a.render&&s.render.resolveDuplicatedEntityReferenceProperties(a.render,r),a.button&&s.button.resolveDuplicatedEntityReferenceProperties(a.button,r),a.scrollview&&s.scrollview.resolveDuplicatedEntityReferenceProperties(a.scrollview,r),a.scrollbar&&s.scrollbar.resolveDuplicatedEntityReferenceProperties(a.scrollbar,r),a.anim&&s.anim.resolveDuplicatedEntityReferenceProperties(a.anim,r);let n=i.children.filter(e=>e instanceof x1),o=s.children.filter(e=>e instanceof x1);for(let i=0,s=n.length;i<s;i++)e(t,n[i],o[i],r);}}(this,this,t,e),t}_getSortedComponents(){let e=this.c,t=xJ(),i=0;for(let s in e)if(e.hasOwnProperty(s)){let r=e[s];i|=0!==r.constructor.order,t.push(r);}return i&&t.length>1&&xK(t),t}_cloneRecursively(e){let t=new this.constructor(void 0,this._app);for(let e in super._cloneInternal(t),this.c)this.c[e].system.cloneComponent(this,t);for(let i=0;i<this._children.length;i++){let s=this._children[i];if(s instanceof x1){let i=s._cloneRecursively(e);t.addChild(i),e[s.getGuid()]=i;}}return t}}class x2{constructor(e,t){this.data=null,this._loading=false,this._onLoadedCallbacks=[],this.name=e,this.url=t;}get loaded(){return !!this.data}get loading(){return this._loading}}class x3{constructor(e){this._list=[],this._index={},this._urlIndex={},this._app=e;}destroy(){this._app=null;}list(){return this._list}add(e,t){if(this._index.hasOwnProperty(e))return false;let i=new x2(e,t),s=this._list.push(i);return this._index[i.name]=s-1,this._urlIndex[i.url]=s-1,true}find(e){return this._index.hasOwnProperty(e)?this._list[this._index[e]]:null}findByUrl(e){return this._urlIndex.hasOwnProperty(e)?this._list[this._urlIndex[e]]:null}remove(e){if(this._index.hasOwnProperty(e)){let t=this._index[e],i=this._list[t];delete this._urlIndex[i.url],delete this._index[e],this._list.splice(t,1);for(let e=0;e<this._list.length;e++)i=this._list[e],this._index[i.name]=e,this._urlIndex[i.url]=e;}}_loadSceneData(e,t,i){let s=this._app,r=e;return ("string"==typeof e&&(e=this.findByUrl(r)||this.find(r)||new x2("Untitled",r)),r=e.url)?e.loaded?void i(null,e):void(s.assets&&s.assets.prefix&&!x_.test(r)&&(r=W.join(s.assets.prefix,r)),e._onLoadedCallbacks.push(i),!e._loading&&s.loader.getHandler("hierarchy").load(r,(i,s)=>{e.data=s,e._loading=false;for(let t=0;t<e._onLoadedCallbacks.length;t++)e._onLoadedCallbacks[t](i,e);t||(e.data=null),e._onLoadedCallbacks.length=0;}),e._loading=true):void i("Cannot find scene to load")}loadSceneData(e,t){this._loadSceneData(e,true,t);}unloadSceneData(e){"string"==typeof e&&(e=this.findByUrl(e)),e&&(e.data=null);}_loadSceneHierarchy(e,t,i){this._loadSceneData(e,false,(e,s)=>{if(e){i&&i(e);return}t&&t(s);let r=this._app;r._preloadScripts(s.data,()=>{let e=r.loader.getHandler("hierarchy");r.systems.script.preloading=true;let t=e.open(s.url,s.data);r.systems.script.preloading=false,r.loader.clearCache(s.url,"hierarchy"),r.root.addChild(t),r.systems.fire("initialize",t),r.systems.fire("postInitialize",t),r.systems.fire("postPostInitialize",t),i&&i(null,t);});});}loadSceneHierarchy(e,t){this._loadSceneHierarchy(e,null,t);}loadSceneSettings(e,t){this._loadSceneData(e,false,(e,i)=>{e?t&&t(e):(this._app.applySceneSettings(i.data.settings),t&&t(null));});}changeScene(e,t){let i=this._app;this._loadSceneHierarchy(e,e=>{let{children:t}=i.root;for(;t.length;)t[0].destroy();i.applySceneSettings(e.data.settings);},t);}loadScene(e,t){let i=this._app,s=i.loader.getHandler("scene");i.assets&&i.assets.prefix&&!x_.test(e)&&(e=W.join(i.assets.prefix,e)),s.load(e,(r,a)=>{r?t&&t(r):i._preloadScripts(a,()=>{i.systems.script.preloading=true;let r=s.open(e,a),n=this.findByUrl(e);n&&!n.loaded&&(n.data=a),i.systems.script.preloading=false,i.loader.clearCache(e,"scene"),i.loader.patch({resource:r,type:"scene"},i.assets),i.root.addChild(r.root),i.systems.rigidbody&&"undefined"!=typeof Ammo&&i.systems.rigidbody.gravity.set(r._gravity.x,r._gravity.y,r._gravity.z),t&&t(null,r);});});}}class x4{constructor(e){this.frame={fps:0,ms:0,dt:0,updateStart:0,updateTime:0,renderStart:0,renderTime:0,physicsStart:0,physicsTime:0,cullTime:0,sortTime:0,skinTime:0,morphTime:0,instancingTime:0,triangles:0,otherPrimitives:0,shaders:0,materials:0,cameras:0,shadowMapUpdates:0,shadowMapTime:0,depthMapTime:0,forwardTime:0,lightClustersTime:0,lightClusters:0,_timeToCountFrames:0,_fpsAccum:0},this.drawCalls={forward:0,depth:0,shadow:0,immediate:0,misc:0,total:0,skinned:0,instanced:0,removedByInstancing:0},this.misc={renderTargetCreationTime:0},this.particles={updatesPerFrame:0,_updatesPerFrame:0,frameTime:0,_frameTime:0},this.shaders=e._shaderStats,this.vram=e._vram,Object.defineProperty(this.vram,"totalUsed",{get:function(){return this.tex+this.vb+this.ib}}),Object.defineProperty(this.vram,"geom",{get:function(){return this.vb+this.ib}});}get scene(){return s.scene._stats}get lightmapper(){return s.lightmapper?.stats}get batcher(){let e=s._batcher;return e?e._stats:null}}let x5={alphaTestPS:`
uniform float alpha_ref;
void alphaTest(float a) {
if (a < alpha_ref) discard;
}
`,ambientPS:`
#ifdef LIT_AMBIENT_SOURCE == AMBIENTSH
uniform vec3 ambientSH[9];
#endif
#if LIT_AMBIENT_SOURCE == ENVALATLAS
#include "envAtlasPS"
#ifndef ENV_ATLAS
#define ENV_ATLAS
uniform sampler2D texture_envAtlas;
#endif
#endif
void addAmbient(vec3 worldNormal) {
#ifdef LIT_AMBIENT_SOURCE == AMBIENTSH
vec3 n = cubeMapRotate(worldNormal);
vec3 color =
ambientSH[0] +
ambientSH[1] * n.x +
ambientSH[2] * n.y +
ambientSH[3] * n.z +
ambientSH[4] * n.x * n.z +
ambientSH[5] * n.z * n.y +
ambientSH[6] * n.y * n.x +
ambientSH[7] * (3.0 * n.z * n.z - 1.0) +
ambientSH[8] * (n.x * n.x - n.y * n.y);
dDiffuseLight += processEnvironment(max(color, vec3(0.0)));
#endif
#if LIT_AMBIENT_SOURCE == ENVALATLAS
vec3 dir = normalize(cubeMapRotate(worldNormal) * vec3(-1.0, 1.0, 1.0));
vec2 uv = mapUv(toSphericalUv(dir), vec4(128.0, 256.0 + 128.0, 64.0, 32.0) / atlasSize);
vec4 raw = texture2D(texture_envAtlas, uv);
vec3 linear = {ambientDecode}(raw);
dDiffuseLight += processEnvironment(linear);
#endif
#if LIT_AMBIENT_SOURCE == CONSTANT
dDiffuseLight += light_globalAmbient;
#endif
}
`,anisotropyPS:`
#ifdef LIT_GGX_SPECULAR
uniform float material_anisotropyIntensity;
uniform vec2 material_anisotropyRotation;
#endif
void getAnisotropy() {
dAnisotropy = 0.0;
dAnisotropyRotation = vec2(1.0, 0.0);
#ifdef LIT_GGX_SPECULAR
dAnisotropy = material_anisotropyIntensity;
dAnisotropyRotation = material_anisotropyRotation;
#endif
#ifdef STD_ANISOTROPY_TEXTURE
vec3 anisotropyTex = texture2DBias({STD_ANISOTROPY_TEXTURE_NAME}, {STD_ANISOTROPY_TEXTURE_UV}, textureBias).rgb;
dAnisotropy *= anisotropyTex.b;
vec2 anisotropyRotationFromTex = anisotropyTex.rg * 2.0 - vec2(1.0);
mat2 rotationMatrix = mat2(dAnisotropyRotation.x, dAnisotropyRotation.y, -dAnisotropyRotation.y, dAnisotropyRotation.x);
dAnisotropyRotation = rotationMatrix * anisotropyRotationFromTex;
#endif
dAnisotropy = clamp(dAnisotropy, 0.0, 1.0);
}
`,aoPS:`
#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX)
uniform float material_aoIntensity;
#endif
#ifdef STD_AODETAIL_TEXTURE
#include "detailModesPS"
#endif
void getAO() {
dAo = 1.0;
#ifdef STD_AO_TEXTURE
float aoBase = texture2DBias({STD_AO_TEXTURE_NAME}, {STD_AO_TEXTURE_UV}, textureBias).{STD_AO_TEXTURE_CHANNEL};
#ifdef STD_AODETAIL_TEXTURE
float aoDetail = texture2DBias({STD_AODETAIL_TEXTURE_NAME}, {STD_AODETAIL_TEXTURE_UV}, textureBias).{STD_AODETAIL_TEXTURE_CHANNEL};
aoBase = detailMode_{STD_AODETAIL_DETAILMODE}(vec3(aoBase), vec3(aoDetail)).r;
#endif
dAo *= aoBase;
#endif
#ifdef STD_AO_VERTEX
dAo *= saturate(vVertexColor.{STD_AO_VERTEX_CHANNEL});
#endif
#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX)
dAo = mix(1.0, dAo, material_aoIntensity);
#endif
}
`,aoDiffuseOccPS:`
void occludeDiffuse(float ao) {
dDiffuseLight *= ao;
}
`,aoSpecOccPS:`
#if LIT_OCCLUDE_SPECULAR != NONE
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
uniform float material_occludeSpecularIntensity;
#endif
#endif
void occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) {
#if LIT_OCCLUDE_SPECULAR == AO
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
float specOcc = mix(1.0, ao, material_occludeSpecularIntensity);
#else
float specOcc = ao;
#endif
#endif
#if LIT_OCCLUDE_SPECULAR == GLOSSDEPENDENT
float specPow = exp2(gloss * 11.0);
float specOcc = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01 * specPow) - 1.0 + ao);
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
specOcc = mix(1.0, specOcc, material_occludeSpecularIntensity);
#endif
#endif
#if LIT_OCCLUDE_SPECULAR != NONE
dSpecularLight *= specOcc;
dReflection *= specOcc;
#ifdef LIT_SHEEN
sSpecularLight *= specOcc;
sReflection *= specOcc;
#endif
#endif
}
`,bakeDirLmEndPS:`
vec4 dirLm = texture2D(texture_dirLightMap, vUv1);
if (bakeDir > 0.5) {
if (dAtten > 0.00001) {
dirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0);
dAtten = saturate(dAtten);
gl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5);
gl_FragColor.a = dirLm.w + dAtten;
gl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0);
} else {
gl_FragColor = dirLm;
}
} else {
gl_FragColor.rgb = dirLm.xyz;
gl_FragColor.a = max(dirLm.w, dAtten > 0.00001 ? (1.0/255.0) : 0.0);
}
`,bakeLmEndPS:`
#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT
dDiffuseLight = ((dDiffuseLight - 0.5) * max(ambientBakeOcclusionContrast + 1.0, 0.0)) + 0.5;
dDiffuseLight += vec3(ambientBakeOcclusionBrightness);
dDiffuseLight = saturate(dDiffuseLight);
dDiffuseLight *= dAmbientLight;
#endif
#ifdef LIGHTMAP_RGBM
gl_FragColor.rgb = dDiffuseLight;
gl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.5));
gl_FragColor.rgb /= 8.0;
gl_FragColor.a = clamp( max( max( gl_FragColor.r, gl_FragColor.g ), max( gl_FragColor.b, 1.0 / 255.0 ) ), 0.0,1.0 );
gl_FragColor.a = ceil(gl_FragColor.a * 255.0) / 255.0;
gl_FragColor.rgb /= gl_FragColor.a;
#else
gl_FragColor = vec4(dDiffuseLight, 1.0);
#endif
`,basePS:`
uniform vec3 view_position;
uniform vec3 light_globalAmbient;
float square(float x) {
return x*x;
}
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
vec3 saturate(vec3 x) {
return clamp(x, vec3(0.0), vec3(1.0));
}
`,baseNineSlicedPS:`
#define NINESLICED
varying vec2 vMask;
varying vec2 vTiledUv;
uniform mediump vec4 innerOffset;
uniform mediump vec2 outerScale;
uniform mediump vec4 atlasRect;
vec2 nineSlicedUv;
`,baseNineSlicedTiledPS:`
#define NINESLICED
#define NINESLICETILED
varying vec2 vMask;
varying vec2 vTiledUv;
uniform mediump vec4 innerOffset;
uniform mediump vec2 outerScale;
uniform mediump vec4 atlasRect;
vec2 nineSlicedUv;
`,bayerPS:`
float bayer2(vec2 p) {
return mod(2.0 * p.y + p.x + 1.0, 4.0);
}
float bayer4(vec2 p) {
vec2 p1 = mod(p, 2.0);
vec2 p2 = floor(0.5 * mod(p, 4.0));
return 4.0 * bayer2(p1) + bayer2(p2);
}
float bayer8(vec2 p) {
vec2 p1 = mod(p, 2.0);
vec2 p2 = floor(0.5 * mod(p, 4.0));
vec2 p4 = floor(0.25 * mod(p, 8.0));
return 4.0 * (4.0 * bayer2(p1) + bayer2(p2)) + bayer2(p4);
}
`,blurVSMPS:`
varying vec2 vUv0;
uniform sampler2D source;
uniform vec2 pixelOffset;
#ifdef GAUSS
uniform float weight[{SAMPLES}];
#endif
void main(void) {
vec3 moments = vec3(0.0);
vec2 uv = vUv0 - pixelOffset * (float({SAMPLES}) * 0.5);
for (int i = 0; i < {SAMPLES}; i++) {
vec4 c = texture2D(source, uv + pixelOffset * float(i));
#ifdef GAUSS
moments += c.xyz * weight[i];
#else
moments += c.xyz;
#endif
}
#ifndef GAUSS
moments *= 1.0 / float({SAMPLES});
#endif
gl_FragColor = vec4(moments.x, moments.y, moments.z, 1.0);
}
`,clearCoatPS:`
uniform float material_clearCoat;
void getClearCoat() {
ccSpecularity = material_clearCoat;
#ifdef STD_CLEARCOAT_TEXTURE
ccSpecularity *= texture2DBias({STD_CLEARCOAT_TEXTURE_NAME}, {STD_CLEARCOAT_TEXTURE_UV}, textureBias).{STD_CLEARCOAT_TEXTURE_CHANNEL};
#endif
#ifdef STD_CLEARCOAT_VERTEX
ccSpecularity *= saturate(vVertexColor.{STD_CLEARCOAT_VERTEX_CHANNEL});
#endif
}
`,clearCoatGlossPS:`
uniform float material_clearCoatGloss;
void getClearCoatGlossiness() {
ccGlossiness = material_clearCoatGloss;
#ifdef STD_CLEARCOATGLOSS_TEXTURE
ccGlossiness *= texture2DBias({STD_CLEARCOATGLOSS_TEXTURE_NAME}, {STD_CLEARCOATGLOSS_TEXTURE_UV}, textureBias).{STD_CLEARCOATGLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_CLEARCOATGLOSS_VERTEX
ccGlossiness *= saturate(vVertexColor.{STD_CLEARCOATGLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_CLEARCOATGLOSS_INVERT
ccGlossiness = 1.0 - ccGlossiness;
#endif
ccGlossiness += 0.0000001;
}
`,clearCoatNormalPS:`
#ifdef STD_CLEARCOATNORMAL_TEXTURE
uniform float material_clearCoatBumpiness;
#endif
void getClearCoatNormal() {
#ifdef STD_CLEARCOATNORMAL_TEXTURE
vec3 normalMap = {STD_CLEARCOATNORMAL_TEXTURE_DECODE}(texture2DBias({STD_CLEARCOATNORMAL_TEXTURE_NAME}, {STD_CLEARCOATNORMAL_TEXTURE_UV}, textureBias));
normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_clearCoatBumpiness);
ccNormalW = normalize(dTBN * normalMap);
#else
ccNormalW = dVertexNormalW;
#endif
}
`,clusteredLightCookiesPS:`
vec3 _getCookieClustered(TEXTURE_ACCEPT(tex), vec2 uv, float intensity, vec4 cookieChannel) {
vec4 pixel = mix(vec4(1.0), texture2DLod(tex, uv, 0.0), intensity);
bool isRgb = dot(cookieChannel.rgb, vec3(1.0)) == 3.0;
return isRgb ? pixel.rgb : vec3(dot(pixel, cookieChannel));
}
vec3 getCookie2DClustered(TEXTURE_ACCEPT(tex), mat4 transform, vec3 worldPosition, float intensity, vec4 cookieChannel) {
vec4 projPos = transform * vec4(worldPosition, 1.0);
return _getCookieClustered(TEXTURE_PASS(tex), projPos.xy / projPos.w, intensity, cookieChannel);
}
vec3 getCookieCubeClustered(TEXTURE_ACCEPT(tex), vec3 dir, float intensity, vec4 cookieChannel, float shadowTextureResolution, float shadowEdgePixels, vec3 omniAtlasViewport) {
vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);
return _getCookieClustered(TEXTURE_PASS(tex), uv, intensity, cookieChannel);
}
`,clusteredLightShadowsPS:`
vec3 _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {
vec4 projPos = shadowMatrix * vec4(wPos, 1.0);
projPos.xyz /= projPos.w;
return projPos.xyz;
}
vec3 getShadowCoordPerspZbufferNormalOffset(mat4 shadowMatrix, vec4 shadowParams, vec3 normal) {
vec3 wPos = vPositionW + normal * shadowParams.y;
return _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);
}
vec3 normalOffsetPointShadow(vec4 shadowParams, vec3 lightPos, vec3 lightDir, vec3 lightDirNorm, vec3 normal) {
float distScale = length(lightDir);
vec3 wPos = vPositionW + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
vec3 dir = wPos - lightPos;
return dir;
}
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
float getShadowOmniClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {
float shadowTextureResolution = shadowParams.x;
vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;
return textureShadow(shadowMap, vec3(uv, shadowZ));
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF3)
float getShadowOmniClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {
float shadowTextureResolution = shadowParams.x;
vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;
vec3 shadowCoord = vec3(uv, shadowZ);
return getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF5)
float getShadowOmniClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {
float shadowTextureResolution = shadowParams.x;
vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;
vec3 shadowCoord = vec3(uv, shadowZ);
return getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
float getShadowSpotClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return textureShadow(shadowMap, shadowCoord);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF3)
float getShadowSpotClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return getShadowSpotPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF5)
float getShadowSpotClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);
}
#endif
`,clusteredLightUtilsPS:`
vec2 getCubemapFaceCoordinates(const vec3 dir, out float faceIndex, out vec2 tileOffset)
{
vec3 vAbs = abs(dir);
float ma;
vec2 uv;
if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) {
faceIndex = dir.z < 0.0 ? 5.0 : 4.0;
ma = 0.5 / vAbs.z;
uv = vec2(dir.z < 0.0 ? -dir.x : dir.x, -dir.y);
tileOffset.x = 2.0;
tileOffset.y = dir.z < 0.0 ? 1.0 : 0.0;
} else if(vAbs.y >= vAbs.x) {
faceIndex = dir.y < 0.0 ? 3.0 : 2.0;
ma = 0.5 / vAbs.y;
uv = vec2(dir.x, dir.y < 0.0 ? -dir.z : dir.z);
tileOffset.x = 1.0;
tileOffset.y = dir.y < 0.0 ? 1.0 : 0.0;
} else {
faceIndex = dir.x < 0.0 ? 1.0 : 0.0;
ma = 0.5 / vAbs.x;
uv = vec2(dir.x < 0.0 ? dir.z : -dir.z, -dir.y);
tileOffset.x = 0.0;
tileOffset.y = dir.x < 0.0 ? 1.0 : 0.0;
}
return uv * ma + 0.5;
}
vec2 getCubemapAtlasCoordinates(const vec3 omniAtlasViewport, float shadowEdgePixels, float shadowTextureResolution, const vec3 dir) {
float faceIndex;
vec2 tileOffset;
vec2 uv = getCubemapFaceCoordinates(dir, faceIndex, tileOffset);
float atlasFaceSize = omniAtlasViewport.z;
float tileSize = shadowTextureResolution * atlasFaceSize;
float offset = shadowEdgePixels / tileSize;
uv = uv * vec2(1.0 - offset * 2.0) + vec2(offset * 1.0);
uv *= atlasFaceSize;
uv += tileOffset * atlasFaceSize;
uv += omniAtlasViewport.xy;
return uv;
}
`,clusteredLightPS:`
#include "lightBufferDefinesPS"
#include "clusteredLightUtilsPS"
#ifdef CLUSTER_COOKIES
#include "clusteredLightCookiesPS"
#endif
#ifdef CLUSTER_SHADOWS
#include "clusteredLightShadowsPS"
#endif
uniform highp sampler2D clusterWorldTexture;
uniform highp sampler2D lightsTexture;
#ifdef CLUSTER_SHADOWS
uniform sampler2DShadow shadowAtlasTexture;
#endif
#ifdef CLUSTER_COOKIES
uniform sampler2D cookieAtlasTexture;
#endif
uniform int clusterMaxCells;
uniform float clusterSkip;
uniform vec3 clusterCellsCountByBoundsSize;
uniform vec3 clusterTextureSize;
uniform vec3 clusterBoundsMin;
uniform vec3 clusterBoundsDelta;
uniform vec3 clusterCellsDot;
uniform vec3 clusterCellsMax;
uniform vec2 shadowAtlasParams;
struct ClusterLightData {
uint flags;
vec3 halfWidth;
bool isSpot;
vec3 halfHeight;
int lightIndex;
vec3 position;
uint shape;
vec3 direction;
bool falloffModeLinear;
vec3 color;
float shadowIntensity;
vec3 omniAtlasViewport;
float range;
vec4 cookieChannelMask;
float biasesData;
float shadowBias;
float shadowNormalBias;
float anglesData;
float innerConeAngleCos;
float outerConeAngleCos;
float cookieIntensity;
bool isDynamic;
bool isLightmapped;
};
mat4 lightProjectionMatrix;
vec4 sampleLightTextureF(const ClusterLightData clusterLightData, int index) {
return texelFetch(lightsTexture, ivec2(index, clusterLightData.lightIndex), 0);
}
void decodeClusterLightCore(inout ClusterLightData clusterLightData, float lightIndex) {
clusterLightData.lightIndex = int(lightIndex);
vec4 halfData = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS});
clusterLightData.anglesData = halfData.z;
clusterLightData.biasesData = halfData.w;
vec2 colorRG = unpackHalf2x16(floatBitsToUint(halfData.x));
vec2 colorB_ = unpackHalf2x16(floatBitsToUint(halfData.y));
clusterLightData.color = vec3(colorRG, colorB_.x) * {LIGHT_COLOR_DIVIDER};
vec4 lightPosRange = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_POSITION_RANGE});
clusterLightData.position = lightPosRange.xyz;
clusterLightData.range = lightPosRange.w;
vec4 lightDir_Flags = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_DIRECTION_FLAGS});
clusterLightData.direction = lightDir_Flags.xyz;
clusterLightData.flags = floatBitsToUint(lightDir_Flags.w);
clusterLightData.isSpot = (clusterLightData.flags & (1u << 30u)) != 0u;
clusterLightData.shape = (clusterLightData.flags >> 28u) & 0x3u;
clusterLightData.falloffModeLinear = (clusterLightData.flags & (1u << 27u)) == 0u;
clusterLightData.shadowIntensity = float((clusterLightData.flags >> 0u) & 0xFFu) / 255.0;
clusterLightData.cookieIntensity = float((clusterLightData.flags >> 8u) & 0xFFu) / 255.0;
clusterLightData.isDynamic = (clusterLightData.flags & (1u << 22u)) != 0u;
clusterLightData.isLightmapped = (clusterLightData.flags & (1u << 21u)) != 0u;
}
void decodeClusterLightSpot(inout ClusterLightData clusterLightData) {
vec2 angles = unpackHalf2x16(floatBitsToUint(clusterLightData.anglesData));
clusterLightData.innerConeAngleCos = angles.x;
clusterLightData.outerConeAngleCos = angles.y;
}
void decodeClusterLightOmniAtlasViewport(inout ClusterLightData clusterLightData) {
clusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz;
}
void decodeClusterLightAreaData(inout ClusterLightData clusterLightData) {
clusterLightData.halfWidth = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz;
clusterLightData.halfHeight = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz;
}
void decodeClusterLightProjectionMatrixData(inout ClusterLightData clusterLightData) {
vec4 m0 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_0});
vec4 m1 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_1});
vec4 m2 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_2});
vec4 m3 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_3});
lightProjectionMatrix = mat4(m0, m1, m2, m3);
}
void decodeClusterLightShadowData(inout ClusterLightData clusterLightData) {
vec2 biases = unpackHalf2x16(floatBitsToUint(clusterLightData.biasesData));
clusterLightData.shadowBias = biases.x;
clusterLightData.shadowNormalBias = biases.y;
}
void decodeClusterLightCookieData(inout ClusterLightData clusterLightData) {
uint cookieFlags = (clusterLightData.flags >> 23u) & 0x0Fu;
clusterLightData.cookieChannelMask = vec4(uvec4(cookieFlags) & uvec4(1u, 2u, 4u, 8u));
clusterLightData.cookieChannelMask = step(1.0, clusterLightData.cookieChannelMask);
}
void evaluateLight(
ClusterLightData light,
vec3 worldNormal,
vec3 viewDir,
vec3 reflectionDir,
#if defined(LIT_CLEARCOAT)
vec3 clearcoatReflectionDir,
#endif
float gloss,
vec3 specularity,
vec3 geometricNormal,
mat3 tbn,
#if defined(LIT_IRIDESCENCE)
vec3 iridescenceFresnel,
#endif
vec3 clearcoat_worldNormal,
float clearcoat_gloss,
float sheen_gloss,
float iridescence_intensity
) {
vec3 cookieAttenuation = vec3(1.0);
float diffuseAttenuation = 1.0;
float falloffAttenuation = 1.0;
vec3 lightDirW = evalOmniLight(light.position);
vec3 lightDirNormW = normalize(lightDirW);
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
decodeClusterLightAreaData(light);
if (light.shape == {LIGHTSHAPE_RECT}) {
calcRectLightValues(light.position, light.halfWidth, light.halfHeight);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
calcDiskLightValues(light.position, light.halfWidth, light.halfHeight);
} else {
calcSphereLightValues(light.position, light.halfWidth, light.halfHeight);
}
falloffAttenuation = getFalloffWindow(light.range, lightDirW);
} else
#endif
{
if (light.falloffModeLinear)
falloffAttenuation = getFalloffLinear(light.range, lightDirW);
else
falloffAttenuation = getFalloffInvSquared(light.range, lightDirW);
}
if (falloffAttenuation > 0.00001) {
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
if (light.shape == {LIGHTSHAPE_RECT}) {
diffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
} else if (light.shape == {LIGHTSHAPE_DISK}) {
diffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
} else {
diffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
}
} else
#endif
{
falloffAttenuation *= getLightDiffuse(worldNormal, viewDir, lightDirNormW);
}
if (light.isSpot) {
decodeClusterLightSpot(light);
falloffAttenuation *= getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos, lightDirNormW);
}
#if defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS)
if (falloffAttenuation > 0.00001) {
if (light.shadowIntensity > 0.0 || light.cookieIntensity > 0.0) {
if (light.isSpot) {
decodeClusterLightProjectionMatrixData(light);
} else {
decodeClusterLightOmniAtlasViewport(light);
}
float shadowTextureResolution = shadowAtlasParams.x;
float shadowEdgePixels = shadowAtlasParams.y;
#ifdef CLUSTER_COOKIES
if (light.cookieIntensity > 0.0) {
decodeClusterLightCookieData(light);
if (light.isSpot) {
cookieAttenuation = getCookie2DClustered(TEXTURE_PASS(cookieAtlasTexture), lightProjectionMatrix, vPositionW, light.cookieIntensity, light.cookieChannelMask);
} else {
cookieAttenuation = getCookieCubeClustered(TEXTURE_PASS(cookieAtlasTexture), lightDirW, light.cookieIntensity, light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport);
}
}
#endif
#ifdef CLUSTER_SHADOWS
if (light.shadowIntensity > 0.0) {
decodeClusterLightShadowData(light);
vec4 shadowParams = vec4(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range);
if (light.isSpot) {
vec3 shadowCoord = getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal);
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
float shadow = getShadowSpotClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCF3)
float shadow = getShadowSpotClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCF5)
float shadow = getShadowSpotClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCSS)
float shadow = getShadowSpotClusteredPCSS(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);
#endif
falloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);
} else {
vec3 dir = normalOffsetPointShadow(shadowParams, light.position, lightDirW, lightDirNormW, geometricNormal);
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
float shadow = getShadowOmniClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);
#elif defined(CLUSTER_SHADOW_TYPE_PCF3)
float shadow = getShadowOmniClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);
#elif defined(CLUSTER_SHADOW_TYPE_PCF5)
float shadow = getShadowOmniClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);
#endif
falloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);
}
}
#endif
}
}
#endif
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
{
vec3 areaDiffuse = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation;
#if defined(LIT_SPECULAR)
areaDiffuse = mix(areaDiffuse, vec3(0), dLTCSpecFres);
#endif
dDiffuseLight += areaDiffuse;
}
#ifdef LIT_SPECULAR
float areaLightSpecular;
if (light.shape == {LIGHTSHAPE_RECT}) {
areaLightSpecular = getRectLightSpecular(worldNormal, viewDir);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
areaLightSpecular = getDiskLightSpecular(worldNormal, viewDir);
} else {
areaLightSpecular = getSphereLightSpecular(worldNormal, viewDir);
}
dSpecularLight += dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation;
#ifdef LIT_CLEARCOAT
float areaLightSpecularCC;
if (light.shape == {LIGHTSHAPE_RECT}) {
areaLightSpecularCC = getRectLightSpecular(clearcoat_worldNormal, viewDir);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
areaLightSpecularCC = getDiskLightSpecular(clearcoat_worldNormal, viewDir);
} else {
areaLightSpecularCC = getSphereLightSpecular(clearcoat_worldNormal, viewDir);
}
ccSpecularLight += ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
} else
#endif
{
{
vec3 punctualDiffuse = falloffAttenuation * light.color * cookieAttenuation;
#if defined(CLUSTER_AREALIGHTS)
#if defined(LIT_SPECULAR)
punctualDiffuse = mix(punctualDiffuse, vec3(0), specularity);
#endif
#endif
dDiffuseLight += punctualDiffuse;
}
#ifdef LIT_SPECULAR
vec3 halfDir = normalize(-lightDirNormW + viewDir);
#ifdef LIT_SPECULAR_FRESNEL
dSpecularLight +=
getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation *
getFresnel(
dot(viewDir, halfDir),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescence_intensity
#endif
);
#else
dSpecularLight += getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity;
#endif
#ifdef LIT_CLEARCOAT
#ifdef LIT_SPECULAR_FRESNEL
ccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir));
#else
ccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
#ifdef LIT_SHEEN
sSpecularLight += getLightSpecularSheen(halfDir, worldNormal, viewDir, lightDirNormW, sheen_gloss) * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
}
}
dAtten = falloffAttenuation;
dLightDirNormW = lightDirNormW;
}
void evaluateClusterLight(
float lightIndex,
vec3 worldNormal,
vec3 viewDir,
vec3 reflectionDir,
#if defined(LIT_CLEARCOAT)
vec3 clearcoatReflectionDir,
#endif
float gloss,
vec3 specularity,
vec3 geometricNormal,
mat3 tbn,
#if defined(LIT_IRIDESCENCE)
vec3 iridescenceFresnel,
#endif
vec3 clearcoat_worldNormal,
float clearcoat_gloss,
float sheen_gloss,
float iridescence_intensity
) {
ClusterLightData clusterLightData;
decodeClusterLightCore(clusterLightData, lightIndex);
#ifdef CLUSTER_MESH_DYNAMIC_LIGHTS
bool acceptLightMask = clusterLightData.isDynamic;
#else
bool acceptLightMask = clusterLightData.isLightmapped;
#endif
if (acceptLightMask)
evaluateLight(
clusterLightData,
worldNormal,
viewDir,
reflectionDir,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir,
#endif
gloss,
specularity,
geometricNormal,
tbn,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
clearcoat_worldNormal,
clearcoat_gloss,
sheen_gloss,
iridescence_intensity
);
}
void addClusteredLights(
vec3 worldNormal,
vec3 viewDir,
vec3 reflectionDir,
#if defined(LIT_CLEARCOAT)
vec3 clearcoatReflectionDir,
#endif
float gloss,
vec3 specularity,
vec3 geometricNormal,
mat3 tbn,
#if defined(LIT_IRIDESCENCE)
vec3 iridescenceFresnel,
#endif
vec3 clearcoat_worldNormal,
float clearcoat_gloss,
float sheen_gloss,
float iridescence_intensity
) {
if (clusterSkip > 0.5)
return;
vec3 cellCoords = floor((vPositionW - clusterBoundsMin) * clusterCellsCountByBoundsSize);
if (!(any(lessThan(cellCoords, vec3(0.0))) || any(greaterThanEqual(cellCoords, clusterCellsMax)))) {
float cellIndex = dot(clusterCellsDot, cellCoords);
float clusterV = floor(cellIndex * clusterTextureSize.y);
float clusterU = cellIndex - (clusterV * clusterTextureSize.x);
for (int lightCellIndex = 0; lightCellIndex < clusterMaxCells; lightCellIndex++) {
float lightIndex = texelFetch(clusterWorldTexture, ivec2(int(clusterU) + lightCellIndex, clusterV), 0).x;
if (lightIndex <= 0.0)
break;
evaluateClusterLight(
lightIndex * 255.0,
worldNormal,
viewDir,
reflectionDir,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir,
#endif
gloss,
specularity,
geometricNormal,
tbn,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
clearcoat_worldNormal,
clearcoat_gloss,
sheen_gloss,
iridescence_intensity
);
}
}
}
`,combinePS:`
vec3 combineColor(vec3 albedo, vec3 sheenSpecularity, float clearcoatSpecularity) {
vec3 ret = vec3(0);
#ifdef LIT_OLD_AMBIENT
ret += (dDiffuseLight - light_globalAmbient) * albedo + material_ambient * light_globalAmbient;
#else
ret += albedo * dDiffuseLight;
#endif
#ifdef LIT_SPECULAR
ret += dSpecularLight;
#endif
#ifdef LIT_REFLECTIONS
ret += dReflection.rgb * dReflection.a;
#endif
#ifdef LIT_SHEEN
float sheenScaling = 1.0 - max(max(sheenSpecularity.r, sheenSpecularity.g), sheenSpecularity.b) * 0.157;
ret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sheenSpecularity;
#endif
#ifdef LIT_CLEARCOAT
float clearCoatScaling = 1.0 - ccFresnel * clearcoatSpecularity;
ret = ret * clearCoatScaling + (ccSpecularLight + ccReflection) * clearcoatSpecularity;
#endif
return ret;
}
`,cookieBlit2DPS:`
varying vec2 uv0;
uniform sampler2D blitTexture;
void main(void) {
gl_FragColor = texture2D(blitTexture, uv0);
}
`,cookieBlitCubePS:`
varying vec2 uv0;
uniform samplerCube blitTexture;
uniform mat4 invViewProj;
void main(void) {
vec4 projPos = vec4(uv0 * 2.0 - 1.0, 0.5, 1.0);
vec4 worldPos = invViewProj * projPos;
gl_FragColor = textureCube(blitTexture, worldPos.xyz);
}
`,cookieBlitVS:`
attribute vec2 vertex_position;
varying vec2 uv0;
void main(void) {
gl_Position = vec4(vertex_position, 0.5, 1.0);
uv0 = vertex_position.xy * 0.5 + 0.5;
#ifndef WEBGPU
uv0.y = 1.0 - uv0.y;
#endif
}
`,cookiePS:`
vec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) {
vec4 projPos = transform * vec4(vPositionW, 1.0);
projPos.xy /= projPos.w;
return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);
}
vec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) {
vec4 projPos = transform * vec4(vPositionW, 1.0);
projPos.xy /= projPos.w;
if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);
return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);
}
vec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {
vec4 projPos = transform * vec4(vPositionW, 1.0);
projPos.xy /= projPos.w;
projPos.xy += cookieOffset;
vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);
return mix(vec4(1.0), texture2D(tex, uv), intensity);
}
vec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {
vec4 projPos = transform * vec4(vPositionW, 1.0);
projPos.xy /= projPos.w;
projPos.xy += cookieOffset;
if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);
vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);
return mix(vec4(1.0), texture2D(tex, uv), intensity);
}
vec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) {
return mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity);
}
`,cubeMapProjectPS:`
#if LIT_CUBEMAP_PROJECTION == BOX
uniform vec3 envBoxMin;
uniform vec3 envBoxMax;
#endif
vec3 cubeMapProject(vec3 nrdir) {
#if LIT_CUBEMAP_PROJECTION == NONE
return cubeMapRotate(nrdir);
#endif
#if LIT_CUBEMAP_PROJECTION == BOX
nrdir = cubeMapRotate(nrdir);
vec3 rbmax = (envBoxMax - vPositionW) / nrdir;
vec3 rbmin = (envBoxMin - vPositionW) / nrdir;
vec3 rbminmax = mix(rbmin, rbmax, vec3(greaterThan(nrdir, vec3(0.0))));
float fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);
vec3 posonbox = vPositionW + nrdir * fa;
vec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5;
return normalize(posonbox - envBoxPos);
#endif
}
`,cubeMapRotatePS:`
#ifdef CUBEMAP_ROTATION
uniform mat3 cubeMapRotationMatrix;
#endif
vec3 cubeMapRotate(vec3 refDir) {
#ifdef CUBEMAP_ROTATION
return refDir * cubeMapRotationMatrix;
#else
return refDir;
#endif
}
`,debugOutputPS:`
#ifdef DEBUG_ALBEDO_PASS
gl_FragColor = vec4(gammaCorrectOutput(dAlbedo), 1.0);
#endif
#ifdef DEBUG_UV0_PASS
gl_FragColor = vec4(litArgs_albedo , 1.0);
#endif
#ifdef DEBUG_WORLD_NORMAL_PASS
gl_FragColor = vec4(litArgs_worldNormal * 0.5 + 0.5, 1.0);
#endif
#ifdef DEBUG_OPACITY_PASS
gl_FragColor = vec4(vec3(litArgs_opacity) , 1.0);
#endif
#ifdef DEBUG_SPECULARITY_PASS
gl_FragColor = vec4(litArgs_specularity, 1.0);
#endif
#ifdef DEBUG_GLOSS_PASS
gl_FragColor = vec4(vec3(litArgs_gloss) , 1.0);
#endif
#ifdef DEBUG_METALNESS_PASS
gl_FragColor = vec4(vec3(litArgs_metalness) , 1.0);
#endif
#ifdef DEBUG_AO_PASS
gl_FragColor = vec4(vec3(litArgs_ao) , 1.0);
#endif
#ifdef DEBUG_EMISSION_PASS
gl_FragColor = vec4(gammaCorrectOutput(litArgs_emission), 1.0);
#endif
`,debugProcessFrontendPS:`
#ifdef DEBUG_LIGHTING_PASS
litArgs_albedo = vec3(0.5);
#endif
#ifdef DEBUG_UV0_PASS
#ifdef VARYING_VUV0
litArgs_albedo = vec3(vUv0, 0);
#else
litArgs_albedo = vec3(0);
#endif
#endif
`,detailModesPS:`
#ifndef _DETAILMODES_INCLUDED_
#define _DETAILMODES_INCLUDED_
vec3 detailMode_mul(vec3 c1, vec3 c2) {
return c1 * c2;
}
vec3 detailMode_add(vec3 c1, vec3 c2) {
return c1 + c2;
}
vec3 detailMode_screen(vec3 c1, vec3 c2) {
return 1.0 - (1.0 - c1)*(1.0 - c2);
}
vec3 detailMode_overlay(vec3 c1, vec3 c2) {
return mix(1.0 - 2.0 * (1.0 - c1)*(1.0 - c2), 2.0 * c1 * c2, step(c1, vec3(0.5)));
}
vec3 detailMode_min(vec3 c1, vec3 c2) {
return min(c1, c2);
}
vec3 detailMode_max(vec3 c1, vec3 c2) {
return max(c1, c2);
}
#endif
`,diffusePS:`
uniform vec3 material_diffuse;
#ifdef STD_DIFFUSEDETAIL_TEXTURE
#include "detailModesPS"
#endif
void getAlbedo() {
dAlbedo = material_diffuse.rgb;
#ifdef STD_DIFFUSE_TEXTURE
vec3 albedoTexture = {STD_DIFFUSE_TEXTURE_DECODE}(texture2DBias({STD_DIFFUSE_TEXTURE_NAME}, {STD_DIFFUSE_TEXTURE_UV}, textureBias)).{STD_DIFFUSE_TEXTURE_CHANNEL};
#ifdef STD_DIFFUSEDETAIL_TEXTURE
vec3 albedoDetail = {STD_DIFFUSEDETAIL_TEXTURE_DECODE}(texture2DBias({STD_DIFFUSEDETAIL_TEXTURE_NAME}, {STD_DIFFUSEDETAIL_TEXTURE_UV}, textureBias)).{STD_DIFFUSEDETAIL_TEXTURE_CHANNEL};
albedoTexture = detailMode_{STD_DIFFUSEDETAIL_DETAILMODE}(albedoTexture, albedoDetail);
#endif
dAlbedo *= albedoTexture;
#endif
#ifdef STD_DIFFUSE_VERTEX
dAlbedo *= gammaCorrectInput(saturate(vVertexColor.{STD_DIFFUSE_VERTEX_CHANNEL}));
#endif
}
`,decodePS:`
#ifndef _DECODE_INCLUDED_
#define _DECODE_INCLUDED_
vec3 decodeLinear(vec4 raw) {
return raw.rgb;
}
float decodeGamma(float raw) {
return pow(raw, 2.2);
}
vec3 decodeGamma(vec3 raw) {
return pow(raw, vec3(2.2));
}
vec3 decodeGamma(vec4 raw) {
return pow(raw.xyz, vec3(2.2));
}
vec3 decodeRGBM(vec4 raw) {
vec3 color = (8.0 * raw.a) * raw.rgb;
return color * color;
}
vec3 decodeRGBP(vec4 raw) {
vec3 color = raw.rgb * (-raw.a * 7.0 + 8.0);
return color * color;
}
vec3 decodeRGBE(vec4 raw) {
if (raw.a == 0.0) {
return vec3(0.0, 0.0, 0.0);
} else {
return raw.xyz * pow(2.0, raw.w * 255.0 - 128.0);
}
}
vec4 passThrough(vec4 raw) {
return raw;
}
vec3 unpackNormalXYZ(vec4 nmap) {
return nmap.xyz * 2.0 - 1.0;
}
vec3 unpackNormalXY(vec4 nmap) {
vec3 normal;
normal.xy = nmap.wy * 2.0 - 1.0;
normal.z = sqrt(1.0 - clamp(dot(normal.xy, normal.xy), 0.0, 1.0));
return normal;
}
#endif
`,emissivePS:`
uniform vec3 material_emissive;
uniform float material_emissiveIntensity;
void getEmission() {
dEmission = material_emissive * material_emissiveIntensity;
#ifdef STD_EMISSIVE_TEXTURE
dEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(texture2DBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_UV}, textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL};
#endif
#ifdef STD_EMISSIVE_VERTEX
dEmission *= gammaCorrectInput(saturate(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL}));
#endif
}
`,encodePS:`
vec4 encodeLinear(vec3 source) {
return vec4(source, 1.0);
}
vec4 encodeGamma(vec3 source) {
return vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);
}
vec4 encodeRGBM(vec3 source) {
vec4 result;
result.rgb = pow(source.rgb, vec3(0.5));
result.rgb *= 1.0 / 8.0;
result.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) );
result.a = ceil(result.a * 255.0) / 255.0;
result.rgb /= result.a;
return result;
}
vec4 encodeRGBP(vec3 source) {
vec3 gamma = pow(source, vec3(0.5));
float maxVal = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));
float v = 1.0 - ((maxVal - 1.0) / 7.0);
v = ceil(v * 255.0) / 255.0;
return vec4(gamma / (-v * 7.0 + 8.0), v);
}
vec4 encodeRGBE(vec3 source) {
float maxVal = max(source.x, max(source.y, source.z));
if (maxVal < 1e-32) {
return vec4(0, 0, 0, 0);
} else {
float e = ceil(log2(maxVal));
return vec4(source / pow(2.0, e), (e + 128.0) / 255.0);
}
}
`,endPS:`
gl_FragColor.rgb = combineColor(litArgs_albedo, litArgs_sheen_specularity, litArgs_clearcoat_specularity);
gl_FragColor.rgb += litArgs_emission;
gl_FragColor.rgb = addFog(gl_FragColor.rgb);
gl_FragColor.rgb = toneMap(gl_FragColor.rgb);
gl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb);
`,envAtlasPS:`
#ifndef _ENVATLAS_INCLUDED_
#define _ENVATLAS_INCLUDED_
const float atlasSize = 512.0;
const float seamSize = 1.0 / atlasSize;
vec2 mapUv(vec2 uv, vec4 rect) {
return vec2(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),
mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));
}
vec2 mapRoughnessUv(vec2 uv, float level) {
float t = 1.0 / exp2(level);
return mapUv(uv, vec4(0, 1.0 - t, t, t * 0.5));
}
vec2 mapShinyUv(vec2 uv, float level) {
float t = 1.0 / exp2(level);
return mapUv(uv, vec4(1.0 - t, 1.0 - t, t, t * 0.5));
}
#endif
`,envProcPS:`
#ifdef LIT_SKYBOX_INTENSITY
uniform float skyboxIntensity;
#endif
vec3 processEnvironment(vec3 color) {
#ifdef LIT_SKYBOX_INTENSITY
return color * skyboxIntensity;
#else
return color;
#endif
}
`,falloffInvSquaredPS:`
float getFalloffWindow(float lightRadius, vec3 lightDir) {
float sqrDist = dot(lightDir, lightDir);
float invRadius = 1.0 / lightRadius;
return square(saturate(1.0 - square(sqrDist * square(invRadius))));
}
float getFalloffInvSquared(float lightRadius, vec3 lightDir) {
float sqrDist = dot(lightDir, lightDir);
float falloff = 1.0 / (sqrDist + 1.0);
float invRadius = 1.0 / lightRadius;
falloff *= 16.0;
falloff *= square(saturate(1.0 - square(sqrDist * square(invRadius))));
return falloff;
}
`,falloffLinearPS:`
float getFalloffLinear(float lightRadius, vec3 lightDir) {
float d = length(lightDir);
return max(((lightRadius - d) / lightRadius), 0.0);
}
`,floatAsUintPS:`
#ifndef FLOAT_AS_UINT
#define FLOAT_AS_UINT
vec4 float2uint(float value) {
uint intBits = floatBitsToUint(value);
return vec4(
float((intBits >> 24u) & 0xFFu) / 255.0,
float((intBits >> 16u) & 0xFFu) / 255.0,
float((intBits >> 8u) & 0xFFu) / 255.0,
float(intBits & 0xFFu) / 255.0
);
}
float uint2float(vec4 value) {
uint intBits =
(uint(value.r * 255.0) << 24u) |
(uint(value.g * 255.0) << 16u) |
(uint(value.b * 255.0) << 8u) |
uint(value.a * 255.0);
return uintBitsToFloat(intBits);
}
vec4 float2vec4(float value) {
#if defined(CAPS_TEXTURE_FLOAT_RENDERABLE)
return vec4(value, 1.0, 1.0, 1.0);
#else
return float2uint(value);
#endif
}
#endif
`,fogPS:`
float dBlendModeFogFactor = 1.0;
#if (FOG != NONE)
uniform vec3 fog_color;
#if (FOG == LINEAR)
uniform float fog_start;
uniform float fog_end;
#else
uniform float fog_density;
#endif
#endif
float getFogFactor() {
float depth = gl_FragCoord.z / gl_FragCoord.w;
float fogFactor = 0.0;
#if (FOG == LINEAR)
fogFactor = (fog_end - depth) / (fog_end - fog_start);
#elif (FOG == EXP)
fogFactor = exp(-depth * fog_density);
#elif (FOG == EXP2)
fogFactor = exp(-depth * depth * fog_density * fog_density);
#endif
return clamp(fogFactor, 0.0, 1.0);
}
vec3 addFog(vec3 color) {
#if (FOG != NONE)
return mix(fog_color * dBlendModeFogFactor, color, getFogFactor());
#endif
return color;
}
`,fresnelSchlickPS:`
vec3 getFresnel(
float cosTheta,
float gloss,
vec3 specularity
#if defined(LIT_IRIDESCENCE)
, vec3 iridescenceFresnel,
float iridescenceIntensity
#endif
) {
float fresnel = pow(1.0 - saturate(cosTheta), 5.0);
float glossSq = gloss * gloss;
vec3 ret = specularity + (max(vec3(glossSq), specularity) - specularity) * fresnel;
#if defined(LIT_IRIDESCENCE)
return mix(ret, iridescenceFresnel, iridescenceIntensity);
#else
return ret;
#endif
}
float getFresnelCC(float cosTheta) {
float fresnel = pow(1.0 - saturate(cosTheta), 5.0);
return 0.04 + (1.0 - 0.04) * fresnel;
}
`,frontendCodePS:"",frontendDeclPS:"",fullscreenQuadVS:`
attribute vec2 vertex_position;
varying vec2 vUv0;
void main(void)
{
gl_Position = vec4(vertex_position, 0.5, 1.0);
vUv0 = vertex_position.xy * 0.5 + 0.5;
}
`,gammaPS:`
#include "decodePS"
#if (GAMMA == SRGB)
float gammaCorrectInput(float color) {
return decodeGamma(color);
}
vec3 gammaCorrectInput(vec3 color) {
return decodeGamma(color);
}
vec4 gammaCorrectInput(vec4 color) {
return vec4(decodeGamma(color.xyz), color.w);
}
vec3 gammaCorrectOutput(vec3 color) {
return pow(color + 0.0000001, vec3(1.0 / 2.2));
}
#else
float gammaCorrectInput(float color) {
return color;
}
vec3 gammaCorrectInput(vec3 color) {
return color;
}
vec4 gammaCorrectInput(vec4 color) {
return color;
}
vec3 gammaCorrectOutput(vec3 color) {
return color;
}
#endif
`,gles3PS:o4,gles3VS:o5,glossPS:`
#ifdef STD_GLOSS_CONSTANT
uniform float material_gloss;
#endif
void getGlossiness() {
dGlossiness = 1.0;
#ifdef STD_GLOSS_CONSTANT
dGlossiness *= material_gloss;
#endif
#ifdef STD_GLOSS_TEXTURE
dGlossiness *= texture2DBias({STD_GLOSS_TEXTURE_NAME}, {STD_GLOSS_TEXTURE_UV}, textureBias).{STD_GLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_GLOSS_VERTEX
dGlossiness *= saturate(vVertexColor.{STD_GLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_GLOSS_INVERT
dGlossiness = 1.0 - dGlossiness;
#endif
dGlossiness += 0.0000001;
}
`,gsplatCenterVS:`
uniform mat4 matrix_model;
uniform mat4 matrix_view;
uniform mat4 matrix_projection;
bool initCenter(vec3 modelCenter, out SplatCenter center) {
mat4 modelView = matrix_view * matrix_model;
vec4 centerView = modelView * vec4(modelCenter, 1.0);
if (centerView.z > 0.0) {
return false;
}
vec4 centerProj = matrix_projection * centerView;
#if WEBGPU
centerProj.z = clamp(centerProj.z, 0, abs(centerProj.w));
#else
centerProj.z = clamp(centerProj.z, -abs(centerProj.w), abs(centerProj.w));
#endif
center.view = centerView.xyz / centerView.w;
center.proj = centerProj;
center.projMat00 = matrix_projection[0][0];
center.modelView = modelView;
return true;
}
`,gsplatCornerVS:`
uniform vec2 viewport;
uniform vec4 camera_params;
bool initCorner(SplatSource source, SplatCenter center, out SplatCorner corner) {
vec3 covA, covB;
readCovariance(source, covA, covB);
mat3 Vrk = mat3(
covA.x, covA.y, covA.z,
covA.y, covB.x, covB.y,
covA.z, covB.y, covB.z
);
float focal = viewport.x * center.projMat00;
vec3 v = camera_params.w == 1.0 ? vec3(0.0, 0.0, 1.0) : center.view.xyz;
float J1 = focal / v.z;
vec2 J2 = -J1 / v.z * v.xy;
mat3 J = mat3(
J1, 0.0, J2.x,
0.0, J1, J2.y,
0.0, 0.0, 0.0
);
mat3 W = transpose(mat3(center.modelView));
mat3 T = W * J;
mat3 cov = transpose(T) * Vrk * T;
#if GSPLAT_AA
float detOrig = cov[0][0] * cov[1][1] - cov[0][1] * cov[0][1];
float detBlur = (cov[0][0] + 0.3) * (cov[1][1] + 0.3) - cov[0][1] * cov[0][1];
corner.aaFactor = sqrt(max(detOrig / detBlur, 0.0));
#endif
float diagonal1 = cov[0][0] + 0.3;
float offDiagonal = cov[0][1];
float diagonal2 = cov[1][1] + 0.3;
float mid = 0.5 * (diagonal1 + diagonal2);
float radius = length(vec2((diagonal1 - diagonal2) / 2.0, offDiagonal));
float lambda1 = mid + radius;
float lambda2 = max(mid - radius, 0.1);
float vmin = min(1024.0, min(viewport.x, viewport.y));
float l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin);
float l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin);
if (l1 < 2.0 && l2 < 2.0) {
return false;
}
vec2 c = center.proj.ww / viewport;
if (any(greaterThan(abs(center.proj.xy) - vec2(max(l1, l2)) * c, center.proj.ww))) {
return false;
}
vec2 diagonalVector = normalize(vec2(offDiagonal, lambda1 - diagonal1));
vec2 v1 = l1 * diagonalVector;
vec2 v2 = l2 * vec2(diagonalVector.y, -diagonalVector.x);
corner.offset = (source.cornerUV.x * v1 + source.cornerUV.y * v2) * c;
corner.uv = source.cornerUV;
return true;
}
`,gsplatColorVS:`
uniform mediump sampler2D splatColor;
vec4 readColor(in SplatSource source) {
return texelFetch(splatColor, source.uv, 0);
}
`,gsplatCommonVS:`
struct SplatSource {
uint order;
uint id;
ivec2 uv;
vec2 cornerUV;
};
struct SplatCenter {
vec3 view;
vec4 proj;
mat4 modelView;
float projMat00;
};
struct SplatCorner {
vec2 offset;
vec2 uv;
#if GSPLAT_AA
float aaFactor;
#endif
vec2 v;
float dlen;
};
#include "gsplatEvalSHVS"
#include "gsplatQuatToMat3VS"
#if GSPLAT_COMPRESSED_DATA == true
#include "gsplatCompressedDataVS"
#if SH_COEFFS > 0
#include "gsplatCompressedSHVS"
#endif
#elif GSPLAT_SOGS_DATA == true
#include "gsplatSogsDataVS"
#include "gsplatSogsColorVS"
#if SH_COEFFS > 0
#include "gsplatSogsSHVS"
#endif
#else
#include "gsplatDataVS"
#include "gsplatColorVS"
#if SH_COEFFS > 0
#include "gsplatSHVS"
#endif
#endif
#include "gsplatSourceVS"
#include "gsplatCenterVS"
#include "gsplatCornerVS"
#include "gsplatOutputVS"
void clipCorner(inout SplatCorner corner, float alpha) {
float clip = min(1.0, sqrt(-log(1.0 / 255.0 / alpha)) / 2.0);
corner.offset *= clip;
corner.uv *= clip;
}
`,gsplatCompressedDataVS:`
uniform highp usampler2D packedTexture;
uniform highp sampler2D chunkTexture;
vec4 chunkDataA;
vec4 chunkDataB;
vec4 chunkDataC;
vec4 chunkDataD;
vec4 chunkDataE;
uvec4 packedData;
vec3 unpack111011(uint bits) {
return vec3(
float(bits >> 21u) / 2047.0,
float((bits >> 11u) & 0x3ffu) / 1023.0,
float(bits & 0x7ffu) / 2047.0
);
}
vec4 unpack8888(uint bits) {
return vec4(
float(bits >> 24u) / 255.0,
float((bits >> 16u) & 0xffu) / 255.0,
float((bits >> 8u) & 0xffu) / 255.0,
float(bits & 0xffu) / 255.0
);
}
const float norm = 1.0 / (sqrt(2.0) * 0.5);
vec4 unpackRotation(uint bits) {
float a = (float((bits >> 20u) & 0x3ffu) / 1023.0 - 0.5) * norm;
float b = (float((bits >> 10u) & 0x3ffu) / 1023.0 - 0.5) * norm;
float c = (float(bits & 0x3ffu) / 1023.0 - 0.5) * norm;
float m = sqrt(1.0 - (a * a + b * b + c * c));
uint mode = bits >> 30u;
if (mode == 0u) return vec4(m, a, b, c);
if (mode == 1u) return vec4(a, m, b, c);
if (mode == 2u) return vec4(a, b, m, c);
return vec4(a, b, c, m);
}
vec3 readCenter(SplatSource source) {
uint w = uint(textureSize(chunkTexture, 0).x) / 5u;
uint chunkId = source.id / 256u;
ivec2 chunkUV = ivec2((chunkId % w) * 5u, chunkId / w);
chunkDataA = texelFetch(chunkTexture, chunkUV, 0);
chunkDataB = texelFetch(chunkTexture, chunkUV + ivec2(1, 0), 0);
chunkDataC = texelFetch(chunkTexture, chunkUV + ivec2(2, 0), 0);
chunkDataD = texelFetch(chunkTexture, chunkUV + ivec2(3, 0), 0);
chunkDataE = texelFetch(chunkTexture, chunkUV + ivec2(4, 0), 0);
packedData = texelFetch(packedTexture, source.uv, 0);
return mix(chunkDataA.xyz, vec3(chunkDataA.w, chunkDataB.xy), unpack111011(packedData.x));
}
vec4 readColor(in SplatSource source) {
vec4 r = unpack8888(packedData.w);
return vec4(mix(chunkDataD.xyz, vec3(chunkDataD.w, chunkDataE.xy), r.rgb), r.w);
}
vec4 getRotation() {
return unpackRotation(packedData.y);
}
vec3 getScale() {
return exp(mix(vec3(chunkDataB.zw, chunkDataC.x), chunkDataC.yzw, unpack111011(packedData.z)));
}
void readCovariance(in SplatSource source, out vec3 covA, out vec3 covB) {
mat3 rot = quatToMat3(getRotation());
vec3 scale = getScale();
mat3 M = transpose(mat3(
scale.x * rot[0],
scale.y * rot[1],
scale.z * rot[2]
));
covA = vec3(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));
covB = vec3(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));
}
`,gsplatCompressedSHVS:`
#if SH_BANDS > 0
uniform highp usampler2D shTexture0;
uniform highp usampler2D shTexture1;
uniform highp usampler2D shTexture2;
vec4 unpack8888s(in uint bits) {
return vec4((uvec4(bits) >> uvec4(0u, 8u, 16u, 24u)) & 0xffu) * (8.0 / 255.0) - 4.0;
}
void readSHData(in SplatSource source, out vec3 sh[15], out float scale) {
uvec4 shData0 = texelFetch(shTexture0, source.uv, 0);
uvec4 shData1 = texelFetch(shTexture1, source.uv, 0);
uvec4 shData2 = texelFetch(shTexture2, source.uv, 0);
vec4 r0 = unpack8888s(shData0.x);
vec4 r1 = unpack8888s(shData0.y);
vec4 r2 = unpack8888s(shData0.z);
vec4 r3 = unpack8888s(shData0.w);
vec4 g0 = unpack8888s(shData1.x);
vec4 g1 = unpack8888s(shData1.y);
vec4 g2 = unpack8888s(shData1.z);
vec4 g3 = unpack8888s(shData1.w);
vec4 b0 = unpack8888s(shData2.x);
vec4 b1 = unpack8888s(shData2.y);
vec4 b2 = unpack8888s(shData2.z);
vec4 b3 = unpack8888s(shData2.w);
sh[0] = vec3(r0.x, g0.x, b0.x);
sh[1] = vec3(r0.y, g0.y, b0.y);
sh[2] = vec3(r0.z, g0.z, b0.z);
sh[3] = vec3(r0.w, g0.w, b0.w);
sh[4] = vec3(r1.x, g1.x, b1.x);
sh[5] = vec3(r1.y, g1.y, b1.y);
sh[6] = vec3(r1.z, g1.z, b1.z);
sh[7] = vec3(r1.w, g1.w, b1.w);
sh[8] = vec3(r2.x, g2.x, b2.x);
sh[9] = vec3(r2.y, g2.y, b2.y);
sh[10] = vec3(r2.z, g2.z, b2.z);
sh[11] = vec3(r2.w, g2.w, b2.w);
sh[12] = vec3(r3.x, g3.x, b3.x);
sh[13] = vec3(r3.y, g3.y, b3.y);
sh[14] = vec3(r3.z, g3.z, b3.z);
scale = 1.0;
}
#endif
`,gsplatEvalSHVS:`
#if SH_BANDS == 1
#define SH_COEFFS 3
#elif SH_BANDS == 2
#define SH_COEFFS 8
#elif SH_BANDS == 3
#define SH_COEFFS 15
#else
#define SH_COEFFS 0
#endif
#if SH_BANDS > 0
const float SH_C1 = 0.4886025119029199f;
#if SH_BANDS > 1
const float SH_C2_0 = 1.0925484305920792f;
const float SH_C2_1 = -1.0925484305920792f;
const float SH_C2_2 = 0.31539156525252005f;
const float SH_C2_3 = -1.0925484305920792f;
const float SH_C2_4 = 0.5462742152960396f;
#endif
#if SH_BANDS > 2
const float SH_C3_0 = -0.5900435899266435f;
const float SH_C3_1 = 2.890611442640554f;
const float SH_C3_2 = -0.4570457994644658f;
const float SH_C3_3 = 0.3731763325901154f;
const float SH_C3_4 = -0.4570457994644658f;
const float SH_C3_5 = 1.445305721320277f;
const float SH_C3_6 = -0.5900435899266435f;
#endif
vec3 evalSH(in vec3 sh[SH_COEFFS], in vec3 dir) {
float x = dir.x;
float y = dir.y;
float z = dir.z;
vec3 result = SH_C1 * (-sh[0] * y + sh[1] * z - sh[2] * x);
#if SH_BANDS > 1
float xx = x * x;
float yy = y * y;
float zz = z * z;
float xy = x * y;
float yz = y * z;
float xz = x * z;
result +=
sh[3] * (SH_C2_0 * xy) +
sh[4] * (SH_C2_1 * yz) +
sh[5] * (SH_C2_2 * (2.0 * zz - xx - yy)) +
sh[6] * (SH_C2_3 * xz) +
sh[7] * (SH_C2_4 * (xx - yy));
#endif
#if SH_BANDS > 2
result +=
sh[8] * (SH_C3_0 * y * (3.0 * xx - yy)) +
sh[9] * (SH_C3_1 * xy * z) +
sh[10] * (SH_C3_2 * y * (4.0 * zz - xx - yy)) +
sh[11] * (SH_C3_3 * z * (2.0 * zz - 3.0 * xx - 3.0 * yy)) +
sh[12] * (SH_C3_4 * x * (4.0 * zz - xx - yy)) +
sh[13] * (SH_C3_5 * z * (xx - yy)) +
sh[14] * (SH_C3_6 * x * (xx - 3.0 * yy));
#endif
return result;
}
#endif
`,gsplatQuatToMat3VS:`
mat3 quatToMat3(vec4 R) {
vec4 R2 = R + R;
float X = R2.x * R.w;
vec4 Y = R2.y * R;
vec4 Z = R2.z * R;
float W = R2.w * R.w;
return mat3(
1.0 - Z.z - W,
Y.z + X,
Y.w - Z.x,
Y.z - X,
1.0 - Y.y - W,
Z.w + Y.x,
Y.w + Z.x,
Z.w - Y.x,
1.0 - Y.y - Z.z
);
}
`,gsplatSogsColorVS:`
uniform mediump sampler2D sh0;
uniform vec4 sh0_mins;
uniform vec4 sh0_maxs;
float SH_C0 = 0.28209479177387814;
vec4 readColor(in SplatSource source) {
vec4 clr = mix(sh0_mins, sh0_maxs, texelFetch(sh0, source.uv, 0));
return vec4(vec3(0.5) + clr.xyz * SH_C0, 1.0 / (1.0 + exp(-clr.w)));
}
`,gsplatSogsDataVS:`
uniform highp usampler2D packedTexture;
uniform vec3 means_mins;
uniform vec3 means_maxs;
uniform vec3 scales_mins;
uniform vec3 scales_maxs;
vec4 unpackU32(uint v) {
return vec4(
float((v >> 24u) & 0xFFu) / 255.0,
float((v >> 16u) & 0xFFu) / 255.0,
float((v >> 8u) & 0xFFu) / 255.0,
float(v & 0xFFu) / 255.0
);
}
uvec4 packedSample;
vec3 readCenter(SplatSource source) {
packedSample = texelFetch(packedTexture, source.uv, 0);
vec3 l = unpackU32(packedSample.x).xyz;
vec3 u = unpackU32(packedSample.y).xyz;
vec3 n = (l * 255.0 + u * 255.0 * 256.0) / 65535.0;
vec3 v = mix(means_mins, means_maxs, n);
return sign(v) * (exp(abs(v)) - 1.0);
}
const float norm = 2.0 / sqrt(2.0);
void readCovariance(in SplatSource source, out vec3 covA, out vec3 covB) {
vec4 qdata = unpackU32(packedSample.z);
vec3 sdata = unpackU32(packedSample.w).xyz;
vec3 abc = (qdata.xyz - 0.5) * norm;
float d = sqrt(max(0.0, 1.0 - dot(abc, abc)));
uint mode = uint(qdata.w * 255.0 + 0.5) - 252u;
vec4 quat = (mode == 0u) ? vec4(d, abc) :
((mode == 1u) ? vec4(abc.x, d, abc.yz) :
((mode == 2u) ? vec4(abc.xy, d, abc.z) : vec4(abc, d)));
mat3 rot = quatToMat3(quat);
vec3 scale = exp(mix(scales_mins, scales_maxs, sdata));
mat3 M = transpose(mat3(
scale.x * rot[0],
scale.y * rot[1],
scale.z * rot[2]
));
covA = vec3(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));
covB = vec3(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));
}
`,gsplatSogsSHVS:`
uniform highp sampler2D sh_centroids;
uniform float shN_mins;
uniform float shN_maxs;
void readSHData(in SplatSource source, out vec3 sh[SH_COEFFS], out float scale) {
ivec2 t = ivec2(packedSample.x & 255u, packedSample.y & 255u);
int n = t.x + t.y * 256;
int u = (n % 64) * SH_COEFFS;
int v = n / 64;
for (int i = 0; i < SH_COEFFS; i++) {
sh[i] = mix(vec3(shN_mins), vec3(shN_maxs), texelFetch(sh_centroids, ivec2(u + i, v), 0).xyz);
}
scale = 1.0;
}
`,gsplatDataVS:`
uniform highp usampler2D transformA;
uniform highp sampler2D transformB;
uint tAw;
vec3 readCenter(SplatSource source) {
uvec4 tA = texelFetch(transformA, source.uv, 0);
tAw = tA.w;
return uintBitsToFloat(tA.xyz);
}
vec4 unpackRotation(vec3 packed) {
return vec4(packed.xyz, sqrt(max(0.0, 1.0 - dot(packed, packed))));
}
void readCovariance(in SplatSource source, out vec3 covA, out vec3 covB) {
vec4 tB = texelFetch(transformB, source.uv, 0);
mat3 rot = quatToMat3(unpackRotation(vec3(unpackHalf2x16(tAw), tB.w)).wxyz);
vec3 scale = tB.xyz;
mat3 M = transpose(mat3(
scale.x * rot[0],
scale.y * rot[1],
scale.z * rot[2]
));
covA = vec3(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));
covB = vec3(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));
}
`,gsplatOutputVS:`
#include "tonemappingPS"
#include "decodePS"
#include "gammaPS"
vec3 prepareOutputFromGamma(vec3 gammaColor) {
#if TONEMAP == NONE
#if GAMMA == NONE
return decodeGamma(gammaColor);
#else
return gammaColor;
#endif
#else
return gammaCorrectOutput(toneMap(decodeGamma(gammaColor)));
#endif
}
`,gsplatPS:`
#ifndef DITHER_NONE
#include "bayerPS"
#include "opacityDitherPS"
varying float id;
#endif
#ifdef PICK_PASS
#include "pickPS"
#endif
#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)
uniform float alphaClip;
#endif
#ifdef PREPASS_PASS
varying float vLinearDepth;
#include "floatAsUintPS"
#endif
const float EXP_A = 12102203.0;
const int EXP_BC_RMS = 1064866808;
float fastExp(float x) {
int i = int(EXP_A * x) + EXP_BC_RMS;
return intBitsToFloat(i);
}
varying mediump vec2 gaussianUV;
varying mediump vec4 gaussianColor;
void main(void) {
mediump float A = dot(gaussianUV, gaussianUV);
if (A > 1.0) {
discard;
}
mediump float alpha = fastExp(-A * 4.0) * gaussianColor.a;
#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)
if (alpha < alphaClip) {
discard;
}
#endif
#ifdef PICK_PASS
gl_FragColor = getPickOutput();
#elif SHADOW_PASS
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
#elif PREPASS_PASS
gl_FragColor = float2vec4(vLinearDepth);
#else
if (alpha < 1.0 / 255.0) {
discard;
}
#ifndef DITHER_NONE
opacityDither(alpha, id * 0.013);
#endif
gl_FragColor = vec4(gaussianColor.xyz * alpha, alpha);
#endif
}
`,gsplatSHVS:`
#if SH_BANDS > 0
vec3 unpack111011s(uint bits) {
return vec3((uvec3(bits) >> uvec3(21u, 11u, 0u)) & uvec3(0x7ffu, 0x3ffu, 0x7ffu)) / vec3(2047.0, 1023.0, 2047.0) * 2.0 - 1.0;
}
void fetchScale(in uvec4 t, out float scale, out vec3 a, out vec3 b, out vec3 c) {
scale = uintBitsToFloat(t.x);
a = unpack111011s(t.y);
b = unpack111011s(t.z);
c = unpack111011s(t.w);
}
void fetch(in uvec4 t, out vec3 a, out vec3 b, out vec3 c, out vec3 d) {
a = unpack111011s(t.x);
b = unpack111011s(t.y);
c = unpack111011s(t.z);
d = unpack111011s(t.w);
}
void fetch(in uint t, out vec3 a) {
a = unpack111011s(t);
}
#if SH_BANDS == 1
uniform highp usampler2D splatSH_1to3;
void readSHData(in SplatSource source, out vec3 sh[3], out float scale) {
fetchScale(texelFetch(splatSH_1to3, source.uv, 0), scale, sh[0], sh[1], sh[2]);
}
#elif SH_BANDS == 2
uniform highp usampler2D splatSH_1to3;
uniform highp usampler2D splatSH_4to7;
uniform highp usampler2D splatSH_8to11;
void readSHData(in SplatSource source, out vec3 sh[8], out float scale) {
fetchScale(texelFetch(splatSH_1to3, source.uv, 0), scale, sh[0], sh[1], sh[2]);
fetch(texelFetch(splatSH_4to7, source.uv, 0), sh[3], sh[4], sh[5], sh[6]);
fetch(texelFetch(splatSH_8to11, source.uv, 0).x, sh[7]);
}
#else
uniform highp usampler2D splatSH_1to3;
uniform highp usampler2D splatSH_4to7;
uniform highp usampler2D splatSH_8to11;
uniform highp usampler2D splatSH_12to15;
void readSHData(in SplatSource source, out vec3 sh[15], out float scale) {
fetchScale(texelFetch(splatSH_1to3, source.uv, 0), scale, sh[0], sh[1], sh[2]);
fetch(texelFetch(splatSH_4to7, source.uv, 0), sh[3], sh[4], sh[5], sh[6]);
fetch(texelFetch(splatSH_8to11, source.uv, 0), sh[7], sh[8], sh[9], sh[10]);
fetch(texelFetch(splatSH_12to15, source.uv, 0), sh[11], sh[12], sh[13], sh[14]);
}
#endif
#endif
`,gsplatSourceVS:`
attribute vec3 vertex_position;
attribute uint vertex_id_attrib;
uniform uint numSplats;
uniform highp usampler2D splatOrder;
bool initSource(out SplatSource source) {
uint w = uint(textureSize(splatOrder, 0).x);
source.order = vertex_id_attrib + uint(vertex_position.z);
if (source.order >= numSplats) {
return false;
}
ivec2 orderUV = ivec2(source.order % w, source.order / w);
source.id = texelFetch(splatOrder, orderUV, 0).r;
source.uv = ivec2(source.id % w, source.id / w);
source.cornerUV = vertex_position.xy;
return true;
}
`,gsplatVS:`
#include "gsplatCommonVS"
varying mediump vec2 gaussianUV;
varying mediump vec4 gaussianColor;
#ifndef DITHER_NONE
varying float id;
#endif
mediump vec4 discardVec = vec4(0.0, 0.0, 2.0, 1.0);
#ifdef PREPASS_PASS
varying float vLinearDepth;
#endif
void main(void) {
SplatSource source;
if (!initSource(source)) {
gl_Position = discardVec;
return;
}
vec3 modelCenter = readCenter(source);
SplatCenter center;
if (!initCenter(modelCenter, center)) {
gl_Position = discardVec;
return;
}
SplatCorner corner;
if (!initCorner(source, center, corner)) {
gl_Position = discardVec;
return;
}
vec4 clr = readColor(source);
#if GSPLAT_AA
clr.a *= corner.aaFactor;
#endif
#if SH_BANDS > 0
vec3 dir = normalize(center.view * mat3(center.modelView));
vec3 sh[SH_COEFFS];
float scale;
readSHData(source, sh, scale);
clr.xyz += evalSH(sh, dir) * scale;
#endif
clipCorner(corner, clr.w);
gl_Position = center.proj + vec4(corner.offset, 0, 0);
gaussianUV = corner.uv;
gaussianColor = vec4(prepareOutputFromGamma(max(clr.xyz, 0.0)), clr.w);
#ifndef DITHER_NONE
id = float(source.id);
#endif
#ifdef PREPASS_PASS
vLinearDepth = -center.view.z;
#endif
}
`,quadVS:`
attribute vec2 aPosition;
varying vec2 uv0;
void main(void)
{
gl_Position = vec4(aPosition, 0.0, 1.0);
uv0 = getImageEffectUV((aPosition.xy + 1.0) * 0.5);
}
`,immediateLinePS:`
#include "gammaPS"
varying vec4 color;
void main(void) {
gl_FragColor = vec4(gammaCorrectOutput(decodeGamma(color.rgb)), color.a);
}
`,immediateLineVS:`
attribute vec4 vertex_position;
attribute vec4 vertex_color;
uniform mat4 matrix_model;
uniform mat4 matrix_viewProjection;
varying vec4 color;
void main(void) {
color = vertex_color;
gl_Position = matrix_viewProjection * matrix_model * vertex_position;
}
`,iridescenceDiffractionPS:`
uniform float material_iridescenceRefractionIndex;
float iridescence_iorToFresnel(float transmittedIor, float incidentIor) {
return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);
}
vec3 iridescence_iorToFresnel(vec3 transmittedIor, float incidentIor) {
return pow((transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor)), vec3(2.0));
}
vec3 iridescence_fresnelToIor(vec3 f0) {
vec3 sqrtF0 = sqrt(f0);
return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);
}
vec3 iridescence_sensitivity(float opd, vec3 shift) {
float PI = 3.141592653589793;
float phase = 2.0 * PI * opd * 1.0e-9;
const vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);
const vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);
const vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);
vec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var);
xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0));
xyz /= vec3(1.0685e-07);
const mat3 XYZ_TO_REC709 = mat3(
3.2404542, -0.9692660, 0.0556434,
-1.5371385, 1.8760108, -0.2040259,
-0.4985314, 0.0415560, 1.0572252
);
return XYZ_TO_REC709 * xyz;
}
float iridescence_fresnel(float cosTheta, float f0) {
float x = clamp(1.0 - cosTheta, 0.0, 1.0);
float x2 = x * x;
float x5 = x * x2 * x2;
return f0 + (1.0 - f0) * x5;
}
vec3 iridescence_fresnel(float cosTheta, vec3 f0) {
float x = clamp(1.0 - cosTheta, 0.0, 1.0);
float x2 = x * x;
float x5 = x * x2 * x2;
return f0 + (vec3(1.0) - f0) * x5;
}
vec3 calcIridescence(float outsideIor, float cosTheta, vec3 base_f0, float iridescenceThickness) {
float PI = 3.141592653589793;
float iridescenceIor = mix(outsideIor, material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, iridescenceThickness));
float sinTheta2Sq = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0));
float cosTheta2Sq = 1.0 - sinTheta2Sq;
if (cosTheta2Sq < 0.0) {
return vec3(1.0);
}
float cosTheta2 = sqrt(cosTheta2Sq);
float r0 = iridescence_iorToFresnel(iridescenceIor, outsideIor);
float r12 = iridescence_fresnel(cosTheta, r0);
float r21 = r12;
float t121 = 1.0 - r12;
float phi12 = iridescenceIor < outsideIor ? PI : 0.0;
float phi21 = PI - phi12;
vec3 baseIor = iridescence_fresnelToIor(base_f0 + vec3(0.0001));
vec3 r1 = iridescence_iorToFresnel(baseIor, iridescenceIor);
vec3 r23 = iridescence_fresnel(cosTheta2, r1);
vec3 phi23 = vec3(0.0);
if (baseIor[0] < iridescenceIor) phi23[0] = PI;
if (baseIor[1] < iridescenceIor) phi23[1] = PI;
if (baseIor[2] < iridescenceIor) phi23[2] = PI;
float opd = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2;
vec3 phi = vec3(phi21) + phi23;
vec3 r123Sq = clamp(r12 * r23, 1e-5, 0.9999);
vec3 r123 = sqrt(r123Sq);
vec3 rs = pow(t121, 2.0) * r23 / (1.0 - r123Sq);
vec3 c0 = r12 + rs;
vec3 i = c0;
vec3 cm = rs - t121;
for (int m = 1; m <= 2; m++) {
cm *= r123;
vec3 sm = 2.0 * iridescence_sensitivity(float(m) * opd, float(m) * phi);
i += cm * sm;
}
return max(i, vec3(0.0));
}
vec3 getIridescence(float cosTheta, vec3 specularity, float iridescenceThickness) {
return calcIridescence(1.0, cosTheta, specularity, iridescenceThickness);
}
`,iridescencePS:`
#ifdef STD_IRIDESCENCE_CONSTANT
uniform float material_iridescence;
#endif
void getIridescence() {
float iridescence = 1.0;
#ifdef STD_IRIDESCENCE_CONSTANT
iridescence *= material_iridescence;
#endif
#ifdef STD_IRIDESCENCE_TEXTURE
iridescence *= texture2DBias({STD_IRIDESCENCE_TEXTURE_NAME}, {STD_IRIDESCENCE_TEXTURE_UV}, textureBias).{STD_IRIDESCENCE_TEXTURE_CHANNEL};
#endif
dIridescence = iridescence;
}
`,iridescenceThicknessPS:`
uniform float material_iridescenceThicknessMax;
#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE
uniform float material_iridescenceThicknessMin;
#endif
void getIridescenceThickness() {
#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE
float blend = texture2DBias({STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}, {STD_IRIDESCENCETHICKNESS_TEXTURE_UV}, textureBias).{STD_IRIDESCENCETHICKNESS_TEXTURE_CHANNEL};
float iridescenceThickness = mix(material_iridescenceThicknessMin, material_iridescenceThicknessMax, blend);
#else
float iridescenceThickness = material_iridescenceThicknessMax;
#endif
dIridescenceThickness = iridescenceThickness;
}
`,iorPS:`
#ifdef STD_IOR_CONSTANT
uniform float material_refractionIndex;
#endif
void getIor() {
#ifdef STD_IOR_CONSTANT
dIor = material_refractionIndex;
#else
dIor = 1.0 / 1.5;
#endif
}
`,lightDeclarationPS:`
#if defined(LIGHT{i})
uniform vec3 light{i}_color;
#if LIGHT{i}TYPE == DIRECTIONAL
uniform vec3 light{i}_direction;
#else
#define LIT_CODE_LIGHTS_POINT
uniform vec3 light{i}_position;
uniform float light{i}_radius;
#if LIGHT{i}TYPE == SPOT
#define LIT_CODE_LIGHTS_SPOT
uniform vec3 light{i}_direction;
uniform float light{i}_innerConeAngle;
uniform float light{i}_outerConeAngle;
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#define LIT_CODE_FALLOFF_SQUARED
#if LIGHT{i}TYPE == DIRECTIONAL
uniform vec3 light{i}_position;
#endif
uniform vec3 light{i}_halfWidth;
uniform vec3 light{i}_halfHeight;
#else
#if LIGHT{i}FALLOFF == LINEAR
#define LIT_CODE_FALLOFF_LINEAR
#endif
#if LIGHT{i}FALLOFF == INVERSESQUARED
#define LIT_CODE_FALLOFF_SQUARED
#endif
#endif
#if defined(LIGHT{i}CASTSHADOW)
uniform mat4 light{i}_shadowMatrix;
uniform float light{i}_shadowIntensity;
uniform vec4 light{i}_shadowParams;
#if LIGHT{i}SHADOWTYPE == PCSS_32F
uniform float light{i}_shadowSearchArea;
uniform vec4 light{i}_cameraParams;
#if LIGHT{i}TYPE == DIRECTIONAL
uniform vec4 light{i}_softShadowParams;
#endif
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
uniform mat4 light{i}_shadowMatrixPalette[4];
uniform vec4 light{i}_shadowCascadeDistances;
uniform int light{i}_shadowCascadeCount;
uniform float light{i}_shadowCascadeBlend;
#endif
#if LIGHT{i}TYPE == OMNI
#if defined(LIGHT{i}SHADOW_PCF)
uniform samplerCubeShadow light{i}_shadowMap;
#else
uniform samplerCube light{i}_shadowMap;
#endif
#else
#if defined(LIGHT{i}SHADOW_PCF)
uniform sampler2DShadow light{i}_shadowMap;
#else
uniform sampler2D light{i}_shadowMap;
#endif
#endif
#endif
#if defined(LIGHT{i}COOKIE)
#define LIT_CODE_COOKIE
#if LIGHT{i}TYPE == OMNI
uniform samplerCube light{i}_cookie;
uniform float light{i}_cookieIntensity;
#if !defined(LIGHT{i}CASTSHADOW)
uniform mat4 light{i}_shadowMatrix;
#endif
#endif
#if LIGHT{i}TYPE == SPOT
uniform sampler2D light{i}_cookie;
uniform float light{i}_cookieIntensity;
#if !defined(LIGHT{i}CASTSHADOW)
uniform mat4 light{i}_shadowMatrix;
#endif
#if defined(LIGHT{i}COOKIE_TRANSFORM)
uniform vec4 light{i}_cookieMatrix;
uniform vec2 light{i}_cookieOffset;
#endif
#endif
#endif
#endif
`,lightDiffuseLambertPS:`
float getLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm) {
return max(dot(worldNormal, -lightDirNorm), 0.0);
}
`,lightDirPointPS:`
vec3 evalOmniLight(vec3 lightPosW) {
return vPositionW - lightPosW;
}
`,lightEvaluationPS:`
#if defined(LIGHT{i})
evaluateLight{i}(
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel
#endif
);
#endif
`,lightFunctionLightPS:`
#if defined(LIGHT{i})
void evaluateLight{i}(
#if defined(LIT_IRIDESCENCE)
vec3 iridescenceFresnel
#endif
) {
vec3 lightColor = light{i}_color;
#if LIGHT{i}TYPE == DIRECTIONAL && !defined(LIT_SHADOW_CATCHER)
if (all(equal(lightColor, vec3(0.0)))) {
return;
}
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
dLightDirNormW = light{i}_direction;
dAtten = 1.0;
#else
vec3 lightDirW = evalOmniLight(light{i}_position);
dLightDirNormW = normalize(lightDirW);
#if defined(LIGHT{i}COOKIE)
#if LIGHT{i}TYPE == SPOT
#ifdef LIGHT{i}COOKIE_FALLOFF
#ifdef LIGHT{i}COOKIE_TRANSFORM
vec3 cookieAttenuation = getCookie2DXform(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity, light{i}_cookieMatrix, light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};
#else
vec3 cookieAttenuation = getCookie2D(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
#else
#ifdef LIGHT{i}COOKIE_TRANSFORM
vec3 cookieAttenuation = getCookie2DClipXform(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity, light{i}_cookieMatrix, light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};
#else
vec3 cookieAttenuation = getCookie2DClip(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
#endif
#endif
#if LIGHT{i}TYPE == OMNI
vec3 cookieAttenuation = getCookieCube(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
lightColor *= cookieAttenuation;
#endif
#if LIGHT{i}SHAPE == PUNCTUAL
#if LIGHT{i}FALLOFF == LINEAR
dAtten = getFalloffLinear(light{i}_radius, lightDirW);
#else
dAtten = getFalloffInvSquared(light{i}_radius, lightDirW);
#endif
#else
dAtten = getFalloffWindow(light{i}_radius, lightDirW);
#endif
#if LIGHT{i}TYPE == SPOT
#if !defined(LIGHT{i}COOKIE) || defined(LIGHT{i}COOKIE_FALLOFF)
dAtten *= getSpotEffect(light{i}_direction, light{i}_innerConeAngle, light{i}_outerConeAngle, dLightDirNormW);
#endif
#endif
#endif
if (dAtten < 0.00001) {
return;
}
#if LIGHT{i}SHAPE != PUNCTUAL
#if LIGHT{i}SHAPE == RECT
calcRectLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight);
#elif LIGHT{i}SHAPE == DISK
calcDiskLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight);
#elif LIGHT{i}SHAPE == SPHERE
calcSphereLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight);
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#if LIGHT{i}TYPE == DIRECTIONAL
float attenDiffuse = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirNormW);
#else
#if LIGHT{i}SHAPE == RECT
float attenDiffuse = getRectLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#elif LIGHT{i}SHAPE == DISK
float attenDiffuse = getDiskLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#elif LIGHT{i}SHAPE == SPHERE
float attenDiffuse = getSphereLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#endif
#endif
#else
dAtten *= getLightDiffuse(litArgs_worldNormal, vec3(0.0), dLightDirNormW);
#endif
#ifdef LIGHT{i}CASTSHADOW
#if LIGHT{i}TYPE == DIRECTIONAL
float shadow = getShadow{i}(vec3(0.0));
#else
float shadow = getShadow{i}(lightDirW);
#endif
shadow = mix(1.0, shadow, light{i}_shadowIntensity);
dAtten *= shadow;
#if defined(LIT_SHADOW_CATCHER) && LIGHT{i}TYPE == DIRECTIONAL
dShadowCatcher *= shadow;
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#ifdef LIT_SPECULAR
dDiffuseLight += ((attenDiffuse * dAtten) * lightColor) * (1.0 - dLTCSpecFres);
#else
dDiffuseLight += (attenDiffuse * dAtten) * lightColor;
#endif
#else
#if defined(AREA_LIGHTS) && defined(LIT_SPECULAR)
dDiffuseLight += (dAtten * lightColor) * (1.0 - litArgs_specularity);
#else
dDiffuseLight += dAtten * lightColor;
#endif
#endif
#ifdef LIGHT{i}AFFECT_SPECULARITY
#if LIGHT{i}SHAPE != PUNCTUAL
#ifdef LIT_CLEARCOAT
#if LIGHT{i}SHAPE == RECT
ccSpecularLight += ccLTCSpecFres * getRectLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor;
#elif LIGHT{i}SHAPE == DISK
ccSpecularLight += ccLTCSpecFres * getDiskLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor;
#elif LIGHT{i}SHAPE == SPHERE
ccSpecularLight += ccLTCSpecFres * getSphereLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor;
#endif
#endif
#ifdef LIT_SPECULAR
#if LIGHT{i}SHAPE == RECT
dSpecularLight += dLTCSpecFres * getRectLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor;
#elif LIGHT{i}SHAPE == DISK
dSpecularLight += dLTCSpecFres * getDiskLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor;
#elif LIGHT{i}SHAPE == SPHERE
dSpecularLight += dLTCSpecFres * getSphereLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor;
#endif
#endif
#else
#if LIGHT{i}TYPE == DIRECTIONAL && LIT_FRESNEL_MODEL != NONE
#define LIGHT{i}FRESNEL
#endif
#ifdef LIT_SPECULAR
vec3 halfDirW = normalize(-dLightDirNormW + dViewDirW);
#endif
#ifdef LIT_CLEARCOAT
vec3 lightspecularCC = getLightSpecular(halfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * lightColor;
#ifdef LIGHT{i}FRESNEL
lightspecularCC *= getFresnelCC(dot(dViewDirW, halfDirW));
#endif
ccSpecularLight += lightspecularCC;
#endif
#ifdef LIT_SHEEN
sSpecularLight += getLightSpecularSheen(halfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * lightColor;
#endif
#ifdef LIT_SPECULAR
vec3 lightSpecular = getLightSpecular(halfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * lightColor;
#ifdef LIGHT{i}FRESNEL
#if defined(LIT_IRIDESCENCE)
lightSpecular *= getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity, iridescenceFresnel, litArgs_iridescence_intensity);
#else
lightSpecular *= getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity);
#endif
#else
lightSpecular *= litArgs_specularity;
#endif
dSpecularLight += lightSpecular;
#endif
#endif
#endif
}
#endif
`,lightFunctionShadowPS:`
#ifdef LIGHT{i}CASTSHADOW
vec3 getShadowSampleCoord{i}(mat4 shadowTransform, vec4 shadowParams, vec3 worldPosition, vec3 lightPos, inout vec3 lightDir, vec3 lightDirNorm, vec3 normal) {
vec3 surfacePosition = worldPosition;
#ifdef LIGHT{i}_SHADOW_SAMPLE_POINT
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
float distScale = length(lightDir);
surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
lightDir = surfacePosition - lightPos;
return lightDir;
#endif
#else
#ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
surfacePosition = surfacePosition + normal * shadowParams.y;
#endif
#else
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
#ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO
float distScale = 1.0;
#else
float distScale = abs(dot(vPositionW - lightPos, lightDirNorm));
#endif
surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
#endif
#endif
vec4 positionInShadowSpace = shadowTransform * vec4(surfacePosition, 1.0);
#ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO
positionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001;
#else
#ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER
positionInShadowSpace.xyz /= positionInShadowSpace.w;
#else
positionInShadowSpace.xy /= positionInShadowSpace.w;
positionInShadowSpace.z = length(lightDir) * shadowParams.w;
#endif
#endif
#ifdef SHADOW_SAMPLE_Z_BIAS
#endif
surfacePosition = positionInShadowSpace.xyz;
#endif
return surfacePosition;
}
float getShadow{i}(vec3 lightDirW) {
#ifdef LIGHT{i}_SHADOW_CASCADES
int cascadeIndex = getShadowCascadeIndex(light{i}_shadowCascadeDistances, light{i}_shadowCascadeCount);
#ifdef LIGHT{i}_SHADOW_CASCADE_BLEND
cascadeIndex = ditherShadowCascadeIndex(cascadeIndex, light{i}_shadowCascadeDistances, light{i}_shadowCascadeCount, light{i}_shadowCascadeBlend);
#endif
mat4 shadowMatrix = light{i}_shadowMatrixPalette[cascadeIndex];
#else
mat4 shadowMatrix = light{i}_shadowMatrix;
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
vec3 shadowCoord = getShadowSampleCoord{i}(shadowMatrix, light{i}_shadowParams, vPositionW, vec3(0.0), lightDirW, dLightDirNormW, dVertexNormalW);
#else
vec3 shadowCoord = getShadowSampleCoord{i}(shadowMatrix, light{i}_shadowParams, vPositionW, light{i}_position, lightDirW, dLightDirNormW, dVertexNormalW);
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
shadowCoord = fadeShadow(shadowCoord, light{i}_shadowCascadeDistances);
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
#if LIGHT{i}SHADOWTYPE == VSM_16F
return getShadowVSM16(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 5.54);
#endif
#if LIGHT{i}SHADOWTYPE == VSM_32F
return getShadowVSM32(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 15.0);
#endif
#if LIGHT{i}SHADOWTYPE == PCSS_32F
#if LIGHT{i}SHAPE != PUNCTUAL
vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea;
return getShadowPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW);
#else
return getShadowPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, light{i}_softShadowParams, lightDirW);
#endif
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F
return getShadowPCF5x5(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#endif
#if LIGHT{i}TYPE == SPOT
#if LIGHT{i}SHADOWTYPE == VSM_16F
return getShadowSpotVSM16(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 5.54, lightDirW);
#endif
#if LIGHT{i}SHADOWTYPE == VSM_32F
return getShadowSpotVSM32(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 15.0, lightDirW);
#endif
#if LIGHT{i}SHADOWTYPE == PCSS_32F
#if LIGHT{i}SHAPE != PUNCTUAL
vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea;
#else
vec2 shadowSearchArea = vec2(light{i}_shadowSearchArea);
#endif
return getShadowSpotPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW);
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowSpotPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowSpotPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F
return getShadowSpotPCF5x5(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#endif
#if LIGHT{i}TYPE == OMNI
#if LIGHT{i}SHADOWTYPE == PCSS_32F
#if LIGHT{i}SHAPE != PUNCTUAL
vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea;
#else
vec2 shadowSearchArea = vec2(light{i}_shadowSearchArea);
#endif
return getShadowOmniPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW);
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowOmniPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, lightDirW);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowOmniPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, lightDirW);
#endif
#endif
}
#endif
`,lightingPS:`
#ifdef LIT_CLUSTERED_LIGHTS
#define LIT_CODE_FALLOFF_LINEAR
#define LIT_CODE_FALLOFF_SQUARED
#define LIT_CODE_LIGHTS_POINT
#define LIT_CODE_LIGHTS_SPOT
#endif
#ifdef AREA_LIGHTS
uniform highp sampler2D areaLightsLutTex1;
uniform highp sampler2D areaLightsLutTex2;
#endif
#ifdef LIT_LIGHTING
#include "lightDiffuseLambertPS"
#if defined(AREA_LIGHTS) || defined(LIT_CLUSTERED_AREA_LIGHTS)
#include "ltcPS"
#endif
#endif
#ifdef SHADOW_DIRECTIONAL
#include "shadowCascadesPS"
#endif
#if defined(SHADOW_KIND_PCF1)
#include "shadowPCF1PS"
#endif
#if defined(SHADOW_KIND_PCF3)
#include "shadowPCF3PS"
#endif
#if defined(SHADOW_KIND_PCF5)
#include "shadowPCF5PS"
#endif
#if defined(SHADOW_KIND_PCSS)
#include "linearizeDepthPS"
#include "shadowPCSSPS"
#include "shadowSoftPS"
#endif
#if defined(SHADOW_KIND_VSM)
#include "shadowEVSMPS"
#endif
#ifdef LIT_CODE_FALLOFF_LINEAR
#include "falloffLinearPS"
#endif
#ifdef LIT_CODE_FALLOFF_SQUARED
#include "falloffInvSquaredPS"
#endif
#ifdef LIT_CODE_LIGHTS_POINT
#include "lightDirPointPS"
#endif
#ifdef LIT_CODE_LIGHTS_SPOT
#include "spotPS"
#endif
#ifdef LIT_CODE_COOKIE
#include "cookiePS"
#endif
#ifdef LIT_CLUSTERED_LIGHTS
#include "clusteredLightPS"
#endif
#ifdef LIGHT_COUNT > 0
#include "lightFunctionShadowPS, LIGHT_COUNT"
#include "lightFunctionLightPS, LIGHT_COUNT"
#endif
`,lightmapAddPS:`
void addLightMap(
vec3 lightmap,
vec3 dir,
vec3 worldNormal,
vec3 viewDir,
vec3 reflectionDir,
float gloss,
vec3 specularity,
vec3 vertexNormal,
mat3 tbn
#if defined(LIT_IRIDESCENCE)
vec3 iridescenceFresnel,
float iridescenceIntensity
#endif
) {
#if defined(LIT_SPECULAR) && defined(LIT_DIR_LIGHTMAP)
if (dot(dir, dir) < 0.0001) {
dDiffuseLight += lightmap;
} else {
float vlight = saturate(dot(dir, -vertexNormal));
float flight = saturate(dot(dir, -worldNormal));
float nlight = (flight / max(vlight, 0.01)) * 0.5;
dDiffuseLight += lightmap * nlight * 2.0;
vec3 halfDir = normalize(-dir + viewDir);
vec3 specularLight = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn);
#ifdef LIT_SPECULAR_FRESNEL
specularLight *=
getFresnel(dot(viewDir, halfDir),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescenceIntensity
#endif
);
#endif
dSpecularLight += specularLight;
}
#else
dDiffuseLight += lightmap;
#endif
}
`,lightmapPS:`
#ifdef STD_LIGHTMAP_DIR
vec3 dLightmapDir;
uniform sampler2D texture_dirLightMap;
#endif
void getLightMap() {
dLightmap = vec3(1.0);
#ifdef STD_LIGHT_TEXTURE
dLightmap *= {STD_LIGHT_TEXTURE_DECODE}(texture2DBias({STD_LIGHT_TEXTURE_NAME}, {STD_LIGHT_TEXTURE_UV}, textureBias)).{STD_LIGHT_TEXTURE_CHANNEL};
#ifdef STD_LIGHTMAP_DIR
vec3 dir = texture2DBias(texture_dirLightMap, {STD_LIGHT_TEXTURE_UV}, textureBias).xyz * 2.0 - 1.0;
float dirDot = dot(dir, dir);
dLightmapDir = (dirDot > 0.001) ? dir / sqrt(dirDot) : vec3(0.0);
#endif
#endif
#ifdef STD_LIGHT_VERTEX
dLightmap *= saturate(vVertexColor.{STD_LIGHT_VERTEX_CHANNEL});
#endif
}
`,lightSpecularAnisoGGXPS:`
float calcLightSpecular(float gloss, vec3 worldNormal, vec3 viewDir, vec3 h, vec3 lightDirNorm, mat3 tbn) {
float PI = 3.141592653589793;
float roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001);
float alphaRoughness = roughness * roughness;
float anisotropy = dAnisotropy;
vec2 direction = dAnisotropyRotation;
float at = mix(alphaRoughness, 1.0, anisotropy * anisotropy);
float ab = clamp(alphaRoughness, 0.001, 1.0);
vec3 anisotropicT = normalize(tbn * vec3(direction, 0.0));
vec3 anisotropicB = normalize(cross(tbn[2], anisotropicT));
float NoH = dot(worldNormal, h);
float ToH = dot(anisotropicT, h);
float BoH = dot(anisotropicB, h);
float a2 = at * ab;
vec3 v = vec3(ab * ToH, at * BoH, a2 * NoH);
float v2 = dot(v, v);
float w2 = a2 / v2;
float D = a2 * w2 * w2 * (1.0 / PI);
float ToV = dot(anisotropicT, viewDir);
float BoV = dot(anisotropicB, viewDir);
float ToL = dot(anisotropicT, -lightDirNorm);
float BoL = dot(anisotropicB, -lightDirNorm);
float NoV = dot(worldNormal, viewDir);
float NoL = dot(worldNormal, -lightDirNorm);
float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));
float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));
float G = 0.5 / (lambdaV + lambdaL);
return D * G;
}
float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {
return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn);
}
`,lightSpecularBlinnPS:`
float calcLightSpecular(float gloss, vec3 worldNormal, vec3 h) {
float nh = max( dot( h, worldNormal ), 0.0 );
float specPow = exp2(gloss * 11.0);
specPow = max(specPow, 0.0001);
return pow(nh, specPow) * (specPow + 2.0) / 8.0;
}
float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {
return calcLightSpecular(gloss, worldNormal, h);
}
`,lightSheenPS:`
float sheenD(vec3 normal, vec3 h, float roughness) {
const float PI = 3.141592653589793;
float invR = 1.0 / (roughness * roughness);
float cos2h = max(dot(normal, h), 0.0);
cos2h *= cos2h;
float sin2h = max(1.0 - cos2h, 0.0078125);
return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);
}
float sheenV(vec3 normal, vec3 viewDir, vec3 light) {
float NoV = max(dot(normal, viewDir), 0.000001);
float NoL = max(dot(normal, light), 0.000001);
return 1.0 / (4.0 * (NoL + NoV - NoL * NoV));
}
float getLightSpecularSheen(vec3 h, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float sheenGloss) {
float D = sheenD(worldNormal, h, sheenGloss);
float V = sheenV(worldNormal, viewDir, -lightDirNorm);
return D * V;
}
`,linearizeDepthPS:`
#ifndef LINEARIZE_DEPTH
#define LINEARIZE_DEPTH
float linearizeDepthWithParams(float z, vec4 cameraParams) {
if (cameraParams.w == 0.0)
return (cameraParams.z * cameraParams.y) / (cameraParams.y + z * (cameraParams.z - cameraParams.y));
else
return cameraParams.z + z * (cameraParams.y - cameraParams.z);
}
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform vec4 camera_params;
#endif
float linearizeDepth(float z) {
return linearizeDepthWithParams(z, camera_params);
}
#endif
`,litForwardBackendPS:`
void evaluateBackend() {
#ifdef LIT_SSAO
litArgs_ao *= texture2DLod(ssaoTexture, gl_FragCoord.xy * ssaoTextureSizeInv, 0.0).r;
#endif
#ifdef LIT_NEEDS_NORMAL
#ifdef LIT_SPECULAR
getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);
#endif
#ifdef LIT_CLEARCOAT
ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));
#endif
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_METALNESS
float f0 = 1.0 / litArgs_ior;
f0 = (f0 - 1.0) / (f0 + 1.0);
f0 *= f0;
litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0);
litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);
#endif
#ifdef LIT_IRIDESCENCE
vec3 iridescenceFresnel = getIridescence(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);
#endif
#endif
#ifdef LIT_ADD_AMBIENT
addAmbient(litArgs_worldNormal);
#ifdef LIT_SPECULAR
dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);
#endif
#ifdef LIT_SEPARATE_AMBIENT
vec3 dAmbientLight = dDiffuseLight;
dDiffuseLight = vec3(0);
#endif
#endif
#ifndef LIT_OLD_AMBIENT
dDiffuseLight *= material_ambient;
#endif
#ifdef LIT_AO
#ifndef LIT_OCCLUDE_DIRECT
occludeDiffuse(litArgs_ao);
#endif
#endif
#ifdef LIT_LIGHTMAP
addLightMap(
litArgs_lightmap,
litArgs_lightmapDir,
litArgs_worldNormal,
dViewDirW,
dReflDirW,
litArgs_gloss,
litArgs_specularity,
dVertexNormalW,
dTBN
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
);
#endif
#ifdef LIT_LIGHTING || LIT_REFLECTIONS
#ifdef LIT_REFLECTIONS
#ifdef LIT_CLEARCOAT
addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);
#ifdef LIT_SPECULAR_FRESNEL
ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));
ccReflection *= ccFresnel;
#else
ccFresnel = 0.0;
#endif
#endif
#ifdef LIT_SPECULARITY_FACTOR
ccReflection *= litArgs_specularityFactor;
#endif
#ifdef LIT_SHEEN
addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);
#endif
addReflection(dReflDirW, litArgs_gloss);
#ifdef LIT_FRESNEL_MODEL
dReflection.rgb *= getFresnel(
dot(dViewDirW, litArgs_worldNormal),
litArgs_gloss,
litArgs_specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
);
#else
dReflection.rgb *= litArgs_specularity;
#endif
#ifdef LIT_SPECULARITY_FACTOR
dReflection.rgb *= litArgs_specularityFactor;
#endif
#endif
#ifdef AREA_LIGHTS
dSpecularLight *= litArgs_specularity;
#ifdef LIT_SPECULAR
calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);
#endif
#endif
#ifdef LIGHT_COUNT > 0
#include "lightEvaluationPS, LIGHT_COUNT"
#endif
#ifdef LIT_CLUSTERED_LIGHTS
addClusteredLights(litArgs_worldNormal, dViewDirW, dReflDirW,
#if defined(LIT_CLEARCOAT)
ccReflDirW,
#endif
litArgs_gloss, litArgs_specularity, dVertexNormalW, dTBN,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
litArgs_clearcoat_worldNormal, litArgs_clearcoat_gloss, litArgs_sheen_gloss, litArgs_iridescence_intensity
);
#endif
#ifdef AREA_LIGHTS
#ifdef LIT_CLEARCOAT
litArgs_clearcoat_specularity = 1.0;
#endif
#ifdef LIT_SPECULAR
litArgs_specularity = vec3(1);
#endif
#endif
#ifdef LIT_REFRACTION
addRefraction(
litArgs_worldNormal,
dViewDirW,
litArgs_thickness,
litArgs_gloss,
litArgs_specularity,
litArgs_albedo,
litArgs_transmission,
litArgs_ior,
litArgs_dispersion
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
);
#endif
#endif
#ifdef LIT_AO
#ifdef LIT_OCCLUDE_DIRECT
occludeDiffuse(litArgs_ao);
#endif
#if LIT_OCCLUDE_SPECULAR != NONE
occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);
#endif
#endif
#ifdef LIT_SPECULARITY_FACTOR
dSpecularLight *= litArgs_specularityFactor;
#endif
#if !defined(LIT_OPACITY_FADES_SPECULAR)
#if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == PREMULTIPLIED
float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));
#ifdef LIT_CLEARCOAT
specLum += dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection * litArgs_clearcoat_specularity, vec3( 0.2126, 0.7152, 0.0722 ));
#endif
litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);
#endif
litArgs_opacity *= material_alphaFade;
#endif
#ifdef LIT_LIGHTMAP_BAKING
#ifdef LIT_LIGHTMAP_BAKING_COLOR
#include "bakeLmEndPS"
#endif
#ifdef LIT_LIGHTMAP_BAKING_DIR
#include "bakeDirLmEndPS"
#endif
#else
#include "endPS"
#include "outputAlphaPS"
#endif
#ifdef LIT_MSDF
gl_FragColor = applyMsdf(gl_FragColor);
#endif
#include "outputPS"
#include "debugOutputPS"
#ifdef LIT_SHADOW_CATCHER
gl_FragColor.rgb = vec3(dShadowCatcher);
#endif
}
`,litForwardDeclarationPS:`
vec3 sReflection;
vec3 dVertexNormalW;
vec3 dTangentW;
vec3 dBinormalW;
vec3 dViewDirW;
vec3 dReflDirW;
vec3 ccReflDirW;
vec3 dLightDirNormW;
float dAtten;
mat3 dTBN;
vec4 dReflection;
vec3 dDiffuseLight;
vec3 dSpecularLight;
float ccFresnel;
vec3 ccReflection;
vec3 ccSpecularLight;
float ccSpecularityNoFres;
vec3 sSpecularLight;
#ifdef LIT_DISPERSION
uniform float material_dispersion;
#endif
#ifndef LIT_OPACITY_FADES_SPECULAR
uniform float material_alphaFade;
#endif
#ifdef LIT_SSAO
uniform sampler2D ssaoTexture;
uniform vec2 ssaoTextureSizeInv;
#endif
#ifdef LIT_SHADOW_CATCHER
float dShadowCatcher = 1.0;
#endif
#if LIGHT_COUNT > 0
#include "lightDeclarationPS, LIGHT_COUNT"
#endif
#ifdef LIT_SPECULAR
#if LIT_FRESNEL_MODEL == NONE && !defined(LIT_REFLECTIONS) && !defined(LIT_DIFFUSE_MAP)
#define LIT_OLD_AMBIENT
#endif
#endif
#ifdef STD_LIGHTMAP_DIR
uniform float bakeDir;
#endif
#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT
uniform float ambientBakeOcclusionContrast;
uniform float ambientBakeOcclusionBrightness;
#endif
`,litForwardMainPS:`
void main(void) {
#include "litUserMainStartPS"
dReflection = vec4(0);
#ifdef LIT_CLEARCOAT
ccSpecularLight = vec3(0);
ccReflection = vec3(0);
#endif
#if LIT_NONE_SLICE_MODE == SLICED
#include "startNineSlicedPS"
#elif LIT_NONE_SLICE_MODE == TILED
#include "startNineSlicedTiledPS"
#endif
#ifdef LIT_NEEDS_NORMAL
dVertexNormalW = normalize(vNormalW);
#ifdef LIT_TANGENTS
#if defined(LIT_HEIGHTS) || defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS) || defined(LIT_GGX_SPECULAR)
dTangentW = vTangentW;
dBinormalW = vBinormalW;
#endif
#endif
getViewDir();
#ifdef LIT_TBN
getTBN(dTangentW, dBinormalW, dVertexNormalW);
#ifdef LIT_TWO_SIDED_LIGHTING
handleTwoSidedLighting();
#endif
#endif
#endif
evaluateFrontend();
#include "debugProcessFrontendPS"
evaluateBackend();
#include "litUserMainEndPS"
}
`,litForwardPostCodePS:`
#ifdef LIT_NEEDS_NORMAL
#include "cubeMapRotatePS"
#include "cubeMapProjectPS"
#include "envProcPS"
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_METALNESS
#include "metalnessModulatePS"
#endif
#if LIT_FRESNEL_MODEL == SCHLICK
#include "fresnelSchlickPS"
#endif
#ifdef LIT_IRIDESCENCE
#include "iridescenceDiffractionPS"
#endif
#endif
#ifdef LIT_AO
#include "aoDiffuseOccPS"
#include "aoSpecOccPS"
#endif
#if LIT_REFLECTION_SOURCE == ENVATLASHQ
#include "envAtlasPS"
#include "reflectionEnvHQPS"
#elif LIT_REFLECTION_SOURCE == ENVATLAS
#include "envAtlasPS"
#include "reflectionEnvPS"
#elif LIT_REFLECTION_SOURCE == CUBEMAP
#include "reflectionCubePS"
#elif LIT_REFLECTION_SOURCE == SPHEREMAP
#include "reflectionSpherePS"
#endif
#ifdef LIT_REFLECTIONS
#ifdef LIT_CLEARCOAT
#include "reflectionCCPS"
#endif
#ifdef LIT_SHEEN
#include "reflectionSheenPS"
#endif
#endif
#ifdef LIT_REFRACTION
#if defined(LIT_DYNAMIC_REFRACTION)
#include "refractionDynamicPS"
#elif defined(LIT_REFLECTIONS)
#include "refractionCubePS"
#endif
#endif
#ifdef LIT_SHEEN
#include "lightSheenPS"
#endif
uniform vec3 material_ambient;
#ifdef LIT_SPECULAR
#ifdef LIT_LIGHTING
#ifdef LIT_GGX_SPECULAR
#include "lightSpecularAnisoGGXPS"
#else
#include "lightSpecularBlinnPS"
#endif
#endif
#endif
#include "combinePS"
#ifdef LIT_LIGHTMAP
#include "lightmapAddPS"
#endif
#ifdef LIT_ADD_AMBIENT
#include "ambientPS"
#endif
#ifdef LIT_MSDF
#include "msdfPS"
#endif
#ifdef LIT_NEEDS_NORMAL
#include "viewDirPS"
#ifdef LIT_SPECULAR
#ifdef LIT_GGX_SPECULAR
#include "reflDirAnisoPS"
#else
#include "reflDirPS"
#endif
#endif
#endif
#include "lightingPS"
`,litForwardPreCodePS:`
#include "basePS"
#include "sphericalPS"
#include "decodePS"
#include "gammaPS"
#include "tonemappingPS"
#include "fogPS"
#if LIT_NONE_SLICE_MODE == SLICED
#include "baseNineSlicedPS"
#elif LIT_NONE_SLICE_MODE == TILED
#include "baseNineSlicedTiledPS"
#endif
#ifdef LIT_TBN
#include "TBNPS"
#ifdef LIT_TWO_SIDED_LIGHTING
#include "twoSidedLightingPS"
#endif
#endif
`,litMainPS:`
#include "varyingsPS"
#include "litUserDeclarationPS"
#include "frontendDeclPS"
#if defined(PICK_PASS) || defined(PREPASS_PASS)
#include "frontendCodePS"
#include "litUserCodePS"
#include "litOtherMainPS"
#elif defined(SHADOW_PASS)
#include "frontendCodePS"
#include "litUserCodePS"
#include "litShadowMainPS"
#else
#include "litForwardDeclarationPS"
#include "litForwardPreCodePS"
#include "frontendCodePS"
#include "litForwardPostCodePS"
#include "litForwardBackendPS"
#include "litUserCodePS"
#include "litForwardMainPS"
#endif
`,litMainVS:`
#include "varyingsVS"
#include "litUserDeclarationVS"
#ifdef VERTEX_COLOR
attribute vec4 vertex_color;
#endif
#ifdef NINESLICED
varying vec2 vMask;
varying vec2 vTiledUv;
uniform mediump vec4 innerOffset;
uniform mediump vec2 outerScale;
uniform mediump vec4 atlasRect;
#endif
vec3 dPositionW;
mat4 dModelMatrix;
#include "transformCoreVS"
#ifdef UV0
attribute vec2 vertex_texCoord0;
#include "uv0VS"
#endif
#ifdef UV1
attribute vec2 vertex_texCoord1;
#include "uv1VS"
#endif
#ifdef LINEAR_DEPTH
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform mat4 matrix_view;
#endif
#endif
#include "transformVS"
#ifdef NORMALS
#include "normalCoreVS"
#include "normalVS"
#endif
#ifdef TANGENTS
attribute vec4 vertex_tangent;
#endif
#include "uvTransformUniformsPS, UV_TRANSFORMS_COUNT"
#ifdef MSDF
#include "msdfVS"
#endif
#include "litUserCodeVS"
void main(void) {
#include "litUserMainStartVS"
gl_PointSize = 1.0;
gl_Position = getPosition();
vPositionW = getWorldPosition();
#ifdef NORMALS
vNormalW = getNormal();
#endif
#ifdef TANGENTS
vTangentW = normalize(dNormalMatrix * vertex_tangent.xyz);
vBinormalW = cross(vNormalW, vTangentW) * vertex_tangent.w;
#elif defined(GGX_SPECULAR)
vObjectSpaceUpW = normalize(dNormalMatrix * vec3(0, 1, 0));
#endif
#ifdef UV0
vec2 uv0 = getUv0();
#ifdef UV0_UNMODIFIED
vUv0 = uv0;
#endif
#endif
#ifdef UV1
vec2 uv1 = getUv1();
#ifdef UV1_UNMODIFIED
vUv1 = uv1;
#endif
#endif
#include "uvTransformVS, UV_TRANSFORMS_COUNT"
#ifdef VERTEX_COLOR
vVertexColor = vertex_color;
#endif
#ifdef LINEAR_DEPTH
vLinearDepth = -(matrix_view * vec4(vPositionW, 1.0)).z;
#endif
#ifdef MSDF
unpackMsdfParams();
#endif
#include "litUserMainEndVS"
}
`,litOtherMainPS:`
#ifdef PICK_PASS
#include "pickPS"
#endif
#ifdef PREPASS_PASS
#include "floatAsUintPS"
#endif
void main(void) {
#include "litUserMainStartPS"
evaluateFrontend();
#ifdef PICK_PASS
gl_FragColor = getPickOutput();
#endif
#ifdef PREPASS_PASS
gl_FragColor = float2vec4(vLinearDepth);
#endif
#include "litUserMainEndPS"
}
`,litShaderArgsPS:`
vec3 litArgs_albedo;
float litArgs_opacity;
vec3 litArgs_emission;
vec3 litArgs_worldNormal;
float litArgs_ao;
vec3 litArgs_lightmap;
vec3 litArgs_lightmapDir;
float litArgs_metalness;
vec3 litArgs_specularity;
float litArgs_specularityFactor;
float litArgs_gloss;
float litArgs_sheen_gloss;
vec3 litArgs_sheen_specularity;
float litArgs_transmission;
float litArgs_thickness;
float litArgs_ior;
float litArgs_dispersion;
float litArgs_iridescence_intensity;
float litArgs_iridescence_thickness;
vec3 litArgs_clearcoat_worldNormal;
float litArgs_clearcoat_specularity;
float litArgs_clearcoat_gloss;
`,litShaderCorePS:`
#if LIT_NONE_SLICE_MODE == TILED
const float textureBias = -1000.0;
#else
uniform float textureBias;
#endif
#include "litShaderArgsPS"
`,litShadowMainPS:`
#if LIGHT_TYPE != DIRECTIONAL
uniform vec3 view_position;
uniform float light_radius;
#endif
#if SHADOW_TYPE == PCSS_32F
#include "linearizeDepthPS"
#endif
void main(void) {
#include "litUserMainStartPS"
evaluateFrontend();
#ifdef PERSPECTIVE_DEPTH
float depth = gl_FragCoord.z;
#if SHADOW_TYPE == PCSS_32F
#if LIGHT_TYPE != DIRECTIONAL
depth = linearizeDepthWithParams(depth, camera_params);
#endif
#endif
#else
float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);
#define MODIFIED_DEPTH
#endif
#if SHADOW_TYPE == VSM_16F || SHADOW_TYPE == VSM_32F
#if SHADOW_TYPE == VSM_32F
float exponent = 15.0;
#else
float exponent = 5.54;
#endif
depth = 2.0 * depth - 1.0;
depth = exp(exponent * depth);
gl_FragColor = vec4(depth, depth*depth, 1.0, 1.0);
#else
#if SHADOW_TYPE == PCSS_32F
gl_FragColor.r = depth;
#else
#ifdef MODIFIED_DEPTH
gl_FragDepth = depth;
#endif
gl_FragColor = vec4(1.0);
#endif
#endif
#include "litUserMainEndPS"
}
`,litUserDeclarationPS:"",litUserDeclarationVS:"",litUserCodePS:"",litUserCodeVS:"",litUserMainStartPS:"",litUserMainStartVS:"",litUserMainEndPS:"",litUserMainEndVS:"",ltcPS:`
mat3 transposeMat3( const in mat3 m ) {
mat3 tmp;
tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
return tmp;
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
const float LUT_SIZE = 64.0;
const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
const float LUT_BIAS = 0.5 / LUT_SIZE;
float dotNV = saturate( dot( N, V ) );
vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
uv = uv * LUT_SCALE + LUT_BIAS;
return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
float l = length( f );
return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
float x = dot( v1, v2 );
float y = abs( x );
float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
float b = 3.4175940 + ( 4.1616724 + y ) * y;
float v = a / b;
float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
return cross( v1, v2 ) * theta_sintheta;
}
struct Coords {
vec3 coord0;
vec3 coord1;
vec3 coord2;
vec3 coord3;
};
float LTC_EvaluateRect( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in Coords rectCoords) {
vec3 v1 = rectCoords.coord1 - rectCoords.coord0;
vec3 v2 = rectCoords.coord3 - rectCoords.coord0;
vec3 lightNormal = cross( v1, v2 );
float factor = sign(-dot( lightNormal, P - rectCoords.coord0 ));
vec3 T1, T2;
T1 = normalize( V - N * dot( V, N ) );
T2 = factor * cross( N, T1 );
mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
vec3 coords[ 4 ];
coords[ 0 ] = mat * ( rectCoords.coord0 - P );
coords[ 1 ] = mat * ( rectCoords.coord1 - P );
coords[ 2 ] = mat * ( rectCoords.coord2 - P );
coords[ 3 ] = mat * ( rectCoords.coord3 - P );
coords[ 0 ] = normalize( coords[ 0 ] );
coords[ 1 ] = normalize( coords[ 1 ] );
coords[ 2 ] = normalize( coords[ 2 ] );
coords[ 3 ] = normalize( coords[ 3 ] );
vec3 vectorFormFactor = vec3( 0.0 );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
return result;
}
Coords dLTCCoords;
Coords getLTCLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){
Coords coords;
coords.coord0 = lightPos + halfWidth - halfHeight;
coords.coord1 = lightPos - halfWidth - halfHeight;
coords.coord2 = lightPos - halfWidth + halfHeight;
coords.coord3 = lightPos + halfWidth + halfHeight;
return coords;
}
float dSphereRadius;
Coords getSphereLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){
dSphereRadius = max(length(halfWidth), length(halfHeight));
vec3 f = reflect(normalize(lightPos - view_position), vNormalW);
vec3 w = normalize(cross(f, halfHeight));
vec3 h = normalize(cross(f, w));
return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);
}
vec2 dLTCUV;
#ifdef LIT_CLEARCOAT
vec2 ccLTCUV;
#endif
vec2 getLTCLightUV(float gloss, vec3 worldNormal, vec3 viewDir)
{
float roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001);
return LTC_Uv( worldNormal, viewDir, roughness );
}
vec3 dLTCSpecFres;
#ifdef LIT_CLEARCOAT
vec3 ccLTCSpecFres;
#endif
vec3 getLTCLightSpecFres(vec2 uv, vec3 specularity)
{
vec4 t2 = texture2DLod(areaLightsLutTex2, uv, 0.0);
return specularity * t2.x + ( vec3( 1.0 ) - specularity) * t2.y;
}
void calcLTCLightValues(float gloss, vec3 worldNormal, vec3 viewDir, vec3 specularity, float clearcoatGloss, vec3 clearcoatWorldNormal, float clearcoatSpecularity)
{
dLTCUV = getLTCLightUV(gloss, worldNormal, viewDir);
dLTCSpecFres = getLTCLightSpecFres(dLTCUV, specularity);
#ifdef LIT_CLEARCOAT
ccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir);
ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(clearcoatSpecularity));
#endif
}
void calcRectLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) {
dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);
}
void calcDiskLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) {
calcRectLightValues(lightPos, halfWidth, halfHeight);
}
void calcSphereLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) {
dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);
}
vec3 SolveCubic(vec4 Coefficient)
{
float pi = 3.14159;
Coefficient.xyz /= Coefficient.w;
Coefficient.yz /= 3.0;
float A = Coefficient.w;
float B = Coefficient.z;
float C = Coefficient.y;
float D = Coefficient.x;
vec3 Delta = vec3(
-Coefficient.z * Coefficient.z + Coefficient.y,
-Coefficient.y * Coefficient.z + Coefficient.x,
dot(vec2(Coefficient.z, -Coefficient.y), Coefficient.xy)
);
float Discriminant = dot(vec2(4.0 * Delta.x, -Delta.y), Delta.zy);
vec2 xlc, xsc;
{
float A_a = 1.0;
float C_a = Delta.x;
float D_a = -2.0 * B * Delta.x + Delta.y;
float Theta = atan(sqrt(Discriminant), -D_a) / 3.0;
float x_1a = 2.0 * sqrt(-C_a) * cos(Theta);
float x_3a = 2.0 * sqrt(-C_a) * cos(Theta + (2.0 / 3.0) * pi);
float xl;
if ((x_1a + x_3a) > 2.0 * B)
xl = x_1a;
else
xl = x_3a;
xlc = vec2(xl - B, A);
}
{
float A_d = D;
float C_d = Delta.z;
float D_d = -D * Delta.y + 2.0 * C * Delta.z;
float Theta = atan(D * sqrt(Discriminant), -D_d) / 3.0;
float x_1d = 2.0 * sqrt(-C_d) * cos(Theta);
float x_3d = 2.0 * sqrt(-C_d) * cos(Theta + (2.0 / 3.0) * pi);
float xs;
if (x_1d + x_3d < 2.0 * C)
xs = x_1d;
else
xs = x_3d;
xsc = vec2(-D, xs + C);
}
float E = xlc.y * xsc.y;
float F = -xlc.x * xsc.y - xlc.y * xsc.x;
float G = xlc.x * xsc.x;
vec2 xmc = vec2(C * F - B * G, -B * F + C * E);
vec3 Root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);
if (Root.x < Root.y && Root.x < Root.z)
Root.xyz = Root.yxz;
else if (Root.z < Root.x && Root.z < Root.y)
Root.xyz = Root.xzy;
return Root;
}
float LTC_EvaluateDisk(vec3 N, vec3 V, vec3 P, mat3 Minv, Coords points)
{
vec3 T1 = normalize(V - N * dot(V, N));
vec3 T2 = cross(N, T1);
mat3 R = transposeMat3( mat3( T1, T2, N ) );
vec3 L_[ 3 ];
L_[ 0 ] = R * ( points.coord0 - P );
L_[ 1 ] = R * ( points.coord1 - P );
L_[ 2 ] = R * ( points.coord2 - P );
vec3 C = 0.5 * (L_[0] + L_[2]);
vec3 V1 = 0.5 * (L_[1] - L_[2]);
vec3 V2 = 0.5 * (L_[1] - L_[0]);
C = Minv * C;
V1 = Minv * V1;
V2 = Minv * V2;
float a, b;
float d11 = dot(V1, V1);
float d22 = dot(V2, V2);
float d12 = dot(V1, V2);
if (abs(d12) / sqrt(d11 * d22) > 0.0001)
{
float tr = d11 + d22;
float det = -d12 * d12 + d11 * d22;
det = sqrt(det);
float u = 0.5 * sqrt(tr - 2.0 * det);
float v = 0.5 * sqrt(tr + 2.0 * det);
float e_max = (u + v) * (u + v);
float e_min = (u - v) * (u - v);
vec3 V1_, V2_;
if (d11 > d22)
{
V1_ = d12 * V1 + (e_max - d11) * V2;
V2_ = d12 * V1 + (e_min - d11) * V2;
}
else
{
V1_ = d12*V2 + (e_max - d22)*V1;
V2_ = d12*V2 + (e_min - d22)*V1;
}
a = 1.0 / e_max;
b = 1.0 / e_min;
V1 = normalize(V1_);
V2 = normalize(V2_);
}
else
{
a = 1.0 / dot(V1, V1);
b = 1.0 / dot(V2, V2);
V1 *= sqrt(a);
V2 *= sqrt(b);
}
vec3 V3 = normalize(cross(V1, V2));
if (dot(C, V3) < 0.0)
V3 *= -1.0;
float L = dot(V3, C);
float x0 = dot(V1, C) / L;
float y0 = dot(V2, C) / L;
float E1 = inversesqrt(a);
float E2 = inversesqrt(b);
a *= L * L;
b *= L * L;
float c0 = a * b;
float c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b;
float c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0);
float c3 = 1.0;
vec3 roots = SolveCubic(vec4(c0, c1, c2, c3));
float e1 = roots.x;
float e2 = roots.y;
float e3 = roots.z;
vec3 avgDir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0);
mat3 rotate = mat3(V1, V2, V3);
avgDir = rotate * avgDir;
avgDir = normalize(avgDir);
float L1 = sqrt(-e2 / e3);
float L2 = sqrt(-e2 / e1);
float formFactor = max(0.0, L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2)));
const float LUT_SIZE = 64.0;
const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
const float LUT_BIAS = 0.5 / LUT_SIZE;
vec2 uv = vec2(avgDir.z * 0.5 + 0.5, formFactor);
uv = uv*LUT_SCALE + LUT_BIAS;
float scale = texture2DLod(areaLightsLutTex2, uv, 0.0).w;
return formFactor*scale;
}
float FixNan(float value) {
#ifdef WEBGPU
return value != value ? 0.0 : value;
#else
return isnan(value) ? 0.0 : value;
#endif
}
float getRectLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {
return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords );
}
float getDiskLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {
return FixNan(LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords ));
}
float getSphereLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {
float falloff = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius);
return FixNan(getLightDiffuse(worldNormal, viewDir, lightDirNorm) * falloff);
}
mat3 getLTCLightInvMat(vec2 uv)
{
vec4 t1 = texture2DLod(areaLightsLutTex1, uv, 0.0);
return mat3(
vec3( t1.x, 0, t1.y ),
vec3( 0, 1, 0 ),
vec3( t1.z, 0, t1.w )
);
}
float calcRectLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {
mat3 mInv = getLTCLightInvMat(uv);
return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );
}
float getRectLightSpecular(vec3 worldNormal, vec3 viewDir) {
return calcRectLightSpecular(worldNormal, viewDir, dLTCUV);
}
float calcDiskLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {
mat3 mInv = getLTCLightInvMat(uv);
return LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );
}
float getDiskLightSpecular(vec3 worldNormal, vec3 viewDir) {
return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);
}
float getSphereLightSpecular(vec3 worldNormal, vec3 viewDir) {
return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);
}
`,metalnessPS:`
#ifdef STD_METALNESS_CONSTANT
uniform float material_metalness;
#endif
void getMetalness() {
float metalness = 1.0;
#ifdef STD_METALNESS_CONSTANT
metalness *= material_metalness;
#endif
#ifdef STD_METALNESS_TEXTURE
metalness *= texture2DBias({STD_METALNESS_TEXTURE_NAME}, {STD_METALNESS_TEXTURE_UV}, textureBias).{STD_METALNESS_TEXTURE_CHANNEL};
#endif
#ifdef STD_METALNESS_VERTEX
metalness *= saturate(vVertexColor.{STD_METALNESS_VERTEX_CHANNEL});
#endif
dMetalness = metalness;
}
`,metalnessModulatePS:`
vec3 getSpecularModulate(in vec3 specularity, in vec3 albedo, in float metalness, in float f0) {
vec3 dielectricF0 = f0 * specularity;
return mix(dielectricF0, albedo, metalness);
}
vec3 getAlbedoModulate(in vec3 albedo, in float metalness) {
return albedo * (1.0 - metalness);
}
`,morphPS:`
varying vec2 uv0;
uniform sampler2DArray morphTexture;
uniform highp float morphFactor[{MORPH_TEXTURE_MAX_COUNT}];
uniform highp uint morphIndex[{MORPH_TEXTURE_MAX_COUNT}];
uniform int count;
#ifdef MORPH_INT
uniform vec3 aabbSize;
uniform vec3 aabbMin;
#endif
void main (void) {
highp vec3 color = vec3(0, 0, 0);
ivec2 pixelCoords = ivec2(uv0 * vec2(textureSize(morphTexture, 0).xy));
for (int i = 0; i < count; i++) {
uint textureIndex = morphIndex[i];
vec3 delta = texelFetch(morphTexture, ivec3(pixelCoords, int(textureIndex)), 0).xyz;
color += morphFactor[i] * delta;
}
#ifdef MORPH_INT
color = (color - aabbMin) / aabbSize * 65535.0;
gl_FragColor = uvec4(color, 1u);
#else
gl_FragColor = vec4(color, 1.0);
#endif
}
`,morphVS:`
attribute vec2 vertex_position;
varying vec2 uv0;
void main(void) {
gl_Position = vec4(vertex_position, 0.5, 1.0);
uv0 = vertex_position.xy * 0.5 + 0.5;
}
`,msdfPS:`
uniform sampler2D texture_msdfMap;
float median(float r, float g, float b) {
return max(min(r, g), min(max(r, g), b));
}
float map (float min, float max, float v) {
return (v - min) / (max - min);
}
uniform float font_sdfIntensity;
uniform float font_pxrange;
uniform float font_textureWidth;
#ifndef LIT_MSDF_TEXT_ATTRIBUTE
uniform vec4 outline_color;
uniform float outline_thickness;
uniform vec4 shadow_color;
uniform vec2 shadow_offset;
#else
varying vec4 outline_color;
varying float outline_thickness;
varying vec4 shadow_color;
varying vec2 shadow_offset;
#endif
vec4 applyMsdf(vec4 color) {
color.rgb = gammaCorrectInput(color.rgb);
vec3 tsample = texture2D(texture_msdfMap, vUv0).rgb;
vec2 uvShdw = vUv0 - shadow_offset;
vec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb;
float sigDist = median(tsample.r, tsample.g, tsample.b);
float sigDistShdw = median(ssample.r, ssample.g, ssample.b);
float smoothingMax = 0.2;
vec2 w = fwidth(vUv0);
float smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, smoothingMax);
float mapMin = 0.05;
float mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0);
float sigDistInner = map(mapMin, mapMax, sigDist);
float sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness);
sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness);
float center = 0.5;
float inside = smoothstep(center-smoothing, center+smoothing, sigDistInner);
float outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline);
float shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw);
vec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);
tcolor = mix(tcolor, color, inside);
vec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;
tcolor = mix(scolor, tcolor, outline);
tcolor.rgb = gammaCorrectOutput(tcolor.rgb);
return tcolor;
}
`,msdfVS:`
attribute vec3 vertex_outlineParameters;
attribute vec3 vertex_shadowParameters;
varying vec4 outline_color;
varying float outline_thickness;
varying vec4 shadow_color;
varying vec2 shadow_offset;
void unpackMsdfParams() {
vec3 little = mod(vertex_outlineParameters, 256.);
vec3 big = (vertex_outlineParameters - little) / 256.;
outline_color.rb = little.xy / 255.;
outline_color.ga = big.xy / 255.;
outline_thickness = little.z / 255. * 0.2;
little = mod(vertex_shadowParameters, 256.);
big = (vertex_shadowParameters - little) / 256.;
shadow_color.rb = little.xy / 255.;
shadow_color.ga = big.xy / 255.;
shadow_offset = (vec2(little.z, big.z) / 127. - 1.) * 0.005;
}
`,normalVS:`
mat3 dNormalMatrix;
vec3 getNormal() {
dNormalMatrix = getNormalMatrix(dModelMatrix);
vec3 localNormal = getLocalNormal(vertex_normal);
return normalize(dNormalMatrix * localNormal);
}
`,normalCoreVS:`
attribute vec3 vertex_normal;
uniform mat3 matrix_normal;
#ifdef MORPHING_NORMAL
#ifdef MORPHING_INT
uniform highp usampler2D morphNormalTex;
#else
uniform highp sampler2D morphNormalTex;
#endif
#endif
vec3 getLocalNormal(vec3 vertexNormal) {
vec3 localNormal = vertex_normal;
#ifdef MORPHING_NORMAL
ivec2 morphUV = getTextureMorphCoords();
#ifdef MORPHING_INT
vec3 morphNormal = vec3(texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz) / 65535.0 * 2.0 - 1.0;
#else
vec3 morphNormal = texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz;
#endif
localNormal += morphNormal;
#endif
return localNormal;
}
#if defined(SKIN) || defined(BATCH)
mat3 getNormalMatrix(mat4 modelMatrix) {
return mat3(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);
}
#elif defined(INSTANCING)
mat3 getNormalMatrix(mat4 modelMatrix) {
return mat3(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);
}
#else
mat3 getNormalMatrix(mat4 modelMatrix) {
return matrix_normal;
}
#endif
`,normalMapPS:`
#ifdef STD_NORMAL_TEXTURE
uniform float material_bumpiness;
#endif
#ifdef STD_NORMALDETAIL_TEXTURE
uniform float material_normalDetailMapBumpiness;
vec3 blendNormals(vec3 n1, vec3 n2) {
n1 += vec3(0, 0, 1);
n2 *= vec3(-1, -1, 1);
return n1 * dot(n1, n2) / n1.z - n2;
}
#endif
void getNormal() {
#ifdef STD_NORMAL_TEXTURE
vec3 normalMap = {STD_NORMAL_TEXTURE_DECODE}(texture2DBias({STD_NORMAL_TEXTURE_NAME}, {STD_NORMAL_TEXTURE_UV}, textureBias));
normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness);
#ifdef STD_NORMALDETAIL_TEXTURE
vec3 normalDetailMap = {STD_NORMALDETAIL_TEXTURE_DECODE}(texture2DBias({STD_NORMALDETAIL_TEXTURE_NAME}, {STD_NORMALDETAIL_TEXTURE_UV}, textureBias));
normalDetailMap = mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness);
normalMap = blendNormals(normalMap, normalDetailMap);
#endif
dNormalW = normalize(dTBN * normalMap);
#else
dNormalW = dVertexNormalW;
#endif
}
`,opacityPS:`
uniform float material_opacity;
void getOpacity() {
dAlpha = material_opacity;
#ifdef STD_OPACITY_TEXTURE
dAlpha *= texture2DBias({STD_OPACITY_TEXTURE_NAME}, {STD_OPACITY_TEXTURE_UV}, textureBias).{STD_OPACITY_TEXTURE_CHANNEL};
#endif
#ifdef STD_OPACITY_VERTEX
dAlpha *= clamp(vVertexColor.{STD_OPACITY_VERTEX_CHANNEL}, 0.0, 1.0);
#endif
}
`,opacityDitherPS:`
#if STD_OPACITY_DITHER == BAYER8
#include "bayerPS"
#endif
uniform vec4 blueNoiseJitter;
#if STD_OPACITY_DITHER == BLUENOISE
uniform sampler2D blueNoiseTex32;
#endif
void opacityDither(float alpha, float id) {
#if STD_OPACITY_DITHER == BAYER8
float noise = bayer8(floor(mod(gl_FragCoord.xy + blueNoiseJitter.xy + id, 8.0))) / 64.0;
#else
#if STD_OPACITY_DITHER == BLUENOISE
vec2 uv = fract(gl_FragCoord.xy / 32.0 + blueNoiseJitter.xy + id);
float noise = texture2DLod(blueNoiseTex32, uv, 0.0).y;
#endif
#if STD_OPACITY_DITHER == IGNNOISE
vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189);
float noise = fract(magic.z * fract(dot(gl_FragCoord.xy + blueNoiseJitter.xy + id, magic.xy)));
#endif
#endif
noise = pow(noise, 2.2);
if (alpha < noise)
discard;
}
`,outputPS:`
`,outputAlphaPS:`
#if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == ADDITIVEALPHA || defined(LIT_ALPHA_TO_COVERAGE)
gl_FragColor.a = litArgs_opacity;
#elif LIT_BLEND_TYPE == PREMULTIPLIED
gl_FragColor.rgb *= litArgs_opacity;
gl_FragColor.a = litArgs_opacity;
#else
gl_FragColor.a = 1.0;
#endif
`,outputTex2DPS:`
varying vec2 vUv0;
uniform sampler2D source;
void main(void) {
gl_FragColor = texture2D(source, vUv0);
}
`,sheenPS:`
uniform vec3 material_sheen;
void getSheen() {
vec3 sheenColor = material_sheen;
#ifdef STD_SHEEN_TEXTURE
sheenColor *= {STD_SHEEN_TEXTURE_DECODE}(texture2DBias({STD_SHEEN_TEXTURE_NAME}, {STD_SHEEN_TEXTURE_UV}, textureBias)).{STD_SHEEN_TEXTURE_CHANNEL};
#endif
#ifdef STD_SHEEN_VERTEX
sheenColor *= saturate(vVertexColor.{STD_SHEEN_VERTEX_CHANNEL});
#endif
sSpecularity = sheenColor;
}
`,sheenGlossPS:`
uniform float material_sheenGloss;
void getSheenGlossiness() {
float sheenGlossiness = material_sheenGloss;
#ifdef STD_SHEENGLOSS_TEXTURE
sheenGlossiness *= texture2DBias({STD_SHEENGLOSS_TEXTURE_NAME}, {STD_SHEENGLOSS_TEXTURE_UV}, textureBias).{STD_SHEENGLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_SHEENGLOSS_VERTEX
sheenGlossiness *= saturate(vVertexColor.{STD_SHEENGLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_SHEENGLOSS_INVERT
sheenGlossiness = 1.0 - sheenGlossiness;
#endif
sGlossiness = sheenGlossiness + 0.0000001;
}
`,parallaxPS:`
uniform float material_heightMapFactor;
void getParallax() {
float parallaxScale = material_heightMapFactor;
float height = texture2DBias({STD_HEIGHT_TEXTURE_NAME}, {STD_HEIGHT_TEXTURE_UV}, textureBias).{STD_HEIGHT_TEXTURE_CHANNEL};
height = height * parallaxScale - parallaxScale * 0.5;
vec3 viewDirT = dViewDirW * dTBN;
viewDirT.z += 0.42;
dUvOffset = height * (viewDirT.xy / viewDirT.z);
}
`,pickPS:`
uniform uint meshInstanceId;
vec4 getPickOutput() {
const vec4 inv = vec4(1.0 / 255.0);
const uvec4 shifts = uvec4(16, 8, 0, 24);
uvec4 col = (uvec4(meshInstanceId) >> shifts) & uvec4(0xff);
return vec4(col) * inv;
}
`,reflDirPS:`
void getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {
dReflDirW = normalize(-reflect(viewDir, worldNormal));
}
`,reflDirAnisoPS:`
void getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {
float roughness = sqrt(1.0 - min(gloss, 1.0));
vec2 direction = dAnisotropyRotation;
vec3 anisotropicT = normalize(tbn * vec3(direction, 0.0));
vec3 anisotropicB = normalize(cross(tbn[2], anisotropicT));
float anisotropy = dAnisotropy;
vec3 anisotropicDirection = anisotropicB;
vec3 anisotropicTangent = cross(anisotropicDirection, viewDir);
vec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection);
float bendFactor = 1.0 - anisotropy * (1.0 - roughness);
float bendFactor4 = bendFactor * bendFactor * bendFactor * bendFactor;
vec3 bentNormal = normalize(mix(normalize(anisotropicNormal), normalize(worldNormal), bendFactor4));
dReflDirW = reflect(-viewDir, bentNormal);
}
`,reflectionCCPS:`
#ifdef LIT_CLEARCOAT
void addReflectionCC(vec3 reflDir, float gloss) {
ccReflection += calcReflection(reflDir, gloss);
}
#endif
`,reflectionCubePS:`
uniform samplerCube texture_cubeMap;
uniform float material_reflectivity;
vec3 calcReflection(vec3 reflDir, float gloss) {
vec3 lookupVec = cubeMapProject(reflDir);
lookupVec.x *= -1.0;
return {reflectionDecode}(textureCube(texture_cubeMap, lookupVec));
}
void addReflection(vec3 reflDir, float gloss) {
dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);
}
`,reflectionEnvHQPS:`
#ifndef ENV_ATLAS
#define ENV_ATLAS
uniform sampler2D texture_envAtlas;
#endif
uniform samplerCube texture_cubeMap;
uniform float material_reflectivity;
vec3 calcReflection(vec3 reflDir, float gloss) {
vec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);
vec2 uv = toSphericalUv(dir);
float level = saturate(1.0 - gloss) * 5.0;
float ilevel = floor(level);
float flevel = level - ilevel;
vec3 sharp = {reflectionCubemapDecode}(textureCube(texture_cubeMap, dir));
vec3 roughA = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel)));
vec3 roughB = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));
return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));
}
void addReflection(vec3 reflDir, float gloss) {
dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);
}
`,reflectionEnvPS:`
#ifndef ENV_ATLAS
#define ENV_ATLAS
uniform sampler2D texture_envAtlas;
#endif
uniform float material_reflectivity;
float shinyMipLevel(vec2 uv) {
vec2 dx = dFdx(uv);
vec2 dy = dFdy(uv);
vec2 uv2 = vec2(fract(uv.x + 0.5), uv.y);
vec2 dx2 = dFdx(uv2);
vec2 dy2 = dFdy(uv2);
float maxd = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));
return clamp(0.5 * log2(maxd) - 1.0 + textureBias, 0.0, 5.0);
}
vec3 calcReflection(vec3 reflDir, float gloss) {
vec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);
vec2 uv = toSphericalUv(dir);
float level = saturate(1.0 - gloss) * 5.0;
float ilevel = floor(level);
float level2 = shinyMipLevel(uv * atlasSize);
float ilevel2 = floor(level2);
vec2 uv0, uv1;
float weight;
if (ilevel == 0.0) {
uv0 = mapShinyUv(uv, ilevel2);
uv1 = mapShinyUv(uv, ilevel2 + 1.0);
weight = level2 - ilevel2;
} else {
uv0 = uv1 = mapRoughnessUv(uv, ilevel);
weight = 0.0;
}
vec3 linearA = {reflectionDecode}(texture2D(texture_envAtlas, uv0));
vec3 linearB = {reflectionDecode}(texture2D(texture_envAtlas, uv1));
vec3 linear0 = mix(linearA, linearB, weight);
vec3 linear1 = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));
return processEnvironment(mix(linear0, linear1, level - ilevel));
}
void addReflection(vec3 reflDir, float gloss) {
dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);
}
`,reflectionSpherePS:`
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform mat4 matrix_view;
#endif
uniform sampler2D texture_sphereMap;
uniform float material_reflectivity;
vec3 calcReflection(vec3 reflDir, float gloss) {
vec3 reflDirV = (mat3(matrix_view) * reflDir);
float m = 2.0 * sqrt(dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z + 1.0) * (reflDirV.z + 1.0));
vec2 sphereMapUv = reflDirV.xy / m + 0.5;
return {reflectionDecode}(texture2D(texture_sphereMap, sphereMapUv));
}
void addReflection(vec3 reflDir, float gloss) {
dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);
}
`,reflectionSheenPS:`
void addReflectionSheen(vec3 worldNormal, vec3 viewDir, float gloss) {
float NoV = dot(worldNormal, viewDir);
float alphaG = gloss * gloss;
float a = gloss < 0.25 ? -339.2 * alphaG + 161.4 * gloss - 25.9 : -8.48 * alphaG + 14.3 * gloss - 9.95;
float b = gloss < 0.25 ? 44.0 * alphaG - 23.7 * gloss + 3.26 : 1.97 * alphaG - 3.27 * gloss + 0.72;
float DG = exp( a * NoV + b ) + ( gloss < 0.25 ? 0.0 : 0.1 * ( gloss - 0.25 ) );
sReflection += calcReflection(worldNormal, 0.0) * saturate(DG);
}
`,refractionCubePS:`
vec3 refract2(vec3 viewVec, vec3 normal, float IOR) {
float vn = dot(viewVec, normal);
float k = 1.0 - IOR * IOR * (1.0 - vn * vn);
vec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * normal;
return refrVec;
}
void addRefraction(
vec3 worldNormal,
vec3 viewDir,
float thickness,
float gloss,
vec3 specularity,
vec3 albedo,
float transmission,
float refractionIndex,
float dispersion
#if defined(LIT_IRIDESCENCE)
, vec3 iridescenceFresnel,
float iridescenceIntensity
#endif
) {
vec4 tmpRefl = dReflection;
vec3 reflectionDir = refract2(-viewDir, worldNormal, refractionIndex);
dReflection = vec4(0);
addReflection(reflectionDir, gloss);
dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission);
dReflection = tmpRefl;
}
`,refractionDynamicPS:`
uniform float material_invAttenuationDistance;
uniform vec3 material_attenuation;
vec3 evalRefractionColor(vec3 refractionVector, float gloss, float refractionIndex) {
vec4 pointOfRefraction = vec4(vPositionW + refractionVector, 1.0);
vec4 projectionPoint = matrix_viewProjection * pointOfRefraction;
vec2 uv = getGrabScreenPos(projectionPoint);
float iorToRoughness = (1.0 - gloss) * clamp((1.0 / refractionIndex) * 2.0 - 2.0, 0.0, 1.0);
float refractionLod = log2(uScreenSize.x) * iorToRoughness;
vec3 refraction = texture2DLod(uSceneColorMap, uv, refractionLod).rgb;
return refraction;
}
void addRefraction(
vec3 worldNormal,
vec3 viewDir,
float thickness,
float gloss,
vec3 specularity,
vec3 albedo,
float transmission,
float refractionIndex,
float dispersion
#if defined(LIT_IRIDESCENCE)
, vec3 iridescenceFresnel,
float iridescenceIntensity
#endif
) {
vec3 modelScale;
modelScale.x = length(vec3(matrix_model[0].xyz));
modelScale.y = length(vec3(matrix_model[1].xyz));
modelScale.z = length(vec3(matrix_model[2].xyz));
vec3 scale = thickness * modelScale;
vec3 refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndex)) * scale;
vec3 refraction = evalRefractionColor(refractionVector, gloss, refractionIndex);
#ifdef LIT_DISPERSION
float halfSpread = (1.0 / refractionIndex - 1.0) * 0.025 * dispersion;
float refractionIndexR = refractionIndex - halfSpread;
refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexR)) * scale;
refraction.r = evalRefractionColor(refractionVector, gloss, refractionIndexR).r;
float refractionIndexB = refractionIndex + halfSpread;
refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexB)) * scale;
refraction.b = evalRefractionColor(refractionVector, gloss, refractionIndexB).b;
#endif
vec3 transmittance;
if (material_invAttenuationDistance != 0.0)
{
vec3 attenuation = -log(material_attenuation) * material_invAttenuationDistance;
transmittance = exp(-attenuation * length(refractionVector));
}
else
{
transmittance = refraction;
}
vec3 fresnel = vec3(1.0) -
getFresnel(
dot(viewDir, worldNormal),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescenceIntensity
#endif
);
dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission);
}
`,reprojectPS:`
varying vec2 vUv0;
#ifdef CUBEMAP_SOURCE
uniform samplerCube sourceCube;
#else
uniform sampler2D sourceTex;
#endif
#ifdef USE_SAMPLES_TEX
uniform sampler2D samplesTex;
uniform vec2 samplesTexInverseSize;
#endif
uniform vec3 params;
float targetFace() { return params.x; }
float targetTotalPixels() { return params.y; }
float sourceTotalPixels() { return params.z; }
float PI = 3.141592653589793;
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
#include "decodePS"
#include "encodePS"
vec3 modifySeams(vec3 dir, float scale) {
vec3 adir = abs(dir);
float M = max(max(adir.x, adir.y), adir.z);
return dir / M * vec3(
adir.x == M ? 1.0 : scale,
adir.y == M ? 1.0 : scale,
adir.z == M ? 1.0 : scale
);
}
vec2 toSpherical(vec3 dir) {
return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));
}
vec3 fromSpherical(vec2 uv) {
return vec3(cos(uv.y) * sin(uv.x),
sin(uv.y),
cos(uv.y) * cos(uv.x));
}
vec3 getDirectionEquirect() {
return fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5));
}
float signNotZero(float k){
return(k >= 0.0) ? 1.0 : -1.0;
}
vec2 signNotZero(vec2 v) {
return vec2(signNotZero(v.x), signNotZero(v.y));
}
vec3 octDecode(vec2 o) {
vec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);
if (v.y < 0.0) {
v.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz);
}
return normalize(v);
}
vec3 getDirectionOctahedral() {
return octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0);
}
vec2 octEncode(in vec3 v) {
float l1norm = abs(v.x) + abs(v.y) + abs(v.z);
vec2 result = v.xz * (1.0 / l1norm);
if (v.y < 0.0) {
result = (1.0 - abs(result.yx)) * signNotZero(result.xy);
}
return result;
}
#ifdef CUBEMAP_SOURCE
vec4 sampleCubemap(vec3 dir) {
return textureCube(sourceCube, modifySeams(dir, 1.0));
}
vec4 sampleCubemap(vec2 sph) {
return sampleCubemap(fromSpherical(sph));
}
vec4 sampleCubemap(vec3 dir, float mipLevel) {
return textureCubeLod(sourceCube, modifySeams(dir, 1.0), mipLevel);
}
vec4 sampleCubemap(vec2 sph, float mipLevel) {
return sampleCubemap(fromSpherical(sph), mipLevel);
}
#else
vec4 sampleEquirect(vec2 sph) {
vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;
return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));
}
vec4 sampleEquirect(vec3 dir) {
return sampleEquirect(toSpherical(dir));
}
vec4 sampleEquirect(vec2 sph, float mipLevel) {
vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;
return texture2DLod(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);
}
vec4 sampleEquirect(vec3 dir, float mipLevel) {
return sampleEquirect(toSpherical(dir), mipLevel);
}
vec4 sampleOctahedral(vec3 dir) {
vec2 uv = octEncode(dir) * 0.5 + 0.5;
return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));
}
vec4 sampleOctahedral(vec2 sph) {
return sampleOctahedral(fromSpherical(sph));
}
vec4 sampleOctahedral(vec3 dir, float mipLevel) {
vec2 uv = octEncode(dir) * 0.5 + 0.5;
return texture2DLod(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);
}
vec4 sampleOctahedral(vec2 sph, float mipLevel) {
return sampleOctahedral(fromSpherical(sph), mipLevel);
}
#endif
vec3 getDirectionCubemap() {
vec2 st = vUv0 * 2.0 - 1.0;
float face = targetFace();
vec3 vec;
if (face == 0.0) {
vec = vec3(1, -st.y, -st.x);
} else if (face == 1.0) {
vec = vec3(-1, -st.y, st.x);
} else if (face == 2.0) {
vec = vec3(st.x, 1, st.y);
} else if (face == 3.0) {
vec = vec3(st.x, -1, -st.y);
} else if (face == 4.0) {
vec = vec3(st.x, -st.y, 1);
} else {
vec = vec3(-st.x, -st.y, -1);
}
return normalize(modifySeams(vec, 1.0));
}
mat3 matrixFromVector(vec3 n) {
float a = 1.0 / (1.0 + n.z);
float b = -n.x * n.y * a;
vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);
vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);
return mat3(b1, b2, n);
}
mat3 matrixFromVectorSlow(vec3 n) {
vec3 up = (1.0 - abs(n.y) <= 0.0000001) ? vec3(0.0, 0.0, n.y > 0.0 ? 1.0 : -1.0) : vec3(0.0, 1.0, 0.0);
vec3 x = normalize(cross(up, n));
vec3 y = cross(n, x);
return mat3(x, y, n);
}
vec4 reproject() {
if ({NUM_SAMPLES} <= 1) {
return {ENCODE_FUNC}({DECODE_FUNC}({SOURCE_FUNC}({TARGET_FUNC}())));
} else {
vec3 t = {TARGET_FUNC}();
vec3 tu = dFdx(t);
vec3 tv = dFdy(t);
vec3 result = vec3(0.0);
for (float u = 0.0; u < {NUM_SAMPLES_SQRT}; ++u) {
for (float v = 0.0; v < {NUM_SAMPLES_SQRT}; ++v) {
result += {DECODE_FUNC}({SOURCE_FUNC}(normalize(t +
tu * (u / {NUM_SAMPLES_SQRT} - 0.5) +
tv * (v / {NUM_SAMPLES_SQRT} - 0.5))));
}
}
return {ENCODE_FUNC}(result / ({NUM_SAMPLES_SQRT} * {NUM_SAMPLES_SQRT}));
}
}
vec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);
#ifdef USE_SAMPLES_TEX
void unpackSample(int i, out vec3 L, out float mipLevel) {
float u = (float(i * 4) + 0.5) * samplesTexInverseSize.x;
float v = (floor(u) + 0.5) * samplesTexInverseSize.y;
vec4 raw;
raw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;
raw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;
raw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;
raw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat);
L.xyz = raw.xyz * 2.0 - 1.0;
mipLevel = raw.w * 8.0;
}
vec4 prefilterSamples() {
mat3 vecSpace = matrixFromVectorSlow({TARGET_FUNC}());
vec3 L;
float mipLevel;
vec3 result = vec3(0.0);
float totalWeight = 0.0;
for (int i = 0; i < {NUM_SAMPLES}; ++i) {
unpackSample(i, L, mipLevel);
result += {DECODE_FUNC}({SOURCE_FUNC}(vecSpace * L, mipLevel)) * L.z;
totalWeight += L.z;
}
return {ENCODE_FUNC}(result / totalWeight);
}
vec4 prefilterSamplesUnweighted() {
mat3 vecSpace = matrixFromVectorSlow({TARGET_FUNC}());
vec3 L;
float mipLevel;
vec3 result = vec3(0.0);
float totalWeight = 0.0;
for (int i = 0; i < {NUM_SAMPLES}; ++i) {
unpackSample(i, L, mipLevel);
result += {DECODE_FUNC}({SOURCE_FUNC}(vecSpace * L, mipLevel));
}
return {ENCODE_FUNC}(result / float({NUM_SAMPLES}));
}
#endif
void main(void) {
gl_FragColor = {PROCESS_FUNC}();
}
`,reprojectVS:`
attribute vec2 vertex_position;
uniform vec4 uvMod;
varying vec2 vUv0;
void main(void) {
gl_Position = vec4(vertex_position, 0.5, 1.0);
vUv0 = getImageEffectUV((vertex_position.xy * 0.5 + 0.5) * uvMod.xy + uvMod.zw);
}
`,screenDepthPS:`
uniform highp sampler2D uSceneDepthMap;
#ifndef SCREENSIZE
#define SCREENSIZE
uniform vec4 uScreenSize;
#endif
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform mat4 matrix_view;
#endif
#ifndef LINEARIZE_DEPTH
#define LINEARIZE_DEPTH
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform vec4 camera_params;
#endif
float linearizeDepth(float z) {
if (camera_params.w == 0.0)
return (camera_params.z * camera_params.y) / (camera_params.y + z * (camera_params.z - camera_params.y));
else
return camera_params.z + z * (camera_params.y - camera_params.z);
}
#endif
float delinearizeDepth(float linearDepth) {
if (camera_params.w == 0.0) {
return (camera_params.y * (camera_params.z - linearDepth)) / (linearDepth * (camera_params.z - camera_params.y));
} else {
return (linearDepth - camera_params.z) / (camera_params.y - camera_params.z);
}
}
float getLinearScreenDepth(vec2 uv) {
#ifdef SCENE_DEPTHMAP_LINEAR
#ifdef SCENE_DEPTHMAP_FLOAT
return texture2D(uSceneDepthMap, uv).r;
#else
ivec2 textureSize = textureSize(uSceneDepthMap, 0);
ivec2 texel = ivec2(uv * vec2(textureSize));
vec4 data = texelFetch(uSceneDepthMap, texel, 0);
uint intBits =
(uint(data.r * 255.0) << 24u) |
(uint(data.g * 255.0) << 16u) |
(uint(data.b * 255.0) << 8u) |
uint(data.a * 255.0);
return uintBitsToFloat(intBits);
#endif
#else
return linearizeDepth(texture2D(uSceneDepthMap, uv).r);
#endif
}
#ifndef VERTEXSHADER
float getLinearScreenDepth() {
vec2 uv = gl_FragCoord.xy * uScreenSize.zw;
return getLinearScreenDepth(uv);
}
#endif
float getLinearDepth(vec3 pos) {
return -(matrix_view * vec4(pos, 1.0)).z;
}
`,shadowCascadesPS:`
int getShadowCascadeIndex(vec4 shadowCascadeDistances, int shadowCascadeCount) {
float depth = 1.0 / gl_FragCoord.w;
vec4 comparisons = step(shadowCascadeDistances, vec4(depth));
int cascadeIndex = int(dot(comparisons, vec4(1.0)));
return min(cascadeIndex, shadowCascadeCount - 1);
}
int ditherShadowCascadeIndex(int cascadeIndex, vec4 shadowCascadeDistances, int shadowCascadeCount, float blendFactor) {
if (cascadeIndex < shadowCascadeCount - 1) {
float currentRangeEnd = shadowCascadeDistances[cascadeIndex];
float transitionStart = blendFactor * currentRangeEnd;
float depth = 1.0 / gl_FragCoord.w;
if (depth > transitionStart) {
float transitionFactor = smoothstep(transitionStart, currentRangeEnd, depth);
float dither = fract(sin(dot(gl_FragCoord.xy, vec2(12.9898, 78.233))) * 43758.5453);
if (dither < transitionFactor) {
cascadeIndex += 1;
}
}
}
return cascadeIndex;
}
vec3 fadeShadow(vec3 shadowCoord, vec4 shadowCascadeDistances) {
float depth = 1.0 / gl_FragCoord.w;
if (depth > shadowCascadeDistances.w) {
shadowCoord.z = -9999999.0;
}
return shadowCoord;
}
`,shadowEVSMPS:`
float linstep(float a, float b, float v) {
return saturate((v - a) / (b - a));
}
float reduceLightBleeding(float pMax, float amount) {
return linstep(amount, 1.0, pMax);
}
float chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) {
float variance = moments.y - (moments.x * moments.x);
variance = max(variance, minVariance);
float d = mean - moments.x;
float pMax = variance / (variance + (d * d));
pMax = reduceLightBleeding(pMax, lightBleedingReduction);
return (mean <= moments.x ? 1.0 : pMax);
}
float calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) {
Z = 2.0 * Z - 1.0;
float warpedDepth = exp(exponent * Z);
moments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z);
float VSMBias = vsmBias;
float depthScale = VSMBias * exponent * warpedDepth;
float minVariance1 = depthScale * depthScale;
return chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1);
}
float VSM16(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {
vec3 moments = texture2DLod(tex, texCoords, 0.0).xyz;
return calculateEVSM(moments, Z, vsmBias, exponent);
}
float getShadowVSM16(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent) {
return VSM16(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);
}
float getShadowSpotVSM16(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {
return VSM16(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);
}
float VSM32(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {
#ifdef CAPS_TEXTURE_FLOAT_FILTERABLE
vec3 moments = texture2DLod(tex, texCoords, 0.0).xyz;
#else
float pixelSize = 1.0 / resolution;
texCoords -= vec2(pixelSize);
vec3 s00 = texture2DLod(tex, texCoords, 0.0).xyz;
vec3 s10 = texture2DLod(tex, texCoords + vec2(pixelSize, 0), 0.0).xyz;
vec3 s01 = texture2DLod(tex, texCoords + vec2(0, pixelSize), 0.0).xyz;
vec3 s11 = texture2DLod(tex, texCoords + vec2(pixelSize), 0.0).xyz;
vec2 fr = fract(texCoords * resolution);
vec3 h0 = mix(s00, s10, fr.x);
vec3 h1 = mix(s01, s11, fr.x);
vec3 moments = mix(h0, h1, fr.y);
#endif
return calculateEVSM(moments, Z, vsmBias, exponent);
}
float getShadowVSM32(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent) {
return VSM32(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);
}
float getShadowSpotVSM32(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {
float Z = length(lightDir) * shadowParams.w + shadowParams.z;
return VSM32(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent);
}
`,shadowPCF1PS:`
float getShadowPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return textureShadow(shadowMap, shadowCoord);
}
float getShadowSpotPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return textureShadow(shadowMap, shadowCoord);
}
#ifndef WEBGPU
float getShadowOmniPCF1x1(samplerCubeShadow shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) {
float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;
return texture(shadowMap, vec4(lightDir, shadowZ));
}
#endif
`,shadowPCF3PS:`
float _getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {
float z = shadowCoord.z;
vec2 uv = shadowCoord.xy * shadowParams.x;
float shadowMapSizeInv = 1.0 / shadowParams.x;
vec2 base_uv = floor(uv + 0.5);
float s = (uv.x + 0.5 - base_uv.x);
float t = (uv.y + 0.5 - base_uv.y);
base_uv -= vec2(0.5);
base_uv *= shadowMapSizeInv;
float sum = 0.0;
float uw0 = (3.0 - 2.0 * s);
float uw1 = (1.0 + 2.0 * s);
float u0 = (2.0 - s) / uw0 - 1.0;
float u1 = s / uw1 + 1.0;
float vw0 = (3.0 - 2.0 * t);
float vw1 = (1.0 + 2.0 * t);
float v0 = (2.0 - t) / vw0 - 1.0;
float v1 = t / vw1 + 1.0;
u0 = u0 * shadowMapSizeInv + base_uv.x;
v0 = v0 * shadowMapSizeInv + base_uv.y;
u1 = u1 * shadowMapSizeInv + base_uv.x;
v1 = v1 * shadowMapSizeInv + base_uv.y;
sum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z));
sum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z));
sum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z));
sum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z));
sum *= 1.0f / 16.0;
return sum;
}
float getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);
}
float getShadowSpotPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);
}
#ifndef WEBGPU
float getShadowOmniPCF3x3(samplerCubeShadow shadowMap, vec4 shadowParams, vec3 dir) {
float shadowZ = length(dir) * shadowParams.w + shadowParams.z;
float z = 1.0 / float(textureSize(shadowMap, 0));
vec3 tc = normalize(dir);
mediump vec4 shadows;
shadows.x = texture(shadowMap, vec4(tc + vec3( z, z, z), shadowZ));
shadows.y = texture(shadowMap, vec4(tc + vec3(-z,-z, z), shadowZ));
shadows.z = texture(shadowMap, vec4(tc + vec3(-z, z,-z), shadowZ));
shadows.w = texture(shadowMap, vec4(tc + vec3( z,-z,-z), shadowZ));
return dot(shadows, vec4(0.25));
}
float getShadowOmniPCF3x3(samplerCubeShadow shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) {
return getShadowOmniPCF3x3(shadowMap, shadowParams, lightDir);
}
#endif
`,shadowPCF5PS:`
float _getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {
float z = shadowCoord.z;
vec2 uv = shadowCoord.xy * shadowParams.x;
float shadowMapSizeInv = 1.0 / shadowParams.x;
vec2 base_uv = floor(uv + 0.5);
float s = (uv.x + 0.5 - base_uv.x);
float t = (uv.y + 0.5 - base_uv.y);
base_uv -= vec2(0.5);
base_uv *= shadowMapSizeInv;
float uw0 = (4.0 - 3.0 * s);
float uw1 = 7.0;
float uw2 = (1.0 + 3.0 * s);
float u0 = (3.0 - 2.0 * s) / uw0 - 2.0;
float u1 = (3.0 + s) / uw1;
float u2 = s / uw2 + 2.0;
float vw0 = (4.0 - 3.0 * t);
float vw1 = 7.0;
float vw2 = (1.0 + 3.0 * t);
float v0 = (3.0 - 2.0 * t) / vw0 - 2.0;
float v1 = (3.0 + t) / vw1;
float v2 = t / vw2 + 2.0;
float sum = 0.0;
u0 = u0 * shadowMapSizeInv + base_uv.x;
v0 = v0 * shadowMapSizeInv + base_uv.y;
u1 = u1 * shadowMapSizeInv + base_uv.x;
v1 = v1 * shadowMapSizeInv + base_uv.y;
u2 = u2 * shadowMapSizeInv + base_uv.x;
v2 = v2 * shadowMapSizeInv + base_uv.y;
sum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z));
sum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z));
sum += uw2 * vw0 * textureShadow(shadowMap, vec3(u2, v0, z));
sum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z));
sum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z));
sum += uw2 * vw1 * textureShadow(shadowMap, vec3(u2, v1, z));
sum += uw0 * vw2 * textureShadow(shadowMap, vec3(u0, v2, z));
sum += uw1 * vw2 * textureShadow(shadowMap, vec3(u1, v2, z));
sum += uw2 * vw2 * textureShadow(shadowMap, vec3(u2, v2, z));
sum *= 1.0f / 144.0;
sum = saturate(sum);
return sum;
}
float getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);
}
float getShadowSpotPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);
}
`,shadowPCSSPS:`
#define PCSS_SAMPLE_COUNT 16
uniform float pcssDiskSamples[PCSS_SAMPLE_COUNT];
uniform float pcssSphereSamples[PCSS_SAMPLE_COUNT];
vec2 vogelDisk(int sampleIndex, float count, float phi, float r) {
const float GoldenAngle = 2.4;
float theta = float(sampleIndex) * GoldenAngle + phi;
float sine = sin(theta);
float cosine = cos(theta);
return vec2(r * cosine, r * sine);
}
vec3 vogelSphere(int sampleIndex, float count, float phi, float r) {
const float GoldenAngle = 2.4;
float theta = float(sampleIndex) * GoldenAngle + phi;
float weight = float(sampleIndex) / count;
return vec3(cos(theta) * r, weight, sin(theta) * r);
}
float noise(vec2 screenPos) {
const float PHI = 1.61803398874989484820459;
return fract(sin(dot(screenPos * PHI, screenPos)) * screenPos.x);
}
float viewSpaceDepth(float depth, mat4 invProjection) {
float z = depth * 2.0 - 1.0;
vec4 clipSpace = vec4(0.0, 0.0, z, 1.0);
vec4 viewSpace = invProjection * clipSpace;
return viewSpace.z;
}
float PCSSBlockerDistance(TEXTURE_ACCEPT(shadowMap), vec2 sampleCoords[PCSS_SAMPLE_COUNT], vec2 shadowCoords, vec2 searchSize, float z, vec4 cameraParams) {
float blockers = 0.0;
float averageBlocker = 0.0;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {
vec2 offset = sampleCoords[i] * searchSize;
vec2 sampleUV = shadowCoords + offset;
float blocker = texture2DLod(shadowMap, sampleUV, 0.0).r;
float isBlocking = step(blocker, z);
blockers += isBlocking;
averageBlocker += blocker * isBlocking;
}
if (blockers > 0.0)
return averageBlocker / blockers;
return -1.0;
}
float PCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec2 shadowSearchArea) {
float receiverDepth = linearizeDepthWithParams(shadowCoords.z, cameraParams);
vec2 samplePoints[PCSS_SAMPLE_COUNT];
const float PI = 3.141592653589793;
float noise = noise( gl_FragCoord.xy ) * 2.0 * PI;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {
float pcssPresample = pcssDiskSamples[i];
samplePoints[i] = vogelDisk(i, float(PCSS_SAMPLE_COUNT), noise, pcssPresample);
}
float averageBlocker = PCSSBlockerDistance(TEXTURE_PASS(shadowMap), samplePoints, shadowCoords.xy, shadowSearchArea, receiverDepth, cameraParams);
if (averageBlocker == -1.0) {
return 1.0;
} else {
float depthDifference = (receiverDepth - averageBlocker) / 3.0;
vec2 filterRadius = depthDifference * shadowSearchArea;
float shadow = 0.0;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i ++)
{
vec2 sampleUV = samplePoints[i] * filterRadius;
sampleUV = shadowCoords.xy + sampleUV;
float depth = texture2DLod(shadowMap, sampleUV, 0.0).r;
shadow += step(receiverDepth, depth);
}
return shadow / float(PCSS_SAMPLE_COUNT);
}
}
#ifndef WEBGPU
float PCSSCubeBlockerDistance(samplerCube shadowMap, vec3 lightDirNorm, vec3 samplePoints[PCSS_SAMPLE_COUNT], float z, float shadowSearchArea) {
float blockers = 0.0;
float averageBlocker = 0.0;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {
vec3 sampleDir = lightDirNorm + samplePoints[i] * shadowSearchArea;
sampleDir = normalize(sampleDir);
float blocker = textureCubeLod(shadowMap, sampleDir, 0.0).r;
float isBlocking = step(blocker, z);
blockers += isBlocking;
averageBlocker += blocker * isBlocking;
}
if (blockers > 0.0)
return averageBlocker / blockers;
return -1.0;
}
float PCSSCube(samplerCube shadowMap, vec4 shadowParams, vec3 shadowCoords, vec4 cameraParams, float shadowSearchArea, vec3 lightDir) {
vec3 samplePoints[PCSS_SAMPLE_COUNT];
const float PI = 3.141592653589793;
float noise = noise( gl_FragCoord.xy ) * 2.0 * PI;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {
float r = pcssSphereSamples[i];
samplePoints[i] = vogelSphere(i, float(PCSS_SAMPLE_COUNT), noise, r);
}
float receiverDepth = length(lightDir) * shadowParams.w + shadowParams.z;
vec3 lightDirNorm = normalize(lightDir);
float averageBlocker = PCSSCubeBlockerDistance(shadowMap, lightDirNorm, samplePoints, receiverDepth, shadowSearchArea);
if (averageBlocker == -1.0) {
return 1.0;
} else {
float filterRadius = ((receiverDepth - averageBlocker) / averageBlocker) * shadowSearchArea;
float shadow = 0.0;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i++)
{
vec3 offset = samplePoints[i] * filterRadius;
vec3 sampleDir = lightDirNorm + offset;
sampleDir = normalize(sampleDir);
float depth = textureCubeLod(shadowMap, sampleDir, 0.0).r;
shadow += step(receiverDepth, depth);
}
return shadow / float(PCSS_SAMPLE_COUNT);
}
}
float getShadowOmniPCSS(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {
return PCSSCube(shadowMap, shadowParams, shadowCoord, cameraParams, shadowSearchArea.x, lightDir);
}
#endif
float getShadowSpotPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {
return PCSS(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, shadowSearchArea);
}
`,shadowSoftPS:`
highp float fractSinRand(const in vec2 uv) {
const float PI = 3.141592653589793;
const highp float a = 12.9898, b = 78.233, c = 43758.5453;
highp float dt = dot(uv.xy, vec2(a, b)), sn = mod(dt, PI);
return fract(sin(sn) * c);
}
struct VogelDiskData {
float invNumSamples;
float initialAngle;
float currentPointId;
};
void prepareDiskConstants(out VogelDiskData data, int sampleCount, float randomSeed) {
const float pi2 = 6.28318530718;
data.invNumSamples = 1.0 / float(sampleCount);
data.initialAngle = randomSeed * pi2;
data.currentPointId = 0.0;
}
vec2 generateDiskSample(inout VogelDiskData data) {
const float GOLDEN_ANGLE = 2.399963;
float r = sqrt((data.currentPointId + 0.5) * data.invNumSamples);
float theta = data.currentPointId * GOLDEN_ANGLE + data.initialAngle;
vec2 offset = vec2(cos(theta), sin(theta)) * pow(r, 1.33);
data.currentPointId += 1.0;
return offset;
}
void PCSSFindBlocker(TEXTURE_ACCEPT(shadowMap), out float avgBlockerDepth, out int numBlockers,
vec2 shadowCoords, float z, int shadowBlockerSamples, float penumbraSize, float invShadowMapSize, float randomSeed) {
VogelDiskData diskData;
prepareDiskConstants(diskData, shadowBlockerSamples, randomSeed);
float searchWidth = penumbraSize * invShadowMapSize;
float blockerSum = 0.0;
numBlockers = 0;
for( int i = 0; i < shadowBlockerSamples; ++i ) {
vec2 diskUV = generateDiskSample(diskData);
vec2 sampleUV = shadowCoords + diskUV * searchWidth;
float shadowMapDepth = texture2DLod(shadowMap, sampleUV, 0.0).r;
if ( shadowMapDepth < z ) {
blockerSum += shadowMapDepth;
numBlockers++;
}
}
avgBlockerDepth = blockerSum / float(numBlockers);
}
float PCSSFilter(TEXTURE_ACCEPT(shadowMap), vec2 uv, float receiverDepth, int shadowSamples, float filterRadius, float randomSeed) {
VogelDiskData diskData;
prepareDiskConstants(diskData, shadowSamples, randomSeed);
float sum = 0.0;
for (int i = 0; i < shadowSamples; i++) {
vec2 offsetUV = generateDiskSample(diskData) * filterRadius;
float depth = texture2DLod(shadowMap, uv + offsetUV, 0.0).r;
sum += step(receiverDepth, depth);
}
return sum / float(shadowSamples);
}
float getPenumbra(float dblocker, float dreceiver, float penumbraSize, float penumbraFalloff) {
float dist = dreceiver - dblocker;
float penumbra = 1.0 - pow(1.0 - dist, penumbraFalloff);
return penumbra * penumbraSize;
}
float PCSSDirectional(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec4 softShadowParams) {
float receiverDepth = shadowCoords.z;
float randomSeed = fractSinRand(gl_FragCoord.xy);
int shadowSamples = int(softShadowParams.x);
int shadowBlockerSamples = int(softShadowParams.y);
float penumbraSize = softShadowParams.z;
float penumbraFalloff = softShadowParams.w;
int shadowMapSize = textureSize(shadowMap, 0).x;
float invShadowMapSize = 1.0 / float(shadowMapSize);
invShadowMapSize *= float(shadowMapSize) / 2048.0;
float penumbra;
if (shadowBlockerSamples > 0) {
float avgBlockerDepth = 0.0;
int numBlockers = 0;
PCSSFindBlocker(TEXTURE_PASS(shadowMap), avgBlockerDepth, numBlockers, shadowCoords.xy, receiverDepth, shadowBlockerSamples, penumbraSize, invShadowMapSize, randomSeed);
if (numBlockers < 1)
return 1.0f;
penumbra = getPenumbra(avgBlockerDepth, shadowCoords.z, penumbraSize, penumbraFalloff);
} else {
penumbra = penumbraSize;
}
float filterRadius = penumbra * invShadowMapSize;
return PCSSFilter(TEXTURE_PASS(shadowMap), shadowCoords.xy, receiverDepth, shadowSamples, filterRadius, randomSeed);
}
float getShadowPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec4 softShadowParams, vec3 lightDir) {
return PCSSDirectional(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, softShadowParams);
}
`,skinBatchVS:`
attribute float vertex_boneIndices;
uniform highp sampler2D texture_poseMap;
mat4 getBoneMatrix(const in float indexFloat) {
int width = textureSize(texture_poseMap, 0).x;
int index = int(indexFloat + 0.5) * 3;
int iy = index / width;
int ix = index % width;
vec4 v1 = texelFetch(texture_poseMap, ivec2(ix + 0, iy), 0);
vec4 v2 = texelFetch(texture_poseMap, ivec2(ix + 1, iy), 0);
vec4 v3 = texelFetch(texture_poseMap, ivec2(ix + 2, iy), 0);
return mat4(
v1.x, v2.x, v3.x, 0,
v1.y, v2.y, v3.y, 0,
v1.z, v2.z, v3.z, 0,
v1.w, v2.w, v3.w, 1
);
}
`,skinVS:`
attribute vec4 vertex_boneWeights;
attribute vec4 vertex_boneIndices;
uniform highp sampler2D texture_poseMap;
void getBoneMatrix(const in int width, const in int index, out vec4 v1, out vec4 v2, out vec4 v3) {
int v = index / width;
int u = index % width;
v1 = texelFetch(texture_poseMap, ivec2(u + 0, v), 0);
v2 = texelFetch(texture_poseMap, ivec2(u + 1, v), 0);
v3 = texelFetch(texture_poseMap, ivec2(u + 2, v), 0);
}
mat4 getSkinMatrix(const in vec4 indicesFloat, const in vec4 weights) {
int width = textureSize(texture_poseMap, 0).x;
ivec4 indices = ivec4(indicesFloat + 0.5) * 3;
vec4 a1, a2, a3;
getBoneMatrix(width, indices.x, a1, a2, a3);
vec4 b1, b2, b3;
getBoneMatrix(width, indices.y, b1, b2, b3);
vec4 c1, c2, c3;
getBoneMatrix(width, indices.z, c1, c2, c3);
vec4 d1, d2, d3;
getBoneMatrix(width, indices.w, d1, d2, d3);
vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;
vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;
vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;
float one = dot(weights, vec4(1.0));
return mat4(
v1.x, v2.x, v3.x, 0,
v1.y, v2.y, v3.y, 0,
v1.z, v2.z, v3.z, 0,
v1.w, v2.w, v3.w, one
);
}
`,skyboxPS:`
#define LIT_SKYBOX_INTENSITY
#include "envProcPS"
#include "gammaPS"
#include "tonemappingPS"
#ifdef PREPASS_PASS
varying float vLinearDepth;
#include "floatAsUintPS"
#endif
varying vec3 vViewDir;
uniform float skyboxHighlightMultiplier;
#ifdef SKY_CUBEMAP
uniform samplerCube texture_cubeMap;
#ifdef SKYMESH
varying vec3 vWorldPos;
uniform mat3 cubeMapRotationMatrix;
uniform vec3 projectedSkydomeCenter;
#endif
#else
#include "sphericalPS"
#include "envAtlasPS"
uniform sampler2D texture_envAtlas;
uniform float mipLevel;
#endif
void main(void) {
#ifdef PREPASS_PASS
gl_FragColor = float2vec4(vLinearDepth);
#else
#ifdef SKY_CUBEMAP
#ifdef SKYMESH
vec3 envDir = normalize(vWorldPos - projectedSkydomeCenter);
vec3 dir = envDir * cubeMapRotationMatrix;
#else
vec3 dir = vViewDir;
#endif
dir.x *= -1.0;
vec3 linear = {SKYBOX_DECODE_FNC}(textureCube(texture_cubeMap, dir));
#else
vec3 dir = vViewDir * vec3(-1.0, 1.0, 1.0);
vec2 uv = toSphericalUv(normalize(dir));
vec3 linear = {SKYBOX_DECODE_FNC}(texture2D(texture_envAtlas, mapRoughnessUv(uv, mipLevel)));
#endif
if (any(greaterThanEqual(linear, vec3(64.0)))) {
linear *= skyboxHighlightMultiplier;
}
gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);
#endif
}
`,skyboxVS:`
attribute vec4 aPosition;
uniform mat4 matrix_view;
uniform mat4 matrix_projectionSkybox;
uniform mat3 cubeMapRotationMatrix;
varying vec3 vViewDir;
#ifdef PREPASS_PASS
varying float vLinearDepth;
#endif
#ifdef SKYMESH
uniform mat4 matrix_model;
varying vec3 vWorldPos;
#endif
void main(void) {
mat4 view = matrix_view;
#ifdef SKYMESH
vec4 worldPos = matrix_model * aPosition;
vWorldPos = worldPos.xyz;
gl_Position = matrix_projectionSkybox * (view * worldPos);
#ifdef PREPASS_PASS
vLinearDepth = -(matrix_view * vec4(vWorldPos, 1.0)).z;
#endif
#else
view[3][0] = view[3][1] = view[3][2] = 0.0;
gl_Position = matrix_projectionSkybox * (view * aPosition);
vViewDir = aPosition.xyz * cubeMapRotationMatrix;
#ifdef PREPASS_PASS
vLinearDepth = -gl_Position.w;
#endif
#endif
gl_Position.z = gl_Position.w - 1.0e-7;
}
`,specularPS:`
#ifdef STD_SPECULAR_CONSTANT
uniform vec3 material_specular;
#endif
void getSpecularity() {
vec3 specularColor = vec3(1,1,1);
#ifdef STD_SPECULAR_CONSTANT
specularColor *= material_specular;
#endif
#ifdef STD_SPECULAR_TEXTURE
specularColor *= {STD_SPECULAR_TEXTURE_DECODE}(texture2DBias({STD_SPECULAR_TEXTURE_NAME}, {STD_SPECULAR_TEXTURE_UV}, textureBias)).{STD_SPECULAR_TEXTURE_CHANNEL};
#endif
#ifdef STD_SPECULAR_VERTEX
specularColor *= saturate(vVertexColor.{STD_SPECULAR_VERTEX_CHANNEL});
#endif
dSpecularity = specularColor;
}
`,sphericalPS:`
vec2 toSpherical(vec3 dir) {
return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));
}
vec2 toSphericalUv(vec3 dir) {
const float PI = 3.141592653589793;
vec2 uv = toSpherical(dir) / vec2(PI * 2.0, PI) + 0.5;
return vec2(uv.x, 1.0 - uv.y);
}
`,specularityFactorPS:`
#ifdef STD_SPECULARITYFACTOR_CONSTANT
uniform float material_specularityFactor;
#endif
void getSpecularityFactor() {
float specularityFactor = 1.0;
#ifdef STD_SPECULARITYFACTOR_CONSTANT
specularityFactor *= material_specularityFactor;
#endif
#ifdef STD_SPECULARITYFACTOR_TEXTURE
specularityFactor *= texture2DBias({STD_SPECULARITYFACTOR_TEXTURE_NAME}, {STD_SPECULARITYFACTOR_TEXTURE_UV}, textureBias).{STD_SPECULARITYFACTOR_TEXTURE_CHANNEL};
#endif
#ifdef STD_SPECULARITYFACTOR_VERTEX
specularityFactor *= saturate(vVertexColor.{STD_SPECULARITYFACTOR_VERTEX_CHANNEL});
#endif
dSpecularityFactor = specularityFactor;
}
`,spotPS:`
float getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOuterConeAngle, vec3 lightDirNorm) {
float cosAngle = dot(lightDirNorm, lightSpotDir);
return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);
}
`,startNineSlicedPS:`
nineSlicedUv = vec2(vUv0.x, 1.0 - vUv0.y);
`,startNineSlicedTiledPS:`
vec2 tileMask = step(vMask, vec2(0.99999));
vec2 tileSize = 0.5 * (innerOffset.xy + innerOffset.zw);
vec2 tileScale = vec2(1.0) / (vec2(1.0) - tileSize);
vec2 clampedUv = mix(innerOffset.xy * 0.5, vec2(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));
clampedUv = clampedUv * atlasRect.zw + atlasRect.xy;
nineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask);
nineSlicedUv.y = 1.0 - nineSlicedUv.y;
`,stdDeclarationPS:`
float dAlpha = 1.0;
#if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE
#ifdef STD_OPACITY_TEXTURE_ALLOCATE
uniform sampler2D texture_opacityMap;
#endif
#endif
#ifdef FORWARD_PASS
vec3 dAlbedo;
vec3 dNormalW;
vec3 dSpecularity = vec3(0.0);
float dGlossiness = 0.0;
#ifdef LIT_REFRACTION
float dTransmission;
float dThickness;
#endif
#ifdef LIT_SCENE_COLOR
uniform sampler2D uSceneColorMap;
#endif
#ifdef LIT_SCREEN_SIZE
uniform vec4 uScreenSize;
#endif
#ifdef LIT_TRANSFORMS
uniform mat4 matrix_viewProjection;
uniform mat4 matrix_model;
#endif
#ifdef STD_HEIGHT_MAP
vec2 dUvOffset;
#ifdef STD_HEIGHT_TEXTURE_ALLOCATE
uniform sampler2D texture_heightMap;
#endif
#endif
#ifdef STD_DIFFUSE_TEXTURE_ALLOCATE
uniform sampler2D texture_diffuseMap;
#endif
#ifdef STD_DIFFUSEDETAIL_TEXTURE_ALLOCATE
uniform sampler2D texture_diffuseDetailMap;
#endif
#ifdef STD_NORMAL_TEXTURE_ALLOCATE
uniform sampler2D texture_normalMap;
#endif
#ifdef STD_NORMALDETAIL_TEXTURE_ALLOCATE
uniform sampler2D texture_normalDetailMap;
#endif
#ifdef STD_THICKNESS_TEXTURE_ALLOCATE
uniform sampler2D texture_thicknessMap;
#endif
#ifdef STD_REFRACTION_TEXTURE_ALLOCATE
uniform sampler2D texture_refractionMap;
#endif
#ifdef LIT_IRIDESCENCE
float dIridescence;
float dIridescenceThickness;
#ifdef STD_IRIDESCENCE_THICKNESS_TEXTURE_ALLOCATE
uniform sampler2D texture_iridescenceThicknessMap;
#endif
#ifdef STD_IRIDESCENCE_TEXTURE_ALLOCATE
uniform sampler2D texture_iridescenceMap;
#endif
#endif
#ifdef LIT_CLEARCOAT
float ccSpecularity;
float ccGlossiness;
vec3 ccNormalW;
#endif
#ifdef LIT_GGX_SPECULAR
float dAnisotropy;
vec2 dAnisotropyRotation;
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
vec3 sSpecularity;
float sGlossiness;
#ifdef STD_SHEEN_TEXTURE_ALLOCATE
uniform sampler2D texture_sheenMap;
#endif
#ifdef STD_SHEENGLOSS_TEXTURE_ALLOCATE
uniform sampler2D texture_sheenGlossMap;
#endif
#endif
#ifdef LIT_METALNESS
float dMetalness;
float dIor;
#ifdef STD_METALNESS_TEXTURE_ALLOCATE
uniform sampler2D texture_metalnessMap;
#endif
#endif
#ifdef LIT_SPECULARITY_FACTOR
float dSpecularityFactor;
#ifdef STD_SPECULARITYFACTOR_TEXTURE_ALLOCATE
uniform sampler2D texture_specularityFactorMap;
#endif
#endif
#ifdef STD_SPECULAR_COLOR
#ifdef STD_SPECULAR_TEXTURE_ALLOCATE
uniform sampler2D texture_specularMap;
#endif
#endif
#ifdef STD_GLOSS_TEXTURE_ALLOCATE
uniform sampler2D texture_glossMap;
#endif
#endif
#ifdef STD_AO
float dAo;
#ifdef STD_AO_TEXTURE_ALLOCATE
uniform sampler2D texture_aoMap;
#endif
#ifdef STD_AODETAIL_TEXTURE_ALLOCATE
uniform sampler2D texture_aoDetailMap;
#endif
#endif
vec3 dEmission;
#ifdef STD_EMISSIVE_TEXTURE_ALLOCATE
uniform sampler2D texture_emissiveMap;
#endif
#ifdef LIT_CLEARCOAT
#ifdef STD_CLEARCOAT_TEXTURE_ALLOCATE
uniform sampler2D texture_clearCoatMap;
#endif
#ifdef STD_CLEARCOATGLOSS_TEXTURE_ALLOCATE
uniform sampler2D texture_clearCoatGlossMap;
#endif
#ifdef STD_CLEARCOATNORMAL_TEXTURE_ALLOCATE
uniform sampler2D texture_clearCoatNormalMap;
#endif
#endif
#ifdef LIT_GGX_SPECULAR
#ifdef STD_ANISOTROPY_TEXTURE_ALLOCATE
uniform sampler2D texture_anisotropyMap;
#endif
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
vec3 dLightmap;
#ifdef STD_LIGHT_TEXTURE_ALLOCATE
uniform sampler2D texture_lightMap;
#endif
#endif
#endif
#include "litShaderCorePS"
`,stdFrontEndPS:`
#if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE
#include "opacityPS"
#if defined(LIT_ALPHA_TEST)
#include "alphaTestPS"
#endif
#if STD_OPACITY_DITHER != NONE
#include "opacityDitherPS"
#endif
#endif
#ifdef FORWARD_PASS
#ifdef STD_HEIGHT_MAP
#include "parallaxPS"
#endif
#include "diffusePS"
#ifdef LIT_NEEDS_NORMAL
#include "normalMapPS"
#endif
#ifdef LIT_REFRACTION
#include "transmissionPS"
#include "thicknessPS"
#endif
#ifdef LIT_IRIDESCENCE
#include "iridescencePS"
#include "iridescenceThicknessPS"
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
#include "sheenPS"
#include "sheenGlossPS"
#endif
#ifdef LIT_METALNESS
#include "metalnessPS"
#include "iorPS"
#endif
#ifdef LIT_SPECULARITY_FACTOR
#include "specularityFactorPS"
#endif
#ifdef STD_SPECULAR_COLOR
#include "specularPS"
#else
void getSpecularity() {
dSpecularity = vec3(1);
}
#endif
#include "glossPS"
#endif
#ifdef STD_AO
#include "aoPS"
#endif
#include "emissivePS"
#ifdef LIT_CLEARCOAT
#include "clearCoatPS"
#include "clearCoatGlossPS"
#include "clearCoatNormalPS"
#endif
#if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)
#include "anisotropyPS"
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
#include "lightmapPS"
#endif
#endif
void evaluateFrontend() {
#if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE
getOpacity();
#if defined(LIT_ALPHA_TEST)
alphaTest(dAlpha);
#endif
#if STD_OPACITY_DITHER != NONE
opacityDither(dAlpha, 0.0);
#endif
litArgs_opacity = dAlpha;
#endif
#ifdef FORWARD_PASS
#ifdef STD_HEIGHT_MAP
getParallax();
#endif
getAlbedo();
litArgs_albedo = dAlbedo;
#ifdef LIT_NEEDS_NORMAL
getNormal();
litArgs_worldNormal = dNormalW;
#endif
#ifdef LIT_REFRACTION
getRefraction();
litArgs_transmission = dTransmission;
getThickness();
litArgs_thickness = dThickness;
#ifdef LIT_DISPERSION
litArgs_dispersion = material_dispersion;
#endif
#endif
#ifdef LIT_IRIDESCENCE
getIridescence();
getIridescenceThickness();
litArgs_iridescence_intensity = dIridescence;
litArgs_iridescence_thickness = dIridescenceThickness;
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
getSheen();
litArgs_sheen_specularity = sSpecularity;
getSheenGlossiness();
litArgs_sheen_gloss = sGlossiness;
#endif
#ifdef LIT_METALNESS
getMetalness();
litArgs_metalness = dMetalness;
getIor();
litArgs_ior = dIor;
#endif
#ifdef LIT_SPECULARITY_FACTOR
getSpecularityFactor();
litArgs_specularityFactor = dSpecularityFactor;
#endif
getGlossiness();
getSpecularity();
litArgs_specularity = dSpecularity;
litArgs_gloss = dGlossiness;
#endif
#ifdef STD_AO
getAO();
litArgs_ao = dAo;
#endif
getEmission();
litArgs_emission = dEmission;
#ifdef LIT_CLEARCOAT
getClearCoat();
getClearCoatGlossiness();
getClearCoatNormal();
litArgs_clearcoat_specularity = ccSpecularity;
litArgs_clearcoat_gloss = ccGlossiness;
litArgs_clearcoat_worldNormal = ccNormalW;
#endif
#if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)
getAnisotropy();
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
getLightMap();
litArgs_lightmap = dLightmap;
#ifdef STD_LIGHTMAP_DIR
litArgs_lightmapDir = dLightmapDir;
#endif
#endif
#endif
}
`,TBNPS:`
#ifdef LIT_TANGENTS
#define TBN_TANGENTS
#else
#if defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS)
#define TBN_DERIVATIVES
#endif
#endif
#if defined(TBN_DERIVATIVES)
uniform float tbnBasis;
#endif
void getTBN(vec3 tangent, vec3 binormal, vec3 normal) {
#ifdef TBN_TANGENTS
dTBN = mat3(normalize(tangent), normalize(binormal), normalize(normal));
#elif defined(TBN_DERIVATIVES)
vec2 uv = {lightingUv};
vec3 dp1 = dFdx( vPositionW );
vec3 dp2 = dFdy( vPositionW );
vec2 duv1 = dFdx( uv );
vec2 duv2 = dFdy( uv );
vec3 dp2perp = cross( dp2, normal );
vec3 dp1perp = cross( normal, dp1 );
vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;
vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;
float denom = max( dot(T,T), dot(B,B) );
float invmax = (denom == 0.0) ? 0.0 : tbnBasis / sqrt( denom );
dTBN = mat3(T * invmax, -B * invmax, normal );
#else
vec3 B = cross(normal, vObjectSpaceUpW);
vec3 T = cross(normal, B);
if (dot(B,B)==0.0)
{
float major=max(max(normal.x, normal.y), normal.z);
if (normal.x == major)
{
B = cross(normal, vec3(0,1,0));
T = cross(normal, B);
}
else if (normal.y == major)
{
B = cross(normal, vec3(0,0,1));
T = cross(normal, B);
}
else if (normal.z == major)
{
B = cross(normal, vec3(1,0,0));
T = cross(normal, B);
}
}
dTBN = mat3(normalize(T), normalize(B), normalize(normal));
#endif
}
`,thicknessPS:`
#ifdef STD_THICKNESS_CONSTANT
uniform float material_thickness;
#endif
void getThickness() {
dThickness = 1.0;
#ifdef STD_THICKNESS_CONSTANT
dThickness *= material_thickness;
#endif
#ifdef STD_THICKNESS_TEXTURE
dThickness *= texture2DBias({STD_THICKNESS_TEXTURE_NAME}, {STD_THICKNESS_TEXTURE_UV}, textureBias).{STD_THICKNESS_TEXTURE_CHANNEL};
#endif
#ifdef STD_THICKNESS_VERTEX
dThickness *= saturate(vVertexColor.{STD_THICKNESS_VERTEX_CHANNEL});
#endif
}
`,tonemappingPS:`
#if (TONEMAP == NONE)
#include "tonemappingNonePS"
#elif TONEMAP == FILMIC
#include "tonemappingFilmicPS"
#elif TONEMAP == LINEAR
#include "tonemappingLinearPS"
#elif TONEMAP == HEJL
#include "tonemappingHejlPS"
#elif TONEMAP == ACES
#include "tonemappingAcesPS"
#elif TONEMAP == ACES2
#include "tonemappingAces2PS"
#elif TONEMAP == NEUTRAL
#include "tonemappingNeutralPS"
#endif
`,tonemappingAcesPS:`
uniform float exposure;
vec3 toneMap(vec3 color) {
float tA = 2.51;
float tB = 0.03;
float tC = 2.43;
float tD = 0.59;
float tE = 0.14;
vec3 x = color * exposure;
return (x*(tA*x+tB))/(x*(tC*x+tD)+tE);
}
`,tonemappingAces2PS:`
uniform float exposure;
const mat3 ACESInputMat = mat3(
0.59719, 0.35458, 0.04823,
0.07600, 0.90834, 0.01566,
0.02840, 0.13383, 0.83777
);
const mat3 ACESOutputMat = mat3(
1.60475, -0.53108, -0.07367,
-0.10208, 1.10813, -0.00605,
-0.00327, -0.07276, 1.07602
);
vec3 RRTAndODTFit(vec3 v) {
vec3 a = v * (v + 0.0245786) - 0.000090537;
vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;
return a / b;
}
vec3 toneMap(vec3 color) {
color *= exposure / 0.6;
color = color * ACESInputMat;
color = RRTAndODTFit(color);
color = color * ACESOutputMat;
color = clamp(color, 0.0, 1.0);
return color;
}
`,tonemappingFilmicPS:`
const float A = 0.15;
const float B = 0.50;
const float C = 0.10;
const float D = 0.20;
const float E = 0.02;
const float F = 0.30;
const float W = 11.2;
uniform float exposure;
vec3 uncharted2Tonemap(vec3 x) {
return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;
}
vec3 toneMap(vec3 color) {
color = uncharted2Tonemap(color * exposure);
vec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W));
color = color * whiteScale;
return color;
}
`,tonemappingHejlPS:`
uniform float exposure;
vec3 toneMap(vec3 color) {
color *= exposure;
const float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3;
const float Scl = 1.25;
vec3 h = max( vec3(0.0), color - vec3(0.004) );
return (h*((Scl*A)*h+Scl*vec3(C*B,C*B,C*B))+Scl*vec3(D*E,D*E,D*E)) / (h*(A*h+vec3(B,B,B))+vec3(D*F,D*F,D*F)) - Scl*vec3(E/F,E/F,E/F);
}
`,tonemappingLinearPS:`
uniform float exposure;
vec3 toneMap(vec3 color) {
return color * exposure;
}
`,tonemappingNeutralPS:`
uniform float exposure;
vec3 toneMap(vec3 color) {
color *= exposure;
float startCompression = 0.8 - 0.04;
float desaturation = 0.15;
float x = min(color.r, min(color.g, color.b));
float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
color -= offset;
float peak = max(color.r, max(color.g, color.b));
if (peak < startCompression) return color;
float d = 1. - startCompression;
float newPeak = 1. - d * d / (peak + d - startCompression);
color *= newPeak / peak;
float g = 1. - 1. / (desaturation * (peak - newPeak) + 1.);
return mix(color, newPeak * vec3(1, 1, 1), g);
}
`,tonemappingNonePS:`
vec3 toneMap(vec3 color) {
return color;
}
`,transformVS:`
#ifdef PIXELSNAP
uniform vec4 uScreenSize;
#endif
#ifdef SCREENSPACE
uniform float projectionFlipY;
#endif
vec4 evalWorldPosition(vec3 vertexPosition, mat4 modelMatrix) {
vec3 localPos = getLocalPosition(vertexPosition);
#ifdef NINESLICED
localPos.xz *= outerScale;
vec2 positiveUnitOffset = clamp(vertexPosition.xz, vec2(0.0), vec2(1.0));
vec2 negativeUnitOffset = clamp(-vertexPosition.xz, vec2(0.0), vec2(1.0));
localPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;
vTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0;
localPos.xz *= -0.5;
localPos = localPos.xzy;
#endif
vec4 posW = modelMatrix * vec4(localPos, 1.0);
#ifdef SCREENSPACE
posW.zw = vec2(0.0, 1.0);
#endif
return posW;
}
vec4 getPosition() {
dModelMatrix = getModelMatrix();
vec4 posW = evalWorldPosition(vertex_position.xyz, dModelMatrix);
dPositionW = posW.xyz;
vec4 screenPos;
#ifdef UV1LAYOUT
screenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1);
#ifdef WEBGPU
screenPos.y *= -1.0;
#endif
#else
#ifdef SCREENSPACE
screenPos = posW;
screenPos.y *= projectionFlipY;
#else
screenPos = matrix_viewProjection * posW;
#endif
#ifdef PIXELSNAP
screenPos.xy = (screenPos.xy * 0.5) + 0.5;
screenPos.xy *= uScreenSize.xy;
screenPos.xy = floor(screenPos.xy);
screenPos.xy *= uScreenSize.zw;
screenPos.xy = (screenPos.xy * 2.0) - 1.0;
#endif
#endif
return screenPos;
}
vec3 getWorldPosition() {
return dPositionW;
}
`,transformCoreVS:`
attribute vec4 vertex_position;
uniform mat4 matrix_viewProjection;
uniform mat4 matrix_model;
#ifdef MORPHING
uniform vec2 morph_tex_params;
attribute uint morph_vertex_id;
ivec2 getTextureMorphCoords() {
ivec2 textureSize = ivec2(morph_tex_params);
int morphGridV = int(morph_vertex_id) / textureSize.x;
int morphGridU = int(morph_vertex_id) - (morphGridV * textureSize.x);
#ifdef WEBGPU
morphGridV = textureSize.y - morphGridV - 1;
#endif
return ivec2(morphGridU, morphGridV);
}
#ifdef MORPHING_POSITION
#ifdef MORPHING_INT
uniform vec3 aabbSize;
uniform vec3 aabbMin;
uniform usampler2D morphPositionTex;
#else
uniform highp sampler2D morphPositionTex;
#endif
#endif
#endif
#ifdef defined(BATCH)
#include "skinBatchVS"
mat4 getModelMatrix() {
return getBoneMatrix(vertex_boneIndices);
}
#elif defined(SKIN)
#include "skinVS"
mat4 getModelMatrix() {
return matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);
}
#elif defined(INSTANCING)
#include "transformInstancingVS"
#else
mat4 getModelMatrix() {
return matrix_model;
}
#endif
vec3 getLocalPosition(vec3 vertexPosition) {
vec3 localPos = vertexPosition;
#ifdef MORPHING_POSITION
ivec2 morphUV = getTextureMorphCoords();
#ifdef MORPHING_INT
vec3 morphPos = vec3(texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz) / 65535.0 * aabbSize + aabbMin;
#else
vec3 morphPos = texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz;
#endif
localPos += morphPos;
#endif
return localPos;
}
`,transformInstancingVS:`
attribute vec4 instance_line1;
attribute vec4 instance_line2;
attribute vec4 instance_line3;
attribute vec4 instance_line4;
mat4 getModelMatrix() {
return matrix_model * mat4(instance_line1, instance_line2, instance_line3, instance_line4);
}
`,transmissionPS:`
#ifdef STD_REFRACTION_CONSTANT
uniform float material_refraction;
#endif
void getRefraction() {
float refraction = 1.0;
#ifdef STD_REFRACTION_CONSTANT
refraction = material_refraction;
#endif
#ifdef STD_REFRACTION_TEXTURE
refraction *= texture2DBias({STD_REFRACTION_TEXTURE_NAME}, {STD_REFRACTION_TEXTURE_UV}, textureBias).{STD_REFRACTION_TEXTURE_CHANNEL};
#endif
#ifdef STD_REFRACTION_VERTEX
refraction *= saturate(vVertexColor.{STD_REFRACTION_VERTEX_CHANNEL});
#endif
dTransmission = refraction;
}
`,twoSidedLightingPS:`
uniform float twoSidedLightingNegScaleFactor;
void handleTwoSidedLighting() {
dTBN[2] *= gl_FrontFacing ? twoSidedLightingNegScaleFactor : -twoSidedLightingNegScaleFactor;
}
`,uv0VS:`
#ifdef NINESLICED
vec2 getUv0() {
vec2 uv = vertex_position.xz;
vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));
vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));
uv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;
uv = uv * -0.5 + 0.5;
uv = uv * atlasRect.zw + atlasRect.xy;
vMask = vertex_texCoord0.xy;
return uv;
}
#else
vec2 getUv0() {
return vertex_texCoord0;
}
#endif
`,uv1VS:`
vec2 getUv1() {
return vertex_texCoord1;
}
`,uvTransformVS:`
vUV{TRANSFORM_UV_{i}}_{TRANSFORM_ID_{i}} = vec2(
dot(vec3(uv{TRANSFORM_UV_{i}}, 1), {TRANSFORM_NAME_{i}}0),
dot(vec3(uv{TRANSFORM_UV_{i}}, 1), {TRANSFORM_NAME_{i}}1)
);
`,uvTransformUniformsPS:`
uniform vec3 {TRANSFORM_NAME_{i}}0;
uniform vec3 {TRANSFORM_NAME_{i}}1;
`,viewDirPS:`
void getViewDir() {
dViewDirW = normalize(view_position - vPositionW);
}
`,webgpuPS:o8,webgpuVS:o6},x8={alphaTestPS:`
uniform alpha_ref: f32;
fn alphaTest(a: f32) {
if (a < uniform.alpha_ref) {
discard;
}
}
`,ambientPS:`
#if LIT_AMBIENT_SOURCE == AMBIENTSH
uniform ambientSH: array<vec3f, 9>;
#endif
#if LIT_AMBIENT_SOURCE == ENVALATLAS
#include "envAtlasPS"
#ifndef ENV_ATLAS
#define ENV_ATLAS
var texture_envAtlas: texture_2d<f32>;
var texture_envAtlasSampler: sampler;
#endif
#endif
fn addAmbient(worldNormal: vec3f) {
#ifdef LIT_AMBIENT_SOURCE == AMBIENTSH
let n: vec3f = cubeMapRotate(worldNormal);
let color: vec3f =
uniform.ambientSH[0] +
uniform.ambientSH[1] * n.x +
uniform.ambientSH[2] * n.y +
uniform.ambientSH[3] * n.z +
uniform.ambientSH[4] * n.x * n.z +
uniform.ambientSH[5] * n.z * n.y +
uniform.ambientSH[6] * n.y * n.x +
uniform.ambientSH[7] * (3.0 * n.z * n.z - 1.0) +
uniform.ambientSH[8] * (n.x * n.x - n.y * n.y);
dDiffuseLight += processEnvironment(max(color, vec3f(0.0)));
#endif
#if LIT_AMBIENT_SOURCE == ENVALATLAS
let dir: vec3f = normalize(cubeMapRotate(worldNormal) * vec3f(-1.0, 1.0, 1.0));
let uv: vec2f = mapUv(toSphericalUv(dir), vec4f(128.0, 256.0 + 128.0, 64.0, 32.0) / atlasSize);
let raw: vec4f = textureSample(texture_envAtlas, texture_envAtlasSampler, uv);
let linear: vec3f = {ambientDecode}(raw);
dDiffuseLight += processEnvironment(linear);
#endif
#if LIT_AMBIENT_SOURCE == CONSTANT
dDiffuseLight += uniform.light_globalAmbient;
#endif
}
`,anisotropyPS:`
#ifdef LIT_GGX_SPECULAR
uniform material_anisotropyIntensity: f32;
uniform material_anisotropyRotation: vec2f;
#endif
fn getAnisotropy() {
dAnisotropy = 0.0;
dAnisotropyRotation = vec2f(1.0, 0.0);
#ifdef LIT_GGX_SPECULAR
dAnisotropy = uniform.material_anisotropyIntensity;
dAnisotropyRotation = uniform.material_anisotropyRotation;
#endif
#ifdef STD_ANISOTROPY_TEXTURE
let anisotropyTex: vec3f = textureSampleBias({STD_ANISOTROPY_TEXTURE_NAME}, {STD_ANISOTROPY_TEXTURE_NAME}Sampler, {STD_ANISOTROPY_TEXTURE_UV}, uniform.textureBias).rgb;
dAnisotropy *= anisotropyTex.b;
let anisotropyRotationFromTex: vec2f = anisotropyTex.rg * 2.0 - vec2f(1.0);
let rotationMatrix: mat2x2f = mat2x2f(dAnisotropyRotation.x, dAnisotropyRotation.y, -dAnisotropyRotation.y, dAnisotropyRotation.x);
dAnisotropyRotation = rotationMatrix * anisotropyRotationFromTex;
#endif
dAnisotropy = clamp(dAnisotropy, 0.0, 1.0);
}
`,aoPS:`
#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX)
uniform material_aoIntensity: f32;
#endif
#ifdef STD_AODETAIL_TEXTURE
#include "detailModesPS"
#endif
fn getAO() {
dAo = 1.0;
#ifdef STD_AO_TEXTURE
var aoBase: f32 = textureSampleBias({STD_AO_TEXTURE_NAME}, {STD_AO_TEXTURE_NAME}Sampler, {STD_AO_TEXTURE_UV}, uniform.textureBias).{STD_AO_TEXTURE_CHANNEL};
#ifdef STD_AODETAIL_TEXTURE
var aoDetail: f32 = textureSampleBias({STD_AODETAIL_TEXTURE_NAME}, {STD_AODETAIL_TEXTURE_NAME}Sampler, {STD_AODETAIL_TEXTURE_UV}, uniform.textureBias).{STD_AODETAIL_TEXTURE_CHANNEL};
aoBase = detailMode_{STD_AODETAIL_DETAILMODE}(vec3f(aoBase), vec3f(aoDetail)).r;
#endif
dAo = dAo * aoBase;
#endif
#ifdef STD_AO_VERTEX
dAo = dAo * saturate(vVertexColor.{STD_AO_VERTEX_CHANNEL});
#endif
#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX)
dAo = mix(1.0, dAo, uniform.material_aoIntensity);
#endif
}
`,aoDiffuseOccPS:`
fn occludeDiffuse(ao: f32) {
dDiffuseLight = dDiffuseLight * ao;
}
`,aoSpecOccPS:`
#if LIT_OCCLUDE_SPECULAR != NONE
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
uniform material_occludeSpecularIntensity: f32;
#endif
#endif
fn occludeSpecular(gloss: f32, ao: f32, worldNormal: vec3f, viewDir: vec3f) {
#if LIT_OCCLUDE_SPECULAR == AO
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
var specOcc: f32 = mix(1.0, ao, uniform.material_occludeSpecularIntensity);
#else
var specOcc: f32 = ao;
#endif
#endif
#if LIT_OCCLUDE_SPECULAR == GLOSSDEPENDENT
var specPow: f32 = exp2(gloss * 11.0);
var specOcc: f32 = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01 * specPow) - 1.0 + ao);
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
specOcc = mix(1.0, specOcc, uniform.material_occludeSpecularIntensity);
#endif
#endif
#if LIT_OCCLUDE_SPECULAR != NONE
dSpecularLight = dSpecularLight * specOcc;
dReflection = dReflection * specOcc;
#ifdef LIT_SHEEN
sSpecularLight = sSpecularLight * specOcc;
sReflection = sReflection * specOcc;
#endif
#endif
}
`,bakeDirLmEndPS:`
let dirLm = textureSample(texture_dirLightMap, texture_dirLightMapSampler, vUv1);
if (uniform.bakeDir > 0.5) {
if (dAtten > 0.00001) {
let unpacked_dir = dirLm.xyz * 2.0 - vec3f(1.0);
dAtten = clamp(dAtten, 0.0, 1.0);
let combined_dir = dLightDirNormW.xyz * dAtten + unpacked_dir * dirLm.w;
let finalRgb = normalize(combined_dir) * 0.5 + vec3f(0.5);
let finalA = max(dirLm.w + dAtten, 1.0 / 255.0);
output.color = vec4f(finalRgb, finalA);
} else {
output.color = dirLm;
}
} else {
let alpha_min = select(0.0, 1.0 / 255.0, dAtten > 0.00001);
let finalA = max(dirLm.w, alpha_min);
output.color = vec4f(dirLm.rgb, finalA);
}
`,bakeLmEndPS:`
#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT
dDiffuseLight = ((dDiffuseLight - 0.5) * max(uniform.ambientBakeOcclusionContrast + 1.0, 0.0)) + 0.5;
dDiffuseLight = dDiffuseLight + vec3f(uniform.ambientBakeOcclusionBrightness);
dDiffuseLight = saturate3(dDiffuseLight);
dDiffuseLight = dDiffuseLight * dAmbientLight;
#endif
#ifdef LIGHTMAP_RGBM
var temp_color_rgbm = vec4f(dDiffuseLight, 1.0);
temp_color_rgbm = vec4f(pow(temp_color_rgbm.rgb, vec3f(0.5)), temp_color_rgbm.a);
temp_color_rgbm = vec4f(temp_color_rgbm.rgb / 8.0, temp_color_rgbm.a);
let max_g_b = max(temp_color_rgbm.g, max(temp_color_rgbm.b, 1.0 / 255.0));
let max_rgb = max(temp_color_rgbm.r, max_g_b);
temp_color_rgbm.a = clamp(max_rgb, 0.0, 1.0);
temp_color_rgbm.a = ceil(temp_color_rgbm.a * 255.0) / 255.0;
temp_color_rgbm = vec4f(temp_color_rgbm.rgb / temp_color_rgbm.a, temp_color_rgbm.a);
output.color = temp_color_rgbm;
#else
output.color = vec4f(dDiffuseLight, 1.0);
#endif
`,basePS:`
uniform view_position: vec3f;
uniform light_globalAmbient: vec3f;
fn square(x: f32) -> f32 {
return x*x;
}
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
fn saturate3(x: vec3f) -> vec3f {
return clamp(x, vec3f(0.0), vec3f(1.0));
}
`,baseNineSlicedPS:`
#define NINESLICED
varying vMask: vec2f;
varying vTiledUv: vec2f;
uniform innerOffset: vec4f;
uniform outerScale: vec2f;
uniform atlasRect: vec4f;
var<private> nineSlicedUv: vec2f;
`,baseNineSlicedTiledPS:`
#define NINESLICED
#define NINESLICETILED
varying vMask: vec2f;
varying vTiledUv: vec2f;
uniform innerOffset: vec4f;
uniform outerScale: vec2f;
uniform atlasRect: vec4f;
var<private> nineSlicedUv: vec2f;
`,bayerPS:`
fn bayer2(p: vec2f) -> f32 {
return (2.0 * p.y + p.x + 1.0) % 4.0;
}
fn bayer4(p: vec2f) -> f32 {
let p1: vec2f = p % vec2f(2.0);
let p2: vec2f = floor(0.5 * (p % vec2f(4.0)));
return 4.0 * bayer2(p1) + bayer2(p2);
}
fn bayer8(p: vec2f) -> f32 {
let p1: vec2f = p % vec2f(2.0);
let p2: vec2f = floor(0.5 * (p % vec2f(4.0)));
let p4: vec2f = floor(0.25 * (p % vec2f(8.0)));
return 4.0 * (4.0 * bayer2(p1) + bayer2(p2)) + bayer2(p4);
}
`,blurVSMPS:`
varying vUv0: vec2f;
var source: texture_2d<f32>;
var sourceSampler: sampler;
#ifdef GAUSS
uniform weight: array<f32, {SAMPLES}>;
#endif
uniform pixelOffset: vec2f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
var moments: vec3f = vec3f(0.0);
let uv: vec2f = input.vUv0 - uniform.pixelOffset * (f32({SAMPLES}) * 0.5);
for (var i: i32 = 0; i < {SAMPLES}; i = i + 1) {
let c: vec4f = textureSample(source, sourceSampler, uv + uniform.pixelOffset * f32(i));
#ifdef GAUSS
moments = moments + c.xyz * uniform.weight[i].element;
#else
moments = moments + c.xyz;
#endif
}
#ifndef GAUSS
moments = moments * (1.0 / f32({SAMPLES}));
#endif
output.color = vec4f(moments, 1.0);
return output;
}
`,clearCoatPS:`
uniform material_clearCoat: f32;
fn getClearCoat() {
ccSpecularity = uniform.material_clearCoat;
#ifdef STD_CLEARCOAT_TEXTURE
ccSpecularity = ccSpecularity * textureSampleBias({STD_CLEARCOAT_TEXTURE_NAME}, {STD_CLEARCOAT_TEXTURE_NAME}Sampler, {STD_CLEARCOAT_TEXTURE_UV}, uniform.textureBias).{STD_CLEARCOAT_TEXTURE_CHANNEL};
#endif
#ifdef STD_CLEARCOAT_VERTEX
ccSpecularity = ccSpecularity * saturate(vVertexColor.{STD_CLEARCOAT_VERTEX_CHANNEL});
#endif
}
`,clearCoatGlossPS:`
uniform material_clearCoatGloss: f32;
fn getClearCoatGlossiness() {
ccGlossiness = uniform.material_clearCoatGloss;
#ifdef STD_CLEARCOATGLOSS_TEXTURE
ccGlossiness = ccGlossiness * textureSampleBias({STD_CLEARCOATGLOSS_TEXTURE_NAME}, {STD_CLEARCOATGLOSS_TEXTURE_NAME}Sampler, {STD_CLEARCOATGLOSS_TEXTURE_UV}, uniform.textureBias).{STD_CLEARCOATGLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_CLEARCOATGLOSS_VERTEX
ccGlossiness = ccGlossiness * saturate(vVertexColor.{STD_CLEARCOATGLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_CLEARCOATGLOSS_INVERT
ccGlossiness = 1.0 - ccGlossiness;
#endif
ccGlossiness += 0.0000001;
}
`,clearCoatNormalPS:`
#ifdef STD_CLEARCOATNORMAL_TEXTURE
uniform material_clearCoatBumpiness: f32;
#endif
fn getClearCoatNormal() {
#ifdef STD_CLEARCOATNORMAL_TEXTURE
var normalMap: vec3f = {STD_CLEARCOATNORMAL_TEXTURE_DECODE}(textureSampleBias({STD_CLEARCOATNORMAL_TEXTURE_NAME}, {STD_CLEARCOATNORMAL_TEXTURE_NAME}Sampler, {STD_CLEARCOATNORMAL_TEXTURE_UV}, uniform.textureBias));
normalMap = mix(vec3f(0.0, 0.0, 1.0), normalMap, uniform.material_clearCoatBumpiness);
ccNormalW = normalize(dTBN * normalMap);
#else
ccNormalW = dVertexNormalW;
#endif
}
`,clusteredLightCookiesPS:`
fn _getCookieClustered(tex: texture_2d<f32>, texSampler: sampler, uv: vec2f, intensity: f32, cookieChannel: vec4f) -> vec3f {
let pixel: vec4f = mix(vec4f(1.0), textureSampleLevel(tex, texSampler, uv, 0.0), intensity);
let isRgb: bool = dot(cookieChannel.rgb, vec3f(1.0)) == 3.0;
return select(vec3f(dot(pixel, cookieChannel)), pixel.rgb, isRgb);
}
fn getCookie2DClustered(tex: texture_2d<f32>, texSampler: sampler, transform: mat4x4f, worldPosition: vec3f, intensity: f32, cookieChannel: vec4f) -> vec3f {
let projPos: vec4f = transform * vec4f(worldPosition, 1.0);
return _getCookieClustered(tex, texSampler, projPos.xy / projPos.w, intensity, cookieChannel);
}
fn getCookieCubeClustered(tex: texture_2d<f32>, texSampler: sampler, dir: vec3f, intensity: f32, cookieChannel: vec4f, shadowTextureResolution: f32, shadowEdgePixels: f32, omniAtlasViewport: vec3f) -> vec3f {
let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);
return _getCookieClustered(tex, texSampler, uv, intensity, cookieChannel);
}
`,clusteredLightShadowsPS:`
fn _getShadowCoordPerspZbuffer(shadowMatrix: mat4x4f, shadowParams: vec4f, wPos: vec3f) -> vec3f {
var projPos = shadowMatrix * vec4f(wPos, 1.0);
return projPos.xyz / projPos.w;
}
fn getShadowCoordPerspZbufferNormalOffset(shadowMatrix: mat4x4f, shadowParams: vec4f, normal: vec3f) -> vec3f {
let wPos: vec3f = vPositionW + normal * shadowParams.y;
return _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);
}
fn normalOffsetPointShadow(shadowParams: vec4f, lightPos: vec3f, lightDir: vec3f, lightDirNorm: vec3f, normal: vec3f) -> vec3f {
let distScale: f32 = length(lightDir);
let wPos: vec3f = vPositionW + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
let dir: vec3f = wPos - lightPos;
return dir;
}
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
fn getShadowOmniClusteredPCF1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 {
let shadowTextureResolution: f32 = shadowParams.x;
let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z;
return textureSampleCompareLevel(shadowMap, shadowMapSampler, uv, shadowZ);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF3)
fn getShadowOmniClusteredPCF3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 {
let shadowTextureResolution: f32 = shadowParams.x;
let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z;
let shadowCoord: vec3f = vec3f(uv, shadowZ);
return getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF5)
fn getShadowOmniClusteredPCF5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 {
let shadowTextureResolution: f32 = shadowParams.x;
let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z;
let shadowCoord: vec3f = vec3f(uv, shadowZ);
return getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
fn getShadowSpotClusteredPCF1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF3)
fn getShadowSpotClusteredPCF3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return getShadowSpotPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF5)
fn getShadowSpotClusteredPCF5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams);
}
#endif
`,clusteredLightUtilsPS:`
struct FaceCoords {
uv: vec2f,
faceIndex: f32,
tileOffset: vec2f,
}
fn getCubemapFaceCoordinates(dir: vec3f) -> FaceCoords {
var faceIndex: f32;
var tileOffset: vec2f;
var uv: vec2f;
let vAbs: vec3f = abs(dir);
var ma: f32;
if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) {
let is_neg_z = dir.z < 0.0;
faceIndex = select(4.0, 5.0, is_neg_z);
ma = 0.5 / vAbs.z;
uv = vec2f(select(dir.x, -dir.x, is_neg_z), -dir.y);
tileOffset = vec2f(2.0, select(0.0, 1.0, is_neg_z));
} else if (vAbs.y >= vAbs.x) {
let is_neg_y = dir.y < 0.0;
faceIndex = select(2.0, 3.0, is_neg_y);
ma = 0.5 / vAbs.y;
uv = vec2f(dir.x, select(dir.z, -dir.z, is_neg_y));
tileOffset = vec2f(1.0, select(0.0, 1.0, is_neg_y));
} else {
let is_neg_x = dir.x < 0.0;
faceIndex = select(0.0, 1.0, is_neg_x);
ma = 0.5 / vAbs.x;
uv = vec2f(select(-dir.z, dir.z, is_neg_x), -dir.y);
tileOffset = vec2f(0.0, select(0.0, 1.0, is_neg_x));
}
uv = uv * ma + 0.5;
return FaceCoords(uv, faceIndex, tileOffset);
}
fn getCubemapAtlasCoordinates(omniAtlasViewport: vec3f, shadowEdgePixels: f32, shadowTextureResolution: f32, dir: vec3f) -> vec2f {
let faceData: FaceCoords = getCubemapFaceCoordinates(dir);
var uv: vec2f = faceData.uv;
let tileOffset: vec2f = faceData.tileOffset;
let atlasFaceSize: f32 = omniAtlasViewport.z;
let tileSize: f32 = shadowTextureResolution * atlasFaceSize;
var offset: f32 = shadowEdgePixels / tileSize;
uv = uv * (1.0 - offset * 2.0) + offset;
uv = uv * atlasFaceSize;
uv = uv + tileOffset * atlasFaceSize;
uv = uv + omniAtlasViewport.xy;
return uv;
}
`,clusteredLightPS:`
#include "lightBufferDefinesPS"
#include "clusteredLightUtilsPS"
#ifdef CLUSTER_COOKIES
#include "clusteredLightCookiesPS"
#endif
#ifdef CLUSTER_SHADOWS
#include "clusteredLightShadowsPS"
#endif
var clusterWorldTexture: texture_2d<f32>;
var lightsTexture: texture_2d<f32>;
#ifdef CLUSTER_SHADOWS
var shadowAtlasTexture: texture_depth_2d;
var shadowAtlasTextureSampler: sampler_comparison;
#endif
#ifdef CLUSTER_COOKIES
var cookieAtlasTexture: texture_2d<f32>;
var cookieAtlasTextureSampler: sampler;
#endif
uniform clusterMaxCells: i32;
uniform clusterSkip: f32;
uniform clusterCellsCountByBoundsSize: vec3f;
uniform clusterTextureSize: vec3f;
uniform clusterBoundsMin: vec3f;
uniform clusterBoundsDelta: vec3f;
uniform clusterCellsDot: vec3f;
uniform clusterCellsMax: vec3f;
uniform shadowAtlasParams: vec2f;
struct ClusterLightData {
flags: u32,
halfWidth: vec3f,
isSpot: bool,
halfHeight: vec3f,
lightIndex: i32,
position: vec3f,
shape: u32,
direction: vec3f,
falloffModeLinear: bool,
color: vec3f,
shadowIntensity: f32,
omniAtlasViewport: vec3f,
range: f32,
cookieChannelMask: vec4f,
biasesData: f32,
shadowBias: f32,
shadowNormalBias: f32,
anglesData: f32,
innerConeAngleCos: f32,
outerConeAngleCos: f32,
cookieIntensity: f32,
isDynamic: bool,
isLightmapped: bool
}
var<private> lightProjectionMatrix: mat4x4f;
fn sampleLightTextureF(lightIndex: i32, index: i32) -> vec4f {
return textureLoad(lightsTexture, vec2<i32>(index, lightIndex), 0);
}
fn decodeClusterLightCore(clusterLightData: ptr<function, ClusterLightData>, lightIndex: f32) {
clusterLightData.lightIndex = i32(lightIndex);
let halfData: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS});
clusterLightData.anglesData = halfData.z;
clusterLightData.biasesData = halfData.w;
let colorRG: vec2f = unpack2x16float(bitcast<u32>(halfData.x));
let colorB_: vec2f = unpack2x16float(bitcast<u32>(halfData.y));
clusterLightData.color = vec3f(colorRG, colorB_.x) * {LIGHT_COLOR_DIVIDER};
let lightPosRange: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_POSITION_RANGE});
clusterLightData.position = lightPosRange.xyz;
clusterLightData.range = lightPosRange.w;
let lightDir_Flags: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_DIRECTION_FLAGS});
clusterLightData.direction = lightDir_Flags.xyz;
let flags_uint: u32 = bitcast<u32>(lightDir_Flags.w);
clusterLightData.flags = flags_uint;
clusterLightData.isSpot = (flags_uint & (1u << 30u)) != 0u;
clusterLightData.shape = (flags_uint >> 28u) & 0x3u;
clusterLightData.falloffModeLinear = (flags_uint & (1u << 27u)) == 0u;
clusterLightData.shadowIntensity = f32((flags_uint >> 0u) & 0xFFu) / 255.0;
clusterLightData.cookieIntensity = f32((flags_uint >> 8u) & 0xFFu) / 255.0;
clusterLightData.isDynamic = (flags_uint & (1u << 22u)) != 0u;
clusterLightData.isLightmapped = (flags_uint & (1u << 21u)) != 0u;
}
fn decodeClusterLightSpot(clusterLightData: ptr<function, ClusterLightData>) {
let angles: vec2f = unpack2x16float(bitcast<u32>(clusterLightData.anglesData));
clusterLightData.innerConeAngleCos = angles.x;
clusterLightData.outerConeAngleCos = angles.y;
}
fn decodeClusterLightOmniAtlasViewport(clusterLightData: ptr<function, ClusterLightData>) {
clusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz;
}
fn decodeClusterLightAreaData(clusterLightData: ptr<function, ClusterLightData>) {
clusterLightData.halfWidth = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz;
clusterLightData.halfHeight = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz;
}
fn decodeClusterLightProjectionMatrixData(clusterLightData: ptr<function, ClusterLightData>) {
let m0: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0});
let m1: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_1});
let m2: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_2});
let m3: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_3});
lightProjectionMatrix = mat4x4f(m0, m1, m2, m3);
}
fn decodeClusterLightShadowData(clusterLightData: ptr<function, ClusterLightData>) {
let biases: vec2f = unpack2x16float(bitcast<u32>(clusterLightData.biasesData));
clusterLightData.shadowBias = biases.x;
clusterLightData.shadowNormalBias = biases.y;
}
fn decodeClusterLightCookieData(clusterLightData: ptr<function, ClusterLightData>) {
let cookieFlags: u32 = (clusterLightData.flags >> 23u) & 0x0Fu;
let mask_uvec: vec4<u32> = vec4<u32>(cookieFlags) & vec4<u32>(1u, 2u, 4u, 8u);
clusterLightData.cookieChannelMask = step(vec4f(1.0), vec4f(mask_uvec));
}
fn evaluateLight(
light: ptr<function, ClusterLightData>,
worldNormal: vec3f,
viewDir: vec3f,
reflectionDir: vec3f,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir: vec3f,
#endif
gloss: f32,
specularity: vec3f,
geometricNormal: vec3f,
tbn: mat3x3f,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel: vec3f,
#endif
clearcoat_worldNormal: vec3f,
clearcoat_gloss: f32,
sheen_gloss: f32,
iridescence_intensity: f32
) {
var cookieAttenuation: vec3f = vec3f(1.0);
var diffuseAttenuation: f32 = 1.0;
var falloffAttenuation: f32 = 1.0;
let lightDirW: vec3f = evalOmniLight(light.position);
let lightDirNormW: vec3f = normalize(lightDirW);
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
decodeClusterLightAreaData(light);
if (light.shape == {LIGHTSHAPE_RECT}) {
calcRectLightValues(light.position, light.halfWidth, light.halfHeight);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
calcDiskLightValues(light.position, light.halfWidth, light.halfHeight);
} else {
calcSphereLightValues(light.position, light.halfWidth, light.halfHeight);
}
falloffAttenuation = getFalloffWindow(light.range, lightDirW);
} else
#endif
{
if (light.falloffModeLinear) {
falloffAttenuation = getFalloffLinear(light.range, lightDirW);
} else {
falloffAttenuation = getFalloffInvSquared(light.range, lightDirW);
}
}
if (falloffAttenuation > 0.00001) {
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
if (light.shape == {LIGHTSHAPE_RECT}) {
diffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
} else if (light.shape == {LIGHTSHAPE_DISK}) {
diffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
} else {
diffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
}
} else
#endif
{
falloffAttenuation = falloffAttenuation * getLightDiffuse(worldNormal, viewDir, lightDirNormW);
}
if (light.isSpot) {
decodeClusterLightSpot(light);
falloffAttenuation = falloffAttenuation * getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos, lightDirNormW);
}
#if defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS)
if (falloffAttenuation > 0.00001) {
if (light.shadowIntensity > 0.0 || light.cookieIntensity > 0.0) {
if (light.isSpot) {
decodeClusterLightProjectionMatrixData(light);
} else {
decodeClusterLightOmniAtlasViewport(light);
}
let shadowTextureResolution: f32 = uniform.shadowAtlasParams.x;
let shadowEdgePixels: f32 = uniform.shadowAtlasParams.y;
#ifdef CLUSTER_COOKIES
if (light.cookieIntensity > 0.0) {
decodeClusterLightCookieData(light);
if (light.isSpot) {
cookieAttenuation = getCookie2DClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightProjectionMatrix, vPositionW, light.cookieIntensity, light.cookieChannelMask);
} else {
cookieAttenuation = getCookieCubeClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightDirW, light.cookieIntensity, light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport);
}
}
#endif
#ifdef CLUSTER_SHADOWS
if (light.shadowIntensity > 0.0) {
decodeClusterLightShadowData(light);
let shadowParams: vec4f = vec4f(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range);
if (light.isSpot) {
let shadowCoord: vec3f = getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal);
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
let shadow: f32 = getShadowSpotClusteredPCF1(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCF3)
let shadow: f32 = getShadowSpotClusteredPCF3(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCF5)
let shadow: f32 = getShadowSpotClusteredPCF5(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCSS)
let shadow: f32 = getShadowSpotClusteredPCSS(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);
#endif
falloffAttenuation = falloffAttenuation * mix(1.0, shadow, light.shadowIntensity);
} else {
let dir: vec3f = normalOffsetPointShadow(shadowParams, light.position, lightDirW, lightDirNormW, geometricNormal);
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
let shadow: f32 = getShadowOmniClusteredPCF1(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);
#elif defined(CLUSTER_SHADOW_TYPE_PCF3)
let shadow: f32 = getShadowOmniClusteredPCF3(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);
#elif defined(CLUSTER_SHADOW_TYPE_PCF5)
let shadow: f32 = getShadowOmniClusteredPCF5(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);
#endif
falloffAttenuation = falloffAttenuation * mix(1.0, shadow, light.shadowIntensity);
}
}
#endif
}
}
#endif
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
{
var areaDiffuse: vec3f = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation;
#if defined(LIT_SPECULAR)
areaDiffuse = mix(areaDiffuse, vec3f(0.0), dLTCSpecFres);
#endif
dDiffuseLight = dDiffuseLight + areaDiffuse;
}
#ifdef LIT_SPECULAR
var areaLightSpecular: f32;
if (light.shape == {LIGHTSHAPE_RECT}) {
areaLightSpecular = getRectLightSpecular(worldNormal, viewDir);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
areaLightSpecular = getDiskLightSpecular(worldNormal, viewDir);
} else {
areaLightSpecular = getSphereLightSpecular(worldNormal, viewDir);
}
dSpecularLight = dSpecularLight + dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation;
#ifdef LIT_CLEARCOAT
var areaLightSpecularCC: f32;
if (light.shape == {LIGHTSHAPE_RECT}) {
areaLightSpecularCC = getRectLightSpecular(clearcoat_worldNormal, viewDir);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
areaLightSpecularCC = getDiskLightSpecular(clearcoat_worldNormal, viewDir);
} else {
areaLightSpecularCC = getSphereLightSpecular(clearcoat_worldNormal, viewDir);
}
ccSpecularLight = ccSpecularLight + ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
} else
#endif
{
{
var punctualDiffuse: vec3f = falloffAttenuation * light.color * cookieAttenuation;
#if defined(CLUSTER_AREALIGHTS)
#if defined(LIT_SPECULAR)
punctualDiffuse = mix(punctualDiffuse, vec3f(0.0), specularity);
#endif
#endif
dDiffuseLight = dDiffuseLight + punctualDiffuse;
}
#ifdef LIT_SPECULAR
let halfDir: vec3f = normalize(-lightDirNormW + viewDir);
#ifdef LIT_SPECULAR_FRESNEL
dSpecularLight = dSpecularLight +
getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation *
getFresnel(
dot(viewDir, halfDir),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescence_intensity
#endif
);
#else
dSpecularLight = dSpecularLight + getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity;
#endif
#ifdef LIT_CLEARCOAT
#ifdef LIT_SPECULAR_FRESNEL
ccSpecularLight = ccSpecularLight + getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir));
#else
ccSpecularLight = ccSpecularLight + getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
#ifdef LIT_SHEEN
sSpecularLight = sSpecularLight + getLightSpecularSheen(halfDir, worldNormal, viewDir, lightDirNormW, sheen_gloss) * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
}
}
dAtten = falloffAttenuation;
dLightDirNormW = lightDirNormW;
}
fn evaluateClusterLight(
lightIndex: f32,
worldNormal: vec3f,
viewDir: vec3f,
reflectionDir: vec3f,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir: vec3f,
#endif
gloss: f32,
specularity: vec3f,
geometricNormal: vec3f,
tbn: mat3x3f,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel: vec3f,
#endif
clearcoat_worldNormal: vec3f,
clearcoat_gloss: f32,
sheen_gloss: f32,
iridescence_intensity: f32
) {
var clusterLightData: ClusterLightData;
decodeClusterLightCore(&clusterLightData, lightIndex);
#ifdef CLUSTER_MESH_DYNAMIC_LIGHTS
let acceptLightMask: bool = clusterLightData.isDynamic;
#else
let acceptLightMask: bool = clusterLightData.isLightmapped;
#endif
if (acceptLightMask) {
evaluateLight(
&clusterLightData,
worldNormal,
viewDir,
reflectionDir,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir,
#endif
gloss,
specularity,
geometricNormal,
tbn,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
clearcoat_worldNormal,
clearcoat_gloss,
sheen_gloss,
iridescence_intensity
);
}
}
fn addClusteredLights(
worldNormal: vec3f,
viewDir: vec3f,
reflectionDir: vec3f,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir: vec3f,
#endif
gloss: f32,
specularity: vec3f,
geometricNormal: vec3f,
tbn: mat3x3f,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel: vec3f,
#endif
clearcoat_worldNormal: vec3f,
clearcoat_gloss: f32,
sheen_gloss: f32,
iridescence_intensity: f32
) {
if (uniform.clusterSkip > 0.5) {
return;
}
let cellCoords: vec3f = floor((vPositionW - uniform.clusterBoundsMin) * uniform.clusterCellsCountByBoundsSize);
if (!(any(cellCoords < vec3f(0.0)) || any(cellCoords >= uniform.clusterCellsMax))) {
let cellIndex: f32 = dot(uniform.clusterCellsDot, cellCoords);
let clusterV: f32 = floor(cellIndex * uniform.clusterTextureSize.y);
let clusterU: f32 = cellIndex - (clusterV * uniform.clusterTextureSize.x);
for (var lightCellIndex: i32 = 0; lightCellIndex < uniform.clusterMaxCells; lightCellIndex = lightCellIndex + 1) {
let lightIndexPacked: f32 = textureLoad(clusterWorldTexture, vec2<i32>(i32(clusterU) + lightCellIndex, i32(clusterV)), 0).r;
if (lightIndexPacked <= 0.0) {
break;
}
evaluateClusterLight(
lightIndexPacked * 255.0,
worldNormal,
viewDir,
reflectionDir,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir,
#endif
gloss,
specularity,
geometricNormal,
tbn,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
clearcoat_worldNormal,
clearcoat_gloss,
sheen_gloss,
iridescence_intensity
);
}
}
}`,combinePS:`
fn combineColor(albedo: vec3f, sheenSpecularity: vec3f, clearcoatSpecularity: f32) -> vec3f {
var ret: vec3f = vec3f(0.0);
#ifdef LIT_OLD_AMBIENT
ret = ret + ((dDiffuseLight - uniform.light_globalAmbient) * albedo + uniform.material_ambient * uniform.light_globalAmbient);
#else
ret = ret + (albedo * dDiffuseLight);
#endif
#ifdef LIT_SPECULAR
ret = ret + dSpecularLight;
#endif
#ifdef LIT_REFLECTIONS
ret = ret + (dReflection.rgb * dReflection.a);
#endif
#ifdef LIT_SHEEN
let sheenScaling: f32 = 1.0 - max(max(sheenSpecularity.r, sheenSpecularity.g), sheenSpecularity.b) * 0.157;
ret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sheenSpecularity;
#endif
#ifdef LIT_CLEARCOAT
let clearCoatScaling: f32 = 1.0 - ccFresnel * clearcoatSpecularity;
ret = ret * clearCoatScaling + (ccSpecularLight + ccReflection) * clearcoatSpecularity;
#endif
return ret;
}
`,cookieBlit2DPS:`
varying uv0: vec2f;
var blitTexture: texture_2d<f32>;
var blitTextureSampler : sampler;
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
output.color = textureSample(blitTexture, blitTextureSampler, input.uv0);
return output;
}
`,cookieBlitCubePS:`
varying uv0: vec2f;
uniform invViewProj: mat4x4<f32>;
var blitTexture: texture_cube<f32>;
var blitTextureSampler : sampler;
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
var projPos = vec4f(input.uv0 * 2.0 - 1.0, 0.5, 1.0);
var worldPos = uniform.invViewProj * projPos;
output.color = textureSample(blitTexture, blitTextureSampler, worldPos.xyz);
return output;
}
`,cookieBlitVS:`
attribute vertex_position: vec2f;
varying uv0: vec2f;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = vec4f(input.vertex_position, 0.5, 1.0);
output.uv0 = input.vertex_position * 0.5 + vec2f(0.5, 0.5);
output.uv0.y = 1.0 - output.uv0.y;
return output;
}
`,cubeMapProjectPS:`
#if LIT_CUBEMAP_PROJECTION == BOX
uniform envBoxMin: vec3f;
uniform envBoxMax: vec3f;
#endif
fn cubeMapProject(nrdir: vec3f) -> vec3f {
#if LIT_CUBEMAP_PROJECTION == NONE
return cubeMapRotate(nrdir);
#endif
#if LIT_CUBEMAP_PROJECTION == BOX
let nrdir_rotated: vec3f = cubeMapRotate(nrdir);
let rbmax: vec3f = (uniform.envBoxMax - vPositionW) / nrdir_rotated;
let rbmin: vec3f = (uniform.envBoxMin - vPositionW) / nrdir_rotated;
let rbminmax: vec3f = select(rbmin, rbmax, nrdir_rotated > vec3f(0.0));
let fa: f32 = min(min(rbminmax.x, rbminmax.y), rbminmax.z);
let posonbox: vec3f = vPositionW + nrdir_rotated * fa;
let envBoxPos: vec3f = (uniform.envBoxMin + uniform.envBoxMax) * 0.5;
return normalize(posonbox - envBoxPos);
#endif
}
`,cubeMapRotatePS:`
#ifdef CUBEMAP_ROTATION
uniform cubeMapRotationMatrix: mat3x3f;
#endif
fn cubeMapRotate(refDir: vec3f) -> vec3f {
#ifdef CUBEMAP_ROTATION
return refDir * uniform.cubeMapRotationMatrix;
#else
return refDir;
#endif
}
`,debugOutputPS:`
#ifdef DEBUG_ALBEDO_PASS
output.color = vec4(gammaCorrectOutput(dAlbedo), 1.0);
#endif
#ifdef DEBUG_UV0_PASS
output.color = vec4f(litArgs_albedo , 1.0);
#endif
#ifdef DEBUG_WORLD_NORMAL_PASS
output.color = vec4f(litArgs_worldNormal * 0.5 + 0.5, 1.0);
#endif
#ifdef DEBUG_OPACITY_PASS
output.color = vec4f(vec3f(litArgs_opacity) , 1.0);
#endif
#ifdef DEBUG_SPECULARITY_PASS
output.color = vec4f(litArgs_specularity, 1.0);
#endif
#ifdef DEBUG_GLOSS_PASS
output.color = vec4f(vec3f(litArgs_gloss) , 1.0);
#endif
#ifdef DEBUG_METALNESS_PASS
output.color = vec4f(vec3f(litArgs_metalness) , 1.0);
#endif
#ifdef DEBUG_AO_PASS
output.color = vec4f(vec3f(litArgs_ao) , 1.0);
#endif
#ifdef DEBUG_EMISSION_PASS
output.color = vec4f(gammaCorrectOutput(litArgs_emission), 1.0);
#endif
`,debugProcessFrontendPS:`
#ifdef DEBUG_LIGHTING_PASS
litArgs_albedo = vec3f(0.5);
#endif
#ifdef DEBUG_UV0_PASS
#ifdef VARYING_VUV0
litArgs_albedo = vec3f(vUv0, 0.0);
#else
litArgs_albedo = vec3f(0.0);
#endif
#endif
`,detailModesPS:`
#ifndef _DETAILMODES_INCLUDED_
#define _DETAILMODES_INCLUDED_
fn detailMode_mul(c1: vec3f, c2: vec3f) -> vec3f {
return c1 * c2;
}
fn detailMode_add(c1: vec3f, c2: vec3f) -> vec3f {
return c1 + c2;
}
fn detailMode_screen(c1: vec3f, c2: vec3f) -> vec3f {
return 1.0 - (1.0 - c1)*(1.0 - c2);
}
fn detailMode_overlay(c1: vec3f, c2: vec3f) -> vec3f {
return mix(1.0 - 2.0 * (1.0 - c1)*(1.0 - c2), 2.0 * c1 * c2, step(c1, vec3f(0.5)));
}
fn detailMode_min(c1: vec3f, c2: vec3f) -> vec3f {
return min(c1, c2);
}
fn detailMode_max(c1: vec3f, c2: vec3f) -> vec3f {
return max(c1, c2);
}
#endif
`,diffusePS:`
uniform material_diffuse: vec3f;
#ifdef STD_DIFFUSEDETAIL_TEXTURE
#include "detailModesPS"
#endif
fn getAlbedo() {
dAlbedo = uniform.material_diffuse.rgb;
#ifdef STD_DIFFUSE_TEXTURE
var albedoTexture: vec3f = {STD_DIFFUSE_TEXTURE_DECODE}(textureSampleBias({STD_DIFFUSE_TEXTURE_NAME}, {STD_DIFFUSE_TEXTURE_NAME}Sampler, {STD_DIFFUSE_TEXTURE_UV}, uniform.textureBias)).{STD_DIFFUSE_TEXTURE_CHANNEL};
#ifdef STD_DIFFUSEDETAIL_TEXTURE
var albedoDetail: vec3f = {STD_DIFFUSEDETAIL_TEXTURE_DECODE}(textureSampleBias({STD_DIFFUSEDETAIL_TEXTURE_NAME}, {STD_DIFFUSEDETAIL_TEXTURE_NAME}Sampler, {STD_DIFFUSEDETAIL_TEXTURE_UV}, uniform.textureBias)).{STD_DIFFUSEDETAIL_TEXTURE_CHANNEL};
albedoTexture = detailMode_{STD_DIFFUSEDETAIL_DETAILMODE}(albedoTexture, albedoDetail);
#endif
dAlbedo = dAlbedo * albedoTexture;
#endif
#ifdef STD_DIFFUSE_VERTEX
dAlbedo = dAlbedo * gammaCorrectInputVec3(saturate3(vVertexColor.{STD_DIFFUSE_VERTEX_CHANNEL}));
#endif
}
`,decodePS:`
#ifndef _DECODE_INCLUDED_
#define _DECODE_INCLUDED_
fn decodeLinear(raw: vec4f) -> vec3f {
return raw.rgb;
}
fn decodeGammaFloat(raw: f32) -> f32 {
return pow(raw, 2.2);
}
fn decodeGamma3(raw: vec3f) -> vec3f {
return pow(raw, vec3f(2.2));
}
fn decodeGamma(raw: vec4f) -> vec3f {
return pow(raw.xyz, vec3f(2.2));
}
fn decodeRGBM(raw: vec4f) -> vec3f {
let color = (8.0 * raw.a) * raw.rgb;
return color * color;
}
fn decodeRGBP(raw: vec4f) -> vec3f {
let color = raw.rgb * (-raw.a * 7.0 + 8.0);
return color * color;
}
fn decodeRGBE(raw: vec4f) -> vec3f {
return select(vec3f(0.0), raw.xyz * pow(2.0, raw.w * 255.0 - 128.0), raw.a != 0.0);
}
fn passThrough(raw: vec4f) -> vec4f {
return raw;
}
fn unpackNormalXYZ(nmap: vec4f) -> vec3f {
return nmap.xyz * 2.0 - 1.0;
}
fn unpackNormalXY(nmap: vec4f) -> vec3f {
var xy = nmap.wy * 2.0 - 1.0;
return vec3f(xy, sqrt(1.0 - clamp(dot(xy, xy), 0.0, 1.0)));
}
#endif
`,emissivePS:`
uniform material_emissive: vec3f;
uniform material_emissiveIntensity: f32;
fn getEmission() {
dEmission = uniform.material_emissive * uniform.material_emissiveIntensity;
#ifdef STD_EMISSIVE_TEXTURE
dEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(textureSampleBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_NAME}Sampler, {STD_EMISSIVE_TEXTURE_UV}, uniform.textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL};
#endif
#ifdef STD_EMISSIVE_VERTEX
dEmission = dEmission * gammaCorrectInputVec3(saturate3(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL}));
#endif
}
`,encodePS:`
fn encodeLinear(source: vec3f) -> vec4f {
return vec4f(source, 1.0);
}
fn encodeGamma(source: vec3f) -> vec4f {
return vec4f(pow(source + vec3f(0.0000001), vec3f(1.0 / 2.2)), 1.0);
}
fn encodeRGBM(source: vec3f) -> vec4f {
var color: vec3f = pow(source, vec3f(0.5));
color *= 1.0 / 8.0;
var a: f32 = saturate(max(max(color.r, color.g), max(color.b, 1.0 / 255.0)));
a = ceil(a * 255.0) / 255.0;
color /= a;
return vec4f(color, a);
}
fn encodeRGBP(source: vec3f) -> vec4f {
var gamma: vec3f = pow(source, vec3f(0.5));
var maxVal: f32 = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));
var v: f32 = 1.0 - ((maxVal - 1.0) / 7.0);
v = ceil(v * 255.0) / 255.0;
return vec4f(gamma / (-v * 7.0 + 8.0), v);
}
fn encodeRGBE(source: vec3f) -> vec4f {
var maxVal: f32 = max(source.x, max(source.y, source.z));
if (maxVal < 1e-32) {
return vec4f(0.0, 0.0, 0.0, 0.0);
} else {
var e: f32 = ceil(log2(maxVal));
return vec4f(source / pow(2.0, e), (e + 128.0) / 255.0);
}
}
`,endPS:`
var finalRgb: vec3f = combineColor(litArgs_albedo, litArgs_sheen_specularity, litArgs_clearcoat_specularity);
finalRgb = finalRgb + litArgs_emission;
finalRgb = addFog(finalRgb);
finalRgb = toneMap(finalRgb);
finalRgb = gammaCorrectOutput(finalRgb);
output.color = vec4f(finalRgb, output.color.a);
`,envAtlasPS:`
#ifndef _ENVATLAS_INCLUDED_
#define _ENVATLAS_INCLUDED_
const atlasSize : f32 = 512.0;
const seamSize : f32 = 1.0 / atlasSize;
fn mapUv(uv : vec2f, rect : vec4f) -> vec2f {
return vec2f(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),
mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));
}
fn mapRoughnessUv(uv : vec2f, level : f32) -> vec2f {
let t : f32 = 1.0 / exp2(level);
return mapUv(uv, vec4f(0.0, 1.0 - t, t, t * 0.5));
}
fn mapShinyUv(uv : vec2f, level : f32) -> vec2f {
let t : f32 = 1.0 / exp2(level);
return mapUv(uv, vec4f(1.0 - t, 1.0 - t, t, t * 0.5));
}
#endif
`,envProcPS:`
#ifdef LIT_SKYBOX_INTENSITY
uniform skyboxIntensity : f32;
#endif
fn processEnvironment(color : vec3f) -> vec3f {
#ifdef LIT_SKYBOX_INTENSITY
return color * uniform.skyboxIntensity;
#else
return color;
#endif
}
`,falloffInvSquaredPS:`
fn getFalloffWindow(lightRadius: f32, lightDir: vec3f) -> f32 {
let sqrDist: f32 = dot(lightDir, lightDir);
let invRadius: f32 = 1.0 / lightRadius;
return square(saturate(1.0 - square(sqrDist * square(invRadius))));
}
fn getFalloffInvSquared(lightRadius: f32, lightDir: vec3f) -> f32 {
let sqrDist: f32 = dot(lightDir, lightDir);
var falloff: f32 = 1.0 / (sqrDist + 1.0);
let invRadius: f32 = 1.0 / lightRadius;
falloff = falloff * 16.0;
falloff = falloff * square(saturate(1.0 - square(sqrDist * square(invRadius))));
return falloff;
}
`,falloffLinearPS:`
fn getFalloffLinear(lightRadius: f32, lightDir: vec3f) -> f32 {
let d: f32 = length(lightDir);
return max(((lightRadius - d) / lightRadius), 0.0);
}
`,floatAsUintPS:`
#ifndef FLOAT_AS_UINT
#define FLOAT_AS_UINT
fn float2uint(value: f32) -> vec4f {
let intBits = bitcast<u32>(value);
return vec4f(
f32((intBits >> 24u) & 0xffu),
f32((intBits >> 16u) & 0xffu),
f32((intBits >> 8u) & 0xffu),
f32(intBits & 0xffu)
) / 255.0;
}
fn uint2float(value: vec4f) -> f32 {
let rgba_u32 = vec4<u32>(value * 255.0);
let intBits: u32 =
(rgba_u32.r << 24u) |
(rgba_u32.g << 16u) |
(rgba_u32.b << 8u) |
rgba_u32.a;
return bitcast<f32>(intBits);
}
fn float2vec4(value: f32) -> vec4f {
#if defined(CAPS_TEXTURE_FLOAT_RENDERABLE)
return vec4f(value, 1.0, 1.0, 1.0);
#else
return float2uint(value);
#endif
}
#endif
`,fogPS:`
var<private> dBlendModeFogFactor : f32 = 1.0;
#if (FOG != NONE)
uniform fog_color : vec3f;
#if (FOG == LINEAR)
uniform fog_start : f32;
uniform fog_end : f32;
#else
uniform fog_density : f32;
#endif
#endif
fn getFogFactor() -> f32 {
let depth = pcPosition.z / pcPosition.w;
var fogFactor : f32 = 0.0;
#if (FOG == LINEAR)
fogFactor = (uniform.fog_end - depth) / (uniform.fog_end - uniform.fog_start);
#elif (FOG == EXP)
fogFactor = exp(-depth * uniform.fog_density);
#elif (FOG == EXP2)
fogFactor = exp(-depth * depth * uniform.fog_density * uniform.fog_density);
#endif
return clamp(fogFactor, 0.0, 1.0);
}
fn addFog(color : vec3f) -> vec3f {
#if (FOG != NONE)
return mix(uniform.fog_color * dBlendModeFogFactor, color, getFogFactor());
#else
return color;
#endif
}
`,fresnelSchlickPS:`
fn getFresnel(
cosTheta: f32,
gloss: f32,
specularity: vec3f
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel: vec3f,
iridescenceIntensity: f32
#endif
) -> vec3f {
let fresnel: f32 = pow(1.0 - saturate(cosTheta), 5.0);
let glossSq: f32 = gloss * gloss;
let ret: vec3f = specularity + (max(vec3f(glossSq), specularity) - specularity) * fresnel;
#if defined(LIT_IRIDESCENCE)
return mix(ret, iridescenceFresnel, iridescenceIntensity);
#else
return ret;
#endif
}
fn getFresnelCC(cosTheta: f32) -> f32 {
let fresnel: f32 = pow(1.0 - saturate(cosTheta), 5.0);
return 0.04 + (1.0 - 0.04) * fresnel;
}`,frontendCodePS:"",frontendDeclPS:"",fullscreenQuadVS:`
attribute vertex_position: vec2f;
varying vUv0: vec2f;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = vec4f(input.vertex_position, 0.5, 1.0);
output.vUv0 = input.vertex_position.xy * 0.5 + vec2f(0.5);
return output;
}
`,gammaPS:`
#include "decodePS"
#if (GAMMA == SRGB)
fn gammaCorrectInput(color: f32) -> f32 {
return decodeGammaFloat(color);
}
fn gammaCorrectInputVec3(color: vec3f) -> vec3f {
return decodeGamma3(color);
}
fn gammaCorrectInputVec4(color: vec4f) -> vec4f {
return vec4f(decodeGamma3(color.xyz), color.w);
}
fn gammaCorrectOutput(color: vec3f) -> vec3f {
return pow(color + 0.0000001, vec3f(1.0 / 2.2));
}
#else
fn gammaCorrectInput(color: f32) -> f32 {
return color;
}
fn gammaCorrectInputVec3(color: vec3f) -> vec3f {
return color;
}
fn gammaCorrectInputVec4(color: vec4f) -> vec4f {
return color;
}
fn gammaCorrectOutput(color: vec3f) -> vec3f {
return color;
}
#endif
`,glossPS:`
#ifdef STD_GLOSS_CONSTANT
uniform material_gloss: f32;
#endif
fn getGlossiness() {
dGlossiness = 1.0;
#ifdef STD_GLOSS_CONSTANT
dGlossiness = dGlossiness * uniform.material_gloss;
#endif
#ifdef STD_GLOSS_TEXTURE
dGlossiness = dGlossiness * textureSampleBias({STD_GLOSS_TEXTURE_NAME}, {STD_GLOSS_TEXTURE_NAME}Sampler, {STD_GLOSS_TEXTURE_UV}, uniform.textureBias).{STD_GLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_GLOSS_VERTEX
dGlossiness = dGlossiness * saturate(vVertexColor.{STD_GLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_GLOSS_INVERT
dGlossiness = 1.0 - dGlossiness;
#endif
dGlossiness = dGlossiness + 0.0000001;
}
`,gsplatCenterVS:`
uniform matrix_model: mat4x4f;
uniform matrix_view: mat4x4f;
uniform matrix_projection: mat4x4f;
fn initCenter(modelCenter: vec3f, center: ptr<function, SplatCenter>) -> bool {
let modelView: mat4x4f = uniform.matrix_view * uniform.matrix_model;
let centerView: vec4f = modelView * vec4f(modelCenter, 1.0);
if (centerView.z > 0.0) {
return false;
}
var centerProj: vec4f = uniform.matrix_projection * centerView;
centerProj.z = clamp(centerProj.z, 0.0, abs(centerProj.w));
center.view = centerView.xyz / centerView.w;
center.proj = centerProj;
center.projMat00 = uniform.matrix_projection[0][0];
center.modelView = modelView;
return true;
}
`,gsplatCornerVS:`
uniform viewport: vec2f;
uniform camera_params: vec4f;
fn initCorner(source: ptr<function, SplatSource>, center: ptr<function, SplatCenter>, corner: ptr<function, SplatCorner>) -> bool {
var covA: vec3f;
var covB: vec3f;
readCovariance(source, &covA, &covB);
let Vrk = mat3x3f(
vec3f(covA.x, covA.y, covA.z),
vec3f(covA.y, covB.x, covB.y),
vec3f(covA.z, covB.y, covB.z)
);
let focal = uniform.viewport.x * center.projMat00;
let v = select(center.view.xyz, vec3f(0.0, 0.0, 1.0), uniform.camera_params.w == 1.0);
let J1 = focal / v.z;
let J2 = -J1 / v.z * v.xy;
let J = mat3x3f(
vec3f(J1, 0.0, J2.x),
vec3f(0.0, J1, J2.y),
vec3f(0.0, 0.0, 0.0)
);
let W = transpose(mat3x3f(center.modelView[0].xyz, center.modelView[1].xyz, center.modelView[2].xyz));
let T = W * J;
let cov = transpose(T) * Vrk * T;
#if GSPLAT_AA
let detOrig = cov[0][0] * cov[1][1] - cov[0][1] * cov[1][0];
let detBlur = (cov[0][0] + 0.3) * (cov[1][1] + 0.3) - cov[0][1] * cov[1][0];
corner.aaFactor = sqrt(detOrig / detBlur);
#endif
let diagonal1 = cov[0][0] + 0.3;
let offDiagonal = cov[0][1];
let diagonal2 = cov[1][1] + 0.3;
let mid = 0.5 * (diagonal1 + diagonal2);
let radius = length(vec2f((diagonal1 - diagonal2) / 2.0, offDiagonal));
let lambda1 = mid + radius;
let lambda2 = max(mid - radius, 0.1);
let vmin = min(1024.0, min(uniform.viewport.x, uniform.viewport.y));
let l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin);
let l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin);
if (l1 < 2.0 && l2 < 2.0) {
return false;
}
let c = center.proj.ww / uniform.viewport;
if (any((abs(center.proj.xy) - vec2f(max(l1, l2)) * c) > center.proj.ww)) {
return false;
}
let diagonalVector = normalize(vec2f(offDiagonal, lambda1 - diagonal1));
let v1 = l1 * diagonalVector;
let v2 = l2 * vec2f(diagonalVector.y, -diagonalVector.x);
corner.offset = (source.cornerUV.x * v1 + source.cornerUV.y * v2) * c;
corner.uv = source.cornerUV;
return true;
}
`,gsplatColorVS:`
var splatColor: texture_2d<f32>;
fn readColor(source: ptr<function, SplatSource>) -> vec4f {
return textureLoad(splatColor, source.uv, 0);
}
`,gsplatCommonVS:`
struct SplatSource {
order: u32,
id: u32,
uv: vec2<i32>,
cornerUV: vec2f,
}
struct SplatCenter {
view: vec3f,
proj: vec4f,
modelView: mat4x4f,
projMat00: f32,
}
struct SplatCorner {
offset: vec2f,
uv: vec2f,
#if GSPLAT_AA
aaFactor: f32,
#endif
}
#include "gsplatEvalSHVS"
#include "gsplatQuatToMat3VS"
#if GSPLAT_COMPRESSED_DATA
#include "gsplatCompressedDataVS"
#if SH_BANDS > 0
#include "gsplatCompressedSHVS"
#endif
#elif GSPLAT_SOGS_DATA
#include "gsplatSogsDataVS"
#include "gsplatSogsColorVS"
#if SH_BANDS > 0
#include "gsplatSogsSHVS"
#endif
#else
#include "gsplatDataVS"
#include "gsplatColorVS"
#if SH_BANDS > 0
#include "gsplatSHVS"
#endif
#endif
#include "gsplatSourceVS"
#include "gsplatCenterVS"
#include "gsplatCornerVS"
#include "gsplatOutputVS"
fn clipCorner(corner: ptr<function, SplatCorner>, alpha: f32) {
let clip: f32 = min(1.0, sqrt(-log(1.0 / (255.0 * alpha))) / 2.0);
corner.offset = corner.offset * clip;
corner.uv = corner.uv * clip;
}
`,gsplatCompressedDataVS:`
var packedTexture: texture_2d<u32>;
var chunkTexture: texture_2d<f32>;
var<private> chunkDataA: vec4f;
var<private> chunkDataB: vec4f;
var<private> chunkDataC: vec4f;
var<private> chunkDataD: vec4f;
var<private> chunkDataE: vec4f;
var<private> packedData: vec4u;
fn unpack111011(bits: u32) -> vec3f {
return (vec3f((vec3<u32>(bits) >> vec3<u32>(21u, 11u, 0u)) & vec3<u32>(0x7ffu, 0x3ffu, 0x7ffu))) / vec3f(2047.0, 1023.0, 2047.0);
}
fn unpack8888(bits: u32) -> vec4f {
return vec4f(
f32((bits >> 24u) & 0xffu),
f32((bits >> 16u) & 0xffu),
f32((bits >> 8u) & 0xffu),
f32(bits & 0xffu)
) / 255.0;
}
const norm_const: f32 = 1.0 / (sqrt(2.0) * 0.5);
fn unpackRotation(bits: u32) -> vec4f {
let a = (f32((bits >> 20u) & 0x3ffu) / 1023.0 - 0.5) * norm_const;
let b = (f32((bits >> 10u) & 0x3ffu) / 1023.0 - 0.5) * norm_const;
let c = (f32(bits & 0x3ffu) / 1023.0 - 0.5) * norm_const;
let m = sqrt(1.0 - (a * a + b * b + c * c));
let mode = bits >> 30u;
if (mode == 0u) { return vec4f(m, a, b, c); }
if (mode == 1u) { return vec4f(a, m, b, c); }
if (mode == 2u) { return vec4f(a, b, m, c); }
return vec4f(a, b, c, m);
}
fn readCenter(source: ptr<function, SplatSource>) -> vec3f {
let tex_size_u = textureDimensions(chunkTexture, 0);
let w: u32 = tex_size_u.x / 5u;
let chunkId: u32 = source.id / 256u;
let chunkUV: vec2<i32> = vec2<i32>(i32((chunkId % w) * 5u), i32(chunkId / w));
chunkDataA = textureLoad(chunkTexture, chunkUV + vec2<i32>(0, 0), 0);
chunkDataB = textureLoad(chunkTexture, chunkUV + vec2<i32>(1, 0), 0);
chunkDataC = textureLoad(chunkTexture, chunkUV + vec2<i32>(2, 0), 0);
chunkDataD = textureLoad(chunkTexture, chunkUV + vec2<i32>(3, 0), 0);
chunkDataE = textureLoad(chunkTexture, chunkUV + vec2<i32>(4, 0), 0);
packedData = textureLoad(packedTexture, source.uv, 0);
return mix(chunkDataA.xyz, vec3f(chunkDataA.w, chunkDataB.xy), unpack111011(packedData.x));
}
fn readColor(source: ptr<function, SplatSource>) -> vec4f {
let r = unpack8888(packedData.w);
return vec4f(mix(chunkDataD.xyz, vec3f(chunkDataD.w, chunkDataE.xy), r.rgb), r.w);
}
fn getRotation() -> vec4f {
return unpackRotation(packedData.y);
}
fn getScale() -> vec3f {
return exp(mix(vec3f(chunkDataB.zw, chunkDataC.x), chunkDataC.yzw, unpack111011(packedData.z)));
}
fn readCovariance(source: ptr<function, SplatSource>, covA_ptr: ptr<function, vec3f>, covB_ptr: ptr<function, vec3f>) {
let rot = quatToMat3(getRotation());
let scale = getScale();
let M = transpose(mat3x3f(
scale.x * rot[0],
scale.y * rot[1],
scale.z * rot[2]
));
*covA_ptr = vec3f(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));
*covB_ptr = vec3f(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));
}
`,gsplatCompressedSHVS:`
#if SH_BANDS > 0
var shTexture0: texture_2d<u32>;
var shTexture1: texture_2d<u32>;
var shTexture2: texture_2d<u32>;
fn unpack8888s(bits: u32) -> vec4f {
let unpacked_u = (vec4<u32>(bits) >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(0xffu);
return vec4f(unpacked_u) * (8.0 / 255.0) - 4.0;
}
fn readSHData(source: ptr<function, SplatSource>, sh: ptr<function, array<vec3f, 15>>, scale: ptr<function, f32>) {
let shData0: vec4<u32> = textureLoad(shTexture0, source.uv, 0);
let shData1: vec4<u32> = textureLoad(shTexture1, source.uv, 0);
let shData2: vec4<u32> = textureLoad(shTexture2, source.uv, 0);
let r0 = unpack8888s(shData0.x);
let r1 = unpack8888s(shData0.y);
let r2 = unpack8888s(shData0.z);
let r3 = unpack8888s(shData0.w);
let g0 = unpack8888s(shData1.x);
let g1 = unpack8888s(shData1.y);
let g2 = unpack8888s(shData1.z);
let g3 = unpack8888s(shData1.w);
let b0 = unpack8888s(shData2.x);
let b1 = unpack8888s(shData2.y);
let b2 = unpack8888s(shData2.z);
let b3 = unpack8888s(shData2.w);
sh[0] = vec3f(r0.x, g0.x, b0.x);
sh[1] = vec3f(r0.y, g0.y, b0.y);
sh[2] = vec3f(r0.z, g0.z, b0.z);
sh[3] = vec3f(r0.w, g0.w, b0.w);
sh[4] = vec3f(r1.x, g1.x, b1.x);
sh[5] = vec3f(r1.y, g1.y, b1.y);
sh[6] = vec3f(r1.z, g1.z, b1.z);
sh[7] = vec3f(r1.w, g1.w, b1.w);
sh[8] = vec3f(r2.x, g2.x, b2.x);
sh[9] = vec3f(r2.y, g2.y, b2.y);
sh[10] = vec3f(r2.z, g2.z, b2.z);
sh[11] = vec3f(r2.w, g2.w, b2.w);
sh[12] = vec3f(r3.x, g3.x, b3.x);
sh[13] = vec3f(r3.y, g3.y, b3.y);
sh[14] = vec3f(r3.z, g3.z, b3.z);
*scale = 1.0;
}
#endif
`,gsplatEvalSHVS:`
#if SH_BANDS == 1
const SH_COEFFS: i32 = 3;
#elif SH_BANDS == 2
const SH_COEFFS: i32 = 8;
#elif SH_BANDS == 3
const SH_COEFFS: i32 = 15;
#else
const SH_COEFFS: i32 = 0;
#endif
#if SH_BANDS > 0
const SH_C1: f32 = 0.4886025119029199;
#if SH_BANDS > 1
const SH_C2_0: f32 = 1.0925484305920792;
const SH_C2_1: f32 = -1.0925484305920792;
const SH_C2_2: f32 = 0.31539156525252005;
const SH_C2_3: f32 = -1.0925484305920792;
const SH_C2_4: f32 = 0.5462742152960396;
#endif
#if SH_BANDS > 2
const SH_C3_0: f32 = -0.5900435899266435;
const SH_C3_1: f32 = 2.890611442640554;
const SH_C3_2: f32 = -0.4570457994644658;
const SH_C3_3: f32 = 0.3731763325901154;
const SH_C3_4: f32 = -0.4570457994644658;
const SH_C3_5: f32 = 1.445305721320277;
const SH_C3_6: f32 = -0.5900435899266435;
#endif
fn evalSH(sh: ptr<function, array<vec3f, SH_COEFFS>>, dir: vec3f) -> vec3f {
let x = dir.x;
let y = dir.y;
let z = dir.z;
var result = SH_C1 * (-sh[0] * y + sh[1] * z - sh[2] * x);
#if SH_BANDS > 1
let xx = x * x;
let yy = y * y;
let zz = z * z;
let xy = x * y;
let yz = y * z;
let xz = x * z;
result = result + (
sh[3] * (SH_C2_0 * xy) +
sh[4] * (SH_C2_1 * yz) +
sh[5] * (SH_C2_2 * (2.0 * zz - xx - yy)) +
sh[6] * (SH_C2_3 * xz) +
sh[7] * (SH_C2_4 * (xx - yy))
);
#endif
#if SH_BANDS > 2
result = result + (
sh[8] * (SH_C3_0 * y * (3.0 * xx - yy)) +
sh[9] * (SH_C3_1 * xy * z) +
sh[10] * (SH_C3_2 * y * (4.0 * zz - xx - yy)) +
sh[11] * (SH_C3_3 * z * (2.0 * zz - 3.0 * xx - 3.0 * yy)) +
sh[12] * (SH_C3_4 * x * (4.0 * zz - xx - yy)) +
sh[13] * (SH_C3_5 * z * (xx - yy)) +
sh[14] * (SH_C3_6 * x * (xx - 3.0 * yy))
);
#endif
return result;
}
#endif
`,gsplatQuatToMat3VS:`
fn quatToMat3(R: vec4<f32>) -> mat3x3<f32> {
let R2: vec4<f32> = R + R;
let X: f32 = R2.x * R.w;
let Y: vec4<f32> = R2.y * R;
let Z: vec4<f32> = R2.z * R;
let W: f32 = R2.w * R.w;
return mat3x3<f32>(
1.0 - Z.z - W, Y.z + X, Y.w - Z.x,
Y.z - X, 1.0 - Y.y - W, Z.w + Y.x,
Y.w + Z.x, Z.w - Y.x, 1.0 - Y.y - Z.z
);
}
`,gsplatSogsColorVS:`
var sh0: texture_2d<f32>;
uniform sh0_mins: vec4f;
uniform sh0_maxs: vec4f;
const SH_C0: f32 = 0.28209479177387814;
fn readColor(source: ptr<function, SplatSource>) -> vec4f {
let clr: vec4f = mix(uniform.sh0_mins, uniform.sh0_maxs, textureLoad(sh0, source.uv, 0));
return vec4f(vec3f(0.5) + clr.xyz * SH_C0, 1.0 / (1.0 + exp(-clr.w)));
}
`,gsplatSogsDataVS:`
var packedTexture: texture_2d<u32>;
uniform means_mins: vec3f;
uniform means_maxs: vec3f;
uniform scales_mins: vec3f;
uniform scales_maxs: vec3f;
fn unpackU32(u: u32) -> vec4f {
return vec4f(
f32((u >> 24u) & 0xFFu) / 255.0,
f32((u >> 16u) & 0xFFu) / 255.0,
f32((u >> 8u) & 0xFFu) / 255.0,
f32(u & 0xFFu) / 255.0
);
}
var<private> packedSample: vec4<u32>;
fn readCenter(source: ptr<function, SplatSource>) -> vec3f {
packedSample = textureLoad(packedTexture, source.uv, 0);
let l: vec3f = unpackU32(packedSample.x).xyz;
let u: vec3f = unpackU32(packedSample.y).xyz;
let n: vec3f = (l * 255.0 + u * 255.0 * 256.0) / 65535.0;
let v: vec3f = mix(uniform.means_mins, uniform.means_maxs, n);
return sign(v) * (exp(abs(v)) - 1.0);
}
const norm: f32 = 2.0 / sqrt(2.0);
fn readCovariance(source: ptr<function, SplatSource>, covA_ptr: ptr<function, vec3f>, covB_ptr: ptr<function, vec3f>) {
let qdata: vec4f = unpackU32(packedSample.z);
let sdata: vec3f = unpackU32(packedSample.w).xyz;
let abc: vec3f = (qdata.xyz - 0.5) * norm;
let d: f32 = sqrt(max(0.0, 1.0 - dot(abc, abc)));
let mode: u32 = u32(qdata.w * 255.0 + 0.5) - 252u;
var quat: vec4f;
if (mode == 0u) {
quat = vec4f(d, abc);
} else if (mode == 1u) {
quat = vec4f(abc.x, d, abc.y, abc.z);
} else if (mode == 2u) {
quat = vec4f(abc.x, abc.y, d, abc.z);
} else {
quat = vec4f(abc.x, abc.y, abc.z, d);
}
let rot: mat3x3f = quatToMat3(quat);
let scale: vec3f = exp(mix(uniform.scales_mins, uniform.scales_maxs, sdata));
let M: mat3x3f = transpose(mat3x3f(
scale.x * rot[0],
scale.y * rot[1],
scale.z * rot[2]
));
*covA_ptr = vec3f(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));
*covB_ptr = vec3f(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));
}
`,gsplatSogsSHVS:`
var sh_centroids: texture_2d<f32>;
uniform shN_mins: f32;
uniform shN_maxs: f32;
fn readSHData(source: ptr<function, SplatSource>, sh: ptr<function, array<vec3f, SH_COEFFS>>, scale: ptr<function, f32>) {
let t: vec2<i32> = vec2<i32>(i32(packedSample.x & 255u), i32(packedSample.y & 255u));
let n: i32 = t.x + t.y * 256;
let u: i32 = (n % 64) * SH_COEFFS;
let v: i32 = n / 64;
for (var i: i32 = 0; i < SH_COEFFS; i = i + 1) {
sh[i] = mix(vec3f(uniform.shN_mins), vec3f(uniform.shN_maxs), textureLoad(sh_centroids, vec2<i32>(u + i, v), 0).xyz);
}
*scale = 1.0;
}
`,gsplatDataVS:`
var transformA: texture_2d<u32>;
var transformB: texture_2d<f32>;
var<private> tAw: u32;
fn readCenter(source: ptr<function, SplatSource>) -> vec3f {
let tA: vec4<u32> = textureLoad(transformA, source.uv, 0);
tAw = tA.w;
return bitcast<vec3f>(tA.xyz);
}
fn unpackRotation(packed: vec3f) -> vec4f {
return vec4f(packed.xyz, sqrt(max(0.0, 1.0 - dot(packed, packed))));
}
fn readCovariance(source: ptr<function, SplatSource>, covA_ptr: ptr<function, vec3f>, covB_ptr: ptr<function, vec3f>) {
let tB: vec4f = textureLoad(transformB, source.uv, 0);
let rot: mat3x3f = quatToMat3(unpackRotation(vec3f(unpack2x16float(bitcast<u32>(tAw)), tB.w)).wxyz);
let scale: vec3f = tB.xyz;
let M = transpose(mat3x3f(
scale.x * rot[0],
scale.y * rot[1],
scale.z * rot[2]
));
*covA_ptr = vec3f(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));
*covB_ptr = vec3f(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));
}
`,gsplatOutputVS:`
#include "tonemappingPS"
#include "decodePS"
#include "gammaPS"
fn prepareOutputFromGamma(gammaColor: vec3f) -> vec3f {
#if TONEMAP == NONE
#if GAMMA == NONE
return decodeGamma3(gammaColor);
#else
return gammaColor;
#endif
#else
return gammaCorrectOutput(toneMap(decodeGamma3(gammaColor)));
#endif
}
`,gsplatPS:`
#ifndef DITHER_NONE
#include "bayerPS"
#include "opacityDitherPS"
varying id: f32;
#endif
#ifdef PICK_PASS
#include "pickPS"
#endif
#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)
uniform alphaClip: f32;
#endif
#ifdef PREPASS_PASS
varying vLinearDepth: f32;
#include "floatAsUintPS"
#endif
const EXP_A: f32 = 12102203.0;
const EXP_BC_RMS: i32 = 1064866808;
fn fastExp(x: f32) -> f32 {
var i: i32 = i32(EXP_A * x) + EXP_BC_RMS;
return bitcast<f32>(i);
}
varying gaussianUV: vec2f;
varying gaussianColor: vec4f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let A: f32 = dot(gaussianUV, gaussianUV);
if (A > 1.0) {
discard;
return output;
}
var alpha: f32 = fastExp(-A * 4.0) * gaussianColor.a;
#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)
if (alpha < uniform.alphaClip) {
discard;
return output;
}
#endif
#ifdef PICK_PASS
output.color = getPickOutput();
#elif SHADOW_PASS
output.color = vec4f(0.0, 0.0, 0.0, 1.0);
#elif PREPASS_PASS
output.color = float2vec4(vLinearDepth);
#else
if (alpha < (1.0 / 255.0)) {
discard;
return output;
}
#ifndef DITHER_NONE
opacityDither(&alpha, id * 0.013);
#endif
output.color = vec4f(input.gaussianColor.xyz * alpha, alpha);
#endif
return output;
}`,gsplatSHVS:`
#if SH_BANDS > 0
fn unpack111011s(bits: u32) -> vec3f {
return (vec3f((vec3<u32>(bits) >> vec3<u32>(21u, 11u, 0u)) & vec3<u32>(0x7ffu, 0x3ffu, 0x7ffu)) / vec3f(2047.0, 1023.0, 2047.0)) * 2.0 - 1.0;
}
struct ScaleAndSH {
scale: f32,
a: vec3f,
b: vec3f,
c: vec3f
};
fn fetchScale(t_in: vec4<u32>) -> ScaleAndSH {
var result: ScaleAndSH;
result.scale = bitcast<f32>(t_in.x);
result.a = unpack111011s(t_in.y);
result.b = unpack111011s(t_in.z);
result.c = unpack111011s(t_in.w);
return result;
}
struct SH {
a: vec3f,
b: vec3f,
c: vec3f,
d: vec3f
};
fn fetch4(t_in: vec4<u32>) -> SH {
var result: SH;
result.a = unpack111011s(t_in.x);
result.b = unpack111011s(t_in.y);
result.c = unpack111011s(t_in.z);
result.d = unpack111011s(t_in.w);
return result;
}
fn fetch1(t_in: u32) -> vec3f {
return unpack111011s(t_in);
}
#if SH_BANDS == 1
var splatSH_1to3: texture_2d<u32>;
fn readSHData(source: ptr<function, SplatSource>, sh: ptr<function, array<vec3f, 3>>, scale: ptr<function, f32>) {
let result = fetchScale(textureLoad(splatSH_1to3, source.uv, 0));
*scale = result.scale;
sh[0] = result.a;
sh[1] = result.b;
sh[2] = result.c;
}
#elif SH_BANDS == 2
var splatSH_1to3: texture_2d<u32>;
var splatSH_4to7: texture_2d<u32>;
var splatSH_8to11: texture_2d<u32>;
fn readSHData(source: ptr<function, SplatSource>, sh: ptr<function, array<vec3f, 8>>, scale: ptr<function, f32>) {
let first: ScaleAndSH = fetchScale(textureLoad(splatSH_1to3, source.uv, 0));
*scale = first.scale;
sh[0] = first.a;
sh[1] = first.b;
sh[2] = first.c;
let second: SH = fetch4(textureLoad(splatSH_4to7, source.uv, 0));
sh[3] = second.a;
sh[4] = second.b;
sh[5] = second.c;
sh[6] = second.d;
sh[7] = fetch1(textureLoad(splatSH_8to11, source.uv, 0).x);
}
#else
var splatSH_1to3: texture_2d<u32>;
var splatSH_4to7: texture_2d<u32>;
var splatSH_8to11: texture_2d<u32>;
var splatSH_12to15: texture_2d<u32>;
fn readSHData(source: ptr<function, SplatSource>, sh: ptr<function, array<vec3f, 15>>, scale: ptr<function, f32>) {
let first: ScaleAndSH = fetchScale(textureLoad(splatSH_1to3, source.uv, 0));
*scale = first.scale;
sh[0] = first.a;
sh[1] = first.b;
sh[2] = first.c;
let second: SH = fetch4(textureLoad(splatSH_4to7, source.uv, 0));
sh[3] = second.a;
sh[4] = second.b;
sh[5] = second.c;
sh[6] = second.d;
let third: SH = fetch4(textureLoad(splatSH_8to11, source.uv, 0));
sh[7] = third.a;
sh[8] = third.b;
sh[9] = third.c;
sh[10] = third.d;
let fourth: SH = fetch4(textureLoad(splatSH_12to15, source.uv, 0));
sh[11] = fourth.a;
sh[12] = fourth.b;
sh[13] = fourth.c;
sh[14] = fourth.d;
}
#endif
#endif
`,gsplatSourceVS:`
attribute vertex_position: vec3f;
attribute vertex_id_attrib: u32;
uniform numSplats: u32;
var splatOrder: texture_2d<u32>;
fn initSource(source: ptr<function, SplatSource>) -> bool {
let w: u32 = textureDimensions(splatOrder, 0).x;
source.order = vertex_id_attrib + u32(vertex_position.z);
if (source.order >= uniform.numSplats) {
return false;
}
let orderUV = vec2i(vec2u(source.order % w, source.order / w));
source.id = textureLoad(splatOrder, orderUV, 0).r;
source.uv = vec2i(vec2u(source.id % w, source.id / w));
source.cornerUV = vertex_position.xy;
return true;
}
`,gsplatVS:`
#include "gsplatCommonVS"
varying gaussianUV: vec2f;
varying gaussianColor: vec4f;
#ifndef DITHER_NONE
varying id: f32;
#endif
const discardVec: vec4f = vec4f(0.0, 0.0, 2.0, 1.0);
#ifdef PREPASS_PASS
varying vLinearDepth: f32;
#endif
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
var source: SplatSource;
if (!initSource(&source)) {
output.position = discardVec;
return output;
}
let modelCenter: vec3f = readCenter(&source);
var center: SplatCenter;
if (!initCenter(modelCenter, ¢er)) {
output.position = discardVec;
return output;
}
var corner: SplatCorner;
if (!initCorner(&source, ¢er, &corner)) {
output.position = discardVec;
return output;
}
var clr: vec4f = readColor(&source);
#if GSPLAT_AA
clr.a = clr.a * corner.aaFactor;
#endif
#if SH_BANDS > 0
let modelView3x3 = mat3x3f(center.modelView[0].xyz, center.modelView[1].xyz, center.modelView[2].xyz);
let dir = normalize(modelView3x3 * center.view);
var sh: array<vec3f, SH_COEFFS>;
var scale: f32;
readSHData(&source, &sh, &scale);
clr = vec4f(clr.xyz + evalSH(&sh, dir) * scale, clr.a);
#endif
clipCorner(&corner, clr.w);
output.position = center.proj + vec4f(corner.offset, 0.0, 0.0);
output.gaussianUV = corner.uv;
output.gaussianColor = vec4f(prepareOutputFromGamma(max(clr.xyz, vec3f(0.0))), clr.w);
#ifndef DITHER_NONE
output.id = f32(source.id);
#endif
#ifdef PREPASS_PASS
output.vLinearDepth = -center.view.z;
#endif
return output;
}
`,quadVS:`
attribute aPosition: vec2f;
varying uv0: vec2f;
@vertex fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = vec4f(input.aPosition, 0.0, 1.0);
output.uv0 = getImageEffectUV((input.aPosition + 1.0) * 0.5);
return output;
}
`,indirectCoreCS:`
struct DrawIndexedIndirectArgs {
indexCount: u32,
instanceCount: u32,
firstIndex: u32,
baseVertex: i32,
firstInstance: u32
};
struct DrawIndirectArgs {
vertexCount: u32,
instanceCount: u32,
firstVertex: u32,
firstInstance: u32,
_pad: u32
};
`,immediateLinePS:`
#include "gammaPS"
varying color: vec4f;
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
output.color = vec4f(gammaCorrectOutput(decodeGamma3(input.color.rgb)), input.color.a);
return output;
}
`,immediateLineVS:`
attribute vertex_position: vec4f;
attribute vertex_color: vec4f;
uniform matrix_model: mat4x4f;
uniform matrix_viewProjection: mat4x4f;
varying color: vec4f;
@vertex
fn vertexMain(input : VertexInput) -> VertexOutput {
var output : VertexOutput;
output.color = input.vertex_color;
output.position = uniform.matrix_viewProjection * uniform.matrix_model * input.vertex_position;
return output;
}
`,iridescenceDiffractionPS:`
uniform material_iridescenceRefractionIndex: f32;
fn iridescence_iorToFresnelScalar(transmittedIor: f32, incidentIor: f32) -> f32 {
return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);
}
fn iridescence_iorToFresnelVec3(transmittedIor: vec3f, incidentIor: f32) -> vec3f {
return pow((transmittedIor - vec3f(incidentIor)) / (transmittedIor + vec3f(incidentIor)), vec3f(2.0));
}
fn iridescence_fresnelToIor(f0: vec3f) -> vec3f {
let sqrtF0: vec3f = sqrt(f0);
return (vec3f(1.0) + sqrtF0) / (vec3f(1.0) - sqrtF0);
}
const XYZ_TO_REC709: mat3x3f = mat3x3f(
vec3f(3.2404542, -1.5371385, -0.4985314),
vec3f(-0.9692660, 1.8760108, 0.0415560),
vec3f(0.0556434, -0.2040259, 1.0572252)
);
fn iridescence_sensitivity(opd: f32, shift: vec3f) -> vec3f {
let PI: f32 = 3.141592653589793;
let phase: f32 = 2.0 * PI * opd * 1.0e-9;
const val: vec3f = vec3f(5.4856e-13, 4.4201e-13, 5.2481e-13);
const pos: vec3f = vec3f(1.6810e+06, 1.7953e+06, 2.2084e+06);
const var_: vec3f = vec3f(4.3278e+09, 9.3046e+09, 6.6121e+09);
var xyz: vec3f = val * sqrt(2.0 * PI * var_) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var_);
xyz.x = xyz.x + 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0));
xyz = xyz / vec3f(1.0685e-07);
return XYZ_TO_REC709 * xyz;
}
fn iridescence_fresnelScalar(cosTheta: f32, f0: f32) -> f32 {
let x: f32 = clamp(1.0 - cosTheta, 0.0, 1.0);
let x2: f32 = x * x;
let x5: f32 = x * x2 * x2;
return f0 + (1.0 - f0) * x5;
}
fn iridescence_fresnelVec3(cosTheta: f32, f0: vec3f) -> vec3f {
let x: f32 = clamp(1.0 - cosTheta, 0.0, 1.0);
let x2: f32 = x * x;
let x5: f32 = x * x2 * x2;
return f0 + (vec3f(1.0) - f0) * x5;
}
fn calcIridescence(outsideIor: f32, cosTheta: f32, base_f0: vec3f, iridescenceThickness: f32) -> vec3f {
let PI: f32 = 3.141592653589793;
let iridescenceIor: f32 = mix(outsideIor, uniform.material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, iridescenceThickness));
let sinTheta2Sq: f32 = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0));
let cosTheta2Sq: f32 = 1.0 - sinTheta2Sq;
if (cosTheta2Sq < 0.0) {
return vec3f(1.0);
}
let cosTheta2: f32 = sqrt(cosTheta2Sq);
let r0: f32 = iridescence_iorToFresnelScalar(iridescenceIor, outsideIor);
let r12: f32 = iridescence_fresnelScalar(cosTheta, r0);
let r21: f32 = r12;
let t121: f32 = 1.0 - r12;
let phi12: f32 = select(0.0, PI, iridescenceIor < outsideIor);
let phi21: f32 = PI - phi12;
let baseIor: vec3f = iridescence_fresnelToIor(base_f0 + vec3f(0.0001));
let r1: vec3f = iridescence_iorToFresnelVec3(baseIor, iridescenceIor);
let r23: vec3f = iridescence_fresnelVec3(cosTheta2, r1);
let phi23: vec3f = select(vec3f(0.0), vec3f(PI), baseIor < vec3f(iridescenceIor));
let opd: f32 = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2;
let phi: vec3f = vec3f(phi21) + phi23;
let r123Sq: vec3f = clamp(vec3f(r12) * r23, vec3f(1e-5), vec3f(0.9999));
let r123: vec3f = sqrt(r123Sq);
let rs: vec3f = pow(vec3f(t121), vec3f(2.0)) * r23 / (vec3f(1.0) - r123Sq);
let c0: vec3f = vec3f(r12) + rs;
var i_irid: vec3f = c0;
var cm: vec3f = rs - vec3f(t121);
cm = cm * r123;
let sm1: vec3f = 2.0 * iridescence_sensitivity(1.0 * opd, 1.0 * phi);
i_irid = i_irid + cm * sm1;
cm = cm * r123;
let sm2: vec3f = 2.0 * iridescence_sensitivity(2.0 * opd, 2.0 * phi);
i_irid = i_irid + cm * sm2;
return max(i_irid, vec3f(0.0));
}
fn getIridescenceDiffraction(cosTheta: f32, specularity: vec3f, iridescenceThickness: f32) -> vec3f {
return calcIridescence(1.0, cosTheta, specularity, iridescenceThickness);
}
`,iridescencePS:`
#ifdef STD_IRIDESCENCE_CONSTANT
uniform material_iridescence: f32;
#endif
fn getIridescence() {
var iridescence = 1.0;
#ifdef STD_IRIDESCENCE_CONSTANT
iridescence = iridescence * uniform.material_iridescence;
#endif
#ifdef STD_IRIDESCENCE_TEXTURE
iridescence = iridescence * textureSampleBias({STD_IRIDESCENCE_TEXTURE_NAME}, {STD_IRIDESCENCE_TEXTURE_NAME}Sampler, {STD_IRIDESCENCE_TEXTURE_UV}, uniform.textureBias).{STD_IRIDESCENCE_TEXTURE_CHANNEL};
#endif
dIridescence = iridescence;
}
`,iridescenceThicknessPS:`
uniform material_iridescenceThicknessMax: f32;
#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE
uniform material_iridescenceThicknessMin: f32;
#endif
fn getIridescenceThickness() {
#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE
var blend: f32 = textureSampleBias({STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}, {STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}Sampler, {STD_IRIDESCENCETHICKNESS_TEXTURE_UV}, uniform.textureBias).{STD_IRIDESCENCETHICKNESS_TEXTURE_CHANNEL};
var iridescenceThickness: f32 = mix(uniform.material_iridescenceThicknessMin, uniform.material_iridescenceThicknessMax, blend);
#else
var iridescenceThickness: f32 = uniform.material_iridescenceThicknessMax;
#endif
dIridescenceThickness = iridescenceThickness;
}
`,iorPS:`
#ifdef STD_IOR_CONSTANT
uniform material_refractionIndex: f32;
#endif
fn getIor() {
#ifdef STD_IOR_CONSTANT
dIor = uniform.material_refractionIndex;
#else
dIor = 1.0 / 1.5;
#endif
}
`,lightDeclarationPS:`
#if defined(LIGHT{i})
uniform light{i}_color: vec3f;
#if LIGHT{i}TYPE == DIRECTIONAL
uniform light{i}_direction: vec3f;
#else
#define LIT_CODE_LIGHTS_POINT
uniform light{i}_position: vec3f;
uniform light{i}_radius: f32;
#if LIGHT{i}TYPE == SPOT
#define LIT_CODE_LIGHTS_SPOT
uniform light{i}_direction: vec3f;
uniform light{i}_innerConeAngle: f32;
uniform light{i}_outerConeAngle: f32;
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#define LIT_CODE_FALLOFF_SQUARED
#if LIGHT{i}TYPE == DIRECTIONAL
uniform light{i}_position: vec3f;
#endif
uniform light{i}_halfWidth: vec3f;
uniform light{i}_halfHeight: vec3f;
#else
#if LIGHT{i}FALLOFF == LINEAR
#define LIT_CODE_FALLOFF_LINEAR
#endif
#if LIGHT{i}FALLOFF == INVERSESQUARED
#define LIT_CODE_FALLOFF_SQUARED
#endif
#endif
#if defined(LIGHT{i}CASTSHADOW)
uniform light{i}_shadowMatrix: mat4x4f;
uniform light{i}_shadowIntensity: f32;
uniform light{i}_shadowParams: vec4f;
#if LIGHT{i}SHADOWTYPE == PCSS_32F
uniform light{i}_shadowSearchArea: f32;
uniform light{i}_cameraParams: vec4f;
#if LIGHT{i}TYPE == DIRECTIONAL
uniform light{i}_softShadowParams: vec4f;
#endif
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
uniform light{i}_shadowMatrixPalette: array<mat4x4f, 4>;
uniform light{i}_shadowCascadeDistances: vec4f;
uniform light{i}_shadowCascadeCount: i32;
uniform light{i}_shadowCascadeBlend: f32;
#endif
#if LIGHT{i}TYPE == OMNI
NOT SUPPORTED
#else
#if defined(LIGHT{i}SHADOW_PCF)
var light{i}_shadowMap: texture_depth_2d;
var light{i}_shadowMapSampler: sampler_comparison;
#else
var light{i}_shadowMap: texture_2d<f32>;
var light{i}_shadowMapSampler: sampler;
#endif
#endif
#endif
#if defined(LIGHT{i}COOKIE)
#define LIT_CODE_COOKIE
#if LIGHT{i}TYPE == OMNI
NOT SUPPORTED
#endif
#if LIGHT{i}TYPE == SPOT
NOT SUPPORTED
#endif
#endif
#endif
`,lightDiffuseLambertPS:`
fn getLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f) -> f32 {
return max(dot(worldNormal, -lightDirNorm), 0.0);
}
`,lightDirPointPS:`
fn evalOmniLight(lightPosW: vec3f) -> vec3f {
return vPositionW - lightPosW;
}
`,lightEvaluationPS:`
#if defined(LIGHT{i})
evaluateLight{i}(
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel
#endif
);
#endif
`,lightFunctionLightPS:`
#if defined(LIGHT{i})
fn evaluateLight{i}(
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel: vec3f
#endif
) {
var lightColor: vec3f = uniform.light{i}_color;
#if LIGHT{i}TYPE == DIRECTIONAL && !defined(LIT_SHADOW_CATCHER)
if (all(lightColor == vec3f(0.0, 0.0, 0.0))) {
return;
}
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
dLightDirNormW = uniform.light{i}_direction;
dAtten = 1.0;
#else
var lightDirW: vec3f = evalOmniLight(uniform.light{i}_position);
dLightDirNormW = normalize(lightDirW);
#if defined(LIGHT{i}COOKIE)
#if LIGHT{i}TYPE == SPOT
#ifdef LIGHT{i}COOKIE_FALLOFF
#ifdef LIGHT{i}COOKIE_TRANSFORM
var cookieAttenuation: vec3f = getCookie2DXform(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity, uniform.light{i}_cookieMatrix, uniform.light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};
#else
var cookieAttenuation: vec3f = getCookie2D(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
#else
#ifdef LIGHT{i}COOKIE_TRANSFORM
var cookieAttenuation: vec3f = getCookie2DClipXform(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity, uniform.light{i}_cookieMatrix, uniform.light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};
#else
var cookieAttenuation: vec3f = getCookie2DClip(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
#endif
#endif
#if LIGHT{i}TYPE == OMNI
var cookieAttenuation: vec3f = getCookieCube(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
lightColor = lightColor * cookieAttenuation;
#endif
#if LIGHT{i}SHAPE == PUNCTUAL
#if LIGHT{i}FALLOFF == LINEAR
dAtten = getFalloffLinear(uniform.light{i}_radius, lightDirW);
#else
dAtten = getFalloffInvSquared(uniform.light{i}_radius, lightDirW);
#endif
#else
dAtten = getFalloffWindow(uniform.light{i}_radius, lightDirW);
#endif
#if LIGHT{i}TYPE == SPOT
#if !defined(LIGHT{i}COOKIE) || defined(LIGHT{i}COOKIE_FALLOFF)
dAtten = dAtten * getSpotEffect(uniform.light{i}_direction, uniform.light{i}_innerConeAngle, uniform.light{i}_outerConeAngle, dLightDirNormW);
#endif
#endif
#endif
if (dAtten < 0.00001) {
return;
}
#if LIGHT{i}SHAPE != PUNCTUAL
#if LIGHT{i}SHAPE == RECT
calcRectLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight);
#elif LIGHT{i}SHAPE == DISK
calcDiskLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight);
#elif LIGHT{i}SHAPE == SPHERE
calcSphereLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight);
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#if LIGHT{i}TYPE == DIRECTIONAL
var attenDiffuse: f32 = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirNormW);
#else
#if LIGHT{i}SHAPE == RECT
var attenDiffuse: f32 = getRectLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#elif LIGHT{i}SHAPE == DISK
var attenDiffuse: f32 = getDiskLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#elif LIGHT{i}SHAPE == SPHERE
var attenDiffuse: f32 = getSphereLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#endif
#endif
#else
dAtten = dAtten * getLightDiffuse(litArgs_worldNormal, vec3(0.0), dLightDirNormW);
#endif
#ifdef LIGHT{i}CASTSHADOW
#if LIGHT{i}TYPE == DIRECTIONAL
var shadow: f32 = getShadow{i}(vec3(0.0));
#else
var shadow: f32 = getShadow{i}(lightDirW);
#endif
shadow = mix(1.0, shadow, uniform.light{i}_shadowIntensity);
dAtten = dAtten * shadow;
#if defined(LIT_SHADOW_CATCHER) && LIGHT{i}TYPE == DIRECTIONAL
dShadowCatcher = dShadowCatcher * shadow;
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#ifdef LIT_SPECULAR
dDiffuseLight = dDiffuseLight + (((attenDiffuse * dAtten) * lightColor) * (1.0 - dLTCSpecFres));
#else
dDiffuseLight = dDiffuseLight + ((attenDiffuse * dAtten) * lightColor);
#endif
#else
#if defined(AREA_LIGHTS) && defined(LIT_SPECULAR)
dDiffuseLight = dDiffuseLight + ((dAtten * lightColor) * (1.0 - litArgs_specularity));
#else
dDiffuseLight = dDiffuseLight + (dAtten * lightColor);
#endif
#endif
#ifdef LIGHT{i}AFFECT_SPECULARITY
#if LIGHT{i}SHAPE != PUNCTUAL
#ifdef LIT_CLEARCOAT
#if LIGHT{i}SHAPE == RECT
ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getRectLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor);
#elif LIGHT{i}SHAPE == DISK
ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getDiskLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor);
#elif LIGHT{i}SHAPE == SPHERE
ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getSphereLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor);
#endif
#endif
#ifdef LIT_SPECULAR
#if LIGHT{i}SHAPE == RECT
dSpecularLight = dSpecularLight + (dLTCSpecFres * getRectLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor);
#elif LIGHT{i}SHAPE == DISK
dSpecularLight = dSpecularLight + (dLTCSpecFres * getDiskLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor);
#elif LIGHT{i}SHAPE == SPHERE
dSpecularLight = dSpecularLight + (dLTCSpecFres * getSphereLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor);
#endif
#endif
#else
#if LIGHT{i}TYPE == DIRECTIONAL && LIT_FRESNEL_MODEL != NONE
#define LIGHT{i}FRESNEL
#endif
#ifdef LIT_SPECULAR
var halfDirW: vec3f = normalize(-dLightDirNormW + dViewDirW);
#endif
#ifdef LIT_CLEARCOAT
var lightspecularCC: vec3f = getLightSpecular(halfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * lightColor;
#ifdef LIGHT{i}FRESNEL
lightspecularCC = lightspecularCC * getFresnelCC(dot(dViewDirW, halfDirW));
#endif
ccSpecularLight = ccSpecularLight + lightspecularCC;
#endif
#ifdef LIT_SHEEN
sSpecularLight = sSpecularLight + (getLightSpecularSheen(halfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * lightColor);
#endif
#ifdef LIT_SPECULAR
var lightSpecular: vec3f = getLightSpecular(halfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * lightColor;
#ifdef LIGHT{i}FRESNEL
#if defined(LIT_IRIDESCENCE)
lightSpecular = lightSpecular * getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity, iridescenceFresnel, litArgs_iridescence_intensity);
#else
lightSpecular = lightSpecular * getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity);
#endif
#else
lightSpecular = lightSpecular * litArgs_specularity;
#endif
dSpecularLight = dSpecularLight + lightSpecular;
#endif
#endif
#endif
}
#endif
`,lightFunctionShadowPS:`
#ifdef LIGHT{i}CASTSHADOW
fn getShadowSampleCoord{i}(shadowTransform: mat4x4f, shadowParams: vec4f, worldPosition: vec3f, lightPos: vec3f, lightDir: ptr<function, vec3f>, lightDirNorm: vec3f, normal: vec3f) -> vec3f {
var surfacePosition = worldPosition;
#ifdef LIGHT{i}_SHADOW_SAMPLE_POINT
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
let distScale: f32 = length(*lightDir);
surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
*lightDir = surfacePosition - lightPos;
return *lightDir;
#endif
#else
#ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
surfacePosition = surfacePosition + normal * shadowParams.y;
#endif
#else
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
#ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO
var distScale: f32 = 1.0;
#else
var distScale: f32 = abs(dot(vPositionW - lightPos, lightDirNorm));
#endif
surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
#endif
#endif
var positionInShadowSpace: vec4f = shadowTransform * vec4f(surfacePosition, 1.0);
#ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO
positionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001;
#else
#ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER
positionInShadowSpace.xyz = positionInShadowSpace.xyz / positionInShadowSpace.w;
#else
positionInShadowSpace.xy = positionInShadowSpace.xy / positionInShadowSpace.w;
positionInShadowSpace.z = length(*lightDir) * shadowParams.w;
#endif
#endif
#ifdef SHADOW_SAMPLE_Z_BIAS
#endif
surfacePosition = positionInShadowSpace.xyz;
#endif
return surfacePosition;
}
fn getShadow{i}(lightDirW_in: vec3f) -> f32 {
#ifdef LIGHT{i}_SHADOW_CASCADES
var cascadeIndex: i32 = getShadowCascadeIndex(uniform.light{i}_shadowCascadeDistances, uniform.light{i}_shadowCascadeCount);
#ifdef LIGHT{i}_SHADOW_CASCADE_BLEND
cascadeIndex = ditherShadowCascadeIndex(cascadeIndex, uniform.light{i}_shadowCascadeDistances, uniform.light{i}_shadowCascadeCount, uniform.light{i}_shadowCascadeBlend);
#endif
var shadowMatrix: mat4x4f = uniform.light{i}_shadowMatrixPalette[cascadeIndex];
#else
var shadowMatrix: mat4x4f = uniform.light{i}_shadowMatrix;
#endif
var lightDirArg = lightDirW_in;
#if LIGHT{i}TYPE == DIRECTIONAL
var shadowCoord: vec3f = getShadowSampleCoord{i}(shadowMatrix, uniform.light{i}_shadowParams, vPositionW, vec3f(0.0), &lightDirArg, dLightDirNormW, dVertexNormalW);
#else
var shadowCoord: vec3f = getShadowSampleCoord{i}(shadowMatrix, uniform.light{i}_shadowParams, vPositionW, uniform.light{i}_position, &lightDirArg, dLightDirNormW, dVertexNormalW);
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
shadowCoord = fadeShadow(shadowCoord, uniform.light{i}_shadowCascadeDistances);
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
#if LIGHT{i}SHADOWTYPE == VSM_16F
return getShadowVSM16(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 5.54);
#endif
#if LIGHT{i}SHADOWTYPE == VSM_32F
return getShadowVSM32(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 15.0);
#endif
#if LIGHT{i}SHADOWTYPE == PCSS_32F
#if LIGHT{i}SHAPE != PUNCTUAL
let shadowSearchArea = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea;
return getShadowPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in);
#else
return getShadowPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, uniform.light{i}_softShadowParams, lightDirW_in);
#endif
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F
return getShadowPCF5x5(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#endif
#if LIGHT{i}TYPE == SPOT
#if LIGHT{i}SHADOWTYPE == VSM_16F
return getShadowSpotVSM16(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 5.54, lightDirW_in);
#endif
#if LIGHT{i}SHADOWTYPE == VSM_32F
return getShadowSpotVSM32(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 15.0, lightDirW_in);
#endif
#if LIGHT{i}SHADOWTYPE == PCSS_32F
#if LIGHT{i}SHAPE != PUNCTUAL
var shadowSearchArea: vec2f = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea;
#else
var shadowSearchArea: vec2f = vec2f(uniform.light{i}_shadowSearchArea);
#endif
return getShadowSpotPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in);
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowSpotPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowSpotPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F
return getShadowSpotPCF5x5(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#endif
#if LIGHT{i}TYPE == OMNI
#if LIGHT{i}SHADOWTYPE == PCSS_32F
var shadowSearchArea: vec2f;
#if LIGHT{i}SHAPE != PUNCTUAL
var shadowSearchArea: vec2f = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea;
#else
var shadowSearchArea: vec2f = vec2f(uniform.light{i}_shadowSearchArea);
#endif
return getShadowOmniPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in);
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowOmniPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, lightDirW_in);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowOmniPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, lightDirW_in);
#endif
#endif
}
#endif
`,lightingPS:`
#ifdef LIT_CLUSTERED_LIGHTS
#define LIT_CODE_FALLOFF_LINEAR
#define LIT_CODE_FALLOFF_SQUARED
#define LIT_CODE_LIGHTS_POINT
#define LIT_CODE_LIGHTS_SPOT
#endif
#ifdef AREA_LIGHTS
var areaLightsLutTex1: texture_2d<f32>;
var areaLightsLutTex1Sampler: sampler;
var areaLightsLutTex2: texture_2d<f32>;
var areaLightsLutTex2Sampler: sampler;
#endif
#ifdef LIT_LIGHTING
#include "lightDiffuseLambertPS"
#if defined(AREA_LIGHTS) || defined(LIT_CLUSTERED_AREA_LIGHTS)
#include "ltcPS"
#endif
#endif
#ifdef SHADOW_DIRECTIONAL
#include "shadowCascadesPS"
#endif
#if defined(SHADOW_KIND_PCF1)
#include "shadowPCF1PS"
#endif
#if defined(SHADOW_KIND_PCF3)
#include "shadowPCF3PS"
#endif
#if defined(SHADOW_KIND_PCF5)
#include "shadowPCF5PS"
#endif
#if defined(SHADOW_KIND_PCSS)
#include "linearizeDepthPS"
#include "shadowSoftPS"
#endif
#if defined(SHADOW_KIND_VSM)
#include "shadowEVSMPS"
#endif
#ifdef LIT_CODE_FALLOFF_LINEAR
#include "falloffLinearPS"
#endif
#ifdef LIT_CODE_FALLOFF_SQUARED
#include "falloffInvSquaredPS"
#endif
#ifdef LIT_CODE_LIGHTS_POINT
#include "lightDirPointPS"
#endif
#ifdef LIT_CODE_LIGHTS_SPOT
#include "spotPS"
#endif
#ifdef LIT_CODE_COOKIE
#include "cookiePS"
#endif
#ifdef LIT_CLUSTERED_LIGHTS
#include "clusteredLightPS"
#endif
#ifdef LIGHT_COUNT > 0
#include "lightFunctionShadowPS, LIGHT_COUNT"
#include "lightFunctionLightPS, LIGHT_COUNT"
#endif
`,lightmapAddPS:`
fn addLightMap(
lightmap: vec3f,
dir: vec3f,
worldNormal: vec3f,
viewDir: vec3f,
reflectionDir: vec3f,
gloss: f32,
specularity: vec3f,
vertexNormal: vec3f,
tbn: mat3x3f
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel: vec3f,
iridescenceIntensity: f32
#endif
) {
#if defined(LIT_SPECULAR) && defined(LIT_DIR_LIGHTMAP)
if (dot(dir, dir) < 0.0001) {
dDiffuseLight = dDiffuseLight + lightmap;
} else {
let vlight: f32 = saturate(dot(dir, -vertexNormal));
let flight: f32 = saturate(dot(dir, -worldNormal));
let nlight: f32 = (flight / max(vlight, 0.01)) * 0.5;
dDiffuseLight = dDiffuseLight + lightmap * nlight * 2.0;
let halfDir: vec3f = normalize(-dir + viewDir);
var specularLight: vec3f = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn);
#ifdef LIT_SPECULAR_FRESNEL
specularLight = specularLight *
getFresnel(dot(viewDir, halfDir),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescenceIntensity
#endif
);
#endif
dSpecularLight = dSpecularLight + specularLight;
}
#else
dDiffuseLight = dDiffuseLight + lightmap;
#endif
}
`,lightmapPS:`
#ifdef STD_LIGHTMAP_DIR
var<private> dLightmapDir: vec3f;
var texture_dirLightMap: texture_2d<f32>;
var texture_dirLightMapSampler: sampler;
#endif
fn getLightMap() {
dLightmap = vec3f(1.0);
#ifdef STD_LIGHT_TEXTURE
dLightmap = dLightmap * {STD_LIGHT_TEXTURE_DECODE}(textureSampleBias({STD_LIGHT_TEXTURE_NAME}, {STD_LIGHT_TEXTURE_NAME}Sampler, {STD_LIGHT_TEXTURE_UV}, uniform.textureBias)).{STD_LIGHT_TEXTURE_CHANNEL};
#ifdef STD_LIGHTMAP_DIR
var dir: vec3f = textureSampleBias(texture_dirLightMap, texture_dirLightMapSampler, {STD_LIGHT_TEXTURE_UV}, uniform.textureBias).xyz * 2.0 - 1.0;
var dirDot = dot(dir, dir);
dLightmapDir = select(vec3(0.0), dir / sqrt(dirDot), dirDot > 0.001);
#endif
#endif
#ifdef STD_LIGHT_VERTEX
dLightmap = dLightmap * saturate(vVertexColor.{STD_LIGHT_VERTEX_CHANNEL});
#endif
}
`,lightSpecularAnisoGGXPS:`
fn calcLightSpecular(gloss: f32, worldNormal: vec3f, viewDir: vec3f, h: vec3f, lightDirNorm: vec3f, tbn: mat3x3f) -> f32 {
let PI: f32 = 3.141592653589793;
let roughness: f32 = max((1.0 - gloss) * (1.0 - gloss), 0.001);
let alphaRoughness: f32 = roughness * roughness;
let anisotropy: f32 = dAnisotropy;
let direction: vec2f = dAnisotropyRotation;
let at: f32 = mix(alphaRoughness, 1.0, anisotropy * anisotropy);
let ab: f32 = clamp(alphaRoughness, 0.001, 1.0);
let anisotropicT: vec3f = normalize(tbn * vec3f(direction, 0.0));
let anisotropicB: vec3f = normalize(cross(tbn[2], anisotropicT));
let NoH: f32 = dot(worldNormal, h);
let ToH: f32 = dot(anisotropicT, h);
let BoH: f32 = dot(anisotropicB, h);
let a2: f32 = at * ab;
let v: vec3f = vec3f(ab * ToH, at * BoH, a2 * NoH);
let v2: f32 = dot(v, v);
let w2: f32 = a2 / v2;
let D: f32 = a2 * w2 * w2 * (1.0 / PI);
let ToV: f32 = dot(anisotropicT, viewDir);
let BoV: f32 = dot(anisotropicB, viewDir);
let ToL: f32 = dot(anisotropicT, -lightDirNorm);
let BoL: f32 = dot(anisotropicB, -lightDirNorm);
let NoV: f32 = dot(worldNormal, viewDir);
let NoL: f32 = dot(worldNormal, -lightDirNorm);
let lambdaV: f32 = NoL * length(vec3f(at * ToV, ab * BoV, NoV));
let lambdaL: f32 = NoV * length(vec3f(at * ToL, ab * BoL, NoL));
let G: f32 = 0.5 / (lambdaV + lambdaL);
return D * G;
}
fn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 {
return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn);
}
`,lightSpecularBlinnPS:`
fn calcLightSpecular(gloss: f32, worldNormal: vec3f, h: vec3f) -> f32 {
let nh: f32 = max( dot( h, worldNormal ), 0.0 );
var specPow: f32 = exp2(gloss * 11.0);
specPow = max(specPow, 0.0001);
return pow(nh, specPow) * (specPow + 2.0) / 8.0;
}
fn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 {
return calcLightSpecular(gloss, worldNormal, h);
}
`,lightSheenPS:`
fn sheenD(normal: vec3f, h: vec3f, roughness: f32) -> f32 {
let PI: f32 = 3.141592653589793;
let invR: f32 = 1.0 / (roughness * roughness);
var cos2h: f32 = max(dot(normal, h), 0.0);
cos2h = cos2h * cos2h;
let sin2h: f32 = max(1.0 - cos2h, 0.0078125);
return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);
}
fn sheenV(normal: vec3f, viewDir: vec3f, light: vec3f) -> f32 {
let NoV: f32 = max(dot(normal, viewDir), 0.000001);
let NoL: f32 = max(dot(normal, light), 0.000001);
return 1.0 / (4.0 * (NoL + NoV - NoL * NoV));
}
fn getLightSpecularSheen(h: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, sheenGloss: f32) -> f32 {
let D: f32 = sheenD(worldNormal, h, sheenGloss);
let V: f32 = sheenV(worldNormal, viewDir, -lightDirNorm);
return D * V;
}`,linearizeDepthPS:`
#ifndef LINEARIZE_DEPTH
#define LINEARIZE_DEPTH
fn linearizeDepthWithParams(z: f32, cameraParams: vec4f) -> f32 {
if (cameraParams.w == 0.0) {
return (cameraParams.z * cameraParams.y) / (cameraParams.y + z * (cameraParams.z - cameraParams.y));
} else {
return cameraParams.z + z * (cameraParams.y - cameraParams.z);
}
}
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform camera_params: vec4f;
#endif
fn linearizeDepth(z: f32) -> f32 {
return linearizeDepthWithParams(z, uniform.camera_params);
}
#endif
`,litForwardBackendPS:`
fn evaluateBackend() -> FragmentOutput {
var output: FragmentOutput;
#ifdef LIT_SSAO
litArgs_ao = litArgs_ao * textureSampleLevel(ssaoTexture, ssaoTextureSampler, pcPosition.xy * uniform.ssaoTextureSizeInv, 0.0).r;
#endif
#ifdef LIT_NEEDS_NORMAL
#ifdef LIT_SPECULAR
getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);
#endif
#ifdef LIT_CLEARCOAT
ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));
#endif
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_METALNESS
var f0: f32 = 1.0 / litArgs_ior;
f0 = (f0 - 1.0) / (f0 + 1.0);
f0 = f0 * f0;
litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0);
litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);
#endif
#ifdef LIT_IRIDESCENCE
var iridescenceFresnel: vec3f = getIridescenceDiffraction(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);
#endif
#endif
#ifdef LIT_ADD_AMBIENT
addAmbient(litArgs_worldNormal);
#ifdef LIT_SPECULAR
dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);
#endif
#ifdef LIT_SEPARATE_AMBIENT
var dAmbientLight: vec3f = dDiffuseLight;
dDiffuseLight = vec3(0.0);
#endif
#endif
#ifndef LIT_OLD_AMBIENT
dDiffuseLight = dDiffuseLight * uniform.material_ambient;
#endif
#ifdef LIT_AO
#ifndef LIT_OCCLUDE_DIRECT
occludeDiffuse(litArgs_ao);
#endif
#endif
#ifdef LIT_LIGHTMAP
addLightMap(
litArgs_lightmap,
litArgs_lightmapDir,
litArgs_worldNormal,
dViewDirW,
dReflDirW,
litArgs_gloss,
litArgs_specularity,
dVertexNormalW,
dTBN
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
);
#endif
#ifdef LIT_LIGHTING || LIT_REFLECTIONS
#ifdef LIT_REFLECTIONS
#ifdef LIT_CLEARCOAT
addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);
#ifdef LIT_SPECULAR_FRESNEL
ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));
ccReflection = ccReflection * ccFresnel;
#else
ccFresnel = 0.0;
#endif
#endif
#ifdef LIT_SPECULARITY_FACTOR
ccReflection = ccReflection * litArgs_specularityFactor;
#endif
#ifdef LIT_SHEEN
addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);
#endif
addReflection(dReflDirW, litArgs_gloss);
#ifdef LIT_FRESNEL_MODEL
dReflection = vec4f(
dReflection.rgb * getFresnel(
dot(dViewDirW, litArgs_worldNormal),
litArgs_gloss,
litArgs_specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
),
dReflection.a
);
#else
dReflection = vec4f(dReflection.rgb * litArgs_specularity, dReflection.a);
#endif
#ifdef LIT_SPECULARITY_FACTOR
dReflection = vec4f(dReflection.rgb * litArgs_specularityFactor, dReflection.a);
#endif
#endif
#ifdef AREA_LIGHTS
dSpecularLight = dSpecularLight * litArgs_specularity;
#ifdef LIT_SPECULAR
calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);
#endif
#endif
#ifdef LIGHT_COUNT > 0
#include "lightEvaluationPS, LIGHT_COUNT"
#endif
#ifdef LIT_CLUSTERED_LIGHTS
addClusteredLights(litArgs_worldNormal, dViewDirW, dReflDirW,
#if defined(LIT_CLEARCOAT)
ccReflDirW,
#endif
litArgs_gloss, litArgs_specularity, dVertexNormalW, dTBN,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
litArgs_clearcoat_worldNormal, litArgs_clearcoat_gloss, litArgs_sheen_gloss, litArgs_iridescence_intensity
);
#endif
#ifdef AREA_LIGHTS
#ifdef LIT_CLEARCOAT
litArgs_clearcoat_specularity = 1.0;
#endif
#ifdef LIT_SPECULAR
litArgs_specularity = vec3(1.0);
#endif
#endif
#ifdef LIT_REFRACTION
addRefraction(
litArgs_worldNormal,
dViewDirW,
litArgs_thickness,
litArgs_gloss,
litArgs_specularity,
litArgs_albedo,
litArgs_transmission,
litArgs_ior,
litArgs_dispersion
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
);
#endif
#endif
#ifdef LIT_AO
#ifdef LIT_OCCLUDE_DIRECT
occludeDiffuse(litArgs_ao);
#endif
#if LIT_OCCLUDE_SPECULAR != NONE
occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);
#endif
#endif
#ifdef LIT_SPECULARITY_FACTOR
dSpecularLight = dSpecularLight * litArgs_specularityFactor;
#endif
#if !defined(LIT_OPACITY_FADES_SPECULAR)
#if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == PREMULTIPLIED
var specLum: f32 = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3f( 0.2126, 0.7152, 0.0722 ));
#ifdef LIT_CLEARCOAT
specLum = specLum + dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection * litArgs_clearcoat_specularity, vec3f( 0.2126, 0.7152, 0.0722 ));
#endif
litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);
#endif
litArgs_opacity = litArgs_opacity * uniform.material_alphaFade;
#endif
#ifdef LIT_LIGHTMAP_BAKING
#ifdef LIT_LIGHTMAP_BAKING_COLOR
#include "bakeLmEndPS"
#endif
#ifdef LIT_LIGHTMAP_BAKING_DIR
#include "bakeDirLmEndPS"
#endif
#else
#include "endPS"
#include "outputAlphaPS"
#endif
#ifdef LIT_MSDF
output.color = applyMsdf(output.color);
#endif
#include "outputPS"
#include "debugOutputPS"
#ifdef LIT_SHADOW_CATCHER
output.color = vec4f(vec3f(dShadowCatcher), output.color.a);
#endif
return output;
}
`,litForwardDeclarationPS:`
var<private> sReflection: vec3f;
var<private> dVertexNormalW: vec3f;
var<private> dTangentW: vec3f;
var<private> dBinormalW: vec3f;
var<private> dViewDirW: vec3f;
var<private> dReflDirW: vec3f;
var<private> ccReflDirW: vec3f;
var<private> dLightDirNormW: vec3f;
var<private> dAtten: f32;
var<private> dTBN: mat3x3f;
var<private> dReflection: vec4f;
var<private> dDiffuseLight: vec3f;
var<private> dSpecularLight: vec3f;
var<private> ccFresnel: f32;
var<private> ccReflection: vec3f;
var<private> ccSpecularLight: vec3f;
var<private> ccSpecularityNoFres: f32;
var<private> sSpecularLight: vec3f;
#ifdef LIT_DISPERSION
uniform material_dispersion: f32;
#endif
#ifndef LIT_OPACITY_FADES_SPECULAR
uniform material_alphaFade: f32;
#endif
#ifdef LIT_SSAO
var ssaoTexture : texture_2d<f32>;
var ssaoTextureSampler : sampler;
uniform ssaoTextureSizeInv: vec2f;
#endif
#ifdef LIT_SHADOW_CATCHER
var<private> dShadowCatcher: f32 = 1.0;
#endif
#if LIGHT_COUNT > 0
#include "lightDeclarationPS, LIGHT_COUNT"
#endif
#ifdef LIT_SPECULAR
#if LIT_FRESNEL_MODEL == NONE && !defined(LIT_REFLECTIONS) && !defined(LIT_DIFFUSE_MAP)
#define LIT_OLD_AMBIENT
#endif
#endif
#ifdef STD_LIGHTMAP_DIR
uniform bakeDir: f32;
#endif
#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT
uniform ambientBakeOcclusionContrast: f32;
uniform ambientBakeOcclusionBrightness: f32;
#endif
`,litForwardMainPS:`
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
#include "litUserMainStartPS"
dReflection = vec4f(0.0);
#ifdef LIT_CLEARCOAT
ccSpecularLight = vec3f(0.0);
ccReflection = vec3f(0.0);
#endif
#if LIT_NONE_SLICE_MODE == SLICED
#include "startNineSlicedPS"
#elif LIT_NONE_SLICE_MODE == TILED
#include "startNineSlicedTiledPS"
#endif
#ifdef LIT_NEEDS_NORMAL
dVertexNormalW = normalize(vNormalW);
#ifdef LIT_TANGENTS
#if defined(LIT_HEIGHTS) || defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS) || defined(LIT_GGX_SPECULAR)
dTangentW = vTangentW;
dBinormalW = vBinormalW;
#endif
#endif
getViewDir();
#ifdef LIT_TBN
getTBN(dTangentW, dBinormalW, dVertexNormalW);
#ifdef LIT_TWO_SIDED_LIGHTING
handleTwoSidedLighting();
#endif
#endif
#endif
evaluateFrontend();
#include "debugProcessFrontendPS"
var output: FragmentOutput = evaluateBackend();
#include "litUserMainEndPS"
return output;
}
`,litForwardPostCodePS:`
#ifdef LIT_NEEDS_NORMAL
#include "cubeMapRotatePS"
#include "cubeMapProjectPS"
#include "envProcPS"
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_METALNESS
#include "metalnessModulatePS"
#endif
#if LIT_FRESNEL_MODEL == SCHLICK
#include "fresnelSchlickPS"
#endif
#ifdef LIT_IRIDESCENCE
#include "iridescenceDiffractionPS"
#endif
#endif
#ifdef LIT_AO
#include "aoDiffuseOccPS"
#include "aoSpecOccPS"
#endif
#if LIT_REFLECTION_SOURCE == ENVATLASHQ
#include "envAtlasPS"
#include "reflectionEnvHQPS"
#elif LIT_REFLECTION_SOURCE == ENVATLAS
#include "envAtlasPS"
#include "reflectionEnvPS"
#elif LIT_REFLECTION_SOURCE == CUBEMAP
#include "reflectionCubePS"
#elif LIT_REFLECTION_SOURCE == SPHEREMAP
#include "reflectionSpherePS"
#endif
#ifdef LIT_REFLECTIONS
#ifdef LIT_CLEARCOAT
#include "reflectionCCPS"
#endif
#ifdef LIT_SHEEN
#include "reflectionSheenPS"
#endif
#endif
#ifdef LIT_REFRACTION
#if defined(LIT_DYNAMIC_REFRACTION)
#include "refractionDynamicPS"
#elif defined(LIT_REFLECTIONS)
#include "refractionCubePS"
#endif
#endif
#ifdef LIT_SHEEN
#include "lightSheenPS"
#endif
uniform material_ambient: vec3f;
#ifdef LIT_SPECULAR
#ifdef LIT_LIGHTING
#ifdef LIT_GGX_SPECULAR
#include "lightSpecularAnisoGGXPS"
#else
#include "lightSpecularBlinnPS"
#endif
#endif
#endif
#include "combinePS"
#ifdef LIT_LIGHTMAP
#include "lightmapAddPS"
#endif
#ifdef LIT_ADD_AMBIENT
#include "ambientPS"
#endif
#ifdef LIT_MSDF
#include "msdfPS"
#endif
#ifdef LIT_NEEDS_NORMAL
#include "viewDirPS"
#ifdef LIT_SPECULAR
#ifdef LIT_GGX_SPECULAR
#include "reflDirAnisoPS"
#else
#include "reflDirPS"
#endif
#endif
#endif
#include "lightingPS"
`,litForwardPreCodePS:`
#include "basePS"
#include "sphericalPS"
#include "decodePS"
#include "gammaPS"
#include "tonemappingPS"
#include "fogPS"
#if LIT_NONE_SLICE_MODE == SLICED
#include "baseNineSlicedPS"
#elif LIT_NONE_SLICE_MODE == TILED
#include "baseNineSlicedTiledPS"
#endif
#ifdef LIT_TBN
#include "TBNPS"
#ifdef LIT_TWO_SIDED_LIGHTING
#include "twoSidedLightingPS"
#endif
#endif
`,litMainPS:`
#include "varyingsPS"
#include "litUserDeclarationPS"
#include "frontendDeclPS"
#if defined(PICK_PASS) || defined(PREPASS_PASS)
#include "frontendCodePS"
#include "litUserCodePS"
#include "litOtherMainPS"
#elif defined(SHADOW_PASS)
#include "frontendCodePS"
#include "litUserCodePS"
#include "litShadowMainPS"
#else
#include "litForwardDeclarationPS"
#include "litForwardPreCodePS"
#include "frontendCodePS"
#include "litForwardPostCodePS"
#include "litForwardBackendPS"
#include "litUserCodePS"
#include "litForwardMainPS"
#endif
`,litMainVS:`
#include "varyingsVS"
#include "litUserDeclarationVS"
#ifdef VERTEX_COLOR
attribute vertex_color: vec4f;
#endif
#ifdef NINESLICED
varying vMask: vec2f;
varying vTiledUv: vec2f;
var<private> dMaskGlobal: vec2f;
var<private> dTiledUvGlobal: vec2f;
uniform innerOffset: vec4f;
uniform outerScale: vec2f;
uniform atlasRect: vec4f;
#endif
var<private> dPositionW: vec3f;
var<private> dModelMatrix: mat4x4f;
#include "transformCoreVS"
#ifdef UV0
attribute vertex_texCoord0: vec2f;
#include "uv0VS"
#endif
#ifdef UV1
attribute vertex_texCoord1: vec2f;
#include "uv1VS"
#endif
#ifdef LINEAR_DEPTH
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform matrix_view: mat4x4f;
#endif
#endif
#include "transformVS"
#ifdef NORMALS
#include "normalCoreVS"
#include "normalVS"
#endif
#ifdef TANGENTS
attribute vertex_tangent: vec4f;
#endif
#include "uvTransformUniformsPS, UV_TRANSFORMS_COUNT"
#ifdef MSDF
#include "msdfVS"
#endif
#include "litUserCodeVS"
@vertex
fn vertexMain(input : VertexInput) -> VertexOutput {
#include "litUserMainStartVS"
var output : VertexOutput;
output.position = getPosition();
output.vPositionW = getWorldPosition();
#ifdef NORMALS
output.vNormalW = getNormal();
#endif
#ifdef TANGENTS
output.vTangentW = normalize(dNormalMatrix * vertex_tangent.xyz);
output.vBinormalW = cross(output.vNormalW, output.vTangentW) * vertex_tangent.w;
#elif defined(GGX_SPECULAR)
output.vObjectSpaceUpW = normalize(dNormalMatrix * vec3f(0.0, 1.0, 0.0));
#endif
#ifdef UV0
var uv0: vec2f = getUv0();
#ifdef UV0_UNMODIFIED
output.vUv0 = uv0;
#endif
#endif
#ifdef UV1
var uv1: vec2f = getUv1();
#ifdef UV1_UNMODIFIED
output.vUv1 = uv1;
#endif
#endif
#include "uvTransformVS, UV_TRANSFORMS_COUNT"
#ifdef VERTEX_COLOR
output.vVertexColor = vertex_color;
#endif
#ifdef LINEAR_DEPTH
output.vLinearDepth = -(uniform.matrix_view * vec4f(output.vPositionW, 1.0)).z;
#endif
#ifdef MSDF
unpackMsdfParams();
output.outline_color = dOutlineColor;
output.outline_thickness = dOutlineThickness;
output.shadow_color = dShadowColor;
output.shadow_offset = dShadowOffset;
#endif
#ifdef NINESLICED
output.vMask = dMaskGlobal;
output.vTiledUv = dTiledUvGlobal;
#endif
#include "litUserMainEndVS"
return output;
}
`,litOtherMainPS:`
#ifdef PICK_PASS
#include "pickPS"
#endif
#ifdef PREPASS_PASS
#include "floatAsUintPS"
#endif
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
#include "litUserMainStartPS"
var output: FragmentOutput;
evaluateFrontend();
#ifdef PICK_PASS
output.color = getPickOutput();
#endif
#ifdef PREPASS_PASS
output.color = float2vec4(vLinearDepth);
#endif
#include "litUserMainEndPS"
return output;
}
`,litShaderArgsPS:`
var<private> litArgs_albedo: vec3f;
var<private> litArgs_opacity: f32;
var<private> litArgs_emission: vec3f;
var<private> litArgs_worldNormal: vec3f;
var<private> litArgs_ao: f32;
var<private> litArgs_lightmap: vec3f;
var<private> litArgs_lightmapDir: vec3f;
var<private> litArgs_metalness: f32;
var<private> litArgs_specularity: vec3f;
var<private> litArgs_specularityFactor: f32;
var<private> litArgs_gloss: f32;
var<private> litArgs_sheen_gloss: f32;
var<private> litArgs_sheen_specularity: vec3f;
var<private> litArgs_transmission: f32;
var<private> litArgs_thickness: f32;
var<private> litArgs_ior: f32;
var<private> litArgs_dispersion: f32;
var<private> litArgs_iridescence_intensity: f32;
var<private> litArgs_iridescence_thickness: f32;
var<private> litArgs_clearcoat_worldNormal: vec3f;
var<private> litArgs_clearcoat_specularity: f32;
var<private> litArgs_clearcoat_gloss: f32;
`,litShaderCorePS:`
#if LIT_NONE_SLICE_MODE == TILED
var<private> textureBias: f32 = -1000.0;
#else
uniform textureBias: f32;
#endif
#include "litShaderArgsPS"
`,litShadowMainPS:`
#if LIGHT_TYPE != DIRECTIONAL
uniform view_position: vec3f;
uniform light_radius: f32;
#endif
#if SHADOW_TYPE == PCSS_32F
#include "linearizeDepthPS"
#endif
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
#include "litUserMainStartPS"
var output: FragmentOutput;
evaluateFrontend();
#ifdef PERSPECTIVE_DEPTH
var depth: f32 = input.position.z;
#if SHADOW_TYPE == PCSS_32F
#if LIGHT_TYPE != DIRECTIONAL
depth = linearizeDepthWithParams(depth, camera_params);
#endif
#endif
#else
var depth: f32 = min(distance(uniform.view_position, input.vPositionW) / uniform.light_radius, 0.99999);
#define MODIFIED_DEPTH
#endif
#if SHADOW_TYPE == VSM_16F || SHADOW_TYPE == VSM_32F
#if SHADOW_TYPE == VSM_32F
var exponent: f32 = 15.0;
#else
var exponent: f32 = 5.54;
#endif
var depth_vsm = 2.0 * depth - 1.0;
depth_vsm = exp(exponent * depth_vsm);
output.color = vec4f(depth_vsm, depth_vsm * depth_vsm, 1.0, 1.0);
#else
#if SHADOW_TYPE == PCSS_32F
output.color = vec4f(depth, 0.0, 0.0, 1.0);
#else
#ifdef MODIFIED_DEPTH
output.fragDepth = depth;
#endif
output.color = vec4f(1.0);
#endif
#endif
#include "litUserMainEndPS"
return output;
}
`,litUserDeclarationPS:"",litUserDeclarationVS:"",litUserCodePS:"",litUserCodeVS:"",litUserMainStartPS:"",litUserMainStartVS:"",litUserMainEndPS:"",litUserMainEndVS:"",ltcPS:`
fn LTC_Uv(N: vec3f, V: vec3f, roughness: f32) -> vec2f {
const LUT_SIZE: f32 = 64.0;
const LUT_SCALE: f32 = (LUT_SIZE - 1.0) / LUT_SIZE;
const LUT_BIAS: f32 = 0.5 / LUT_SIZE;
let dotNV: f32 = saturate(dot( N, V ));
let uv: vec2f = vec2f( roughness, sqrt( 1.0 - dotNV ) );
return uv * LUT_SCALE + LUT_BIAS;
}
fn LTC_ClippedSphereFormFactor( f: vec3f ) -> f32 {
let l: f32 = length( f );
return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
fn LTC_EdgeVectorFormFactor( v1: vec3f, v2: vec3f ) -> vec3f {
let x: f32 = dot( v1, v2 );
let y: f32 = abs( x );
let a: f32 = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
let b: f32 = 3.4175940 + ( 4.1616724 + y ) * y;
let v: f32 = a / b;
let inv_sqrt_term = inverseSqrt( max( 1.0 - x * x, 1e-7f ) );
let theta_sintheta: f32 = select( (0.5 * inv_sqrt_term - v), v, x > 0.0 );
return cross( v1, v2 ) * theta_sintheta;
}
struct Coords {
coord0: vec3f,
coord1: vec3f,
coord2: vec3f,
coord3: vec3f,
}
fn LTC_EvaluateRect( N: vec3f, V: vec3f, P: vec3f, mInv: mat3x3f, rectCoords: Coords) -> f32 {
let v1: vec3f = rectCoords.coord1 - rectCoords.coord0;
let v2: vec3f = rectCoords.coord3 - rectCoords.coord0;
let lightNormal: vec3f = cross( v1, v2 );
let factor: f32 = sign(-dot( lightNormal, P - rectCoords.coord0 ));
let T1: vec3f = normalize( V - N * dot( V, N ) );
let T2: vec3f = factor * cross( N, T1 );
let mat: mat3x3f = mInv * transpose( mat3x3f( T1, T2, N ) );
var coords: array<vec3f, 4>;
coords[0] = mat * ( rectCoords.coord0 - P );
coords[1] = mat * ( rectCoords.coord1 - P );
coords[2] = mat * ( rectCoords.coord2 - P );
coords[3] = mat * ( rectCoords.coord3 - P );
coords[0] = normalize( coords[0] );
coords[1] = normalize( coords[1] );
coords[2] = normalize( coords[2] );
coords[3] = normalize( coords[3] );
var vectorFormFactor: vec3f = vec3f( 0.0 );
vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[0], coords[1] );
vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[1], coords[2] );
vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[2], coords[3] );
vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[3], coords[0] );
let result: f32 = LTC_ClippedSphereFormFactor( vectorFormFactor );
return result;
}
var<private> dLTCCoords: Coords;
fn getLTCLightCoords(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) -> Coords {
var coords: Coords;
coords.coord0 = lightPos + halfWidth - halfHeight;
coords.coord1 = lightPos - halfWidth - halfHeight;
coords.coord2 = lightPos - halfWidth + halfHeight;
coords.coord3 = lightPos + halfWidth + halfHeight;
return coords;
}
var<private> dSphereRadius: f32;
fn getSphereLightCoords(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) -> Coords {
dSphereRadius = max(length(halfWidth), length(halfHeight));
let f: vec3f = reflect(normalize(lightPos - uniform.view_position), vNormalW);
let w: vec3f = normalize(cross(f, halfHeight));
let h: vec3f = normalize(cross(f, w));
return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);
}
var<private> dLTCUV: vec2f;
#ifdef LIT_CLEARCOAT
var<private> ccLTCUV: vec2f;
#endif
fn getLTCLightUV(gloss: f32, worldNormal: vec3f, viewDir: vec3f) -> vec2f {
let roughness: f32 = max((1.0 - gloss) * (1.0 - gloss), 0.001);
return LTC_Uv( worldNormal, viewDir, roughness );
}
var<private> dLTCSpecFres: vec3f;
#ifdef LIT_CLEARCOAT
var<private> ccLTCSpecFres: vec3f;
#endif
fn getLTCLightSpecFres(uv: vec2f, specularity: vec3f) -> vec3f {
let t2: vec4f = textureSampleLevel(areaLightsLutTex2, areaLightsLutTex2Sampler, uv, 0.0);
return specularity * t2.x + ( vec3f( 1.0 ) - specularity) * t2.y;
}
fn calcLTCLightValues(gloss: f32, worldNormal: vec3f, viewDir: vec3f, specularity: vec3f, clearcoatGloss: f32, clearcoatWorldNormal: vec3f, clearcoatSpecularity: f32) {
dLTCUV = getLTCLightUV(gloss, worldNormal, viewDir);
dLTCSpecFres = getLTCLightSpecFres(dLTCUV, specularity);
#ifdef LIT_CLEARCOAT
ccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir);
ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3f(clearcoatSpecularity));
#endif
}
fn calcRectLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) {
dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);
}
fn calcDiskLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) {
calcRectLightValues(lightPos, halfWidth, halfHeight);
}
fn calcSphereLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) {
dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);
}
fn SolveCubic(Coefficient_in: vec4f) -> vec3f {
let pi: f32 = 3.14159;
var Coefficient = Coefficient_in;
Coefficient = vec4f(Coefficient.xyz / Coefficient.w, Coefficient.w);
let new_yz: vec2f = Coefficient.yz / 3.0;
Coefficient = vec4f(Coefficient.x, new_yz.x, new_yz.y, Coefficient.w);
let A: f32 = Coefficient.w;
let B: f32 = Coefficient.z;
let C: f32 = Coefficient.y;
let D: f32 = Coefficient.x;
let Delta: vec3f = vec3f(
-Coefficient.z * Coefficient.z + Coefficient.y,
-Coefficient.y * Coefficient.z + Coefficient.x,
dot(vec2f(Coefficient.z, -Coefficient.y), Coefficient.xy)
);
let Discriminant: f32 = dot(vec2f(4.0 * Delta.x, -Delta.y), Delta.zy);
var xlc: vec2f;
var xsc: vec2f;
{
let A_a: f32 = 1.0;
let C_a: f32 = Delta.x;
let D_a: f32 = -2.0 * B * Delta.x + Delta.y;
let Theta: f32 = atan2(sqrt(Discriminant), -D_a) / 3.0;
let sqrt_neg_Ca = sqrt(-C_a);
let x_1a: f32 = 2.0 * sqrt_neg_Ca * cos(Theta);
let x_3a: f32 = 2.0 * sqrt_neg_Ca * cos(Theta + (2.0 / 3.0) * pi);
let xl: f32 = select(x_3a, x_1a, (x_1a + x_3a) > 2.0 * B);
xlc = vec2f(xl - B, A);
}
{
let A_d: f32 = D;
let C_d: f32 = Delta.z;
let D_d: f32 = -D * Delta.y + 2.0 * C * Delta.z;
let Theta: f32 = atan2(D * sqrt(Discriminant), -D_d) / 3.0;
let sqrt_neg_Cd = sqrt(-C_d);
let x_1d: f32 = 2.0 * sqrt_neg_Cd * cos(Theta);
let x_3d: f32 = 2.0 * sqrt_neg_Cd * cos(Theta + (2.0 / 3.0) * pi);
let xs: f32 = select(x_3d, x_1d, x_1d + x_3d < 2.0 * C);
xsc = vec2f(-D, xs + C);
}
let E: f32 = xlc.y * xsc.y;
let F: f32 = -xlc.x * xsc.y - xlc.y * xsc.x;
let G: f32 = xlc.x * xsc.x;
let xmc: vec2f = vec2f(C * F - B * G, -B * F + C * E);
var Root: vec3f = vec3f(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);
if (Root.x < Root.y && Root.x < Root.z) {
Root = Root.yxz;
} else if (Root.z < Root.x && Root.z < Root.y) {
Root = Root.xzy;
}
return Root;
}
fn LTC_EvaluateDisk(N: vec3f, V: vec3f, P: vec3f, Minv: mat3x3f, points: Coords) -> f32 {
let T1: vec3f = normalize(V - N * dot(V, N));
let T2: vec3f = cross(N, T1);
let R: mat3x3f = transpose( mat3x3f( T1, T2, N ) );
var L_: array<vec3f, 3>;
L_[0] = R * ( points.coord0 - P );
L_[1] = R * ( points.coord1 - P );
L_[2] = R * ( points.coord2 - P );
let C: vec3f = 0.5 * (L_[0] + L_[2]);
var V1: vec3f = 0.5 * (L_[1] - L_[2]);
var V2: vec3f = 0.5 * (L_[1] - L_[0]);
let C_Minv: vec3f = Minv * C;
let V1_Minv: vec3f = Minv * V1;
let V2_Minv: vec3f = Minv * V2;
var a: f32;
var b: f32;
let d11: f32 = dot(V1_Minv, V1_Minv);
let d22: f32 = dot(V2_Minv, V2_Minv);
let d12: f32 = dot(V1_Minv, V2_Minv);
if (abs(d12) / sqrt(d11 * d22) > 0.0001) {
let tr: f32 = d11 + d22;
let det_inner: f32 = -d12 * d12 + d11 * d22;
let det: f32 = sqrt(det_inner);
let u: f32 = 0.5 * sqrt(tr - 2.0 * det);
let v: f32 = 0.5 * sqrt(tr + 2.0 * det);
let e_max: f32 = (u + v) * (u + v);
let e_min: f32 = (u - v) * (u - v);
var V1_: vec3f;
var V2_: vec3f;
if (d11 > d22) {
V1_ = d12 * V1_Minv + (e_max - d11) * V2_Minv;
V2_ = d12 * V1_Minv + (e_min - d11) * V2_Minv;
} else {
V1_ = d12*V2_Minv + (e_max - d22)*V1_Minv;
V2_ = d12*V2_Minv + (e_min - d22)*V1_Minv;
}
a = 1.0 / e_max;
b = 1.0 / e_min;
V1 = normalize(V1_);
V2 = normalize(V2_);
} else {
a = 1.0 / dot(V1_Minv, V1_Minv);
b = 1.0 / dot(V2_Minv, V2_Minv);
V1 = V1_Minv * sqrt(a);
V2 = V2_Minv * sqrt(b);
}
var V3: vec3f = normalize(cross(V1, V2));
if (dot(C_Minv, V3) < 0.0) {
V3 = V3 * -1.0;
}
let L: f32 = dot(V3, C_Minv);
let x0: f32 = dot(V1, C_Minv) / L;
let y0: f32 = dot(V2, C_Minv) / L;
let E1: f32 = inverseSqrt(a);
let E2: f32 = inverseSqrt(b);
let a_scaled = a * L * L;
let b_scaled = b * L * L;
let c0: f32 = a_scaled * b_scaled;
let c1: f32 = a_scaled * b_scaled * (1.0 + x0 * x0 + y0 * y0) - a_scaled - b_scaled;
let c2: f32 = 1.0 - a_scaled * (1.0 + x0 * x0) - b_scaled * (1.0 + y0 * y0);
let c3: f32 = 1.0;
let roots: vec3f = SolveCubic(vec4f(c0, c1, c2, c3));
let e1: f32 = roots.x;
let e2: f32 = roots.y;
let e3: f32 = roots.z;
var avgDir: vec3f = vec3f(a_scaled * x0 / (a_scaled - e2), b_scaled * y0 / (b_scaled - e2), 1.0);
let rotate: mat3x3f = mat3x3f(V1, V2, V3);
avgDir = rotate * avgDir;
avgDir = normalize(avgDir);
let L1: f32 = sqrt(-e2 / e3);
let L2: f32 = sqrt(-e2 / e1);
let formFactor: f32 = max(0.0, L1 * L2 * inverseSqrt((1.0 + L1 * L1) * (1.0 + L2 * L2)));
const LUT_SIZE_disk: f32 = 64.0;
const LUT_SCALE_disk: f32 = ( LUT_SIZE_disk - 1.0 ) / LUT_SIZE_disk;
const LUT_BIAS_disk: f32 = 0.5 / LUT_SIZE_disk;
var uv: vec2f = vec2f(avgDir.z * 0.5 + 0.5, formFactor);
uv = uv * LUT_SCALE_disk + LUT_BIAS_disk;
let scale: f32 = textureSampleLevel(areaLightsLutTex2, areaLightsLutTex2Sampler, uv, 0.0).w;
return formFactor * scale;
}
fn FixNan(value: f32) -> f32 {
return select(value, 0.0, value != value);
}
fn getRectLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 {
let identityMat = mat3x3f(vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0));
return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, identityMat, dLTCCoords );
}
fn getDiskLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 {
let identityMat = mat3x3f(vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0));
return FixNan(LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, identityMat, dLTCCoords ));
}
fn getSphereLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 {
let falloff: f32 = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius);
return FixNan(getLightDiffuse(worldNormal, viewDir, lightDirNorm) * falloff);
}
fn getLTCLightInvMat(uv: vec2f) -> mat3x3f {
let t1: vec4f = textureSampleLevel(areaLightsLutTex1, areaLightsLutTex1Sampler, uv, 0.0);
return mat3x3f(
vec3f( t1.x, 0.0, t1.y ),
vec3f( 0.0, 1.0, 0.0 ),
vec3f( t1.z, 0.0, t1.w )
);
}
fn calcRectLightSpecular(worldNormal: vec3f, viewDir: vec3f, uv: vec2f) -> f32 {
let mInv: mat3x3f = getLTCLightInvMat(uv);
return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );
}
fn getRectLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 {
return calcRectLightSpecular(worldNormal, viewDir, dLTCUV);
}
fn calcDiskLightSpecular(worldNormal: vec3f, viewDir: vec3f, uv: vec2f) -> f32 {
let mInv: mat3x3f = getLTCLightInvMat(uv);
return LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );
}
fn getDiskLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 {
return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);
}
fn getSphereLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 {
return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);
}
`,metalnessPS:`
#ifdef STD_METALNESS_CONSTANT
uniform material_metalness: f32;
#endif
fn getMetalness() {
var metalness: f32 = 1.0;
#ifdef STD_METALNESS_CONSTANT
metalness = metalness * uniform.material_metalness;
#endif
#ifdef STD_METALNESS_TEXTURE
metalness = metalness * textureSampleBias({STD_METALNESS_TEXTURE_NAME}, {STD_METALNESS_TEXTURE_NAME}Sampler, {STD_METALNESS_TEXTURE_UV}, uniform.textureBias).{STD_METALNESS_TEXTURE_CHANNEL};
#endif
#ifdef STD_METALNESS_VERTEX
metalness = metalness * saturate(vVertexColor.{STD_METALNESS_VERTEX_CHANNEL});
#endif
dMetalness = metalness;
}
`,metalnessModulatePS:`
fn getSpecularModulate(specularity: vec3f, albedo: vec3f, metalness: f32, f0: f32) -> vec3f {
let dielectricF0: vec3f = f0 * specularity;
return mix(dielectricF0, albedo, metalness);
}
fn getAlbedoModulate(albedo: vec3f, metalness: f32) -> vec3f {
return albedo * (1.0 - metalness);
}
`,morphPS:`
varying uv0: vec2f;
var morphTexture: texture_2d_array<f32>;
uniform morphFactor: array<f32, {MORPH_TEXTURE_MAX_COUNT}>;
uniform morphIndex: array<u32, {MORPH_TEXTURE_MAX_COUNT}>;
uniform count: u32;
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var color = vec3f(0, 0, 0);
let textureDims = textureDimensions(morphTexture);
let pixelCoords = vec2i(input.uv0 * vec2f(textureDims));
for (var i: u32 = 0; i < uniform.count; i = i + 1) {
var textureIndex: u32 = uniform.morphIndex[i].element;
var delta = textureLoad(morphTexture, pixelCoords, textureIndex, 0).xyz;
color += uniform.morphFactor[i].element * delta;
}
var output: FragmentOutput;
output.color = vec4f(color, 1.0);
return output;
}
`,morphVS:`
attribute vertex_position: vec2f;
varying uv0: vec2f;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = vec4f(input.vertex_position, 0.5, 1.0);
output.uv0 = input.vertex_position * 0.5 + vec2f(0.5, 0.5);
return output;
}
`,msdfPS:`
var texture_msdfMap: texture_2d<f32>;
var texture_msdfMapSampler: sampler;
fn median(r: f32, g: f32, b: f32) -> f32 {
return max(min(r, g), min(max(r, g), b));
}
fn map(min: f32, max: f32, v: f32) -> f32 {
return (v - min) / (max - min);
}
uniform font_sdfIntensity: f32;
uniform font_pxrange: f32;
uniform font_textureWidth: f32;
#ifndef LIT_MSDF_TEXT_ATTRIBUTE
uniform outline_color: vec4f;
uniform outline_thickness: f32;
uniform shadow_color: vec4f;
uniform shadow_offset: vec2f;
#else
varying outline_color: vec4f;
varying outline_thickness: f32;
varying shadow_color: vec4f;
varying shadow_offset: vec2f;
#endif
fn applyMsdf(color_in: vec4f) -> vec4f {
#ifndef LIT_MSDF_TEXT_ATTRIBUTE
var outline_colorValue = uniform.outline_color;
var outline_thicknessValue = uniform.outline_thickness;
var shadow_colorValue = uniform.shadow_color;
var shadow_offsetValue = uniform.shadow_offset;
#else
var outline_colorValue = outline_color;
var outline_thicknessValue = outline_thickness;
var shadow_colorValue = shadow_color;
var shadow_offsetValue = shadow_offset;
#endif
var color = vec4f(gammaCorrectInputVec3(color_in.rgb), color_in.a);
let tsample: vec3f = textureSample(texture_msdfMap, texture_msdfMapSampler, vUv0).rgb;
let uvShdw: vec2f = vUv0 - shadow_offsetValue;
let ssample: vec3f = textureSample(texture_msdfMap, texture_msdfMapSampler, uvShdw).rgb;
let sigDist: f32 = median(tsample.r, tsample.g, tsample.b);
var sigDistShdw: f32 = median(ssample.r, ssample.g, ssample.b);
let smoothingMax: f32 = 0.2;
let w: vec2f = abs(dpdx(vUv0)) + abs(dpdy(vUv0));
let smoothing: f32 = clamp(w.x * uniform.font_textureWidth / uniform.font_pxrange, 0.0, smoothingMax);
let mapMin: f32 = 0.05;
let mapMax: f32 = clamp(1.0 - uniform.font_sdfIntensity, mapMin, 1.0);
let sigDistInner: f32 = map(mapMin, mapMax, sigDist);
let sigDistOutline: f32 = map(mapMin, mapMax, sigDist + outline_thicknessValue);
sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thicknessValue);
let center: f32 = 0.5;
let inside: f32 = smoothstep(center - smoothing, center + smoothing, sigDistInner);
let outline: f32 = smoothstep(center - smoothing, center + smoothing, sigDistOutline);
let shadow: f32 = smoothstep(center - smoothing, center + smoothing, sigDistShdw);
let tcolor_outline: vec4f = outline * vec4f(outline_colorValue.a * outline_colorValue.rgb, outline_colorValue.a);
var tcolor: vec4f = select(vec4f(0.0), tcolor_outline, outline > inside);
tcolor = mix(tcolor, color, inside);
let scolor_shadow: vec4f = shadow * vec4f(shadow_colorValue.a * shadow_colorValue.rgb, shadow_colorValue.a);
let scolor: vec4f = select(tcolor, scolor_shadow, shadow > outline);
tcolor = mix(scolor, tcolor, outline);
tcolor = vec4f(gammaCorrectOutput(tcolor.rgb), tcolor.a);
return tcolor;
}
`,msdfVS:`
attribute vertex_outlineParameters: vec3f;
attribute vertex_shadowParameters: vec3f;
varying outline_color: vec4f;
varying outline_thickness: f32;
varying shadow_color: vec4f;
varying shadow_offset: vec2f;
var<private> dOutlineColor: vec4f;
var<private> dOutlineThickness: f32;
var<private> dShadowColor: vec4f;
var<private> dShadowOffset: vec2f;
fn unpackMsdfParams() {
let little: vec3f = vertex_outlineParameters % vec3f(256.0);
let big: vec3f = (vertex_outlineParameters - little) / 256.0;
dOutlineColor = vec4f(little.x, big.x, little.y, big.y) / 255.0;
dOutlineThickness = little.z / 255.0 * 0.2;
let little_shadow = vertex_shadowParameters % vec3f(256.0);
let big_shadow = (vertex_shadowParameters - little_shadow) / 256.0;
dShadowColor = vec4f(little_shadow.x, big_shadow.x, little_shadow.y, big_shadow.y) / 255.0;
dShadowOffset = (vec2f(little_shadow.z, big_shadow.z) / 127.0 - 1.0) * 0.005;
}
`,normalVS:`
var<private> dNormalMatrix: mat3x3f;
fn getNormal() -> vec3f {
dNormalMatrix = getNormalMatrix(dModelMatrix);
let localNormal: vec3f = getLocalNormal(vertex_normal);
return normalize(dNormalMatrix * localNormal);
}`,normalCoreVS:`
attribute vertex_normal: vec3f;
uniform matrix_normal: mat3x3f;
#ifdef MORPHING_NORMAL
#ifdef MORPHING_INT
var morphNormalTex: texture_2d<u32>;
var morphNormalTexSampler: sampler;
#else
var morphNormalTex: texture_2d<f32>;
var morphNormalTexSampler: sampler;
#endif
#endif
fn getLocalNormal(vertexNormal: vec3f) -> vec3f {
var localNormal: vec3f = vertexNormal;
#ifdef MORPHING_NORMAL
let morphUV: vec2i = getTextureMorphCoords();
#ifdef MORPHING_INT
let morphNormalInt: vec4u = textureLoad(morphNormalTex, morphUV, 0);
let morphNormalF: vec3f = vec3f(morphNormalInt.xyz) / 65535.0 * 2.0 - 1.0;
localNormal = localNormal + morphNormalF;
#else
let morphNormal: vec3f = textureLoad(morphNormalTex, morphUV, 0).xyz;
localNormal = localNormal + morphNormal;
#endif
#endif
return localNormal;
}
#if defined(SKIN) || defined(BATCH)
fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f {
return mat3x3f(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);
}
#elif defined(INSTANCING)
fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f {
return mat3x3f(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);
}
#else
fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f {
return uniform.matrix_normal;
}
#endif
`,normalMapPS:`
#ifdef STD_NORMAL_TEXTURE
uniform material_bumpiness: f32;
#endif
#ifdef STD_NORMALDETAIL_TEXTURE
uniform material_normalDetailMapBumpiness: f32;
fn blendNormals(inN1: vec3f, inN2: vec3f) -> vec3f {
let n1: vec3f = inN1 + vec3f(0.0, 0.0, 1.0);
let n2: vec3f = inN2 * vec3f(-1.0, -1.0, 1.0);
return n1 * dot(n1, n2) / n1.z - n2;
}
#endif
fn getNormal() {
#ifdef STD_NORMAL_TEXTURE
var normalMap: vec3f = {STD_NORMAL_TEXTURE_DECODE}(textureSampleBias({STD_NORMAL_TEXTURE_NAME}, {STD_NORMAL_TEXTURE_NAME}Sampler, {STD_NORMAL_TEXTURE_UV}, uniform.textureBias));
normalMap = mix(vec3f(0.0, 0.0, 1.0), normalMap, uniform.material_bumpiness);
#ifdef STD_NORMALDETAIL_TEXTURE
var normalDetailMap: vec3f = {STD_NORMALDETAIL_TEXTURE_DECODE}(textureSampleBias({STD_NORMALDETAIL_TEXTURE_NAME}, {STD_NORMALDETAIL_TEXTURE_NAME}Sampler, {STD_NORMALDETAIL_TEXTURE_UV}, uniform.textureBias));
normalDetailMap = mix(vec3f(0.0, 0.0, 1.0), normalDetailMap, uniform.material_normalDetailMapBumpiness);
normalMap = blendNormals(normalMap, normalDetailMap);
#endif
dNormalW = normalize(dTBN * normalMap);
#else
dNormalW = dVertexNormalW;
#endif
}
`,opacityPS:`
uniform material_opacity: f32;
fn getOpacity() {
dAlpha = uniform.material_opacity;
#ifdef STD_OPACITY_TEXTURE
dAlpha = dAlpha * textureSampleBias({STD_OPACITY_TEXTURE_NAME}, {STD_OPACITY_TEXTURE_NAME}Sampler, {STD_OPACITY_TEXTURE_UV}, uniform.textureBias).{STD_OPACITY_TEXTURE_CHANNEL};
#endif
#ifdef STD_OPACITY_VERTEX
dAlpha = dAlpha * clamp(vVertexColor.{STD_OPACITY_VERTEX_CHANNEL}, 0.0, 1.0);
#endif
}
`,opacityDitherPS:`
#if STD_OPACITY_DITHER == BAYER8
#include "bayerPS"
#endif
uniform blueNoiseJitter: vec4f;
#if STD_OPACITY_DITHER == BLUENOISE
var blueNoiseTex32 : texture_2d<f32>;
var blueNoiseTex32Sampler : sampler;
#endif
fn opacityDither(alpha: f32, id: f32) {
#if STD_OPACITY_DITHER == BAYER8
var noise: f32 = bayer8(floor((pcPosition.xy + uniform.blueNoiseJitter.xy + id) % vec2f(8.0))) / 64.0;
#else
#if STD_OPACITY_DITHER == BLUENOISE
var uv = fract(pcPosition.xy / 32.0 + uniform.blueNoiseJitter.xy + id);
var noise: f32 = textureSampleLevel(blueNoiseTex32, blueNoiseTex32Sampler, uv, 0.0).y;
#endif
#if STD_OPACITY_DITHER == IGNNOISE
var magic = vec3f(0.06711056, 0.00583715, 52.9829189);
var noise: f32 = fract(magic.z * fract(dot(pcPosition.xy + uniform.blueNoiseJitter.xy + id, magic.xy)));
#endif
#endif
noise = pow(noise, 2.2);
if (alpha < noise) {
discard;
}
}
`,outputPS:`
`,outputAlphaPS:`
#if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == ADDITIVEALPHA || defined(LIT_ALPHA_TO_COVERAGE)
output.color = vec4f(output.color.rgb, litArgs_opacity);
#elif LIT_BLEND_TYPE == PREMULTIPLIED
output.color = vec4f(output.color.rgb * litArgs_opacity, litArgs_opacity);
#else
output.color = vec4f(output.color.rgb, 1.0);
#endif
`,outputTex2DPS:`
varying vUv0: vec2f;
var source: texture_2d<f32>;
var sourceSampler: sampler;
@fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
output.color = textureSample(source, sourceSampler, input.vUv0);
return output;
}
`,sheenPS:`
uniform material_sheen: vec3f;
fn getSheen() {
var sheenColor = uniform.material_sheen;
#ifdef STD_SHEEN_TEXTURE
sheenColor = sheenColor * {STD_SHEEN_TEXTURE_DECODE}(textureSampleBias({STD_SHEEN_TEXTURE_NAME}, {STD_SHEEN_TEXTURE_NAME}Sampler, {STD_SHEEN_TEXTURE_UV}, uniform.textureBias)).{STD_SHEEN_TEXTURE_CHANNEL};
#endif
#ifdef STD_SHEEN_VERTEX
sheenColor = sheenColor * saturate3(vVertexColor.{STD_SHEEN_VERTEX_CHANNEL});
#endif
sSpecularity = sheenColor;
}
`,sheenGlossPS:`
uniform material_sheenGloss: f32;
fn getSheenGlossiness() {
var sheenGlossiness = uniform.material_sheenGloss;
#ifdef STD_SHEENGLOSS_TEXTURE
sheenGlossiness = sheenGlossiness * textureSampleBias({STD_SHEENGLOSS_TEXTURE_NAME}, {STD_SHEENGLOSS_TEXTURE_NAME}Sampler, {STD_SHEENGLOSS_TEXTURE_UV}, uniform.textureBias).{STD_SHEENGLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_SHEENGLOSS_VERTEX
sheenGlossiness = sheenGlossiness * saturate(vVertexColor.{STD_SHEENGLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_SHEENGLOSS_INVERT
sheenGlossiness = 1.0 - sheenGlossiness;
#endif
sGlossiness = sheenGlossiness + 0.0000001;
}
`,parallaxPS:`
uniform material_heightMapFactor: f32;
fn getParallax() {
var parallaxScale = uniform.material_heightMapFactor;
var height: f32 = textureSampleBias({STD_HEIGHT_TEXTURE_NAME}, {STD_HEIGHT_TEXTURE_NAME}Sampler, {STD_HEIGHT_TEXTURE_UV}, uniform.textureBias).{STD_HEIGHT_TEXTURE_CHANNEL};
height = height * parallaxScale - parallaxScale * 0.5;
var viewDirT: vec3f = dViewDirW * dTBN;
viewDirT.z = viewDirT.z + 0.42;
dUvOffset = height * (viewDirT.xy / viewDirT.z);
}
`,pickPS:`
uniform meshInstanceId: u32;
fn getPickOutput() -> vec4f {
let inv: vec4f = vec4f(1.0 / 255.0);
let shifts: vec4u = vec4u(16u, 8u, 0u, 24u);
let col: vec4u = (vec4u(uniform.meshInstanceId) >> shifts) & vec4u(0xffu);
return vec4f(col) * inv;
}`,reflDirPS:`
fn getReflDir(worldNormal: vec3f, viewDir: vec3f, gloss: f32, tbn: mat3x3f) {
dReflDirW = normalize(-reflect(viewDir, worldNormal));
}
`,reflDirAnisoPS:`
fn getReflDir(worldNormal: vec3f, viewDir: vec3f, gloss: f32, tbn: mat3x3f) {
let roughness: f32 = sqrt(1.0 - min(gloss, 1.0));
let direction: vec2f = dAnisotropyRotation;
let anisotropicT: vec3f = normalize(tbn * vec3f(direction, 0.0));
let anisotropicB: vec3f = normalize(cross(tbn[2], anisotropicT));
let anisotropy: f32 = dAnisotropy;
let anisotropicDirection: vec3f = anisotropicB;
let anisotropicTangent: vec3f = cross(anisotropicDirection, viewDir);
let anisotropicNormal: vec3f = cross(anisotropicTangent, anisotropicDirection);
let bendFactor: f32 = 1.0 - anisotropy * (1.0 - roughness);
let bendFactor4: f32 = bendFactor * bendFactor * bendFactor * bendFactor;
let bentNormal: vec3f = normalize(mix(normalize(anisotropicNormal), normalize(worldNormal), bendFactor4));
dReflDirW = reflect(-viewDir, bentNormal);
}`,reflectionCCPS:`
#ifdef LIT_CLEARCOAT
fn addReflectionCC(reflDir: vec3f, gloss: f32) {
ccReflection = ccReflection + calcReflection(reflDir, gloss);
}
#endif
`,reflectionCubePS:`
var texture_cubeMap: texture_cube<f32>;
var texture_cubeMapSampler: sampler;
uniform material_reflectivity: f32;
fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {
var lookupVec: vec3f = cubeMapProject(reflDir);
lookupVec.x = lookupVec.x * -1.0;
return {reflectionDecode}(textureSample(texture_cubeMap, texture_cubeMapSampler, lookupVec));
}
fn addReflection(reflDir: vec3f, gloss: f32) {
dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);
}
`,reflectionEnvHQPS:`
#ifndef ENV_ATLAS
#define ENV_ATLAS
var texture_envAtlas: texture_2d<f32>;
var texture_envAtlasSampler: sampler;
#endif
var texture_cubeMap: texture_cube<f32>;
var texture_cubeMapSampler: sampler;
uniform material_reflectivity: f32;
fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {
let dir: vec3f = cubeMapProject(reflDir) * vec3f(-1.0, 1.0, 1.0);
let uv: vec2f = toSphericalUv(dir);
let level: f32 = saturate(1.0 - gloss) * 5.0;
let ilevel: f32 = floor(level);
let flevel: f32 = level - ilevel;
let sharp: vec3f = {reflectionCubemapDecode}(textureSample(texture_cubeMap, texture_cubeMapSampler, dir));
let roughA: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel)));
let roughB: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel + 1.0)));
return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));
}
fn addReflection(reflDir: vec3f, gloss: f32) {
dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);
}
`,reflectionEnvPS:`
#ifndef ENV_ATLAS
#define ENV_ATLAS
var texture_envAtlas: texture_2d<f32>;
var texture_envAtlasSampler: sampler;
#endif
uniform material_reflectivity: f32;
fn shinyMipLevel(uv: vec2f) -> f32 {
let dx: vec2f = dpdx(uv);
let dy: vec2f = dpdy(uv);
let uv2: vec2f = vec2f(fract(uv.x + 0.5), uv.y);
let dx2: vec2f = dpdx(uv2);
let dy2: vec2f = dpdy(uv2);
let maxd: f32 = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));
return clamp(0.5 * log2(maxd) - 1.0 + uniform.textureBias, 0.0, 5.0);
}
fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {
let dir: vec3f = cubeMapProject(reflDir) * vec3f(-1.0, 1.0, 1.0);
let uv: vec2f = toSphericalUv(dir);
let level: f32 = saturate(1.0 - gloss) * 5.0;
let ilevel: f32 = floor(level);
let level2: f32 = shinyMipLevel(uv * atlasSize);
let ilevel2: f32 = floor(level2);
var uv0: vec2f;
var uv1: vec2f;
var weight: f32;
if (ilevel == 0.0) {
uv0 = mapShinyUv(uv, ilevel2);
uv1 = mapShinyUv(uv, ilevel2 + 1.0);
weight = level2 - ilevel2;
} else {
uv0 = mapRoughnessUv(uv, ilevel);
uv1 = uv0;
weight = 0.0;
}
let linearA: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, uv0));
let linearB: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, uv1));
let linear0: vec3f = mix(linearA, linearB, weight);
let linear1: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel + 1.0)));
return processEnvironment(mix(linear0, linear1, level - ilevel));
}
fn addReflection(reflDir: vec3f, gloss: f32) {
dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);
}
`,reflectionSpherePS:`
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform matrix_view: mat4x4f;
#endif
var texture_sphereMap: texture_2d<f32>;
var texture_sphereMapSampler: sampler;
uniform material_reflectivity: f32;
fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {
let viewRotationMatrix = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz);
let reflDirV: vec3f = viewRotationMatrix * reflDir;
let m: f32 = 2.0 * sqrt(dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z + 1.0) * (reflDirV.z + 1.0));
let sphereMapUv: vec2f = reflDirV.xy / m + 0.5;
return {reflectionDecode}(textureSample(texture_sphereMap, texture_sphereMapSampler, sphereMapUv));
}
fn addReflection(reflDir: vec3f, gloss: f32) {
dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);
}
`,reflectionSheenPS:`
fn addReflectionSheen(worldNormal: vec3f, viewDir: vec3f, gloss: f32) {
let NoV: f32 = dot(worldNormal, viewDir);
let alphaG: f32 = gloss * gloss;
let a: f32 = select(
-8.48 * alphaG + 14.3 * gloss - 9.95,
-339.2 * alphaG + 161.4 * gloss - 25.9,
gloss < 0.25
);
let b: f32 = select(
1.97 * alphaG - 3.27 * gloss + 0.72,
44.0 * alphaG - 23.7 * gloss + 3.26,
gloss < 0.25
);
let dg_add: f32 = select(
0.1 * ( gloss - 0.25 ),
0.0,
gloss < 0.25
);
let dg: f32 = exp( a * NoV + b ) + dg_add;
sReflection = sReflection + (calcReflection(worldNormal, 0.0) * saturate(dg));
}`,refractionCubePS:`
fn refract2(viewVec: vec3f, normal: vec3f, IOR: f32) -> vec3f {
let vn: f32 = dot(viewVec, normal);
let k: f32 = 1.0 - IOR * IOR * (1.0 - vn * vn);
let refrVec: vec3f = IOR * viewVec - (IOR * vn + sqrt(k)) * normal;
return refrVec;
}
fn addRefraction(
worldNormal: vec3f,
viewDir: vec3f,
thickness: f32,
gloss: f32,
specularity: vec3f,
albedo: vec3f,
transmission: f32,
refractionIndex: f32,
dispersion: f32
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel: vec3f,
iridescenceIntensity: f32
#endif
) {
let tmpRefl: vec4f = dReflection;
let reflectionDir: vec3f = refract2(-viewDir, worldNormal, refractionIndex);
dReflection = vec4f(0.0);
addReflection(reflectionDir, gloss);
dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission);
dReflection = tmpRefl;
}
`,refractionDynamicPS:`
uniform material_invAttenuationDistance: f32;
uniform material_attenuation: vec3f;
fn evalRefractionColor(refractionVector: vec3f, gloss: f32, refractionIndex: f32) -> vec3f {
let pointOfRefraction: vec4f = vec4f(vPositionW + refractionVector, 1.0);
let projectionPoint: vec4f = uniform.matrix_viewProjection * pointOfRefraction;
let uv: vec2f = getGrabScreenPos(projectionPoint);
let iorToRoughness: f32 = (1.0 - gloss) * clamp((1.0 / refractionIndex) * 2.0 - 2.0, 0.0, 1.0);
let refractionLod: f32 = log2(uniform.uScreenSize.x) * iorToRoughness;
let refraction: vec3f = textureSampleLevel(uSceneColorMap, uSceneColorMapSampler, uv, refractionLod).rgb;
return refraction;
}
fn addRefraction(
worldNormal: vec3f,
viewDir: vec3f,
thickness: f32,
gloss: f32,
specularity: vec3f,
albedo: vec3f,
transmission: f32,
refractionIndex: f32,
dispersion: f32,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel: vec3f,
iridescenceIntensity: f32
#endif
) {
var modelScale: vec3f;
modelScale.x = length(uniform.matrix_model[0].xyz);
modelScale.y = length(uniform.matrix_model[1].xyz);
modelScale.z = length(uniform.matrix_model[2].xyz);
let scale: vec3f = thickness * modelScale;
var refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndex)) * scale;
var refraction = evalRefractionColor(refractionVector, gloss, refractionIndex);
#ifdef LIT_DISPERSION
let halfSpread: f32 = (1.0 / refractionIndex - 1.0) * 0.025 * dispersion;
let refractionIndexR: f32 = refractionIndex - halfSpread;
refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexR)) * scale;
refraction.r = evalRefractionColor(refractionVector, gloss, refractionIndexR).r;
let refractionIndexB: f32 = refractionIndex + halfSpread;
refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexB)) * scale;
refraction.b = evalRefractionColor(refractionVector, gloss, refractionIndexB).b;
#endif
var transmittance: vec3f;
if (uniform.material_invAttenuationDistance != 0.0)
{
let attenuation: vec3f = -log(uniform.material_attenuation) * uniform.material_invAttenuationDistance;
transmittance = exp(-attenuation * length(refractionVector));
}
else
{
transmittance = refraction;
}
let fresnel: vec3f = vec3f(1.0) -
getFresnel(
dot(viewDir, worldNormal),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescenceIntensity
#endif
);
dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission);
}
`,reprojectPS:`
varying vUv0: vec2f;
#ifdef CUBEMAP_SOURCE
var sourceCube: texture_cube<f32>;
var sourceCubeSampler : sampler;
#else
var sourceTex: texture_2d<f32>;
var sourceTexSampler : sampler;
#endif
#ifdef USE_SAMPLES_TEX
var samplesTex: texture_2d<f32>;
var samplesTexSampler : sampler;
uniform samplesTexInverseSize: vec2f;
#endif
uniform params: vec3f;
fn targetFace() -> f32 { return uniform.params.x; }
fn targetTotalPixels() -> f32 { return uniform.params.y; }
fn sourceTotalPixels() -> f32 { return uniform.params.z; }
const PI: f32 = 3.141592653589793;
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
#include "decodePS"
#include "encodePS"
fn modifySeams(dir: vec3f, scale: f32) -> vec3f {
let adir = abs(dir);
let M = max(max(adir.x, adir.y), adir.z);
return dir / M * vec3f(
select(scale, 1.0, adir.x == M),
select(scale, 1.0, adir.y == M),
select(scale, 1.0, adir.z == M)
);
}
fn toSpherical(dir: vec3f) -> vec2f {
let nonZeroXZ = any(dir.xz != vec2f(0.0, 0.0));
return vec2f(select(0.0, atan2(dir.x, dir.z), nonZeroXZ), asin(dir.y));
}
fn fromSpherical(uv: vec2f) -> vec3f {
return vec3f(cos(uv.y) * sin(uv.x),
sin(uv.y),
cos(uv.y) * cos(uv.x));
}
fn getDirectionEquirect(uv: vec2f) -> vec3f {
return fromSpherical((vec2f(uv.x, 1.0 - uv.y) * 2.0 - 1.0) * vec2f(PI, PI * 0.5));
}
fn signNotZero(k: f32) -> f32 {
return select(-1.0, 1.0, k >= 0.0);
}
fn signNotZeroVec2(v: vec2f) -> vec2f {
return vec2f(signNotZero(v.x), signNotZero(v.y));
}
fn octDecode(o: vec2f) -> vec3f {
var v = vec3f(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);
if (v.y < 0.0) {
var temp: vec2f = (1.0 - abs(v.zx)) * signNotZeroVec2(v.xz);
v = vec3f(temp.x, v.y, temp.y);
}
return normalize(v);
}
fn getDirectionOctahedral(uv: vec2f) -> vec3f {
return octDecode(vec2f(uv.x, 1.0 - uv.y) * 2.0 - 1.0);
}
fn octEncode(v: vec3f) -> vec2f {
let l1norm = abs(v.x) + abs(v.y) + abs(v.z);
var result = v.xz * (1.0 / l1norm);
if (v.y < 0.0) {
result = (1.0 - abs(result.yx)) * signNotZeroVec2(result.xy);
}
return result;
}
#ifdef CUBEMAP_SOURCE
fn sampleCubemapDir(dir: vec3f) -> vec4f {
return textureSample(sourceCube, sourceCubeSampler, modifySeams(dir, 1.0));
}
fn sampleCubemapSph(sph: vec2f) -> vec4f {
return sampleCubemapDir(fromSpherical(sph));
}
fn sampleCubemapDirLod(dir: vec3f, mipLevel: f32) -> vec4f {
return textureSampleLevel(sourceCube, sourceCubeSampler, modifySeams(dir, 1.0), mipLevel);
}
fn sampleCubemapSphLod(sph: vec2f, mipLevel: f32) -> vec4f {
return sampleCubemapDirLod(fromSpherical(sph), mipLevel);
}
#else
fn sampleEquirectSph(sph: vec2f) -> vec4f {
let uv = sph / vec2f(PI * 2.0, PI) + 0.5;
return textureSample(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y));
}
fn sampleEquirectDir(dir: vec3f) -> vec4f {
return sampleEquirectSph(toSpherical(dir));
}
fn sampleEquirectSphLod(sph: vec2f, mipLevel: f32) -> vec4f {
let uv = sph / vec2f(PI * 2.0, PI) + 0.5;
return textureSampleLevel(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y), mipLevel);
}
fn sampleEquirectDirLod(dir: vec3f, mipLevel: f32) -> vec4f {
return sampleEquirectSphLod(toSpherical(dir), mipLevel);
}
fn sampleOctahedralDir(dir: vec3f) -> vec4f {
let uv = octEncode(dir) * 0.5 + 0.5;
return textureSample(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y));
}
fn sampleOctahedralSph(sph: vec2f) -> vec4f {
return sampleOctahedralDir(fromSpherical(sph));
}
fn sampleOctahedralDirLod(dir: vec3f, mipLevel: f32) -> vec4f {
let uv = octEncode(dir) * 0.5 + 0.5;
return textureSampleLevel(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y), mipLevel);
}
fn sampleOctahedralSphLod(sph: vec2f, mipLevel: f32) -> vec4f {
return sampleOctahedralDirLod(fromSpherical(sph), mipLevel);
}
#endif
fn getDirectionCubemap(uv: vec2f) -> vec3f {
let st = uv * 2.0 - 1.0;
let face = targetFace();
var vec: vec3f;
if (face == 0.0) {
vec = vec3f(1, -st.y, -st.x);
} else if (face == 1.0) {
vec = vec3f(-1, -st.y, st.x);
} else if (face == 2.0) {
vec = vec3f(st.x, 1, st.y);
} else if (face == 3.0) {
vec = vec3f(st.x, -1, -st.y);
} else if (face == 4.0) {
vec = vec3f(st.x, -st.y, 1);
} else {
vec = vec3f(-st.x, -st.y, -1);
}
return normalize(modifySeams(vec, 1.0));
}
fn matrixFromVector(n: vec3f) -> mat3x3f {
let a = 1.0 / (1.0 + n.z);
let b = -n.x * n.y * a;
let b1 = vec3f(1.0 - n.x * n.x * a, b, -n.x);
let b2 = vec3f(b, 1.0 - n.y * n.y * a, -n.y);
return mat3x3f(b1, b2, n);
}
fn matrixFromVectorSlow(n: vec3f) -> mat3x3f {
let up = select(vec3f(0.0, 0.0, select(-1.0, 1.0, n.y > 0.0)), vec3f(0.0, 1.0, 0.0), abs(n.y) > 0.0000001);
let x = normalize(cross(up, n));
let y = cross(n, x);
return mat3x3f(x, y, n);
}
fn reproject(uv: vec2f) -> vec4f {
if ({NUM_SAMPLES} <= 1) {
return {ENCODE_FUNC}({DECODE_FUNC}({SOURCE_FUNC}Dir({TARGET_FUNC}(uv))));
} else {
let t = {TARGET_FUNC}(uv);
let tu = dpdx(t);
let tv = dpdy(t);
var result = vec3f(0.0);
for (var u = 0.0; u < {NUM_SAMPLES_SQRT}; u += 1.0) {
for (var v = 0.0; v < {NUM_SAMPLES_SQRT}; v += 1.0) {
result += {DECODE_FUNC}({SOURCE_FUNC}Dir(normalize(t +
tu * (u / {NUM_SAMPLES_SQRT} - 0.5) +
tv * (v / {NUM_SAMPLES_SQRT} - 0.5))));
}
}
return {ENCODE_FUNC}(result / ({NUM_SAMPLES_SQRT} * {NUM_SAMPLES_SQRT}));
}
}
const unpackFloat: vec4f = vec4f(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);
#ifdef USE_SAMPLES_TEX
fn unpackSample(i: i32, L: ptr<function, vec3f>, mipLevel: ptr<function, f32>) {
var u = (f32(i * 4) + 0.5) * uniform.samplesTexInverseSize.x;
var v = (floor(u) + 0.5) * uniform.samplesTexInverseSize.y;
var raw: vec4f;
raw.x = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x;
raw.y = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x;
raw.z = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x;
raw.w = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat);
*L = raw.xyz * 2.0 - 1.0;
*mipLevel = raw.w * 8.0;
}
fn prefilterSamples(uv: vec2f) -> vec4f {
let vecSpace = matrixFromVectorSlow({TARGET_FUNC}(uv));
var L: vec3f;
var mipLevel: f32;
var result = vec3f(0.0);
var totalWeight = 0.0;
for (var i = 0; i < {NUM_SAMPLES}; i += 1) {
unpackSample(i, &L, &mipLevel);
result += {DECODE_FUNC}({SOURCE_FUNC}DirLod(vecSpace * L, mipLevel)) * L.z;
totalWeight += L.z;
}
return {ENCODE_FUNC}(result / totalWeight);
}
fn prefilterSamplesUnweighted(uv: vec2f) -> vec4f {
let vecSpace = matrixFromVectorSlow({TARGET_FUNC}(uv));
var L: vec3f;
var mipLevel: f32;
var result = vec3f(0.0);
for (var i = 0; i < {NUM_SAMPLES}; i += 1) {
unpackSample(i, &L, &mipLevel);
result += {DECODE_FUNC}({SOURCE_FUNC}DirLod(vecSpace * L, mipLevel));
}
return {ENCODE_FUNC}(result / f32({NUM_SAMPLES}));
}
#endif
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
output.color = {PROCESS_FUNC}(input.vUv0);
return output;
}
`,reprojectVS:`
attribute vertex_position: vec2f;
uniform uvMod: vec4f;
varying vUv0: vec2f;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = vec4f(input.vertex_position, 0.5, 1.0);
output.vUv0 = getImageEffectUV((input.vertex_position * 0.5 + vec2f(0.5, 0.5)) * uniform.uvMod.xy + uniform.uvMod.zw);
return output;
}
`,screenDepthPS:`
var uSceneDepthMap: texture_2d<f32>;
var uSceneDepthMapSampler: sampler;
#ifndef SCREENSIZE
#define SCREENSIZE
uniform uScreenSize: vec4f;
#endif
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform matrix_view: mat4x4f;
#endif
#ifndef LINEARIZE_DEPTH
#define LINEARIZE_DEPTH
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform camera_params: vec4f;
#endif
fn linearizeDepth(z: f32) -> f32 {
if (uniform.camera_params.w == 0.0) {
return (uniform.camera_params.z * uniform.camera_params.y) / (uniform.camera_params.y + z * (uniform.camera_params.z - uniform.camera_params.y));
} else {
return uniform.camera_params.z + z * (uniform.camera_params.y - uniform.camera_params.z);
}
}
#endif
fn delinearizeDepth(linearDepth: f32) -> f32 {
if (uniform.camera_params.w == 0.0) {
return (uniform.camera_params.y * (uniform.camera_params.z - linearDepth)) / (linearDepth * (uniform.camera_params.z - uniform.camera_params.y));
} else {
return (linearDepth - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
}
}
fn getLinearScreenDepth(uv: vec2f) -> f32 {
#ifdef SCENE_DEPTHMAP_LINEAR
#ifdef SCENE_DEPTHMAP_FLOAT
return textureSample(uSceneDepthMap, uSceneDepthMapSampler, uv).r;
#else
let textureSize = textureDimensions(uSceneDepthMap, 0);
let texel: vec2i = vec2i(uv * vec2f(textureSize));
let data: vec4f = textureLoad(uSceneDepthMap, texel, 0);
let data_u32: vec4u = vec4u(data * 255.0);
let intBits: u32 = (data_u32.r << 24u) | (data_u32.g << 16u) | (data_u32.b << 8u) | data_u32.a;
return bitcast<f32>(intBits);
#endif
#else
return linearizeDepth(textureSample(uSceneDepthMap, uSceneDepthMapSampler, uv).r);
#endif
}
#ifndef VERTEXSHADER
fn getLinearScreenDepthFrag() -> f32 {
let uv: vec2f = pcPosition.xy * uniform.uScreenSize.zw;
return getLinearScreenDepth(uv);
}
#endif
fn getLinearDepth(pos: vec3f) -> f32 {
return -(uniform.matrix_view * vec4f(pos, 1.0)).z;
}
`,shadowCascadesPS:`
fn getShadowCascadeIndex(shadowCascadeDistances: vec4f, shadowCascadeCount: i32) -> i32 {
let depth: f32 = 1.0 / pcPosition.w;
let comparisons: vec4f = step(shadowCascadeDistances, vec4f(depth));
let cascadeIndex: i32 = i32(dot(comparisons, vec4f(1.0)));
return min(cascadeIndex, shadowCascadeCount - 1);
}
fn ditherShadowCascadeIndex(cascadeIndex_in: i32, shadowCascadeDistances: vec4f, shadowCascadeCount: i32, blendFactor: f32) -> i32 {
var cascadeIndex: i32 = cascadeIndex_in;
if (cascadeIndex < shadowCascadeCount - 1) {
let currentRangeEnd: f32 = shadowCascadeDistances[cascadeIndex];
let transitionStart: f32 = blendFactor * currentRangeEnd;
let depth: f32 = 1.0 / pcPosition.w;
if (depth > transitionStart) {
let transitionFactor: f32 = smoothstep(transitionStart, currentRangeEnd, depth);
let dither: f32 = fract(sin(dot(pcPosition.xy, vec2f(12.9898, 78.233))) * 43758.5453);
if (dither < transitionFactor) {
cascadeIndex = cascadeIndex + 1;
}
}
}
return cascadeIndex;
}
fn fadeShadow(shadowCoord_in: vec3f, shadowCascadeDistances: vec4f) -> vec3f {
var shadowCoord: vec3f = shadowCoord_in;
let depth: f32 = 1.0 / pcPosition.w;
if (depth > shadowCascadeDistances.w) {
shadowCoord.z = -9999999.0;
}
return shadowCoord;
}
`,shadowEVSMPS:`
fn linstep(a: f32, b: f32, v: f32) -> f32 {
return clamp((v - a) / (b - a), 0.0, 1.0);
}
fn reduceLightBleeding(pMax: f32, amount: f32) -> f32 {
return linstep(amount, 1.0, pMax);
}
fn chebyshevUpperBound(moments: vec2f, mean: f32, minVariance: f32, lightBleedingReduction: f32) -> f32 {
var variance: f32 = moments.y - (moments.x * moments.x);
variance = max(variance, minVariance);
let d: f32 = mean - moments.x;
var pMax: f32 = variance / (variance + (d * d));
pMax = reduceLightBleeding(pMax, lightBleedingReduction);
return select(pMax, 1.0, mean <= moments.x);
}
fn calculateEVSM(moments_in: vec3f, Z_in: f32, vsmBias: f32, exponent: f32) -> f32 {
let Z: f32 = 2.0 * Z_in - 1.0;
let warpedDepth: f32 = exp(exponent * Z);
let moments: vec2f = moments_in.xy + vec2f(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments_in.z);
let VSMBias: f32 = vsmBias;
let depthScale: f32 = VSMBias * exponent * warpedDepth;
let minVariance1: f32 = depthScale * depthScale;
return chebyshevUpperBound(moments, warpedDepth, minVariance1, 0.1);
}
fn VSM16(tex: texture_2d<f32>, texSampler: sampler, texCoords: vec2f, resolution: f32, Z: f32, vsmBias: f32, exponent: f32) -> f32 {
let moments: vec3f = textureSampleLevel(tex, texSampler, texCoords, 0.0).xyz;
return calculateEVSM(moments, Z, vsmBias, exponent);
}
fn getShadowVSM16(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32) -> f32 {
return VSM16(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);
}
fn getShadowSpotVSM16(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32, lightDir: vec3f) -> f32 {
let Z: f32 = length(lightDir) * shadowParams.w + shadowParams.z;
return VSM16(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent);
}
fn VSM32(tex: texture_2d<f32>, texSampler: sampler, texCoords_in: vec2f, resolution: f32, Z: f32, vsmBias: f32, exponent: f32) -> f32 {
#ifdef CAPS_TEXTURE_FLOAT_FILTERABLE
var moments: vec3f = textureSampleLevel(tex, texSampler, texCoords_in, 0.0).xyz;
#else
var pixelSize : f32 = 1.0 / resolution;
let texCoords: vec2f = texCoords_in - vec2f(pixelSize);
let s00: vec3f = textureSampleLevel(tex, texSampler, texCoords, 0.0).xyz;
let s10: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(pixelSize, 0.0), 0.0).xyz;
let s01: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(0.0, pixelSize), 0.0).xyz;
let s11: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(pixelSize), 0.0).xyz;
let fr: vec2f = fract(texCoords * resolution);
let h0: vec3f = mix(s00, s10, fr.x);
let h1: vec3f = mix(s01, s11, fr.x);
var moments: vec3f = mix(h0, h1, fr.y);
#endif
return calculateEVSM(moments, Z, vsmBias, exponent);
}
fn getShadowVSM32(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32) -> f32 {
return VSM32(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);
}
fn getShadowSpotVSM32(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32, lightDir: vec3f) -> f32 {
let Z: f32 = length(lightDir) * shadowParams.w + shadowParams.z;
return VSM32(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent);
}
`,shadowPCF1PS:`
fn getShadowPCF1x1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z);
}
fn getShadowSpotPCF1x1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z);
}
`,shadowPCF3PS:`
fn _getShadowPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec3f) -> f32 {
let z: f32 = shadowCoord.z;
let uv: vec2f = shadowCoord.xy * shadowParams.x;
let shadowMapSizeInv: f32 = 1.0 / shadowParams.x;
let base_uv_temp: vec2f = floor(uv + 0.5);
let s: f32 = (uv.x + 0.5 - base_uv_temp.x);
let t: f32 = (uv.y + 0.5 - base_uv_temp.y);
let base_uv: vec2f = (base_uv_temp - vec2f(0.5)) * shadowMapSizeInv;
var sum: f32 = 0.0;
let uw0: f32 = (3.0 - 2.0 * s);
let uw1: f32 = (1.0 + 2.0 * s);
let u0_offset: f32 = (2.0 - s) / uw0 - 1.0;
let u1_offset: f32 = s / uw1 + 1.0;
let vw0: f32 = (3.0 - 2.0 * t);
let vw1: f32 = (1.0 + 2.0 * t);
let v0_offset: f32 = (2.0 - t) / vw0 - 1.0;
let v1_offset: f32 = t / vw1 + 1.0;
let u0: f32 = u0_offset * shadowMapSizeInv + base_uv.x;
let v0: f32 = v0_offset * shadowMapSizeInv + base_uv.y;
let u1: f32 = u1_offset * shadowMapSizeInv + base_uv.x;
let v1: f32 = v1_offset * shadowMapSizeInv + base_uv.y;
sum = sum + uw0 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v0), z);
sum = sum + uw1 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v0), z);
sum = sum + uw0 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v1), z);
sum = sum + uw1 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v1), z);
sum = sum * (1.0 / 16.0);
return sum;
}
fn getShadowPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return _getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);
}
fn getShadowSpotPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return _getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);
}
`,shadowPCF5PS:`
fn _getShadowPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec3f) -> f32 {
let z: f32 = shadowCoord.z;
let uv: vec2f = shadowCoord.xy * shadowParams.x;
let shadowMapSizeInv: f32 = 1.0 / shadowParams.x;
let base_uv_temp: vec2f = floor(uv + 0.5);
let s: f32 = (uv.x + 0.5 - base_uv_temp.x);
let t: f32 = (uv.y + 0.5 - base_uv_temp.y);
let base_uv: vec2f = (base_uv_temp - vec2f(0.5)) * shadowMapSizeInv;
let uw0: f32 = (4.0 - 3.0 * s);
let uw1: f32 = 7.0;
let uw2: f32 = (1.0 + 3.0 * s);
let u0_offset: f32 = (3.0 - 2.0 * s) / uw0 - 2.0;
let u1_offset: f32 = (3.0 + s) / uw1;
let u2_offset: f32 = s / uw2 + 2.0;
let vw0: f32 = (4.0 - 3.0 * t);
let vw1: f32 = 7.0;
let vw2: f32 = (1.0 + 3.0 * t);
let v0_offset: f32 = (3.0 - 2.0 * t) / vw0 - 2.0;
let v1_offset: f32 = (3.0 + t) / vw1;
let v2_offset: f32 = t / vw2 + 2.0;
var sum: f32 = 0.0;
let u0: f32 = u0_offset * shadowMapSizeInv + base_uv.x;
let v0: f32 = v0_offset * shadowMapSizeInv + base_uv.y;
let u1: f32 = u1_offset * shadowMapSizeInv + base_uv.x;
let v1: f32 = v1_offset * shadowMapSizeInv + base_uv.y;
let u2: f32 = u2_offset * shadowMapSizeInv + base_uv.x;
let v2: f32 = v2_offset * shadowMapSizeInv + base_uv.y;
sum = sum + uw0 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v0), z);
sum = sum + uw1 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v0), z);
sum = sum + uw2 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v0), z);
sum = sum + uw0 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v1), z);
sum = sum + uw1 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v1), z);
sum = sum + uw2 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v1), z);
sum = sum + uw0 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v2), z);
sum = sum + uw1 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v2), z);
sum = sum + uw2 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v2), z);
sum = sum * (1.0 / 144.0);
sum = saturate(sum);
return sum;
}
fn getShadowPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return _getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);
}
fn getShadowSpotPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return _getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);
}
`,shadowSoftPS:`
fn fractSinRand(uv: vec2f) -> f32 {
let PI: f32 = 3.141592653589793;
let a: f32 = 12.9898; let b: f32 = 78.233; let c: f32 = 43758.5453;
let dt: f32 = dot(uv.xy, vec2f(a, b));
let sn: f32 = dt % PI;
return fract(sin(sn) * c);
}
struct VogelDiskData {
invNumSamples: f32,
initialAngle: f32,
currentPointId: f32,
}
fn prepareDiskConstants(data: ptr<function, VogelDiskData>, sampleCount: i32, randomSeed: f32) {
let pi2: f32 = 6.28318530718;
data.invNumSamples = 1.0 / f32(sampleCount);
data.initialAngle = randomSeed * pi2;
data.currentPointId = 0.0;
}
fn generateDiskSample(data: ptr<function, VogelDiskData>) -> vec2f {
let GOLDEN_ANGLE: f32 = 2.399963;
let r: f32 = sqrt((data.currentPointId + 0.5) * data.invNumSamples);
let theta: f32 = data.currentPointId * GOLDEN_ANGLE + data.initialAngle;
let offset: vec2f = vec2f(cos(theta), sin(theta)) * pow(r, 1.33);
data.currentPointId = data.currentPointId + 1.0;
return offset;
}
fn PCSSFindBlocker(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, avgBlockerDepth: ptr<function, f32>, numBlockers: ptr<function, i32>,
shadowCoords: vec2f, z: f32, shadowBlockerSamples: i32, penumbraSize: f32, invShadowMapSize: f32, randomSeed: f32) {
var diskData: VogelDiskData;
prepareDiskConstants(&diskData, shadowBlockerSamples, randomSeed);
let searchWidth: f32 = penumbraSize * invShadowMapSize;
var blockerSum: f32 = 0.0;
var numBlockers_local: i32 = 0;
for( var i: i32 = 0; i < shadowBlockerSamples; i = i + 1 ) {
let diskUV: vec2f = generateDiskSample(&diskData);
let sampleUV: vec2f = shadowCoords + diskUV * searchWidth;
let shadowMapDepth: f32 = textureSampleLevel(shadowMap, shadowMapSampler, sampleUV, 0.0).r;
if ( shadowMapDepth < z ) {
blockerSum = blockerSum + shadowMapDepth;
numBlockers_local = numBlockers_local + 1;
}
}
*avgBlockerDepth = blockerSum / f32(numBlockers_local);
*numBlockers = numBlockers_local;
}
fn PCSSFilter(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, uv: vec2f, receiverDepth: f32, shadowSamples: i32, filterRadius: f32, randomSeed: f32) -> f32 {
var diskData: VogelDiskData;
prepareDiskConstants(&diskData, shadowSamples, randomSeed);
var sum: f32 = 0.0;
for (var i: i32 = 0; i < shadowSamples; i = i + 1) {
let offsetUV: vec2f = generateDiskSample(&diskData) * filterRadius;
let depth: f32 = textureSampleLevel(shadowMap, shadowMapSampler, uv + offsetUV, 0.0).r;
sum = sum + step(receiverDepth, depth);
}
return sum / f32(shadowSamples);
}
fn getPenumbra(dblocker: f32, dreceiver: f32, penumbraSize: f32, penumbraFalloff: f32) -> f32 {
let dist: f32 = dreceiver - dblocker;
let penumbra: f32 = 1.0 - pow(1.0 - dist, penumbraFalloff);
return penumbra * penumbraSize;
}
fn PCSSDirectional(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoords: vec3f, cameraParams: vec4f, softShadowParams: vec4f) -> f32 {
let receiverDepth: f32 = shadowCoords.z;
let randomSeed: f32 = fractSinRand(pcPosition.xy);
let shadowSamples: i32 = i32(softShadowParams.x);
let shadowBlockerSamples: i32 = i32(softShadowParams.y);
let penumbraSize: f32 = softShadowParams.z;
let penumbraFalloff: f32 = softShadowParams.w;
let shadowMapSize: i32 = i32(textureDimensions(shadowMap, 0).x);
var invShadowMapSize: f32 = 1.0 / f32(shadowMapSize);
invShadowMapSize = invShadowMapSize * (f32(shadowMapSize) / 2048.0);
var penumbra: f32;
if (shadowBlockerSamples > 0) {
var avgBlockerDepth: f32 = 0.0;
var numBlockers: i32 = 0;
PCSSFindBlocker(shadowMap, shadowMapSampler, &avgBlockerDepth, &numBlockers, shadowCoords.xy, receiverDepth, shadowBlockerSamples, penumbraSize, invShadowMapSize, randomSeed);
if (numBlockers < 1) {
return 1.0;
}
penumbra = getPenumbra(avgBlockerDepth, shadowCoords.z, penumbraSize, penumbraFalloff);
} else {
penumbra = penumbraSize;
}
let filterRadius: f32 = penumbra * invShadowMapSize;
return PCSSFilter(shadowMap, shadowMapSampler, shadowCoords.xy, receiverDepth, shadowSamples, filterRadius, randomSeed);
}
fn getShadowPCSS(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, cameraParams: vec4f, softShadowParams: vec4f, lightDir: vec3f) -> f32 {
return PCSSDirectional(shadowMap, shadowMapSampler, shadowCoord, cameraParams, softShadowParams);
}
`,skinBatchVS:`
attribute vertex_boneIndices: f32;
var texture_poseMap: texture_2d<f32>;
fn getBoneMatrix(indexFloat: f32) -> mat4x4f {
let width = i32(textureDimensions(texture_poseMap).x);
let index: i32 = i32(indexFloat + 0.5) * 3;
let iy: i32 = index / width;
let ix: i32 = index % width;
let v1: vec4f = textureLoad(texture_poseMap, vec2i(ix + 0, iy), 0);
let v2: vec4f = textureLoad(texture_poseMap, vec2i(ix + 1, iy), 0);
let v3: vec4f = textureLoad(texture_poseMap, vec2i(ix + 2, iy), 0);
return mat4x4f(
v1.x, v2.x, v3.x, 0,
v1.y, v2.y, v3.y, 0,
v1.z, v2.z, v3.z, 0,
v1.w, v2.w, v3.w, 1.0
);
}
`,skinVS:`
attribute vertex_boneWeights: vec4f;
attribute vertex_boneIndices: vec4f;
var texture_poseMap: texture_2d<f32>;
struct BoneMatrix {
v1: vec4f,
v2: vec4f,
v3: vec4f,
}
fn getBoneMatrix(width: i32, index: i32) -> BoneMatrix {
let v = index / width;
let u = index % width;
var result: BoneMatrix;
result.v1 = textureLoad(texture_poseMap, vec2i(u + 0, v), 0);
result.v2 = textureLoad(texture_poseMap, vec2i(u + 1, v), 0);
result.v3 = textureLoad(texture_poseMap, vec2i(u + 2, v), 0);
return result;
}
fn getSkinMatrix(indicesFloat: vec4f, weights: vec4f) -> mat4x4f {
let width = i32(textureDimensions(texture_poseMap).x);
var indices = vec4i(indicesFloat + 0.5) * 3;
let boneA = getBoneMatrix(width, indices.x);
let boneB = getBoneMatrix(width, indices.y);
let boneC = getBoneMatrix(width, indices.z);
let boneD = getBoneMatrix(width, indices.w);
let v1 = boneA.v1 * weights.x + boneB.v1 * weights.y + boneC.v1 * weights.z + boneD.v1 * weights.w;
let v2 = boneA.v2 * weights.x + boneB.v2 * weights.y + boneC.v2 * weights.z + boneD.v2 * weights.w;
let v3 = boneA.v3 * weights.x + boneB.v3 * weights.y + boneC.v3 * weights.z + boneD.v3 * weights.w;
let one = dot(weights, vec4f(1.0, 1.0, 1.0, 1.0));
return mat4x4f(
v1.x, v2.x, v3.x, 0,
v1.y, v2.y, v3.y, 0,
v1.z, v2.z, v3.z, 0,
v1.w, v2.w, v3.w, one
);
}
`,skyboxPS:`
#define LIT_SKYBOX_INTENSITY
#include "envProcPS"
#include "gammaPS"
#include "tonemappingPS"
#ifdef PREPASS_PASS
varying vLinearDepth: f32;
#include "floatAsUintPS"
#endif
varying vViewDir : vec3f;
uniform skyboxHighlightMultiplier : f32;
#ifdef SKY_CUBEMAP
var texture_cubeMap : texture_cube<f32>;
var texture_cubeMap_sampler : sampler;
#ifdef SKYMESH
varying vWorldPos : vec3f;
uniform cubeMapRotationMatrix : mat3x3f;
uniform projectedSkydomeCenter : vec3f;
#endif
#else
#include "sphericalPS"
#include "envAtlasPS"
var texture_envAtlas : texture_2d<f32>;
var texture_envAtlas_sampler : sampler;
uniform mipLevel : f32;
#endif
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
#ifdef PREPASS_PASS
output.color = float2vec4(vLinearDepth);
#else
var linear : vec3f;
var dir : vec3f;
#ifdef SKY_CUBEMAP
#ifdef SKYMESH
var envDir : vec3f = normalize(input.vWorldPos - uniform.projectedSkydomeCenter);
dir = envDir * uniform.cubeMapRotationMatrix;
#else
dir = input.vViewDir;
#endif
dir.x *= -1.0;
linear = {SKYBOX_DECODE_FNC}(textureSample(texture_cubeMap, texture_cubeMap_sampler, dir));
#else
dir = input.vViewDir * vec3f(-1.0, 1.0, 1.0);
let uv : vec2f = toSphericalUv(normalize(dir));
linear = {SKYBOX_DECODE_FNC}(textureSample(texture_envAtlas, texture_envAtlas_sampler, mapRoughnessUv(uv, uniform.mipLevel)));
#endif
if (any(linear >= vec3f(64.0))) {
linear *= uniform.skyboxHighlightMultiplier;
}
output.color = vec4f(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);
#endif
return output;
}
`,skyboxVS:`
attribute aPosition : vec4f;
uniform matrix_view : mat4x4f;
uniform matrix_projectionSkybox : mat4x4f;
uniform cubeMapRotationMatrix : mat3x3f;
varying vViewDir : vec3f;
#ifdef PREPASS_PASS
varying vLinearDepth: f32;
#endif
#ifdef SKYMESH
uniform matrix_model : mat4x4f;
varying vWorldPos : vec3f;
#endif
@vertex
fn vertexMain(input : VertexInput) -> VertexOutput {
var output : VertexOutput;
var view : mat4x4f = uniform.matrix_view;
#ifdef SKYMESH
var worldPos : vec4f = uniform.matrix_model * input.aPosition;
output.vWorldPos = worldPos.xyz;
output.position = uniform.matrix_projectionSkybox * (view * worldPos);
#ifdef PREPASS_PASS
output.vLinearDepth = -(uniform.matrix_view * vec4f(worldPos.xyz, 1.0)).z;
#endif
#else
view[3][0] = 0.0;
view[3][1] = 0.0;
view[3][2] = 0.0;
output.position = uniform.matrix_projectionSkybox * (view * input.aPosition);
output.vViewDir = input.aPosition.xyz * uniform.cubeMapRotationMatrix;
#ifdef PREPASS_PASS
output.vLinearDepth = -pcPosition.w;
#endif
#endif
output.position.z = output.position.w - 1.0e-7;
return output;
}
`,specularPS:`
#ifdef STD_SPECULAR_CONSTANT
uniform material_specular: vec3f;
#endif
fn getSpecularity() {
var specularColor = vec3f(1.0, 1.0, 1.0);
#ifdef STD_SPECULAR_CONSTANT
specularColor = specularColor * uniform.material_specular;
#endif
#ifdef STD_SPECULAR_TEXTURE
specularColor = specularColor * {STD_SPECULAR_TEXTURE_DECODE}(textureSampleBias({STD_SPECULAR_TEXTURE_NAME}, {STD_SPECULAR_TEXTURE_NAME}Sampler, {STD_SPECULAR_TEXTURE_UV}, uniform.textureBias)).{STD_SPECULAR_TEXTURE_CHANNEL};
#endif
#ifdef STD_SPECULAR_VERTEX
specularColor = specularColor * saturate3(vVertexColor.{STD_SPECULAR_VERTEX_CHANNEL});
#endif
dSpecularity = specularColor;
}
`,sphericalPS:`
fn toSpherical(dir: vec3f) -> vec2f {
let angle_xz = select(0.0, atan2(dir.x, dir.z), any(dir.xz != vec2f(0.0)));
return vec2f(angle_xz, asin(dir.y));
}
fn toSphericalUv(dir : vec3f) -> vec2f {
const PI : f32 = 3.141592653589793;
let uv : vec2f = toSpherical(dir) / vec2f(PI * 2.0, PI) + vec2f(0.5, 0.5);
return vec2f(uv.x, 1.0 - uv.y);
}
`,specularityFactorPS:`
#ifdef STD_SPECULARITYFACTOR_CONSTANT
uniform material_specularityFactor: f32;
#endif
fn getSpecularityFactor() {
var specularityFactor = 1.0;
#ifdef STD_SPECULARITYFACTOR_CONSTANT
specularityFactor = specularityFactor * uniform.material_specularityFactor;
#endif
#ifdef STD_SPECULARITYFACTOR_TEXTURE
specularityFactor = specularityFactor * textureSampleBias({STD_SPECULARITYFACTOR_TEXTURE_NAME}, {STD_SPECULARITYFACTOR_TEXTURE_NAME}Sampler, {STD_SPECULARITYFACTOR_TEXTURE_UV}, uniform.textureBias).{STD_SPECULARITYFACTOR_TEXTURE_CHANNEL};
#endif
#ifdef STD_SPECULARITYFACTOR_VERTEX
specularityFactor = specularityFactor * saturate(vVertexColor.{STD_SPECULARITYFACTOR_VERTEX_CHANNEL});
#endif
dSpecularityFactor = specularityFactor;
}
`,spotPS:`
fn getSpotEffect(lightSpotDir: vec3f, lightInnerConeAngle: f32, lightOuterConeAngle: f32, lightDirNorm: vec3f) -> f32 {
let cosAngle: f32 = dot(lightDirNorm, lightSpotDir);
return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);
}`,startNineSlicedPS:`
nineSlicedUv = vec2f(vUv0.x, 1.0 - vUv0.y);
`,startNineSlicedTiledPS:`
let tileMask: vec2f = step(vMask, vec2f(0.99999));
let tileSize: vec2f = 0.5 * (innerOffset.xy + innerOffset.zw);
let tileScale: vec2f = vec2f(1.0) / (vec2f(1.0) - tileSize);
var clampedUv: vec2f = mix(innerOffset.xy * 0.5, vec2f(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));
clampedUv = clampedUv * atlasRect.zw + atlasRect.xy;
var nineSlicedUv: vec2f = vUv0 * tileMask + clampedUv * (vec2f(1.0) - tileMask);
nineSlicedUv.y = 1.0 - nineSlicedUv.y;
`,stdDeclarationPS:`
var<private> dAlpha: f32 = 1.0;
#if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE
#ifdef STD_OPACITY_TEXTURE_ALLOCATE
var texture_opacityMap : texture_2d<f32>;
var texture_opacityMapSampler : sampler;
#endif
#endif
#ifdef FORWARD_PASS
var<private> dAlbedo: vec3f;
var<private> dNormalW: vec3f;
var<private> dSpecularity: vec3f = vec3f(0.0, 0.0, 0.0);
var<private> dGlossiness: f32 = 0.0;
#ifdef LIT_REFRACTION
var<private> dTransmission: f32;
var<private> dThickness: f32;
#endif
#ifdef LIT_SCENE_COLOR
var uSceneColorMap : texture_2d<f32>;
var uSceneColorMapSampler : sampler;
#endif
#ifdef LIT_SCREEN_SIZE
uniform uScreenSize: vec4f;
#endif
#ifdef LIT_TRANSFORMS
var<private> matrix_viewProjection: mat4x4f;
var<private> matrix_model: mat4x4f;
#endif
#ifdef STD_HEIGHT_MAP
var<private> dUvOffset: vec2f;
#ifdef STD_HEIGHT_TEXTURE_ALLOCATE
var texture_heightMap : texture_2d<f32>;
var texture_heightMapSampler : sampler;
#endif
#endif
#ifdef STD_DIFFUSE_TEXTURE_ALLOCATE
var texture_diffuseMap : texture_2d<f32>;
var texture_diffuseMapSampler : sampler;
#endif
#ifdef STD_DIFFUSEDETAIL_TEXTURE_ALLOCATE
var texture_diffuseDetailMap : texture_2d<f32>;
var texture_diffuseDetailMapSampler : sampler;
#endif
#ifdef STD_NORMAL_TEXTURE_ALLOCATE
var texture_normalMap : texture_2d<f32>;
var texture_normalMapSampler : sampler;
#endif
#ifdef STD_NORMALDETAIL_TEXTURE_ALLOCATE
var texture_normalDetailMap : texture_2d<f32>;
var texture_normalDetailMapSampler : sampler;
#endif
#ifdef STD_THICKNESS_TEXTURE_ALLOCATE
var texture_thicknessMap : texture_2d<f32>;
var texture_thicknessMapSampler : sampler;
#endif
#ifdef STD_REFRACTION_TEXTURE_ALLOCATE
var texture_refractionMap : texture_2d<f32>;
var texture_refractionMapSampler : sampler;
#endif
#ifdef LIT_IRIDESCENCE
var<private> dIridescence: f32;
var<private> dIridescenceThickness: f32;
#ifdef STD_IRIDESCENCE_THICKNESS_TEXTURE_ALLOCATE
var texture_iridescenceThicknessMap : texture_2d<f32>;
var texture_iridescenceThicknessMapSampler : sampler;
#endif
#ifdef STD_IRIDESCENCE_TEXTURE_ALLOCATE
var texture_iridescenceMap : texture_2d<f32>;
var texture_iridescenceMapSampler : sampler;
#endif
#endif
#ifdef LIT_CLEARCOAT
var<private> ccSpecularity: f32;
var<private> ccGlossiness: f32;
var<private> ccNormalW: vec3f;
#endif
#ifdef LIT_GGX_SPECULAR
var<private> dAnisotropy: f32;
var<private> dAnisotropyRotation: vec2f;
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
var<private> sSpecularity: vec3f;
var<private> sGlossiness: f32;
#ifdef STD_SHEEN_TEXTURE_ALLOCATE
var texture_sheenMap : texture_2d<f32>;
var texture_sheenMapSampler : sampler;
#endif
#ifdef STD_SHEENGLOSS_TEXTURE_ALLOCATE
var texture_sheenGlossMap : texture_2d<f32>;
var texture_sheenGlossMapSampler : sampler;
#endif
#endif
#ifdef LIT_METALNESS
var<private> dMetalness: f32;
var<private> dIor: f32;
#ifdef STD_METALNESS_TEXTURE_ALLOCATE
var texture_metalnessMap : texture_2d<f32>;
var texture_metalnessMapSampler : sampler;
#endif
#endif
#ifdef LIT_SPECULARITY_FACTOR
var<private> dSpecularityFactor: f32;
#ifdef STD_SPECULARITYFACTOR_TEXTURE_ALLOCATE
var texture_specularityFactorMap : texture_2d<f32>;
var texture_specularityFactorMapSampler : sampler;
#endif
#endif
#ifdef STD_SPECULAR_COLOR
#ifdef STD_SPECULAR_TEXTURE_ALLOCATE
var texture_specularMap : texture_2d<f32>;
var texture_specularMapSampler : sampler;
#endif
#endif
#ifdef STD_GLOSS_TEXTURE_ALLOCATE
var texture_glossMap : texture_2d<f32>;
var texture_glossMapSampler : sampler;
#endif
#endif
#ifdef STD_AO
var <private> dAo: f32;
#ifdef STD_AO_TEXTURE_ALLOCATE
var texture_aoMap : texture_2d<f32>;
var texture_aoMapSampler : sampler;
#endif
#ifdef STD_AODETAIL_TEXTURE_ALLOCATE
var texture_aoDetailMap : texture_2d<f32>;
var texture_aoDetailMapSampler : sampler;
#endif
#endif
var <private> dEmission: vec3f;
#ifdef STD_EMISSIVE_TEXTURE_ALLOCATE
var texture_emissiveMap : texture_2d<f32>;
var texture_emissiveMapSampler : sampler;
#endif
#ifdef LIT_CLEARCOAT
#ifdef STD_CLEARCOAT_TEXTURE_ALLOCATE
var texture_clearCoatMap : texture_2d<f32>;
var texture_clearCoatMapSampler : sampler;
#endif
#ifdef STD_CLEARCOATGLOSS_TEXTURE_ALLOCATE
var texture_clearCoatGlossMap : texture_2d<f32>;
var texture_clearCoatGlossMapSampler : sampler;
#endif
#ifdef STD_CLEARCOATNORMAL_TEXTURE_ALLOCATE
var texture_clearCoatNormalMap : texture_2d<f32>;
var texture_clearCoatNormalMapSampler : sampler;
#endif
#endif
#ifdef LIT_GGX_SPECULAR
#ifdef STD_ANISOTROPY_TEXTURE_ALLOCATE
var texture_anisotropyMap : texture_2d<f32>;
var texture_anisotropyMapSampler : sampler;
#endif
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
var<private> dLightmap: vec3f;
#ifdef STD_LIGHT_TEXTURE_ALLOCATE
var texture_lightMap : texture_2d<f32>;
var texture_lightMapSampler : sampler;
#endif
#endif
#endif
#include "litShaderCorePS"
`,stdFrontEndPS:`
#if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE
#include "opacityPS"
#if defined(LIT_ALPHA_TEST)
#include "alphaTestPS"
#endif
#if STD_OPACITY_DITHER != NONE
#include "opacityDitherPS"
#endif
#endif
#ifdef FORWARD_PASS
#ifdef STD_HEIGHT_MAP
#include "parallaxPS"
#endif
#include "diffusePS"
#ifdef LIT_NEEDS_NORMAL
#include "normalMapPS"
#endif
#ifdef LIT_REFRACTION
#include "transmissionPS"
#include "thicknessPS"
#endif
#ifdef LIT_IRIDESCENCE
#include "iridescencePS"
#include "iridescenceThicknessPS"
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
#include "sheenPS"
#include "sheenGlossPS"
#endif
#ifdef LIT_METALNESS
#include "metalnessPS"
#include "iorPS"
#endif
#ifdef LIT_SPECULARITY_FACTOR
#include "specularityFactorPS"
#endif
#ifdef STD_SPECULAR_COLOR
#include "specularPS"
#else
fn getSpecularity() {
dSpecularity = vec3f(1.0, 1.0, 1.0);
}
#endif
#include "glossPS"
#endif
#ifdef STD_AO
#include "aoPS"
#endif
#include "emissivePS"
#ifdef LIT_CLEARCOAT
#include "clearCoatPS"
#include "clearCoatGlossPS"
#include "clearCoatNormalPS"
#endif
#if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)
#include "anisotropyPS"
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
#include "lightmapPS"
#endif
#endif
fn evaluateFrontend() {
#if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE
getOpacity();
#if defined(LIT_ALPHA_TEST)
alphaTest(dAlpha);
#endif
#if STD_OPACITY_DITHER != NONE
opacityDither(dAlpha, 0.0);
#endif
litArgs_opacity = dAlpha;
#endif
#ifdef FORWARD_PASS
#ifdef STD_HEIGHT_MAP
getParallax();
#endif
getAlbedo();
litArgs_albedo = dAlbedo;
#ifdef LIT_NEEDS_NORMAL
getNormal();
litArgs_worldNormal = dNormalW;
#endif
#ifdef LIT_REFRACTION
getRefraction();
litArgs_transmission = dTransmission;
getThickness();
litArgs_thickness = dThickness;
#ifdef LIT_DISPERSION
litArgs_dispersion = uniform.material_dispersion;
#endif
#endif
#ifdef LIT_IRIDESCENCE
getIridescence();
getIridescenceThickness();
litArgs_iridescence_intensity = dIridescence;
litArgs_iridescence_thickness = dIridescenceThickness;
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
getSheen();
litArgs_sheen_specularity = sSpecularity;
getSheenGlossiness();
litArgs_sheen_gloss = sGlossiness;
#endif
#ifdef LIT_METALNESS
getMetalness();
litArgs_metalness = dMetalness;
getIor();
litArgs_ior = dIor;
#endif
#ifdef LIT_SPECULARITY_FACTOR
getSpecularityFactor();
litArgs_specularityFactor = dSpecularityFactor;
#endif
getGlossiness();
getSpecularity();
litArgs_specularity = dSpecularity;
litArgs_gloss = dGlossiness;
#endif
#ifdef STD_AO
getAO();
litArgs_ao = dAo;
#endif
getEmission();
litArgs_emission = dEmission;
#ifdef LIT_CLEARCOAT
getClearCoat();
getClearCoatGlossiness();
getClearCoatNormal();
litArgs_clearcoat_specularity = ccSpecularity;
litArgs_clearcoat_gloss = ccGlossiness;
litArgs_clearcoat_worldNormal = ccNormalW;
#endif
#if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)
getAnisotropy();
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
getLightMap();
litArgs_lightmap = dLightmap;
#ifdef STD_LIGHTMAP_DIR
litArgs_lightmapDir = dLightmapDir;
#endif
#endif
#endif
}
`,TBNPS:`
#ifdef LIT_TANGENTS
#define TBN_TANGENTS
#else
#if defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS)
#define TBN_DERIVATIVES
#endif
#endif
#if defined(TBN_DERIVATIVES)
uniform tbnBasis: f32;
#endif
fn getTBN(tangent: vec3f, binormal: vec3f, normal: vec3f) {
#ifdef TBN_TANGENTS
dTBN = mat3x3f(normalize(tangent), normalize(binormal), normalize(normal));
#elif defined(TBN_DERIVATIVES)
let uv: vec2f = {lightingUv};
let dp1: vec3f = dpdx( vPositionW );
let dp2: vec3f = dpdy( vPositionW );
let duv1: vec2f = dpdx( uv );
let duv2: vec2f = dpdy( uv );
let dp2perp: vec3f = cross( dp2, normal );
let dp1perp: vec3f = cross( normal, dp1 );
let T: vec3f = dp2perp * duv1.x + dp1perp * duv2.x;
let B: vec3f = dp2perp * duv1.y + dp1perp * duv2.y;
let denom: f32 = max( dot(T, T), dot(B, B) );
let invmax: f32 = select(uniform.tbnBasis / sqrt( denom ), 0.0, denom == 0.0);
dTBN = mat3x3f(T * invmax, -B * invmax, normal );
#else
var B: vec3f = cross(normal, vObjectSpaceUpW);
var T: vec3f = cross(normal, B);
if (dot(B,B) == 0.0)
{
let major: f32 = max(max(normal.x, normal.y), normal.z);
if (normal.x == major)
{
B = cross(normal, vec3f(0.0, 1.0, 0.0));
T = cross(normal, B);
}
else if (normal.y == major)
{
B = cross(normal, vec3f(0.0, 0.0, 1.0));
T = cross(normal, B);
}
else
{
B = cross(normal, vec3f(1.0, 0.0, 0.0));
T = cross(normal, B);
}
}
dTBN = mat3x3f(normalize(T), normalize(B), normalize(normal));
#endif
}`,thicknessPS:`
#ifdef STD_THICKNESS_CONSTANT
uniform material_thickness: f32;
#endif
fn getThickness() {
dThickness = 1.0;
#ifdef STD_THICKNESS_CONSTANT
dThickness = dThickness * uniform.material_thickness;
#endif
#ifdef STD_THICKNESS_TEXTURE
dThickness = dThickness * textureSampleBias({STD_THICKNESS_TEXTURE_NAME}, {STD_THICKNESS_TEXTURE_NAME}Sampler, {STD_THICKNESS_TEXTURE_UV}, uniform.textureBias).{STD_THICKNESS_TEXTURE_CHANNEL};
#endif
#ifdef STD_THICKNESS_VERTEX
dThickness = dThickness * saturate(vVertexColor.{STD_THICKNESS_VERTEX_CHANNEL});
#endif
}
`,tonemappingPS:`
#if (TONEMAP == NONE)
#include "tonemappingNonePS"
#elif TONEMAP == FILMIC
#include "tonemappingFilmicPS"
#elif TONEMAP == LINEAR
#include "tonemappingLinearPS"
#elif TONEMAP == HEJL
#include "tonemappingHejlPS"
#elif TONEMAP == ACES
#include "tonemappingAcesPS"
#elif TONEMAP == ACES2
#include "tonemappingAces2PS"
#elif TONEMAP == NEUTRAL
#include "tonemappingNeutralPS"
#endif
`,tonemappingAcesPS:`
uniform exposure: f32;
fn toneMap(color: vec3f) -> vec3f {
let tA: f32 = 2.51;
let tB: f32 = 0.03;
let tC: f32 = 2.43;
let tD: f32 = 0.59;
let tE: f32 = 0.14;
let x: vec3f = color * uniform.exposure;
return (x * (tA * x + tB)) / (x * (tC * x + tD) + tE);
}
`,tonemappingAces2PS:`
uniform exposure: f32;
const ACESInputMat: mat3x3f = mat3x3f(
vec3f(0.59719, 0.35458, 0.04823),
vec3f(0.07600, 0.90834, 0.01566),
vec3f(0.02840, 0.13383, 0.83777)
);
const ACESOutputMat: mat3x3f = mat3x3f(
vec3f( 1.60475, -0.53108, -0.07367),
vec3f(-0.10208, 1.10813, -0.00605),
vec3f(-0.00327, -0.07276, 1.07602)
);
fn RRTAndODTFit(v: vec3f) -> vec3f {
let a: vec3f = v * (v + vec3f(0.0245786)) - vec3f(0.000090537);
let b: vec3f = v * (vec3f(0.983729) * v + vec3f(0.4329510)) + vec3f(0.238081);
return a / b;
}
fn toneMap(color: vec3f) -> vec3f {
var c: vec3f = color * (uniform.exposure / 0.6);
c = c * ACESInputMat;
c = RRTAndODTFit(c);
c = c * ACESOutputMat;
return clamp(c, vec3f(0.0), vec3f(1.0));
}
`,tonemappingFilmicPS:`
const A: f32 = 0.15;
const B: f32 = 0.50;
const C: f32 = 0.10;
const D: f32 = 0.20;
const E: f32 = 0.02;
const F: f32 = 0.30;
const W: f32 = 11.2;
uniform exposure: f32;
fn uncharted2Tonemap(x: vec3f) -> vec3f {
return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - vec3f(E / F);
}
fn toneMap(color: vec3f) -> vec3f {
var c: vec3f = uncharted2Tonemap(color * uniform.exposure);
let whiteScale: vec3f = vec3f(1.0) / uncharted2Tonemap(vec3f(W, W, W));
c *= whiteScale;
return c;
}
`,tonemappingHejlPS:`
uniform exposure: f32;
fn toneMap(color: vec3f) -> vec3f {
let A: f32 = 0.22;
let B: f32 = 0.3;
let C: f32 = 0.1;
let D: f32 = 0.2;
let E: f32 = 0.01;
let F: f32 = 0.3;
let Scl: f32 = 1.25;
let adjusted_color = color * uniform.exposure;
let h = max(vec3f(0.0), adjusted_color - vec3f(0.004));
return (h * ((Scl * A) * h + Scl * vec3f(C * B)) + Scl * vec3f(D * E)) /
(h * (A * h + vec3f(B)) + vec3f(D * F)) -
Scl * vec3f(E / F);
}
`,tonemappingLinearPS:`
uniform exposure: f32;
fn toneMap(color: vec3f) -> vec3f {
return color * uniform.exposure;
}
`,tonemappingNeutralPS:`
uniform exposure: f32;
fn toneMap(col: vec3f) -> vec3f {
var color = col * uniform.exposure;
let startCompression = 0.8 - 0.04;
let desaturation = 0.15;
let x = min(color.r, min(color.g, color.b));
let offset = select(0.04, x - 6.25 * x * x, x < 0.08);
color -= vec3f(offset);
let peak = max(color.r, max(color.g, color.b));
if (peak < startCompression) {
return color;
}
let d = 1.0 - startCompression;
let newPeak = 1.0 - d * d / (peak + d - startCompression);
color *= newPeak / peak;
let g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);
return mix(color, vec3f(newPeak), vec3f(g));
}
`,tonemappingNonePS:`
fn toneMap(color: vec3f) -> vec3f {
return color;
}
`,transformVS:`
#ifdef PIXELSNAP
uniform uScreenSize: vec4f;
#endif
#ifdef SCREENSPACE
uniform projectionFlipY: f32;
#endif
fn evalWorldPosition(vertexPosition: vec3f, modelMatrix: mat4x4f) -> vec4f {
var localPos: vec3f = getLocalPosition(vertexPosition);
#ifdef NINESLICED
var localPosXZ: vec2f = localPos.xz;
localPosXZ = localPosXZ * uniform.outerScale;
let positiveUnitOffset: vec2f = clamp(vertexPosition.xz, vec2f(0.0), vec2f(1.0));
let negativeUnitOffset: vec2f = clamp(-vertexPosition.xz, vec2f(0.0), vec2f(1.0));
localPosXZ = localPosXZ + (-positiveUnitOffset * uniform.innerOffset.xy + negativeUnitOffset * uniform.innerOffset.zw) * vertex_texCoord0.xy;
dTiledUvGlobal = (localPosXZ - uniform.outerScale + uniform.innerOffset.xy) * -0.5 + 1.0;
localPosXZ = localPosXZ * -0.5;
localPos = vec3f(localPosXZ.x, localPosXZ.y, localPos.y);
#endif
var posW: vec4f = modelMatrix * vec4f(localPos, 1.0);
#ifdef SCREENSPACE
posW = vec4f(posW.xy, 0.0, 1.0);
#endif
return posW;
}
fn getPosition() -> vec4f {
dModelMatrix = getModelMatrix();
let posW: vec4f = evalWorldPosition(vertex_position.xyz, dModelMatrix);
dPositionW = posW.xyz;
var screenPos: vec4f;
#ifdef UV1LAYOUT
screenPos = vec4f(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1.0);
screenPos.y *= -1.0;
#else
#ifdef SCREENSPACE
screenPos = posW;
screenPos.y *= uniform.projectionFlipY;
#else
screenPos = uniform.matrix_viewProjection * posW;
#endif
#ifdef PIXELSNAP
screenPos.xy = (screenPos.xy * 0.5) + 0.5;
screenPos.xy *= uniforms.uScreenSize.xy;
screenPos.xy = floor(screenPos.xy);
screenPos.xy *= uniforms.uScreenSize.zw;
screenPos.xy = (screenPos.xy * 2.0) - 1.0;
#endif
#endif
return screenPos;
}
fn getWorldPosition() -> vec3f {
return dPositionW;
}
`,transformCoreVS:`
attribute vertex_position: vec4f;
uniform matrix_viewProjection: mat4x4f;
uniform matrix_model: mat4x4f;
#ifdef MORPHING
uniform morph_tex_params: vec2f;
attribute morph_vertex_id: u32;
fn getTextureMorphCoords() -> vec2i {
var textureSize: vec2i = vec2i(uniform.morph_tex_params);
var morphGridV: i32 = i32(morph_vertex_id) / textureSize.x;
var morphGridU: i32 = i32(morph_vertex_id) - (morphGridV * textureSize.x);
morphGridV = textureSize.y - morphGridV - 1;
return vec2i(morphGridU, morphGridV);
}
#ifdef MORPHING_POSITION
#ifdef MORPHING_INT
uniform aabbSize: vec3f;
uniform aabbMin: vec3f;
var morphPositionTex: texture_2d<u32>;
#else
var morphPositionTex: texture_2d<f32>;
#endif
#endif
#endif
#ifdef defined(BATCH)
#include "skinBatchVS"
fn getModelMatrix() -> mat4x4f {
return getBoneMatrix(vertex_boneIndices);
}
#elif defined(SKIN)
#include "skinVS"
fn getModelMatrix() -> mat4x4f {
return uniform.matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);
}
#elif defined(INSTANCING)
#include "transformInstancingVS"
#else
fn getModelMatrix() -> mat4x4f {
return uniform.matrix_model;
}
#endif
fn getLocalPosition(vertexPosition: vec3f) -> vec3f {
var localPos: vec3f = vertexPosition;
#ifdef MORPHING_POSITION
var morphUV: vec2i = getTextureMorphCoords();
#ifdef MORPHING_INT
var morphPos: vec3f = vec3f(textureLoad(morphPositionTex, morphUV, 0).xyz) / 65535.0 * uniform.aabbSize + uniform.aabbMin;
#else
var morphPos: vec3f = textureLoad(morphPositionTex, morphUV, 0).xyz;
#endif
localPos += morphPos;
#endif
return localPos;
}
`,transformInstancingVS:`
attribute instance_line1: vec4f;
attribute instance_line2: vec4f;
attribute instance_line3: vec4f;
attribute instance_line4: vec4f;
fn getModelMatrix() -> mat4x4f {
return uniform.matrix_model * mat4x4f(instance_line1, instance_line2, instance_line3, instance_line4);
}
`,transmissionPS:`
#ifdef STD_REFRACTION_CONSTANT
uniform material_refraction: f32;
#endif
fn getRefraction() {
var refraction: f32 = 1.0;
#ifdef STD_REFRACTION_CONSTANT
refraction = uniform.material_refraction;
#endif
#ifdef STD_REFRACTION_TEXTURE
refraction = refraction * textureSampleBias({STD_REFRACTION_TEXTURE_NAME}, {STD_REFRACTION_TEXTURE_NAME}Sampler, {STD_REFRACTION_TEXTURE_UV}, uniform.textureBias).{STD_REFRACTION_TEXTURE_CHANNEL};
#endif
#ifdef STD_REFRACTION_VERTEX
refraction = refraction * saturate(vVertexColor.{STD_REFRACTION_VERTEX_CHANNEL});
#endif
dTransmission = refraction;
}
`,twoSidedLightingPS:`
uniform twoSidedLightingNegScaleFactor: f32;
fn handleTwoSidedLighting() {
dTBN[2] = dTBN[2] * select(-uniform.twoSidedLightingNegScaleFactor, uniform.twoSidedLightingNegScaleFactor, pcFrontFacing);
}
`,uv0VS:`
#ifdef NINESLICED
fn getUv0() -> vec2f {
var uv = vertex_position.xz;
let positiveUnitOffset = clamp(vertex_position.xz, vec2f(0.0, 0.0), vec2f(1.0, 1.0));
let negativeUnitOffset = clamp(-vertex_position.xz, vec2f(0.0, 0.0), vec2f(1.0, 1.0));
uv = uv + ((-positiveUnitOffset * uniform.innerOffset.xy) + (negativeUnitOffset * uniform.innerOffset.zw)) * vertex_texCoord0.xy;
uv = uv * -0.5 + vec2f(0.5, 0.5);
uv = uv * uniform.atlasRect.zw + uniform.atlasRect.xy;
dMaskGlobal = vertex_texCoord0.xy;
return uv;
}
#else
fn getUv0() -> vec2f {
return vertex_texCoord0;
}
#endif
`,uv1VS:`
fn getUv1() -> vec2f {
return vertex_texCoord1;
}
`,uvTransformVS:`
output.vUV{TRANSFORM_UV_{i}}_{TRANSFORM_ID_{i}} = vec2f(
dot(vec3f(uv{TRANSFORM_UV_{i}}, 1), uniform.{TRANSFORM_NAME_{i}}0),
dot(vec3f(uv{TRANSFORM_UV_{i}}, 1), uniform.{TRANSFORM_NAME_{i}}1)
);
`,uvTransformUniformsPS:`
uniform {TRANSFORM_NAME_{i}}0: vec3f;
uniform {TRANSFORM_NAME_{i}}1: vec3f;
`,viewDirPS:`
fn getViewDir() {
dViewDirW = normalize(uniform.view_position - vPositionW);
}
`,webgpuPS:o9,webgpuVS:o7},x6=null;class x9 extends eo{constructor(e){super(),this._batcher=null,this._destroyRequested=false,this._inFrameUpdate=false,this._librariesLoaded=false,this._fillMode=xe,this._resolutionMode=xi,this._allowResize=true,this._skyboxAsset=null,this._entityIndex={},this._inTools=false,this._scriptPrefix="",this._time=0,this.enableBundles="undefined"!=typeof TextDecoder,this.timeScale=1,this.maxDeltaTime=.1,this.frame=0,this.frameGraph=new xa,this.scriptsOrder=[],this.autoRender=true,this.renderNextFrame=false,this.lightmapper=null,this.loader=new xX(this),this.scenes=new x3(this),this.scripts=new x$(this),this.systems=new xV,this.i18n=new xq(this),this.keyboard=null,this.mouse=null,this.touch=null,this.gamepads=null,this.elementInput=null,this.xr=null,x9._applications[e.id]=this,s=this,x6=this,this.root=new x1,this.root._enabledInHierarchy=true;}init(e){let{assetPrefix:t,batchManager:i,componentSystems:s,elementInput:r,gamepads:a,graphicsDevice:n,keyboard:o,lightmapper:l,mouse:h,resourceHandlers:c,scriptsOrder:d,scriptPrefix:u,soundManager:f,touch:p,xr:m}=e;this.graphicsDevice=n,mr.get(n,rb).add(x5),mr.get(n,rw).add(x8),this._initDefaultMaterial(),this._initProgramLibrary(),this.stats=new x4(n),this._soundManager=f,this.scene=new SD(n),this._registerSceneImmediate(this.scene),this.assets=new xU(this.loader),t&&(this.assets.prefix=t),this.bundles=new xk(this.assets),this.scriptsOrder=d||[],this.defaultLayerWorld=new gH({name:"World",id:ub}),this.defaultLayerDepth=new gH({name:"Depth",id:uw,enabled:false,opaqueSortMode:pO}),this.defaultLayerSkybox=new gH({name:"Skybox",id:uC,opaqueSortMode:pO}),this.defaultLayerUi=new gH({name:"UI",id:uL,transparentSortMode:pN}),this.defaultLayerImmediate=new gH({name:"Immediate",id:uP,opaqueSortMode:pO});let _=new gY("default");_.pushOpaque(this.defaultLayerWorld),_.pushOpaque(this.defaultLayerDepth),_.pushOpaque(this.defaultLayerSkybox),_.pushTransparent(this.defaultLayerWorld),_.pushOpaque(this.defaultLayerImmediate),_.pushTransparent(this.defaultLayerImmediate),_.pushTransparent(this.defaultLayerUi),this.scene.layers=_,xl.createPlaceholder(n),this.renderer=new gB(n),this.renderer.scene=this.scene,l&&(this.lightmapper=new l(n,this.root,this.scene,this.renderer,this.assets),this.once("prerender",this._firstBake,this)),i&&(this._batcher=new i(n,this.root,this.scene),this.once("prerender",this._firstBatch,this)),this.keyboard=o||null,this.mouse=h||null,this.touch=p||null,this.gamepads=a||null,r&&(this.elementInput=r,this.elementInput.app=this),this.xr=m?new m(this):null,this.elementInput&&this.elementInput.attachSelectEvents(),this._scriptPrefix=u||"",this.enableBundles&&this.loader.addHandler("bundle",new xW(this)),c.forEach(e=>{let t=new e(this);this.loader.addHandler(t.handlerType,t);}),s.forEach(e=>{this.systems.add(new e(this));}),this._visibilityChangeHandler=this.onVisibilityChange.bind(this),"undefined"!=typeof document&&(void 0!==document.hidden?(this._hiddenAttr="hidden",document.addEventListener("visibilitychange",this._visibilityChangeHandler,false)):void 0!==document.mozHidden?(this._hiddenAttr="mozHidden",document.addEventListener("mozvisibilitychange",this._visibilityChangeHandler,false)):void 0!==document.msHidden?(this._hiddenAttr="msHidden",document.addEventListener("msvisibilitychange",this._visibilityChangeHandler,false)):void 0!==document.webkitHidden&&(this._hiddenAttr="webkitHidden",document.addEventListener("webkitvisibilitychange",this._visibilityChangeHandler,false))),this.tick=x7(this);}static{this._applications={};}static getApplication(e){return e?x9._applications[e]:s}_initDefaultMaterial(){var e;let t=new yo;t.name="Default Material",e=this.graphicsDevice,mC.get(e,()=>t);}_initProgramLibrary(){var e;let t=new yb(this.graphicsDevice,new yo);e=this.graphicsDevice,p8.get(e,()=>t);}get soundManager(){return this._soundManager}get batcher(){return this._batcher}get fillMode(){return this._fillMode}get resolutionMode(){return this._resolutionMode}configure(e,t){d1.get(e,(e,i)=>{if(e)return void t(e);let s=i.application_properties,r=i.scenes,a=i.assets;this._parseApplicationProperties(s,e=>{this._parseScenes(r),this._parseAssets(a),e?t(e):t(null);});});}preload(e){this.fire("preload:start");let t=this.assets.list({preload:true});if(0===t.length){this.fire("preload:end"),e();return}let i=0,s=()=>{i++,this.fire("preload:progress",i/t.length),i===t.length&&(this.fire("preload:end"),e());};t.forEach(e=>{e.loaded?s():(e.once("load",s),e.once("error",s),this.assets.load(e));});}_preloadScripts(e,t){t();}_parseApplicationProperties(e,t){if("number"==typeof e.maxAssetRetries&&e.maxAssetRetries>0&&this.loader.enableRetry(e.maxAssetRetries),e.useDevicePixelRatio||(e.useDevicePixelRatio=e.use_device_pixel_ratio),e.resolutionMode||(e.resolutionMode=e.resolution_mode),e.fillMode||(e.fillMode=e.fill_mode),this._width=e.width,this._height=e.height,e.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio),this.setCanvasResolution(e.resolutionMode,this._width,this._height),this.setCanvasFillMode(e.fillMode,this._width,this._height),e.layers&&e.layerOrder){let t=new gY("application"),i={};for(let t in e.layers){let s=e.layers[t];s.id=parseInt(t,10),s.enabled=s.id!==uw,i[t]=new gH(s);}for(let s=0,r=e.layerOrder.length;s<r;s++){let r=e.layerOrder[s],a=i[r.layer];a&&(r.transparent?t.pushTransparent(a):t.pushOpaque(a),t.subLayerEnabled[s]=r.enabled);}this.scene.layers=t;}if(e.batchGroups){let t=this.batcher;if(t)for(let i=0,s=e.batchGroups.length;i<s;i++){let s=e.batchGroups[i];t.addGroup(s.name,s.dynamic,s.maxAabbSize,s.id,s.layers);}}e.i18nAssets&&(this.i18n.assets=e.i18nAssets),this._loadLibraries(e.libraries,t);}_loadLibraries(e,t){let i=e.length,s=i,r=/^https?:\/\//;if(i){let a=(e,i)=>{s--,e?t(e):0===s&&(this.onLibrariesLoaded(),t(null));};for(let t=0;t<i;++t){let i=e[t];!r.test(i.toLowerCase())&&this._scriptPrefix&&(i=W.join(this._scriptPrefix,i)),this.loader.load(i,"script",a);}}else this.onLibrariesLoaded(),t(null);}_parseScenes(e){if(e)for(let t=0;t<e.length;t++)this.scenes.add(e[t].name,e[t].url);}_parseAssets(e){let t=[],i={},s={};for(let s=0;s<this.scriptsOrder.length;s++){let r=this.scriptsOrder[s];e[r]&&(i[r]=true,t.push(e[r]));}if(this.enableBundles)for(let i in e)"bundle"===e[i].type&&(s[i]=true,t.push(e[i]));for(let r in e)i[r]||s[r]||t.push(e[r]);for(let e=0;e<t.length;e++){let i=t[e],s=new xF(i.name,i.type,i.file,i.data);if(s.id=parseInt(i.id,10),s.preload=!!i.preload&&i.preload,s.loaded="script"===i.type&&i.data&&i.data.loadingType>0,s.tags.add(i.tags),i.i18n)for(let e in i.i18n)s.addLocalizedAssetId(e,i.i18n[e]);this.assets.add(s);}}start(){this.frame=0,this.fire("start",{timestamp:em(),target:this}),this._librariesLoaded||this.onLibrariesLoaded(),this.systems.fire("initialize",this.root),this.fire("initialize"),this.systems.fire("postInitialize",this.root),this.systems.fire("postPostInitialize",this.root),this.fire("postinitialize"),this.tick();}inputUpdate(e){this.controller&&this.controller.update(e),this.mouse&&this.mouse.update(),this.keyboard&&this.keyboard.update(),this.gamepads&&this.gamepads.update();}update(e){this.frame++,this.graphicsDevice.update(),this.systems.fire(this._inTools?"toolsUpdate":"update",e),this.systems.fire("animationUpdate",e),this.systems.fire("postUpdate",e),this.fire("update",e),this.inputUpdate(e);}render(){this.updateCanvasSize(),this.graphicsDevice.frameStart(),this.fire("prerender"),this.root.syncHierarchy(),this._batcher&&this._batcher.updateAll(),this.renderComposition(this.scene.layers),this.fire("postrender"),this.graphicsDevice.frameEnd();}renderComposition(e){this.renderer.update(e),this.renderer.buildFrameGraph(this.frameGraph,e),this.frameGraph.render(this.graphicsDevice);}_fillFrameStatsBasic(e,t,i){let s=this.stats.frame;s.dt=t,s.ms=i,e>s._timeToCountFrames?(s.fps=s._fpsAccum,s._fpsAccum=0,s._timeToCountFrames=e+1e3):s._fpsAccum++,this.stats.drawCalls.total=this.graphicsDevice._drawCallsPerFrame,this.graphicsDevice._drawCallsPerFrame=0;}_fillFrameStats(){let e=this.stats.frame;e.cameras=this.renderer._camerasRendered,e.materials=this.renderer._materialSwitches,e.shaders=this.graphicsDevice._shaderSwitchesPerFrame,e.shadowMapUpdates=this.renderer._shadowMapUpdates,e.shadowMapTime=this.renderer._shadowMapTime,e.depthMapTime=this.renderer._depthMapTime,e.forwardTime=this.renderer._forwardTime;let t=this.graphicsDevice._primsPerFrame;e.triangles=t[sS]/3+Math.max(t[sy]-2,0)+Math.max(t[sx]-2,0),e.cullTime=this.renderer._cullTime,e.sortTime=this.renderer._sortTime,e.skinTime=this.renderer._skinTime,e.morphTime=this.renderer._morphTime,e.lightClusters=this.renderer._lightClusters,e.lightClustersTime=this.renderer._lightClustersTime,e.otherPrimitives=0;for(let i=0;i<t.length;i++)i<sS&&(e.otherPrimitives+=t[i]),t[i]=0;this.renderer._camerasRendered=0,this.renderer._materialSwitches=0,this.renderer._shadowMapUpdates=0,this.graphicsDevice._shaderSwitchesPerFrame=0,this.renderer._cullTime=0,this.renderer._layerCompositionUpdateTime=0,this.renderer._lightClustersTime=0,this.renderer._sortTime=0,this.renderer._skinTime=0,this.renderer._morphTime=0,this.renderer._shadowMapTime=0,this.renderer._depthMapTime=0,this.renderer._forwardTime=0,(e=this.stats.drawCalls).forward=this.renderer._forwardDrawCalls,e.culled=this.renderer._numDrawCallsCulled,e.depth=0,e.shadow=this.renderer._shadowDrawCalls,e.skinned=this.renderer._skinDrawCalls,e.immediate=0,e.instanced=0,e.removedByInstancing=0,e.misc=e.total-(e.forward+e.shadow),this.renderer._depthDrawCalls=0,this.renderer._shadowDrawCalls=0,this.renderer._forwardDrawCalls=0,this.renderer._numDrawCallsCulled=0,this.renderer._skinDrawCalls=0,this.renderer._immediateRendered=0,this.renderer._instancedDrawCalls=0,this.stats.misc.renderTargetCreationTime=this.graphicsDevice.renderTargetCreationTime,(e=this.stats.particles).updatesPerFrame=e._updatesPerFrame,e.frameTime=e._frameTime,e._updatesPerFrame=0,e._frameTime=0;}setCanvasFillMode(e,t,i){this._fillMode=e,this.resizeCanvas(t,i);}setCanvasResolution(e,t,i){this._resolutionMode=e,e===xt&&void 0===t&&(t=this.graphicsDevice.canvas.clientWidth,i=this.graphicsDevice.canvas.clientHeight),this.graphicsDevice.resizeCanvas(t,i);}isHidden(){return document[this._hiddenAttr]}onVisibilityChange(){this.isHidden()?this._soundManager&&this._soundManager.suspend():this._soundManager&&this._soundManager.resume();}resizeCanvas(e,t){if(!this._allowResize||this.xr&&this.xr.session)return;let i=window.innerWidth,s=window.innerHeight;if(this._fillMode===xe){let r=this.graphicsDevice.canvas.width/this.graphicsDevice.canvas.height;r>i/s?t=(e=i)/r:e=(t=s)*r;}else this._fillMode===y7&&(e=i,t=s);return this.graphicsDevice.canvas.style.width=`${e}px`,this.graphicsDevice.canvas.style.height=`${t}px`,this.updateCanvasSize(),{width:e,height:t}}updateCanvasSize(){if(!(!this._allowResize||this.xr?.active)&&this._resolutionMode===xt){let e=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(e.clientWidth,e.clientHeight);}}onLibrariesLoaded(){this._librariesLoaded=true,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded();}applySceneSettings(e){let t;if(this.systems.rigidbody&&"undefined"!=typeof Ammo){let[t,i,s]=e.physics.gravity;this.systems.rigidbody.gravity.set(t,i,s);}this.scene.applySettings(e),e.render.hasOwnProperty("skybox")&&(e.render.skybox?(t=this.assets.get(e.render.skybox))?this.setSkybox(t):this.assets.once(`add:${e.render.skybox}`,this.setSkybox,this):this.setSkybox(null));}setAreaLightLuts(e,t){e&&t&&xl.set(this.graphicsDevice,e,t);}setSkybox(e){if(e!==this._skyboxAsset){let t=()=>{this.setSkybox(null);},i=()=>{this.scene.setSkybox(this._skyboxAsset?this._skyboxAsset.resources:null);};this._skyboxAsset&&(this.assets.off(`load:${this._skyboxAsset.id}`,i,this),this.assets.off(`remove:${this._skyboxAsset.id}`,t,this),this._skyboxAsset.off("change",i,this)),this._skyboxAsset=e,this._skyboxAsset&&(this.assets.on(`load:${this._skyboxAsset.id}`,i,this),this.assets.once(`remove:${this._skyboxAsset.id}`,t,this),this._skyboxAsset.on("change",i,this),0!==this.scene.skyboxMip||this._skyboxAsset.loadFaces||(this._skyboxAsset.loadFaces=true),this.assets.load(this._skyboxAsset)),i();}}_firstBake(){this.lightmapper?.bake(null,this.scene.lightmapMode);}_firstBatch(){this.batcher?.generate();}_processTimestamp(e){return e}drawLine(e,t,i,s,r){this.scene.drawLine(e,t,i,s,r);}drawLines(e,t,i=true,s=this.scene.defaultDrawLayer){this.scene.drawLines(e,t,i,s);}drawLineArrays(e,t,i=true,s=this.scene.defaultDrawLayer){this.scene.drawLineArrays(e,t,i,s);}drawWireSphere(e,t,i=eb.WHITE,s=20,r=true,a=this.scene.defaultDrawLayer){this.scene.immediate.drawWireSphere(e,t,i,s,r,a);}drawWireAlignedBox(e,t,i=eb.WHITE,s=true,r=this.scene.defaultDrawLayer,a){this.scene.immediate.drawWireAlignedBox(e,t,i,s,r,a);}drawMeshInstance(e,t=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(null,null,null,e,t);}drawMesh(e,t,i,s=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(t,i,e,null,s);}drawQuad(e,t,i=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(t,e,this.scene.immediate.getQuadMesh(),null,i);}drawTexture(e,t,i,s,r,a,n=this.scene.defaultDrawLayer,o=true){if(false===o&&!this.graphicsDevice.isWebGPU)return;let l=new eG;l.setTRS(new eM(e,t,0),eH.IDENTITY,new eM(i,-s,0)),a||((a=new vY).cull=tY,a.setParameter("colorMap",r),a.shaderDesc=o?this.scene.immediate.getTextureShaderDesc(r.encoding):this.scene.immediate.getUnfilterableTextureShaderDesc(),a.update()),this.drawQuad(l,a,n);}drawDepthTexture(e,t,i,s,r=this.scene.defaultDrawLayer){let a=new vY;a.cull=tY,a.shaderDesc=this.scene.immediate.getDepthTextureShaderDesc(),a.update(),this.drawTexture(e,t,i,s,null,a,r);}destroy(){if(this._inFrameUpdate){this._destroyRequested=true;return}let e=this.graphicsDevice.canvas.id;this.fire("destroy",this),this.off("librariesloaded"),"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this._visibilityChangeHandler,false),document.removeEventListener("mozvisibilitychange",this._visibilityChangeHandler,false),document.removeEventListener("msvisibilitychange",this._visibilityChangeHandler,false),document.removeEventListener("webkitvisibilitychange",this._visibilityChangeHandler,false)),this._visibilityChangeHandler=null,this.root.destroy(),this.root=null,this.mouse&&(this.mouse.off(),this.mouse.detach(),this.mouse=null),this.keyboard&&(this.keyboard.off(),this.keyboard.detach(),this.keyboard=null),this.touch&&(this.touch.off(),this.touch.detach(),this.touch=null),this.elementInput&&(this.elementInput.detach(),this.elementInput=null),this.gamepads&&(this.gamepads.destroy(),this.gamepads=null),this.controller&&(this.controller=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy();let t=this.assets.list();for(let e=0;e<t.length;e++)t[e].unload(),t[e].off();this.assets.off(),this.bundles.destroy(),this.bundles=null,this.i18n.destroy(),this.i18n=null;let i=this.loader.getHandler("script");i?.clearCache(),this.loader.destroy(),this.loader=null,this.scene.destroy(),this.scene=null,this.systems=null,this.context=null,this.scripts.destroy(),this.scripts=null,this.scenes.destroy(),this.scenes=null,this.lightmapper?.destroy(),this.lightmapper=null,this._batcher&&(this._batcher.destroy(),this._batcher=null),this._entityIndex={},this.defaultLayerDepth.onDisable=null,this.defaultLayerDepth.onEnable=null,this.defaultLayerDepth=null,this.defaultLayerWorld=null,this.xr?.end(),this.xr?.destroy(),this.renderer.destroy(),this.renderer=null,this.graphicsDevice.destroy(),this.graphicsDevice=null,this.tick=null,this.off(),this._soundManager?.destroy(),this._soundManager=null,xr.app=null,x9._applications[e]=null,s===this&&(s=null),x9.cancelTick(this);}static cancelTick(e){e.frameRequestId&&(window.cancelAnimationFrame(e.frameRequestId),e.frameRequestId=void 0);}getEntityFromIndex(e){return this._entityIndex[e]}_registerSceneImmediate(e){this.on("postrender",e.immediate.onPostRender,e.immediate);}}let x7=function(e){return function(t,i){if(!e.graphicsDevice)return;e.frameRequestId&&(e.xr?.session?.cancelAnimationFrame(e.frameRequestId),cancelAnimationFrame(e.frameRequestId),e.frameRequestId=null),e._inFrameUpdate=true,s=e,x6=e;let r=e._processTimestamp(t)||em(),a=r-(e._time||r),n=a/1e3;if(n=eA.clamp(n,0,e.maxDeltaTime)*e.timeScale,e._time=r,e.xr?.session?e.frameRequestId=e.xr.session.requestAnimationFrame(e.tick):e.frameRequestId=ee.browser||ee.worker?requestAnimationFrame(e.tick):null,e.graphicsDevice.contextLost)return;e._fillFrameStatsBasic(r,n,a),e.fire("frameupdate",a);let o=false;i?(o=!e.xr?.update(i),e.graphicsDevice.defaultFramebuffer=i.session.renderState.baseLayer.framebuffer):e.graphicsDevice.defaultFramebuffer=null,o||(e.update(n),e.fire("framerender"),(e.autoRender||e.renderNextFrame)&&(e.render(),e.renderNextFrame=false),e.fire("frameend")),e._inFrameUpdate=false,e._destroyRequested&&e.destroy();}};class Te{constructor(){this.componentSystems=[],this.resourceHandlers=[];}}let Tt=new eQ;class Ti{constructor(e,t,i){this.scene=e,this.light=t,this.store(),t.numCascades=1,this.scene.clusteredLightingEnabled&&!i.shadowsEnabled&&(t.castShadows=false),t.type!==uI&&(t._node.getWorldTransform(),t.getBoundingSphere(Tt),this.lightBounds=new ej,this.lightBounds.center.copy(Tt.center),this.lightBounds.halfExtents.set(Tt.radius,Tt.radius,Tt.radius));}store(){this.mask=this.light.mask,this.shadowUpdateMode=this.light.shadowUpdateMode,this.enabled=this.light.enabled,this.intensity=this.light.intensity,this.rotation=this.light._node.getLocalRotation().clone(),this.numCascades=this.light.numCascades,this.castShadows=this.light._castShadows;}restore(){let e=this.light;e.mask=this.mask,e.shadowUpdateMode=this.shadowUpdateMode,e.enabled=this.enabled,e.intensity=this.intensity,e._node.setLocalRotation(this.rotation),e.numCascades=this.numCascades,e._castShadows=this.castShadows;}startBake(){this.light.enabled=true,this.light._destroyShadowMap(),this.light.beginFrame();}endBake(e){let t=this.light;t.enabled=false,t.shadowMap&&(t.shadowMap.cached&&e.add(t,t.shadowMap),t.shadowMap=null);}}let Ts=new eN;class Tr extends Ti{constructor(e,t){super(e.scene,t,e.lightingParams);}get numVirtualLights(){return this.light.type===uI?this.light.bakeNumSamples:1}prepareVirtualLight(e,t){let i=this.light;if(i._node.setLocalRotation(this.rotation),e>0){let s=i.bakeArea;St.circlePointDeterministic(Ts,e,t),Ts.mulScalar(.5*s),i._node.rotateLocal(Ts.x,0,Ts.y);}i._node.getWorldTransform(),i.intensity=Math.pow(Math.pow(this.intensity,2.2)/t,.45454545454545453);}}let Ta=new eM;class Tn extends Ti{constructor(e){let t=e.scene,i=new x1("AmbientLight");i.addComponent("light",{type:"directional",affectDynamic:true,affectLightmapped:false,bake:true,bakeNumSamples:t.ambientBakeNumSamples,castShadows:true,normalOffsetBias:.05,shadowBias:.2,shadowDistance:1,shadowResolution:2048,shadowType:uX,color:eb.WHITE,intensity:1,bakeDir:false}),super(t,i.light.light,e.lightingParams);}get numVirtualLights(){return this.light.bakeNumSamples}prepareVirtualLight(e,t){St.spherePointDeterministic(Ta,e,t,0,this.scene.ambientBakeSpherePart),this.light._node.lookAt(Ta.mulScalar(-1)),this.light._node.rotateLocal(90,0,0);let i=Math.pow(2*Math.PI*this.scene.ambientBakeSpherePart,2.2);this.light.intensity=Math.pow(i/t,.45454545454545453);}}class To{constructor(e,t=null){this.node=e,this.component=e.render||e.model,t=t||this.component.meshInstances,this.store(),this.meshInstances=t,this.bounds=null,this.renderTargets=[];}store(){this.castShadows=this.component.castShadows;}restore(){this.component.castShadows=this.castShadows;}}let Tl={glslBilateralDeNoisePS:`
float normpdf3(in vec3 v, in float sigma) {
return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma;
}
vec3 decodeRGBM(vec4 rgbm) {
vec3 color = (8.0 * rgbm.a) * rgbm.rgb;
return color * color;
}
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
vec4 encodeRGBM(vec3 color) {
vec4 encoded;
encoded.rgb = pow(color.rgb, vec3(0.5));
encoded.rgb *= 1.0 / 8.0;
encoded.a = saturate( max( max( encoded.r, encoded.g ), max( encoded.b, 1.0 / 255.0 ) ) );
encoded.a = ceil(encoded.a * 255.0) / 255.0;
encoded.rgb /= encoded.a;
return encoded;
}
vec3 decode(vec4 pixel) {
#if HDR
return pixel.rgb;
#else
return decodeRGBM(pixel);
#endif
}
bool isUsed(vec4 pixel) {
#if HDR
return any(greaterThan(pixel.rgb, vec3(0.0)));
#else
return pixel.a > 0.0;
#endif
}
varying vec2 vUv0;
uniform sampler2D source;
uniform vec2 pixelOffset;
uniform vec2 sigmas;
uniform float bZnorm;
uniform float kernel[{MSIZE}];
void main(void) {
vec4 pixel = texture2DLod(source, vUv0, 0.0);
if (!isUsed(pixel)) {
gl_FragColor = pixel;
return ;
}
float sigma = sigmas.x;
float bSigma = sigmas.y;
vec3 pixelHdr = decode(pixel);
vec3 accumulatedHdr = vec3(0.0);
float accumulatedFactor = 0.000001;
const int kSize = ({MSIZE} - 1) / 2;
for (int i = -kSize; i <= kSize; ++i) {
for (int j = -kSize; j <= kSize; ++j) {
vec2 coord = vUv0 + vec2(float(i), float(j)) * pixelOffset;
vec4 pix = texture2DLod(source, coord, 0.0);
if (isUsed(pix)) {
vec3 hdr = decode(pix);
float factor = kernel[kSize + j] * kernel[kSize + i];
factor *= normpdf3(hdr - pixelHdr, bSigma) * bZnorm;
accumulatedHdr += factor * hdr;
accumulatedFactor += factor;
}
}
}
vec3 finalHDR = accumulatedHdr / accumulatedFactor;
#if HDR
gl_FragColor = vec4(finalHDR, 1.0);
#else
gl_FragColor = encodeRGBM(finalHDR);
#endif
}
`,glslDilatePS:`
varying vec2 vUv0;
uniform sampler2D source;
uniform vec2 pixelOffset;
bool isUsed(vec4 pixel) {
#if HDR
return any(greaterThan(pixel.rgb, vec3(0.0)));
#else
return pixel.a > 0.0;
#endif
}
void main(void) {
vec4 c = texture2DLod(source, vUv0, 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 - pixelOffset, 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(0, -pixelOffset.y), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(-pixelOffset.x, 0), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(pixelOffset.x, 0), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(0, pixelOffset.y), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + pixelOffset, 0.0);
gl_FragColor = c;
}
`},Th={wgslBilateralDeNoisePS:`
fn normpdf3(v: vec3f, sigma: f32) -> f32 {
return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma;
}
fn decodeRGBM(rgbm: vec4f) -> vec3f {
let color = (8.0 * rgbm.a) * rgbm.rgb;
return color * color;
}
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
fn encodeRGBM(color: vec3f) -> vec4f {
var encoded: vec4f;
let rgb_processed = pow(color.rgb, vec3f(0.5)) * (1.0 / 8.0);
encoded = vec4f(rgb_processed, 0.0);
let max_g_b = max( encoded.g, max( encoded.b, 1.0 / 255.0 ) );
let max_rgb = max( encoded.r, max_g_b );
encoded.a = clamp(max_rgb, 0.0, 1.0);
encoded.a = ceil(encoded.a * 255.0) / 255.0;
encoded = vec4f(encoded.rgb / encoded.a, encoded.a);
return encoded;
}
fn decode(pixel: vec4f) -> vec3f {
#if HDR
return pixel.rgb;
#else
return decodeRGBM(pixel);
#endif
}
fn isUsed(pixel: vec4f) -> bool {
#if HDR
return any(pixel.rgb > vec3f(0.0));
#else
return pixel.a > 0.0;
#endif
}
varying vUv0: vec2f;
var source: texture_2d<f32>;
var sourceSampler: sampler;
uniform kernel: array<f32, {MSIZE}>;
uniform pixelOffset: vec2f;
uniform sigmas: vec2f;
uniform bZnorm: f32;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let pixel = textureSampleLevel(source, sourceSampler, input.vUv0, 0.0);
if (!isUsed(pixel)) {
output.color = pixel;
return output;
}
let sigma = uniform.sigmas.x;
let bSigma = uniform.sigmas.y;
let pixelHdr = decode(pixel);
var accumulatedHdr = vec3f(0.0);
var accumulatedFactor = 0.000001;
const kSize = ({MSIZE} - 1) / 2;
for (var i: i32 = -kSize; i <= kSize; i = i + 1) {
for (var j: i32 = -kSize; j <= kSize; j = j + 1) {
let coord = input.vUv0 + vec2f(f32(i), f32(j)) * uniform.pixelOffset;
let pix = textureSampleLevel(source, sourceSampler, coord, 0.0);
if (isUsed(pix)) {
let hdr = decode(pix);
var factor = uniform.kernel[u32(kSize + j)].element * uniform.kernel[u32(kSize + i)].element;
factor = factor * normpdf3(hdr - pixelHdr, bSigma) * uniform.bZnorm;
accumulatedHdr = accumulatedHdr + factor * hdr;
accumulatedFactor = accumulatedFactor + factor;
}
}
}
let finalHDR = accumulatedHdr / accumulatedFactor;
#if HDR
output.color = vec4f(finalHDR, 1.0);
#else
output.color = encodeRGBM(finalHDR);
#endif
return output;
}
`,wgslDilatePS:`
varying vUv0: vec2f;
var source: texture_2d<f32>;
var sourceSampler: sampler;
uniform pixelOffset: vec2f;
fn isUsed(pixel: vec4f) -> bool {
#ifdef HDR
return any(pixel.rgb > vec3f(0.0));
#else
return pixel.a > 0.0;
#endif
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var c: vec4f = textureSampleLevel(source, sourceSampler, input.vUv0, 0.0);
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 - uniform.pixelOffset, 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(0.0, -uniform.pixelOffset.y), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(uniform.pixelOffset.x, -uniform.pixelOffset.y), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(-uniform.pixelOffset.x, 0.0), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(uniform.pixelOffset.x, 0.0), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(-uniform.pixelOffset.x, uniform.pixelOffset.y), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(0.0, uniform.pixelOffset.y), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + uniform.pixelOffset, 0.0), c, isUsed(c));
var output: FragmentOutput;
output.color = c;
return output;
}
`};class Tc{constructor(e){this.shaderDilate=[],this.shaderDenoise=[],this.device=e,mr.get(this.device,rb).add(Tl),mr.get(this.device,rw).add(Th),this.constantTexSource=e.scope.resolve("source"),this.constantPixelOffset=e.scope.resolve("pixelOffset"),this.pixelOffset=new Float32Array(2),this.sigmas=null,this.constantSigmas=null,this.kernel=null;}setSourceTexture(e){this.constantTexSource.setValue(e);}prepare(e,t){this.pixelOffset[0]=1/e,this.pixelOffset[1]=1/t,this.constantPixelOffset.setValue(this.pixelOffset);}prepareDenoise(e,t,i){let s=+!i;if(!this.shaderDenoise[s]){let e=new Map;e.set("{MSIZE}",15),i&&e.set("HDR",""),this.shaderDenoise[s]=mo.createShader(this.device,{uniqueName:`lmBilateralDeNoise-${i?"hdr":"rgbm"}`,attributes:{vertex_position:sT},vertexGLSL:mr.get(this.device,rb).get("fullscreenQuadVS"),vertexWGSL:mr.get(this.device,rw).get("fullscreenQuadVS"),fragmentGLSL:mr.get(this.device,rb).get("glslBilateralDeNoisePS"),fragmentWGSL:mr.get(this.device,rw).get("wgslBilateralDeNoisePS"),fragmentDefines:e}),this.sigmas=new Float32Array(2),this.constantSigmas=this.device.scope.resolve("sigmas"),this.constantKernel=this.device.scope.resolve("kernel[0]"),this.bZnorm=this.device.scope.resolve("bZnorm");}this.sigmas[0]=e,this.sigmas[1]=t,this.constantSigmas.setValue(this.sigmas),this.evaluateDenoiseUniforms(e,t);}getDenoise(e){return this.shaderDenoise[+!e]}getDilate(e,t){let i=+!t;if(!this.shaderDilate[i]){let s=t?"#define HDR\n":"";this.shaderDilate[i]=mo.createShader(e,{uniqueName:`lmDilate-${t?"hdr":"rgbm"}`,attributes:{vertex_position:sT},vertexGLSL:mr.get(this.device,rb).get("fullscreenQuadVS"),vertexWGSL:mr.get(this.device,rw).get("fullscreenQuadVS"),fragmentGLSL:s+mr.get(this.device,rb).get("glslDilatePS"),fragmentWGSL:s+mr.get(this.device,rw).get("wgslDilatePS")});}return this.shaderDilate[i]}evaluateDenoiseUniforms(e,t){function i(e,t){return .39894*Math.exp(-0.5*e*e/(t*t))/t}this.kernel=this.kernel||new Float32Array(15);let s=this.kernel,r=Math.floor(7);for(let t=0;t<=r;++t){let a=i(t,e);s[r+t]=a,s[r-t]=a;}this.constantKernel.setValue(this.kernel);let a=1/i(0,t);this.bZnorm.setValue(a);}}class Td extends l2{constructor(e,t,i,s,r,a){super(e),this.viewBindGroups=[],this.renderer=t,this.camera=i,this.worldClusters=s,this.receivers=r,this.lightArray=a;}destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;}execute(){this.device;let{renderer:e,camera:t,receivers:i,renderTarget:s,worldClusters:r,lightArray:a}=this;e.renderForwardLayer(t,s,null,void 0,pc,this.viewBindGroups,{meshInstances:i,splitLights:a,lightClusters:r});}}let Tu=new eM;class Tf{constructor(e,t,i,s,r){this.device=e,this.root=t,this.scene=i,this.renderer=s,this.assets=r,this.shadowMapCache=s.shadowMapCache,this._tempSet=new Set,this._initCalled=false,this.passMaterials=[],this.ambientAOMaterial=null,this.fog="",this.ambientLight=new eb,this.renderTargets=new Map,this.stats={renderPasses:0,lightmapCount:0,totalRenderTime:0,forwardTime:0,fboTime:0,shadowMapTime:0,compileTime:0,shadersLinked:0};}destroy(){mI.decRef(this.blackTex),this.blackTex=null,mI.destroy(),this.device=null,this.root=null,this.scene=null,this.renderer=null,this.assets=null,this.camera?.destroy(),this.camera=null;}initBake(e){if(this.bakeHDR=this.scene.lightmapPixelFormat!==id,!this._initCalled){this._initCalled=true,this.lightmapFilters=new Tc(e),this.constantBakeDir=e.scope.resolve("bakeDir"),this.materials=[],this.blackTex=new ns(this.device,{width:4,height:4,format:id,type:ri,name:"lightmapBlack"}),mI.incRef(this.blackTex);let t=new m3;t.clearColor.set(0,0,0,0),t.clearColorBuffer=true,t.clearDepthBuffer=false,t.clearStencilBuffer=false,t.frustumCulling=false,t.projection=fm,t.aspectRatio=1,t.node=new _c,this.camera=t,this.camera.shaderParams.gammaCorrection=fP,this.camera.shaderParams.toneMapping=fD;}if(this.scene.clusteredLightingEnabled){let t=new g3(e.supportsAreaLights,e.maxTextureSize,()=>{});this.lightingParams=t;let i=this.scene.lighting;t.shadowsEnabled=i.shadowsEnabled,t.shadowAtlasResolution=i.shadowAtlasResolution,t.cookiesEnabled=i.cookiesEnabled,t.cookieAtlasResolution=i.cookieAtlasResolution,t.areaLightsEnabled=i.areaLightsEnabled,t.cells=new eM(3,3,3),t.maxLightsPerCell=4,this.worldClusters=new _L(e),this.worldClusters.name="ClusterLightmapper";}}finishBake(e){function t(e){mI.decRef(e.colorBuffer),e.destroy();}this.materials=[],this.renderTargets.forEach(e=>{t(e);}),this.renderTargets.clear(),e.forEach(e=>{e.renderTargets.forEach(e=>{t(e);}),e.renderTargets.length=0;}),this.ambientAOMaterial=null,this.worldClusters&&(this.worldClusters.destroy(),this.worldClusters=null);}createMaterialForPass(e,t,i){let s=new yo;return s.name=`lmMaterial-pass:${t}-ambient:${i}`,s.setDefine("UV1LAYOUT",""),s.setDefine("LIT_LIGHTMAP_BAKING",""),0===t?(s.setDefine("LIT_LIGHTMAP_BAKING_COLOR",""),i?s.setDefine("LIT_LIGHTMAP_BAKING_ADD_AMBIENT",""):s.ambient=new eb(0,0,0),this.bakeHDR||s.setDefine("LIGHTMAP_RGBM",""),s.lightMap=this.blackTex):(s.setDefine("LIT_LIGHTMAP_BAKING_DIR",""),s.setDefine("STD_LIGHTMAP_DIR","")),s.cull=tY,s.forceUv1=true,s.update(),s}createMaterials(e,t,i){for(let e=0;e<i;e++)this.passMaterials[e]||(this.passMaterials[e]=this.createMaterialForPass(t,e,false));this.ambientAOMaterial||(this.ambientAOMaterial=this.createMaterialForPass(t,0,true),this.ambientAOMaterial.onUpdateShader=function(e){return e.litOptions.lightMapWithoutAmbient=true,e.litOptions.separateAmbient=true,e});}createTexture(e,t){return new ns(this.device,{width:e,height:e,format:this.scene.lightmapPixelFormat,mipmaps:false,type:this.bakeHDR?rt:ri,minFilter:tK,magFilter:tK,addressU:tr,addressV:tr,name:t})}collectModels(e,t,i){let s;if(e.enabled){if(e.model?.model&&e.model?.enabled&&(i&&i.push(new To(e)),e.model.lightmapped&&t&&(s=e.model.model.meshInstances)),e.render?.enabled&&(i&&i.push(new To(e)),e.render.lightmapped&&t&&(s=e.render.meshInstances)),s){let i=true;for(let e=0;e<s.length;e++)if(!s[e].mesh.vertexBuffer.format.hasUv1){i=false;break}if(i){let i=[];for(let r=0;r<s.length;r++){let a=s[r].mesh;this._tempSet.has(a)?t.push(new To(e,[s[r]])):i.push(s[r]),this._tempSet.add(a);}this._tempSet.clear(),i.length>0&&t.push(new To(e,i));}}for(let s=0;s<e._children.length;s++)this.collectModels(e._children[s],t,i);}}prepareShadowCasters(e){let t=[];for(let i=0;i<e.length;i++){let s=e[i].component;if(s.castShadows=s.castShadowsLightmap,s.castShadowsLightmap){let s=e[i].meshInstances;for(let e=0;e<s.length;e++)s[e].visibleThisFrame=true,t.push(s[e]);}}return t}updateTransforms(e){for(let t=0;t<e.length;t++){let i=e[t].meshInstances;for(let e=0;e<i.length;e++)i[e].node.getWorldTransform();}}calculateLightmapSize(e){let t,i,s,r=this.scene.lightmapSizeMultiplier||16;e.model?(s=e.model.lightmapSizeMultiplier,e.model.asset?(t=this.assets.get(e.model.asset).data).area&&(i=t.area):e.model._area&&(t=e.model)._area&&(i=t._area)):e.render&&(s=e.render.lightmapSizeMultiplier,"asset"!==e.render.type&&e.render._area&&(t=e.render)._area&&(i=t._area));let a={x:1,y:1,z:1,uv:1};i&&(a.x=i.x,a.y=i.y,a.z=i.z,a.uv=i.uv);let n=s||1;a.x*=n,a.y*=n,a.z*=n;let o=e.render||e.model,l=this.computeNodeBounds(o.meshInstances);Tu.copy(l.halfExtents);let h=a.x*Tu.y*Tu.z+a.y*Tu.x*Tu.z+a.z*Tu.x*Tu.y;return h/=a.uv,h=Math.sqrt(h),Math.min(eA.nextPowerOfTwo(h*r),this.scene.lightmapMaxResolution||2048)}setLightmapping(e,t,i,s){for(let r=0;r<e.length;r++){let a=e[r],n=a.meshInstances;for(let e=0;e<n.length;e++){let r=n[e];if(r.setLightmapped(t),t){s&&(r._shaderDefs|=s),r.mask=pl;for(let e=0;e<i;e++){let t=a.renderTargets[e].colorBuffer;t.minFilter=tZ,t.magFilter=tZ,r.setRealtimeLightmap(mV.lightmapParamNames[e],t);}}}}}bake(e,t=pI){let i=this.device,s=em();this.scene._updateSkyMesh(),this.stats.renderPasses=0,this.stats.shadowMapTime=0,this.stats.forwardTime=0;let r=i._shaderStats.linked,a=i._renderTargetCreationTime,n=i._shaderStats.compileTime,o=[],l=[];if(e){for(let t=0;t<e.length;t++)this.collectModels(e[t],o,null);this.collectModels(this.root,null,l);}else this.collectModels(this.root,o,l);if(o.length>0){this.renderer.shadowRenderer.frameUpdate();let e=t===pI?2:1;this.setLightmapping(o,false,e),this.initBake(i),this.bakeInternal(e,o,l);let s=f5;t===pI&&(s|=f8),this.scene.ambientBake&&(s|=pt),this.setLightmapping(o,true,e,s),this.finishBake(o);}let h=em();this.stats.totalRenderTime=h-s,this.stats.shadersLinked=i._shaderStats.linked-r,this.stats.compileTime=i._shaderStats.compileTime-n,this.stats.fboTime=i._renderTargetCreationTime-a,this.stats.lightmapCount=o.length;}allocateTextures(e,t){for(let i=0;i<e.length;i++){let s=e[i],r=this.calculateLightmapSize(s.node);for(let e=0;e<t;e++){let t=this.createTexture(r,`lightmapper_lightmap_${i}`);mI.incRef(t),s.renderTargets[e]=new nM({colorBuffer:t,depth:false});}if(!this.renderTargets.has(r)){let e=this.createTexture(r,`lightmapper_temp_lightmap_${r}`);mI.incRef(e),this.renderTargets.set(r,new nM({colorBuffer:e,depth:false}));}}}prepareLightsToBake(e,t){if(this.scene.ambientBake){let e=new Tn(this);t.push(e);}let i=this.renderer.lights;for(let s=0;s<i.length;s++){let r=i[s],a=new Tr(this,r);e.push(a),r.enabled&&(r.mask&ph)!=0&&(r.mask=ph|pl|po,r.shadowUpdateMode=r.type===uI?pn:pa,t.push(a));}t.sort();}restoreLights(e){for(let t=0;t<e.length;t++)e[t].restore();}setupScene(){this.ambientLight.copy(this.scene.ambientLight),this.scene.ambientBake||this.scene.ambientLight.set(0,0,0),this.renderer.setSceneConstants(),this.device.scope.resolve("ambientBakeOcclusionContrast").setValue(this.scene.ambientBakeOcclusionContrast),this.device.scope.resolve("ambientBakeOcclusionBrightness").setValue(this.scene.ambientBakeOcclusionBrightness);}restoreScene(){this.scene.ambientLight.copy(this.ambientLight);}computeNodeBounds(e){let t=new ej;if(e.length>0){t.copy(e[0].aabb);for(let i=1;i<e.length;i++)t.add(e[i].aabb);}return t}computeNodesBounds(e){for(let t=0;t<e.length;t++){let i=e[t].meshInstances;e[t].bounds=this.computeNodeBounds(i);}}computeBounds(e){let t=new ej;for(let i=0;i<e.length;i++){t.copy(e[0].aabb);for(let i=1;i<e.length;i++)t.add(e[i].aabb);}return t}backupMaterials(e){for(let t=0;t<e.length;t++)this.materials[t]=e[t].material;}restoreMaterials(e){for(let t=0;t<e.length;t++)e[t].material=this.materials[t];}lightCameraPrepare(e,t){let i,s=t.light;return s.type===uM&&((i=s.getRenderData(null,0).shadowCamera)._node.setPosition(s._node.getPosition()),i._node.setRotation(s._node.getRotation()),i._node.rotateLocal(-90,0,0),i.projection=fp,i.nearClip=s.attenuationEnd/1e3,i.farClip=s.attenuationEnd,i.aspectRatio=1,i.fov=2*s._outerConeAngle,this.renderer.updateCameraFrustum(i)),i}lightCameraPrepareAndCull(e,t,i,s){let r=e.light,a=true;if(r.type===uI){Tu.copy(s.center),Tu.y+=s.halfExtents.y,this.camera.node.setPosition(Tu),this.camera.node.setEulerAngles(-90,0,0),this.camera.nearClip=0,this.camera.farClip=2*s.halfExtents.y;let e=Math.max(s.halfExtents.x,s.halfExtents.z);this.camera.orthoHeight=e;}else e.lightBounds.intersects(t.bounds)||(a=false);if(r.type===uM){let e=false,s=t.meshInstances;for(let t=0;t<s.length;t++)if(s[t]._isVisible(i)){e=true;break}e||(a=false);}return a}setupLightArray(e,t){e[uI].length=0,e[uD].length=0,e[uM].length=0,e[t.type][0]=t,t.visibleThisFrame=true;}renderShadowMap(e,t,i,s){let r=s.light,a=this.scene.clusteredLightingEnabled,n=r.castShadows&&(!a||this.scene.lighting.shadowsEnabled);if(!t&&n)if(r.shadowMap||a||(r.shadowMap=this.shadowMapCache.get(this.device,r)),r.type===uI){this.renderer._shadowRendererDirectional.cull(r,e,this.camera,i);let t=this.renderer._shadowRendererDirectional.getLightRenderPass(r,this.camera);t?.render();}else {if(this.device.isWebGPU)return true;this.renderer._shadowRendererLocal.cull(r,e,i),this.renderer.shadowRenderer.render(r,this.camera,false);}return true}postprocessTextures(e,t,i){let s,r=this.lightmapFilters.getDilate(e,this.bakeHDR),a=this.scene.lightmapFilterEnabled;a&&(this.lightmapFilters.prepareDenoise(this.scene.lightmapFilterRange,this.scene.lightmapFilterSmoothness,this.bakeHDR),s=this.lightmapFilters.getDenoise(this.bakeHDR)),e.setBlendState(nu.NOBLEND),e.setDepthState(nm.NODEPTH),e.setStencilState(null,null);for(let n=0;n<t.length;n++){let o=t[n];for(let t=0;t<i;t++){let i=o.renderTargets[t],n=i.colorBuffer,l=this.renderTargets.get(n.width),h=l.colorBuffer;this.lightmapFilters.prepare(n.width,n.height);for(let o=0;o<1;o++)this.lightmapFilters.setSourceTexture(n),mg(e,l,a&&0===t&&0===o?s:r),this.lightmapFilters.setSourceTexture(h),mg(e,i,r);}}}bakeInternal(e,t,i){let s,r,a,n,o,l,h=this.scene,c=h.layers,d=this.device,u=h.clusteredLightingEnabled;this.createMaterials(d,h,e),this.setupScene(),c._update(),this.computeNodesBounds(t),this.allocateTextures(t,e),this.renderer.collectLights(c);let f=[],p=[];this.prepareLightsToBake(f,p),this.updateTransforms(i);let m=this.prepareShadowCasters(i);this.renderer.updateCpuSkinMatrices(m),this.renderer.gpuUpdate(m);let _=this.computeBounds(m);for(s=0;s<t.length;s++)for(r=0,a=t[s].meshInstances;r<a.length;r++)(n=a[r]).setLightmapped(false),n.mask=ph,n.setRealtimeLightmap(mV.lightmapParamNames[0],this.blackTex),n.setRealtimeLightmap(mV.lightmapParamNames[1],this.blackTex);for(r=0;r<p.length;r++)p[r].light.enabled=false;let g=[[],[],[]],v=false;for(s=0;s<p.length;s++){let i=p[s],f=i instanceof Tn,S=i.light.type===uI,y=i.numVirtualLights;e>1&&y>1&&i.light.bakeDir&&(y=1);for(let s=0;s<y;s++){y>1&&i.prepareVirtualLight(s,y),i.startBake();let p=false,x=this.lightCameraPrepare(d,i);for(l=0;l<t.length;l++){let T=t[l];if(a=T.meshInstances,!this.lightCameraPrepareAndCull(i,T,x,_))continue;this.setupLightArray(g,i.light);let E=S?[]:[i.light];for(u&&this.renderer.lightTextureAtlas.update(E,this.lightingParams),p=this.renderShadowMap(c,p,m,i),u&&this.worldClusters.update(E,this.lightingParams),this.backupMaterials(a),o=0;o<e&&(!(o>0)||!(s>0))&&(!f||!(o>0));o++){let e=T.renderTargets[o],t=T.renderTargets[o].colorBuffer.width,l=this.renderTargets.get(t),c=l.colorBuffer;0===o?v=h.updateShaders:v&&(h.updateShaders=true);let p=this.passMaterials[o];for(f&&s+1===y&&0===o&&(p=this.ambientAOMaterial),r=0;r<a.length;r++)a[r].material=p;if(this.renderer.updateShaders(a),1===o&&this.constantBakeDir.setValue(+!!i.light.bakeDir),d.isWebGPU){let e=new Td(d,this.renderer,this.camera,u?this.worldClusters:null,a,g);e.init(l),e.render(),e.destroy();}else this.renderer.setCamera(this.camera,l,true),u&&this.worldClusters.activate(),this.renderer._forwardTime=0,this.renderer._shadowMapTime=0,this.renderer.renderForward(this.camera,l,a,g,pc),d.updateEnd();for(T.renderTargets[o]=l,this.renderTargets.set(t,e),r=0;r<a.length;r++)(n=a[r]).setRealtimeLightmap(mV.lightmapParamNames[o],c),n._shaderDefs|=f5;}this.restoreMaterials(a);}i.endBake(this.shadowMapCache);}}for(this.postprocessTextures(d,t,e),l=0;l<i.length;l++)i[l].restore();this.restoreLights(f),this.restoreScene(),u||this.shadowMapCache.clear();}}class Tp extends eo{static{this.order=0;}constructor(e,t){super(),this.system=e,this.entity=t,this.system.schema&&!this._accessorsBuilt&&this.buildAccessors(this.system.schema),this.on("set",function(e,t,i){this.fire(`set_${e}`,e,t,i);}),this.on("set_enabled",this.onSetEnabled,this);}static _buildAccessors(e,t){t.forEach(t=>{let i="object"==typeof t?t.name:t;Object.defineProperty(e,i,{get:function(){return this.data[i]},set:function(e){let t=this.data,s=t[i];t[i]=e,this.fire("set",i,s,e);},configurable:true});}),e._accessorsBuilt=true;}buildAccessors(e){Tp._buildAccessors(this,e);}onSetEnabled(e,t,i){t!==i&&this.entity.enabled&&(i?this.onEnable():this.onDisable());}onEnable(){}onDisable(){}onPostStateChange(){}get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){}get enabled(){return true}}class Tm extends eo{constructor(e){super(),this.app=e,this.store={},this.schema=[];}addComponent(e,t={}){let i=new this.ComponentType(this,e),s=new this.DataType;return this.store[e.getGuid()]={entity:e,data:s},e[this.id]=i,e.c[this.id]=i,this.initializeComponentData(i,t,[]),this.fire("add",e,i),i}removeComponent(e){let t=this.id,i=this.store[e.getGuid()],s=e.c[t];s.fire("beforeremove"),this.fire("beforeremove",e,s),delete this.store[e.getGuid()],e[t]=void 0,delete e.c[t],this.fire("remove",e,i.data);}cloneComponent(e,t){let i=this.store[e.getGuid()];return this.addComponent(t,i.data)}initializeComponentData(e,t={},i){for(let s=0,r=i.length;s<r;s++){let r,a,n=i[s];"object"==typeof n?(r=n.name,a=n.type):(r=n,a=void 0);let o=t[r];void 0!==o?(void 0!==a&&(o=function(e,t){if(!e)return e;switch(t){case "rgb":if(e instanceof eb)return e.clone();return new eb(e[0],e[1],e[2]);case "rgba":if(e instanceof eb)return e.clone();return new eb(e[0],e[1],e[2],e[3]);case "vec2":if(e instanceof eN)return e.clone();return new eN(e[0],e[1]);case "vec3":if(e instanceof eM)return e.clone();return new eM(e[0],e[1],e[2]);case "vec4":if(e instanceof eF)return e.clone();return new eF(e[0],e[1],e[2],e[3]);case "boolean":case "number":case "string":case "entity":return e;default:throw Error(`Could not convert unhandled type: ${t}`)}}(o,a)),e[r]=o):e[r]=e.data[r];}e.enabled&&e.entity.enabled&&e.onEnable();}getPropertiesOfType(e){let t=[];return (this.schema||[]).forEach(i=>{i&&"object"==typeof i&&i.type===e&&t.push(i);}),t}destroy(){this.off();}}let T_=0,Tg=1,Tv=2;class TS{constructor(){this._left=1/0,this._right=-1/0,this._len=0,this._recip=0,this._p0=0,this._p1=0,this._t=0,this._hermite={valid:false,p0:0,m0:0,p1:0,m1:0};}update(e,t){if(e<this._left||e>=this._right){let i=t.length;if(i)if(e<t[0])this._left=-1/0,this._right=t[0],this._len=0,this._recip=0,this._p0=this._p1=0;else if(e>=t[i-1])this._left=t[i-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=i-1;else {let i=this._findKey(e,t);this._left=t[i],this._right=t[i+1],this._len=this._right-this._left;let s=1/this._len;this._recip=isFinite(s)?s:0,this._p0=i,this._p1=i+1;}else this._left=-1/0,this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=0;}this._t=0===this._recip?0:(e-this._left)*this._recip,this._hermite.valid=false;}_findKey(e,t){let i=0;for(;e>=t[i+1];)i++;return i}eval(e,t,i){let s=i._data,r=i._components,a=this._p0*r;if(t===T_)for(let t=0;t<r;++t)e[t]=s[a+t];else {let i=this._t,n=this._p1*r;switch(t){case Tg:for(let t=0;t<r;++t)e[t]=eA.lerp(s[a+t],s[n+t],i);break;case Tv:{let t=this._hermite;if(!t.valid){let e=i*i,s=i+i,r=1-i,a=r*r;t.valid=true,t.p0=(1+s)*a,t.m0=i*a,t.p1=e*(3-s),t.m1=e*(i-1);}let a=(3*this._p0+1)*r,n=(3*this._p0+2)*r,o=(3*this._p1+1)*r,l=(3*this._p1+0)*r;for(let i=0;i<r;++i)e[i]=t.p0*s[a+i]+t.m0*s[n+i]*this._len+t.p1*s[o+i]+t.m1*s[l+i]*this._len;}}}}}class Ty{constructor(e){this._name=`${e.name}Snapshot`,this._time=-1,this._cache=[],this._results=[];for(let t=0;t<e._inputs.length;++t)this._cache[t]=new TS;let t=e._curves,i=e._outputs;for(let e=0;e<t.length;++e){let s=i[t[e]._output],r=[];for(let e=0;e<s._components;++e)r[e]=0;this._results[e]=r;}}}class Tx{static{this.eventFrame={start:0,end:0,residual:0};}constructor(e,t,i,s,r,a){this._name=e.name,this._track=e,this._snapshot=new Ty(e),this._playing=s,this._time=t,this._speed=i,this._loop=r,this._blendWeight=1,this._blendOrder=0,this._eventHandler=a,this.alignCursorToCurrentTime();}set name(e){this._name=e;}get name(){return this._name}set track(e){this._track=e,this._snapshot=new Ty(e);}get track(){return this._track}get snapshot(){return this._snapshot}set time(e){this._time=e,this.alignCursorToCurrentTime();}get time(){return this._time}set speed(e){let t=Math.sign(e)!==Math.sign(this._speed);this._speed=e,t&&this.alignCursorToCurrentTime();}get speed(){return this._speed}set loop(e){this._loop=e;}get loop(){return this._loop}set blendWeight(e){this._blendWeight=e;}get blendWeight(){return this._blendWeight}set blendOrder(e){this._blendOrder=e;}get blendOrder(){return this._blendOrder}set eventCursor(e){this._eventCursor=e;}get eventCursor(){return this._eventCursor}get eventCursorEnd(){return this.isReverse?0:this._track.events.length-1}get nextEvent(){return this._track.events[this._eventCursor]}get isReverse(){return this._speed<0}nextEventAheadOfTime(e){return !!this.nextEvent&&(this.isReverse?this.nextEvent.time<=e:this.nextEvent.time>=e)}nextEventBehindTime(e){return !!this.nextEvent&&(e===this.track.duration?this.isReverse?this.nextEvent.time>=e:this.nextEvent.time<=e:this.isReverse?this.nextEvent.time>e:this.nextEvent.time<e)}resetEventCursor(){this._eventCursor=this.isReverse?this._track.events.length-1:0;}moveEventCursor(){this._eventCursor+=this.isReverse?-1:1,this._eventCursor>=this.track.events.length?this._eventCursor=0:this._eventCursor<0&&(this._eventCursor=this.track.events.length-1);}clipFrameTime(e){let t=Tx.eventFrame;t.start=0,t.end=e,t.residual=0,this.isReverse?e<0&&(t.start=this.track.duration,t.end=0,t.residual=e+this.track.duration):e>this.track.duration&&(t.start=0,t.end=this.track.duration,t.residual=e-this.track.duration);}alignCursorToCurrentTime(){for(this.resetEventCursor();this.nextEventBehindTime(this._time)&&this._eventCursor!==this.eventCursorEnd;)this.moveEventCursor();}fireNextEvent(){this._eventHandler.fire(this.nextEvent.name,{track:this.track,...this.nextEvent}),this.moveEventCursor();}fireNextEventInFrame(e,t){return !!(this.nextEventAheadOfTime(e)&&this.nextEventBehindTime(t))&&(this.fireNextEvent(),true)}activeEventsForFrame(e,t){let i=Tx.eventFrame;this.clipFrameTime(t);let s=this.eventCursor;for(;this.fireNextEventInFrame(e,i.end)&&s!==this.eventCursor;);this.loop&&Math.abs(i.residual)>0&&this.activeEventsForFrame(i.start,i.residual);}progressForTime(e){return e*this._speed/this._track.duration}_update(e){if(this._playing){let t=this._time,i=this._track.duration,s=this._speed,r=this._loop;this._track.events.length>0&&i>0&&this.activeEventsForFrame(t,t+s*e),t+=s*e,s>=0?t>i&&(r?t=t%i||0:(t=this._track.duration,this.pause())):t<0&&(r?t=i+(t%i||0):(t=0,this.pause())),this._time=t;}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot);}play(){this._playing=true,this._time=0;}stop(){this._playing=false,this._time=0;}pause(){this._playing=false;}resume(){this._playing=true;}reset(){this._time=0;}}let TT="NONE",TE="PREV_STATE",TA="NEXT_STATE",Tb="PREV_STATE_NEXT_STATE",Tw="NEXT_STATE_PREV_STATE",TC="GREATER_THAN",TP="LESS_THAN",TL="GREATER_THAN_EQUAL_TO",TI="LESS_THAN_EQUAL_TO",TD="EQUAL_TO",TR="NOT_EQUAL_TO",TM="INTEGER",TO="FLOAT",TN="BOOLEAN",TF="TRIGGER",TB="1D",TU="2D_DIRECTIONAL",Tk="2D_CARTESIAN",TV="DIRECT",Tz="START",TG="END",TH="ANY",TW=[Tz,TG,TH],TX="OVERWRITE",TY="ADDITIVE";class Tq{static dot(e,t){let i=e.length,s=0;for(let r=0;r<i;++r)s+=e[r]*t[r];return s}static normalize(e){let t=Tq.dot(e,e);if(t>0){t=1/Math.sqrt(t);let i=e.length;for(let s=0;s<i;++s)e[s]*=t;}}static set(e,t,i){let s=e.length;if("quaternion"===i){let i=Tq.dot(t,t);i>0&&(i=1/Math.sqrt(i));for(let r=0;r<s;++r)e[r]=t[r]*i;}else for(let i=0;i<s;++i)e[i]=t[i];}static blendVec(e,t,i,s){let r=s?1:1-i,a=e.length;for(let s=0;s<a;++s)e[s]=e[s]*r+t[s]*i;}static blendQuat(e,t,i,s){let r=e.length,a=s?1:1-i;0>Tq.dot(e,t)&&(i=-i);for(let s=0;s<r;++s)e[s]=e[s]*a+t[s]*i;s||Tq.normalize(e);}static blend(e,t,i,s,r){"quaternion"===s?Tq.blendQuat(e,t,i,r):Tq.blendVec(e,t,i,r);}static stableSort(e,t){let i=e.length;for(let s=0;s<i-1;++s)for(let r=s+1;r<i;++r)if(t(e[r],e[s])){let t=e[s];e[s]=e[r],e[r]=t;}}}class T${static{this.TYPE_QUAT="quaternion";}static{this.TYPE_VEC3="vector3";}static{this.q1=new eH;}static{this.q2=new eH;}static{this.q3=new eH;}static{this.quatArr=[0,0,0,1];}static{this.vecArr=[0,0,0];}static{this.IDENTITY_QUAT_ARR=[0,0,0,1];}constructor(e,t){this._component=e,this.mask=new Int8Array(e.layers.length),this.weights=new Float32Array(e.layers.length),this.totalWeight=0,this.counter=0,this.layerCounter=0,this.valueType=t,this.dirty=true,this.value=t===T$.TYPE_QUAT?[0,0,0,1]:[0,0,0],this.baseValue=null,this.setter=null;}get _normalizeWeights(){return this._component.normalizeWeights}getWeight(e){return (this.dirty&&this.updateWeights(),this._normalizeWeights&&0===this.totalWeight||!this.mask[e])?0:this._normalizeWeights?this.weights[e]/this.totalWeight:eA.clamp(this.weights[e],0,1)}_layerBlendType(e){return this._component.layers[e].blendType}setMask(e,t){this.mask[e]=t,this._normalizeWeights&&(this._component.layers[e].blendType===TX&&(this.mask=this.mask.fill(0,0,e)),this.dirty=true);}updateWeights(){this.totalWeight=0;for(let e=0;e<this.weights.length;e++)this.weights[e]=this._component.layers[e].weight,this.totalWeight+=this.mask[e]*this.weights[e];this.dirty=false;}updateValue(e,t){if(0===this.counter&&(Tq.set(this.value,T$.IDENTITY_QUAT_ARR,this.valueType),this._normalizeWeights||Tq.blend(this.value,this.baseValue,1,this.valueType)),this.mask[e]&&0!==this.getWeight(e)){if(this._layerBlendType(e)!==TY||this._normalizeWeights)Tq.blend(this.value,t,this.getWeight(e),this.valueType);else if(this.valueType===T$.TYPE_QUAT){let i=T$.q1.set(this.value[0],this.value[1],this.value[2],this.value[3]),s=T$.q2.set(this.baseValue[0],this.baseValue[1],this.baseValue[2],this.baseValue[3]),r=T$.q3.set(t[0],t[1],t[2],t[3]),a=s.invert().mul(r);a.slerp(eH.IDENTITY,a,this.getWeight(e)),i.mul(a),T$.quatArr[0]=i.x,T$.quatArr[1]=i.y,T$.quatArr[2]=i.z,T$.quatArr[3]=i.w,Tq.set(this.value,T$.quatArr,this.valueType);}else T$.vecArr[0]=t[0]-this.baseValue[0],T$.vecArr[1]=t[1]-this.baseValue[1],T$.vecArr[2]=t[2]-this.baseValue[2],Tq.blend(this.value,T$.vecArr,this.getWeight(e),this.valueType,true);this.setter&&this.setter(this.value);}}unbind(){this.setter&&this.setter(this.baseValue);}}class Tj{constructor(e){this._binder=e,this._clips=[],this._inputs=[],this._outputs=[],this._targets={};}get clips(){return this._clips}addClip(e){let t=this._targets,i=this._binder,s=e.track.curves,r=e.snapshot,a=[],n=[];for(let e=0;e<s.length;++e){let o=s[e].paths;for(let s=0;s<o.length;++s){let l=o[s],h=i.resolve(l),c=t[h&&h.targetPath||null];if(!c&&h){c={target:h,value:[],curves:0,blendCounter:0};for(let e=0;e<c.target.components;++e)c.value.push(0);if(t[h.targetPath]=c,i.animComponent){if(!i.animComponent.targets[h.targetPath]){let e;e="localRotation"===h.targetPath.substring(h.targetPath.length-13)?T$.TYPE_QUAT:T$.TYPE_VEC3,i.animComponent.targets[h.targetPath]=new T$(i.animComponent,e);}i.animComponent.targets[h.targetPath].layerCounter++,i.animComponent.targets[h.targetPath].setMask(i.layerIndex,1);}}c&&(c.curves++,a.push(r._results[e]),n.push(c));}}this._clips.push(e),this._inputs.push(a),this._outputs.push(n);}removeClip(e){let t=this._targets,i=this._binder,s=this._clips,r=s[e].track.curves;for(let e=0;e<r.length;++e){let s=r[e].paths;for(let e=0;e<s.length;++e){let r=s[e],a=this._binder.resolve(r);a&&(a.curves--,0===a.curves&&(i.unresolve(r),delete t[a.targetPath],i.animComponent&&i.animComponent.targets[a.targetPath].layerCounter--));}}s.splice(e,1),this._inputs.splice(e,1),this._outputs.splice(e,1);}removeClips(){for(;this._clips.length>0;)this.removeClip(0);}updateClipTrack(e,t){this._clips.forEach(i=>{i.name.includes(e)&&(i.track=t);}),this.rebind();}findClip(e){let t=this._clips;for(let i=0;i<t.length;++i){let s=t[i];if(s.name===e)return s}return null}rebind(){this._binder.rebind(),this._targets={};let e=[...this.clips];this.removeClips(),e.forEach(e=>{this.addClip(e);});}assignMask(e){return this._binder.assignMask(e)}update(e,t=true){let i=this._clips,s=i.map((e,t)=>t);Tq.stableSort(s,(e,t)=>i[e].blendOrder<i[t].blendOrder);for(let r=0;r<s.length;++r){let a,n,o,l=s[r],h=i[l],c=this._inputs[l],d=this._outputs[l],u=h.blendWeight;if(u>0&&h._update(e),!t)break;if(u>=1)for(let e=0;e<c.length;++e)a=c[e],o=(n=d[e]).value,Tq.set(o,a,n.target.type),n.blendCounter++;else if(u>0)for(let e=0;e<c.length;++e)a=c[e],o=(n=d[e]).value,0===n.blendCounter?Tq.set(o,a,n.target.type):Tq.blend(o,a,u,n.target.type),n.blendCounter++;}let r=this._targets,a=this._binder;for(let e in r)if(r.hasOwnProperty(e)){let t=r[e];if(a.animComponent&&t.target.isTransform){let i=a.animComponent.targets[e];i.counter===i.layerCounter&&(i.counter=0),i.path||(i.path=e,i.baseValue=t.target.get(),i.setter=t.target.set),i.updateValue(a.layerIndex,t.value),i.counter++;}else t.target.set(t.value);t.blendCounter=0;}this._binder.update(e);}}class TK{constructor(e){this._events=[...e],this._events.sort((e,t)=>e.time-t.time);}get events(){return this._events}}class TZ{static{this.EMPTY=Object.freeze(new TZ("empty",Number.MAX_VALUE,[],[],[]));}constructor(e,t,i,s,r,a=new TK([])){this._name=e,this._duration=t,this._inputs=i,this._outputs=s,this._curves=r,this._animEvents=a;}get name(){return this._name}get duration(){return this._duration}get inputs(){return this._inputs}get outputs(){return this._outputs}get curves(){return this._curves}set events(e){this._animEvents=e;}get events(){return this._animEvents.events}eval(e,t){t._time=e;let i=this._inputs,s=this._outputs,r=this._curves,a=t._cache,n=t._results;for(let t=0;t<i.length;++t)a[t].update(e,i[t]._data);for(let e=0;e<r.length;++e){let t=r[e],i=s[t._output],o=n[e];a[t._input].eval(o,t._interpolation,i);}}}class TQ{static joinPath(e,t){return t=t||".",e.map(function(e){return e.replace(/\\/g,"\\\\").replace(RegExp(`\\${t}`,"g"),`\\${t}`)}).join(t)}static splitPath(e,t){t=t||".";let i=[],s="",r=0;for(;r<e.length;){let a=e[r++];"\\"===a&&r<e.length?"\\"===(a=e[r++])||a===t?s+=a:s+=`\\${a}`:a===t?(i.push(s),s=""):s+=a;}return s.length>0&&i.push(s),i}static encode(e,t,i){return `${Array.isArray(e)?e.join("/"):e}/${t}/${Array.isArray(i)?i.join("/"):i}`}resolve(e){return null}unresolve(e){}update(e){}}class TJ{constructor(e,t,i,s){e.set?(this._set=e.set,this._get=e.get):this._set=e,this._type=t,this._components=i,this._targetPath=s,this._isTransform="localRotation"===this._targetPath.substring(this._targetPath.length-13)||"localPosition"===this._targetPath.substring(this._targetPath.length-13)||"localScale"===this._targetPath.substring(this._targetPath.length-10);}get set(){return this._set}get get(){return this._get}get type(){return this._type}get components(){return this._components}get targetPath(){return this._targetPath}get isTransform(){return this._isTransform}}class T0{constructor(e){if(this._isPathInMask=(e,t)=>{let i=this._mask[e];if(i&&(i.children||t&&false!==i.value))return true;return false},this.graph=e,!e)return;this._mask=null;let t={},i=function(e){t[e.name]=e;for(let t=0;t<e.children.length;++t)i(e.children[t]);};i(e),this.nodes=t,this.targetCache={};let s=function(e){let t,i=e;for(;i&&!(i instanceof x1);)i=i.parent;return i&&(i.render?t=i.render.meshInstances:i.model&&(t=i.model.meshInstances)),t};this.nodeCounts={},this.activeNodes=[],this.handlers={localPosition:function(e){let t=e.localPosition;return T0.createAnimTarget(function(e){t.set(...e);},"vector",3,e,"localPosition")},localRotation:function(e){let t=e.localRotation;return T0.createAnimTarget(function(e){t.set(...e);},"quaternion",4,e,"localRotation")},localScale:function(e){let t=e.localScale;return T0.createAnimTarget(function(e){t.set(...e);},"vector",3,e,"localScale")},weight:function(e,t){let i;t=0===t.indexOf("name.")?t.replace("name.",""):Number(t);let r=s(e);if(r){for(let s=0;s<r.length;++s)if(r[s].node.name===e.name&&r[s].morphInstance){let e=r[s].morphInstance,a=i=>{e.setWeight(t,i[0]);};i||(i=[]),i.push(a);}}return i?T0.createAnimTarget(e=>{for(let t=0;t<i.length;++t)i[t](e);},"number",1,e,`weight.${t}`):null},materialTexture:(e,t)=>{let i=s(e);if(i){let s;for(let t=0;t<i.length;++t)if(i[t].node.name===e.name){s=i[t];break}if(s)return T0.createAnimTarget(e=>{let i=this.animComponent.system.app.assets.get(e[0]);i&&i.resource&&"texture"===i.type&&(s.material[t]=i.resource,s.material.update());},"vector",1,e,"materialTexture","material")}return null}};}_isPathActive(e){if(!this._mask)return true;let t=[e.entityPath[0],this.graph.name];for(let i=0;i<t.length;++i){let s=t[i];if(this._isPathInMask(s,1===e.entityPath.length))return true;for(let t=1;t<e.entityPath.length;t++)if(s+=`/${e.entityPath[t]}`,this._isPathInMask(s,t===e.entityPath.length-1))return true}return false}findNode(e){let t;return this._isPathActive(e)?(this.graph&&((t=this.graph.findByPath(e.entityPath))||(t=this.graph.findByPath(e.entityPath.slice(1)))),t||(t=this.nodes[e.entityPath[e.entityPath.length-1]||""]),t):null}static createAnimTarget(e,t,i,s,r,a){return new TJ(e,t,i,TQ.encode(s.path,a||"entity",r))}resolve(e){let t=TQ.encode(e.entityPath,e.component,e.propertyPath),i=this.targetCache[t];if(i)return i;let s=this.findNode(e);if(!s)return null;let r=this.handlers[e.propertyPath];return r&&(i=r(s))?(this.targetCache[t]=i,this.nodeCounts[s.path]?this.nodeCounts[s.path]++:(this.activeNodes.push(s),this.nodeCounts[s.path]=1),i):null}unresolve(e){if("graph"!==e.component)return;let t=this.nodes[e.entityPath[e.entityPath.length-1]||""];if(this.nodeCounts[t.path]--,0===this.nodeCounts[t.path]){let e=this.activeNodes,i=e.indexOf(t.node),s=e.length;i<s-1&&(e[i]=e[s-1]),e.pop();}}update(e){let t=this.activeNodes;for(let e=0;e<t.length;++e)t[e]._dirtifyLocal();}assignMask(e){return e!==this._mask&&(this._mask=e,true)}}class T1 extends Tp{set animations(e){this._animations=e,this.onSetAnimations();}get animations(){return this._animations}set assets(e){let t=this._assets;if(t&&t.length){for(let e=0;e<t.length;e++)if(t[e]){let i=this.system.app.assets.get(t[e]);if(i){i.off("change",this.onAssetChanged,this),i.off("remove",this.onAssetRemoved,this);let e=this.animationsIndex[i.id];this.currAnim===e&&this._stopCurrentAnimation(),delete this.animations[e],delete this.animationsIndex[i.id];}}}this._assets=e;let i=e.map(e=>e instanceof xF?e.id:e);this.loadAnimationAssets(i);}get assets(){return this._assets}set currentTime(e){if(this.skeleton&&(this.skeleton.currentTime=e,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator){let t=this.animEvaluator.clips;for(let i=0;i<t.length;++i)t[i].time=e;}}get currentTime(){if(this.skeleton)return this.skeleton._time;if(this.animEvaluator){let e=this.animEvaluator.clips;if(e.length>0)return e[e.length-1].time}return 0}get duration(){return this.currAnim?this.animations[this.currAnim].duration:0}set loop(e){if(this._loop=e,this.skeleton&&(this.skeleton.looping=e),this.animEvaluator)for(let t=0;t<this.animEvaluator.clips.length;++t)this.animEvaluator.clips[t].loop=e;}get loop(){return this._loop}play(e,t=0){if(this.enabled&&this.entity.enabled&&this.animations[e]){if(this.prevAnim=this.currAnim,this.currAnim=e,this.model){this.skeleton||this.animEvaluator||this._createAnimationController();let e=this.animations[this.prevAnim],i=this.animations[this.currAnim];if(this.blending=t>0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/t),this.skeleton&&(this.blending?(this.fromSkel.animation=e,this.fromSkel.addTime(this.skeleton._time),this.toSkel.animation=i):this.skeleton.animation=i),this.animEvaluator){let e=this.animEvaluator;if(this.blending)for(;e.clips.length>1;)e.removeClip(0);else this.animEvaluator.removeClips();let t=new Tx(this.animations[this.currAnim],0,1,true,this.loop);t.name=this.currAnim,t.blendWeight=+!this.blending,t.reset(),this.animEvaluator.addClip(t);}}this.playing=true;}}getAnimation(e){return this.animations[e]}setModel(e){e!==this.model&&(this._resetAnimationController(),this.model=e,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim));}onSetAnimations(){let e=this.entity.model;if(e){let t=e.model;t&&t!==this.model&&this.setModel(t);}if(!this.currAnim&&this.activate&&this.enabled&&this.entity.enabled){let e=Object.keys(this._animations);e.length>0&&this.play(e[0]);}}_resetAnimationController(){this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null;}_createAnimationController(){let e=this.model,t=this.animations,i=false,s=false;for(let e in t)t.hasOwnProperty(e)&&(t[e].constructor===TZ?s=true:i=true);let r=e.getGraph();i?(this.fromSkel=new Sz(r),this.toSkel=new Sz(r),this.skeleton=new Sz(r),this.skeleton.looping=this.loop,this.skeleton.setGraph(r)):s&&(this.animEvaluator=new Tj(new T0(this.entity)));}loadAnimationAssets(e){if(!e||!e.length)return;let t=this.system.app.assets,i=e=>{if(e.resources.length>1)for(let t=0;t<e.resources.length;t++)this.animations[e.resources[t].name]=e.resources[t],this.animationsIndex[e.id]=e.resources[t].name;else this.animations[e.name]=e.resource,this.animationsIndex[e.id]=e.name;this.animations=this.animations;},s=e=>{e.off("change",this.onAssetChanged,this),e.on("change",this.onAssetChanged,this),e.off("remove",this.onAssetRemoved,this),e.on("remove",this.onAssetRemoved,this),e.resource?i(e):(e.once("load",i,this),this.enabled&&this.entity.enabled&&t.load(e));};for(let i=0,r=e.length;i<r;i++){let r=t.get(e[i]);r?s(r):t.on(`add:${e[i]}`,s);}}onAssetChanged(e,t,i,s){if("resource"===t||"resources"===t)if("resources"===t&&i&&0===i.length&&(i=null),i){let t=false;if(i.length>1){if(s&&s.length>1)for(let e=0;e<s.length;e++)delete this.animations[s[e].name];else delete this.animations[e.name];t=false;for(let e=0;e<i.length;e++)this.animations[i[e].name]=i[e],!t&&this.currAnim===i[e].name&&this.playing&&this.enabled&&this.entity.enabled&&(t=true,this.play(i[e].name));t||(this._stopCurrentAnimation(),this.onSetAnimations());}else {if(s&&s.length>1)for(let e=0;e<s.length;e++)delete this.animations[s[e].name];this.animations[e.name]=i[0]||i,t=false,this.currAnim===e.name&&this.playing&&this.enabled&&this.entity.enabled&&(t=true,this.play(e.name)),t||(this._stopCurrentAnimation(),this.onSetAnimations());}this.animationsIndex[e.id]=e.name;}else {if(s.length>1)for(let e=0;e<s.length;e++)delete this.animations[s[e].name],this.currAnim===s[e].name&&this._stopCurrentAnimation();else delete this.animations[e.name],this.currAnim===e.name&&this._stopCurrentAnimation();delete this.animationsIndex[e.id];}}onAssetRemoved(e){if(e.off("remove",this.onAssetRemoved,this),this.animations){if(e.resources.length>1)for(let t=0;t<e.resources.length;t++)delete this.animations[e.resources[t].name],this.currAnim===e.resources[t].name&&this._stopCurrentAnimation();else delete this.animations[e.name],this.currAnim===e.name&&this._stopCurrentAnimation();delete this.animationsIndex[e.id];}}_stopCurrentAnimation(){if(this.currAnim=null,this.playing=false,this.skeleton&&(this.skeleton.currentTime=0,this.skeleton.animation=null),this.animEvaluator){for(let e=0;e<this.animEvaluator.clips.length;++e)this.animEvaluator.clips[e].stop();this.animEvaluator.update(0),this.animEvaluator.removeClips();}}onEnable(){super.onEnable();let e=this.assets,t=this.system.app.assets;if(e)for(let i=0,s=e.length;i<s;i++){let s=e[i];s instanceof xF||(s=t.get(s)),s&&!s.resource&&t.load(s);}if(this.activate&&!this.currAnim){let e=Object.keys(this.animations);e.length>0&&this.play(e[0]);}}onBeforeRemove(){for(let e=0;e<this.assets.length;e++){let t=this.assets[e];"number"==typeof t&&(t=this.system.app.assets.get(t)),t&&(t.off("change",this.onAssetChanged,this),t.off("remove",this.onAssetRemoved,this));}this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null;}update(e){if(this.blending&&(this.blend+=e*this.blendSpeed,this.blend>=1&&(this.blend=1)),this.playing){let t=this.skeleton;if(null!==t&&null!==this.model){if(this.blending)t.blend(this.fromSkel,this.toSkel,this.blend);else {let i=e*this.speed;t.addTime(i),this.speed>0&&t._time===t.animation.duration&&!this.loop?this.playing=false:this.speed<0&&0===t._time&&!this.loop&&(this.playing=false);}this.blending&&1===this.blend&&(t.animation=this.toSkel.animation),t.updateGraph();}}let t=this.animEvaluator;if(t){for(let e=0;e<t.clips.length;++e){let i=t.clips[e];i.speed=this.speed,this.playing?i.resume():i.pause();}this.blending&&t.clips.length>1&&(t.clips[1].blendWeight=this.blend),t.update(e);}this.blending&&1===this.blend&&(this.blending=false);}constructor(...e){super(...e),this._animations={},this._assets=[],this._loop=true,this.animEvaluator=null,this.model=null,this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animationsIndex={},this.prevAnim=null,this.currAnim=null,this.blend=0,this.blending=false,this.blendSpeed=0,this.activate=true,this.speed=1;}}class T2{constructor(){this.enabled=true;}}let T3=["enabled"];class T4 extends Tm{constructor(e){super(e),this.id="animation",this.ComponentType=T1,this.DataType=T2,this.schema=T3,this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("update",this.onUpdate,this);}initializeComponentData(e,t,i){for(let i of ["activate","enabled","loop","speed","assets"])t.hasOwnProperty(i)&&(e[i]=t[i]);super.initializeComponentData(e,t,T3);}cloneComponent(e,t){this.addComponent(t,{}),t.animation.assets=e.animation.assets.slice(),t.animation.speed=e.animation.speed,t.animation.loop=e.animation.loop,t.animation.activate=e.animation.activate,t.animation.enabled=e.animation.enabled;let i={},s=e.animation.animations;for(let e in s)s.hasOwnProperty(e)&&(i[e]=s[e]);t.animation.animations=i;let r={},a=e.animation.animationsIndex;for(let e in a)a.hasOwnProperty(e)&&(r[e]=a[e]);return t.animation.animationsIndex=r,t.animation}onBeforeRemove(e,t){t.onBeforeRemove();}onUpdate(e){let t=this.store;for(let i in t)if(t.hasOwnProperty(i)){let s=t[i];s.data.enabled&&s.entity.enabled&&s.entity.animation.update(e);}}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this);}}Tp._buildAccessors(T1.prototype,T3);class T5{constructor(e,t,i,s,r=1){this._state=e,this._parent=t,this._name=i,Array.isArray(s)?(this._point=new eN(s[0],s[1]),this._pointLength=this._point.length()):(this._point=s,this._pointLength=s),this._speed=r,this._weightedSpeed=1,this._weight=1,this._animTrack=null;}get parent(){return this._parent}get name(){return this._name}get path(){return this._parent?`${this._parent.path}.${this._name}`:this._name}get point(){return this._point}get pointLength(){return this._pointLength}set weight(e){this._weight=e;}get weight(){return this._parent?this._parent.weight*this._weight:this._weight}get normalizedWeight(){let e=this._state.totalWeight;return 0===e?0:this.weight/e}get speed(){return this._weightedSpeed*this._speed}get absoluteSpeed(){return Math.abs(this._speed)}set weightedSpeed(e){this._weightedSpeed=e;}get weightedSpeed(){return this._weightedSpeed}set animTrack(e){this._animTrack=e;}get animTrack(){return this._animTrack}}class T8 extends T5{constructor(e,t,i,s,r,a,n,o,l){super(e,t,i,s),this._parameters=r,this._parameterValues=Array(r.length),this._children=[],this._findParameter=l,this._syncAnimations=false!==n,this._pointCache={};for(let t=0;t<a.length;t++){let i=a[t];i.children?this._children.push(o(i.type,e,this,i.name,1,i.parameter?[i.parameter]:i.parameters,i.children,i.syncAnimations,o,l)):this._children.push(new T5(e,this,i.name,i.point,i.speed));}}get weight(){return this.calculateWeights(),this._parent?this._parent.weight*this._weight:this._weight}get syncAnimations(){return this._syncAnimations}getChild(e){for(let t=0;t<this._children.length;t++)if(this._children[t].name===e)return this._children[t];return null}updateParameterValues(){let e=true;for(let t=0;t<this._parameterValues.length;t++){let i=this._findParameter(this._parameters[t]).value;this._parameterValues[t]!==i&&(this._parameterValues[t]=i,e=false);}return e}getNodeWeightedDuration(e){return this._children[e].animTrack.duration/this._children[e].speedMultiplier*this._children[e].weight}getNodeCount(){let e=0;for(let t=0;t<this._children.length;t++)this._children[t].constructor===T8?e+=this._children[t].getNodeCount():e++;return e}}class T6 extends T8{constructor(e,t,i,s,r,a,n,o,l){a.sort((e,t)=>e.point-t.point),super(e,t,i,s,r,a,n,o,l);}calculateWeights(){if(this.updateParameterValues())return;let e=0;this._children[0].weight=0;for(let t=0;t<this._children.length;t++){let i=this._children[t];if(t!==this._children.length-1){let e=this._children[t+1];if(i.point===e.point)i.weight=.5,e.weight=.5;else if(eA.between(this._parameterValues[0],i.point,e.point,true)){let t=Math.abs(i.point-e.point),s=(t-Math.abs(i.point-this._parameterValues[0]))/t;i.weight=s,e.weight=1-s;}else e.weight=0;}this._syncAnimations&&(e+=i.animTrack.duration/i.absoluteSpeed*i.weight);}if(this._syncAnimations)for(let t=0;t<this._children.length;t++){let i=this._children[t];i.weightedSpeed=i.animTrack.duration/i.absoluteSpeed/e;}}}class T9 extends T8{static{this._p=new eN;}static{this._pip=new eN;}pointDistanceCache(e,t){let i=`${e}${t}`;return this._pointCache[i]||(this._pointCache[i]=this._children[t].point.clone().sub(this._children[e].point)),this._pointCache[i]}calculateWeights(){let e,t;if(!this.updateParameterValues()){T9._p.set(...this._parameterValues),e=0,t=0;for(let i=0;i<this._children.length;i++){let s=this._children[i],r=s.point;T9._pip.set(T9._p.x,T9._p.y).sub(r);let a=Number.MAX_VALUE;for(let e=0;e<this._children.length;e++){if(i===e)continue;let t=this.pointDistanceCache(i,e),s=eA.clamp(1-T9._pip.dot(t)/t.lengthSq(),0,1);s<a&&(a=s);}s.weight=a,e+=a,this._syncAnimations&&(t+=s.animTrack.duration/s.absoluteSpeed*s.weight);}for(let i=0;i<this._children.length;i++){let s=this._children[i];s.weight=s._weight/e,this._syncAnimations&&(s.weightedSpeed=s.animTrack.duration/s.absoluteSpeed/t);}}}}class T7 extends T8{static{this._p=new eN;}static{this._pip=new eN;}pointCache(e,t){let i=`${e}${t}`;return this._pointCache[i]||(this._pointCache[i]=new eN((this._children[t].pointLength-this._children[e].pointLength)/((this._children[t].pointLength+this._children[e].pointLength)/2),2*eN.angleRad(this._children[e].point,this._children[t].point))),this._pointCache[i]}calculateWeights(){let e,t;if(this.updateParameterValues())return;T7._p.set(...this._parameterValues);let i=T7._p.length();e=0,t=0;for(let s=0;s<this._children.length;s++){let r=this._children[s],a=r.point,n=r.pointLength,o=Number.MAX_VALUE;for(let e=0;e<this._children.length;e++){if(s===e)continue;let t=this.pointCache(s,e),r=this._children[e].pointLength;T7._pip.set((i-n)/((r+n)/2),2*eN.angleRad(a,T7._p));let l=eA.clamp(1-Math.abs(T7._pip.dot(t)/t.lengthSq()),0,1);l<o&&(o=l);}r.weight=o,e+=o,this._syncAnimations&&(t+=r.animTrack.duration/r.absoluteSpeed*r.weight);}for(let i=0;i<this._children.length;i++){let s=this._children[i];if(s.weight=s._weight/e,this._syncAnimations){let i=s.animTrack.duration/t*e;s.weightedSpeed=s.absoluteSpeed*i;}}}}class Ee extends T8{calculateWeights(){if(this.updateParameterValues())return;let e=0,t=0;for(let i=0;i<this._children.length;i++)if(e+=Math.max(this._parameterValues[i],0),this._syncAnimations){let e=this._children[i];t+=e.animTrack.duration/e.absoluteSpeed*e.weight;}for(let i=0;i<this._children.length;i++){let s=this._children[i],r=Math.max(this._parameterValues[i],0);e?(s.weight=r/e,this._syncAnimations&&(s.weightedSpeed=s.animTrack.duration/s.absoluteSpeed/t)):(s.weight=0,this._syncAnimations&&(s.weightedSpeed=0));}}}class Et{constructor(e,t,i=1,s=true,r){this._animations={},this._animationList=[],this._controller=e,this._name=t,this._speed=i,this._loop=s,this._hasAnimations=false,r?this._blendTree=this._createTree(r.type,this,null,t,1,r.parameter?[r.parameter]:r.parameters,r.children,r.syncAnimations,this._createTree,this._controller.findParameter):this._blendTree=new T5(this,null,t,1,i);}_createTree(e,t,i,s,r,a,n,o,l,h){switch(e){case TB:return new T6(t,i,s,r,a,n,o,l,h);case Tk:return new T9(t,i,s,r,a,n,o,l,h);case TU:return new T7(t,i,s,r,a,n,o,l,h);case TV:return new Ee(t,i,s,r,a,n,o,l,h)}}_getNodeFromPath(e){let t=this._blendTree;for(let i=1;i<e.length;i++)t=t.getChild(e[i]);return t}addAnimation(e,t){let i=e.join("."),s=this._animationList.findIndex(e=>e.path===i);if(s>=0)this._animationList[s].animTrack=t;else {let i=this._getNodeFromPath(e);i.animTrack=t,this._animationList.push(i);}this._updateHasAnimations();}_updateHasAnimations(){this._hasAnimations=this._animationList.length>0&&this._animationList.every(e=>e.animTrack&&e.animTrack!==TZ.EMPTY);}get name(){return this._name}set animations(e){this._animationList=e,this._updateHasAnimations();}get animations(){return this._animationList}get hasAnimations(){return this._hasAnimations}set speed(e){this._speed=e;}get speed(){return this._speed}set loop(e){this._loop=e;}get loop(){return this._loop}get nodeCount(){return this._blendTree&&this._blendTree.constructor!==T5?this._blendTree.getNodeCount():1}get playable(){return -1!==TW.indexOf(this.name)||this.animations.length===this.nodeCount}get looping(){if(this.animations.length>0){let e=`${this.name}.${this.animations[0].animTrack.name}`,t=this._controller.animEvaluator.findClip(e);if(t)return t.loop}return false}get totalWeight(){let e=0;for(let t=0;t<this.animations.length;t++)e+=this.animations[t].weight;return e}get timelineDuration(){let e=0;for(let t=0;t<this.animations.length;t++){let i=this.animations[t];i.animTrack.duration>e&&(e=i.animTrack.duration);}return e}}class Ei{constructor({from:e,to:t,time:i=0,priority:s=0,conditions:r=[],exitTime:a=null,transitionOffset:n=null,interruptionSource:o=TT}){this._from=e,this._to=t,this._time=i,this._priority=s,this._conditions=r,this._exitTime=a,this._transitionOffset=n,this._interruptionSource=o;}get from(){return this._from}set to(e){this._to=e;}get to(){return this._to}get time(){return this._time}get priority(){return this._priority}get conditions(){return this._conditions}get exitTime(){return this._exitTime}get transitionOffset(){return this._transitionOffset}get interruptionSource(){return this._interruptionSource}get hasExitTime(){return !!this.exitTime}}class Es{constructor(e,t,i,s,r,a,n){this._states={},this._stateNames=[],this._findTransitionsFromStateCache={},this._findTransitionsBetweenStatesCache={},this._previousStateName=null,this._activeStateName=Tz,this._activeStateDuration=0,this._activeStateDurationDirty=true,this._playing=false,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=false,this._transitionInterruptionSource=TT,this._transitionPreviousStates=[],this._timeInState=0,this._timeInStateBefore=0,this.findParameter=e=>this._findParameter(e),this._animEvaluator=e,this._eventHandler=r,this._findParameter=a,this._consumeTrigger=n;for(let e=0;e<t.length;e++)this._states[t[e].name]=new Et(this,t[e].name,t[e].speed,t[e].loop,t[e].blendTree),this._stateNames.push(t[e].name);this._transitions=i.map(e=>new Ei({...e})),this._activate=s;}get animEvaluator(){return this._animEvaluator}set activeState(e){this._activeStateName=e;}get activeState(){return this._findState(this._activeStateName)}get activeStateName(){return this._activeStateName}get activeStateAnimations(){return this.activeState.animations}set previousState(e){this._previousStateName=e;}get previousState(){return this._findState(this._previousStateName)}get previousStateName(){return this._previousStateName}get playable(){let e=true;for(let t=0;t<this._stateNames.length;t++)this._states[this._stateNames[t]].playable||(e=false);return e}set playing(e){this._playing=e;}get playing(){return this._playing}get activeStateProgress(){return this._getActiveStateProgressForTime(this._timeInState)}get activeStateDuration(){if(this._activeStateDurationDirty){let e=0;for(let t=0;t<this.activeStateAnimations.length;t++){let i=this._animEvaluator.findClip(this.activeStateAnimations[t].name);i&&(e=Math.max(e,i.track.duration));}this._activeStateDuration=e,this._activeStateDurationDirty=false;}return this._activeStateDuration}set activeStateCurrentTime(e){this._timeInStateBefore=e,this._timeInState=e;for(let t=0;t<this.activeStateAnimations.length;t++){let i=this.animEvaluator.findClip(this.activeStateAnimations[t].name);i&&(i.time=e);}}get activeStateCurrentTime(){return this._timeInState}get transitioning(){return this._isTransitioning}get transitionProgress(){return this._currTransitionTime/this._totalTransitionTime}get states(){return this._stateNames}assignMask(e){return this._animEvaluator.assignMask(e)}_findState(e){return this._states[e]}_getActiveStateProgressForTime(e){if(this.activeStateName===Tz||this.activeStateName===TG||this.activeStateName===TH)return 1;let t=this._animEvaluator.findClip(this.activeStateAnimations[0].name);return t?t.progressForTime(e):null}_findTransitionsFromState(e){let t=this._findTransitionsFromStateCache[e];return t||(gX(t=this._transitions.filter(t=>t.from===e)),this._findTransitionsFromStateCache[e]=t),t}_findTransitionsBetweenStates(e,t){let i=this._findTransitionsBetweenStatesCache[`${e}->${t}`];return i||(gX(i=this._transitions.filter(i=>i.from===e&&i.to===t)),this._findTransitionsBetweenStatesCache[`${e}->${t}`]=i),i}_transitionHasConditionsMet(e){let t=e.conditions;for(let e=0;e<t.length;e++){let i=t[e],s=this._findParameter(i.parameterName);switch(i.predicate){case TC:if(!(s.value>i.value))return false;break;case TP:if(!(s.value<i.value))return false;break;case TL:if(!(s.value>=i.value))return false;break;case TI:if(!(s.value<=i.value))return false;break;case TD:if(s.value!==i.value)return false;break;case TR:if(s.value===i.value)return false}}return true}_findTransition(e,t){let i=[];if(e&&t)i=i.concat(this._findTransitionsBetweenStates(e,t));else if(this._isTransitioning)switch(this._transitionInterruptionSource){case TE:i=(i=i.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(TH));break;case TA:i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(TH));break;case Tb:i=(i=(i=i.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(TH));break;case Tw:i=(i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(TH));}else i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(TH));if((i=i.filter(e=>{if(e.to===this.activeStateName)return false;if(e.hasExitTime){let t=this._getActiveStateProgressForTime(this._timeInStateBefore),i=this._getActiveStateProgressForTime(this._timeInState);if(e.exitTime<1&&this.activeState.loop&&(t-=Math.floor(t),i-=Math.floor(i)),i===t){if(i!==e.exitTime)return null}else if(!(e.exitTime>t&&e.exitTime<=i))return null}return this._transitionHasConditionsMet(e)})).length>0){let e=i[0];return e.to===TG&&(e.to=this._findTransitionsFromState(Tz)[0].to),e}return null}updateStateFromTransition(e){let t,i,s;this.previousState=e.from?this.activeStateName:null,this.activeState=e.to,this._activeStateDurationDirty=true;for(let t=0;t<e.conditions.length;t++){let i=e.conditions[t];this._findParameter(i.parameterName).type===TF&&this._consumeTrigger(i.parameterName);}if(this.previousState){this._isTransitioning||(this._transitionPreviousStates=[]),this._transitionPreviousStates.push({name:this._previousStateName,weight:1});let e=Math.min(0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,1);for(let r=0;r<this._transitionPreviousStates.length;r++){this._isTransitioning?r!==this._transitionPreviousStates.length-1?this._transitionPreviousStates[r].weight*=1-e:this._transitionPreviousStates[r].weight=e:this._transitionPreviousStates[r].weight=1,t=this._findState(this._transitionPreviousStates[r].name);for(let e=0;e<t.animations.length;e++)i=t.animations[e],(s=this._animEvaluator.findClip(`${i.name}.previous.${r}`))||((s=this._animEvaluator.findClip(i.name)).name=`${i.name}.previous.${r}`),r!==this._transitionPreviousStates.length-1&&s.pause();}}this._isTransitioning=true,this._totalTransitionTime=e.time,this._currTransitionTime=0,this._transitionInterruptionSource=e.interruptionSource;let r=this.activeState,a=e.transitionOffset&&e.transitionOffset>0&&e.transitionOffset<1,n=0,o=0;if(a){let t=r.timelineDuration*e.transitionOffset;n=t,o=t;}this._timeInState=n,this._timeInStateBefore=o;for(let t=0;t<r.animations.length;t++){if(s=this._animEvaluator.findClip(r.animations[t].name))s.reset();else {let e=Number.isFinite(r.animations[t].speed)?r.animations[t].speed:r.speed;(s=new Tx(r.animations[t].animTrack,this._timeInState,e,true,r.loop,this._eventHandler)).name=r.animations[t].name,this._animEvaluator.addClip(s);}if(e.time>0?s.blendWeight=0:s.blendWeight=r.animations[t].normalizedWeight,s.play(),a)s.time=r.timelineDuration*e.transitionOffset;else {let e=r.speed>=0?0:this.activeStateDuration;s.time=e;}}}_transitionToState(e){if(!this._findState(e))return;let t=this._findTransition(this._activeStateName,e);t||(this._animEvaluator.removeClips(),t=new Ei({from:null,to:e})),this.updateStateFromTransition(t);}assignAnimation(e,t,i,s){let r=e.split("."),a=this._findState(r[0]);a||(a=new Et(this,r[0],i),this._states[r[0]]=a,this._stateNames.push(r[0])),a.addAnimation(r,t),this._animEvaluator.updateClipTrack(a.name,t),void 0!==i&&(a.speed=i),void 0!==s&&(a.loop=s),!this._playing&&this._activate&&this.playable&&this.play(),this._activeStateDurationDirty=true;}removeNodeAnimations(e){if(-1!==TW.indexOf(e))return false;let t=this._findState(e);return !!t&&(t.animations=[],true)}play(e){e&&this._transitionToState(e),this._playing=true;}pause(){this._playing=false;}reset(){this._previousStateName=null,this._activeStateName=Tz,this._playing=false,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=false,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips();}rebind(){this._animEvaluator.rebind();}update(e){let t,i,s;if(!this._playing)return;(this.activeState.loop||this._timeInState<this.activeStateDuration)&&(this._timeInStateBefore=this._timeInState,this._timeInState+=e*this.activeState.speed,!this.activeState.loop&&this._timeInState>this.activeStateDuration&&(this._timeInState=this.activeStateDuration,e=this.activeStateDuration-this._timeInStateBefore));let r=this._findTransition(this._activeStateName);if(r&&this.updateStateFromTransition(r),this._isTransitioning)if(this._currTransitionTime+=e,this._currTransitionTime<=this._totalTransitionTime){let e=0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1;for(let r=0;r<this._transitionPreviousStates.length;r++){t=this._findState(this._transitionPreviousStates[r].name);let a=this._transitionPreviousStates[r].weight;for(let n=0;n<t.animations.length;n++)i=t.animations[n],(s=this._animEvaluator.findClip(`${i.name}.previous.${r}`))&&(s.blendWeight=(1-e)*i.normalizedWeight*a);}t=this.activeState;for(let s=0;s<t.animations.length;s++)i=t.animations[s],this._animEvaluator.findClip(i.name).blendWeight=e*i.normalizedWeight;}else {this._isTransitioning=false;let e=this.activeStateAnimations.length,r=this._animEvaluator.clips.length;for(let t=0;t<r-e;t++)this._animEvaluator.removeClip(0);this._transitionPreviousStates=[],t=this.activeState;for(let e=0;e<t.animations.length;e++)i=t.animations[e],(s=this._animEvaluator.findClip(i.name))&&(s.blendWeight=i.normalizedWeight);}else if(this.activeState._blendTree.constructor!==T5){t=this.activeState;for(let e=0;e<t.animations.length;e++)i=t.animations[e],(s=this._animEvaluator.findClip(i.name))&&(s.blendWeight=i.normalizedWeight,i.parent.syncAnimations&&(s.speed=i.speed));}this._animEvaluator.update(e,this.activeState.hasAnimations);}}let Er=new eN,Ea=new eM,En=new eF,Eo=new eb,El=new eH;class Eh extends T0{constructor(e,t,i,s,r){super(t),this.animComponent=e,this._mask=s,this.layerName=i,this.layerIndex=r;}static _packFloat(e){return e[0]}static _packBoolean(e){return !!e[0]}static _packVec2(e){return Er.x=e[0],Er.y=e[1],Er}static _packVec3(e){return Ea.x=e[0],Ea.y=e[1],Ea.z=e[2],Ea}static _packVec4(e){return En.x=e[0],En.y=e[1],En.z=e[2],En.w=e[3],En}static _packColor(e){return Eo.r=e[0],Eo.g=e[1],Eo.b=e[2],Eo.a=e[3],Eo}static _packQuat(e){return El.x=e[0],El.y=e[1],El.z=e[2],El.w=e[3],El}resolve(e){let t,i,s,r=TQ.encode(e.entityPath,e.component,e.propertyPath),a=this.targetCache[r];if(a)return a;switch(e.component){case "entity":t=this._getEntityFromHierarchy(e.entityPath),s=TQ.encode(t.path,"entity",e.propertyPath),i=t;break;case "graph":if(!(i=this.findNode(e)))return null;s=TQ.encode(i.path,"graph",e.propertyPath);break;default:if(!(i=(t=this._getEntityFromHierarchy(e.entityPath)).findComponent(e.component)))return null;s=TQ.encode(t.path,e.component,e.propertyPath);}return a=this._createAnimTargetForProperty(i,e.propertyPath,s),this.targetCache[r]=a,a}update(e){let t=this.activeNodes;if(t)for(let e=0;e<t.length;e++)t[e]._dirtifyLocal();}_getEntityFromHierarchy(e){if(!this.animComponent.entity.name===e[0])return null;let t=this.animComponent.entity;return 1===e.length?t:t._parent.findByPath(e)}_resolvePath(e,t,i){let s=t.length-!i;for(let i=0;i<s;i++)e=e[t[i]];return e}_setter(e,t,i){let s=this._resolvePath(e,t),r=t[t.length-1],a=`set${r.substring(0,1).toUpperCase()}${r.substring(1)}`;if(s[a]){let e=s[`get${r.substring(0,1).toUpperCase()}${r.substring(1)}`].bind(s)();e=[e.x,e.y,e.z,e.w];let t=s[a].bind(s);return {set:e=>{t(i(e));},get:()=>e}}let n=s[r];if("object"==typeof n&&n.hasOwnProperty("copy"))return function(e){n.copy(i(e));};if(-1!==[eN,eM,eF,eb,eH].indexOf(s.constructor)&&t.length>1){let a=t.length>2?this._resolvePath(e,t.slice(0,-1)):e,n=t[t.length-2];return function(e){s[r]=i(e),a[n]=s;}}return function(e){s[r]=i(e);}}_createAnimTargetForProperty(e,t,i){let s,r,a;if(this.handlers&&t[0].startsWith("weight."))return this.handlers.weight(e,t[0].replace("weight.",""));if(this.handlers&&"material"===t[0]&&2===t.length){let i=t[1];if(i.endsWith("Map"))return this.handlers.materialTexture(e,i)}let n=this._resolvePath(e,t,true);if(void 0===n)return null;if("number"==typeof n)s=this._setter(e,t,Eh._packFloat),r="vector",a=1;else if("boolean"==typeof n)s=this._setter(e,t,Eh._packBoolean),r="vector",a=1;else if("object"==typeof n)switch(n.constructor){case eN:s=this._setter(e,t,Eh._packVec2),r="vector",a=2;break;case eM:s=this._setter(e,t,Eh._packVec3),r="vector",a=3;break;case eF:s=this._setter(e,t,Eh._packVec4),r="vector",a=4;break;case eb:s=this._setter(e,t,Eh._packColor),r="vector",a=4;break;case eH:s=this._setter(e,t,Eh._packQuat),r="quaternion",a=4;break;default:return null}return -1!==t.indexOf("material")?new TJ(t=>{s(t),e.material.update();},r,a,i):new TJ(s,r,a,i)}rebind(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;let e={},t=function(i){e[i.name]=i;for(let e=0;e<i.children.length;++e)t(i.children[e]);};t(this.graph),this.nodes=e;}}class Ec{constructor(e,t,i,s=1,r=TX){this._mask=null,this._blendTime=0,this._blendTimeElapsed=0,this._startingWeight=0,this._targetWeight=0,this._name=e,this._controller=t,this._component=i,this._weight=s,this._blendType=r;}get name(){return this._name}set playing(e){this._controller.playing=e;}get playing(){return this._controller.playing}get playable(){return this._controller.playable}get activeState(){return this._controller.activeStateName}get previousState(){return this._controller.previousStateName}get activeStateProgress(){return this._controller.activeStateProgress}get activeStateDuration(){return this._controller.activeStateDuration}set activeStateCurrentTime(e){let t=this._controller,i=t.playing;t.playing=true,t.activeStateCurrentTime=e,i||t.update(0),t.playing=i;}get activeStateCurrentTime(){return this._controller.activeStateCurrentTime}get transitioning(){return this._controller.transitioning}get transitionProgress(){return this.transitioning?this._controller.transitionProgress:null}get states(){return this._controller.states}set weight(e){this._weight=e,this._component.dirtifyTargets();}get weight(){return this._weight}set blendType(e){e!==this._blendType&&(this._blendType=e,this._controller.normalizeWeights&&this._component.rebind());}get blendType(){return this._blendType}set mask(e){this._controller.assignMask(e)&&this._component.rebind(),this._mask=e;}get mask(){return this._mask}play(e){this._controller.play(e);}pause(){this._controller.pause();}reset(){this._controller.reset();}rebind(){this._controller.rebind();}update(e){this._blendTime&&(this._blendTimeElapsed<this._blendTime?(this.weight=eA.lerp(this._startingWeight,this._targetWeight,this._blendTimeElapsed/this._blendTime),this._blendTimeElapsed+=e):(this.weight=this._targetWeight,this._blendTime=0,this._blendTimeElapsed=0,this._startingWeight=0,this._targetWeight=0)),this._controller.update(e);}blendToWeight(e,t){this._startingWeight=this.weight,this._targetWeight=e,this._blendTime=Math.max(0,t),this._blendTimeElapsed=0;}assignAnimation(e,t,i,s){t instanceof TZ&&(this._controller.assignAnimation(e,t,i,s),0===this._controller._transitions.length&&this._controller._transitions.push(new Ei({from:"START",to:e})),this._component.activate&&this._component.playable&&(this._component.playing=true));}removeNodeAnimations(e){this._controller.removeNodeAnimations(e)&&(this._component.playing=false);}getAnimationAsset(e){return this._component.animationAssets[`${this.name}:${e}`]}transition(e,t=0,i=null){this._controller.updateStateFromTransition(new Ei({from:this._controller.activeStateName,to:e,time:t,transitionOffset:i}));}}class Ed{constructor(e){if(this._layers=[],this._parameters={},Array.isArray(e.layers))this._layers=e.layers;else for(let t in e.layers){let i=e.layers[t],s={name:i.name,blendType:i.blendType,weight:i.weight,states:[],transitions:[]};for(let t=0;t<i.states.length;t++)s.states.push(e.states[i.states[t]]);for(let t=0;t<i.transitions.length;t++){let r=e.transitions[i.transitions[t]];if(r.conditions&&!Array.isArray(r.conditions)){let e=Object.keys(r.conditions),t=[];for(let i=0;i<e.length;i++){let s=r.conditions[e[i]];s.parameterName&&t.push(s);}r.conditions=t;}Number.isInteger(r.from)&&(r.from=e.states[r.from].name),Number.isInteger(r.to)&&(r.to=e.states[r.to].name),s.transitions.push(r);}this._layers.push(s);}for(let t in e.parameters){let i=e.parameters[t];this._parameters[i.name]={type:i.type,value:i.value};}}get parameters(){return Object.assign({},this._parameters)}get layers(){return this._layers}}class Eu extends Tp{set stateGraphAsset(e){let t,i;if(null===e)return void this.removeStateGraph();this._stateGraphAsset&&this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this),e instanceof xF?(t=e.id,(i=this.system.app.assets.get(t))||(this.system.app.assets.add(e),i=this.system.app.assets.get(t))):(t=e,i=this.system.app.assets.get(t)),i&&this._stateGraphAsset!==t&&(i.resource?(this._stateGraph=i.resource,this.loadStateGraph(this._stateGraph),i.on("change",this._onStateGraphAssetChangeEvent,this)):(i.once("load",e=>{this._stateGraph=e.resource,this.loadStateGraph(this._stateGraph);}),i.on("change",this._onStateGraphAssetChangeEvent,this),this.system.app.assets.load(i)),this._stateGraphAsset=t);}get stateGraphAsset(){return this._stateGraphAsset}set normalizeWeights(e){this._normalizeWeights=e,this.unbind();}get normalizeWeights(){return this._normalizeWeights}set animationAssets(e){this._animationAssets=e,this.loadAnimationAssets();}get animationAssets(){return this._animationAssets}set speed(e){this._speed=e;}get speed(){return this._speed}set activate(e){this._activate=e;}get activate(){return this._activate}set playing(e){this._playing=e;}get playing(){return this._playing}set rootBone(e){if("string"==typeof e){let t=this.entity.root.findByGuid(e);this._rootBone=t;}else e instanceof x1?this._rootBone=e:this._rootBone=null;this.rebind();}get rootBone(){return this._rootBone}set stateGraph(e){this._stateGraph=e;}get stateGraph(){return this._stateGraph}get layers(){return this._layers}set layerIndices(e){this._layerIndices=e;}get layerIndices(){return this._layerIndices}set parameters(e){this._parameters=e;}get parameters(){return this._parameters}set targets(e){this._targets=e;}get targets(){return this._targets}get playable(){for(let e=0;e<this._layers.length;e++)if(!this._layers[e].playable)return false;return true}get baseLayer(){return this._layers.length>0?this._layers[0]:null}_onStateGraphAssetChangeEvent(e){let t=this.animationAssets,i=this.layers.map(e=>e.mask);this.removeStateGraph(),this._stateGraph=new Ed(e._data),this.loadStateGraph(this._stateGraph),this.animationAssets=t,this.loadAnimationAssets(),this.layers.forEach((e,t)=>{e.mask=i[t];}),this.rebind();}dirtifyTargets(){let e=Object.values(this._targets);for(let t=0;t<e.length;t++)e[t].dirty=true;}_addLayer({name:e,states:t,transitions:i,weight:s,mask:r,blendType:a}){let n;n=this.rootBone?this.rootBone:this.entity;let o=this._layers.length,l=new Es(new Tj(new Eh(this,n,e,r,o)),t,i,this._activate,this,this.findParameter,this.consumeTrigger);return this._layers.push(new Ec(e,l,this,s,a)),this._layerIndices[e]=o,this._layers[o]}addLayer(e,t,i,s){let r=this.findAnimationLayer(e);return r||this._addLayer({name:e,states:[{name:"START",speed:1}],transitions:[],weight:t,mask:i,blendType:s})}_assignParameters(e){this._parameters={};let t=Object.keys(e.parameters);for(let i=0;i<t.length;i++){let s=t[i];this._parameters[s]={type:e.parameters[s].type,value:e.parameters[s].value};}}loadStateGraph(e){this._stateGraph=e,this._assignParameters(e),this._layers=[];let t=false;for(let i=0;i<e.layers.length;i++){let s=e.layers[i];this._addLayer({...s}),s.states.some(e=>e.blendTree)&&(t=true);}t||this.setupAnimationAssets();}setupAnimationAssets(){for(let e=0;e<this._layers.length;e++){let t=this._layers[e],i=t.name;for(let e=0;e<t.states.length;e++){let s=t.states[e];if(-1===TW.indexOf(s)){let e=`${i}:${s}`;this._animationAssets[e]||(this._animationAssets[e]={asset:null});}}}this.loadAnimationAssets();}loadAnimationAssets(){for(let e=0;e<this._layers.length;e++){let t=this._layers[e];for(let e=0;e<t.states.length;e++){let i=t.states[e];if(-1!==TW.indexOf(i))continue;let s=this._animationAssets[`${t.name}:${i}`];if(!s||!s.asset){this.findAnimationLayer(t.name).assignAnimation(i,TZ.EMPTY);continue}let r=s.asset,a=this.system.app.assets.get(r);a&&(a.resource?this.onAnimationAssetLoaded(t.name,i,a):(a.once("load",(function(e,t){return (function(i){this.onAnimationAssetLoaded(e,t,i);}).bind(this)}).bind(this)(t.name,i)),this.system.app.assets.load(a)));}}}onAnimationAssetLoaded(e,t,i){this.findAnimationLayer(e).assignAnimation(t,i.resource);}removeStateGraph(){this._stateGraph=null,this._stateGraphAsset=null,this._animationAssets={},this._layers=[],this._layerIndices={},this._parameters={},this._playing=false,this.unbind(),this._targets={};}reset(){this._assignParameters(this._stateGraph);for(let e=0;e<this._layers.length;e++){let t=this._layers[e].playing;this._layers[e].reset(),this._layers[e].playing=t;}}unbind(){this._normalizeWeights||Object.keys(this._targets).forEach(e=>{this._targets[e].unbind();});}rebind(){this._targets={};for(let e=0;e<this._layers.length;e++)this._layers[e].rebind();}findAnimationLayer(e){let t=this._layerIndices[e];return this._layers[t]||null}addAnimationState(e,t,i=1,s=true,r="Base"){this._stateGraph||this.loadStateGraph(new Ed({layers:[{name:r,states:[{name:"START",speed:1},{name:e,speed:i,loop:s,defaultState:true}],transitions:[{from:"START",to:e}]}],parameters:{}}));let a=this.findAnimationLayer(r);a?a.assignAnimation(e,t,i,s):this.addLayer(r)?.assignAnimation(e,t,i,s);}assignAnimation(e,t,i,s=1,r=true){if(!this._stateGraph&&-1===e.indexOf(".")){this.loadStateGraph(new Ed({layers:[{name:"Base",states:[{name:"START",speed:1},{name:e,speed:s,loop:r,defaultState:true}],transitions:[{from:"START",to:e}]}],parameters:{}})),this.baseLayer.assignAnimation(e,t);return}let a=i?this.findAnimationLayer(i):this.baseLayer;a&&a.assignAnimation(e,t,s,r);}removeNodeAnimations(e,t){let i=t?this.findAnimationLayer(t):this.baseLayer;i&&i.removeNodeAnimations(e);}getParameterValue(e,t){let i=this._parameters[e];if(i&&i.type===t)return i.value}setParameterValue(e,t,i){let s=this._parameters[e];if(s&&s.type===t){s.value=i;return}}getFloat(e){return this.getParameterValue(e,TO)}setFloat(e,t){this.setParameterValue(e,TO,t);}getInteger(e){return this.getParameterValue(e,TM)}setInteger(e,t){"number"==typeof t&&t%1==0&&this.setParameterValue(e,TM,t);}getBoolean(e){return this.getParameterValue(e,TN)}setBoolean(e,t){this.setParameterValue(e,TN,!!t);}getTrigger(e){return this.getParameterValue(e,TF)}setTrigger(e,t=false){this.setParameterValue(e,TF,true),t&&this._consumedTriggers.add(e);}resetTrigger(e){this.setParameterValue(e,TF,false);}onBeforeRemove(){Number.isFinite(this._stateGraphAsset)&&this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this);}update(e){for(let t=0;t<this.layers.length;t++)this.layers[t].update(e*this.speed);this._consumedTriggers.forEach(e=>{this.parameters[e].value=false;}),this._consumedTriggers.clear();}resolveDuplicatedEntityReferenceProperties(e,t){e.rootBone&&t[e.rootBone.getGuid()]?this.rootBone=t[e.rootBone.getGuid()]:this.rebind();}constructor(...e){super(...e),this._stateGraphAsset=null,this._animationAssets={},this._speed=1,this._activate=true,this._playing=false,this._rootBone=null,this._stateGraph=null,this._layers=[],this._layerIndices={},this._parameters={},this._targets={},this._consumedTriggers=new Set,this._normalizeWeights=false,this.findParameter=e=>this._parameters[e],this.consumeTrigger=e=>{this._consumedTriggers.add(e);};}}class Ef{constructor(){this.enabled=true;}}let Ep=["enabled"];class Em extends Tm{constructor(e){super(e),this.id="anim",this.ComponentType=Eu,this.DataType=Ef,this.schema=Ep,this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("animationUpdate",this.onAnimationUpdate,this);}initializeComponentData(e,t,i){super.initializeComponentData(e,t,Ep);let s=["animationAssets","stateGraph","layers","masks"];Object.keys(t).forEach(i=>{s.includes(i)||(e[i]=t[i]);}),t.stateGraph&&(e.stateGraph=t.stateGraph,e.loadStateGraph(e.stateGraph)),t.layers&&t.layers.forEach((t,i)=>{t._controller.states.forEach(s=>{t._controller._states[s]._animationList.forEach(s=>{if(s.animTrack&&s.animTrack!==TZ.EMPTY)e.layers[i].assignAnimation(s.name,s.animTrack);else {let r=this.app.assets.get(t._component._animationAssets[`${t.name}:${s.name}`].asset);r&&!r.loaded&&r.once("load",()=>{e.layers[i].assignAnimation(s.name,r.resource);});}});});}),t.animationAssets&&(e.animationAssets=Object.assign(e.animationAssets,t.animationAssets)),t.masks&&Object.keys(t.masks).forEach(i=>{if(e.layers[i]){let s=t.masks[i].mask,r={};Object.keys(s).forEach(e=>{r[decodeURI(e)]=s[e];}),e.layers[i].mask=r;}});}onAnimationUpdate(e){let t=this.store;for(let i in t)if(t.hasOwnProperty(i)){let s=t[i].entity.anim;s.data.enabled&&s.entity.enabled&&s.playing&&s.update(e);}}cloneComponent(e,t){let i;e.anim.rootBone&&e.anim.rootBone!==e||(i={},e.anim.layers.forEach((e,s)=>{if(e.mask){let r={};Object.keys(e.mask).forEach(i=>{let s=i.split("/");s.shift(),r[[t.name,...s].join("/")]=e.mask[i];}),i[s]={mask:r};}}));let s={enabled:e.anim.enabled,stateGraphAsset:e.anim.stateGraphAsset,animationAssets:e.anim.animationAssets,speed:e.anim.speed,activate:e.anim.activate,playing:e.anim.playing,rootBone:e.anim.rootBone,stateGraph:e.anim.stateGraph,layers:e.anim.layers,layerIndices:e.anim.layerIndices,parameters:e.anim.parameters,normalizeWeights:e.anim.normalizeWeights,masks:i};return this.addComponent(t,s)}onBeforeRemove(e,t){t.onBeforeRemove();}destroy(){super.destroy(),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this);}}Tp._buildAccessors(Eu.prototype,Ep);class E_ extends Tp{setCurrentListener(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;let e=this.system.current.getPosition();this.system.manager.listener.setPosition(e);}}onEnable(){this.setCurrentListener();}onDisable(){this.system.current===this.entity&&(this.system.current=null);}}class Eg{constructor(){this.enabled=true;}}let Ev=["enabled"];class ES extends Tm{constructor(e){super(e),this.id="audiolistener",this.ComponentType=E_,this.DataType=Eg,this.schema=Ev,this.manager=e.soundManager,this.current=null,this.app.systems.on("update",this.onUpdate,this);}initializeComponentData(e,t,i){i=["enabled"],super.initializeComponentData(e,t,i);}onUpdate(e){if(this.current){let e=this.current.getPosition();this.manager.listener.setPosition(e);let t=this.current.getWorldTransform();this.manager.listener.setOrientation(t);}}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this);}}Tp._buildAccessors(E_.prototype,Ev);let Ey=0,Ex=1,ET="group",EE="image",EA="text",Eb="stretch",Ew="contain",EC="cover",EP={DEFAULT:"DEFAULT",HOVER:"HOVER",PRESSED:"PRESSED",INACTIVE:"INACTIVE"},EL={};EL[EP.DEFAULT]="_defaultTint",EL[EP.HOVER]="hoverTint",EL[EP.PRESSED]="pressedTint",EL[EP.INACTIVE]="inactiveTint";let EI={};EI[EP.DEFAULT]="_defaultSpriteAsset",EI[EP.HOVER]="hoverSpriteAsset",EI[EP.PRESSED]="pressedSpriteAsset",EI[EP.INACTIVE]="inactiveSpriteAsset";let ED={};ED[EP.DEFAULT]="_defaultSpriteFrame",ED[EP.HOVER]="hoverSpriteFrame",ED[EP.PRESSED]="pressedSpriteFrame",ED[EP.INACTIVE]="inactiveSpriteFrame";class ER extends Tp{static{this.EVENT_MOUSEDOWN="mousedown";}static{this.EVENT_MOUSEUP="mouseup";}static{this.EVENT_MOUSEENTER="mouseenter";}static{this.EVENT_MOUSELEAVE="mouseleave";}static{this.EVENT_CLICK="click";}static{this.EVENT_TOUCHSTART="touchstart";}static{this.EVENT_TOUCHEND="touchend";}static{this.EVENT_TOUCHCANCEL="touchcancel";}static{this.EVENT_TOUCHLEAVE="touchleave";}static{this.EVENT_SELECTSTART="selectstart";}static{this.EVENT_SELECTEND="selectend";}static{this.EVENT_SELECTENTER="selectenter";}static{this.EVENT_SELECTLEAVE="selectleave";}static{this.EVENT_HOVERSTART="hoverstart";}static{this.EVENT_HOVEREND="hoverend";}static{this.EVENT_PRESSEDSTART="pressedstart";}static{this.EVENT_PRESSEDEND="pressedend";}constructor(e,t){super(e,t),this._visualState=EP.DEFAULT,this._isHovering=false,this._hoveringCounter=0,this._isPressed=false,this._defaultTint=new eb(1,1,1,1),this._defaultSpriteAsset=null,this._defaultSpriteFrame=0,this._imageEntity=null,this._evtElementAdd=null,this._evtImageEntityElementAdd=null,this._evtImageEntityElementRemove=null,this._evtImageEntityElementColor=null,this._evtImageEntityElementOpacity=null,this._evtImageEntityElementSpriteAsset=null,this._evtImageEntityElementSpriteFrame=null,this._visualState=EP.DEFAULT,this._isHovering=false,this._hoveringCounter=0,this._isPressed=false,this._defaultTint=new eb(1,1,1,1),this._defaultSpriteAsset=null,this._defaultSpriteFrame=0,this._toggleLifecycleListeners("on",e);}get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){this._setValue("enabled",e);}get enabled(){return this.data.enabled}set active(e){this._setValue("active",e);}get active(){return this.data.active}set imageEntity(e){if(this._imageEntity!==e){let t="string"==typeof e;(!this._imageEntity||!t||this._imageEntity.getGuid()!==e)&&(this._imageEntity&&this._imageEntityUnsubscribe(),e instanceof _c?this._imageEntity=e:t?this._imageEntity=this.system.app.getEntityFromIndex(e)||null:this._imageEntity=null,this._imageEntity&&this._imageEntitySubscribe(),this._imageEntity?this.data.imageEntity=this._imageEntity.getGuid():t&&e&&(this.data.imageEntity=e));}}get imageEntity(){return this._imageEntity}set hitPadding(e){this._setValue("hitPadding",e);}get hitPadding(){return this.data.hitPadding}set transitionMode(e){this._setValue("transitionMode",e);}get transitionMode(){return this.data.transitionMode}set hoverTint(e){this._setValue("hoverTint",e);}get hoverTint(){return this.data.hoverTint}set pressedTint(e){this._setValue("pressedTint",e);}get pressedTint(){return this.data.pressedTint}set inactiveTint(e){this._setValue("inactiveTint",e);}get inactiveTint(){return this.data.inactiveTint}set fadeDuration(e){this._setValue("fadeDuration",e);}get fadeDuration(){return this.data.fadeDuration}set hoverSpriteAsset(e){this._setValue("hoverSpriteAsset",e);}get hoverSpriteAsset(){return this.data.hoverSpriteAsset}set hoverSpriteFrame(e){this._setValue("hoverSpriteFrame",e);}get hoverSpriteFrame(){return this.data.hoverSpriteFrame}set pressedSpriteAsset(e){this._setValue("pressedSpriteAsset",e);}get pressedSpriteAsset(){return this.data.pressedSpriteAsset}set pressedSpriteFrame(e){this._setValue("pressedSpriteFrame",e);}get pressedSpriteFrame(){return this.data.pressedSpriteFrame}set inactiveSpriteAsset(e){this._setValue("inactiveSpriteAsset",e);}get inactiveSpriteAsset(){return this.data.inactiveSpriteAsset}set inactiveSpriteFrame(e){this._setValue("inactiveSpriteFrame",e);}get inactiveSpriteFrame(){return this.data.inactiveSpriteFrame}_setValue(e,t){let i=this.data,s=i[e];i[e]=t,this.fire("set",e,s,t);}_toggleLifecycleListeners(e,t){this[e]("set_active",this._onSetActive,this),this[e]("set_transitionMode",this._onSetTransitionMode,this),this[e]("set_hoverTint",this._onSetTransitionValue,this),this[e]("set_pressedTint",this._onSetTransitionValue,this),this[e]("set_inactiveTint",this._onSetTransitionValue,this),this[e]("set_hoverSpriteAsset",this._onSetTransitionValue,this),this[e]("set_hoverSpriteFrame",this._onSetTransitionValue,this),this[e]("set_pressedSpriteAsset",this._onSetTransitionValue,this),this[e]("set_pressedSpriteFrame",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteAsset",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteFrame",this._onSetTransitionValue,this),"on"===e?this._evtElementAdd=this.entity.on("element:add",this._onElementComponentAdd,this):(this._evtElementAdd?.off(),this._evtElementAdd=null);}_onSetActive(e,t,i){t!==i&&this._updateVisualState();}_onSetTransitionMode(e,t,i){t!==i&&(this._cancelTween(),this._resetToDefaultVisualState(t),this._forceReapplyVisualState());}_onSetTransitionValue(e,t,i){t!==i&&this._forceReapplyVisualState();}_imageEntitySubscribe(){this._evtImageEntityElementAdd=this._imageEntity.on("element:add",this._onImageElementGain,this),this._imageEntity.element&&this._onImageElementGain();}_imageEntityUnsubscribe(){this._evtImageEntityElementAdd?.off(),this._evtImageEntityElementAdd=null,this._imageEntity?.element&&this._onImageElementLose();}_imageEntityElementSubscribe(){let e=this._imageEntity.element;this._evtImageEntityElementRemove=e.once("beforeremove",this._onImageElementLose,this),this._evtImageEntityElementColor=e.on("set:color",this._onSetColor,this),this._evtImageEntityElementOpacity=e.on("set:opacity",this._onSetOpacity,this),this._evtImageEntityElementSpriteAsset=e.on("set:spriteAsset",this._onSetSpriteAsset,this),this._evtImageEntityElementSpriteFrame=e.on("set:spriteFrame",this._onSetSpriteFrame,this);}_imageEntityElementUnsubscribe(){this._evtImageEntityElementRemove?.off(),this._evtImageEntityElementRemove=null,this._evtImageEntityElementColor?.off(),this._evtImageEntityElementColor=null,this._evtImageEntityElementOpacity?.off(),this._evtImageEntityElementOpacity=null,this._evtImageEntityElementSpriteAsset?.off(),this._evtImageEntityElementSpriteAsset=null,this._evtImageEntityElementSpriteFrame?.off(),this._evtImageEntityElementSpriteFrame=null;}_onElementComponentRemove(){this._toggleHitElementListeners("off");}_onElementComponentAdd(){this._toggleHitElementListeners("on");}_onImageElementLose(){this._imageEntityElementUnsubscribe(),this._cancelTween(),this._resetToDefaultVisualState(this.transitionMode);}_onImageElementGain(){this._imageEntityElementSubscribe(),this._storeDefaultVisualState(),this._forceReapplyVisualState();}_toggleHitElementListeners(e){if(this.entity.element){let t="on"===e;t&&this._hasHitElementListeners||(this.entity.element[e]("beforeremove",this._onElementComponentRemove,this),this.entity.element[e]("mouseenter",this._onMouseEnter,this),this.entity.element[e]("mouseleave",this._onMouseLeave,this),this.entity.element[e]("mousedown",this._onMouseDown,this),this.entity.element[e]("mouseup",this._onMouseUp,this),this.entity.element[e]("touchstart",this._onTouchStart,this),this.entity.element[e]("touchend",this._onTouchEnd,this),this.entity.element[e]("touchleave",this._onTouchLeave,this),this.entity.element[e]("touchcancel",this._onTouchCancel,this),this.entity.element[e]("selectstart",this._onSelectStart,this),this.entity.element[e]("selectend",this._onSelectEnd,this),this.entity.element[e]("selectenter",this._onSelectEnter,this),this.entity.element[e]("selectleave",this._onSelectLeave,this),this.entity.element[e]("click",this._onClick,this),this._hasHitElementListeners=t);}}_storeDefaultVisualState(){let e=this._imageEntity?.element;e&&e.type!==ET&&(this._storeDefaultColor(e.color),this._storeDefaultOpacity(e.opacity),this._storeDefaultSpriteAsset(e.spriteAsset),this._storeDefaultSpriteFrame(e.spriteFrame));}_storeDefaultColor(e){this._defaultTint.r=e.r,this._defaultTint.g=e.g,this._defaultTint.b=e.b;}_storeDefaultOpacity(e){this._defaultTint.a=e;}_storeDefaultSpriteAsset(e){this._defaultSpriteAsset=e;}_storeDefaultSpriteFrame(e){this._defaultSpriteFrame=e;}_onSetColor(e){this._isApplyingTint||(this._storeDefaultColor(e),this._forceReapplyVisualState());}_onSetOpacity(e){this._isApplyingTint||(this._storeDefaultOpacity(e),this._forceReapplyVisualState());}_onSetSpriteAsset(e){this._isApplyingSprite||(this._storeDefaultSpriteAsset(e),this._forceReapplyVisualState());}_onSetSpriteFrame(e){this._isApplyingSprite||(this._storeDefaultSpriteFrame(e),this._forceReapplyVisualState());}_onMouseEnter(e){this._isHovering=true,this._updateVisualState(),this._fireIfActive("mouseenter",e);}_onMouseLeave(e){this._isHovering=false,this._isPressed=false,this._updateVisualState(),this._fireIfActive("mouseleave",e);}_onMouseDown(e){this._isPressed=true,this._updateVisualState(),this._fireIfActive("mousedown",e);}_onMouseUp(e){this._isPressed=false,this._updateVisualState(),this._fireIfActive("mouseup",e);}_onTouchStart(e){this._isPressed=true,this._updateVisualState(),this._fireIfActive("touchstart",e);}_onTouchEnd(e){e.event.preventDefault(),this._isPressed=false,this._updateVisualState(),this._fireIfActive("touchend",e);}_onTouchLeave(e){this._isPressed=false,this._updateVisualState(),this._fireIfActive("touchleave",e);}_onTouchCancel(e){this._isPressed=false,this._updateVisualState(),this._fireIfActive("touchcancel",e);}_onSelectStart(e){this._isPressed=true,this._updateVisualState(),this._fireIfActive("selectstart",e);}_onSelectEnd(e){this._isPressed=false,this._updateVisualState(),this._fireIfActive("selectend",e);}_onSelectEnter(e){this._hoveringCounter++,1===this._hoveringCounter&&(this._isHovering=true,this._updateVisualState()),this._fireIfActive("selectenter",e);}_onSelectLeave(e){this._hoveringCounter--,0===this._hoveringCounter&&(this._isHovering=false,this._isPressed=false,this._updateVisualState()),this._fireIfActive("selectleave",e);}_onClick(e){this._fireIfActive("click",e);}_fireIfActive(e,t){this.data.active&&this.fire(e,t);}_updateVisualState(e){let t=this._visualState,i=this._determineVisualState();if((t!==i||e)&&this.enabled)switch(this._visualState=i,t===EP.HOVER&&this._fireIfActive("hoverend"),t===EP.PRESSED&&this._fireIfActive("pressedend"),i===EP.HOVER&&this._fireIfActive("hoverstart"),i===EP.PRESSED&&this._fireIfActive("pressedstart"),this.transitionMode){case Ey:{let e=this[EL[this._visualState]];this._applyTint(e);break}case Ex:{let e=EI[this._visualState],t=ED[this._visualState],i=this[e],s=this[t];this._applySprite(i,s);}}}_forceReapplyVisualState(){this._updateVisualState(true);}_resetToDefaultVisualState(e){if(this._imageEntity?.element)switch(e){case Ey:this._cancelTween(),this._applyTintImmediately(this._defaultTint);break;case Ex:this._applySprite(this._defaultSpriteAsset,this._defaultSpriteFrame);}}_determineVisualState(){return this.active?this._isPressed?EP.PRESSED:this._isHovering?EP.HOVER:EP.DEFAULT:EP.INACTIVE}_applySprite(e,t){let i=this._imageEntity?.element;i&&(t=t||0,this._isApplyingSprite=true,i.spriteAsset!==e&&(i.spriteAsset=e),i.spriteFrame!==t&&(i.spriteFrame=t),this._isApplyingSprite=false);}_applyTint(e){this._cancelTween(),0===this.fadeDuration?this._applyTintImmediately(e):this._applyTintWithTween(e);}_applyTintImmediately(e){let t=this._imageEntity?.element;if(!e||!t||t.type===ET)return;let i=EM(e);this._isApplyingTint=true,i.equals(t.color)||(t.color=i),t.opacity!==e.a&&(t.opacity=e.a),this._isApplyingTint=false;}_applyTintWithTween(e){let t=this._imageEntity?.element;if(!e||!t||t.type===ET)return;let i=EM(e),s=t.color,r=t.opacity;i.equals(s)&&e.a===r||(this._tweenInfo={startTime:em(),from:new eb(s.r,s.g,s.b,r),to:e.clone(),lerpColor:new eb});}_updateTintTween(){let e=em()-this._tweenInfo.startTime,t=0===this.fadeDuration?1:e/this.fadeDuration;if(Math.abs((t=eA.clamp(t,0,1))-1)>1e-5){let e=this._tweenInfo.lerpColor;e.lerp(this._tweenInfo.from,this._tweenInfo.to,t),this._applyTintImmediately(new eb(e.r,e.g,e.b,e.a));}else this._applyTintImmediately(this._tweenInfo.to),this._cancelTween();}_cancelTween(){delete this._tweenInfo;}onUpdate(){this._tweenInfo&&this._updateTintTween();}onEnable(){this._isHovering=false,this._hoveringCounter=0,this._isPressed=false,this._toggleHitElementListeners("on"),this._forceReapplyVisualState();}onDisable(){this._toggleHitElementListeners("off"),this._resetToDefaultVisualState(this.transitionMode);}onRemove(){this._imageEntityUnsubscribe(),this._toggleLifecycleListeners("off",this.system),this.onDisable();}resolveDuplicatedEntityReferenceProperties(e,t){e.imageEntity&&(this.imageEntity=t[e.imageEntity.getGuid()]);}}function EM(e){return new eb(e.r,e.g,e.b)}class EO{constructor(){this.enabled=true,this.active=true,this.imageEntity=null,this.hitPadding=new eF,this.transitionMode=Ey,this.hoverTint=new eb(.75,.75,.75),this.pressedTint=new eb(.5,.5,.5),this.inactiveTint=new eb(.25,.25,.25),this.fadeDuration=0,this.hoverSpriteAsset=null,this.hoverSpriteFrame=0,this.pressedSpriteAsset=null,this.pressedSpriteFrame=0,this.inactiveSpriteAsset=null,this.inactiveSpriteFrame=0;}}let EN=["enabled","active",{name:"hitPadding",type:"vec4"},"transitionMode",{name:"hoverTint",type:"rgba"},{name:"pressedTint",type:"rgba"},{name:"inactiveTint",type:"rgba"},"fadeDuration","hoverSpriteAsset","hoverSpriteFrame","pressedSpriteAsset","pressedSpriteFrame","inactiveSpriteAsset","inactiveSpriteFrame"];class EF extends Tm{constructor(e){super(e),this.id="button",this.ComponentType=ER,this.DataType=EO,this.schema=EN,this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("update",this.onUpdate,this);}initializeComponentData(e,t,i){e.imageEntity=t.imageEntity,super.initializeComponentData(e,t,EN);}onUpdate(e){let t=this.store;for(let e in t){let i=t[e].entity,s=i.button;s.enabled&&i.enabled&&s.onUpdate();}}_onRemoveComponent(e,t){t.onRemove();}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this);}}let EB=new eM,EU=new eH;class Ek extends Tp{static{this.EVENT_CONTACT="contact";}static{this.EVENT_COLLISIONSTART="collisionstart";}static{this.EVENT_COLLISIONEND="collisionend";}static{this.EVENT_TRIGGERENTER="triggerenter";}static{this.EVENT_TRIGGERLEAVE="triggerleave";}constructor(e,t){super(e,t),this._compoundParent=null,this._hasOffset=false,this.entity.on("insert",this._onInsert,this),this.on("set_type",this.onSetType,this),this.on("set_convexHull",this.onSetModel,this),this.on("set_halfExtents",this.onSetHalfExtents,this),this.on("set_linearOffset",this.onSetOffset,this),this.on("set_angularOffset",this.onSetOffset,this),this.on("set_radius",this.onSetRadius,this),this.on("set_height",this.onSetHeight,this),this.on("set_axis",this.onSetAxis,this),this.on("set_asset",this.onSetAsset,this),this.on("set_renderAsset",this.onSetRenderAsset,this),this.on("set_model",this.onSetModel,this),this.on("set_render",this.onSetRender,this);}get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){this._setValue("enabled",e);}get enabled(){return this.data.enabled}set type(e){this._setValue("type",e);}get type(){return this.data.type}set halfExtents(e){this._setValue("halfExtents",e);}get halfExtents(){return this.data.halfExtents}set linearOffset(e){this._setValue("linearOffset",e);}get linearOffset(){return this.data.linearOffset}set angularOffset(e){this._setValue("angularOffset",e);}get angularOffset(){return this.data.angularOffset}set radius(e){this._setValue("radius",e);}get radius(){return this.data.radius}set axis(e){this._setValue("axis",e);}get axis(){return this.data.axis}set height(e){this._setValue("height",e);}get height(){return this.data.height}set asset(e){this._setValue("asset",e);}get asset(){return this.data.asset}set renderAsset(e){this._setValue("renderAsset",e);}get renderAsset(){return this.data.renderAsset}set convexHull(e){this._setValue("convexHull",e);}get convexHull(){return this.data.convexHull}set shape(e){this._setValue("shape",e);}get shape(){return this.data.shape}set model(e){this._setValue("model",e);}get model(){return this.data.model}set render(e){this._setValue("render",e);}get render(){return this.data.render}set checkVertexDuplicates(e){this._setValue("checkVertexDuplicates",e);}get checkVertexDuplicates(){return this.data.checkVertexDuplicates}_setValue(e,t){let i=this.data,s=i[e];i[e]=t,this.fire("set",e,s,t);}onSetType(e,t,i){t!==i&&this.system.changeType(this,t,i);}onSetHalfExtents(e,t,i){let s=this.data.type;this.data.initialized&&"box"===s&&this.system.recreatePhysicalShapes(this);}onSetOffset(e,t,i){this._hasOffset=!this.data.linearOffset.equals(eM.ZERO)||!this.data.angularOffset.equals(eH.IDENTITY),this.data.initialized&&this.system.recreatePhysicalShapes(this);}onSetRadius(e,t,i){let s=this.data.type;this.data.initialized&&("sphere"===s||"capsule"===s||"cylinder"===s||"cone"===s)&&this.system.recreatePhysicalShapes(this);}onSetHeight(e,t,i){let s=this.data.type;this.data.initialized&&("capsule"===s||"cylinder"===s||"cone"===s)&&this.system.recreatePhysicalShapes(this);}onSetAxis(e,t,i){let s=this.data.type;this.data.initialized&&("capsule"===s||"cylinder"===s||"cone"===s)&&this.system.recreatePhysicalShapes(this);}onSetAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&e.off("remove",this.onAssetRemoved,this);}if(i){i instanceof xF&&(this.data.asset=i.id);let e=s.get(this.data.asset);e&&(e.off("remove",this.onAssetRemoved,this),e.on("remove",this.onAssetRemoved,this));}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.model=null),this.system.recreatePhysicalShapes(this));}onSetRenderAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&e.off("remove",this.onRenderAssetRemoved,this);}if(i){i instanceof xF&&(this.data.renderAsset=i.id);let e=s.get(this.data.renderAsset);e&&(e.off("remove",this.onRenderAssetRemoved,this),e.on("remove",this.onRenderAssetRemoved,this));}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.render=null),this.system.recreatePhysicalShapes(this));}onSetModel(e,t,i){this.data.initialized&&"mesh"===this.data.type&&this.system.implementations.mesh.doRecreatePhysicalShape(this);}onSetRender(e,t,i){this.onSetModel(e,t,i);}onAssetRemoved(e){e.off("remove",this.onAssetRemoved,this),this.data.asset===e.id&&(this.asset=null);}onRenderAssetRemoved(e){e.off("remove",this.onRenderAssetRemoved,this),this.data.renderAsset===e.id&&(this.renderAsset=null);}getCompoundChildShapeIndex(e){let t=this.data.shape,i=t.getNumChildShapes();for(let s=0;s<i;s++){let i=t.getChildShape(s);if(Ammo.getPointer(i)===Ammo.getPointer(e))return s}return null}_onInsert(e){if("undefined"!=typeof Ammo){if(this._compoundParent)this.system.recreatePhysicalShapes(this);else if(!this.entity.rigidbody){let e=this.entity.parent;for(;e;){if(e.collision&&"compound"===e.collision.type){0===e.collision.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(e.collision):this.system.recreatePhysicalShapes(this);break}e=e.parent;}}}}_updateCompound(){let e=this.entity;if(e._dirtyWorld){let t=e._dirtyLocal,i=e;for(;i&&!t&&(!i.collision||i.collision!==this._compoundParent);)i._dirtyLocal&&(t=true),i=i.parent;if(t){e.forEach(this.system.implementations.compound._updateEachDescendantTransform,e);let t=this._compoundParent.entity.rigidbody;t&&t.activate();}}}getShapePosition(){let e=this.entity.getPosition();if(this._hasOffset){let t=this.entity.getRotation(),i=this.data.linearOffset;return EU.copy(t).transformVector(i,EB),EB.add(e)}return e}getShapeRotation(){let e=this.entity.getRotation();return this._hasOffset?EU.copy(e).mul(this.data.angularOffset):e}onEnable(){if("mesh"===this.data.type&&(this.data.asset||this.data.renderAsset)&&this.data.initialized){let e=this.system.app.assets.get(this.data.asset||this.data.renderAsset);if(e&&(!e.resource||!this.data.shape))return void this.system.recreatePhysicalShapes(this)}if(this.entity.rigidbody)this.entity.rigidbody.enabled&&this.entity.rigidbody.enableSimulation();else if(this._compoundParent&&this!==this._compoundParent)if(0===this._compoundParent.shape.getNumChildShapes())this.system.recreatePhysicalShapes(this._compoundParent);else {let e=this.system._getNodeTransform(this.entity,this._compoundParent.entity);this._compoundParent.shape.addChildShape(e,this.data.shape),Ammo.destroy(e),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate();}else this.entity.trigger&&this.entity.trigger.enable();}onDisable(){this.entity.rigidbody?this.entity.rigidbody.disableSimulation():this._compoundParent&&this!==this._compoundParent?!this._compoundParent.entity._destroying&&(this.system._removeCompoundChild(this._compoundParent,this.data.shape),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()):this.entity.trigger&&this.entity.trigger.disable();}onBeforeRemove(){this.asset&&(this.asset=null),this.renderAsset&&(this.renderAsset=null),this.entity.off("insert",this._onInsert,this),this.off();}}class EV{constructor(){this.enabled=true,this.type="box",this.halfExtents=new eM(.5,.5,.5),this.linearOffset=new eM,this.angularOffset=new eH,this.radius=.5,this.axis=1,this.height=2,this.convexHull=false,this.asset=null,this.renderAsset=null,this.checkVertexDuplicates=true,this.shape=null,this.model=null,this.render=null,this.initialized=false;}}let Ez="static",EG="dynamic",EH="kinematic",EW=1,EX=2,EY=4,Eq=1,E$=2,Ej=3,EK=4,EZ=5,EQ=0,EJ=1,E0=1,E1=2,E2=4,E3=8,E4=16,E5=32,E8=64,E6=128,E9=256,E7=512,Ae=1024,At=2048,Ai=4096,As=8192,Ar=16384,Aa=0,An=65535,Ao=2,Al=65533,Ah=65529;class Ac{constructor(e,t,i){this.entity=t.entity,this.component=t,this.app=e,"undefined"==typeof Ammo||r||(r=new Ammo.btVector3,a=new Ammo.btQuaternion,n=new Ammo.btTransform),this.initialize(i);}initialize(e){let t=this.entity,i=e.shape;if(i&&"undefined"!=typeof Ammo){t.trigger&&t.trigger.destroy();let e=this.component;if(e){let t=e.getShapePosition(),i=e.getShapeRotation();r.setValue(t.x,t.y,t.z),a.setValue(i.x,i.y,i.z,i.w);}else {let e=t.getPosition(),i=t.getRotation();r.setValue(e.x,e.y,e.z),a.setValue(i.x,i.y,i.z,i.w);}n.setOrigin(r),n.setRotation(a);let s=this.app.systems.rigidbody.createBody(1,i,n);s.setRestitution(0),s.setFriction(0),s.setDamping(0,0),r.setValue(0,0,0),s.setLinearFactor(r),s.setAngularFactor(r),s.setCollisionFlags(s.getCollisionFlags()|EY),s.entity=t,this.body=s,this.component.enabled&&t.enabled&&this.enable();}}destroy(){this.body&&(this.disable(),this.app.systems.rigidbody.destroyBody(this.body),this.body=null);}_getEntityTransform(e){let t=this.component;if(t){let e=t.getShapePosition(),i=t.getShapeRotation();r.setValue(e.x,e.y,e.z),a.setValue(i.x,i.y,i.z,i.w);}else {let e=this.entity.getPosition(),t=this.entity.getRotation();r.setValue(e.x,e.y,e.z),a.setValue(t.x,t.y,t.z,t.w);}e.setOrigin(r),e.setRotation(a);}updateTransform(){this._getEntityTransform(n);let e=this.body;e.setWorldTransform(n),e.activate();}enable(){let e=this.body;if(!e)return;let t=this.app.systems.rigidbody;0>t._triggers.indexOf(this)&&(t.addBody(e,E4,Al^E4),t._triggers.push(this)),e.forceActivationState(Eq),this.updateTransform();}disable(){let e=this.body;if(!e)return;let t=this.app.systems.rigidbody,i=t._triggers.indexOf(this);i>-1&&(t.removeBody(e),t._triggers.splice(i,1)),e.forceActivationState(EZ);}}let Ad=new eG,Au=new eM,Af=new eM,Ap=new eH,Am=new _c,A_=["enabled","type","halfExtents","linearOffset","angularOffset","radius","axis","height","convexHull","asset","renderAsset","shape","model","render","checkVertexDuplicates"];class Ag{constructor(e){this.system=e;}beforeInitialize(e,t){t.shape=null,t.model=new g5,t.model.graph=new _c;}afterInitialize(e,t){this.recreatePhysicalShapes(e),e.data.initialized=true;}reset(e,t){this.beforeInitialize(e,t),this.afterInitialize(e,t);}recreatePhysicalShapes(e){let t=e.entity,i=e.data;if("undefined"!=typeof Ammo){t.trigger&&(t.trigger.destroy(),delete t.trigger),i.shape&&(e._compoundParent&&(e!==e._compoundParent&&this.system._removeCompoundChild(e._compoundParent,i.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),this.destroyShape(i)),i.shape=this.createPhysicalShape(e.entity,i);let s=!e._compoundParent;if("compound"!==i.type||e._compoundParent&&e!==e._compoundParent){if("compound"!==i.type&&!e.rigidbody){e._compoundParent=null;let i=t.parent;for(;i;){if(i.collision&&"compound"===i.collision.type){e._compoundParent=i.collision;break}i=i.parent;}}}else e._compoundParent=e,t.forEach(this._addEachDescendant,e);e._compoundParent&&e!==e._compoundParent&&(s&&0===e._compoundParent.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(e._compoundParent):(this.system.updateCompoundChildTransform(t,true),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate())),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):e._compoundParent||(t.trigger?t.trigger.initialize(i):t.trigger=new Ac(this.system.app,e,i));}}createPhysicalShape(e,t){}updateTransform(e,t,i,s){e.entity.trigger&&e.entity.trigger.updateTransform();}destroyShape(e){e.shape&&(Ammo.destroy(e.shape),e.shape=null);}beforeRemove(e,t){t.data.shape&&(t._compoundParent&&!t._compoundParent.entity._destroying&&(this.system._removeCompoundChild(t._compoundParent,t.data.shape),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate()),t._compoundParent=null,this.destroyShape(t.data));}remove(e,t){e.rigidbody&&e.rigidbody.body&&e.rigidbody.disableSimulation(),e.trigger&&(e.trigger.destroy(),delete e.trigger);}clone(e,t){let i=this.system.store[e.getGuid()],s={enabled:i.data.enabled,type:i.data.type,halfExtents:[i.data.halfExtents.x,i.data.halfExtents.y,i.data.halfExtents.z],linearOffset:[i.data.linearOffset.x,i.data.linearOffset.y,i.data.linearOffset.z],angularOffset:[i.data.angularOffset.x,i.data.angularOffset.y,i.data.angularOffset.z,i.data.angularOffset.w],radius:i.data.radius,axis:i.data.axis,height:i.data.height,convexHull:i.data.convexHull,asset:i.data.asset,renderAsset:i.data.renderAsset,model:i.data.model,render:i.data.render,checkVertexDuplicates:i.data.checkVertexDuplicates};return this.system.addComponent(t,s)}}class Av extends Ag{createPhysicalShape(e,t){if("undefined"!=typeof Ammo){let e=t.halfExtents,i=new Ammo.btVector3(e?e.x:.5,e?e.y:.5,e?e.z:.5),s=new Ammo.btBoxShape(i);return Ammo.destroy(i),s}}}class AS extends Ag{createPhysicalShape(e,t){if("undefined"!=typeof Ammo)return new Ammo.btSphereShape(t.radius)}}class Ay extends Ag{createPhysicalShape(e,t){let i=t.axis??1,s=t.radius??.5,r=Math.max((t.height??2)-2*s,0),a=null;if("undefined"!=typeof Ammo)switch(i){case 0:a=new Ammo.btCapsuleShapeX(s,r);break;case 1:a=new Ammo.btCapsuleShape(s,r);break;case 2:a=new Ammo.btCapsuleShapeZ(s,r);}return a}}class Ax extends Ag{createPhysicalShape(e,t){let i=t.axis??1,s=t.radius??.5,r=t.height??1,a=null,n=null;if("undefined"!=typeof Ammo)switch(i){case 0:a=new Ammo.btVector3(.5*r,s,s),n=new Ammo.btCylinderShapeX(a);break;case 1:a=new Ammo.btVector3(s,.5*r,s),n=new Ammo.btCylinderShape(a);break;case 2:a=new Ammo.btVector3(s,s,.5*r),n=new Ammo.btCylinderShapeZ(a);}return a&&Ammo.destroy(a),n}}class AT extends Ag{createPhysicalShape(e,t){let i=t.axis??1,s=t.radius??.5,r=t.height??1,a=null;if("undefined"!=typeof Ammo)switch(i){case 0:a=new Ammo.btConeShapeX(s,r);break;case 1:a=new Ammo.btConeShape(s,r);break;case 2:a=new Ammo.btConeShapeZ(s,r);}return a}}class AE extends Ag{beforeInitialize(e,t){}createAmmoHull(e,t,i,s){let r=new Ammo.btConvexHullShape,a=new Ammo.btVector3,n=[];e.getPositions(n);for(let e=0;e<n.length;e+=3)a.setValue(n[e]*s.x,n[e+1]*s.y,n[e+2]*s.z),r.addPoint(a,false);Ammo.destroy(a),r.recalcLocalAabb(),r.setMargin(.01);let o=this.system._getNodeTransform(t);i.addChildShape(o,r),Ammo.destroy(o);}createAmmoMesh(e,t,i,s,r=true){let a,n=this.system;if(n._triMeshCache[e.id])a=n._triMeshCache[e.id];else {let t,i,o,l,h,c=e.vertexBuffer,d=c.getFormat();for(let e=0;e<d.elements.length;e++){let s=d.elements[e];if(s.name===sT){i=new Float32Array(c.lock(),s.offset),t=s.stride/4;break}}let u=[];e.getIndices(u);let f=e.primitive[0].count/3,p=new Ammo.btVector3,m=e.primitive[0].base;a=new Ammo.btTriangleMesh,n._triMeshCache[e.id]=a;let _=new Map;a.getIndexedMeshArray().at(0).m_numTriangles=f;let g=s?s.x:1,v=s?s.y:1,S=s?s.z:1,y=e=>{let s,n=i[e*t]*g,o=i[e*t+1]*v,l=i[e*t+2]*S;if(r){let e=`${n}:${o}:${l}`;if(void 0!==(s=_.get(e)))return s;p.setValue(n,o,l),s=a.findOrAddVertex(p,false),_.set(e,s);}else p.setValue(n,o,l),s=a.findOrAddVertex(p,false);return s};for(let e=0;e<f;e++)o=y(u[m+3*e]),l=y(u[m+3*e+1]),h=y(u[m+3*e+2]),a.addIndex(o),a.addIndex(l),a.addIndex(h);Ammo.destroy(p);}let o=new Ammo.btBvhTriangleMeshShape(a,true);if(!s){let e=n._getNodeScaling(t);o.setLocalScaling(e),Ammo.destroy(e);}let l=n._getNodeTransform(t);i.addChildShape(l,o),Ammo.destroy(l);}createPhysicalShape(e,t){if("undefined"!=typeof Ammo&&(t.model||t.render)){let i=new Ammo.btCompoundShape,s=e.getWorldTransform().getScale();if(t.render){let e=t.render.meshes;for(let r=0;r<e.length;r++)t.convexHull?this.createAmmoHull(e[r],Am,i,s):this.createAmmoMesh(e[r],Am,i,s,t.checkVertexDuplicates);}else if(t.model){let e=t.model.meshInstances;for(let s=0;s<e.length;s++)this.createAmmoMesh(e[s].mesh,e[s].node,i,null,t.checkVertexDuplicates);let r=new Ammo.btVector3(s.x,s.y,s.z);i.setLocalScaling(r),Ammo.destroy(r);}return i}}recreatePhysicalShapes(e){let t=e.data;if((t.renderAsset||t.asset)&&e.enabled&&e.entity.enabled)return void this.loadAsset(e,t.renderAsset||t.asset,t.renderAsset?"render":"model");this.doRecreatePhysicalShape(e);}loadAsset(e,t,i){let s=e.data,r=this.system.app.assets,a=s[i],n=t=>{s[i]===a&&(s[i]=t.resource,this.doRecreatePhysicalShape(e));},o=e=>{e.ready(e=>{if(e.data.containerAsset){let t=r.get(e.data.containerAsset);t.loaded?n(e):(t.ready(()=>{n(e);}),r.load(t));}else n(e);}),r.load(e);},l=r.get(t);l?o(l):r.once(`add:${t}`,o);}doRecreatePhysicalShape(e){let t=e.entity,i=e.data;i.model||i.render?(this.destroyShape(i),i.shape=this.createPhysicalShape(t,i),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):t.trigger?t.trigger.initialize(i):t.trigger=new Ac(this.system.app,e,i)):(this.beforeRemove(t,e),this.remove(t,i));}updateTransform(e,t,i,s){if(e.shape){let t=e.entity.getWorldTransform().getScale(),i=e.shape.getLocalScaling();(t.x!==i.x()||t.y!==i.y()||t.z!==i.z())&&this.doRecreatePhysicalShape(e);}super.updateTransform(e,t,i,s);}destroyShape(e){if(!e.shape)return;let t=e.shape.getNumChildShapes();for(let i=0;i<t;i++){let t=e.shape.getChildShape(i);Ammo.destroy(t);}Ammo.destroy(e.shape),e.shape=null;}}class AA extends Ag{createPhysicalShape(e,t){if("undefined"!=typeof Ammo)return new Ammo.btCompoundShape}_addEachDescendant(e){e.collision&&!e.rigidbody&&(e.collision._compoundParent=this,e!==this.entity&&e.collision.system.recreatePhysicalShapes(e.collision));}_updateEachDescendant(e){e.collision&&e.collision._compoundParent===this&&(e.collision._compoundParent=null,e===this.entity||e.rigidbody||e.collision.system.recreatePhysicalShapes(e.collision));}_updateEachDescendantTransform(e){e.collision&&e.collision._compoundParent===this.collision._compoundParent&&this.collision.system.updateCompoundChildTransform(e,false);}}class Ab extends Tm{constructor(e){super(e),this.id="collision",this.ComponentType=Ek,this.DataType=EV,this.schema=A_,this.implementations={},this._triMeshCache={},this.on("beforeremove",this.onBeforeRemove,this),this.on("remove",this.onRemove,this);}initializeComponentData(e,t,i){let s;i=["type","halfExtents","radius","axis","height","convexHull","shape","model","asset","render","renderAsset","enabled","linearOffset","angularOffset","checkVertexDuplicates"];let r={};for(let e=0,s=i.length;e<s;e++){let s=i[e];r[s]=t[s];}if(t.hasOwnProperty("asset")?(-1!==(s=i.indexOf("model"))&&i.splice(s,1),-1!==(s=i.indexOf("render"))&&i.splice(s,1)):t.hasOwnProperty("model")&&-1!==(s=i.indexOf("asset"))&&i.splice(s,1),r.type||(r.type=e.data.type),e.data.type=r.type,Array.isArray(r.halfExtents)&&(r.halfExtents=new eM(r.halfExtents)),Array.isArray(r.linearOffset)&&(r.linearOffset=new eM(r.linearOffset)),Array.isArray(r.angularOffset)){let e=r.angularOffset;3===e.length?r.angularOffset=new eH().setFromEulerAngles(e[0],e[1],e[2]):r.angularOffset=new eH(r.angularOffset);}let a=this._createImplementation(r.type);a.beforeInitialize(e,r),super.initializeComponentData(e,r,i),a.afterInitialize(e,r);}_createImplementation(e){if(void 0===this.implementations[e]){let t;switch(e){case "box":t=new Av(this);break;case "sphere":t=new AS(this);break;case "capsule":t=new Ay(this);break;case "cylinder":t=new Ax(this);break;case "cone":t=new AT(this);break;case "mesh":t=new AE(this);break;case "compound":t=new AA(this);}this.implementations[e]=t;}return this.implementations[e]}_getImplementation(e){return this.implementations[e.collision.data.type]}cloneComponent(e,t){return this._getImplementation(e).clone(e,t)}onBeforeRemove(e,t){this.implementations[t.data.type].beforeRemove(e,t),t.onBeforeRemove();}onRemove(e,t){this.implementations[t.type].remove(e,t);}updateCompoundChildTransform(e,t){let i=e.collision._compoundParent;if(i!==e.collision&&e.enabled&&e.collision.enabled&&(e._dirtyLocal||t)){let t=this._getNodeTransform(e,i.entity),s=i.getCompoundChildShapeIndex(e.collision.shape);null===s?i.shape.addChildShape(t,e.collision.data.shape):i.shape.updateChildTransform(s,t,true),Ammo.destroy(t);}}_removeCompoundChild(e,t){if(0!==e.shape.getNumChildShapes())if(e.shape.removeChildShape)e.shape.removeChildShape(t);else {let i=e.getCompoundChildShapeIndex(t);null!==i&&e.shape.removeChildShapeByIndex(i);}}onTransformChanged(e,t,i,s){this.implementations[e.data.type].updateTransform(e,t,i,s);}changeType(e,t,i){this.implementations[t].beforeRemove(e.entity,e),this.implementations[t].remove(e.entity,e.data),this._createImplementation(i).reset(e,e.data);}recreatePhysicalShapes(e){this.implementations[e.data.type].recreatePhysicalShapes(e);}_calculateNodeRelativeTransform(e,t){if(e===t){let t=e.getWorldTransform().getScale();Ad.setScale(t.x,t.y,t.z);}else this._calculateNodeRelativeTransform(e.parent,t),Ad.mul(e.getLocalTransform());}_getNodeScaling(e){let t=e.getWorldTransform().getScale();return new Ammo.btVector3(t.x,t.y,t.z)}_getNodeTransform(e,t){let i,s;t?(this._calculateNodeRelativeTransform(e,t),i=Au,s=Ap,Ad.getTranslation(i),s.setFromMat4(Ad)):(i=e.getPosition(),s=e.getRotation());let r=new Ammo.btQuaternion,a=new Ammo.btTransform;a.setIdentity();let n=a.getOrigin(),o=e.collision;if(o&&o._hasOffset){let e=o.data.linearOffset,t=o.data.angularOffset;Ap.copy(s).transformVector(e,Af),Af.add(i),Ap.copy(s).mul(t),n.setValue(Af.x,Af.y,Af.z),r.setValue(Ap.x,Ap.y,Ap.z,Ap.w);}else n.setValue(i.x,i.y,i.z),r.setValue(s.x,s.y,s.z,s.w);return a.setRotation(r),Ammo.destroy(r),a}destroy(){for(let e in this._triMeshCache)Ammo.destroy(this._triMeshCache[e]);this._triMeshCache=null,super.destroy();}}let Aw=new eb,AC=new ne;class AP{constructor(e,t,i){this._entity=e,this._element=e.element,this.model=new g5,this.node=new _c,this.model.graph=this.node,this.mesh=t,this.meshInstance=new mV(this.mesh,i,this.node),this.meshInstance.name=`ImageElement: ${e.name}`,this.meshInstance.castShadow=false,this.meshInstance.receiveShadow=false,this._meshDirty=false,this.model.meshInstances.push(this.meshInstance),this._entity.addChild(this.model.graph),this.model._entity=this._entity,this.unmaskMeshInstance=null;}destroy(){this.setMaterial(null),this._element.removeModelFromLayers(this.model),this.model.destroy(),this.model=null,this.node=null,this.mesh=null,this.meshInstance?.destroy(),this.meshInstance=null,this.unmaskMeshInstance?.destroy(),this.unmaskMeshInstance=null,this._entity=null,this._element=null;}setMesh(e){this.meshInstance&&(this.mesh=e,this.meshInstance.mesh=e,this.meshInstance.visible=!!e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.mesh=e),this.forceUpdateAabb());}setMask(e){if(this.meshInstance){if(this._entity.enabled&&this._element.enabled&&this._element.removeModelFromLayers(this.model),e)for(let e in this.unmaskMeshInstance=new mV(this.mesh,this.meshInstance.material,this.node),this.unmaskMeshInstance.name=`Unmask: ${this._entity.name}`,this.unmaskMeshInstance.castShadow=false,this.unmaskMeshInstance.receiveShadow=false,this.unmaskMeshInstance.pick=false,this.model.meshInstances.push(this.unmaskMeshInstance),this.meshInstance.parameters)this.unmaskMeshInstance.setParameter(e,this.meshInstance.parameters[e].data);else {let e=this.model.meshInstances.indexOf(this.unmaskMeshInstance);e>=0&&this.model.meshInstances.splice(e,1);}this._entity.enabled&&this._element.enabled&&this._element.addModelToLayers(this.model),e||(this.unmaskMeshInstance?.destroy(),this.unmaskMeshInstance=null);}}setMaterial(e){this.meshInstance&&(this.meshInstance.material=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=e));}setParameter(e,t){this.meshInstance&&(this.meshInstance.setParameter(e,t),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(e,t));}deleteParameter(e){this.meshInstance&&(this.meshInstance.deleteParameter(e),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(e));}setUnmaskDrawOrder(){if(!this.meshInstance)return;let e=function(t){let i,s=t.children,r=s.length;if(r){for(let e=0;e<r;e++)s[e].element&&(i=s[e]);if(!i)return null;let t=e(i);return t||i}return null};if(this.unmaskMeshInstance){let t=e(this._entity);t&&t.element?this.unmaskMeshInstance.drawOrder=t.element.drawOrder+t.element.getMaskOffset():this.unmaskMeshInstance.drawOrder=this.meshInstance.drawOrder+this._element.getMaskOffset();}}setDrawOrder(e){this.meshInstance&&(this.meshInstance.drawOrder=e);}setCull(e){if(!this.meshInstance)return;let t=this._element,i=null;e&&t._isScreenSpace()&&(i=function(e){return t.isVisibleForCamera(e)}),this.meshInstance.cull=e,this.meshInstance.isVisibleFunc=i,this.unmaskMeshInstance&&(this.unmaskMeshInstance.cull=e,this.unmaskMeshInstance.isVisibleFunc=i);}setScreenSpace(e){this.meshInstance&&(this.meshInstance.screenSpace=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.screenSpace=e));}setLayer(e){this.meshInstance&&(this.meshInstance.layer=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.layer=e));}forceUpdateAabb(e){this.meshInstance&&(this.meshInstance._aabbVer=-1,this.unmaskMeshInstance&&(this.unmaskMeshInstance._aabbVer=-1));}setAabbFunc(e){this.meshInstance&&(this.meshInstance._updateAabbFunc=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance._updateAabbFunc=e));}}class AL{constructor(e){this._evtSetMeshes=null,this._element=e,this._entity=e.entity,this._system=e.system,this._textureAsset=null,this._texture=null,this._materialAsset=null,this._material=null,this._spriteAsset=null,this._sprite=null,this._spriteFrame=0,this._pixelsPerUnit=null,this._targetAspectRatio=-1,this._rect=new eF(0,0,1,1),this._mask=false,this._maskRef=0,this._outerScale=new eN,this._outerScaleUniform=new Float32Array(2),this._innerOffset=new eF,this._innerOffsetUniform=new Float32Array(4),this._atlasRect=new eF,this._atlasRectUniform=new Float32Array(4),this._defaultMesh=this._createMesh(),this._renderable=new AP(this._entity,this._defaultMesh,this._material),this._color=new eb(1,1,1,1),this._colorUniform=new Float32Array([1,1,1]),this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",1),this._updateAabbFunc=this._updateAabb.bind(this),this._onScreenChange(this._element.screen),this._element.on("resize",this._onParentResizeOrPivotChange,this),this._element.on("set:pivot",this._onParentResizeOrPivotChange,this),this._element.on("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.on("set:screen",this._onScreenChange,this),this._element.on("set:draworder",this._onDrawOrderChange,this),this._element.on("screen:set:resolution",this._onResolutionChange,this);}destroy(){this.textureAsset=null,this.spriteAsset=null,this.materialAsset=null,this._renderable.setMesh(this._defaultMesh),this._renderable.destroy(),this._defaultMesh=null,this._element.off("resize",this._onParentResizeOrPivotChange,this),this._element.off("set:pivot",this._onParentResizeOrPivotChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("screen:set:resolution",this._onResolutionChange,this);}_onResolutionChange(e){}_onParentResizeOrPivotChange(){this._renderable.mesh&&this._updateMesh(this._renderable.mesh);}_onScreenSpaceChange(e){this._updateMaterial(e);}_onScreenChange(e,t){e?this._updateMaterial(e.screen.screenSpace):this._updateMaterial(false);}_onDrawOrderChange(e){this._renderable.setDrawOrder(e),this.mask&&this._element.screen&&this._element.screen.screen.once("syncdraworder",function(){this._renderable.setUnmaskDrawOrder();},this);}_hasUserMaterial(){return !!this._materialAsset||!!this._material&&-1===this._system.defaultImageMaterials.indexOf(this._material)}_use9Slicing(){return this.sprite&&(this.sprite.renderMode===pw||this.sprite.renderMode===pC)}_updateMaterial(e){let t=!!this._mask,i=!!(this.sprite&&this.sprite.renderMode===pw),s=!!(this.sprite&&this.sprite.renderMode===pC);this._hasUserMaterial()||(this._material=this._system.getImageElementMaterial(e,t,i,s)),this._renderable&&(this._renderable.setCull(!this._element._isScreenSpace()||this._element._isScreenCulled()),this._renderable.setMaterial(this._material),this._renderable.setScreenSpace(e),this._renderable.setLayer(e?uT:uA));}_createMesh(){let e=this._element,t=e.calculatedWidth,i=e.calculatedHeight,s=this._rect,r=this._system.app.graphicsDevice,a=new Float32Array([t,0,0,0,0,1,s.x+s.z,1-s.y,t,i,0,0,0,1,s.x+s.z,1-(s.y+s.w),0,0,0,0,0,1,s.x,1-s.y,0,i,0,0,0,1,s.x,1-(s.y+s.w)]),n=AC.get(r,()=>new nP(r,[{semantic:sT,components:3,type:rM},{semantic:sE,components:3,type:rM},{semantic:sL,components:2,type:rM}])),o=new nT(r,n,4,{data:a.buffer}),l=new mw(r);return l.vertexBuffer=o,l.primitive[0].type=sy,l.primitive[0].base=0,l.primitive[0].count=4,l.primitive[0].indexed=false,l.aabb.setMinMax(eM.ZERO,new eM(t,i,0)),this._updateMesh(l),l}_updateMesh(e){let t=this._element,i=t.calculatedWidth,s=t.calculatedHeight;if(t.fitMode!==Eb&&this._targetAspectRatio>0){let e=t.calculatedWidth/t.calculatedHeight;t.fitMode===Ew&&e>this._targetAspectRatio||t.fitMode===EC&&e<this._targetAspectRatio?i=t.calculatedHeight*this._targetAspectRatio:s=t.calculatedWidth/this._targetAspectRatio;}let r=t._isScreenSpace();if(this._updateMaterial(r),this._renderable&&this._renderable.forceUpdateAabb(),this.sprite&&(this.sprite.renderMode===pw||this.sprite.renderMode===pC)){let e=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]],r=2/e.rect.z,a=2/e.rect.w;this._innerOffset.set(e.border.x*r,e.border.y*a,e.border.z*r,e.border.w*a);let n=this.sprite.atlas.texture;this._atlasRect.set(e.rect.x/n.width,e.rect.y/n.height,e.rect.z/n.width,e.rect.w/n.height);let o=null!==this._pixelsPerUnit?this._pixelsPerUnit:this.sprite.pixelsPerUnit,l=e.rect.z/o,h=e.rect.w/o;this._outerScale.set(Math.max(i,this._innerOffset.x*l),Math.max(s,this._innerOffset.y*h));let c=l,d=h;this._outerScale.x/=l,this._outerScale.y/=h,c*=eA.clamp(i/(this._innerOffset.x*l),1e-4,1),d*=eA.clamp(s/(this._innerOffset.y*h),1e-4,1),this._renderable&&(this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._renderable.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._renderable.setParameter("atlasRect",this._atlasRectUniform),this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._renderable.setParameter("outerScale",this._outerScaleUniform),this._renderable.setAabbFunc(this._updateAabbFunc),this._renderable.node.setLocalScale(c,d,1),this._renderable.node.setLocalPosition((.5-t.pivot.x)*i,(.5-t.pivot.y)*s,0));}else {let r=e.vertexBuffer,a=new Float32Array(r.lock()),n=t.pivot.x,o=t.pivot.y;a[0]=i-n*i,a[1]=0-o*s,a[8]=i-n*i,a[9]=s-o*s,a[16]=0-n*i,a[17]=0-o*s,a[24]=0-n*i,a[25]=s-o*s;let l=1,h=1,c=this._rect;if(this._sprite&&this._sprite.frameKeys[this._spriteFrame]&&this._sprite.atlas){let e=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];e&&(c=e.rect,l=this._sprite.atlas.texture.width,h=this._sprite.atlas.texture.height);}a[6]=(c.x+c.z)/l,a[7]=1-c.y/h,a[14]=(c.x+c.z)/l,a[15]=1-(c.y+c.w)/h,a[22]=c.x/l,a[23]=1-c.y/h,a[30]=c.x/l,a[31]=1-(c.y+c.w)/h,r.unlock();let d=new eM(0-n*i,0-o*s,0),u=new eM(i-n*i,s-o*s,0);e.aabb.setMinMax(d,u),this._renderable&&(this._renderable.node.setLocalScale(1,1,1),this._renderable.node.setLocalPosition(0,0,0),this._renderable.setAabbFunc(null));}this._meshDirty=false;}_updateSprite(){let e=false,t=null;if(this._targetAspectRatio=-1,this._sprite&&this._sprite.atlas){t=this._sprite.meshes[this.spriteFrame],e=this._sprite.renderMode===pw||this._sprite.renderMode===pC;let i=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];i?.rect.w>0&&(this._targetAspectRatio=i.rect.z/i.rect.w);}this.mesh=e?t:this._defaultMesh,this.refreshMesh();}refreshMesh(){this.mesh&&(this._element._beingInitialized?this._meshDirty=true:this._updateMesh(this.mesh));}_updateAabb(e){return e.center.set(0,0,0),e.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),e.setFromTransformedAabb(e,this._renderable.node.getWorldTransform()),e}_toggleMask(){this._element._dirtifyMask();let e=this._element._isScreenSpace();this._updateMaterial(e),this._renderable.setMask(!!this._mask);}_onMaterialLoad(e){this.material=e.resource;}_onMaterialAdded(e){this._system.app.assets.off(`add:${e.id}`,this._onMaterialAdded,this),this._materialAsset===e.id&&this._bindMaterialAsset(e);}_bindMaterialAsset(e){this._entity.enabled&&(e.on("load",this._onMaterialLoad,this),e.on("change",this._onMaterialChange,this),e.on("remove",this._onMaterialRemove,this),e.resource?this._onMaterialLoad(e):this._system.app.assets.load(e));}_unbindMaterialAsset(e){e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this);}_onMaterialChange(){}_onMaterialRemove(){}_onTextureAdded(e){this._system.app.assets.off(`add:${e.id}`,this._onTextureAdded,this),this._textureAsset===e.id&&this._bindTextureAsset(e);}_bindTextureAsset(e){this._entity.enabled&&(e.on("load",this._onTextureLoad,this),e.on("change",this._onTextureChange,this),e.on("remove",this._onTextureRemove,this),e.resource?this._onTextureLoad(e):this._system.app.assets.load(e));}_unbindTextureAsset(e){e.off("load",this._onTextureLoad,this),e.off("change",this._onTextureChange,this),e.off("remove",this._onTextureRemove,this);}_onTextureLoad(e){this.texture=e.resource;}_onTextureChange(e){}_onTextureRemove(e){}_onSpriteAssetAdded(e){this._system.app.assets.off(`add:${e.id}`,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e);}_bindSpriteAsset(e){this._entity.enabled&&(e.on("load",this._onSpriteAssetLoad,this),e.on("change",this._onSpriteAssetChange,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._system.app.assets.load(e));}_unbindSpriteAsset(e){e.off("load",this._onSpriteAssetLoad,this),e.off("change",this._onSpriteAssetChange,this),e.off("remove",this._onSpriteAssetRemove,this),e.data.textureAtlasAsset&&this._system.app.assets.off(`load:${e.data.textureAtlasAsset}`,this._onTextureAtlasLoad,this);}_onSpriteAssetLoad(e){if(e&&e.resource)if(e.resource.atlas)this.sprite=e.resource;else {let t=e.data.textureAtlasAsset;if(t){let e=this._system.app.assets;e.off(`load:${t}`,this._onTextureAtlasLoad,this),e.once(`load:${t}`,this._onTextureAtlasLoad,this);}}else this.sprite=null;}_onSpriteAssetChange(e){this._onSpriteAssetLoad(e);}_onSpriteAssetRemove(e){}_bindSprite(e){this._evtSetMeshes=e.on("set:meshes",this._onSpriteMeshesChange,this),e.on("set:pixelsPerUnit",this._onSpritePpuChange,this),e.on("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.on("set:texture",this._onAtlasTextureChange,this);}_unbindSprite(e){this._evtSetMeshes?.off(),this._evtSetMeshes=null,e.off("set:pixelsPerUnit",this._onSpritePpuChange,this),e.off("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.off("set:texture",this._onAtlasTextureChange,this);}_onSpriteMeshesChange(){this._sprite&&(this._spriteFrame=eA.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite();}_onSpritePpuChange(){this.sprite.renderMode!==pb&&null===this._pixelsPerUnit&&this._updateSprite();}_onAtlasTextureChange(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"));}_onTextureAtlasLoad(e){let t=this._spriteAsset;t instanceof xF?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._system.app.assets.get(t));}onEnable(){if(this._materialAsset){let e=this._system.app.assets.get(this._materialAsset);e&&e.resource!==this._material&&this._bindMaterialAsset(e);}if(this._textureAsset){let e=this._system.app.assets.get(this._textureAsset);e&&e.resource!==this._texture&&this._bindTextureAsset(e);}if(this._spriteAsset){let e=this._system.app.assets.get(this._spriteAsset);e&&e.resource!==this._sprite&&this._bindSpriteAsset(e);}this._element.addModelToLayers(this._renderable.model);}onDisable(){this._element.removeModelFromLayers(this._renderable.model);}_setStencil(e){this._renderable.meshInstance.stencilFront=e,this._renderable.meshInstance.stencilBack=e;let t=0;if(this._element.maskedBy&&(t=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){let e=new nI({ref:t+1,func:t4,zpass:s5});this._renderable.unmaskMeshInstance.stencilFront=e,this._renderable.unmaskMeshInstance.stencilBack=e;}}_updateRenderableEmissive(){Aw.linear(this._color),this._colorUniform[0]=Aw.r,this._colorUniform[1]=Aw.g,this._colorUniform[2]=Aw.b,this._renderable.setParameter("material_emissive",this._colorUniform);}set color(e){let{r:t,g:i,b:s}=e;(this._color.r!==t||this._color.g!==i||this._color.b!==s)&&(this._color.r=t,this._color.g=i,this._color.b=s,this._updateRenderableEmissive()),this._element&&this._element.fire("set:color",this._color);}get color(){return this._color}set opacity(e){e!==this._color.a&&(this._color.a=e,this._renderable.setParameter("material_opacity",e)),this._element&&this._element.fire("set:opacity",e);}get opacity(){return this._color.a}set rect(e){let t,i,s,r;e instanceof eF?(t=e.x,i=e.y,s=e.z,r=e.w):(t=e[0],i=e[1],s=e[2],r=e[3]),(t!==this._rect.x||i!==this._rect.y||s!==this._rect.z||r!==this._rect.w)&&(this._rect.set(t,i,s,r),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=true:this._updateMesh(this._renderable.mesh)));}get rect(){return this._rect}_removeMaterialAssetEvents(){if(this._materialAsset){let e=this._system.app.assets;e.off(`add:${this._materialAsset}`,this._onMaterialAdded,this);let t=e.get(this._materialAsset);t&&(t.off("load",this._onMaterialLoad,this),t.off("change",this._onMaterialChange,this),t.off("remove",this._onMaterialRemove,this));}}set material(e){if(this._material!==e){if(!e){let t=this._element._isScreenSpace();e=this.mask?t?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:t?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial;}if(this._material=e,this._materialAsset){let t=this._system.app.assets.get(this._materialAsset);t&&t.resource===e||(this._removeMaterialAssetEvents(),this._materialAsset=null);}e&&(this._renderable.setMaterial(e),this._hasUserMaterial()?(this._renderable.deleteParameter("material_opacity"),this._renderable.deleteParameter("material_emissive")):(this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a)));}}get material(){return this._material}set materialAsset(e){let t=this._system.app.assets,i=e;if(e instanceof xF&&(i=e.id),this._materialAsset!==i)if(this._removeMaterialAssetEvents(),this._materialAsset=i,this._materialAsset){let e=t.get(this._materialAsset);e?this._bindMaterialAsset(e):(this._materialAsset=null,this.material=null,this._materialAsset=i,t.on(`add:${this._materialAsset}`,this._onMaterialAdded,this));}else this._materialAsset=null,this.material=null,this._materialAsset=i;}get materialAsset(){return this._materialAsset}set texture(e){if(this._texture!==e){if(this._textureAsset){let t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==e&&(this.textureAsset=null);}if(this._texture=e,e){this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a);let e=this._texture.width/this._texture.height;e!==this._targetAspectRatio&&(this._targetAspectRatio=e,this._element.fitMode!==Eb&&this.refreshMesh());}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==Eb&&this.refreshMesh();}}get texture(){return this._texture}set textureAsset(e){let t=this._system.app.assets,i=e;if(e instanceof xF&&(i=e.id),this._textureAsset!==i){if(this._textureAsset){t.off(`add:${this._textureAsset}`,this._onTextureAdded,this);let e=t.get(this._textureAsset);e&&(e.off("load",this._onTextureLoad,this),e.off("change",this._onTextureChange,this),e.off("remove",this._onTextureRemove,this));}if(this._textureAsset=i,this._textureAsset){let e=t.get(this._textureAsset);e?this._bindTextureAsset(e):(this.texture=null,t.on(`add:${this._textureAsset}`,this._onTextureAdded,this));}else this.texture=null;}}get textureAsset(){return this._textureAsset}set spriteAsset(e){let t=this._system.app.assets,i=e;if(e instanceof xF&&(i=e.id),this._spriteAsset!==i){if(this._spriteAsset){t.off(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this);let e=t.get(this._spriteAsset);e&&this._unbindSpriteAsset(e);}if(this._spriteAsset=i,this._spriteAsset){let e=t.get(this._spriteAsset);e?this._bindSpriteAsset(e):(this.sprite=null,t.on(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this));}else this.sprite=null;}this._element&&this._element.fire("set:spriteAsset",i);}get spriteAsset(){return this._spriteAsset}set sprite(e){if(this._sprite!==e){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){let t=this._system.app.assets.get(this._spriteAsset);t&&t.resource!==e&&(this.spriteAsset=null);}this._sprite=e,this._sprite&&(this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null)),this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap")),this._sprite&&(this._spriteFrame=eA.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite();}}get sprite(){return this._sprite}set spriteFrame(e){let t=this._spriteFrame;this._sprite?this._spriteFrame=eA.clamp(e,0,this._sprite.frameKeys.length-1):this._spriteFrame=e,this._spriteFrame!==t&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",e);}get spriteFrame(){return this._spriteFrame}set mesh(e){this._renderable.setMesh(e),this._defaultMesh===e?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc);}get mesh(){return this._renderable.mesh}set mask(e){this._mask!==e&&(this._mask=e,this._toggleMask());}get mask(){return this._mask}set pixelsPerUnit(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,this._sprite&&(this._sprite.renderMode===pw||this._sprite.renderMode===pC)&&this._updateSprite());}get pixelsPerUnit(){return this._pixelsPerUnit}get aabb(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}}class AI extends eo{constructor(e){super(),this._app=e,e.i18n.on(xq.EVENT_CHANGE,this._onSetLocale,this),this._autoLoad=false,this._disableLocalization=false,this._defaultAsset=null,this._localizedAsset=null;}set defaultAsset(e){let t=e instanceof xF?e.id:e;this._defaultAsset!==t&&(this._defaultAsset&&this._unbindDefaultAsset(),this._defaultAsset=t,this._defaultAsset&&this._bindDefaultAsset(),this._onSetLocale(this._app.i18n.locale));}get defaultAsset(){return this._defaultAsset}set localizedAsset(e){let t=e instanceof xF?e.id:e;this._localizedAsset!==t&&(this._localizedAsset&&(this._app.assets.off(`add:${this._localizedAsset}`,this._onLocalizedAssetAdd,this),this._unbindLocalizedAsset()),this._localizedAsset=t,this._localizedAsset&&(this._app.assets.get(this._localizedAsset)?this._bindLocalizedAsset():this._app.assets.once(`add:${this._localizedAsset}`,this._onLocalizedAssetAdd,this)));}get localizedAsset(){return this._localizedAsset}set autoLoad(e){this._autoLoad!==e&&(this._autoLoad=e,this._autoLoad&&this._localizedAsset&&(this._unbindLocalizedAsset(),this._bindLocalizedAsset()));}get autoLoad(){return this._autoLoad}set disableLocalization(e){this._disableLocalization!==e&&(this._disableLocalization=e,this._onSetLocale(this._app.i18n.locale));}get disableLocalization(){return this._disableLocalization}_bindDefaultAsset(){let e=this._app.assets.get(this._defaultAsset);e?this._onDefaultAssetAdd(e):this._app.assets.once(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this);}_unbindDefaultAsset(){if(!this._defaultAsset)return;this._app.assets.off(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this);let e=this._app.assets.get(this._defaultAsset);e&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleRemove,this),e.off("remove",this._onDefaultAssetRemove,this));}_onDefaultAssetAdd(e){this._defaultAsset===e.id&&(e.on("add:localized",this._onLocaleAdd,this),e.on("remove:localized",this._onLocaleRemove,this),e.once("remove",this._onDefaultAssetRemove,this));}_onDefaultAssetRemove(e){this._defaultAsset===e.id&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleAdd,this),this._app.assets.once(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this));}_bindLocalizedAsset(){if(!this._autoLoad)return;let e=this._app.assets.get(this._localizedAsset);e&&(e.on("load",this._onLocalizedAssetLoad,this),e.on("change",this._onLocalizedAssetChange,this),e.on("remove",this._onLocalizedAssetRemove,this),e.resource?this._onLocalizedAssetLoad(e):this._app.assets.load(e));}_unbindLocalizedAsset(){let e=this._app.assets.get(this._localizedAsset);e&&(e.off("load",this._onLocalizedAssetLoad,this),e.off("change",this._onLocalizedAssetChange,this),e.off("remove",this._onLocalizedAssetRemove,this));}_onLocalizedAssetAdd(e){this._localizedAsset===e.id&&this._bindLocalizedAsset();}_onLocalizedAssetLoad(e){this.fire("load",e);}_onLocalizedAssetChange(e,t,i,s){this.fire("change",e,t,i,s);}_onLocalizedAssetRemove(e){this._localizedAsset===e.id&&(this.localizedAsset=this._defaultAsset),this.fire("remove",e);}_onLocaleAdd(e,t){this._app.i18n.locale===e&&this._onSetLocale(e);}_onLocaleRemove(e,t){this._app.i18n.locale===e&&this._onSetLocale(e);}_onSetLocale(e){if(!this._defaultAsset){this.localizedAsset=null;return}let t=this._app.assets.get(this._defaultAsset);if(!t||this._disableLocalization){this.localizedAsset=this._defaultAsset;return}let i=t.getLocalizedAssetId(e);if(!i){this.localizedAsset=this._defaultAsset;return}this.localizedAsset=i;}destroy(){this.defaultAsset=null,this._app.i18n.off(xq.EVENT_CHANGE,this._onSetLocale,this),this.off();}}let AD="msdf",AR="bitmap",AM=/[\w|/]/;class AO{constructor(e){this._symbols=e,this._index=0,this._last=0,this._cur=this._symbols.length>0?this._symbols[0]:null,this._buf=[],this._mode="text",this._error=null;}read(){let e=this._read();for(;8===e;)e=this._read();return 0!==e&&1!==e&&(this._last=this._index),e}buf(){return this._buf}last(){return this._last}error(){return this._error}debugPrint(){let e=["EOF","ERROR","TEXT","OPEN_BRACKET","CLOSE_BRACKET","EQUALS","STRING","IDENTIFIER","WHITESPACE"],t=this.read(),i="";for(;i+=`${(i.length>0?"\n":"")+e[t]} '${this.buf().join("")}'`,0!==t&&1!==t;)t=this.read();return i}_read(){return (this._buf=[],this._eof())?0:"text"===this._mode?this._text():this._tag()}_text(){for(;;)switch(this._cur){case null:return 2*(this._buf.length>0);case "[":return this._mode="tag",this._buf.length>0?2:this._tag();case "\\":this._next(),"["===this._cur?this._store():this._output("\\");break;default:this._store();}}_tag(){switch(this._cur){case null:return this._error="unexpected end of input reading tag",1;case "[":return this._store(),3;case "]":return this._store(),this._mode="text",4;case "=":return this._store(),5;case " ":case " ":case "\n":case "\r":case "\v":case "\f":return this._whitespace();case '"':return this._string();default:if(!this._isIdentifierSymbol(this._cur))return this._error="unrecognized character",1;return this._identifier()}}_whitespace(){for(this._store();-1!==" \n\r\v\f".indexOf(this._cur);)this._store();return 8}_string(){for(this._next();;)switch(this._cur){case null:return this._error="unexpected end of input reading string",1;case '"':return this._next(),6;default:this._store();}}_identifier(){for(this._store();null!==this._cur&&this._isIdentifierSymbol(this._cur);)this._store();return 7}_isIdentifierSymbol(e){return 1===e.length&&null!==e.match(AM)}_eof(){return null===this._cur}_next(){return this._eof()||(this._index++,this._cur=this._index<this._symbols.length?this._symbols[this._index]:null),this._cur}_store(){return this._buf.push(this._cur),this._next()}_output(e){this._buf.push(e);}}class AN{constructor(e){this._scanner=new AO(e),this._error=null;}parse(e,t){for(;;)switch(this._scanner.read()){case 0:return true;case 1:default:return false;case 2:Array.prototype.push.apply(e,this._scanner.buf());break;case 3:if(!this._parseTag(e,t))return false}}error(){return `Error evaluating markup at #${this._scanner.last().toString()} (${this._scanner.error()||this._error})`}_parseTag(e,t){let i=this._scanner.read();if(7!==i)return this._error="expected identifier",false;let s=this._scanner.buf().join("");if("/"===s[0]){for(let r=t.length-1;r>=0;--r)if(s===`/${t[r].name}`&&null===t[r].end){if(t[r].end=e.length,4!==(i=this._scanner.read()))return this._error="expected close bracket",false;return true}return this._error="failed to find matching tag",false}let r={name:s,value:null,attributes:{},start:e.length,end:null};if(5===(i=this._scanner.read())){if(6!==(i=this._scanner.read()))return this._error="expected string",false;r.value=this._scanner.buf().join(""),i=this._scanner.read();}for(;;){switch(i){case 4:return t.push(r),true;case 7:{let e=this._scanner.buf().join("");if(5!==(i=this._scanner.read()))return this._error="expected equals",false;if(6!==(i=this._scanner.read()))return this._error="expected string",false;let t=this._scanner.buf().join("");r.attributes[e]=t;break}default:return this._error="expected close bracket or identifier",false}i=this._scanner.read();}}}class AF{static evaluate(e){let t=new AN(e),i=[],s=[];if(!t.parse(i,s)||s.find(e=>null===e.end))return {symbols:e,tags:null};let r=function(e,t){if(0===e.length)return null;let i={};for(let t=0;t<e.length;++t){let s=e[t];i.hasOwnProperty(s.start)?null===i[s.start].open?i[s.start].open=[s]:i[s.start].open.push(s):i[s.start]={open:[s],close:null},i.hasOwnProperty(s.end)?null===i[s.end].close?i[s.end].close=[s]:i[s.end].close.push(s):i[s.end]={open:null,close:[s]};}let s=[],r=Object.keys(i).sort((e,t)=>e-t),a=[];for(let e=0;e<r.length;++e){let t=i[r[e]];null!==t.close&&function(e){s=s.filter(t=>void 0===e.find(e=>e===t));}(t.close),null!==t.open&&function(e){for(let t=0;t<e.length;++t)s.push(e[t]);}(t.open),a.push({start:r[e],tags:function(e){if(0===e.length)return null;let t={};for(let i=0;i<e.length;++i){let s=e[i],r={};r[s.name]={value:s.value,attributes:s.attributes},function e(t,i){for(let s in i){if(!i.hasOwnProperty(s))continue;let r=i[s];r instanceof Object?(t.hasOwnProperty(s)||(t[s]={}),e(t[s],i[s])):t[s]=r;}}(t,r);}return t}(s)});}let n=[],o=null;for(let e=0;e<a.length;++e){let t=a[e];for(;n.length<t.start;)n.push(o?o.tags:null);o=t;}for(;n.length<t;)n.push(null);return n}(s,i.length);return {symbols:i,tags:r}}}class AB{constructor(){this.count=0,this.quad=0,this.lines={},this.positions=[],this.normals=[],this.uvs=[],this.colors=[],this.indices=[],this.outlines=[],this.shadows=[],this.meshInstance=null;}}let AU=/^[\r\n]$/,Ak=/^[ \t]$/,AV=/^[ \t\-]|\u200b$/,Az=/^[a-z0-9]$/i,AG=/^[\u1100-\u11ff]|[\u3000-\u9fff\ua960-\ua97f]|[\uac00-\ud7ff]$/,AH=/^[〕〉》」』】〙〗〟ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻]$/,AW=["","","","","","","","","","","","",""],AX={width:0,height:0,xadvance:0,xoffset:0,yoffset:0},AY=new eb,Aq=new eN,A$=new eb;class Aj{constructor(e){this._element=e,this._system=e.system,this._entity=e.entity,this._text="",this._symbols=[],this._colorPalette=[],this._outlinePalette=[],this._shadowPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null,this._i18nKey=null,this._fontAsset=new AI(this._system.app),this._fontAsset.disableLocalization=true,this._fontAsset.on("load",this._onFontLoad,this),this._fontAsset.on("change",this._onFontChange,this),this._fontAsset.on("remove",this._onFontRemove,this),this._font=null,this._color=new eb(1,1,1,1),this._colorUniform=new Float32Array(3),this._spacing=1,this._fontSize=32,this._fontMinY=0,this._fontMaxY=0,this._originalFontSize=32,this._maxFontSize=32,this._minFontSize=8,this._autoFitWidth=false,this._autoFitHeight=false,this._maxLines=-1,this._lineHeight=32,this._scaledLineHeight=32,this._wrapLines=false,this._drawOrder=0,this._alignment=new eN(.5,.5),this._autoWidth=true,this._autoHeight=true,this.width=0,this.height=0,this._node=new _c,this._model=new g5,this._model.graph=this._node,this._entity.addChild(this._node),this._meshInfo=[],this._material=null,this._aabbDirty=true,this._aabb=new ej,this._noResize=false,this._currentMaterialType=null,this._maskedMaterialSrc=null,this._rtlReorder=false,this._unicodeConverter=false,this._rtl=false,this._outlineColor=new eb(0,0,0,1),this._outlineColorUniform=new Float32Array(4),this._outlineThicknessScale=.2,this._outlineThickness=0,this._shadowColor=new eb(0,0,0,1),this._shadowColorUniform=new Float32Array(4),this._shadowOffsetScale=.005,this._shadowOffset=new eN(0,0),this._shadowOffsetUniform=new Float32Array(2),this._enableMarkup=false,this._onScreenChange(this._element.screen),e.on("resize",this._onParentResize,this),e.on("set:screen",this._onScreenChange,this),e.on("screen:set:screenspace",this._onScreenSpaceChange,this),e.on("set:draworder",this._onDrawOrderChange,this),e.on("set:pivot",this._onPivotChange,this),this._system.app.i18n.on(xq.EVENT_CHANGE,this._onLocaleSet,this),this._system.app.i18n.on("data:add",this._onLocalizationData,this),this._system.app.i18n.on("data:remove",this._onLocalizationData,this),this._rangeStart=0,this._rangeEnd=0;}destroy(){this._setMaterial(null),this._model&&(this._element.removeModelFromLayers(this._model),this._model.destroy(),this._model=null),this._fontAsset.destroy(),this.font=null,this._element.off("resize",this._onParentResize,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("set:pivot",this._onPivotChange,this),this._system.app.i18n.off(xq.EVENT_CHANGE,this._onLocaleSet,this),this._system.app.i18n.off("data:add",this._onLocalizationData,this),this._system.app.i18n.off("data:remove",this._onLocalizationData,this);}_onParentResize(e,t){!this._noResize&&this._font&&this._updateText();}_onScreenChange(e){e?this._updateMaterial(e.screen.screenSpace):this._updateMaterial(false);}_onScreenSpaceChange(e){this._updateMaterial(e);}_onDrawOrderChange(e){if(this._drawOrder=e,this._model)for(let t=0,i=this._model.meshInstances.length;t<i;t++)this._model.meshInstances[t].drawOrder=e;}_onPivotChange(e){this._font&&this._updateText();}_onLocaleSet(e){if(this._i18nKey){if(this.fontAsset){let e=this._system.app.assets.get(this.fontAsset);e&&e.resource&&e.resource===this._font||(this.font=null);}this._resetLocalizedText();}}_onLocalizationData(e,t){this._i18nKey&&t[this._i18nKey]&&this._resetLocalizedText();}_resetLocalizedText(){this._setText(this._system.app.i18n.getText(this._i18nKey));}_setText(e){if(this.unicodeConverter){let t=this._system.getUnicodeConverter();t&&(e=t(e));}this._text!==e&&(this._font&&this._updateText(e),this._text=e);}_updateText(e){let t;if(void 0===e&&(e=this._text),this._symbols=ea.getSymbols(e.normalize?e.normalize("NFC"):e),0===this._symbols.length&&(this._symbols=[" "]),this._enableMarkup){let e=AF.evaluate(this._symbols);this._symbols=e.symbols,t=e.tags||[];}if(this._rtlReorder){let e=this._system.app.systems.element.getRtlReorder();if(e){let i=e(this._symbols);this._rtl=i.rtl,this._symbols=i.mapping.map(function(e){return this._symbols[e]},this),t&&(t=i.mapping.map(e=>t[e]));}}else this._rtl=false;let i=(e,t)=>`${e.toString(true).toLowerCase()}:${t.toFixed(2)}`,s=(e,t)=>`${e.toString(true).toLowerCase()}:${t.x.toFixed(2)}:${t.y.toFixed(2)}`;if(t){let e={},r={},a={};this._colorPalette=[Math.round(255*this._color.r),Math.round(255*this._color.g),Math.round(255*this._color.b)],this._outlinePalette=[Math.round(255*this._outlineColor.r),Math.round(255*this._outlineColor.g),Math.round(255*this._outlineColor.b),Math.round(255*this._outlineColor.a),Math.round(255*this._outlineThickness)],this._shadowPalette=[Math.round(255*this._shadowColor.r),Math.round(255*this._shadowColor.g),Math.round(255*this._shadowColor.b),Math.round(255*this._shadowColor.a),Math.round(127*this._shadowOffset.x),Math.round(127*this._shadowOffset.y)],this._symbolColors=[],this._symbolOutlineParams=[],this._symbolShadowParams=[],e[this._color.toString(false).toLowerCase()]=0,r[i(this._outlineColor,this._outlineThickness)]=0,a[s(this._shadowColor,this._shadowOffset)]=0;for(let n=0,o=this._symbols.length;n<o;++n){let o=t[n],l=0;if(o&&o.color&&o.color.value){let t=o.color.value;if(7===t.length&&"#"===t[0]){let i=t.substring(1).toLowerCase();e.hasOwnProperty(i)?l=e[i]:/^[0-9a-f]{6}$/.test(i)&&(l=this._colorPalette.length/3,e[i]=l,this._colorPalette.push(parseInt(i.substring(0,2),16)),this._colorPalette.push(parseInt(i.substring(2,4),16)),this._colorPalette.push(parseInt(i.substring(4,6),16)));}}this._symbolColors.push(l);let h=0;if(o&&o.outline&&(o.outline.attributes.color||o.outline.attributes.thickness)){let e=o.outline.attributes.color?AY.fromString(o.outline.attributes.color):this._outlineColor,t=Number(o.outline.attributes.thickness);(Number.isNaN(e.r)||Number.isNaN(e.g)||Number.isNaN(e.b)||Number.isNaN(e.a))&&(e=this._outlineColor),Number.isNaN(t)&&(t=this._outlineThickness);let s=i(e,t);r.hasOwnProperty(s)?h=r[s]:(h=this._outlinePalette.length/5,r[s]=h,this._outlinePalette.push(Math.round(255*e.r),Math.round(255*e.g),Math.round(255*e.b),Math.round(255*e.a),Math.round(255*t)));}this._symbolOutlineParams.push(h);let c=0;if(o&&o.shadow&&(o.shadow.attributes.color||o.shadow.attributes.offset||o.shadow.attributes.offsetX||o.shadow.attributes.offsetY)){let e=o.shadow.attributes.color?AY.fromString(o.shadow.attributes.color):this._shadowColor,t=Number(o.shadow.attributes.offset),i=Number(o.shadow.attributes.offsetX),r=Number(o.shadow.attributes.offsetY);(Number.isNaN(e.r)||Number.isNaN(e.g)||Number.isNaN(e.b)||Number.isNaN(e.a))&&(e=this._shadowColor);let n=Aq.set(Number.isNaN(i)?Number.isNaN(t)?this._shadowOffset.x:t:i,Number.isNaN(r)?Number.isNaN(t)?this._shadowOffset.y:t:r),l=s(e,n);a.hasOwnProperty(l)?c=a[l]:(c=this._shadowPalette.length/6,a[l]=c,this._shadowPalette.push(Math.round(255*e.r),Math.round(255*e.g),Math.round(255*e.b),Math.round(255*e.a),Math.round(127*n.x),Math.round(127*n.y)));}this._symbolShadowParams.push(c);}}else this._colorPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null;this._updateMaterialEmissive(),this._updateMaterialOutline(),this._updateMaterialShadow();let r=this._calculateCharsPerTexture(),a=false,n=this._element,o=n._isScreenSpace(),l=n._isScreenCulled(),h=function(e){return n.isVisibleForCamera(e)};for(let e=0,t=this._meshInfo.length;e<t;e++){let t=r[e]||0,i=this._meshInfo[e];if(i.count!==t){if(a||(n.removeModelFromLayers(this._model),a=true),i.count=t,i.positions.length=i.normals.length=3*t*4,i.indices.length=3*t*2,i.uvs.length=2*t*4,i.colors.length=4*t*4,i.outlines.length=4*t*3,i.shadows.length=4*t*3,i.meshInstance&&this._removeMeshInstance(i.meshInstance),0===t){i.meshInstance=null;continue}for(let e=0;e<t;e++)i.indices[3*e*2+0]=4*e,i.indices[3*e*2+1]=4*e+1,i.indices[3*e*2+2]=4*e+3,i.indices[3*e*2+3]=4*e+2,i.indices[3*e*2+4]=4*e+3,i.indices[3*e*2+5]=4*e+1,i.normals[4*e*3+0]=0,i.normals[4*e*3+1]=0,i.normals[4*e*3+2]=-1,i.normals[4*e*3+3]=0,i.normals[4*e*3+4]=0,i.normals[4*e*3+5]=-1,i.normals[4*e*3+6]=0,i.normals[4*e*3+7]=0,i.normals[4*e*3+8]=-1,i.normals[4*e*3+9]=0,i.normals[4*e*3+10]=0,i.normals[4*e*3+11]=-1;let s=new mV(function(e,t){let i=new mw(e);return i.setPositions(t.positions),i.setNormals(t.normals),i.setColors32(t.colors),i.setUvs(0,t.uvs),i.setIndices(t.indices),i.setVertexStream(sX,t.outlines,3,void 0,rM,false),i.setVertexStream(sY,t.shadows,3,void 0,rM,false),i.update(),i}(this._system.app.graphicsDevice,i),this._material,this._node);if(s.name=`Text Element: ${this._entity.name}`,s.castShadow=false,s.receiveShadow=false,s.cull=!o,s.screenSpace=o,s.drawOrder=this._drawOrder,l&&(s.cull=true,s.isVisibleFunc=h),this._setTextureParams(s,this._font.textures[e]),s.setParameter("material_emissive",this._colorUniform),s.setParameter("material_opacity",this._color.a),s.setParameter("font_sdfIntensity",this._font.intensity),s.setParameter("font_pxrange",this._getPxRange(this._font)),s.setParameter("font_textureWidth",this._font.data.info.maps[e].width),s.setParameter("outline_color",this._outlineColorUniform),s.setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness),s.setParameter("shadow_color",this._shadowColorUniform),this._symbolShadowParams)this._shadowOffsetUniform[0]=0,this._shadowOffsetUniform[1]=0;else {let t=-this._font.data.info.maps[e].width/this._font.data.info.maps[e].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=t*this._shadowOffsetScale*this._shadowOffset.y;}s.setParameter("shadow_offset",this._shadowOffsetUniform),i.meshInstance=s,this._model.meshInstances.push(s);}}this._element.maskedBy&&this._element._setMaskedBy(this._element.maskedBy),a&&this._element.enabled&&this._entity.enabled&&this._element.addModelToLayers(this._model),this._updateMeshes(),this._rangeStart=0,this._rangeEnd=this._symbols.length,this._updateRenderRange();}_removeMeshInstance(e){e.destroy();let t=this._model.meshInstances.indexOf(e);-1!==t&&this._model.meshInstances.splice(t,1);}_setMaterial(e){if(this._material=e,this._model)for(let t=0,i=this._model.meshInstances.length;t<i;t++)this._model.meshInstances[t].material=e;}_updateMaterial(e){let t=this._element,i=t._isScreenCulled(),s=function(e){return t.isVisibleForCamera(e)},r=this._font&&this._font.type===AD;if(this._material=this._system.getTextElementMaterial(e,r,this._enableMarkup),this._model)for(let t=0,r=this._model.meshInstances.length;t<r;t++){let r=this._model.meshInstances[t];r.cull=!e,r.material=this._material,r.screenSpace=e,i?(r.cull=true,r.isVisibleFunc=s):r.isVisibleFunc=null;}}_updateMaterialEmissive(){this._symbolColors?(this._colorUniform[0]=1,this._colorUniform[1]=1,this._colorUniform[2]=1):(A$.linear(this._color),this._colorUniform[0]=A$.r,this._colorUniform[1]=A$.g,this._colorUniform[2]=A$.b);}_updateMaterialOutline(){this._symbolOutlineParams?(this._outlineColorUniform[0]=0,this._outlineColorUniform[1]=0,this._outlineColorUniform[2]=0,this._outlineColorUniform[3]=1):(A$.linear(this._outlineColor),this._outlineColorUniform[0]=A$.r,this._outlineColorUniform[1]=A$.g,this._outlineColorUniform[2]=A$.b,this._outlineColorUniform[3]=A$.a);}_updateMaterialShadow(){this._symbolOutlineParams?(this._shadowColorUniform[0]=0,this._shadowColorUniform[1]=0,this._shadowColorUniform[2]=0,this._shadowColorUniform[3]=0):(A$.linear(this._shadowColor),this._shadowColorUniform[0]=A$.r,this._shadowColorUniform[1]=A$.g,this._shadowColorUniform[2]=A$.b,this._shadowColorUniform[3]=A$.a);}_isWordBoundary(e){return AV.test(e)}_isValidNextChar(e){return null!==e&&!AH.test(e)}_isNextCJKBoundary(e,t){return AG.test(e)&&(AV.test(t)||Az.test(t))}_isNextCJKWholeWord(e){return AG.test(e)}_updateMeshes(){let e,t,i,s,r=this._font.data,a=this,n=Math.min(this._minFontSize,this._maxFontSize),o=this._maxFontSize,l=this._shouldAutoFit();l&&(this._fontSize=this._maxFontSize);let h=this._symbols.length,c=0,d=0,u=0,f=0,p=1,m=0,_=0,g=0,v=0,S=0,y=0,x=Math.abs(this._element.anchor.x-this._element.anchor.z)>=1e-4,T=this._element.calculatedWidth;(!this.autoWidth||x)&&this._wrapLines||(T=Number.POSITIVE_INFINITY);let E=0,A=0;function b(e,t,i){a._lineWidths.push(Math.abs(i));let s=g>t?t+1:g,r=g>t?g+1:t,n=e.slice(s,r);if(y){let e=n.length;for(;e--&&y>0;)AU.test(n[e])&&(n.splice(e,1),y--);}a._lineContents.push(n.join("")),c=0,d-=a._scaledLineHeight,p++,v=0,S=0,y=0,m=0,g=t;}let w=true;for(;w;){w=false,l?this._scaledLineHeight=this._lineHeight*this._fontSize/(this._maxFontSize||1e-4):this._scaledLineHeight=this._lineHeight,this.width=0,this.height=0,this._lineWidths=[],this._lineContents=[],c=0,d=0,u=0,f=0,p=1,m=0,_=0,g=0,v=0,S=0,y=0;let a=this._fontSize/32;E=this._fontMinY*a,A=this._fontMaxY*a;for(let e=0;e<this._meshInfo.length;e++)this._meshInfo[e].quad=0,this._meshInfo[e].lines={};let x=255,C=255,P=255,L=65535,I=65535,D=0,R=65535,M=65535,O=32639;for(let l=0;l<h;l++){let N,F;if(e=this._symbols[l],s=l+1>=h?null:this._symbols[l+1],AU.test(e)){y++,(!this._wrapLines||this._maxLines<0||p<this._maxLines)&&(b(this._symbols,l,f),_=l+1,g=l+1);continue}let B=0,U=0,k=0,V=1;if(!(t=r.chars[e]))if(-1!==AW.indexOf(e))t=AX;else if(r.chars[" "])t=r.chars[" "];else for(let e in r.chars){t=r.chars[e];break}if(t){let e=0;if(S>0){let t=this._font.data.kerning;if(t){let i=t[ea.getCodePoint(this._symbols[l-1])||0];i&&(e=i[ea.getCodePoint(this._symbols[l])||0]||0);}}N=t.scale||1,V=a*((t.width+t.height)/2)/N,k=(t.xadvance+e)*a,B=(t.xoffset-e)*a,U=t.yoffset*a;}let z=Ak.test(e),G=t&&t.map||0,H=-this._font.data.info.maps[G].width/this._font.data.info.maps[G].height,W=this._meshInfo[G],X=c+this._spacing*k;if(X>T&&S>0&&!z&&(this._maxLines<0||p<this._maxLines))if(0===v)_=l,b(this._symbols,l,f);else {let e=Math.max(l-_,0);if(this._meshInfo.length<=1)W.lines[p-1]-=e,W.quad-=e;else {let e=_,t=l;for(let i=e;i<t;i++){let e=this._symbols[i],t=r.chars[e],s=this._meshInfo[t&&t.map||0];s.lines[p-1]-=1,s.quad-=1;}}l-=e+1,b(this._symbols,_,m);continue}i=W.quad,W.lines[p-1]=i;let Y=c-B,q=Y+V,$=d-U,j=$+V;if(this._rtl){let e=V-B-this._spacing*k-B;Y-=e,q-=e;}if(W.positions[4*i*3+0]=Y,W.positions[4*i*3+1]=$,W.positions[4*i*3+2]=u,W.positions[4*i*3+3]=q,W.positions[4*i*3+4]=$,W.positions[4*i*3+5]=u,W.positions[4*i*3+6]=q,W.positions[4*i*3+7]=j,W.positions[4*i*3+8]=u,W.positions[4*i*3+9]=Y,W.positions[4*i*3+10]=j,W.positions[4*i*3+11]=u,this.width=Math.max(this.width,X),this._shouldAutoFitWidth()&&this.width>this._element.calculatedWidth&&(F=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),(F=eA.clamp(F,n,o))!==this._element.fontSize)||(this.height=Math.max(this.height,A-(d+E)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(F=eA.clamp(this._fontSize-1,n,o))!==this._element.fontSize)){this._fontSize=F,w=true;break}c+=this._spacing*k,z||(f=c),(this._isWordBoundary(e)||this._isValidNextChar(s)&&(this._isNextCJKBoundary(e,s)||this._isNextCJKWholeWord(s)))&&(v++,m=f,_=l+1),S++;let K=this._getUv(e);if(W.uvs[4*i*2+0]=K[0],W.uvs[4*i*2+1]=1-K[1],W.uvs[4*i*2+2]=K[2],W.uvs[4*i*2+3]=1-K[1],W.uvs[4*i*2+4]=K[2],W.uvs[4*i*2+5]=1-K[3],W.uvs[4*i*2+6]=K[0],W.uvs[4*i*2+7]=1-K[3],this._symbolColors){let e=3*this._symbolColors[l];x=this._colorPalette[e],C=this._colorPalette[e+1],P=this._colorPalette[e+2];}if(W.colors[4*i*4+0]=x,W.colors[4*i*4+1]=C,W.colors[4*i*4+2]=P,W.colors[4*i*4+3]=255,W.colors[4*i*4+4]=x,W.colors[4*i*4+5]=C,W.colors[4*i*4+6]=P,W.colors[4*i*4+7]=255,W.colors[4*i*4+8]=x,W.colors[4*i*4+9]=C,W.colors[4*i*4+10]=P,W.colors[4*i*4+11]=255,W.colors[4*i*4+12]=x,W.colors[4*i*4+13]=C,W.colors[4*i*4+14]=P,W.colors[4*i*4+15]=255,this._symbolOutlineParams){let e=5*this._symbolOutlineParams[l];L=this._outlinePalette[e]+256*this._outlinePalette[e+1],I=this._outlinePalette[e+2]+256*this._outlinePalette[e+3],D=this._outlinePalette[e+4];}if(W.outlines[4*i*3+0]=L,W.outlines[4*i*3+1]=I,W.outlines[4*i*3+2]=D,W.outlines[4*i*3+3]=L,W.outlines[4*i*3+4]=I,W.outlines[4*i*3+5]=D,W.outlines[4*i*3+6]=L,W.outlines[4*i*3+7]=I,W.outlines[4*i*3+8]=D,W.outlines[4*i*3+9]=L,W.outlines[4*i*3+10]=I,W.outlines[4*i*3+11]=D,this._symbolShadowParams){let e=6*this._symbolShadowParams[l];R=this._shadowPalette[e]+256*this._shadowPalette[e+1],M=this._shadowPalette[e+2]+256*this._shadowPalette[e+3],O=this._shadowPalette[e+4]+127+256*Math.round(H*this._shadowPalette[e+5]+127);}W.shadows[4*i*3+0]=R,W.shadows[4*i*3+1]=M,W.shadows[4*i*3+2]=O,W.shadows[4*i*3+3]=R,W.shadows[4*i*3+4]=M,W.shadows[4*i*3+5]=O,W.shadows[4*i*3+6]=R,W.shadows[4*i*3+7]=M,W.shadows[4*i*3+8]=O,W.shadows[4*i*3+9]=R,W.shadows[4*i*3+10]=M,W.shadows[4*i*3+11]=O,W.quad++;}!w&&g<h&&b(this._symbols,h,c);}this._noResize=true,this.autoWidth=this._autoWidth,this.autoHeight=this._autoHeight,this._noResize=false;let C=this._element.pivot.x,P=this._element.pivot.y,L=this._alignment.x,I=this._alignment.y;for(let e=0;e<this._meshInfo.length;e++){if(0===this._meshInfo[e].count)continue;let t=0;for(let i in this._meshInfo[e].lines){let s=this._meshInfo[e].lines[i],r=this._lineWidths[parseInt(i,10)],a=-C*this._element.calculatedWidth+L*(this._element.calculatedWidth-r)*(this._rtl?-1:1),n=(1-P)*this._element.calculatedHeight-A-(1-I)*(this._element.calculatedHeight-this.height);for(let i=t;i<=s;i++)this._meshInfo[e].positions[4*i*3]+=a,this._meshInfo[e].positions[4*i*3+3]+=a,this._meshInfo[e].positions[4*i*3+6]+=a,this._meshInfo[e].positions[4*i*3+9]+=a,this._meshInfo[e].positions[4*i*3+1]+=n,this._meshInfo[e].positions[4*i*3+4]+=n,this._meshInfo[e].positions[4*i*3+7]+=n,this._meshInfo[e].positions[4*i*3+10]+=n;if(this._rtl)for(let i=t;i<=s;i++){let t=4*i*3;for(let i=0;i<4;++i)this._meshInfo[e].positions[t+3*i]=this._element.calculatedWidth-this._meshInfo[e].positions[t+3*i]+2*a;let s=this._meshInfo[e].positions[t+3],r=this._meshInfo[e].positions[t+6];this._meshInfo[e].positions[t+3]=this._meshInfo[e].positions[t+0],this._meshInfo[e].positions[t+6]=this._meshInfo[e].positions[t+9],this._meshInfo[e].positions[t+0]=s,this._meshInfo[e].positions[t+9]=r;}t=s+1;}let i=4*this._meshInfo[e].count,s=4*this._meshInfo[e].quad,r=new ho(this._meshInfo[e].meshInstance.mesh.vertexBuffer);for(let t=0;t<i;t++)t>=s?(r.element[sT].set(0,0,0),r.element[sL].set(0,0),r.element[sC].set(0,0,0,0),r.element[sX].set(0,0,0,0),r.element[sY].set(0,0,0,0)):(r.element[sT].set(this._meshInfo[e].positions[3*t+0],this._meshInfo[e].positions[3*t+1],this._meshInfo[e].positions[3*t+2]),r.element[sL].set(this._meshInfo[e].uvs[2*t+0],this._meshInfo[e].uvs[2*t+1]),r.element[sC].set(this._meshInfo[e].colors[4*t+0],this._meshInfo[e].colors[4*t+1],this._meshInfo[e].colors[4*t+2],this._meshInfo[e].colors[4*t+3]),r.element[sX].set(this._meshInfo[e].outlines[3*t+0],this._meshInfo[e].outlines[3*t+1],this._meshInfo[e].outlines[3*t+2]),r.element[sY].set(this._meshInfo[e].shadows[3*t+0],this._meshInfo[e].shadows[3*t+1],this._meshInfo[e].shadows[3*t+2])),r.next();r.end(),this._meshInfo[e].meshInstance.mesh.aabb.compute(this._meshInfo[e].positions),this._meshInfo[e].meshInstance._aabbVer=-1;}this._aabbDirty=true;}_onFontRender(){this.font=this._font;}_onFontLoad(e){this.font!==e.resource&&(this.font=e.resource);}_onFontChange(e,t,i,s){if("data"===t){this._font.data=i;let e=this._font.data.info.maps.length;for(let t=0;t<e;t++){if(!this._meshInfo[t])continue;let e=this._meshInfo[t].meshInstance;e&&(e.setParameter("font_sdfIntensity",this._font.intensity),e.setParameter("font_pxrange",this._getPxRange(this._font)),e.setParameter("font_textureWidth",this._font.data.info.maps[t].width));}}}_onFontRemove(e){}_setTextureParams(e,t){this._font&&(this._font.type===AD?(e.deleteParameter("texture_emissiveMap"),e.deleteParameter("texture_opacityMap"),e.setParameter("texture_msdfMap",t)):this._font.type===AR&&(e.deleteParameter("texture_msdfMap"),e.setParameter("texture_emissiveMap",t),e.setParameter("texture_opacityMap",t)));}_getPxRange(e){let t=Object.keys(this._font.data.chars);for(let e=0;e<t.length;e++){let i=this._font.data.chars[t[e]];if(i.range)return (i.scale||1)*i.range}return 2}_getUv(e){let t=this._font.data;if(!t.chars[e])return t.chars[" "]?this._getUv(" "):[0,0,0,0];let i=t.chars[e].map,s=t.info.maps[i].width,r=t.info.maps[i].height,a=t.chars[e].x,n=t.chars[e].y,o=a+t.chars[e].width,l=n-t.chars[e].height,h=1-t.chars[e].height/r;return [a/s,h-n/r,o/s,h-l/r]}onEnable(){this._fontAsset.autoLoad=true,this._model&&this._element.addModelToLayers(this._model);}onDisable(){this._fontAsset.autoLoad=false,this._model&&this._element.removeModelFromLayers(this._model);}_setStencil(e){if(this._model){let t=this._model.meshInstances;for(let i=0;i<t.length;i++)t[i].stencilFront=e,t[i].stencilBack=e;}}_shouldAutoFitWidth(){return this._autoFitWidth&&!this._autoWidth}_shouldAutoFitHeight(){return this._autoFitHeight&&!this._autoHeight}_shouldAutoFit(){return this._autoFitWidth&&!this._autoWidth||this._autoFitHeight&&!this._autoHeight}_calculateCharsPerTexture(e){let t={};void 0===e&&(e=this._symbols.length);for(let i=0,s=e;i<s;i++){let e=this._symbols[i],s=this._font.data.chars[e];!s&&((s=this._font.data.chars[" "])||(s=this._font.data.chars[Object.keys(this._font.data.chars)[0]]));let r=s.map;t[r]?t[r]++:t[r]=1;}return t}_updateRenderRange(){let e=0===this._rangeStart?0:this._calculateCharsPerTexture(this._rangeStart),t=0===this._rangeEnd?0:this._calculateCharsPerTexture(this._rangeEnd);for(let i=0,s=this._meshInfo.length;i<s;i++){let s=e[i]||0,r=t[i]||0,a=this._meshInfo[i].meshInstance;if(a){let e=a.mesh;e&&(e.primitive[0].base=3*s*2,e.primitive[0].count=(r-s)*6);}}}set text(e){this._i18nKey=null;let t=null!=e&&e.toString()||"";this._setText(t);}get text(){return this._text}set key(e){let t=null!==e?e.toString():null;this._i18nKey!==t&&(this._i18nKey=t,t?(this._fontAsset.disableLocalization=false,this._resetLocalizedText()):this._fontAsset.disableLocalization=true);}get key(){return this._i18nKey}set color(e){let t=e.r,i=e.g,s=e.b;if((this._color.r!==t||this._color.g!==i||this._color.b!==s)&&(this._color.r=t,this._color.g=i,this._color.b=s,this._model)){if(this._symbolColors)this._font&&this._updateText();else {A$.linear(this._color),this._colorUniform[0]=A$.r,this._colorUniform[1]=A$.g,this._colorUniform[2]=A$.b;for(let e=0,t=this._model.meshInstances.length;e<t;e++)this._model.meshInstances[e].setParameter("material_emissive",this._colorUniform);}this._element&&this._element.fire("set:color",this._color);}}get color(){return this._color}set opacity(e){if(this._color.a!==e&&(this._color.a=e,this._model))for(let t=0,i=this._model.meshInstances.length;t<i;t++)this._model.meshInstances[t].setParameter("material_opacity",e);this._element&&this._element.fire("set:opacity",e);}get opacity(){return this._color.a}set lineHeight(e){let t=this._lineHeight;this._lineHeight=e,this._scaledLineHeight=e,t!==e&&this._font&&this._updateText();}get lineHeight(){return this._lineHeight}set wrapLines(e){let t=this._wrapLines;this._wrapLines=e,t!==e&&this._font&&this._updateText();}get wrapLines(){return this._wrapLines}get lines(){return this._lineContents}set spacing(e){let t=this._spacing;this._spacing=e,t!==e&&this._font&&this._updateText();}get spacing(){return this._spacing}set fontSize(e){let t=this._fontSize;this._fontSize=e,this._originalFontSize=e,t!==e&&this._font&&this._updateText();}get fontSize(){return this._fontSize}set fontAsset(e){this._fontAsset.defaultAsset=e;}get fontAsset(){return this._fontAsset.localizedAsset}set font(e){let t;if(this._font&&(t=this._font.type,this._font.off&&this._font.off("render",this._onFontRender,this)),this._font=e,this._fontMinY=0,this._fontMaxY=0,!e)return;let i=this._font.data;for(let e in i.chars){let t=i.chars[e];t.bounds&&(this._fontMinY=Math.min(this._fontMinY,t.bounds[1]),this._fontMaxY=Math.max(this._fontMaxY,t.bounds[3]));}if(this._font.on&&this._font.on("render",this._onFontRender,this),this._fontAsset.localizedAsset&&this._system.app.assets.get(this._fontAsset.localizedAsset).resource!==this._font&&(this._fontAsset.defaultAsset=null),e.type!==t){let e=this._element._isScreenSpace();this._updateMaterial(e);}for(let e=0,t=this._font.textures.length;e<t;e++)if(this._meshInfo[e]){let t=this._meshInfo[e].meshInstance;t&&(t.setParameter("font_sdfIntensity",this._font.intensity),t.setParameter("font_pxrange",this._getPxRange(this._font)),t.setParameter("font_textureWidth",this._font.data.info.maps[e].width),this._setTextureParams(t,this._font.textures[e]));}else this._meshInfo[e]=new AB;let s=false;for(let e=this._font.textures.length;e<this._meshInfo.length;e++)this._meshInfo[e].meshInstance&&(s||(this._element.removeModelFromLayers(this._model),s=true),this._removeMeshInstance(this._meshInfo[e].meshInstance));this._meshInfo.length>this._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText();}get font(){return this._font}set alignment(e){e instanceof eN?this._alignment.set(e.x,e.y):this._alignment.set(e[0],e[1]),this._font&&this._updateText();}get alignment(){return this._alignment}set autoWidth(e){let t=this._autoWidth;if(this._autoWidth=e,e&&1e-4>Math.abs(this._element.anchor.x-this._element.anchor.z)&&(this._element.width=this.width),t!==e){let e=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;e!==this._fontSize&&(this._fontSize=e,this._font&&this._updateText());}}get autoWidth(){return this._autoWidth}set autoHeight(e){let t=this._autoHeight;if(this._autoHeight=e,e&&1e-4>Math.abs(this._element.anchor.y-this._element.anchor.w)&&(this._element.height=this.height),t!==e){let e=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;e!==this._fontSize&&(this._fontSize=e,this._font&&this._updateText());}}get autoHeight(){return this._autoHeight}set rtlReorder(e){this._rtlReorder!==e&&(this._rtlReorder=e,this._font&&this._updateText());}get rtlReorder(){return this._rtlReorder}set unicodeConverter(e){this._unicodeConverter!==e&&(this._unicodeConverter=e,this._setText(this._text));}get unicodeConverter(){return this._unicodeConverter}get aabb(){if(this._aabbDirty){let e=false;for(let t=0;t<this._meshInfo.length;t++)this._meshInfo[t].meshInstance&&(e?this._aabb.add(this._meshInfo[t].meshInstance.aabb):(this._aabb.copy(this._meshInfo[t].meshInstance.aabb),e=true));this._aabbDirty=false;}return this._aabb}set outlineColor(e){let t=e instanceof eb?e.r:e[0],i=e instanceof eb?e.g:e[1],s=e instanceof eb?e.b:e[2],r=e instanceof eb?e.a:e[3];if((this._outlineColor.r!==t||this._outlineColor.g!==i||this._outlineColor.b!==s||this._outlineColor.a!==r)&&(this._outlineColor.r=t,this._outlineColor.g=i,this._outlineColor.b=s,this._outlineColor.a=r,this._model)){if(this._symbolOutlineParams)this._font&&this._updateText();else {A$.linear(this._outlineColor),this._outlineColorUniform[0]=A$.r,this._outlineColorUniform[1]=A$.g,this._outlineColorUniform[2]=A$.b,this._outlineColorUniform[3]=A$.a;for(let e=0,t=this._model.meshInstances.length;e<t;e++)this._model.meshInstances[e].setParameter("outline_color",this._outlineColorUniform);}this._element&&this._element.fire("set:outline",this._color);}}get outlineColor(){return this._outlineColor}set outlineThickness(e){let t=this._outlineThickness;if(this._outlineThickness=e,t!==e&&this._font){if(!this._model)return;if(this._symbolOutlineParams)this._font&&this._updateText();else for(let e=0,t=this._model.meshInstances.length;e<t;e++)this._model.meshInstances[e].setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness);}}get outlineThickness(){return this._outlineThickness}set shadowColor(e){let t=e instanceof eb?e.r:e[0],i=e instanceof eb?e.g:e[1],s=e instanceof eb?e.b:e[2],r=e instanceof eb?e.a:e[3];if((this._shadowColor.r!==t||this._shadowColor.g!==i||this._shadowColor.b!==s||this._shadowColor.a!==r)&&(this._shadowColor.r=t,this._shadowColor.g=i,this._shadowColor.b=s,this._shadowColor.a=r,this._model))if(this._symbolShadowParams)this._font&&this._updateText();else {A$.linear(this._shadowColor),this._shadowColorUniform[0]=A$.r,this._shadowColorUniform[1]=A$.g,this._shadowColorUniform[2]=A$.b,this._shadowColorUniform[3]=A$.a;for(let e=0,t=this._model.meshInstances.length;e<t;e++)this._model.meshInstances[e].setParameter("shadow_color",this._shadowColorUniform);}}get shadowColor(){return this._shadowColor}set shadowOffset(e){let t=e instanceof eN?e.x:e[0],i=e instanceof eN?e.y:e[1];if((this._shadowOffset.x!==t||this._shadowOffset.y!==i)&&(this._shadowOffset.set(t,i),this._font&&this._model))if(this._symbolShadowParams)this._updateText();else for(let e=0,t=this._model.meshInstances.length;e<t;e++){let t=-this._font.data.info.maps[e].width/this._font.data.info.maps[e].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=t*this._shadowOffsetScale*this._shadowOffset.y,this._model.meshInstances[e].setParameter("shadow_offset",this._shadowOffsetUniform);}}get shadowOffset(){return this._shadowOffset}set minFontSize(e){this._minFontSize!==e&&(this._minFontSize=e,this.font&&this._shouldAutoFit()&&this._updateText());}get minFontSize(){return this._minFontSize}set maxFontSize(e){this._maxFontSize!==e&&(this._maxFontSize=e,this.font&&this._shouldAutoFit()&&this._updateText());}get maxFontSize(){return this._maxFontSize}set autoFitWidth(e){this._autoFitWidth!==e&&(this._autoFitWidth=e,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText());}get autoFitWidth(){return this._autoFitWidth}set autoFitHeight(e){this._autoFitHeight!==e&&(this._autoFitHeight=e,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText());}get autoFitHeight(){return this._autoFitHeight}set maxLines(e){this._maxLines!==e&&(null!==e||-1!==this._maxLines)&&(this._maxLines=null===e?-1:e,this.font&&this._wrapLines&&this._updateText());}get maxLines(){return this._maxLines}set enableMarkup(e){if(e=!!e,this._enableMarkup===e)return;this._enableMarkup=e,this.font&&this._updateText();let t=this._element._isScreenSpace();this._updateMaterial(t);}get enableMarkup(){return this._enableMarkup}get symbols(){return this._symbols}get symbolColors(){return null===this._symbolColors?null:this._symbolColors.map(function(e){return this._colorPalette.slice(3*e,3*e+3)},this)}get symbolOutlineParams(){return null===this._symbolOutlineParams?null:this._symbolOutlineParams.map(function(e){return this._outlinePalette.slice(5*e,5*e+5)},this)}get symbolShadowParams(){return null===this._symbolShadowParams?null:this._symbolShadowParams.map(function(e){return this._shadowPalette.slice(6*e,6*e+6)},this)}get rtl(){return this._rtl}set rangeStart(e){(e=Math.max(0,Math.min(e,this._symbols.length)))!==this._rangeStart&&(this._rangeStart=e,this._updateRenderRange());}get rangeStart(){return this._rangeStart}set rangeEnd(e){(e=Math.max(this._rangeStart,Math.min(e,this._symbols.length)))!==this._rangeEnd&&(this._rangeEnd=e,this._updateRenderRange());}get rangeEnd(){return this._rangeEnd}}let AK=new eM,AZ=new eG,AQ=new eM,AJ=new eM,A0=new eG,A1=new eG,A2=new eG,A3=new eG;class A4 extends Tp{static{this.EVENT_MOUSEDOWN="mousedown";}static{this.EVENT_MOUSEUP="mouseup";}static{this.EVENT_MOUSEENTER="mouseenter";}static{this.EVENT_MOUSELEAVE="mouseleave";}static{this.EVENT_MOUSEMOVE="mousemove";}static{this.EVENT_MOUSEWHEEL="mousewheel";}static{this.EVENT_CLICK="click";}static{this.EVENT_TOUCHSTART="touchstart";}static{this.EVENT_TOUCHEND="touchend";}static{this.EVENT_TOUCHMOVE="touchmove";}static{this.EVENT_TOUCHCANCEL="touchcancel";}constructor(e,t){super(e,t),this._evtLayersChanged=null,this._evtLayerAdded=null,this._evtLayerRemoved=null,this._beingInitialized=false,this._anchor=new eF,this._localAnchor=new eF,this._pivot=new eN,this._width=this._calculatedWidth=32,this._height=this._calculatedHeight=32,this._margin=new eF(0,0,-32,-32),this._modelTransform=new eG,this._screenToWorld=new eG,this._anchorTransform=new eG,this._anchorDirty=true,this._parentWorldTransform=new eG,this._screenTransform=new eG,this._screenCorners=[new eM,new eM,new eM,new eM],this._canvasCorners=[new eN,new eN,new eN,new eN],this._worldCorners=[new eM,new eM,new eM,new eM],this._cornersDirty=true,this._canvasCornersDirty=true,this._worldCornersDirty=true,this.entity.on("insert",this._onInsert,this),this._patch(),this.screen=null,this._type=ET,this._image=null,this._text=null,this._group=null,this._drawOrder=0,this._fitMode=Eb,this._useInput=false,this._layers=[uL],this._addedModels=[],this._batchGroupId=-1,this._offsetReadAt=0,this._maskOffset=.5,this._maskedBy=null;}get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){let t=this.data,i=t.enabled;t.enabled=e,this.fire("set","enabled",i,e);}get enabled(){return this.data.enabled}get _absLeft(){return this._localAnchor.x+this._margin.x}get _absRight(){return this._localAnchor.z-this._margin.z}get _absTop(){return this._localAnchor.w-this._margin.w}get _absBottom(){return this._localAnchor.y+this._margin.y}get _hasSplitAnchorsX(){return Math.abs(this._anchor.x-this._anchor.z)>.001}get _hasSplitAnchorsY(){return Math.abs(this._anchor.y-this._anchor.w)>.001}get aabb(){return this._image?this._image.aabb:this._text?this._text.aabb:null}set anchor(e){e instanceof eF?this._anchor.copy(e):this._anchor.set(...e),this.entity._parent||this.screen?this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY):this._calculateLocalAnchors(),this._anchorDirty=true,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:anchor",this._anchor);}get anchor(){return this._anchor}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher?.remove(mS.ELEMENT,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(mS.ELEMENT,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&(this._image&&this._image._renderable.model?this.addModelToLayers(this._image._renderable.model):this._text&&this._text._model&&this.addModelToLayers(this._text._model)),this._batchGroupId=e);}get batchGroupId(){return this._batchGroupId}set bottom(e){this._margin.y=e;let t=this.entity.getLocalPosition(),i=this._absTop,s=this._localAnchor.y+e;this._setHeight(i-s),t.y=e+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(t);}get bottom(){return this._margin.y}set calculatedWidth(e){this._setCalculatedWidth(e,true);}get calculatedWidth(){return this._calculatedWidth}set calculatedHeight(e){this._setCalculatedHeight(e,true);}get calculatedHeight(){return this._calculatedHeight}get canvasCorners(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;let e=this.system.app.graphicsDevice,t=this.screenCorners,i=e.canvas.clientWidth/e.width,s=e.canvas.clientHeight/e.height;for(let r=0;r<4;r++)this._canvasCorners[r].set(t[r].x*i,(e.height-t[r].y)*s);return this._canvasCornersDirty=false,this._canvasCorners}set drawOrder(e){let t=0;this.screen&&(t=this.screen.screen.priority),e>0xffffff&&(e=0xffffff),this._drawOrder=(t<<24)+e,this.fire("set:draworder",this._drawOrder);}get drawOrder(){return this._drawOrder}set height(e){this._height=e,this._hasSplitAnchorsY||this._setCalculatedHeight(e,true),this.fire("set:height",this._height);}get height(){return this._height}set layers(e){if(this._addedModels.length)for(let e=0;e<this._layers.length;e++){let t=this.system.app.scene.layers.getLayerById(this._layers[e]);if(t)for(let e=0;e<this._addedModels.length;e++)t.removeMeshInstances(this._addedModels[e].meshInstances);}if(this._layers=e,this.enabled&&this.entity.enabled&&this._addedModels.length)for(let e=0;e<this._layers.length;e++){let t=this.system.app.scene.layers.getLayerById(this._layers[e]);if(t)for(let e=0;e<this._addedModels.length;e++)t.addMeshInstances(this._addedModels[e].meshInstances);}}get layers(){return this._layers}set left(e){this._margin.x=e;let t=this.entity.getLocalPosition(),i=this._absRight,s=this._localAnchor.x+e;this._setWidth(i-s),t.x=e+this._calculatedWidth*this._pivot.x,this.entity.setLocalPosition(t);}get left(){return this._margin.x}set margin(e){this._margin.copy(e),this._calculateSize(true,true),this.fire("set:margin",this._margin);}get margin(){return this._margin}get maskedBy(){return this._maskedBy}set pivot(e){let{pivot:t,margin:i}=this,s=t.x,r=t.y;e instanceof eN?t.copy(e):t.set(...e);let a=i.x+i.z,n=t.x-s;i.x+=a*n,i.z-=a*n;let o=i.y+i.w,l=t.y-r;i.y+=o*l,i.w-=o*l,this._anchorDirty=true,this._cornersDirty=true,this._worldCornersDirty=true,this._calculateSize(false,false),this._flagChildrenAsDirty(),this.fire("set:pivot",t);}get pivot(){return this._pivot}set right(e){this._margin.z=e;let t=this.entity.getLocalPosition(),i=this._absLeft,s=this._localAnchor.z-e;this._setWidth(s-i),t.x=this._localAnchor.z-this._localAnchor.x-e-this._calculatedWidth*(1-this._pivot.x),this.entity.setLocalPosition(t);}get right(){return this._margin.z}get screenCorners(){if(!this._cornersDirty||!this.screen)return this._screenCorners;let e=this.entity.parent&&this.entity.parent.element&&this.entity.parent.element.screenCorners[0];this._screenCorners[0].set(this._absLeft,this._absBottom,0),this._screenCorners[1].set(this._absRight,this._absBottom,0),this._screenCorners[2].set(this._absRight,this._absTop,0),this._screenCorners[3].set(this._absLeft,this._absTop,0);let t=this.screen.screen.screenSpace;for(let i=0;i<4;i++)this._screenTransform.transformPoint(this._screenCorners[i],this._screenCorners[i]),t&&this._screenCorners[i].mulScalar(this.screen.screen.scale),e&&this._screenCorners[i].add(e);return this._cornersDirty=false,this._canvasCornersDirty=true,this._worldCornersDirty=true,this._screenCorners}get textWidth(){return this._text?this._text.width:0}get textHeight(){return this._text?this._text.height:0}set top(e){this._margin.w=e;let t=this.entity.getLocalPosition(),i=this._absBottom,s=this._localAnchor.w-e;this._setHeight(s-i),t.y=this._localAnchor.w-this._localAnchor.y-e-this._calculatedHeight*(1-this._pivot.y),this.entity.setLocalPosition(t);}get top(){return this._margin.w}set type(e){e!==this._type&&(this._type=e,this._image&&(this._image.destroy(),this._image=null),this._text&&(this._text.destroy(),this._text=null),e===EE?this._image=new AL(this):e===EA&&(this._text=new Aj(this)));}get type(){return this._type}set useInput(e){this._useInput!==e&&(this._useInput=e,this.system.app.elementInput?e?this.enabled&&this.entity.enabled&&this.system.app.elementInput.addElement(this):this.system.app.elementInput.removeElement(this):this._useInput,this.fire("set:useInput",e));}get useInput(){return this._useInput}set fitMode(e){this._fitMode=e,this._calculateSize(true,true),this._image&&this._image.refreshMesh();}get fitMode(){return this._fitMode}set width(e){this._width=e,this._hasSplitAnchorsX||this._setCalculatedWidth(e,true),this.fire("set:width",this._width);}get width(){return this._width}get worldCorners(){if(!this._worldCornersDirty)return this._worldCorners;if(this.screen){let e=this.screenCorners;if(!this.screen.screen.screenSpace){A0.copy(this.screen.screen._screenMatrix),A0.data[13]=-A0.data[13],A0.mul2(this.screen.getWorldTransform(),A0);for(let t=0;t<4;t++)A0.transformPoint(e[t],this._worldCorners[t]);}}else {let e=this.entity.getLocalPosition();A0.setTranslate(-e.x,-e.y,-e.z),A1.setTRS(eM.ZERO,this.entity.getLocalRotation(),this.entity.getLocalScale()),A2.setTranslate(e.x,e.y,e.z);let t=this.entity.parent?this.entity.parent:this.entity;A3.copy(t.getWorldTransform()),A3.mul(A2).mul(A1).mul(A0),AQ.set(e.x-this.pivot.x*this.calculatedWidth,e.y-this.pivot.y*this.calculatedHeight,e.z),A3.transformPoint(AQ,this._worldCorners[0]),AQ.set(e.x+(1-this.pivot.x)*this.calculatedWidth,e.y-this.pivot.y*this.calculatedHeight,e.z),A3.transformPoint(AQ,this._worldCorners[1]),AQ.set(e.x+(1-this.pivot.x)*this.calculatedWidth,e.y+(1-this.pivot.y)*this.calculatedHeight,e.z),A3.transformPoint(AQ,this._worldCorners[2]),AQ.set(e.x-this.pivot.x*this.calculatedWidth,e.y+(1-this.pivot.y)*this.calculatedHeight,e.z),A3.transformPoint(AQ,this._worldCorners[3]);}return this._worldCornersDirty=false,this._worldCorners}set fontSize(e){this._setValue("fontSize",e);}get fontSize(){return this._text?this._text.fontSize:null}set minFontSize(e){this._setValue("minFontSize",e);}get minFontSize(){return this._text?this._text.minFontSize:null}set maxFontSize(e){this._setValue("maxFontSize",e);}get maxFontSize(){return this._text?this._text.maxFontSize:null}set maxLines(e){this._setValue("maxLines",e);}get maxLines(){return this._text?this._text.maxLines:null}set autoFitWidth(e){this._setValue("autoFitWidth",e);}get autoFitWidth(){return this._text?this._text.autoFitWidth:null}set autoFitHeight(e){this._setValue("autoFitHeight",e);}get autoFitHeight(){return this._text?this._text.autoFitHeight:null}set color(e){this._setValue("color",e);}get color(){return this._text?this._text.color:this._image?this._image.color:null}set font(e){this._setValue("font",e);}get font(){return this._text?this._text.font:null}set fontAsset(e){this._setValue("fontAsset",e);}get fontAsset(){return this._text&&"number"==typeof this._text.fontAsset?this._text.fontAsset:null}set spacing(e){this._setValue("spacing",e);}get spacing(){return this._text?this._text.spacing:null}set lineHeight(e){this._setValue("lineHeight",e);}get lineHeight(){return this._text?this._text.lineHeight:null}set wrapLines(e){this._setValue("wrapLines",e);}get wrapLines(){return this._text?this._text.wrapLines:null}set lines(e){this._setValue("lines",e);}get lines(){return this._text?this._text.lines:null}set alignment(e){this._setValue("alignment",e);}get alignment(){return this._text?this._text.alignment:null}set autoWidth(e){this._setValue("autoWidth",e);}get autoWidth(){return this._text?this._text.autoWidth:null}set autoHeight(e){this._setValue("autoHeight",e);}get autoHeight(){return this._text?this._text.autoHeight:null}set rtlReorder(e){this._setValue("rtlReorder",e);}get rtlReorder(){return this._text?this._text.rtlReorder:null}set unicodeConverter(e){this._setValue("unicodeConverter",e);}get unicodeConverter(){return this._text?this._text.unicodeConverter:null}set text(e){this._setValue("text",e);}get text(){return this._text?this._text.text:null}set key(e){this._setValue("key",e);}get key(){return this._text?this._text.key:null}set texture(e){this._setValue("texture",e);}get texture(){return this._image?this._image.texture:null}set textureAsset(e){this._setValue("textureAsset",e);}get textureAsset(){return this._image?this._image.textureAsset:null}set material(e){this._setValue("material",e);}get material(){return this._image?this._image.material:null}set materialAsset(e){this._setValue("materialAsset",e);}get materialAsset(){return this._image?this._image.materialAsset:null}set sprite(e){this._setValue("sprite",e);}get sprite(){return this._image?this._image.sprite:null}set spriteAsset(e){this._setValue("spriteAsset",e);}get spriteAsset(){return this._image?this._image.spriteAsset:null}set spriteFrame(e){this._setValue("spriteFrame",e);}get spriteFrame(){return this._image?this._image.spriteFrame:null}set pixelsPerUnit(e){this._setValue("pixelsPerUnit",e);}get pixelsPerUnit(){return this._image?this._image.pixelsPerUnit:null}set opacity(e){this._setValue("opacity",e);}get opacity(){return this._text?this._text.opacity:this._image?this._image.opacity:null}set rect(e){this._setValue("rect",e);}get rect(){return this._image?this._image.rect:null}set mask(e){this._setValue("mask",e);}get mask(){return this._image?this._image.mask:null}set outlineColor(e){this._setValue("outlineColor",e);}get outlineColor(){return this._text?this._text.outlineColor:null}set outlineThickness(e){this._setValue("outlineThickness",e);}get outlineThickness(){return this._text?this._text.outlineThickness:null}set shadowColor(e){this._setValue("shadowColor",e);}get shadowColor(){return this._text?this._text.shadowColor:null}set shadowOffset(e){this._setValue("shadowOffset",e);}get shadowOffset(){return this._text?this._text.shadowOffset:null}set enableMarkup(e){this._setValue("enableMarkup",e);}get enableMarkup(){return this._text?this._text.enableMarkup:null}set rangeStart(e){this._setValue("rangeStart",e);}get rangeStart(){return this._text?this._text.rangeStart:null}set rangeEnd(e){this._setValue("rangeEnd",e);}get rangeEnd(){return this._text?this._text.rangeEnd:null}_setValue(e,t){this._text?(this._text[e]!==t&&this._dirtyBatch(),this._text[e]=t):this._image&&(this._image[e]!==t&&this._dirtyBatch(),this._image[e]=t);}_patch(){this.entity._sync=this._sync,this.entity.setPosition=this._setPosition,this.entity.setLocalPosition=this._setLocalPosition;}_unpatch(){this.entity._sync=x1.prototype._sync,this.entity.setPosition=x1.prototype.setPosition,this.entity.setLocalPosition=x1.prototype.setLocalPosition;}_setPosition(e,t,i){if(!this.element.screen)return void x1.prototype.setPosition.call(this,e,t,i);e instanceof eM?AK.copy(e):AK.set(e,t,i),this.getWorldTransform(),AZ.copy(this.element._screenToWorld).invert(),AZ.transformPoint(AK,this.localPosition),this._dirtyLocal||this._dirtifyLocal();}_setLocalPosition(e,t,i){e instanceof eM?this.localPosition.copy(e):this.localPosition.set(e,t,i);let s=this.element,r=this.localPosition,a=s._pivot;s._margin.x=r.x-s._calculatedWidth*a.x,s._margin.z=s._localAnchor.z-s._localAnchor.x-s._calculatedWidth-s._margin.x,s._margin.y=r.y-s._calculatedHeight*a.y,s._margin.w=s._localAnchor.w-s._localAnchor.y-s._calculatedHeight-s._margin.y,this._dirtyLocal||this._dirtifyLocal();}_sync(){let e=this.element,t=e.screen;if(t){if(e._anchorDirty){let i=0,s=0,r=0,a=1;if(this._parent&&this._parent.element)i=this._parent.element.calculatedWidth,s=this._parent.element.calculatedHeight,r=this._parent.element.pivot.x,a=this._parent.element.pivot.y;else {let e=t.screen.resolution;i=e.x/t.screen.scale,s=e.y/t.screen.scale;}e._anchorTransform.setTranslate(i*(e.anchor.x-r),-(s*(a-e.anchor.y)),0),e._anchorDirty=false,e._calculateLocalAnchors();}e._sizeDirty&&e._calculateSize(false,false);}if(this._dirtyLocal){this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale);let t=this.localPosition,i=e._pivot;e._margin.x=t.x-e._calculatedWidth*i.x,e._margin.z=e._localAnchor.z-e._localAnchor.x-e._calculatedWidth-e._margin.x,e._margin.y=t.y-e._calculatedHeight*i.y,e._margin.w=e._localAnchor.w-e._localAnchor.y-e._calculatedHeight-e._margin.y,this._dirtyLocal=false;}if(!t){this._dirtyWorld&&(e._cornersDirty=true,e._canvasCornersDirty=true,e._worldCornersDirty=true),x1.prototype._sync.call(this);return}if(this._dirtyWorld){if(null===this._parent)this.worldTransform.copy(this.localTransform);else if(this._parent.element?e._screenToWorld.mul2(this._parent.element._modelTransform,e._anchorTransform):e._screenToWorld.copy(e._anchorTransform),e._modelTransform.mul2(e._screenToWorld,this.localTransform),t){e._screenToWorld.mul2(t.screen._screenMatrix,e._screenToWorld),t.screen.screenSpace||e._screenToWorld.mul2(t.worldTransform,e._screenToWorld),this.worldTransform.mul2(e._screenToWorld,this.localTransform);let i=e._parentWorldTransform;i.setIdentity();let s=this._parent;s&&s.element&&s!==t&&(A0.setTRS(eM.ZERO,s.getLocalRotation(),s.getLocalScale()),i.mul2(s.element._parentWorldTransform,A0)),AQ.set(0,0,this.localPosition.z),AJ.set(e._absLeft+e._pivot.x*e.calculatedWidth,e._absBottom+e._pivot.y*e.calculatedHeight,0),A0.setTranslate(-AJ.x,-AJ.y,-AJ.z),A1.setTRS(AQ,this.getLocalRotation(),this.getLocalScale()),A2.setTranslate(AJ.x,AJ.y,AJ.z),e._screenTransform.mul2(e._parentWorldTransform,A2).mul(A1).mul(A0),e._cornersDirty=true,e._canvasCornersDirty=true,e._worldCornersDirty=true;}else this.worldTransform.copy(e._modelTransform);this._dirtyWorld=false;}}_onInsert(e){let t=this._parseUpToScreen();this.entity._dirtifyWorld(),this._updateScreen(t.screen),this._dirtifyMask();}_dirtifyMask(){let e=this.entity;for(;e;){let t=e.parent;if((null===t||t.screen)&&e.element){this.system._prerender&&this.system._prerender.length||(this.system._prerender=[],this.system.app.once("prerender",this._onPrerender,this));let t=this.system._prerender.indexOf(this.entity);t>=0&&this.system._prerender.splice(t,1),0>this.system._prerender.indexOf(e)&&this.system._prerender.push(e);}e=t;}}_onPrerender(){for(let e=0;e<this.system._prerender.length;e++){let t=this.system._prerender[e];t.element&&t.element.syncMask(1);}this.system._prerender.length=0;}_bindScreen(e){e._bindElement(this);}_unbindScreen(e){e._unbindElement(this);}_updateScreen(e){this.screen&&this.screen!==e&&this._unbindScreen(this.screen.screen);let t=this.screen;this.screen=e,this.screen&&this._bindScreen(this.screen.screen),this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("set:screen",this.screen,t),this._anchorDirty=true;let i=this.entity.children;for(let t=0,s=i.length;t<s;t++)i[t].element&&i[t].element._updateScreen(e);this.screen&&this.screen.screen.syncDrawOrder();}syncMask(e){let t=this._parseUpToScreen();this._updateMask(t.mask,e);}_setMaskedBy(e){let t=this._image||this._text;if(e){let i=e.element._image._maskRef;t?._setStencil(new nI({ref:i,func:t4})),this._maskedBy=e;}else t?._setStencil(null),this._maskedBy=null;}_updateMask(e,t){if(e){if(this._setMaskedBy(e),this.mask){let i=new nI({ref:e.element._image._maskRef,func:t4,zpass:s3});this._image._setStencil(i),this._image._maskRef=t,t++,e=this.entity;}let i=this.entity.children;for(let s=0,r=i.length;s<r;s++)i[s].element?._updateMask(e,t);this.mask&&t--;}else {if(this._setMaskedBy(null),this.mask){let i=new nI({ref:t,func:t7,zpass:s2});this._image._setStencil(i),this._image._maskRef=t,t++,e=this.entity;}let i=this.entity.children;for(let s=0,r=i.length;s<r;s++)i[s].element?._updateMask(e,t);this.mask&&t--;}}_parseUpToScreen(){let e={screen:null,mask:null},t=this.entity._parent;for(;t&&!t.screen;)t.element&&t.element.mask&&!e.mask&&(e.mask=t),t=t.parent;return t&&t.screen&&(e.screen=t),e}_onScreenResize(e){this._anchorDirty=true,this._cornersDirty=true,this._worldCornersDirty=true,this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("screen:set:resolution",e);}_onScreenSpaceChange(){this.fire("screen:set:screenspace",this.screen.screen.screenSpace);}_onScreenRemove(){this.screen&&(this.screen._destroying?this.screen=null:this._updateScreen(null));}_calculateLocalAnchors(){let e=1e3,t=1e3,i=this.entity._parent;if(i&&i.element)e=i.element.calculatedWidth,t=i.element.calculatedHeight;else if(this.screen){let i=this.screen.screen.resolution,s=this.screen.screen.scale;e=i.x/s,t=i.y/s;}this._localAnchor.set(this._anchor.x*e,this._anchor.y*t,this._anchor.z*e,this._anchor.w*t);}getOffsetPosition(e,t){let i=this.entity.getLocalPosition().clone();return i.x+=e,i.y+=t,this._screenToWorld.transformPoint(i,i),i}onLayersChanged(e,t){this.addModelToLayers(this._image?this._image._renderable.model:this._text._model),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this);}onLayerAdded(e){!(0>this.layers.indexOf(e.id))&&(this._image?e.addMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.addMeshInstances(this._text._model.meshInstances));}onLayerRemoved(e){!(0>this.layers.indexOf(e.id))&&(this._image?e.removeMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.removeMeshInstances(this._text._model.meshInstances));}onEnable(){let e=this.system.app.scene,t=e.layers;this._image&&this._image.onEnable(),this._text&&this._text.onEnable(),this._group&&this._group.onEnable(),this.useInput&&this.system.app.elementInput&&this.system.app.elementInput.addElement(this),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this._batchGroupId>=0&&this.system.app.batcher?.insert(mS.ELEMENT,this.batchGroupId,this.entity),this.fire("enableelement");}onDisable(){let e=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,e&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._image&&this._image.onDisable(),this._text&&this._text.onDisable(),this._group&&this._group.onDisable(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this._batchGroupId>=0&&this.system.app.batcher?.remove(mS.ELEMENT,this.batchGroupId,this.entity),this.fire("disableelement");}onRemove(){this.entity.off("insert",this._onInsert,this),this._unpatch(),this._image&&this._image.destroy(),this._text&&this._text.destroy(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this.screen&&this.screen.screen&&(this._unbindScreen(this.screen.screen),this.screen.screen.syncDrawOrder()),this.off();}_calculateSize(e,t){if(!this.entity._parent&&!this.screen)return;this._calculateLocalAnchors();let i=this._absRight-this._absLeft,s=this._absTop-this._absBottom;e?this._setWidth(i):this._setCalculatedWidth(i,false),t?this._setHeight(s):this._setCalculatedHeight(s,false);let r=this.entity.getLocalPosition();r.x=this._margin.x+this._calculatedWidth*this._pivot.x,r.y=this._margin.y+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(r),this._sizeDirty=false;}_setWidth(e){this._width=e,this._setCalculatedWidth(e,false),this.fire("set:width",this._width);}_setHeight(e){this._height=e,this._setCalculatedHeight(e,false),this.fire("set:height",this._height);}_setCalculatedWidth(e,t){if(!(1e-4>=Math.abs(e-this._calculatedWidth))){if(this._calculatedWidth=e,this.entity._dirtifyLocal(),t){let e=this.entity.getLocalPosition(),t=this._pivot;this._margin.x=e.x-this._calculatedWidth*t.x,this._margin.z=this._localAnchor.z-this._localAnchor.x-this._calculatedWidth-this._margin.x;}this._flagChildrenAsDirty(),this.fire("set:calculatedWidth",this._calculatedWidth),this.fire("resize",this._calculatedWidth,this._calculatedHeight);}}_setCalculatedHeight(e,t){if(!(1e-4>=Math.abs(e-this._calculatedHeight))){if(this._calculatedHeight=e,this.entity._dirtifyLocal(),t){let e=this.entity.getLocalPosition(),t=this._pivot;this._margin.y=e.y-this._calculatedHeight*t.y,this._margin.w=this._localAnchor.w-this._localAnchor.y-this._calculatedHeight-this._margin.y;}this._flagChildrenAsDirty(),this.fire("set:calculatedHeight",this._calculatedHeight),this.fire("resize",this._calculatedWidth,this._calculatedHeight);}}_flagChildrenAsDirty(){let e=this.entity._children;for(let t=0,i=e.length;t<i;t++)e[t].element&&(e[t].element._anchorDirty=true,e[t].element._sizeDirty=true);}addModelToLayers(e){this._addedModels.push(e);for(let t=0;t<this.layers.length;t++){let i=this.system.app.scene.layers.getLayerById(this.layers[t]);i&&i.addMeshInstances(e.meshInstances);}}removeModelFromLayers(e){let t=this._addedModels.indexOf(e);t>=0&&this._addedModels.splice(t,1);for(let t=0;t<this.layers.length;t++){let i=this.system.app.scene.layers.getLayerById(this.layers[t]);i&&i.removeMeshInstances(e.meshInstances);}}getMaskOffset(){let e=this.system.app.frame;this._offsetReadAt!==e&&(this._maskOffset=.5,this._offsetReadAt=e);let t=this._maskOffset;return this._maskOffset-=.001,t}isVisibleForCamera(e){let t,i,s,r;if(this.maskedBy){let e=this.maskedBy.element.screenCorners;t=Math.min(Math.min(e[0].x,e[1].x),Math.min(e[2].x,e[3].x)),i=Math.max(Math.max(e[0].x,e[1].x),Math.max(e[2].x,e[3].x)),r=Math.min(Math.min(e[0].y,e[1].y),Math.min(e[2].y,e[3].y)),s=Math.max(Math.max(e[0].y,e[1].y),Math.max(e[2].y,e[3].y));}else {let a=this.system.app.graphicsDevice.width,n=this.system.app.graphicsDevice.height,o=e._rect.z*a,l=e._rect.w*n;i=(t=e._rect.x*a)+o,r=(s=(1-e._rect.y)*n)-l;}let a=this.screenCorners,n=Math.min(Math.min(a[0].x,a[1].x),Math.min(a[2].x,a[3].x)),o=Math.max(Math.max(a[0].x,a[1].x),Math.max(a[2].x,a[3].x)),l=Math.min(Math.min(a[0].y,a[1].y),Math.min(a[2].y,a[3].y)),h=Math.max(Math.max(a[0].y,a[1].y),Math.max(a[2].y,a[3].y));return !(o<t)&&!(n>i)&&!(l>s)&&!(h<r)}_isScreenSpace(){return !!this.screen&&!!this.screen.screen&&this.screen.screen.screenSpace}_isScreenCulled(){return !!this.screen&&!!this.screen.screen&&this.screen.screen.cull}_dirtyBatch(){ -1!==this.batchGroupId&&this.system.app.batcher?.markGroupDirty(this.batchGroupId);}}class A5{constructor(){this.enabled=true;}}let A8=["enabled"];class A6 extends Tm{constructor(e){super(e),this.id="element",this.ComponentType=A4,this.DataType=A5,this.schema=A8,this._unicodeConverter=null,this._rtlReorder=null,this._defaultTexture=new ns(e.graphicsDevice,{width:1,height:1,format:ib,name:"element-system"});let t=this._defaultTexture.lock(),i=new Uint8Array(4);i[0]=255,i[1]=255,i[2]=255,i[3]=255,t.set(i),this._defaultTexture.unlock(),this.defaultImageMaterial=null,this.defaultImage9SlicedMaterial=null,this.defaultImage9TiledMaterial=null,this.defaultImageMaskMaterial=null,this.defaultImage9SlicedMaskMaterial=null,this.defaultImage9TiledMaskMaterial=null,this.defaultScreenSpaceImageMaterial=null,this.defaultScreenSpaceImage9SlicedMaterial=null,this.defaultScreenSpaceImage9TiledMaterial=null,this.defaultScreenSpaceImageMask9SlicedMaterial=null,this.defaultScreenSpaceImageMask9TiledMaterial=null,this.defaultScreenSpaceImageMaskMaterial=null,this._defaultTextMaterials={},this.defaultImageMaterials=[],this.on("add",this.onAddComponent,this),this.on("beforeremove",this.onRemoveComponent,this);}destroy(){super.destroy(),this._defaultTexture.destroy();}initializeComponentData(e,t,i){let s;e._beingInitialized=true,void 0!==t.anchor&&(t.anchor instanceof eF?e.anchor.copy(t.anchor):e.anchor.set(t.anchor[0],t.anchor[1],t.anchor[2],t.anchor[3])),void 0!==t.pivot&&(t.pivot instanceof eN?e.pivot.copy(t.pivot):e.pivot.set(t.pivot[0],t.pivot[1]));let r=Math.abs(e.anchor.x-e.anchor.z)>.001,a=Math.abs(e.anchor.y-e.anchor.w)>.001,n=false;void 0!==t.margin&&(t.margin instanceof eF?e.margin.copy(t.margin):e._margin.set(t.margin[0],t.margin[1],t.margin[2],t.margin[3]),n=true),void 0!==t.left&&(e._margin.x=t.left,n=true),void 0!==t.bottom&&(e._margin.y=t.bottom,n=true),void 0!==t.right&&(e._margin.z=t.right,n=true),void 0!==t.top&&(e._margin.w=t.top,n=true),n&&(e.margin=e._margin);let o=false;void 0===t.width||r?r&&(o=true):e.width=t.width,void 0===t.height||a?a&&(o=true):e.height=t.height,o&&(e.anchor=e.anchor),void 0!==t.enabled&&(e.enabled=t.enabled),void 0!==t.useInput&&(e.useInput=t.useInput),void 0!==t.fitMode&&(e.fitMode=t.fitMode),e.batchGroupId=void 0===t.batchGroupId||null===t.batchGroupId?-1:t.batchGroupId,t.layers&&Array.isArray(t.layers)&&(e.layers=t.layers.slice(0)),void 0!==t.type&&(e.type=t.type),e.type===EE?(void 0!==t.rect&&(e.rect=t.rect),void 0!==t.color&&((s=t.color)instanceof eb||(s=new eb(t.color[0],t.color[1],t.color[2])),e.color=s),void 0!==t.opacity&&(e.opacity=t.opacity),void 0!==t.textureAsset&&(e.textureAsset=t.textureAsset),t.texture&&(e.texture=t.texture),void 0!==t.spriteAsset&&(e.spriteAsset=t.spriteAsset),t.sprite&&(e.sprite=t.sprite),void 0!==t.spriteFrame&&(e.spriteFrame=t.spriteFrame),void 0!==t.pixelsPerUnit&&null!==t.pixelsPerUnit&&(e.pixelsPerUnit=t.pixelsPerUnit),void 0!==t.materialAsset&&(e.materialAsset=t.materialAsset),t.material&&(e.material=t.material),void 0!==t.mask&&(e.mask=t.mask)):e.type===EA&&(void 0!==t.autoWidth&&(e.autoWidth=t.autoWidth),void 0!==t.autoHeight&&(e.autoHeight=t.autoHeight),void 0!==t.rtlReorder&&(e.rtlReorder=t.rtlReorder),void 0!==t.unicodeConverter&&(e.unicodeConverter=t.unicodeConverter),null!==t.text&&void 0!==t.text?e.text=t.text:null!==t.key&&void 0!==t.key&&(e.key=t.key),void 0!==t.color&&((s=t.color)instanceof eb||(s=new eb(s[0],s[1],s[2])),e.color=s),void 0!==t.opacity&&(e.opacity=t.opacity),void 0!==t.spacing&&(e.spacing=t.spacing),void 0!==t.fontSize&&(e.fontSize=t.fontSize,t.lineHeight||(e.lineHeight=t.fontSize)),void 0!==t.lineHeight&&(e.lineHeight=t.lineHeight),void 0!==t.maxLines&&(e.maxLines=t.maxLines),void 0!==t.wrapLines&&(e.wrapLines=t.wrapLines),void 0!==t.minFontSize&&(e.minFontSize=t.minFontSize),void 0!==t.maxFontSize&&(e.maxFontSize=t.maxFontSize),t.autoFitWidth&&(e.autoFitWidth=t.autoFitWidth),t.autoFitHeight&&(e.autoFitHeight=t.autoFitHeight),void 0!==t.fontAsset&&(e.fontAsset=t.fontAsset),void 0!==t.font&&(e.font=t.font),void 0!==t.alignment&&(e.alignment=t.alignment),void 0!==t.outlineColor&&(e.outlineColor=t.outlineColor),void 0!==t.outlineThickness&&(e.outlineThickness=t.outlineThickness),void 0!==t.shadowColor&&(e.shadowColor=t.shadowColor),void 0!==t.shadowOffset&&(e.shadowOffset=t.shadowOffset),void 0!==t.enableMarkup&&(e.enableMarkup=t.enableMarkup));let l=e._parseUpToScreen();l.screen&&e._updateScreen(l.screen),super.initializeComponentData(e,t,i),e._beingInitialized=false,e.type===EE&&e._image._meshDirty&&e._image._updateMesh(e._image.mesh);}onAddComponent(e,t){e.fire("element:add");}onRemoveComponent(e,t){t.onRemove();}cloneComponent(e,t){let i=e.element,s={enabled:i.enabled,width:i.width,height:i.height,anchor:i.anchor.clone(),pivot:i.pivot.clone(),margin:i.margin.clone(),alignment:i.alignment&&i.alignment.clone()||i.alignment,autoWidth:i.autoWidth,autoHeight:i.autoHeight,type:i.type,rect:i.rect&&i.rect.clone()||i.rect,rtlReorder:i.rtlReorder,unicodeConverter:i.unicodeConverter,materialAsset:i.materialAsset,material:i.material,color:i.color&&i.color.clone()||i.color,opacity:i.opacity,textureAsset:i.textureAsset,texture:i.texture,spriteAsset:i.spriteAsset,sprite:i.sprite,spriteFrame:i.spriteFrame,pixelsPerUnit:i.pixelsPerUnit,spacing:i.spacing,lineHeight:i.lineHeight,wrapLines:i.wrapLines,layers:i.layers,fontSize:i.fontSize,minFontSize:i.minFontSize,maxFontSize:i.maxFontSize,autoFitWidth:i.autoFitWidth,autoFitHeight:i.autoFitHeight,maxLines:i.maxLines,fontAsset:i.fontAsset,font:i.font,useInput:i.useInput,fitMode:i.fitMode,batchGroupId:i.batchGroupId,mask:i.mask,outlineColor:i.outlineColor&&i.outlineColor.clone()||i.outlineColor,outlineThickness:i.outlineThickness,shadowColor:i.shadowColor&&i.shadowColor.clone()||i.shadowColor,shadowOffset:i.shadowOffset&&i.shadowOffset.clone()||i.shadowOffset,enableMarkup:i.enableMarkup};return void 0!==i.key&&null!==i.key?s.key=i.key:s.text=i.text,this.addComponent(t,s)}getTextElementMaterial(e,t,i){let s=(e&&1)|(t&&2)|(i&&4),r=this._defaultTextMaterials[s];if(r)return r;let a="TextMaterial";return r=new yo,t?(r.msdfMap=this._defaultTexture,r.msdfTextAttribute=i,r.emissive.set(1,1,1)):(a=`Bitmap${a}`,r.emissive.set(1,1,1),r.emissiveMap=this._defaultTexture,r.opacityMap=this._defaultTexture,r.opacityMapChannel="a"),e&&(a=`ScreenSpace${a}`,r.depthTest=false),r.name=`default${a}`,r.useLighting=false,r.useTonemap=false,r.useFog=false,r.useSkybox=false,r.diffuse.set(0,0,0),r.opacity=.5,r.blendType=uo,r.depthWrite=false,r.emissiveVertexColor=true,r.update(),this._defaultTextMaterials[s]=r,r}_createBaseImageMaterial(){let e=new yo;return e.diffuse.set(0,0,0),e.emissive.set(1,1,1),e.emissiveMap=this._defaultTexture,e.opacityMap=this._defaultTexture,e.opacityMapChannel="a",e.useLighting=false,e.useTonemap=false,e.useFog=false,e.useSkybox=false,e.blendType=uo,e.depthWrite=false,e}getImageElementMaterial(e,t,i,s){if(e)if(t)if(i)return this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name="defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=pw,this.defaultScreenSpaceImageMask9SlicedMaterial.depthTest=false,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9SlicedMaterial.redWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.greenWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.blueWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9SlicedMaterial)),this.defaultScreenSpaceImageMask9SlicedMaterial;else if(s)return this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=pC,this.defaultScreenSpaceImageMask9TiledMaterial.depthTest=false,this.defaultScreenSpaceImageMask9TiledMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9TiledMaterial.redWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.greenWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.blueWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.alphaWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9TiledMaterial)),this.defaultScreenSpaceImageMask9TiledMaterial;else return this.defaultScreenSpaceImageMaskMaterial||(this.defaultScreenSpaceImageMaskMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaskMaterial.name="defaultScreenSpaceImageMaskMaterial",this.defaultScreenSpaceImageMaskMaterial.depthTest=false,this.defaultScreenSpaceImageMaskMaterial.alphaTest=1,this.defaultScreenSpaceImageMaskMaterial.redWrite=false,this.defaultScreenSpaceImageMaskMaterial.greenWrite=false,this.defaultScreenSpaceImageMaskMaterial.blueWrite=false,this.defaultScreenSpaceImageMaskMaterial.alphaWrite=false,this.defaultScreenSpaceImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaskMaterial)),this.defaultScreenSpaceImageMaskMaterial;else if(i)return this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=pw,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=false,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial;else if(s)return this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=pC,this.defaultScreenSpaceImage9TiledMaterial.depthTest=false,this.defaultScreenSpaceImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9TiledMaterial)),this.defaultScreenSpaceImage9TiledMaterial;else return this.defaultScreenSpaceImageMaterial||(this.defaultScreenSpaceImageMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaterial.name="defaultScreenSpaceImageMaterial",this.defaultScreenSpaceImageMaterial.depthTest=false,this.defaultScreenSpaceImageMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaterial)),this.defaultScreenSpaceImageMaterial;if(t)if(i)return this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=pw,this.defaultImage9SlicedMaskMaterial.alphaTest=1,this.defaultImage9SlicedMaskMaterial.redWrite=false,this.defaultImage9SlicedMaskMaterial.greenWrite=false,this.defaultImage9SlicedMaskMaterial.blueWrite=false,this.defaultImage9SlicedMaskMaterial.alphaWrite=false,this.defaultImage9SlicedMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaskMaterial)),this.defaultImage9SlicedMaskMaterial;else if(s)return this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=pC,this.defaultImage9TiledMaskMaterial.alphaTest=1,this.defaultImage9TiledMaskMaterial.redWrite=false,this.defaultImage9TiledMaskMaterial.greenWrite=false,this.defaultImage9TiledMaskMaterial.blueWrite=false,this.defaultImage9TiledMaskMaterial.alphaWrite=false,this.defaultImage9TiledMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaskMaterial)),this.defaultImage9TiledMaskMaterial;else return this.defaultImageMaskMaterial||(this.defaultImageMaskMaterial=this._createBaseImageMaterial(),this.defaultImageMaskMaterial.name="defaultImageMaskMaterial",this.defaultImageMaskMaterial.alphaTest=1,this.defaultImageMaskMaterial.redWrite=false,this.defaultImageMaskMaterial.greenWrite=false,this.defaultImageMaskMaterial.blueWrite=false,this.defaultImageMaskMaterial.alphaWrite=false,this.defaultImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaskMaterial)),this.defaultImageMaskMaterial;return i?(this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=pw,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial):s?(this.defaultImage9TiledMaterial||(this.defaultImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaterial.name="defaultImage9TiledMaterial",this.defaultImage9TiledMaterial.nineSlicedMode=pC,this.defaultImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaterial)),this.defaultImage9TiledMaterial):(this.defaultImageMaterial||(this.defaultImageMaterial=this._createBaseImageMaterial(),this.defaultImageMaterial.name="defaultImageMaterial",this.defaultImageMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaterial)),this.defaultImageMaterial)}registerUnicodeConverter(e){this._unicodeConverter=e;}registerRtlReorder(e){this._rtlReorder=e;}getUnicodeConverter(){return this._unicodeConverter}getRtlReorder(){return this._rtlReorder}}let A9="free",A7="limited",be="locked",bt=["angularDampingX","angularDampingY","angularDampingZ","angularEquilibriumX","angularEquilibriumY","angularEquilibriumZ","angularLimitsX","angularLimitsY","angularLimitsZ","angularMotionX","angularMotionY","angularMotionZ","angularSpringX","angularSpringY","angularSpringZ","angularStiffnessX","angularStiffnessY","angularStiffnessZ","breakForce","enableCollision","enabled","entityA","entityB","linearDampingX","linearDampingY","linearDampingZ","linearEquilibriumX","linearEquilibriumY","linearEquilibriumZ","linearLimitsX","linearLimitsY","linearLimitsZ","linearMotionX","linearMotionY","linearMotionZ","linearSpringX","linearSpringY","linearSpringZ","linearStiffnessX","linearStiffnessY","linearStiffnessZ"];class bi extends Tp{constructor(e,t){super(e,t),this._constraint=null,this._entityA=null,this._entityB=null,this._breakForce=34e37,this._enableCollision=true,this._linearMotionX=be,this._linearLimitsX=new eN(0,0),this._linearSpringX=false,this._linearStiffnessX=0,this._linearDampingX=1,this._linearEquilibriumX=0,this._linearMotionY=be,this._linearLimitsY=new eN(0,0),this._linearSpringY=false,this._linearStiffnessY=0,this._linearDampingY=1,this._linearEquilibriumY=0,this._linearMotionZ=be,this._linearLimitsZ=new eN(0,0),this._linearSpringZ=false,this._linearStiffnessZ=0,this._linearDampingZ=1,this._linearEquilibriumZ=0,this._angularMotionX=be,this._angularLimitsX=new eN(0,0),this._angularSpringX=false,this._angularStiffnessX=0,this._angularDampingX=1,this._angularEquilibriumX=0,this._angularMotionY=be,this._angularLimitsY=new eN(0,0),this._angularSpringY=false,this._angularStiffnessY=0,this._angularDampingY=1,this._angularEquilibriumY=0,this._angularMotionZ=be,this._angularLimitsZ=new eN(0,0),this._angularSpringZ=false,this._angularEquilibriumZ=0,this._angularDampingZ=1,this._angularStiffnessZ=0,this.on("set_enabled",this._onSetEnabled,this);}set entityA(e){this._destroyConstraint(),this._entityA=e,this._createConstraint();}get entityA(){return this._entityA}set entityB(e){this._destroyConstraint(),this._entityB=e,this._createConstraint();}get entityB(){return this._entityB}set breakForce(e){this._constraint&&this._breakForce!==e&&(this._constraint.setBreakingImpulseThreshold(e),this._breakForce=e);}get breakForce(){return this._breakForce}set enableCollision(e){this._destroyConstraint(),this._enableCollision=e,this._createConstraint();}get enableCollision(){return this._enableCollision}set angularLimitsX(e){this._angularLimitsX.equals(e)||(this._angularLimitsX.copy(e),this._updateAngularLimits());}get angularLimitsX(){return this._angularLimitsX}set angularMotionX(e){this._angularMotionX!==e&&(this._angularMotionX=e,this._updateAngularLimits());}get angularMotionX(){return this._angularMotionX}set angularLimitsY(e){this._angularLimitsY.equals(e)||(this._angularLimitsY.copy(e),this._updateAngularLimits());}get angularLimitsY(){return this._angularLimitsY}set angularMotionY(e){this._angularMotionY!==e&&(this._angularMotionY=e,this._updateAngularLimits());}get angularMotionY(){return this._angularMotionY}set angularLimitsZ(e){this._angularLimitsZ.equals(e)||(this._angularLimitsZ.copy(e),this._updateAngularLimits());}get angularLimitsZ(){return this._angularLimitsZ}set angularMotionZ(e){this._angularMotionZ!==e&&(this._angularMotionZ=e,this._updateAngularLimits());}get angularMotionZ(){return this._angularMotionZ}set linearLimitsX(e){this._linearLimitsX.equals(e)||(this._linearLimitsX.copy(e),this._updateLinearLimits());}get linearLimitsX(){return this._linearLimitsX}set linearMotionX(e){this._linearMotionX!==e&&(this._linearMotionX=e,this._updateLinearLimits());}get linearMotionX(){return this._linearMotionX}set linearLimitsY(e){this._linearLimitsY.equals(e)||(this._linearLimitsY.copy(e),this._updateLinearLimits());}get linearLimitsY(){return this._linearLimitsY}set linearMotionY(e){this._linearMotionY!==e&&(this._linearMotionY=e,this._updateLinearLimits());}get linearMotionY(){return this._linearMotionY}set linearLimitsZ(e){this._linearLimitsZ.equals(e)||(this._linearLimitsZ.copy(e),this._updateLinearLimits());}get linearLimitsZ(){return this._linearLimitsZ}set linearMotionZ(e){this._linearMotionZ!==e&&(this._linearMotionZ=e,this._updateLinearLimits());}get linearMotionZ(){return this._linearMotionZ}_convertTransform(e,t){let i=e.getTranslation(),s=new eH;s.setFromMat4(e);let r=new Ammo.btVector3(i.x,i.y,i.z),a=new Ammo.btQuaternion(s.x,s.y,s.z,s.w);t.setOrigin(r),t.setRotation(a),Ammo.destroy(r),Ammo.destroy(a);}_updateAngularLimits(){let e=this._constraint;if(e){let t,i,s,r,a,n;this._angularMotionX===A7?(t=this._angularLimitsX.x*eA.DEG_TO_RAD,r=this._angularLimitsX.y*eA.DEG_TO_RAD):this._angularMotionX===A9?(t=1,r=0):t=r=0,this._angularMotionY===A7?(i=this._angularLimitsY.x*eA.DEG_TO_RAD,a=this._angularLimitsY.y*eA.DEG_TO_RAD):this._angularMotionY===A9?(i=1,a=0):i=a=0,this._angularMotionZ===A7?(s=this._angularLimitsZ.x*eA.DEG_TO_RAD,n=this._angularLimitsZ.y*eA.DEG_TO_RAD):this._angularMotionZ===A9?(s=1,n=0):s=n=0;let o=new Ammo.btVector3(t,i,s);e.setAngularLowerLimit(o),o.setValue(r,a,n),e.setAngularUpperLimit(o),Ammo.destroy(o);}}_updateLinearLimits(){let e=this._constraint;if(e){let t,i,s,r,a,n;this._linearMotionX===A7?(t=this._linearLimitsX.x,r=this._linearLimitsX.y):this._linearMotionX===A9?(t=1,r=0):t=r=0,this._linearMotionY===A7?(i=this._linearLimitsY.x,a=this._linearLimitsY.y):this._linearMotionY===A9?(i=1,a=0):i=a=0,this._linearMotionZ===A7?(s=this._linearLimitsZ.x,n=this._linearLimitsZ.y):this._linearMotionZ===A9?(s=1,n=0):s=n=0;let o=new Ammo.btVector3(t,i,s);e.setLinearLowerLimit(o),o.setValue(r,a,n),e.setLinearUpperLimit(o),Ammo.destroy(o);}}_createConstraint(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();let e=new eG,t=this._entityA.rigidbody.body;t.activate();let i=this.entity.getWorldTransform(),s=this._entityA.getWorldTransform().clone().invert();e.mul2(s,i);let r=new Ammo.btTransform;if(this._convertTransform(e,r),this._entityB&&this._entityB.rigidbody){let s=this._entityB.rigidbody.body;s.activate();let a=this._entityB.getWorldTransform().clone().invert();e.mul2(a,i);let n=new Ammo.btTransform;this._convertTransform(e,n),this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,s,r,n,!this._enableCollision),Ammo.destroy(n);}else this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,r,!this._enableCollision);Ammo.destroy(r);let a=["X","Y","Z","X","Y","Z"];for(let e=0;e<6;e++){let t=e<3?"_linear":"_angular";this._constraint.enableSpring(e,this[`${t}Spring${a[e]}`]),this._constraint.setDamping(e,this[`${t}Damping${a[e]}`]),this._constraint.setEquilibriumPoint(e,this[`${t}Equilibrium${a[e]}`]),this._constraint.setStiffness(e,this[`${t}Stiffness${a[e]}`]);}this._constraint.setBreakingImpulseThreshold(this._breakForce),this._updateLinearLimits(),this._updateAngularLimits(),this.system.app.systems.rigidbody.dynamicsWorld.addConstraint(this._constraint,!this._enableCollision);}}_destroyConstraint(){this._constraint&&(this.system.app.systems.rigidbody.dynamicsWorld.removeConstraint(this._constraint),Ammo.destroy(this._constraint),this._constraint=null);}initFromData(e){for(let t of bt)e.hasOwnProperty(t)&&(e[t]instanceof eN?this[`_${t}`].copy(e[t]):this[`_${t}`]=e[t]);this._createConstraint();}onEnable(){this._createConstraint();}onDisable(){this._destroyConstraint();}_onSetEnabled(e,t,i){}_onBeforeRemove(){this.fire("remove");}}let bs={Damping:"setDamping",Equilibrium:"setEquilibriumPoint",Spring:"enableSpring",Stiffness:"setStiffness"};["linear","angular"].forEach(e=>{["Damping","Equilibrium","Spring","Stiffness"].forEach(t=>{["X","Y","Z"].forEach(i=>{let s=e+t+i,r=`_${s}`,a=3*("linear"!==e);"Y"===i&&(a+=1),"Z"===i&&(a+=2),Object.defineProperty(bi.prototype,s,{get:function(){return this[r]},set:function(e){this[r]!==e&&(this[r]=e,this._constraint[bs[t]](a,e));}});});});});class br{constructor(){this.enabled=true;}}let ba=["enabled"];class bn extends Tm{constructor(e){super(e),this.id="joint",this.app=e,this.ComponentType=bi,this.DataType=br,this.schema=ba;}initializeComponentData(e,t,i){e.initFromData(t),super.initializeComponentData(e,t,ba);}}Tp._buildAccessors(bi.prototype,ba);class bo extends Tp{set minWidth(e){e!==this._minWidth&&(this._minWidth=e,this.fire("resize"));}get minWidth(){return this._minWidth}set minHeight(e){e!==this._minHeight&&(this._minHeight=e,this.fire("resize"));}get minHeight(){return this._minHeight}set maxWidth(e){e!==this._maxWidth&&(this._maxWidth=e,this.fire("resize"));}get maxWidth(){return this._maxWidth}set maxHeight(e){e!==this._maxHeight&&(this._maxHeight=e,this.fire("resize"));}get maxHeight(){return this._maxHeight}set fitWidthProportion(e){e!==this._fitWidthProportion&&(this._fitWidthProportion=e,this.fire("resize"));}get fitWidthProportion(){return this._fitWidthProportion}set fitHeightProportion(e){e!==this._fitHeightProportion&&(this._fitHeightProportion=e,this.fire("resize"));}get fitHeightProportion(){return this._fitHeightProportion}set excludeFromLayout(e){e!==this._excludeFromLayout&&(this._excludeFromLayout=e,this.fire("resize"));}get excludeFromLayout(){return this._excludeFromLayout}constructor(...e){super(...e),this._minWidth=0,this._minHeight=0,this._maxWidth=null,this._maxHeight=null,this._fitWidthProportion=0,this._fitHeightProportion=0,this._excludeFromLayout=false;}}class bl{constructor(){this.enabled=true;}}let bh=["enabled"];class bc extends Tm{constructor(e){super(e),this.id="layoutchild",this.ComponentType=bo,this.DataType=bl,this.schema=bh;}initializeComponentData(e,t,i){ void 0!==t.enabled&&(e.enabled=t.enabled),void 0!==t.minWidth&&(e.minWidth=t.minWidth),void 0!==t.minHeight&&(e.minHeight=t.minHeight),void 0!==t.maxWidth&&(e.maxWidth=t.maxWidth),void 0!==t.maxHeight&&(e.maxHeight=t.maxHeight),void 0!==t.fitWidthProportion&&(e.fitWidthProportion=t.fitWidthProportion),void 0!==t.fitHeightProportion&&(e.fitHeightProportion=t.fitHeightProportion),void 0!==t.excludeFromLayout&&(e.excludeFromLayout=t.excludeFromLayout),super.initializeComponentData(e,t,i);}cloneComponent(e,t){let i=e.layoutchild;return this.addComponent(t,{enabled:i.enabled,minWidth:i.minWidth,minHeight:i.minHeight,maxWidth:i.maxWidth,maxHeight:i.maxHeight,fitWidthProportion:i.fitWidthProportion,fitHeightProportion:i.fitHeightProportion,excludeFromLayout:i.excludeFromLayout})}}Tp._buildAccessors(bo.prototype,bh);let bd=0,bu=1,bf=2,bp=3,bm={};bm[pG]={axis:"x",size:"width",calculatedSize:"calculatedWidth",minSize:"minWidth",maxSize:"maxWidth",fitting:"widthFitting",fittingProportion:"fitWidthProportion"},bm[pH]={axis:"y",size:"height",calculatedSize:"calculatedHeight",minSize:"minHeight",maxSize:"maxHeight",fitting:"heightFitting",fittingProportion:"fitHeightProportion"};let b_={};b_[pG]=pH,b_[pH]=pG;let bg={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},bv={NONE:"NONE",APPLY_STRETCHING:"APPLY_STRETCHING",APPLY_SHRINKING:"APPLY_SHRINKING"},bS=new eN;function by(e){let t,i=bm[e],s=bm[b_[e]];function r(e,t){return -t[s.size]*e.pivot[s.axis]}function a(e){let t=e.entity.layoutchild;return !t||!t.enabled||!t.excludeFromLayout}function n(e,t,i){switch(e){case bd:return bv.NONE;case bu:if(t<i)return bv.APPLY_STRETCHING;return bv.NONE;case bf:if(t>=i)return bv.APPLY_SHRINKING;return bv.NONE;case bp:if(t<i)return bv.APPLY_STRETCHING;return bv.APPLY_SHRINKING;default:throw Error(`Unrecognized fitting mode: ${e}`)}}function o(e,i){return p(e,i.size)+(e.length-1)*t.spacing[i.axis]}function l(e,t,i){let s=_(e,i.maxSize),r=m(e,i.fittingProportion),a=S(r,s),n=bS[i.axis]-t;for(let t=0;t<e.length;++t){let o=s[t],l=c(o,n,r,a),h=e[o][i.size]+l,d=Math.min(h,e[o][i.maxSize]);e[o][i.size]=d,n-=l-Math.max(h-d,0);}}function h(e,t,i){let s=_(e,i.minSize,true),r=function(e){if(1===e.length)return [1];let t=[],i=e.length;for(let s=0;s<i;++s)t.push((1-e[s])/(i-1));return t}(m(e,i.fittingProportion)),a=S(r,s),n=t-bS[i.axis];for(let t=0;t<e.length;++t){let o=s[t],l=c(o,n,r,a),h=e[o][i.size]-l,d=Math.max(h,e[o][i.minSize]);e[o][i.size]=d,n-=l-Math.max(d-h,0);}}function c(e,t,i,s){let r=i[e],a=s[e];return 1e-5>Math.abs(r)&&1e-5>Math.abs(a)?t:t*r/a}function d(e){let t=[];for(let i=0;i<e.length;++i){let s=e[i],r=Math.max(u(s,"minWidth"),0),a=Math.max(u(s,"minHeight"),0),n=Math.max(u(s,"maxWidth"),r),o=Math.max(u(s,"maxHeight"),a),l=f(u(s,"width"),r,n),h=f(u(s,"height"),a,o),c=u(s,"fitWidthProportion"),d=u(s,"fitHeightProportion");t.push({minWidth:r,minHeight:a,maxWidth:n,maxHeight:o,width:l,height:h,fitWidthProportion:c,fitHeightProportion:d});}return t}function u(e,t){let i=e.entity.layoutchild;return i&&i.enabled&&void 0!==i[t]&&null!==i[t]?i[t]:void 0!==e[t]?e[t]:bg[t]}function f(e,t,i){return Math.min(Math.max(e,t),i)}function p(e,t){return e.reduce((e,i)=>e+i[t],0)}function m(e,t){let i=p(e,t),s=[],r=e.length;if(0===i)for(let e=0;e<r;++e)s.push(1/r);else for(let a=0;a<r;++a)s.push(e[a][t]/i);return s}function _(e,t,i){return e.forEach(g),e.slice().sort((e,s)=>i?s[t]-e[t]:e[t]-s[t]).map(v)}function g(e,t){e.index=t;}function v(e){return e.index}function S(e,t){let i=[];i[t[e.length-1]]=e[t[e.length-1]];for(let s=e.length-2;s>=0;--s)i[t[s]]=i[t[s+1]]+e[t[s]];return i}return function(e,c){e=e.filter(a),bS.x=(t=c).containerSize.x-t.padding.x-t.padding.z,bS.y=t.containerSize.y-t.padding.y-t.padding.w,function(e){for(let t=0;t<e.length;++t){let i=e[t],s=i.anchor;(0!==s.x||0!==s.y||0!==s.z||0!==s.w)&&(i.anchor=eF.ZERO);}}(e);let u=function(e){let i=t.orientation===pG&&t.reverseX||t.orientation===pH&&t.reverseY,s=t.orientation===pG&&t.reverseY||t.orientation===pH&&t.reverseX;if(i)for(let t=0;t<e.length;++t)i&&e[t].reverse();return s&&e.reverse(),e}(function(e){if(!t.wrap)return [e];let s=[[]],r=d(e),a=0,n=t[i.fitting]===bf;for(let o=0;o<e.length;++o){s[s.length-1].length>0&&(a+=t.spacing[i.axis]);let l=r[o][i.size];a+=l,!n&&a>bS[i.axis]&&0!==s[s.length-1].length&&(a=l,s.push([])),s[s.length-1].push(e[o]),n&&a>bS[i.axis]&&o!==e.length-1&&(a=0,s.push([]));}return s}(e)),f=function(e,i){let r=[],a=[];for(let t=0;t<e.length;++t){let n=e[t];n.largestElement=null,n.largestSize={width:Number.NEGATIVE_INFINITY,height:Number.NEGATIVE_INFINITY};for(let e=0;e<n.length;++e){let r=i[t][e];r[s.size]>n.largestSize[s.size]&&(n.largestElement=n[e],n.largestSize=r);}r.push(n.largestElement),a.push(n.largestSize);}let c=o(a,s),d=n(t[s.fitting],c,bS[s.axis]);d===bv.APPLY_STRETCHING?l(a,c,s):d===bv.APPLY_SHRINKING&&h(a,c,s);for(let r=0;r<e.length;++r){let a=e[r];for(let o=0;o<a.length;++o){let l=i[r][o],h=l[s.size],c=1===e.length?bS[s.axis]:a.largestSize[s.size],d=n(t[s.fitting],h,c);d===bv.APPLY_STRETCHING?l[s.size]=Math.min(c,l[s.maxSize]):d===bv.APPLY_SHRINKING&&(l[s.size]=Math.max(c,l[s.minSize]));}}return i}(u,function(e){let s=[];for(let r=0;r<e.length;++r){let a=d(e[r]),c=o(a,i),u=n(t[i.fitting],c,bS[i.axis]);u===bv.APPLY_STRETCHING?l(a,c,i):u===bv.APPLY_SHRINKING&&h(a,c,i),s.push(a);}return s}(u)),p=function(e,a){let n={};n[i.axis]=0,n[s.axis]=0,e[i.size]=Number.NEGATIVE_INFINITY;let o=[];for(let l=0;l<e.length;++l){let h=e[l];if(0===h.length){o.push([]);continue}let c=[],d=a[l];for(let e=0;e<h.length;++e){let a=h[e],o=d[e];n[s.axis]-=r(a,o),n[i.axis]-=-o[i.size]*a.pivot[i.axis],c[e]={},c[e][i.axis]=n[i.axis],c[e][s.axis]=n[s.axis],n[s.axis]+=r(a,o),n[i.axis]+=o[i.size]*(1-a.pivot[i.axis])+t.spacing[i.axis];}h[i.size]=n[i.axis]-t.spacing[i.axis],h[s.size]=h.largestSize[s.size],e[i.size]=Math.max(e[i.size],h[i.size]),n[i.axis]=0,n[s.axis]+=h[s.size]+t.spacing[s.axis],o.push(c);}return e[s.size]=n[s.axis]-t.spacing[s.axis],o}(u,f);return function(e,r,a){let n=t.alignment[i.axis],o=t.alignment[s.axis],l=t.padding[i.axis],h=t.padding[s.axis];for(let c=0;c<e.length;++c){let d=e[c],u=r[c],f=a[c],p=(bS[i.axis]-d[i.size])*n+l,m=(bS[s.axis]-e[s.size])*o+h;for(let e=0;e<d.length;++e){let r=(d[s.size]-u[e][s.size])*t.alignment[s.axis];f[e][i.axis]+=p,f[e][s.axis]+=m+r;}}}(u,f,p),function(e,r,a){for(let n=0;n<e.length;++n){let o=e[n],l=r[n],h=a[n];for(let e=0;e<o.length;++e){let r=o[e];r[i.calculatedSize]=l[e][i.size],r[s.calculatedSize]=l[e][s.size],t.orientation===pG?r.entity.setLocalPosition(h[e][i.axis],h[e][s.axis],r.entity.getLocalPosition().z):r.entity.setLocalPosition(h[e][s.axis],h[e][i.axis],r.entity.getLocalPosition().z);}}}(u,f,p),function(e){let i=e.width,s=e.height;return {bounds:new eF((bS.x-i)*t.alignment.x+t.padding.x,(bS.y-s)*t.alignment.y+t.padding.y,i,s)}}(u)}}let bx={};bx[pG]=by(pG),bx[pH]=by(pH);class bT{calculateLayout(e,t){let i=bx[t.orientation];if(i)return i(e,t);throw Error(`Unrecognized orientation value: ${t.orientation}`)}}function bE(e){return e.element}function bA(e){return e.enabled&&e.element&&e.element.enabled}class bb extends Tp{constructor(e,t){super(e,t),this._orientation=pG,this._reverseX=false,this._reverseY=true,this._alignment=new eN(0,1),this._padding=new eF,this._spacing=new eN,this._widthFitting=bd,this._heightFitting=bd,this._wrap=false,this._layoutCalculator=new bT,this._listenForReflowEvents(this.entity,"on"),this.entity.children.forEach(e=>{this._listenForReflowEvents(e,"on");}),this.entity.on("childinsert",this._onChildInsert,this),this.entity.on("childremove",this._onChildRemove,this),e.app.systems.element.on("add",this._onElementOrLayoutComponentAdd,this),e.app.systems.element.on("beforeremove",this._onElementOrLayoutComponentRemove,this),e.app.systems.layoutchild.on("add",this._onElementOrLayoutComponentAdd,this),e.app.systems.layoutchild.on("beforeremove",this._onElementOrLayoutComponentRemove,this);}set orientation(e){e!==this._orientation&&(this._orientation=e,this._scheduleReflow());}get orientation(){return this._orientation}set reverseX(e){e!==this._reverseX&&(this._reverseX=e,this._scheduleReflow());}get reverseX(){return this._reverseX}set reverseY(e){e!==this._reverseY&&(this._reverseY=e,this._scheduleReflow());}get reverseY(){return this._reverseY}set alignment(e){e.equals(this._alignment)||(this._alignment.copy(e),this._scheduleReflow());}get alignment(){return this._alignment}set padding(e){e.equals(this._padding)||(this._padding.copy(e),this._scheduleReflow());}get padding(){return this._padding}set spacing(e){e.equals(this._spacing)||(this._spacing.copy(e),this._scheduleReflow());}get spacing(){return this._spacing}set widthFitting(e){e!==this._widthFitting&&(this._widthFitting=e,this._scheduleReflow());}get widthFitting(){return this._widthFitting}set heightFitting(e){e!==this._heightFitting&&(this._heightFitting=e,this._scheduleReflow());}get heightFitting(){return this._heightFitting}set wrap(e){e!==this._wrap&&(this._wrap=e,this._scheduleReflow());}get wrap(){return this._wrap}_isSelfOrChild(e){return e===this.entity||-1!==this.entity.children.indexOf(e)}_listenForReflowEvents(e,t){e.element&&(e.element[t]("enableelement",this._scheduleReflow,this),e.element[t]("disableelement",this._scheduleReflow,this),e.element[t]("resize",this._scheduleReflow,this),e.element[t]("set:pivot",this._scheduleReflow,this)),e.layoutchild&&(e.layoutchild[t]("set_enabled",this._scheduleReflow,this),e.layoutchild[t]("resize",this._scheduleReflow,this));}_onElementOrLayoutComponentAdd(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"on"),this._scheduleReflow());}_onElementOrLayoutComponentRemove(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"off"),this._scheduleReflow());}_onChildInsert(e){this._listenForReflowEvents(e,"on"),this._scheduleReflow();}_onChildRemove(e){this._listenForReflowEvents(e,"off"),this._scheduleReflow();}_scheduleReflow(){this.enabled&&this.entity&&this.entity.enabled&&!this._isPerformingReflow&&this.system.scheduleReflow(this);}reflow(){let e=bE(this.entity),t=this.entity.children.filter(bA).map(bE);if(!e||0===t.length)return;let i=Math.max(e.calculatedWidth,0),s=Math.max(e.calculatedHeight,0),r={orientation:this._orientation,reverseX:this._reverseX,reverseY:this._reverseY,alignment:this._alignment,padding:this._padding,spacing:this._spacing,widthFitting:this._widthFitting,heightFitting:this._heightFitting,wrap:this._wrap,containerSize:new eN(i,s)};this._isPerformingReflow=true;let a=this._layoutCalculator.calculateLayout(t,r);this._isPerformingReflow=false,this.fire("reflow",a);}onEnable(){this._scheduleReflow();}onRemove(){this.entity.off("childinsert",this._onChildInsert,this),this.entity.off("childremove",this._onChildRemove,this),this._listenForReflowEvents(this.entity,"off"),this.entity.children.forEach(e=>{this._listenForReflowEvents(e,"off");}),this.system.app.systems.element.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.element.off("beforeremove",this._onElementOrLayoutComponentRemove,this),this.system.app.systems.layoutchild.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.layoutchild.off("beforeremove",this._onElementOrLayoutComponentRemove,this);}}class bw{constructor(){this.enabled=true;}}let bC=["enabled"];class bP extends Tm{constructor(e){super(e),this.id="layoutgroup",this.ComponentType=bb,this.DataType=bw,this.schema=bC,this._reflowQueue=[],this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("postUpdate",this._onPostUpdate,this);}initializeComponentData(e,t,i){ void 0!==t.enabled&&(e.enabled=t.enabled),void 0!==t.orientation&&(e.orientation=t.orientation),void 0!==t.reverseX&&(e.reverseX=t.reverseX),void 0!==t.reverseY&&(e.reverseY=t.reverseY),void 0!==t.alignment&&(e.alignment=Array.isArray(t.alignment)?new eN(t.alignment):t.alignment),void 0!==t.padding&&(e.padding=Array.isArray(t.padding)?new eF(t.padding):t.padding),void 0!==t.spacing&&(e.spacing=Array.isArray(t.spacing)?new eN(t.spacing):t.spacing),void 0!==t.widthFitting&&(e.widthFitting=t.widthFitting),void 0!==t.heightFitting&&(e.heightFitting=t.heightFitting),void 0!==t.wrap&&(e.wrap=t.wrap),super.initializeComponentData(e,t,i);}cloneComponent(e,t){let i=e.layoutgroup;return this.addComponent(t,{enabled:i.enabled,orientation:i.orientation,reverseX:i.reverseX,reverseY:i.reverseY,alignment:i.alignment,padding:i.padding,spacing:i.spacing,widthFitting:i.widthFitting,heightFitting:i.heightFitting,wrap:i.wrap})}scheduleReflow(e){ -1===this._reflowQueue.indexOf(e)&&this._reflowQueue.push(e);}_onPostUpdate(){this._processReflowQueue();}_processReflowQueue(){if(0===this._reflowQueue.length)return;let e=0;for(;this._reflowQueue.length>0;){let t=this._reflowQueue.slice();this._reflowQueue.length=0,t.sort((e,t)=>e.entity.graphDepth-t.entity.graphDepth);for(let e=0;e<t.length;++e)t[e].reflow();if(++e>=100)break}}_onRemoveComponent(e,t){t.onRemove();}destroy(){super.destroy(),this.app.systems.off("postUpdate",this._onPostUpdate,this);}}Tp._buildAccessors(bb.prototype,bC);class bL{destroy(e){this.map.forEach(e=>e.mesh.destroy());}constructor(){this.map=new Map;}}let bI=new ne,bD=(e,t)=>{let i=bI.get(e,()=>new bL),s=i.map.get(t);if(!s){let r,a;switch(t){case "box":r=mw.fromGeometry(e,new vJ),a={x:2,y:2,z:2,uv:2/3};break;case "capsule":r=mw.fromGeometry(e,new yy({radius:.5,height:2})),a={x:2*Math.PI,y:Math.PI,z:2*Math.PI,uv:1/3+1/3/3*2};break;case "cone":r=mw.fromGeometry(e,new yx({baseRadius:.5,peakRadius:0,height:1})),a={x:2.54,y:2.54,z:2.54,uv:1/3+1/3/3};break;case "cylinder":r=mw.fromGeometry(e,new yT({radius:.5,height:1})),a={x:Math.PI,y:1.58,z:Math.PI,uv:1/3+1/3/3*2};break;case "plane":r=mw.fromGeometry(e,new yE({halfExtents:new eN(.5,.5),widthSegments:1,lengthSegments:1})),a={x:0,y:1,z:0,uv:1};break;case "sphere":r=mw.fromGeometry(e,new v0({radius:.5})),a={x:Math.PI,y:Math.PI,z:Math.PI,uv:1};break;case "torus":r=mw.fromGeometry(e,new yA({tubeRadius:.2,ringRadius:.3})),a={x:.5*Math.PI*.5-.1*Math.PI*.1,y:.4,z:.4,uv:1};break;default:throw Error(`Invalid primitive type: ${t}`)}r.incRefCount(),s={mesh:r,area:a},i.map.set(t,s);}return s};class bR extends Tp{constructor(e,t){super(e,t),this._type="asset",this._asset=null,this._model=null,this._mapping={},this._castShadows=true,this._receiveShadows=true,this._materialAsset=null,this._castShadowsLightmap=true,this._lightmapped=false,this._lightmapSizeMultiplier=1,this.isStatic=false,this._layers=[ub],this._batchGroupId=-1,this._customAabb=null,this._area=null,this._materialEvents=null,this._clonedModel=false,this._evtLayersChanged=null,this._evtLayerAdded=null,this._evtLayerRemoved=null,this._material=e.defaultMaterial,t.on("remove",this.onRemoveChild,this),t.on("removehierarchy",this.onRemoveChild,this),t.on("insert",this.onInsertChild,this),t.on("inserthierarchy",this.onInsertChild,this);}set meshInstances(e){this._model&&(this._model.meshInstances=e);}get meshInstances(){return this._model?this._model.meshInstances:null}set customAabb(e){if(this._customAabb=e,this._model){let e=this._model.meshInstances;if(e)for(let t=0;t<e.length;t++)e[t].setCustomAabb(this._customAabb);}}get customAabb(){return this._customAabb}set type(e){if(this._type!==e)if(this._area=null,this._type=e,"asset"===e)null!==this._asset?this._bindModelAsset(this._asset):this.model=null;else {let t=bD(this.system.app.graphicsDevice,e);this._area=t.area;let i=t.mesh,s=new _c,r=new g5;r.graph=s,r.meshInstances=[new mV(i,this._material,s)],this.model=r,this._asset=null;}}get type(){return this._type}set asset(e){let t=this.system.app.assets,i=e;if(e instanceof xF&&(i=e.id),this._asset!==i){if(this._asset){t.off(`add:${this._asset}`,this._onModelAssetAdded,this);let e=t.get(this._asset);e&&this._unbindModelAsset(e);}if(this._asset=i,this._asset){let e=t.get(this._asset);e?this._bindModelAsset(e):(this.model=null,t.on(`add:${this._asset}`,this._onModelAssetAdded,this));}else this.model=null;}}get asset(){return this._asset}set model(e){if(this._model!==e&&(!e||!e._immutable)&&(this._model&&(this._model._immutable=false,this.removeModelFromLayers(),this._model.getGraph().destroy(),delete this._model._entity,this._clonedModel&&(this._model.destroy(),this._clonedModel=false)),this._model=e,this._model)){this._model._immutable=true;let e=this._model.meshInstances;for(let t=0;t<e.length;t++)e[t].castShadow=this._castShadows,e[t].receiveShadow=this._receiveShadows,e[t].setCustomAabb(this._customAabb);this.lightmapped=this._lightmapped,this.entity.addChild(this._model.graph),this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._model._entity=this.entity,this.entity.animation&&this.entity.animation.setModel(this._model),this.entity.anim&&this.entity.anim.rebind(),"asset"===this.type?this.mapping=this._mapping:this._unsetMaterialEvents();}}get model(){return this._model}set lightmapped(e){if(e!==this._lightmapped&&(this._lightmapped=e,this._model)){let t=this._model.meshInstances;for(let i=0;i<t.length;i++)t[i].setLightmapped(e);}}get lightmapped(){return this._lightmapped}set castShadows(e){if(this._castShadows===e)return;let t=this._model;if(t){let i=this.layers,s=this.system.app.scene;if(this._castShadows&&!e)for(let e=0;e<i.length;e++){let i=this.system.app.scene.layers.getLayerById(this.layers[e]);i&&i.removeShadowCasters(t.meshInstances);}let r=t.meshInstances;for(let t=0;t<r.length;t++)r[t].castShadow=e;if(!this._castShadows&&e)for(let e=0;e<i.length;e++){let r=s.layers.getLayerById(i[e]);r&&r.addShadowCasters(t.meshInstances);}}this._castShadows=e;}get castShadows(){return this._castShadows}set receiveShadows(e){if(this._receiveShadows!==e&&(this._receiveShadows=e,this._model)){let t=this._model.meshInstances;for(let i=0,s=t.length;i<s;i++)t[i].receiveShadow=e;}}get receiveShadows(){return this._receiveShadows}set castShadowsLightmap(e){this._castShadowsLightmap=e;}get castShadowsLightmap(){return this._castShadowsLightmap}set lightmapSizeMultiplier(e){this._lightmapSizeMultiplier=e;}get lightmapSizeMultiplier(){return this._lightmapSizeMultiplier}set layers(e){let t=this.system.app.scene.layers;if(this.meshInstances)for(let e=0;e<this._layers.length;e++){let i=t.getLayerById(this._layers[e]);i&&i.removeMeshInstances(this.meshInstances);}this._layers.length=0;for(let t=0;t<e.length;t++)this._layers[t]=e[t];if(this.enabled&&this.entity.enabled&&this.meshInstances)for(let e=0;e<this._layers.length;e++){let i=t.getLayerById(this._layers[e]);i&&i.addMeshInstances(this.meshInstances);}}get layers(){return this._layers}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher?.remove(mS.MODEL,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(mS.MODEL,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._batchGroupId=e);}get batchGroupId(){return this._batchGroupId}set materialAsset(e){let t=e;e instanceof xF&&(t=e.id);let i=this.system.app.assets;if(t!==this._materialAsset){if(this._materialAsset){i.off(`add:${this._materialAsset}`,this._onMaterialAssetAdd,this);let e=i.get(this._materialAsset);e&&this._unbindMaterialAsset(e);}if(this._materialAsset=t,this._materialAsset){let e=i.get(this._materialAsset);e?this._bindMaterialAsset(e):(this._setMaterial(this.system.defaultMaterial),i.on(`add:${this._materialAsset}`,this._onMaterialAssetAdd,this));}else this._setMaterial(this.system.defaultMaterial);}}get materialAsset(){return this._materialAsset}set material(e){this._material!==e&&(this.materialAsset=null,this._setMaterial(e));}get material(){return this._material}set mapping(e){if("asset"!==this._type||(this._unsetMaterialEvents(),e||(e={}),this._mapping=e,!this._model))return;let t=this._model.meshInstances,i=this.asset?this.system.app.assets.get(this.asset):null,s=i?i.data.mapping:null,r=null;for(let i=0,a=t.length;i<a;i++)if(void 0!==e[i])e[i]?(r=this.system.app.assets.get(e[i]),this._loadAndSetMeshInstanceMaterial(r,t[i],i)):t[i].material=this.system.defaultMaterial;else if(s)if(s[i]&&(s[i].material||s[i].path)){if(void 0!==s[i].material)r=this.system.app.assets.get(s[i].material);else if(void 0!==s[i].path){let e=this._getMaterialAssetUrl(s[i].path);e&&(r=this.system.app.assets.getByUrl(e));}this._loadAndSetMeshInstanceMaterial(r,t[i],i);}else t[i].material=this.system.defaultMaterial;}get mapping(){return this._mapping}addModelToLayers(){let e=this.system.app.scene.layers;for(let t=0;t<this._layers.length;t++){let i=e.getLayerById(this._layers[t]);i&&i.addMeshInstances(this.meshInstances);}}removeModelFromLayers(){let e=this.system.app.scene.layers;for(let t=0;t<this._layers.length;t++){let i=e.getLayerById(this._layers[t]);i&&i.removeMeshInstances(this.meshInstances);}}onRemoveChild(){this._model&&this.removeModelFromLayers();}onInsertChild(){this._model&&this.enabled&&this.entity.enabled&&this.addModelToLayers();}onRemove(){this.asset=null,this.model=null,this.materialAsset=null,this._unsetMaterialEvents(),this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this);}onLayersChanged(e,t){this.addModelToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this);}onLayerAdded(e){0>this.layers.indexOf(e.id)||e.addMeshInstances(this.meshInstances);}onLayerRemoved(e){0>this.layers.indexOf(e.id)||e.removeMeshInstances(this.meshInstances);}_setMaterialEvent(e,t,i,s){let r=`${t}:${i}`;this.system.app.assets.on(r,s,this),this._materialEvents||(this._materialEvents=[]),this._materialEvents[e]||(this._materialEvents[e]={}),this._materialEvents[e][r]={id:i,handler:s};}_unsetMaterialEvents(){let e=this.system.app.assets,t=this._materialEvents;if(t){for(let i=0,s=t.length;i<s;i++){if(!t[i])continue;let s=t[i];for(let t in s)e.off(t,s[t].handler,this);}this._materialEvents=null;}}_getAssetByIdOrPath(e){let t=null;if(isNaN(parseInt(e,10))){if(this.asset){let i=this._getMaterialAssetUrl(e);i&&(t=this.system.app.assets.getByUrl(i));}}else t=this.system.app.assets.get(e);return t}_getMaterialAssetUrl(e){if(!this.asset)return null;let t=this.system.app.assets.get(this.asset);return t?t.getAbsoluteUrl(e):null}_loadAndSetMeshInstanceMaterial(e,t,i){let s=this.system.app.assets;e&&(e.resource?(t.material=e.resource,this._setMaterialEvent(i,"remove",e.id,function(){t.material=this.system.defaultMaterial;})):(this._setMaterialEvent(i,"load",e.id,function(s){t.material=s.resource,this._setMaterialEvent(i,"remove",e.id,function(){t.material=this.system.defaultMaterial;});}),this.enabled&&this.entity.enabled&&s.load(e)));}onEnable(){let e,t=this.system.app,i=t.scene,s=i?.layers;this._evtLayersChanged=i.on("set:layers",this.onLayersChanged,this),s&&(this._evtLayerAdded=s.on("add",this.onLayerAdded,this),this._evtLayerRemoved=s.on("remove",this.onLayerRemoved,this));let r="asset"===this._type;if(this._model?this.addModelToLayers():r&&this._asset&&(e=t.assets.get(this._asset))&&e.resource!==this._model&&this._bindModelAsset(e),this._materialAsset&&(e=t.assets.get(this._materialAsset))&&e.resource!==this._material&&this._bindMaterialAsset(e),r&&this._mapping)for(let i in this._mapping)this._mapping[i]&&(e=this._getAssetByIdOrPath(this._mapping[i]))&&!e.resource&&t.assets.load(e);this._batchGroupId>=0&&t.batcher?.insert(mS.MODEL,this.batchGroupId,this.entity);}onDisable(){let e=this.system.app,t=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&e.batcher?.remove(mS.MODEL,this.batchGroupId,this.entity),this._model&&this.removeModelFromLayers();}hide(){if(this._model){let e=this._model.meshInstances;for(let t=0,i=e.length;t<i;t++)e[t].visible=false;}}show(){if(this._model){let e=this._model.meshInstances;for(let t=0,i=e.length;t<i;t++)e[t].visible=true;}}_bindMaterialAsset(e){if(e.on("load",this._onMaterialAssetLoad,this),e.on("unload",this._onMaterialAssetUnload,this),e.on("remove",this._onMaterialAssetRemove,this),e.on("change",this._onMaterialAssetChange,this),e.resource)this._onMaterialAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}}_unbindMaterialAsset(e){e.off("load",this._onMaterialAssetLoad,this),e.off("unload",this._onMaterialAssetUnload,this),e.off("remove",this._onMaterialAssetRemove,this),e.off("change",this._onMaterialAssetChange,this);}_onMaterialAssetAdd(e){this.system.app.assets.off(`add:${e.id}`,this._onMaterialAssetAdd,this),this._materialAsset===e.id&&this._bindMaterialAsset(e);}_onMaterialAssetLoad(e){this._setMaterial(e.resource);}_onMaterialAssetUnload(e){this._setMaterial(this.system.defaultMaterial);}_onMaterialAssetRemove(e){this._onMaterialAssetUnload(e);}_onMaterialAssetChange(e){}_bindModelAsset(e){if(this._unbindModelAsset(e),e.on("load",this._onModelAssetLoad,this),e.on("unload",this._onModelAssetUnload,this),e.on("change",this._onModelAssetChange,this),e.on("remove",this._onModelAssetRemove,this),e.resource)this._onModelAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}}_unbindModelAsset(e){e.off("load",this._onModelAssetLoad,this),e.off("unload",this._onModelAssetUnload,this),e.off("change",this._onModelAssetChange,this),e.off("remove",this._onModelAssetRemove,this);}_onModelAssetAdded(e){this.system.app.assets.off(`add:${e.id}`,this._onModelAssetAdded,this),e.id===this._asset&&this._bindModelAsset(e);}_onModelAssetLoad(e){this.model=e.resource.clone(),this._clonedModel=true;}_onModelAssetUnload(e){this.model=null;}_onModelAssetChange(e,t,i,s){"data"===t&&(this.mapping=this._mapping);}_onModelAssetRemove(e){this.model=null;}_setMaterial(e){if(this._material===e)return;this._material=e;let t=this._model;if(t&&"asset"!==this._type){let i=t.meshInstances;for(let t=0,s=i.length;t<s;t++)i[t].material=e;}}}class bM{constructor(){this.enabled=true;}}let bO=["enabled"];class bN extends Tm{constructor(e){super(e),this.id="model",this.ComponentType=bR,this.DataType=bM,this.schema=bO,this.defaultMaterial=mP(e.graphicsDevice),this.on("beforeremove",this.onRemove,this);}initializeComponentData(e,t,i){i=["material","materialAsset","asset","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","type","mapping","layers","isStatic","batchGroupId"],(null===t.batchGroupId||void 0===t.batchGroupId)&&(t.batchGroupId=-1),t.layers&&t.layers.length&&(t.layers=t.layers.slice(0));for(let s=0;s<i.length;s++)t.hasOwnProperty(i[s])&&(e[i[s]]=t[i[s]]);t.aabbCenter&&t.aabbHalfExtents&&(e.customAabb=new ej(new eM(t.aabbCenter),new eM(t.aabbHalfExtents))),super.initializeComponentData(e,t,["enabled"]);}cloneComponent(e,t){let i={type:e.model.type,asset:e.model.asset,castShadows:e.model.castShadows,receiveShadows:e.model.receiveShadows,castShadowsLightmap:e.model.castShadowsLightmap,lightmapped:e.model.lightmapped,lightmapSizeMultiplier:e.model.lightmapSizeMultiplier,isStatic:e.model.isStatic,enabled:e.model.enabled,layers:e.model.layers,batchGroupId:e.model.batchGroupId,mapping:G({},e.model.mapping)},s=e.model.materialAsset;s instanceof xF||null==s||(s=this.app.assets.get(s));let r=e.model.material;r&&r!==this.defaultMaterial&&s&&r!==s.resource||(i.materialAsset=s);let a=this.addComponent(t,i);if(e.model.model&&"asset"===e.model.type&&!e.model.asset&&(a.model=e.model.model.clone(),a._clonedModel=true),i.materialAsset||(a.material=r),e.model.model){let t=e.model.model.meshInstances,i=a.model.meshInstances;for(let e=0;e<t.length;e++)i[e].mask=t[e].mask,i[e].material=t[e].material,i[e].layer=t[e].layer,i[e].receiveShadow=t[e].receiveShadow;}return e.model.customAabb&&(a.customAabb=e.model.customAabb.clone()),a}onRemove(e,t){t.onRemove();}}Tp._buildAccessors(bR.prototype,bO);let bF=["emitterExtents","emitterRadius","emitterExtentsInner","emitterRadiusInner","loop","initialVelocity","animSpeed","normalMap","particleNormal"],bB=["numParticles","lifetime","rate","rate2","startAngle","startAngle2","lighting","halfLambert","intensity","wrap","wrapBounds","depthWrite","noFog","sort","stretch","alignToMotion","preWarm","emitterShape","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animLoop","colorMap","localSpace","screenSpace","orientation"],bU=["scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","velocityGraph","velocityGraph2","localVelocityGraph","localVelocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2"],bk=["colorMapAsset","normalMapAsset","meshAsset","renderAsset"];class bV extends Tp{constructor(e,t){super(e,t),this._requestedDepth=false,this._drawOrder=0,this._evtLayersChanged=null,this._evtLayerAdded=null,this._evtLayerRemoved=null,this._evtSetMeshes=null,this.on("set_colorMapAsset",this.onSetColorMapAsset,this),this.on("set_normalMapAsset",this.onSetNormalMapAsset,this),this.on("set_meshAsset",this.onSetMeshAsset,this),this.on("set_mesh",this.onSetMesh,this),this.on("set_renderAsset",this.onSetRenderAsset,this),this.on("set_loop",this.onSetLoop,this),this.on("set_blendType",this.onSetBlendType,this),this.on("set_depthSoftening",this.onSetDepthSoftening,this),this.on("set_layers",this.onSetLayers,this),bF.forEach(e=>{this.on(`set_${e}`,this.onSetSimpleProperty,this);}),bB.forEach(e=>{this.on(`set_${e}`,this.onSetComplexProperty,this);}),bU.forEach(e=>{this.on(`set_${e}`,this.onSetGraphProperty,this);});}get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){this._setValue("enabled",e);}get enabled(){return this.data.enabled}set autoPlay(e){this._setValue("autoPlay",e);}get autoPlay(){return this.data.autoPlay}set numParticles(e){this._setValue("numParticles",e);}get numParticles(){return this.data.numParticles}set lifetime(e){this._setValue("lifetime",e);}get lifetime(){return this.data.lifetime}set rate(e){this._setValue("rate",e);}get rate(){return this.data.rate}set rate2(e){this._setValue("rate2",e);}get rate2(){return this.data.rate2}set startAngle(e){this._setValue("startAngle",e);}get startAngle(){return this.data.startAngle}set startAngle2(e){this._setValue("startAngle2",e);}get startAngle2(){return this.data.startAngle2}set loop(e){this._setValue("loop",e);}get loop(){return this.data.loop}set preWarm(e){this._setValue("preWarm",e);}get preWarm(){return this.data.preWarm}set lighting(e){this._setValue("lighting",e);}get lighting(){return this.data.lighting}set halfLambert(e){this._setValue("halfLambert",e);}get halfLambert(){return this.data.halfLambert}set intensity(e){this._setValue("intensity",e);}get intensity(){return this.data.intensity}set depthWrite(e){this._setValue("depthWrite",e);}get depthWrite(){return this.data.depthWrite}set noFog(e){this._setValue("noFog",e);}get noFog(){return this.data.noFog}set depthSoftening(e){this._setValue("depthSoftening",e);}get depthSoftening(){return this.data.depthSoftening}set sort(e){this._setValue("sort",e);}get sort(){return this.data.sort}set blendType(e){this._setValue("blendType",e);}get blendType(){return this.data.blendType}set stretch(e){this._setValue("stretch",e);}get stretch(){return this.data.stretch}set alignToMotion(e){this._setValue("alignToMotion",e);}get alignToMotion(){return this.data.alignToMotion}set emitterShape(e){this._setValue("emitterShape",e);}get emitterShape(){return this.data.emitterShape}set emitterExtents(e){this._setValue("emitterExtents",e);}get emitterExtents(){return this.data.emitterExtents}set emitterExtentsInner(e){this._setValue("emitterExtentsInner",e);}get emitterExtentsInner(){return this.data.emitterExtentsInner}set emitterRadius(e){this._setValue("emitterRadius",e);}get emitterRadius(){return this.data.emitterRadius}set emitterRadiusInner(e){this._setValue("emitterRadiusInner",e);}get emitterRadiusInner(){return this.data.emitterRadiusInner}set initialVelocity(e){this._setValue("initialVelocity",e);}get initialVelocity(){return this.data.initialVelocity}set wrap(e){this._setValue("wrap",e);}get wrap(){return this.data.wrap}set wrapBounds(e){this._setValue("wrapBounds",e);}get wrapBounds(){return this.data.wrapBounds}set localSpace(e){this._setValue("localSpace",e);}get localSpace(){return this.data.localSpace}set screenSpace(e){this._setValue("screenSpace",e);}get screenSpace(){return this.data.screenSpace}set colorMapAsset(e){this._setValue("colorMapAsset",e);}get colorMapAsset(){return this.data.colorMapAsset}set normalMapAsset(e){this._setValue("normalMapAsset",e);}get normalMapAsset(){return this.data.normalMapAsset}set mesh(e){this._setValue("mesh",e);}get mesh(){return this.data.mesh}set meshAsset(e){this._setValue("meshAsset",e);}get meshAsset(){return this.data.meshAsset}set renderAsset(e){this._setValue("renderAsset",e);}get renderAsset(){return this.data.renderAsset}set orientation(e){this._setValue("orientation",e);}get orientation(){return this.data.orientation}set particleNormal(e){this._setValue("particleNormal",e);}get particleNormal(){return this.data.particleNormal}set localVelocityGraph(e){this._setValue("localVelocityGraph",e);}get localVelocityGraph(){return this.data.localVelocityGraph}set localVelocityGraph2(e){this._setValue("localVelocityGraph2",e);}get localVelocityGraph2(){return this.data.localVelocityGraph2}set velocityGraph(e){this._setValue("velocityGraph",e);}get velocityGraph(){return this.data.velocityGraph}set velocityGraph2(e){this._setValue("velocityGraph2",e);}get velocityGraph2(){return this.data.velocityGraph2}set rotationSpeedGraph(e){this._setValue("rotationSpeedGraph",e);}get rotationSpeedGraph(){return this.data.rotationSpeedGraph}set rotationSpeedGraph2(e){this._setValue("rotationSpeedGraph2",e);}get rotationSpeedGraph2(){return this.data.rotationSpeedGraph2}set radialSpeedGraph(e){this._setValue("radialSpeedGraph",e);}get radialSpeedGraph(){return this.data.radialSpeedGraph}set radialSpeedGraph2(e){this._setValue("radialSpeedGraph2",e);}get radialSpeedGraph2(){return this.data.radialSpeedGraph2}set scaleGraph(e){this._setValue("scaleGraph",e);}get scaleGraph(){return this.data.scaleGraph}set scaleGraph2(e){this._setValue("scaleGraph2",e);}get scaleGraph2(){return this.data.scaleGraph2}set colorGraph(e){this._setValue("colorGraph",e);}get colorGraph(){return this.data.colorGraph}set colorGraph2(e){this._setValue("colorGraph2",e);}get colorGraph2(){return this.data.colorGraph2}set alphaGraph(e){this._setValue("alphaGraph",e);}get alphaGraph(){return this.data.alphaGraph}set alphaGraph2(e){this._setValue("alphaGraph2",e);}get alphaGraph2(){return this.data.alphaGraph2}set colorMap(e){this._setValue("colorMap",e);}get colorMap(){return this.data.colorMap}set normalMap(e){this._setValue("normalMap",e);}get normalMap(){return this.data.normalMap}set animTilesX(e){this._setValue("animTilesX",e);}get animTilesX(){return this.data.animTilesX}set animTilesY(e){this._setValue("animTilesY",e);}get animTilesY(){return this.data.animTilesY}set animStartFrame(e){this._setValue("animStartFrame",e);}get animStartFrame(){return this.data.animStartFrame}set animNumFrames(e){this._setValue("animNumFrames",e);}get animNumFrames(){return this.data.animNumFrames}set animNumAnimations(e){this._setValue("animNumAnimations",e);}get animNumAnimations(){return this.data.animNumAnimations}set animIndex(e){this._setValue("animIndex",e);}get animIndex(){return this.data.animIndex}set randomizeAnimIndex(e){this._setValue("randomizeAnimIndex",e);}get randomizeAnimIndex(){return this.data.randomizeAnimIndex}set animSpeed(e){this._setValue("animSpeed",e);}get animSpeed(){return this.data.animSpeed}set animLoop(e){this._setValue("animLoop",e);}get animLoop(){return this.data.animLoop}set layers(e){this._setValue("layers",e);}get layers(){return this.data.layers}set drawOrder(e){this._drawOrder=e,this.emitter&&(this.emitter.drawOrder=e);}get drawOrder(){return this._drawOrder}_setValue(e,t){let i=this.data,s=i[e];i[e]=t,this.fire("set",e,s,t);}addMeshInstanceToLayers(){if(this.emitter)for(let e=0;e<this.layers.length;e++){let t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&(t.addMeshInstances([this.emitter.meshInstance]),this.emitter._layer=t);}}removeMeshInstanceFromLayers(){if(this.emitter)for(let e=0;e<this.layers.length;e++){let t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.removeMeshInstances([this.emitter.meshInstance]);}}onSetLayers(e,t,i){if(this.emitter){for(let e=0;e<t.length;e++){let i=this.system.app.scene.layers.getLayerById(t[e]);i&&i.removeMeshInstances([this.emitter.meshInstance]);}if(this.enabled&&this.entity.enabled)for(let e=0;e<i.length;e++){let t=this.system.app.scene.layers.getLayerById(i[e]);t&&t.addMeshInstances([this.emitter.meshInstance]);}}}onLayersChanged(e,t){this.addMeshInstanceToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this);}onLayerAdded(e){this.emitter&&(0>this.layers.indexOf(e.id)||e.addMeshInstances([this.emitter.meshInstance]));}onLayerRemoved(e){this.emitter&&(0>this.layers.indexOf(e.id)||e.removeMeshInstances([this.emitter.meshInstance]));}_bindColorMapAsset(e){if(e.on("load",this._onColorMapAssetLoad,this),e.on("unload",this._onColorMapAssetUnload,this),e.on("remove",this._onColorMapAssetRemove,this),e.on("change",this._onColorMapAssetChange,this),e.resource)this._onColorMapAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}}_unbindColorMapAsset(e){e.off("load",this._onColorMapAssetLoad,this),e.off("unload",this._onColorMapAssetUnload,this),e.off("remove",this._onColorMapAssetRemove,this),e.off("change",this._onColorMapAssetChange,this);}_onColorMapAssetLoad(e){this.colorMap=e.resource;}_onColorMapAssetUnload(e){this.colorMap=null;}_onColorMapAssetRemove(e){this._onColorMapAssetUnload(e);}_onColorMapAssetChange(e){}onSetColorMapAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&this._unbindColorMapAsset(e);}if(i){i instanceof xF&&(this.data.colorMapAsset=i.id,i=i.id);let e=s.get(i);e?this._bindColorMapAsset(e):s.once(`add:${i}`,e=>{this._bindColorMapAsset(e);});}else this.colorMap=null;}_bindNormalMapAsset(e){if(e.on("load",this._onNormalMapAssetLoad,this),e.on("unload",this._onNormalMapAssetUnload,this),e.on("remove",this._onNormalMapAssetRemove,this),e.on("change",this._onNormalMapAssetChange,this),e.resource)this._onNormalMapAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}}_unbindNormalMapAsset(e){e.off("load",this._onNormalMapAssetLoad,this),e.off("unload",this._onNormalMapAssetUnload,this),e.off("remove",this._onNormalMapAssetRemove,this),e.off("change",this._onNormalMapAssetChange,this);}_onNormalMapAssetLoad(e){this.normalMap=e.resource;}_onNormalMapAssetUnload(e){this.normalMap=null;}_onNormalMapAssetRemove(e){this._onNormalMapAssetUnload(e);}_onNormalMapAssetChange(e){}onSetNormalMapAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&this._unbindNormalMapAsset(e);}if(i){i instanceof xF&&(this.data.normalMapAsset=i.id,i=i.id);let e=s.get(i);e?this._bindNormalMapAsset(e):s.once(`add:${i}`,e=>{this._bindNormalMapAsset(e);});}else this.normalMap=null;}_bindMeshAsset(e){if(e.on("load",this._onMeshAssetLoad,this),e.on("unload",this._onMeshAssetUnload,this),e.on("remove",this._onMeshAssetRemove,this),e.on("change",this._onMeshAssetChange,this),e.resource)this._onMeshAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}}_unbindMeshAsset(e){e.off("load",this._onMeshAssetLoad,this),e.off("unload",this._onMeshAssetUnload,this),e.off("remove",this._onMeshAssetRemove,this),e.off("change",this._onMeshAssetChange,this);}_onMeshAssetLoad(e){this._onMeshChanged(e.resource);}_onMeshAssetUnload(e){this.mesh=null;}_onMeshAssetRemove(e){this._onMeshAssetUnload(e);}_onMeshAssetChange(e){}onSetMeshAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&this._unbindMeshAsset(e);}if(i){i instanceof xF&&(this.data.meshAsset=i.id,i=i.id);let e=s.get(i);e&&this._bindMeshAsset(e);}else this._onMeshChanged(null);}onSetMesh(e,t,i){!i||i instanceof xF||"number"==typeof i?this.meshAsset=i:this._onMeshChanged(i);}_onMeshChanged(e){!e||e instanceof mw||(e=e.meshInstances[0]?e.meshInstances[0].mesh:null),this.data.mesh=e,this.emitter&&(this.emitter.mesh=e,this.emitter.resetMaterial(),this.rebuild());}onSetRenderAsset(e,t,i){let s=this.system.app.assets;if(t){let e=s.get(t);e&&this._unbindRenderAsset(e);}if(i){i instanceof xF&&(this.data.renderAsset=i.id,i=i.id);let e=s.get(i);e&&this._bindRenderAsset(e);}else this._onRenderChanged(null);}_bindRenderAsset(e){if(e.on("load",this._onRenderAssetLoad,this),e.on("unload",this._onRenderAssetUnload,this),e.on("remove",this._onRenderAssetRemove,this),e.resource)this._onRenderAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}}_unbindRenderAsset(e){e.off("load",this._onRenderAssetLoad,this),e.off("unload",this._onRenderAssetUnload,this),e.off("remove",this._onRenderAssetRemove,this),this._evtSetMeshes?.off(),this._evtSetMeshes=null;}_onRenderAssetLoad(e){this._onRenderChanged(e.resource);}_onRenderAssetUnload(e){this._onRenderChanged(null);}_onRenderAssetRemove(e){this._onRenderAssetUnload(e);}_onRenderChanged(e){if(!e)return void this._onMeshChanged(null);this._evtSetMeshes?.off(),this._evtSetMeshes=e.on("set:meshes",this._onRenderSetMeshes,this),e.meshes&&this._onRenderSetMeshes(e.meshes);}_onRenderSetMeshes(e){this._onMeshChanged(e&&e[0]);}onSetLoop(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetTime());}onSetBlendType(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.material.blendType=i,this.emitter.resetMaterial(),this.rebuild());}_requestDepth(){!this._requestedDepth&&(o||(o=this.system.app.scene.layers.getLayerById(uw)),o&&(o.incrementCounter(),this._requestedDepth=true));}_releaseDepth(){this._requestedDepth&&o&&(o.decrementCounter(),this._requestedDepth=false);}onSetDepthSoftening(e,t,i){t!==i&&(i?this.enabled&&this.entity.enabled&&this._requestDepth():this.enabled&&this.entity.enabled&&this._releaseDepth(),this.emitter&&(this.emitter[e]=i),this.emitter&&(this.reset(),this.emitter.resetMaterial(),this.rebuild()));}onSetSimpleProperty(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial());}onSetComplexProperty(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial(),this.rebuild(),this.reset());}onSetGraphProperty(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.rebuildGraphs(),this.emitter.resetMaterial());}onEnable(){let e=this.system.app.scene,t=e.layers,i=this.data;for(let e=0,t=bk.length;e<t;e++){let t=i[bk[e]];if(t){if(!(t instanceof xF)){if(!(parseInt(t,10)>=0))continue;t=this.system.app.assets.get(t);}t&&!t.resource&&this.system.app.assets.load(t);}}if(!this.system.app.graphicsDevice.disableParticleSystem){if(!this.emitter){let e=i.mesh;e instanceof mw||(e=null),this.emitter=new vW(this.system.app.graphicsDevice,{numParticles:i.numParticles,emitterExtents:i.emitterExtents,emitterExtentsInner:i.emitterExtentsInner,emitterRadius:i.emitterRadius,emitterRadiusInner:i.emitterRadiusInner,emitterShape:i.emitterShape,initialVelocity:i.initialVelocity,wrap:i.wrap,localSpace:i.localSpace,screenSpace:i.screenSpace,wrapBounds:i.wrapBounds,lifetime:i.lifetime,rate:i.rate,rate2:i.rate2,orientation:i.orientation,particleNormal:i.particleNormal,animTilesX:i.animTilesX,animTilesY:i.animTilesY,animStartFrame:i.animStartFrame,animNumFrames:i.animNumFrames,animNumAnimations:i.animNumAnimations,animIndex:i.animIndex,randomizeAnimIndex:i.randomizeAnimIndex,animSpeed:i.animSpeed,animLoop:i.animLoop,startAngle:i.startAngle,startAngle2:i.startAngle2,scaleGraph:i.scaleGraph,scaleGraph2:i.scaleGraph2,colorGraph:i.colorGraph,colorGraph2:i.colorGraph2,alphaGraph:i.alphaGraph,alphaGraph2:i.alphaGraph2,localVelocityGraph:i.localVelocityGraph,localVelocityGraph2:i.localVelocityGraph2,velocityGraph:i.velocityGraph,velocityGraph2:i.velocityGraph2,rotationSpeedGraph:i.rotationSpeedGraph,rotationSpeedGraph2:i.rotationSpeedGraph2,radialSpeedGraph:i.radialSpeedGraph,radialSpeedGraph2:i.radialSpeedGraph2,colorMap:i.colorMap,normalMap:i.normalMap,loop:i.loop,preWarm:i.preWarm,sort:i.sort,stretch:i.stretch,alignToMotion:i.alignToMotion,lighting:i.lighting,halfLambert:i.halfLambert,intensity:i.intensity,depthSoftening:i.depthSoftening,scene:this.system.app.scene,mesh:e,depthWrite:i.depthWrite,noFog:i.noFog,node:this.entity,blendType:i.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,i.autoPlay||(this.pause(),this.emitter.meshInstance.visible=false);}this.emitter.colorMap&&this.addMeshInstanceToLayers(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&i.depthSoftening&&this._requestDepth();}}onDisable(){let e=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,e&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.emitter&&(this.removeMeshInstanceFromLayers(),this.data.depthSoftening&&this._releaseDepth(),this.emitter.camera=null);}onBeforeRemove(){this.enabled&&(this.enabled=false),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(let e=0;e<bk.length;e++){let t=bk[e];this.data[t]&&(this[t]=null);}this.off();}reset(){this.emitter&&this.emitter.reset();}stop(){this.emitter&&(this.emitter.loop=false,this.emitter.resetTime(),this.emitter.addTime(0,true));}pause(){this.data.paused=true;}unpause(){this.data.paused=false;}play(){this.data.paused=false,this.emitter&&(this.emitter.meshInstance.visible=true,this.emitter.loop=this.data.loop,this.emitter.resetTime());}isPlaying(){return !this.data.paused&&(!!this.emitter&&!!this.emitter.loop||Date.now()<=this.emitter.endTime)}setInTools(){let{emitter:e}=this;e&&!e.inTools&&(e.inTools=true,this.rebuild());}rebuild(){let e=this.enabled;this.enabled=false,this.emitter&&this.emitter.rebuild(),this.enabled=e;}}class bz{constructor(){this.numParticles=1,this.rate=1,this.rate2=null,this.startAngle=0,this.startAngle2=null,this.lifetime=50,this.emitterExtents=new eM,this.emitterExtentsInner=new eM,this.emitterRadius=0,this.emitterRadiusInner=0,this.emitterShape=fh,this.initialVelocity=0,this.wrap=false,this.wrapBounds=new eM,this.localSpace=false,this.screenSpace=false,this.colorMap=null,this.colorMapAsset=null,this.normalMap=null,this.normalMapAsset=null,this.loop=true,this.preWarm=false,this.sort=0,this.mode=fo,this.scene=null,this.lighting=false,this.halfLambert=false,this.intensity=1,this.stretch=0,this.alignToMotion=false,this.depthSoftening=0,this.renderAsset=null,this.meshAsset=null,this.mesh=null,this.depthWrite=false,this.noFog=false,this.orientation=fd,this.particleNormal=new eM(0,1,0),this.animTilesX=1,this.animTilesY=1,this.animStartFrame=0,this.animNumFrames=1,this.animNumAnimations=1,this.animIndex=0,this.randomizeAnimIndex=false,this.animSpeed=1,this.animLoop=true,this.scaleGraph=null,this.scaleGraph2=null,this.colorGraph=null,this.colorGraph2=null,this.alphaGraph=null,this.alphaGraph2=null,this.localVelocityGraph=null,this.localVelocityGraph2=null,this.velocityGraph=null,this.velocityGraph2=null,this.rotationSpeedGraph=null,this.rotationSpeedGraph2=null,this.radialSpeedGraph=null,this.radialSpeedGraph2=null,this.blendType=ua,this.enabled=true,this.paused=false,this.autoPlay=true,this.layers=[ub];}}let bG={particlePS:`
varying vec4 texCoordsAlphaLife;
uniform sampler2D colorMap;
uniform sampler2D colorParam;
uniform float graphSampleSize;
uniform float graphNumSamples;
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform vec4 camera_params;
#endif
uniform float softening;
uniform float colorMult;
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
void main(void) {
vec4 tex = texture2D(colorMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y));
vec4 ramp = texture2D(colorParam, vec2(texCoordsAlphaLife.w, 0.0));
ramp.rgb *= colorMult;
ramp.a += texCoordsAlphaLife.z;
vec3 rgb = tex.rgb * ramp.rgb;
float a = tex.a * ramp.a;
`,particleVS:`
vec3 unpack3NFloats(float src) {
float r = fract(src);
float g = fract(src * 256.0);
float b = fract(src * 65536.0);
return vec3(r, g, b);
}
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
vec4 tex1Dlod_lerp(TEXTURE_ACCEPT_HIGHP(tex), vec2 tc) {
return mix( texture2D(tex,tc), texture2D(tex,tc + graphSampleSize), fract(tc.x*graphNumSamples) );
}
vec4 tex1Dlod_lerp(TEXTURE_ACCEPT_HIGHP(tex), vec2 tc, out vec3 w) {
vec4 a = texture2D(tex,tc);
vec4 b = texture2D(tex,tc + graphSampleSize);
float c = fract(tc.x*graphNumSamples);
vec3 unpackedA = unpack3NFloats(a.w);
vec3 unpackedB = unpack3NFloats(b.w);
w = mix(unpackedA, unpackedB, c);
return mix(a, b, c);
}
vec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) {
float c = cos(pRotation);
float s = sin(pRotation);
mat2 m = mat2(c, -s, s, c);
rotMatrix = m;
return m * quadXY;
}
vec3 billboard(vec3 InstanceCoords, vec2 quadXY) {
#ifdef SCREEN_SPACE
vec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y;
#else
vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;
#endif
return pos;
}
vec3 customFace(vec3 InstanceCoords, vec2 quadXY) {
vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;
return pos;
}
vec2 safeNormalize(vec2 v) {
float l = length(v);
return (l > 1e-06) ? v / l : v;
}
void main(void) {
vec3 meshLocalPos = particle_vertexData.xyz;
float id = floor(particle_vertexData.w);
float rndFactor = fract(sin(id + 1.0 + seed));
vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));
float uv = id / numParticlesPot;
readInput(uv);
#ifdef LOCAL_SPACE
inVel = mat3(matrix_model) * inVel;
#endif
vec2 velocityV = safeNormalize((mat3(matrix_view) * inVel).xy);
float particleLifetime = lifetime;
if (inLife <= 0.0 || inLife > particleLifetime || !inShow)
meshLocalPos = vec3(0.0);
vec2 quadXY = meshLocalPos.xy;
float nlife = clamp(inLife / particleLifetime, 0.0, 1.0);
vec3 paramDiv;
vec4 params = tex1Dlod_lerp(TEXTURE_PASS(internalTex2), vec2(nlife, 0), paramDiv);
float scale = params.y;
float scaleDiv = paramDiv.x;
float alphaDiv = paramDiv.z;
scale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0);
#ifndef USE_MESH
texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);
#else
texCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);
#endif
vec3 particlePos = inPos;
vec3 particlePosMoved = vec3(0.0);
mat2 rotMatrix;
`,particleAnimFrameClampVS:`
float animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z);
`,particleAnimFrameLoopVS:`
float animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0));
`,particleAnimTexVS:`
float animationIndex;
if (animTexIndexParams.y == 1.0) {
animationIndex = floor((animTexParams.w + 1.0) * rndFactor3.z) * (animTexParams.z + 1.0);
} else {
animationIndex = animTexIndexParams.x * (animTexParams.z + 1.0);
}
float atlasX = (animationIndex + animFrame) * animTexTilesParams.x;
float atlasY = 1.0 - floor(atlasX + 1.0) * animTexTilesParams.y;
atlasX = fract(atlasX);
texCoordsAlphaLife.xy *= animTexTilesParams.xy;
texCoordsAlphaLife.xy += vec2(atlasX, atlasY);
`,particleInputFloatPS:`
void readInput(float uv) {
vec4 tex = texture2D(particleTexIN, vec2(uv, 0.25));
vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75));
inPos = tex.xyz;
inVel = tex2.xyz;
inAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0;
inShow = tex.w >= 0.0;
inLife = tex2.w;
}
`,particleInputRgba8PS:`
#define PI2 6.283185307179586
uniform vec3 inBoundsSize;
uniform vec3 inBoundsCenter;
uniform float maxVel;
float decodeFloatRG(vec2 rg) {
return rg.y * (1.0 / 255.0) + rg.x;
}
float decodeFloatRGBA( vec4 rgba ) {
return dot(rgba, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));
}
void readInput(float uv) {
vec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125));
vec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375));
vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625));
vec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875));
inPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));
inPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter;
inVel = tex2.xyz;
inVel = (inVel - vec3(0.5)) * maxVel;
inAngle = decodeFloatRG(tex1.ba) * PI2;
inShow = tex2.a > 0.5;
inLife = decodeFloatRGBA(tex3);
float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));
float maxPosLife = lifetime+1.0;
inLife = inLife * (maxNegLife + maxPosLife) - maxNegLife;
}
`,particleOutputFloatPS:`
void writeOutput() {
if (gl_FragCoord.y<1.0) {
gl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode);
} else {
gl_FragColor = vec4(outVel, outLife);
}
}
`,particleOutputRgba8PS:`
uniform vec3 outBoundsMul;
uniform vec3 outBoundsAdd;
vec2 encodeFloatRG( float v ) {
vec2 enc = vec2(1.0, 255.0) * v;
enc = fract(enc);
enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);
return enc;
}
vec4 encodeFloatRGBA( float v ) {
vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v;
enc = fract(enc);
enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);
return enc;
}
void writeOutput() {
outPos = outPos * outBoundsMul + outBoundsAdd;
outAngle = fract(outAngle / PI2);
outVel = (outVel / maxVel) + vec3(0.5);
float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));
float maxPosLife = lifetime+1.0;
outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);
if (gl_FragCoord.y < 1.0) {
gl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));
} else if (gl_FragCoord.y < 2.0) {
gl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));
} else if (gl_FragCoord.y < 3.0) {
gl_FragColor = vec4(outVel, visMode*0.5+0.5);
} else {
gl_FragColor = encodeFloatRGBA(outLife);
}
}
`,particleUpdaterAABBPS:`
uniform mat3 spawnBounds;
uniform vec3 spawnPosInnerRatio;
vec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {
vec3 pos = inBounds - vec3(0.5);
vec3 posAbs = abs(pos);
vec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z)));
vec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio;
pos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x);
pos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y);
pos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z);
#ifndef LOCAL_SPACE
return emitterPos + spawnBounds * pos;
#else
return spawnBounds * pos;
#endif
}
void addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {
localVelocity -= vec3(0, 0, initialVelocity);
}
`,particleUpdaterEndPS:`
writeOutput();
}
`,particleUpdaterInitPS:`
varying vec2 vUv0;
uniform highp sampler2D particleTexIN;
uniform highp sampler2D internalTex0;
uniform highp sampler2D internalTex1;
uniform highp sampler2D internalTex2;
uniform highp sampler2D internalTex3;
uniform mat3 emitterMatrix;
uniform mat3 emitterMatrixInv;
uniform vec3 emitterScale;
uniform vec3 emitterPos;
uniform vec3 frameRandom;
uniform vec3 localVelocityDivMult;
uniform vec3 velocityDivMult;
uniform float delta;
uniform float rate;
uniform float rateDiv;
uniform float lifetime;
uniform float numParticles;
uniform float rotSpeedDivMult;
uniform float radialSpeedDivMult;
uniform float seed;
uniform float startAngle;
uniform float startAngle2;
uniform float initialVelocity;
uniform float graphSampleSize;
uniform float graphNumSamples;
vec3 inPos;
vec3 inVel;
float inAngle;
bool inShow;
float inLife;
float visMode;
vec3 outPos;
vec3 outVel;
float outAngle;
bool outShow;
float outLife;
`,particleUpdaterNoRespawnPS:`
if (outLife >= lifetime) {
outLife -= max(lifetime, (numParticles - 1.0) * particleRate);
visMode = -1.0;
}
`,particleUpdaterOnStopPS:`
visMode = outLife < 0.0? -1.0: visMode;
`,particleUpdaterRespawnPS:`
if (outLife >= lifetime) {
outLife -= max(lifetime, (numParticles - 1.0) * particleRate);
visMode = 1.0;
}
visMode = outLife < 0.0? 1.0: visMode;
`,particleUpdaterSpherePS:`
uniform float spawnBoundsSphere;
uniform float spawnBoundsSphereInnerRatio;
vec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {
float rnd4 = fract(rndFactor * 1000.0);
vec3 norm = normalize(inBounds.xyz - vec3(0.5));
float r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio;
#ifndef LOCAL_SPACE
return emitterPos + norm * r * spawnBoundsSphere;
#else
return norm * r * spawnBoundsSphere;
#endif
}
void addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {
localVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity;
}
`,particleUpdaterStartPS:`
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
vec3 unpack3NFloats(float src) {
float r = fract(src);
float g = fract(src * 256.0);
float b = fract(src * 65536.0);
return vec3(r, g, b);
}
vec3 tex1Dlod_lerp(TEXTURE_ACCEPT_HIGHP(tex), vec2 tc, out vec3 w) {
vec4 a = texture2D(tex, tc);
vec4 b = texture2D(tex, tc + graphSampleSize);
float c = fract(tc.x * graphNumSamples);
vec3 unpackedA = unpack3NFloats(a.w);
vec3 unpackedB = unpack3NFloats(b.w);
w = mix(unpackedA, unpackedB, c);
return mix(a.xyz, b.xyz, c);
}
#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)
vec4 hash41(float p) {
vec4 p4 = fract(vec4(p) * HASHSCALE4);
p4 += dot(p4, p4.wzxy+19.19);
return fract(vec4((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));
}
void main(void) {
if (gl_FragCoord.x > numParticles) discard;
readInput(vUv0.x);
visMode = inShow? 1.0 : -1.0;
vec4 rndFactor = hash41(gl_FragCoord.x + seed);
float particleRate = rate + rateDiv * rndFactor.x;
outLife = inLife + delta;
float nlife = clamp(outLife / lifetime, 0.0, 1.0);
vec3 localVelocityDiv;
vec3 velocityDiv;
vec3 paramDiv;
vec3 localVelocity = tex1Dlod_lerp(TEXTURE_PASS(internalTex0), vec2(nlife, 0), localVelocityDiv);
vec3 velocity = tex1Dlod_lerp(TEXTURE_PASS(internalTex1), vec2(nlife, 0), velocityDiv);
vec3 params = tex1Dlod_lerp(TEXTURE_PASS(internalTex2), vec2(nlife, 0), paramDiv);
float rotSpeed = params.x;
float rotSpeedDiv = paramDiv.y;
vec3 radialParams = tex1Dlod_lerp(TEXTURE_PASS(internalTex3), vec2(nlife, 0), paramDiv);
float radialSpeed = radialParams.x;
float radialSpeedDiv = radialParams.y;
bool respawn = inLife <= 0.0 || outLife >= lifetime;
inPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos;
inAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle;
#ifndef LOCAL_SPACE
vec3 radialVel = inPos - emitterPos;
#else
vec3 radialVel = inPos;
#endif
radialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0);
radialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;
localVelocity += (localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;
velocity += (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;
rotSpeed += (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;
addInitialVelocity(localVelocity, rndFactor.xyz);
#ifndef LOCAL_SPACE
outVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;
#else
outVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;
#endif
outPos = inPos + outVel * delta;
outAngle = inAngle + rotSpeed * delta;
`,particle_billboardVS:`
quadXY = rotate(quadXY, inAngle, rotMatrix);
vec3 localPos = billboard(particlePos, quadXY);
`,particle_blendAddPS:`
dBlendModeFogFactor = 0.0;
rgb *= saturate(gammaCorrectInput(max(a, 0.0)));
if ((rgb.r + rgb.g + rgb.b) < 0.000001) discard;
`,particle_blendMultiplyPS:`
rgb = mix(vec3(1.0), rgb, vec3(a));
if (rgb.r + rgb.g + rgb.b > 2.99) discard;
`,particle_blendNormalPS:`
if (a < 0.01) discard;
`,particle_cpuVS:`
attribute vec4 particle_vertexData;
attribute vec4 particle_vertexData2;
attribute vec4 particle_vertexData3;
attribute float particle_vertexData4;
#ifndef USE_MESH
attribute vec2 particle_vertexData5;
#else
attribute vec4 particle_vertexData5;
#endif
uniform mat4 matrix_viewProjection;
uniform mat4 matrix_model;
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform mat4 matrix_view;
#endif
uniform mat3 matrix_normal;
uniform mat4 matrix_viewInverse;
uniform float numParticles;
uniform float lifetime;
uniform float stretch;
uniform float seed;
uniform vec3 wrapBounds;
uniform vec3 emitterScale;
uniform vec3 faceTangent;
uniform vec3 faceBinorm;
#ifdef PARTICLE_GPU
uniform highp sampler2D internalTex0;
uniform highp sampler2D internalTex1;
uniform highp sampler2D internalTex2;
#endif
uniform vec3 emitterPos;
varying vec4 texCoordsAlphaLife;
vec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix)
{
float c = cos(pRotation);
float s = sin(pRotation);
mat2 m = mat2(c, -s, s, c);
rotMatrix = m;
return m * quadXY;
}
vec3 billboard(vec3 InstanceCoords, vec2 quadXY)
{
vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;
return pos;
}
vec3 customFace(vec3 InstanceCoords, vec2 quadXY)
{
vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;
return pos;
}
void main(void)
{
vec3 particlePos = particle_vertexData.xyz;
vec3 inPos = particlePos;
vec3 vertPos = particle_vertexData3.xyz;
vec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData5.x);
float id = floor(particle_vertexData4);
float rndFactor = fract(sin(id + 1.0 + seed));
vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));
#ifdef LOCAL_SPACE
inVel = mat3(matrix_model) * inVel;
#endif
vec2 velocityV = normalize((mat3(matrix_view) * inVel).xy);
vec2 quadXY = vertPos.xy;
#ifdef USE_MESH
texCoordsAlphaLife = vec4(particle_vertexData5.zw, particle_vertexData2.z, particle_vertexData.w);
#else
texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w);
#endif
mat2 rotMatrix;
float inAngle = particle_vertexData2.x;
vec3 particlePosMoved = vec3(0.0);
vec3 meshLocalPos = particle_vertexData3.xyz;
`,particle_cpu_endVS:`
localPos *= particle_vertexData2.y * emitterScale;
localPos += particlePos;
gl_Position = matrix_viewProjection * vec4(localPos, 1.0);
`,particle_customFaceVS:`
quadXY = rotate(quadXY, inAngle, rotMatrix);
vec3 localPos = customFace(particlePos, quadXY);
`,particle_endPS:`
rgb = addFog(rgb);
rgb = toneMap(rgb);
rgb = gammaCorrectOutput(rgb);
gl_FragColor = vec4(rgb, a);
}
`,particle_endVS:`
localPos *= scale * emitterScale;
localPos += particlePos;
#ifdef SCREEN_SPACE
gl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0);
#else
gl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0);
#endif
`,particle_halflambertPS:`
vec3 negNormal = normal * 0.5 + 0.5;
vec3 posNormal = -normal * 0.5 + 0.5;
negNormal *= negNormal;
posNormal *= posNormal;
`,particle_initVS:`
attribute vec4 particle_vertexData;
#if defined(USE_MESH)
#if defined(USE_MESH_UV)
attribute vec2 particle_uv;
#else
vec2 particle_uv = vec2(0.0, 0.0);
#endif
#endif
uniform mat4 matrix_viewProjection;
uniform mat4 matrix_model;
uniform mat3 matrix_normal;
uniform mat4 matrix_viewInverse;
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform mat4 matrix_view;
#endif
uniform float numParticles;
uniform float numParticlesPot;
uniform float graphSampleSize;
uniform float graphNumSamples;
uniform float stretch;
uniform vec3 wrapBounds;
uniform vec3 emitterScale;
uniform vec3 emitterPos;
uniform vec3 faceTangent;
uniform vec3 faceBinorm;
uniform float rate;
uniform float rateDiv;
uniform float lifetime;
uniform float deltaRandomnessStatic;
uniform float scaleDivMult;
uniform float alphaDivMult;
uniform float seed;
uniform float delta;
uniform sampler2D particleTexOUT;
uniform sampler2D particleTexIN;
#ifdef PARTICLE_GPU
uniform highp sampler2D internalTex0;
uniform highp sampler2D internalTex1;
uniform highp sampler2D internalTex2;
#endif
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform vec4 camera_params;
#endif
varying vec4 texCoordsAlphaLife;
vec3 inPos;
vec3 inVel;
float inAngle;
bool inShow;
float inLife;
`,particle_lambertPS:`
vec3 negNormal = max(normal, vec3(0.0));
vec3 posNormal = max(-normal, vec3(0.0));
`,particle_lightingPS:`
vec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] +
negNormal.y*lightCube[2] + posNormal.y*lightCube[3] +
negNormal.z*lightCube[4] + posNormal.z*lightCube[5];
rgb *= light;
`,particle_localShiftVS:`
particlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;
`,particle_meshVS:`
vec3 localPos = meshLocalPos;
localPos.xy = rotate(localPos.xy, inAngle, rotMatrix);
localPos.yz = rotate(localPos.yz, inAngle, rotMatrix);
billboard(particlePos, quadXY);
`,particle_normalVS:`
Normal = normalize(localPos + matrix_viewInverse[2].xyz);
`,particle_normalMapPS:`
vec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0);
vec3 normal = ParticleMat * normalMap;
`,particle_pointAlongVS:`
inAngle = atan(velocityV.x, velocityV.y);
`,particle_simulationPS:`
#include "particleUpdaterInitPS"
#ifdef PACK8
#include "particleInputRgba8PS"
#include "particleOutputRgba8PS"
#else
#include "particleInputFloatPS"
#include "particleOutputFloatPS"
#endif
#ifdef EMITTERSHAPE_BOX
#include "particleUpdaterAABBPS"
#else
#include "particleUpdaterSpherePS"
#endif
#include "particleUpdaterStartPS"
#ifdef RESPAWN
#include "particleUpdaterRespawnPS"
#endif
#ifdef NO_RESPAWN
#include "particleUpdaterNoRespawnPS"
#endif
#ifdef ON_STOP
#include "particleUpdaterOnStopPS"
#endif
#include "particleUpdaterEndPS"
`,particle_shaderPS:`
#if NORMAL != NONE
#if NORMAL == VERTEX
varying vec3 Normal;
#endif
#if NORMAL == MAP
varying mat3 ParticleMat;
#endif
uniform vec3 lightCube[6];
#endif
#ifdef SOFT
varying float vDepth;
#include "screenDepthPS"
#endif
#include "gammaPS"
#include "tonemappingPS"
#include "fogPS"
#if NORMAL == MAP
uniform sampler2D normalMap;
#endif
#include "particlePS"
#ifdef SOFT
#include "particle_softPS"
#endif
#if NORMAL == VERTEX
vec3 normal = Normal;
#endif
#if NORMAL == MAP
#include "particle_normalMapPS"
#endif
#if NORMAL != NONE
#ifdef HALF_LAMBERT
#include "particle_halflambertPS"
#else
#include "particle_lambertPS"
#endif
#include "particle_lightingPS"
#endif
#if BLEND == NORMAL
#include "particle_blendNormalPS"
#elif BLEND == ADDITIVE
#include "particle_blendAddPS"
#elif BLEND == MULTIPLICATIVE
#include "particle_blendMultiplyPS"
#endif
#include "particle_endPS"
`,particle_shaderVS:`
#ifdef ANIMTEX
uniform vec2 animTexTilesParams;
uniform vec4 animTexParams;
uniform vec2 animTexIndexParams;
#endif
#if NORMAL == MAP
varying mat3 ParticleMat;
#endif
#if NORMAL == VERTEX
varying vec3 Normal;
#endif
#ifdef SOFT
varying float vDepth;
#endif
#ifdef PARTICLE_GPU
#include "particle_initVS"
#ifdef PACK8
#include "particleInputRgba8PS"
#else
#include "particleInputFloatPS"
#endif
#ifdef SOFT
#include "screenDepthPS"
#endif
#include "particleVS"
#else
#ifdef SOFT
#include "screenDepthPS"
#endif
#include "particle_cpuVS"
#endif
#ifdef LOCAL_SPACE
#include "particle_localShiftVS"
#endif
#ifdef ANIMTEX
#ifdef ANIMTEX_LOOP
#include "particleAnimFrameLoopVS"
#else
#include "particleAnimFrameClampVS"
#endif
#include "particleAnimTexVS"
#endif
#ifdef PARTICLE_GPU
#ifdef WRAP
#include "particle_wrapVS"
#endif
#endif
#ifdef ALIGN_TO_MOTION
#include "particle_pointAlongVS"
#endif
#ifdef USE_MESH
#include "particle_meshVS"
#else
#ifdef CUSTOM_FACE
#include "particle_customFaceVS"
#else
#include "particle_billboardVS"
#endif
#endif
#if NORMAL == VERTEX
#include "particle_normalVS"
#endif
#if NORMAL == MAP
#include "particle_TBNVS"
#endif
#ifdef STRETCH
#include "particle_stretchVS"
#endif
#ifdef PARTICLE_GPU
#include "particle_endVS"
#else
#include "particle_cpu_endVS"
#endif
#ifdef SOFT
#include "particle_softVS"
#endif
}
`,particle_softPS:`
float depth = getLinearScreenDepth();
float particleDepth = vDepth;
float depthDiff = saturate(abs(particleDepth - depth) * softening);
a *= depthDiff;
`,particle_softVS:`
vDepth = getLinearDepth(localPos);
`,particle_stretchVS:`
vec3 moveDir = inVel * stretch;
vec3 posPrev = particlePos - moveDir;
posPrev += particlePosMoved;
vec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy);
float interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;
particlePos = mix(particlePos, posPrev, interpolation);
`,particle_TBNVS:`
mat3 rot3 = mat3(rotMatrix[0][0], rotMatrix[0][1], 0.0, rotMatrix[1][0], rotMatrix[1][1], 0.0, 0.0, 0.0, 1.0);
ParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3;
`,particle_wrapVS:`
vec3 origParticlePos = particlePos;
particlePos -= matrix_model[3].xyz;
particlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5;
particlePos += matrix_model[3].xyz;
particlePosMoved = particlePos - origParticlePos;
`},bH={particlePS:`
varying texCoordsAlphaLife: vec4f;
var colorMap: texture_2d<f32>;
var colorMapSampler: sampler;
var colorParam: texture_2d<f32>;
var colorParamSampler: sampler;
uniform graphSampleSize: f32;
uniform graphNumSamples: f32;
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform camera_params: vec4f;
#endif
uniform softening: f32;
uniform colorMult: f32;
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let tex: vec4f = textureSample(colorMap, colorMapSampler, vec2f(input.texCoordsAlphaLife.x, 1.0 - input.texCoordsAlphaLife.y));
var ramp: vec4f = textureSample(colorParam, colorParamSampler, vec2f(input.texCoordsAlphaLife.w, 0.0));
ramp = vec4f(ramp.rgb * uniform.colorMult, ramp.a);
ramp.a = ramp.a + input.texCoordsAlphaLife.z;
var rgb: vec3f = tex.rgb * ramp.rgb;
var a: f32 = tex.a * ramp.a;
`,particleVS:`
fn unpack3NFloats(src: f32) -> vec3f {
let r = fract(src);
let g = fract(src * 256.0);
let b = fract(src * 65536.0);
return vec3f(r, g, b);
}
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
struct TexLerpUnpackResult {
result: vec4f,
unpacked: vec3f
}
fn tex1Dlod_lerp_simple(tex: texture_2d<f32>, texSampler: sampler, tc: vec2f) -> vec4f {
let tc_next = tc + vec2f(uniform.graphSampleSize);
return mix( textureSample(tex, texSampler, tc), textureSample(tex, texSampler, tc_next), fract(tc.x * uniform.graphNumSamples) );
}
fn tex1Dlod_lerp_unpack(tex: texture_2d<f32>, texSampler: sampler, tc: vec2f) -> TexLerpUnpackResult {
let tc_next = tc + vec2f(uniform.graphSampleSize);
let a = textureSampleLevel(tex, texSampler, tc, 0.0);
let b = textureSampleLevel(tex, texSampler, tc_next, 0.0);
let c = fract(tc.x * uniform.graphNumSamples);
let unpackedA = unpack3NFloats(a.w);
let unpackedB = unpack3NFloats(b.w);
let w_out = mix(unpackedA, unpackedB, c);
return TexLerpUnpackResult(mix(a, b, c), w_out);
}
struct RotateResult {
rotatedVec: vec2f,
matrix: mat2x2f
}
fn rotateWithMatrix(quadXY: vec2f, pRotation: f32) -> RotateResult {
let c = cos(pRotation);
let s = sin(pRotation);
let m = mat2x2f(vec2f(c, s), vec2f(-s, c));
return RotateResult(m * quadXY, m);
}
fn billboard(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {
var pos: vec3f;
#ifdef SCREEN_SPACE
pos = vec3f(-1.0, 0.0, 0.0) * quadXY.x + vec3f(0.0, -1.0, 0.0) * quadXY.y;
#else
pos = -uniform.matrix_viewInverse[0].xyz * quadXY.x + -uniform.matrix_viewInverse[1].xyz * quadXY.y;
#endif
return pos;
}
fn customFace(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {
let pos = uniform.faceTangent * quadXY.x + uniform.faceBinorm * quadXY.y;
return pos;
}
fn safeNormalize(v: vec2f) -> vec2f {
let l = length(v);
return select(v, v / l, l > 1e-06);
}
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
let meshLocalPos_in = input.particle_vertexData.xyz;
let id = floor(input.particle_vertexData.w);
let rndFactor = fract(sin(id + 1.0 + uniform.seed));
let rndFactor3 = vec3f(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));
let uv = id / uniform.numParticlesPot;
readInput(uv);
#ifdef LOCAL_SPACE
let modelRotation = mat3x3f(uniform.matrix_model[0].xyz, uniform.matrix_model[1].xyz, uniform.matrix_model[2].xyz);
inVel = modelRotation * inVel;
#endif
let viewRotation = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz);
let velocityV = safeNormalize((viewRotation * inVel).xy);
let particleLifetime = uniform.lifetime;
var meshLocalPos = meshLocalPos_in;
if (inLife <= 0.0 || inLife > particleLifetime || !inShow) {
meshLocalPos = vec3f(0.0);
}
let quadXY = meshLocalPos.xy;
let nlife = clamp(inLife / particleLifetime, 0.0, 1.0);
let lerp_result = tex1Dlod_lerp_unpack(internalTex2, internalTex2Sampler, vec2f(nlife, 0.0));
let params = lerp_result.result;
let paramDiv = lerp_result.unpacked;
var scale = params.y;
let scaleDiv = paramDiv.x;
let alphaDiv = paramDiv.z;
scale = scale + (scaleDiv * 2.0 - 1.0) * uniform.scaleDivMult * fract(rndFactor*10000.0);
#ifndef USE_MESH
output.texCoordsAlphaLife = vec4f(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * uniform.alphaDivMult * fract(rndFactor*1000.0), nlife);
#else
output.texCoordsAlphaLife = vec4f(particle_uv, (alphaDiv * 2.0 - 1.0) * uniform.alphaDivMult * fract(rndFactor*1000.0), nlife);
#endif
var particlePos = inPos;
var particlePosMoved = vec3f(0.0);
var rotMatrix: mat2x2f;
`,particleAnimFrameClampVS:`
let animFrame: f32 = min(floor(input.texCoordsAlphaLife.w * uniform.animTexParams.y) + uniform.animTexParams.x, uniform.animTexParams.z);
`,particleAnimFrameLoopVS:`
let animFrame: f32 = floor((output.texCoordsAlphaLife.w * uniform.animTexParams.y + uniform.animTexParams.x) % (uniform.animTexParams.z + 1.0));
`,particleAnimTexVS:`
var animationIndex: f32;
if (uniform.animTexIndexParams.y == 1.0) {
animationIndex = floor((uniform.animTexParams.w + 1.0) * rndFactor3.z) * (uniform.animTexParams.z + 1.0);
} else {
animationIndex = uniform.animTexIndexParams.x * (uniform.animTexParams.z + 1.0);
}
var atlasX: f32 = (animationIndex + animFrame) * uniform.animTexTilesParams.x;
let atlasY: f32 = 1.0 - floor(atlasX + 1.0) * uniform.animTexTilesParams.y;
atlasX = fract(atlasX);
let current_tcal_xy = output.texCoordsAlphaLife.xy;
let scaled_tcal_xy = current_tcal_xy * uniform.animTexTilesParams.xy;
let final_tcal_xy = scaled_tcal_xy + vec2f(atlasX, atlasY);
output.texCoordsAlphaLife = vec4f(final_tcal_xy, output.texCoordsAlphaLife.z, output.texCoordsAlphaLife.w);
`,particleInputFloatPS:`
fn readInput(uv: f32) {
let tex: vec4f = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.25), 0.0);
let tex2: vec4f = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.75), 0.0);
inPos = tex.xyz;
inVel = tex2.xyz;
inAngle = abs(tex.w) - 1000.0;
inShow = tex.w >= 0.0;
inLife = tex2.w;
}
`,particleInputRgba8PS:`
const PI2: f32 = 6.283185307179586;
uniform inBoundsSize: vec3f;
uniform inBoundsCenter: vec3f;
uniform maxVel: f32;
fn decodeFloatRG(rg: vec2f) -> f32 {
return rg.y * (1.0 / 255.0) + rg.x;
}
fn decodeFloatRGBA( rgba: vec4f ) -> f32 {
return dot(rgba, vec4f(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));
}
fn readInput(uv: f32) {
let tex0 = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.125), 0.0);
let tex1 = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.375), 0.0);
let tex2 = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.625), 0.0);
let tex3 = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.875), 0.0);
inPos = vec3f(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));
inPos = (inPos - vec3f(0.5)) * uniform.inBoundsSize + uniform.inBoundsCenter;
inVel = tex2.xyz;
inVel = (inVel - vec3f(0.5)) * uniform.maxVel;
inAngle = decodeFloatRG(tex1.ba) * PI2;
inShow = tex2.a > 0.5;
let life_decoded = decodeFloatRGBA(tex3);
let maxNegLife = max(uniform.lifetime, (uniform.numParticles - 1.0) * (uniform.rate + uniform.rateDiv));
let maxPosLife = uniform.lifetime + 1.0;
inLife = life_decoded * (maxNegLife + maxPosLife) - maxNegLife;
}`,particleOutputFloatPS:`
fn getOutput() -> vec4f {
if (pcPosition.y < 1.0) {
return vec4f(outPos, (outAngle + 1000.0) * visMode);
} else {
return vec4f(outVel, outLife);
}
}
`,particleOutputRgba8PS:`
uniform outBoundsMul: vec3f;
uniform outBoundsAdd: vec3f;
fn encodeFloatRG( v: f32 ) -> vec2f {
var enc: vec2f = vec2f(1.0, 255.0) * v;
enc = fract(enc);
enc = enc - enc.yy * (1.0 / 255.0);
return enc;
}
fn encodeFloatRGBA( v: f32 ) -> vec4f {
let factors = vec4f(1.0, 255.0, 65025.0, 160581375.0);
var enc: vec4f = factors * v;
enc = fract(enc);
enc = enc - enc.yzww * vec4f(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);
return enc;
}
fn getOutput() -> vec4f {
outPos = outPos * uniform.outBoundsMul + uniform.outBoundsAdd;
outAngle = fract(outAngle / PI2);
outVel = (outVel / uniform.maxVel) + vec3f(0.5);
let maxNegLife = max(uniform.lifetime, (uniform.numParticles - 1.0) * (uniform.rate + uniform.rateDiv));
let maxPosLife = uniform.lifetime + 1.0;
outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);
if (pcPosition.y < 1.0) {
return vec4f(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));
} else if (pcPosition.y < 2.0) {
return vec4f(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));
} else if (pcPosition.y < 3.0) {
return vec4f(outVel, visMode * 0.5 + 0.5);
} else {
return encodeFloatRGBA(outLife);
}
}
`,particleUpdaterAABBPS:`
uniform spawnBounds: mat3x3f;
uniform spawnPosInnerRatio: vec3f;
fn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f {
var pos = inBounds - vec3f(0.5);
let posAbs = abs(pos);
let maxComp = max(posAbs.x, max(posAbs.y, posAbs.z));
let maxPos = vec3f(maxComp);
let edge = maxPos + (vec3f(0.5) - maxPos) * uniform.spawnPosInnerRatio;
pos.x = edge.x * select(2.0 * pos.x, sign(pos.x), maxPos.x == posAbs.x);
pos.y = edge.y * select(2.0 * pos.y, sign(pos.y), maxPos.y == posAbs.y);
pos.z = edge.z * select(2.0 * pos.z, sign(pos.z), maxPos.z == posAbs.z);
#ifndef LOCAL_SPACE
return uniform.emitterPos + uniform.spawnBounds * pos;
#else
return uniform.spawnBounds * pos;
#endif
}
fn addInitialVelocity(localVelocity: ptr<function, vec3f>, inBounds: vec3f) {
*localVelocity = *localVelocity - vec3f(0.0, 0.0, uniform.initialVelocity);
}
`,particleUpdaterEndPS:`
output.color = getOutput();
return output;
}
`,particleUpdaterInitPS:`
varying vUv0: vec2f;
var particleTexIN: texture_2d<f32>;
var particleTexINSampler: sampler;
var internalTex0: texture_2d<f32>;
var internalTex0Sampler: sampler;
var internalTex1: texture_2d<f32>;
var internalTex1Sampler: sampler;
var internalTex2: texture_2d<f32>;
var internalTex2Sampler: sampler;
var internalTex3: texture_2d<f32>;
var internalTex3Sampler: sampler;
uniform emitterMatrix: mat3x3f;
uniform emitterMatrixInv: mat3x3f;
uniform emitterScale: vec3f;
uniform emitterPos: vec3f;
uniform frameRandom: vec3f;
uniform localVelocityDivMult: vec3f;
uniform velocityDivMult: vec3f;
uniform delta: f32;
uniform rate: f32;
uniform rateDiv: f32;
uniform lifetime: f32;
uniform numParticles: f32;
uniform rotSpeedDivMult: f32;
uniform radialSpeedDivMult: f32;
uniform seed: f32;
uniform startAngle: f32;
uniform startAngle2: f32;
uniform initialVelocity: f32;
uniform graphSampleSize: f32;
uniform graphNumSamples: f32;
var<private> inPos: vec3f;
var<private> inVel: vec3f;
var<private> inAngle: f32;
var<private> inShow: bool;
var<private> inLife: f32;
var<private> visMode: f32;
var<private> outPos: vec3f;
var<private> outVel: vec3f;
var<private> outAngle: f32;
var<private> outShow: bool;
var<private> outLife: f32;
`,particleUpdaterNoRespawnPS:`
if (outLife >= uniform.lifetime) {
outLife = outLife - max(uniform.lifetime, (uniform.numParticles - 1.0) * particleRate);
visMode = -1.0;
}
`,particleUpdaterOnStopPS:`
visMode = select(visMode, -1.0, outLife < 0.0);
`,particleUpdaterRespawnPS:`
if (outLife >= uniform.lifetime) {
let subtractAmount = max(uniform.lifetime, (uniform.numParticles - 1.0) * particleRate);
outLife = outLife - subtractAmount;
visMode = 1.0;
}
visMode = select(visMode, 1.0, outLife < 0.0);
`,particleUpdaterSpherePS:`
uniform spawnBoundsSphere: f32;
uniform spawnBoundsSphereInnerRatio: f32;
fn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f {
let rnd4: f32 = fract(rndFactor * 1000.0);
let norm: vec3f = normalize(inBounds.xyz - vec3f(0.5));
let r: f32 = rnd4 * (1.0 - uniform.spawnBoundsSphereInnerRatio) + uniform.spawnBoundsSphereInnerRatio;
#ifndef LOCAL_SPACE
return uniform.emitterPos + norm * r * uniform.spawnBoundsSphere;
#else
return norm * r * uniform.spawnBoundsSphere;
#endif
}
fn addInitialVelocity(localVelocity: ptr<function, vec3f>, inBounds: vec3f) {
let initialVelOffset: vec3f = normalize(inBounds - vec3f(0.5)) * uniform.initialVelocity;
*localVelocity = *localVelocity + initialVelOffset;
}
`,particleUpdaterStartPS:`
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
fn unpack3NFloats(src: f32) -> vec3f {
let r = fract(src);
let g = fract(src * 256.0);
let b = fract(src * 65536.0);
return vec3f(r, g, b);
}
struct TexLerpUnpackResult {
result: vec3f,
unpacked: vec3f
}
fn tex1Dlod_lerp(tex: texture_2d<f32>, texSampler: sampler, tc: vec2f) -> TexLerpUnpackResult {
let tc_next = tc + vec2f(uniform.graphSampleSize);
let a = textureSampleLevel(tex, texSampler, tc, 0.0);
let b = textureSampleLevel(tex, texSampler, tc_next, 0.0);
let c = fract(tc.x * uniform.graphNumSamples);
let unpackedA = unpack3NFloats(a.w);
let unpackedB = unpack3NFloats(b.w);
let w_out = mix(unpackedA, unpackedB, c);
return TexLerpUnpackResult(mix(a.xyz, b.xyz, c), w_out);
}
const HASHSCALE4: vec4f = vec4f(1031.0, 0.1030, 0.0973, 0.1099);
fn hash41(p: f32) -> vec4f {
var p4 = fract(vec4f(p) * HASHSCALE4);
p4 = p4 + dot(p4, p4.wzxy + 19.19);
return fract(vec4f((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));
}
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
if (pcPosition.x > uniform.numParticles) {
discard;
return output;
}
readInput(input.vUv0.x);
visMode = select(-1.0, 1.0, inShow);
let rndFactor = hash41(pcPosition.x + uniform.seed);
let particleRate = uniform.rate + uniform.rateDiv * rndFactor.x;
outLife = inLife + uniform.delta;
let nlife = clamp(outLife / uniform.lifetime, 0.0, 1.0);
let lerpResult0 = tex1Dlod_lerp(internalTex0, internalTex0Sampler, vec2f(nlife, 0.0));
var localVelocity = lerpResult0.result;
let localVelocityDiv = lerpResult0.unpacked;
let lerpResult1 = tex1Dlod_lerp(internalTex1, internalTex1Sampler, vec2f(nlife, 0.0));
var velocity = lerpResult1.result;
let velocityDiv = lerpResult1.unpacked;
let lerpResult2 = tex1Dlod_lerp(internalTex2, internalTex2Sampler, vec2f(nlife, 0.0));
let params = lerpResult2.result;
let paramDiv = lerpResult2.unpacked;
var rotSpeed = params.x;
let rotSpeedDiv = paramDiv.y;
let lerpResult3 = tex1Dlod_lerp(internalTex3, internalTex3Sampler, vec2f(nlife, 0.0));
let radialParams = lerpResult3.result;
let radialParamDiv = lerpResult3.unpacked;
let radialSpeed = radialParams.x;
let radialSpeedDiv = radialParamDiv.y;
let respawn = inLife <= 0.0 || outLife >= uniform.lifetime;
inPos = select(inPos, calcSpawnPosition(rndFactor.xyz, rndFactor.x), respawn);
inAngle = select(inAngle, mix(uniform.startAngle, uniform.startAngle2, rndFactor.x), respawn);
#ifndef LOCAL_SPACE
var radialVel: vec3f = inPos - uniform.emitterPos;
#else
var radialVel: vec3f = inPos;
#endif
radialVel = select(vec3f(0.0), radialSpeed * normalize(radialVel), dot(radialVel, radialVel) > 1.0E-8);
radialVel = radialVel + (radialSpeedDiv * vec3f(2.0) - vec3f(1.0)) * uniform.radialSpeedDivMult * rndFactor.xyz;
localVelocity = localVelocity + (localVelocityDiv * vec3f(2.0) - vec3f(1.0)) * uniform.localVelocityDivMult * rndFactor.xyz;
velocity = velocity + (velocityDiv * vec3f(2.0) - vec3f(1.0)) * uniform.velocityDivMult * rndFactor.xyz;
rotSpeed = rotSpeed + (rotSpeedDiv * 2.0 - 1.0) * uniform.rotSpeedDivMult * rndFactor.y;
addInitialVelocity(&localVelocity, rndFactor.xyz);
#ifndef LOCAL_SPACE
outVel = uniform.emitterMatrix * localVelocity + (radialVel + velocity) * uniform.emitterScale;
#else
outVel = (localVelocity + radialVel) / uniform.emitterScale + uniform.emitterMatrixInv * velocity;
#endif
outPos = inPos + outVel * uniform.delta;
outAngle = inAngle + rotSpeed * uniform.delta;
`,particle_billboardVS:`
let rotationResult = rotateWithMatrix(quadXY, inAngle);
let rotatedQuadXY = rotationResult.rotatedVec;
rotMatrix = rotationResult.matrix;
var localPos = billboard(particlePos, rotatedQuadXY);
`,particle_blendAddPS:`
dBlendModeFogFactor = 0.0;
rgb = rgb * saturate(gammaCorrectInput(max(a, 0.0)));
if ((rgb.r + rgb.g + rgb.b) < 0.000001) {
discard;
}
`,particle_blendMultiplyPS:`
rgb = mix(vec3f(1.0), rgb, a);
if ((rgb.r + rgb.g + rgb.b) > 2.99) {
discard;
}
`,particle_blendNormalPS:`
if (a < 0.01) {
discard;
}
`,particle_cpuVS:`
attribute particle_vertexData: vec4f;
attribute particle_vertexData2: vec4f;
attribute particle_vertexData3: vec4f;
attribute particle_vertexData4: f32;
#ifndef USE_MESH
attribute particle_vertexData5: vec2f;
#else
attribute particle_vertexData5: vec4f;
#endif
uniform matrix_viewProjection: mat4x4f;
uniform matrix_model: mat4x4f;
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform matrix_view: mat4x4f;
#endif
uniform matrix_normal: mat3x3f;
uniform matrix_viewInverse: mat4x4f;
uniform numParticles: f32;
uniform lifetime: f32;
uniform stretch: f32;
uniform seed: f32;
uniform wrapBounds: vec3f;
uniform emitterScale: vec3f;
uniform faceTangent: vec3f;
uniform faceBinorm: vec3f;
#ifdef PARTICLE_GPU
var internalTex0: texture_2d<f32>;
var internalTex0Sampler: sampler;
var internalTex1: texture_2d<f32>;
var internalTex1Sampler: sampler;
var internalTex2: texture_2d<f32>;
var internalTex2Sampler: sampler;
#endif
uniform emitterPos: vec3f;
varying texCoordsAlphaLife: vec4f;
struct RotateResult {
rotatedVec: vec2f,
matrix: mat2x2f
}
fn rotateWithMatrix(quadXY: vec2f, pRotation: f32) -> RotateResult {
let c = cos(pRotation);
let s = sin(pRotation);
let m = mat2x2f(vec2f(c, s), vec2f(-s, c));
return RotateResult(m * quadXY, m);
}
fn billboard(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {
let pos = -uniform.matrix_viewInverse[0].xyz * quadXY.x + -uniform.matrix_viewInverse[1].xyz * quadXY.y;
return pos;
}
fn customFace(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {
let pos = uniform.faceTangent * quadXY.x + uniform.faceBinorm * quadXY.y;
return pos;
}
fn safeNormalize(v: vec2f) -> vec2f {
let l = length(v);
return select(v, v / l, l > 1e-06);
}
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
var particlePos = input.particle_vertexData.xyz;
let inPos = particlePos;
let vertPos = input.particle_vertexData3.xyz;
var inVel = vec3f(input.particle_vertexData2.w, input.particle_vertexData3.w, input.particle_vertexData5.x);
let id = floor(input.particle_vertexData4);
let rndFactor = fract(sin(id + 1.0 + uniform.seed));
let rndFactor3 = vec3f(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));
#ifdef LOCAL_SPACE
let modelRotation = mat3x3f(uniform.matrix_model[0].xyz, uniform.matrix_model[1].xyz, uniform.matrix_model[2].xyz);
inVel = modelRotation * inVel;
#endif
let velocityV = safeNormalize((mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz) * inVel).xy);
let quadXY = vertPos.xy;
#ifdef USE_MESH
output.texCoordsAlphaLife = vec4f(input.particle_vertexData5.zw, input.particle_vertexData2.z, input.particle_vertexData.w);
#else
output.texCoordsAlphaLife = vec4f(quadXY * -0.5 + 0.5, input.particle_vertexData2.z, input.particle_vertexData.w);
#endif
var rotMatrix: mat2x2f;
var inAngle = input.particle_vertexData2.x;
var particlePosMoved = vec3f(0.0);
let meshLocalPos = input.particle_vertexData3.xyz;
`,particle_cpu_endVS:`
localPos = localPos * input.particle_vertexData2.y * uniform.emitterScale;
localPos = localPos + particlePos;
output.position = uniform.matrix_viewProjection * vec4f(localPos, 1.0);
`,particle_customFaceVS:`
let rotationResult = rotateWithMatrix(quadXY, inAngle);
let rotatedQuadXY = rotationResult.rotatedVec;
rotMatrix = rotationResult.matrix;
var localPos = customFace(particlePos, rotatedQuadXY);
`,particle_endPS:`
rgb = addFog(rgb);
rgb = toneMap(rgb);
rgb = gammaCorrectOutput(rgb);
output.color = vec4f(rgb, a);
return output;
}
`,particle_endVS:`
localPos = localPos * scale * uniform.emitterScale;
localPos = localPos + particlePos;
#ifdef SCREEN_SPACE
output.position = vec4f(localPos.x, localPos.y, 0.0, 1.0);
#else
output.position = uniform.matrix_viewProjection * vec4f(localPos.xyz, 1.0);
#endif
`,particle_halflambertPS:`
var negNormal: vec3f = normal * 0.5 + 0.5;
var posNormal: vec3f = -normal * 0.5 + 0.5;
negNormal = negNormal * negNormal;
posNormal = posNormal * posNormal;
`,particle_initVS:`
attribute particle_vertexData: vec4f;
#if defined(USE_MESH)
#if defined(USE_MESH_UV)
attribute particle_uv: vec2f;
#else
var<private> particle_uv: vec2f = vec2f(0.0, 0.0);
#endif
#endif
uniform matrix_viewProjection: mat4x4f;
uniform matrix_model: mat4x4f;
uniform matrix_normal: mat3x3f;
uniform matrix_viewInverse: mat4x4f;
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform matrix_view: mat4x4f;
#endif
uniform numParticles: f32;
uniform numParticlesPot: f32;
uniform graphSampleSize: f32;
uniform graphNumSamples: f32;
uniform stretch: f32;
uniform wrapBounds: vec3f;
uniform emitterScale: vec3f;
uniform emitterPos: vec3f;
uniform faceTangent: vec3f;
uniform faceBinorm: vec3f;
uniform rate: f32;
uniform rateDiv: f32;
uniform lifetime: f32;
uniform deltaRandomnessStatic: f32;
uniform scaleDivMult: f32;
uniform alphaDivMult: f32;
uniform seed: f32;
uniform delta: f32;
var particleTexOUT: texture_2d<f32>;
var particleTexOUTSampler: sampler;
var particleTexIN: texture_2d<f32>;
var particleTexINSampler: sampler;
#ifdef PARTICLE_GPU
var internalTex0: texture_2d<f32>;
var internalTex0Sampler: sampler;
var internalTex1: texture_2d<f32>;
var internalTex1Sampler: sampler;
var internalTex2: texture_2d<f32>;
var internalTex2Sampler: sampler;
#endif
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform camera_params: vec4f;
#endif
varying texCoordsAlphaLife: vec4f;
var<private> inPos: vec3f;
var<private> inVel: vec3f;
var<private> inAngle: f32;
var<private> inShow: bool;
var<private> inLife: f32;
`,particle_lambertPS:`
var negNormal: vec3f = max(normal, vec3(0.0));
var posNormal: vec3f = max(-normal, vec3(0.0));
`,particle_lightingPS:`
let light: vec3f = negNormal.x * uniform.lightCube[0] + posNormal.x * uniform.lightCube[1] +
negNormal.y * uniform.lightCube[2] + posNormal.y * uniform.lightCube[3] +
negNormal.z * uniform.lightCube[4] + posNormal.z * uniform.lightCube[5];
rgb = rgb * light;
`,particle_localShiftVS:`
particlePos = (uniform.matrix_model * vec4f(particlePos, 1.0)).xyz;
`,particle_meshVS:`
var localPos = meshLocalPos;
let rotResultXY = rotateWithMatrix(localPos.xy, inAngle);
localPos = vec3f(rotResultXY.rotatedVec, localPos.z);
rotMatrix = rotResultXY.matrix;
let rotResultYZ = rotateWithMatrix(localPos.yz, inAngle);
localPos = vec3f(localPos.x, rotResultYZ.rotatedVec);
rotMatrix = rotResultYZ.matrix;
billboard(particlePos, quadXY);
`,particle_normalVS:`
output.Normal = normalize(localPos + uniform.matrix_viewInverse[2].xyz);
`,particle_normalMapPS:`
let sampledNormal: vec4f = textureSample(normalMap, normalMapSampler, vec2f(input.texCoordsAlphaLife.x, 1.0 - input.texCoordsAlphaLife.y));
let normalMap: vec3f = normalize(sampledNormal.xyz * 2.0 - 1.0);
let ParticleMat = mat3x3<f32>(ParticleMat0, ParticleMat1, ParticleMat2);
let normal: vec3f = ParticleMat * normalMap;
`,particle_pointAlongVS:`
inAngle = atan2(velocityV.x, velocityV.y);
`,particle_simulationPS:`
#include "particleUpdaterInitPS"
#ifdef PACK8
#include "particleInputRgba8PS"
#include "particleOutputRgba8PS"
#else
#include "particleInputFloatPS"
#include "particleOutputFloatPS"
#endif
#ifdef EMITTERSHAPE_BOX
#include "particleUpdaterAABBPS"
#else
#include "particleUpdaterSpherePS"
#endif
#include "particleUpdaterStartPS"
#ifdef RESPAWN
#include "particleUpdaterRespawnPS"
#endif
#ifdef NO_RESPAWN
#include "particleUpdaterNoRespawnPS"
#endif
#ifdef ON_STOP
#include "particleUpdaterOnStopPS"
#endif
#include "particleUpdaterEndPS"
`,particle_shaderPS:`
#if NORMAL != NONE
#if NORMAL == VERTEX
varying Normal: vec3f;
#endif
#if NORMAL == MAP
varying ParticleMat0: vec3f;
varying ParticleMat1: vec3f;
varying ParticleMat2: vec3f;
#endif
uniform lightCube: array<vec3f, 6>;
#endif
#ifdef SOFT
varying vDepth: f32;
#include "screenDepthPS"
#endif
#include "gammaPS"
#include "tonemappingPS"
#include "fogPS"
#if NORMAL == MAP
var normalMap: texture_2d<f32>;
var normalMapSampler: sampler;
#endif
#include "particlePS"
#ifdef SOFT
#include "particle_softPS"
#endif
#if NORMAL == VERTEX
var normal: vec3f = Normal;
#endif
#if NORMAL == MAP
#include "particle_normalMapPS"
#endif
#if NORMAL != NONE
#ifdef HALF_LAMBERT
#include "particle_halflambertPS"
#else
#include "particle_lambertPS"
#endif
#include "particle_lightingPS"
#endif
#if BLEND == NORMAL
#include "particle_blendNormalPS"
#elif BLEND == ADDITIVE
#include "particle_blendAddPS"
#elif BLEND == MULTIPLICATIVE
#include "particle_blendMultiplyPS"
#endif
#include "particle_endPS"
`,particle_shaderVS:`
#ifdef ANIMTEX
uniform animTexTilesParams: vec2f;
uniform animTexParams: vec4f;
uniform animTexIndexParams: vec2f;
#endif
#if NORMAL == MAP
varying ParticleMat0: vec3f;
varying ParticleMat1: vec3f;
varying ParticleMat2: vec3f;
#endif
#if NORMAL == VERTEX
varying Normal: vec3f;
#endif
#ifdef SOFT
varying vDepth: f32;
#endif
#ifdef PARTICLE_GPU
#include "particle_initVS"
#ifdef PACK8
#include "particleInputRgba8PS"
#else
#include "particleInputFloatPS"
#endif
#ifdef SOFT
#include "screenDepthPS"
#endif
#include "particleVS"
#else
#ifdef SOFT
#include "screenDepthPS"
#endif
#include "particle_cpuVS"
#endif
#ifdef LOCAL_SPACE
#include "particle_localShiftVS"
#endif
#ifdef ANIMTEX
#ifdef ANIMTEX_LOOP
#include "particleAnimFrameLoopVS"
#else
#include "particleAnimFrameClampVS"
#endif
#include "particleAnimTexVS"
#endif
#ifdef PARTICLE_GPU
#ifdef WRAP
#include "particle_wrapVS"
#endif
#endif
#ifdef ALIGN_TO_MOTION
#include "particle_pointAlongVS"
#endif
#ifdef USE_MESH
#include "particle_meshVS"
#else
#ifdef CUSTOM_FACE
#include "particle_customFaceVS"
#else
#include "particle_billboardVS"
#endif
#endif
#if NORMAL == VERTEX
#include "particle_normalVS"
#endif
#if NORMAL == MAP
#include "particle_TBNVS"
#endif
#ifdef STRETCH
#include "particle_stretchVS"
#endif
#ifdef PARTICLE_GPU
#include "particle_endVS"
#else
#include "particle_cpu_endVS"
#endif
#ifdef SOFT
#include "particle_softVS"
#endif
return output;
}
`,particle_softPS:`
var depth: f32 = getLinearScreenDepthFrag();
var particleDepth: f32 = vDepth;
var depthDiff: f32 = saturate(abs(particleDepth - depth) * uniform.softening);
a = a * depthDiff;
`,particle_softVS:`
output.vDepth = getLinearDepth(localPos);
`,particle_stretchVS:`
let moveDir: vec3f = inVel * uniform.stretch;
var posPrev: vec3f = particlePos - moveDir;
posPrev = posPrev + particlePosMoved;
let viewRotationTemp: mat3x3f = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz);
let centerToVertexV: vec2f = normalize((viewRotationTemp * localPos).xy);
let interpolation: f32 = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;
particlePos = mix(particlePos, posPrev, interpolation);
`,particle_TBNVS:`
let rot3 = mat3x3f(
vec3f(rotMatrix[0][0], rotMatrix[1][0], 0.0),
vec3f(rotMatrix[0][1], rotMatrix[1][1], 0.0),
vec3f(0.0, 0.0, 1.0)
);
let viewBasis = mat3x3f(
-uniform.matrix_viewInverse[0].xyz,
-uniform.matrix_viewInverse[1].xyz,
uniform.matrix_viewInverse[2].xyz
);
let tempMat = viewBasis * rot3;
output.ParticleMat0 = tempMat[0];
output.ParticleMat1 = tempMat[1];
output.ParticleMat2 = tempMat[2];
`,particle_wrapVS:`
let origParticlePos: vec3f = particlePos;
particlePos = particlePos - uniform.matrix_model[3].xyz;
particlePos = (particlePos % uniform.wrapBounds) - uniform.wrapBounds * 0.5;
particlePos = particlePos + uniform.matrix_model[3].xyz;
particlePosMoved = particlePos - origParticlePos;
`},bW=["enabled","autoPlay","numParticles","lifetime","rate","rate2","startAngle","startAngle2","loop","preWarm","lighting","halfLambert","intensity","depthWrite","noFog","depthSoftening","sort","blendType","stretch","alignToMotion","emitterShape","emitterExtents","emitterExtentsInner","emitterRadius","emitterRadiusInner","initialVelocity","wrap","wrapBounds","localSpace","screenSpace","colorMapAsset","normalMapAsset","mesh","meshAsset","renderAsset","orientation","particleNormal","localVelocityGraph","localVelocityGraph2","velocityGraph","velocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2","scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","colorMap","normalMap","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animSpeed","animLoop","layers"];class bX extends Tm{constructor(e){super(e),this.id="particlesystem",this.ComponentType=bV,this.DataType=bz,this.schema=bW,this.propertyTypes={emitterExtents:"vec3",emitterExtentsInner:"vec3",particleNormal:"vec3",wrapBounds:"vec3",localVelocityGraph:"curveset",localVelocityGraph2:"curveset",velocityGraph:"curveset",velocityGraph2:"curveset",colorGraph:"curveset",colorGraph2:"curveset",alphaGraph:"curve",alphaGraph2:"curve",rotationSpeedGraph:"curve",rotationSpeedGraph2:"curve",radialSpeedGraph:"curve",radialSpeedGraph2:"curve",scaleGraph:"curve",scaleGraph2:"curve"},this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("update",this.onUpdate,this),mr.get(e.graphicsDevice,rb).add(bG),mr.get(e.graphicsDevice,rw).add(bH);}initializeComponentData(e,t,i){let s={};i=[];let r=this.propertyTypes;for(let e in (t.mesh instanceof xF||"number"==typeof t.mesh)&&(t.meshAsset=t.mesh,delete t.mesh),t){if(t.hasOwnProperty(e)&&(i.push(e),s[e]=t[e]),"vec3"===r[e])Array.isArray(s[e])&&(s[e]=new eM(s[e][0],s[e][1],s[e][2]));else if("curve"===r[e]){if(!(s[e]instanceof eC)){let t=s[e].type;s[e]=new eC(s[e].keys),s[e].type=t;}}else if("curveset"===r[e]&&!(s[e]instanceof eP)){let t=s[e].type;s[e]=new eP(s[e].keys),s[e].type=t;}s.layers&&Array.isArray(s.layers)&&(s.layers=s.layers.slice(0));}super.initializeComponentData(e,s,i);}cloneComponent(e,t){let i=e.particlesystem.data,s=this.schema,r={};for(let e=0,t=s.length;e<t;e++){let t=s[e],a=i[t];a instanceof eM||a instanceof eC||a instanceof eP?(a=a.clone(),r[t]=a):"layers"===t?r.layers=i.layers.slice(0):null!=a&&(r[t]=a);}return this.addComponent(t,r)}onUpdate(e){let t=this.store,i=this.app.stats.particles,s=this.app.scene.layers;for(let e=0;e<s.layerList.length;e++)s.layerList[e].requiresLightCube=false;for(let r in t)if(t.hasOwnProperty(r)){let a=t[r],n=a.entity,o=a.data;if(o.enabled&&n.enabled){let t=n.particlesystem.emitter;if(!t?.meshInstance.visible)continue;if(t.lighting){let e=o.layers;for(let t=0;t<e.length;t++){let i=s.getLayerById(e[t]);i&&(i.requiresLightCube=true);}}if(!o.paused){let s=0;if(t.simTime+=e,t.simTime>=t.fixedTimeStep&&(s=Math.floor(t.simTime/t.fixedTimeStep),t.simTime-=s*t.fixedTimeStep),s){s=Math.min(s,t.maxSubSteps);for(let e=0;e<s;e++)t.addTime(t.fixedTimeStep,false);i._updatesPerFrame+=s,i._frameTime+=t._addTimeTime,t._addTimeTime=0;}t.finishFrame();}}}}onBeforeRemove(e,t){t.onBeforeRemove();}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this);}}class bY extends n4{constructor(e,t){super(),this.skin=e,this.skinInstance=t;}}class bq{static{this._skinInstanceCache=new Map;}static createCachedSkinInstance(e,t,i){let s=bq.getCachedSkinInstance(e,t);return s||((s=new mx(e)).resolve(t,i),bq.addCachedSkinInstance(e,t,s)),s}static getCachedSkinInstance(e,t){let i=null,s=bq._skinInstanceCache.get(t);if(s){let t=s.find(t=>t.skin===e);t&&(t.incRefCount(),i=t.skinInstance);}return i}static addCachedSkinInstance(e,t,i){let s=bq._skinInstanceCache.get(t);s||(s=[],bq._skinInstanceCache.set(t,s));let r=s.find(t=>t.skin===e);r||(r=new bY(e,i),s.push(r)),r.incRefCount();}static removeCachedSkinInstance(e){if(e){let t=e.rootBone;if(t){let i=bq._skinInstanceCache.get(t);if(i){let s=i.findIndex(t=>t.skinInstance===e);if(s>=0){let r=i[s];r.decRefCount(),0===r.refCount&&(i.splice(s,1),i.length||bq._skinInstanceCache.delete(t),e&&(e.destroy(),r.skinInstance=null));}}}}}}class b${constructor(e,t,i,s,r){this._evtLoadById=null,this._evtUnloadById=null,this._evtAddById=null,this._evtRemoveById=null,this._evtLoadByUrl=null,this._evtAddByUrl=null,this._evtRemoveByUrl=null,this.propertyName=e,this.parent=t,this._scope=r,this._registry=i,this.id=null,this.url=null,this.asset=null,this._onAssetLoad=s.load,this._onAssetAdd=s.add,this._onAssetRemove=s.remove,this._onAssetUnload=s.unload;}set id(e){if(this.url)throw Error("Can't set id and url");this._unbind(),this._id=e,this.asset=this._registry.get(this._id),this._bind();}get id(){return this._id}set url(e){if(this.id)throw Error("Can't set id and url");this._unbind(),this._url=e,this.asset=this._registry.getByUrl(this._url),this._bind();}get url(){return this._url}_bind(){this.id&&(this._onAssetLoad&&(this._evtLoadById=this._registry.on(`load:${this.id}`,this._onLoad,this)),this._onAssetAdd&&(this._evtAddById=this._registry.once(`add:${this.id}`,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveById=this._registry.on(`remove:${this.id}`,this._onRemove,this)),this._onAssetUnload&&(this._evtUnloadById=this._registry.on(`unload:${this.id}`,this._onUnload,this))),this.url&&(this._onAssetLoad&&(this._evtLoadByUrl=this._registry.on(`load:url:${this.url}`,this._onLoad,this)),this._onAssetAdd&&(this._evtAddByUrl=this._registry.once(`add:url:${this.url}`,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveByUrl=this._registry.on(`remove:url:${this.url}`,this._onRemove,this)));}_unbind(){this.id&&(this._evtLoadById?.off(),this._evtLoadById=null,this._evtAddById?.off(),this._evtAddById=null,this._evtRemoveById?.off(),this._evtRemoveById=null,this._evtUnloadById?.off(),this._evtUnloadById=null),this.url&&(this._evtLoadByUrl?.off(),this._evtLoadByUrl=null,this._evtAddByUrl?.off(),this._evtAddByUrl=null,this._evtRemoveByUrl?.off(),this._evtRemoveByUrl=null);}_onLoad(e){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,e);}_onAdd(e){this.asset=e,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,e);}_onRemove(e){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,e),this.asset=null;}_onUnload(e){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,e);}}class bj extends Tp{constructor(e,t){super(e,t),this._type="asset",this._castShadows=true,this._receiveShadows=true,this._castShadowsLightmap=true,this._lightmapped=false,this._lightmapSizeMultiplier=1,this.isStatic=false,this._batchGroupId=-1,this._layers=[ub],this._renderStyle=f_,this._meshInstances=[],this._customAabb=null,this._area=null,this._materialReferences=[],this._rootBone=null,this._evtLayersChanged=null,this._evtLayerAdded=null,this._evtLayerRemoved=null,this._evtSetMeshes=null,this._assetReference=new b$("asset",this,e.app.assets,{add:this._onRenderAssetAdded,load:this._onRenderAssetLoad,remove:this._onRenderAssetRemove,unload:this._onRenderAssetUnload},this),this._material=e.defaultMaterial,t.on("remove",this.onRemoveChild,this),t.on("removehierarchy",this.onRemoveChild,this),t.on("insert",this.onInsertChild,this),t.on("inserthierarchy",this.onInsertChild,this);}set renderStyle(e){this._renderStyle!==e&&(this._renderStyle=e,mV._prepareRenderStyleForArray(this._meshInstances,e));}get renderStyle(){return this._renderStyle}set customAabb(e){this._customAabb=e;let t=this._meshInstances;if(t)for(let e=0;e<t.length;e++)t[e].setCustomAabb(this._customAabb);}get customAabb(){return this._customAabb}set type(e){if(this._type!==e&&(this._area=null,this._type=e,this.destroyMeshInstances(),"asset"!==e)){let t=this._material;t&&t!==this.system.defaultMaterial||(t=this._materialReferences[0]&&this._materialReferences[0].asset&&this._materialReferences[0].asset.resource);let i=bD(this.system.app.graphicsDevice,e);this._area=i.area,this.meshInstances=[new mV(i.mesh,t||this.system.defaultMaterial,this.entity)];}}get type(){return this._type}set meshInstances(e){if(this.destroyMeshInstances(),this._meshInstances=e,this._meshInstances){let e=this._meshInstances;for(let t=0;t<e.length;t++)e[t].node||(e[t].node=this.entity),e[t].castShadow=this._castShadows,e[t].receiveShadow=this._receiveShadows,e[t].renderStyle=this._renderStyle,e[t].setLightmapped(this._lightmapped),e[t].setCustomAabb(this._customAabb);this.enabled&&this.entity.enabled&&this.addToLayers();}}get meshInstances(){return this._meshInstances}set lightmapped(e){if(e!==this._lightmapped){this._lightmapped=e;let t=this._meshInstances;if(t)for(let i=0;i<t.length;i++)t[i].setLightmapped(e);}}get lightmapped(){return this._lightmapped}set castShadows(e){if(this._castShadows!==e){let t=this._meshInstances;if(t){let i=this.layers,s=this.system.app.scene;if(this._castShadows&&!e)for(let e=0;e<i.length;e++){let i=s.layers.getLayerById(this.layers[e]);i&&i.removeShadowCasters(t);}for(let i=0;i<t.length;i++)t[i].castShadow=e;if(!this._castShadows&&e)for(let e=0;e<i.length;e++){let r=s.layers.getLayerById(i[e]);r&&r.addShadowCasters(t);}}this._castShadows=e;}}get castShadows(){return this._castShadows}set receiveShadows(e){if(this._receiveShadows!==e){this._receiveShadows=e;let t=this._meshInstances;if(t)for(let i=0;i<t.length;i++)t[i].receiveShadow=e;}}get receiveShadows(){return this._receiveShadows}set castShadowsLightmap(e){this._castShadowsLightmap=e;}get castShadowsLightmap(){return this._castShadowsLightmap}set lightmapSizeMultiplier(e){this._lightmapSizeMultiplier=e;}get lightmapSizeMultiplier(){return this._lightmapSizeMultiplier}set layers(e){let t,i=this.system.app.scene.layers;if(this._meshInstances)for(let e=0;e<this._layers.length;e++)(t=i.getLayerById(this._layers[e]))&&t.removeMeshInstances(this._meshInstances);this._layers.length=0;for(let t=0;t<e.length;t++)this._layers[t]=e[t];if(this.enabled&&this.entity.enabled&&this._meshInstances)for(let e=0;e<this._layers.length;e++)(t=i.getLayerById(this._layers[e]))&&t.addMeshInstances(this._meshInstances);}get layers(){return this._layers}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher?.remove(mS.RENDER,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(mS.RENDER,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=e);}get batchGroupId(){return this._batchGroupId}set material(e){if(this._material!==e&&(this._material=e,this._meshInstances&&"asset"!==this._type))for(let t=0;t<this._meshInstances.length;t++)this._meshInstances[t].material=e;}get material(){return this._material}set materialAssets(e=[]){if(this._materialReferences.length>e.length){for(let t=e.length;t<this._materialReferences.length;t++)this._materialReferences[t].id=null;this._materialReferences.length=e.length;}for(let t=0;t<e.length;t++)if(this._materialReferences[t]||this._materialReferences.push(new b$(t,this,this.system.app.assets,{add:this._onMaterialAdded,load:this._onMaterialLoad,remove:this._onMaterialRemove,unload:this._onMaterialUnload},this)),e[t]){let i=e[t]instanceof xF?e[t].id:e[t];this._materialReferences[t].id!==i&&(this._materialReferences[t].id=i),this._materialReferences[t].asset&&this._onMaterialAdded(t,this,this._materialReferences[t].asset);}else this._materialReferences[t].id=null,this._meshInstances[t]&&(this._meshInstances[t].material=this.system.defaultMaterial);}get materialAssets(){return this._materialReferences.map(e=>e.id)}set asset(e){let t=e instanceof xF?e.id:e;this._assetReference.id!==t&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onRenderAssetRemove(),this._assetReference.id=t,this._assetReference.asset&&this._onRenderAssetAdded());}get asset(){return this._assetReference.id}assignAsset(e){let t=e instanceof xF?e.id:e;this._assetReference.id=t;}set rootBone(e){if(this._rootBone!==e){let t="string"==typeof e;this._rootBone&&t&&this._rootBone.getGuid()===e||(this._rootBone&&this._clearSkinInstances(),e instanceof _c?this._rootBone=e:t?(this._rootBone=this.system.app.getEntityFromIndex(e)||null,this._rootBone):this._rootBone=null,this._rootBone&&this._cloneSkinInstances());}}get rootBone(){return this._rootBone}destroyMeshInstances(){let e=this._meshInstances;if(e){this.removeFromLayers(),this._clearSkinInstances();for(let t=0;t<e.length;t++)e[t].destroy();this._meshInstances.length=0;}}addToLayers(){let e=this.system.app.scene.layers;for(let t=0;t<this._layers.length;t++){let i=e.getLayerById(this._layers[t]);i&&i.addMeshInstances(this._meshInstances);}}removeFromLayers(){if(this._meshInstances&&this._meshInstances.length){let e=this.system.app.scene.layers;for(let t=0;t<this._layers.length;t++){let i=e.getLayerById(this._layers[t]);i&&i.removeMeshInstances(this._meshInstances);}}}onRemoveChild(){this.removeFromLayers();}onInsertChild(){this._meshInstances&&this.enabled&&this.entity.enabled&&this.addToLayers();}onRemove(){this.destroyMeshInstances(),this.asset=null,this.materialAsset=null,this._assetReference.id=null;for(let e=0;e<this._materialReferences.length;e++)this._materialReferences[e].id=null;this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this);}onLayersChanged(e,t){this.addToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this);}onLayerAdded(e){0>this.layers.indexOf(e.id)||e.addMeshInstances(this._meshInstances);}onLayerRemoved(e){0>this.layers.indexOf(e.id)||e.removeMeshInstances(this._meshInstances);}onEnable(){let e=this.system.app,t=e.scene,i=t.layers;this._rootBone&&this._cloneSkinInstances(),this._evtLayersChanged=t.on("set:layers",this.onLayersChanged,this),i&&(this._evtLayerAdded=i.on("add",this.onLayerAdded,this),this._evtLayerRemoved=i.on("remove",this.onLayerRemoved,this));let s="asset"===this._type;this._meshInstances&&this._meshInstances.length?this.addToLayers():s&&this.asset&&this._onRenderAssetAdded();for(let e=0;e<this._materialReferences.length;e++)this._materialReferences[e].asset&&this.system.app.assets.load(this._materialReferences[e].asset);this._batchGroupId>=0&&e.batcher?.insert(mS.RENDER,this.batchGroupId,this.entity);}onDisable(){let e=this.system.app,t=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,this._rootBone&&this._clearSkinInstances(),t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&e.batcher?.remove(mS.RENDER,this.batchGroupId,this.entity),this.removeFromLayers();}hide(){if(this._meshInstances)for(let e=0;e<this._meshInstances.length;e++)this._meshInstances[e].visible=false;}show(){if(this._meshInstances)for(let e=0;e<this._meshInstances.length;e++)this._meshInstances[e].visible=true;}_onRenderAssetAdded(){this._assetReference.asset&&(this._assetReference.asset.resource?this._onRenderAssetLoad():this.enabled&&this.entity.enabled&&this.system.app.assets.load(this._assetReference.asset));}_onRenderAssetLoad(){if(this.destroyMeshInstances(),this._assetReference.asset){let e=this._assetReference.asset.resource;this._evtSetMeshes?.off(),this._evtSetMeshes=e.on("set:meshes",this._onSetMeshes,this),e.meshes&&this._onSetMeshes(e.meshes);}}_onSetMeshes(e){this._cloneMeshes(e);}_clearSkinInstances(){for(let e=0;e<this._meshInstances.length;e++){let t=this._meshInstances[e];bq.removeCachedSkinInstance(t.skinInstance),t.skinInstance=null;}}_cloneSkinInstances(){if(this._meshInstances.length&&this._rootBone instanceof _c)for(let e=0;e<this._meshInstances.length;e++){let t=this._meshInstances[e],i=t.mesh;i.skin&&!t.skinInstance&&(t.skinInstance=bq.createCachedSkinInstance(i.skin,this._rootBone,this.entity));}}_cloneMeshes(e){if(e&&e.length){let t=[];for(let i=0;i<e.length;i++){let s=e[i],r=new mV(s,this._materialReferences[i]&&this._materialReferences[i].asset&&this._materialReferences[i].asset.resource||this.system.defaultMaterial,this.entity);t.push(r),s.morph&&(r.morphInstance=new g4(s.morph));}this.meshInstances=t,this._cloneSkinInstances();}}_onRenderAssetUnload(){"asset"===this._type&&this.destroyMeshInstances();}_onRenderAssetRemove(){this._evtSetMeshes?.off(),this._evtSetMeshes=null,this._onRenderAssetUnload();}_onMaterialAdded(e,t,i){i.resource?this._onMaterialLoad(e,t,i):this.enabled&&this.entity.enabled&&this.system.app.assets.load(i);}_updateMainMaterial(e,t){0===e&&(this.material=t);}_onMaterialLoad(e,t,i){this._meshInstances[e]&&(this._meshInstances[e].material=i.resource),this._updateMainMaterial(e,i.resource);}_onMaterialRemove(e,t,i){this._meshInstances[e]&&(this._meshInstances[e].material=this.system.defaultMaterial),this._updateMainMaterial(e,this.system.defaultMaterial);}_onMaterialUnload(e,t,i){this._meshInstances[e]&&(this._meshInstances[e].material=this.system.defaultMaterial),this._updateMainMaterial(e,this.system.defaultMaterial);}resolveDuplicatedEntityReferenceProperties(e,t){e.rootBone&&(this.rootBone=t[e.rootBone.getGuid()]);}}class bK{constructor(){this.enabled=true;}}let bZ=["enabled"],bQ=["material","meshInstances","asset","materialAssets","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","renderStyle","type","layers","isStatic","batchGroupId","rootBone"];class bJ extends Tm{constructor(e){super(e),this.id="render",this.ComponentType=bj,this.DataType=bK,this.schema=bZ,this.defaultMaterial=mP(e.graphicsDevice),this.on("beforeremove",this.onRemove,this);}initializeComponentData(e,t,i){(null===t.batchGroupId||void 0===t.batchGroupId)&&(t.batchGroupId=-1),t.layers&&t.layers.length&&(t.layers=t.layers.slice(0));for(let i=0;i<bQ.length;i++)t.hasOwnProperty(bQ[i])&&(e[bQ[i]]=t[bQ[i]]);t.aabbCenter&&t.aabbHalfExtents&&(e.customAabb=new ej(new eM(t.aabbCenter),new eM(t.aabbHalfExtents))),super.initializeComponentData(e,t,bZ);}cloneComponent(e,t){let i={};for(let t=0;t<bQ.length;t++)i[bQ[t]]=e.render[bQ[t]];i.enabled=e.render.enabled,delete i.meshInstances;let s=this.addComponent(t,i),r=e.render.meshInstances,a=r.map(e=>e.mesh);s._onSetMeshes(a);for(let e=0;e<r.length;e++)s.meshInstances[e].material=r[e].material;return e.render.customAabb&&(s.customAabb=e.render.customAabb.clone()),s}onRemove(e,t){t.onRemove();}}Tp._buildAccessors(bj.prototype,bZ);class b0{constructor(e,t){this._pool=[],this._count=0,this._constructor=e,this._resize(t);}_resize(e){if(e>this._pool.length)for(let t=this._pool.length;t<e;t++)this._pool[t]=new this._constructor;}allocate(){return this._count>=this._pool.length&&this._resize(2*this._pool.length),this._pool[this._count++]}freeAll(){this._count=0;}}let b1=new eH,b2=new eH,b3=new eM;class b4 extends Tp{static{this.EVENT_CONTACT="contact";}static{this.EVENT_COLLISIONSTART="collisionstart";}static{this.EVENT_COLLISIONEND="collisionend";}static{this.EVENT_TRIGGERENTER="triggerenter";}static{this.EVENT_TRIGGERLEAVE="triggerleave";}static{this.order=-1;}static onLibraryLoaded(){"undefined"!=typeof Ammo&&(l=new Ammo.btTransform,h=new Ammo.btVector3,c=new Ammo.btVector3,d=new Ammo.btQuaternion);}static onAppDestroy(){Ammo.destroy(l),Ammo.destroy(h),Ammo.destroy(c),Ammo.destroy(d),l=null,h=null,c=null,d=null;}set angularDamping(e){this._angularDamping!==e&&(this._angularDamping=e,this._body&&this._body.setDamping(this._linearDamping,e));}get angularDamping(){return this._angularDamping}set angularFactor(e){!this._angularFactor.equals(e)&&(this._angularFactor.copy(e),this._body&&this._type===EG&&(h.setValue(e.x,e.y,e.z),this._body.setAngularFactor(h)));}get angularFactor(){return this._angularFactor}set angularVelocity(e){this._body&&this._type===EG&&(this._body.activate(),h.setValue(e.x,e.y,e.z),this._body.setAngularVelocity(h),this._angularVelocity.copy(e));}get angularVelocity(){if(this._body&&this._type===EG){let e=this._body.getAngularVelocity();this._angularVelocity.set(e.x(),e.y(),e.z());}return this._angularVelocity}set body(e){this._body!==e&&(this._body=e,e&&this._simulationEnabled&&e.activate());}get body(){return this._body}set friction(e){this._friction!==e&&(this._friction=e,this._body&&this._body.setFriction(e));}get friction(){return this._friction}set group(e){this._group!==e&&(this._group=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()));}get group(){return this._group}set linearDamping(e){this._linearDamping!==e&&(this._linearDamping=e,this._body&&this._body.setDamping(e,this._angularDamping));}get linearDamping(){return this._linearDamping}set linearFactor(e){!this._linearFactor.equals(e)&&(this._linearFactor.copy(e),this._body&&this._type===EG&&(h.setValue(e.x,e.y,e.z),this._body.setLinearFactor(h)));}get linearFactor(){return this._linearFactor}set linearVelocity(e){this._body&&this._type===EG&&(this._body.activate(),h.setValue(e.x,e.y,e.z),this._body.setLinearVelocity(h),this._linearVelocity.copy(e));}get linearVelocity(){if(this._body&&this._type===EG){let e=this._body.getLinearVelocity();this._linearVelocity.set(e.x(),e.y(),e.z());}return this._linearVelocity}set mask(e){this._mask!==e&&(this._mask=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()));}get mask(){return this._mask}set mass(e){if(this._mass!==e&&(this._mass=e,this._body&&this._type===EG)){let t=this.enabled&&this.entity.enabled;t&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(e,h),this._body.setMassProps(e,h),this._body.updateInertiaTensor(),t&&this.enableSimulation();}}get mass(){return this._mass}set restitution(e){this._restitution!==e&&(this._restitution=e,this._body&&this._body.setRestitution(e));}get restitution(){return this._restitution}set rollingFriction(e){this._rollingFriction!==e&&(this._rollingFriction=e,this._body&&this._body.setRollingFriction(e));}get rollingFriction(){return this._rollingFriction}set type(e){if(this._type!==e){switch(this._type=e,this.disableSimulation(),e){case EG:this._group=E0,this._mask=An;break;case EH:this._group=E2,this._mask=An;break;default:this._group=E1,this._mask=Al;}this.createBody();}}get type(){return this._type}createBody(){let e,t=this.entity;if(t.collision&&(e=t.collision.shape,t.trigger&&(t.trigger.destroy(),delete t.trigger)),e){this._body&&(this.system.removeBody(this._body),this.system.destroyBody(this._body),this._body=null);let i=this._type===EG?this._mass:0;this._getEntityTransform(l);let s=this.system.createBody(i,e,l);if(s.setRestitution(this._restitution),s.setFriction(this._friction),s.setRollingFriction(this._rollingFriction),s.setDamping(this._linearDamping,this._angularDamping),this._type===EG){let e=this._linearFactor;h.setValue(e.x,e.y,e.z),s.setLinearFactor(h);let t=this._angularFactor;h.setValue(t.x,t.y,t.z),s.setAngularFactor(h);}else this._type===EH&&(s.setCollisionFlags(s.getCollisionFlags()|EX),s.setActivationState(EK));s.entity=t,this.body=s,this.enabled&&t.enabled&&this.enableSimulation();}}isActive(){return !!this._body&&this._body.isActive()}activate(){this._body&&this._body.activate();}enableSimulation(){let e=this.entity;if(e.collision&&e.collision.enabled&&!this._simulationEnabled){let t=this._body;if(t){switch(this.system.addBody(t,this._group,this._mask),this._type){case EG:this.system._dynamic.push(this),t.forceActivationState(Eq),this.syncEntityToBody();break;case EH:this.system._kinematic.push(this),t.forceActivationState(EK);break;case Ez:t.forceActivationState(Eq),this.syncEntityToBody();}"compound"===e.collision.type&&this.system._compounds.push(e.collision),t.activate(),this._simulationEnabled=true;}}}disableSimulation(){let e=this._body;if(e&&this._simulationEnabled){let t=this.system,i=t._compounds.indexOf(this.entity.collision);i>-1&&t._compounds.splice(i,1),(i=t._dynamic.indexOf(this))>-1&&t._dynamic.splice(i,1),(i=t._kinematic.indexOf(this))>-1&&t._kinematic.splice(i,1),t.removeBody(e),e.forceActivationState(EZ),this._simulationEnabled=false;}}applyForce(e,t,i,s,r,a){let n=this._body;n&&(n.activate(),e instanceof eM?h.setValue(e.x,e.y,e.z):h.setValue(e,t,i),t instanceof eM?c.setValue(t.x,t.y,t.z):void 0!==s?c.setValue(s,r,a):c.setValue(0,0,0),n.applyForce(h,c));}applyTorque(e,t,i){let s=this._body;s&&(s.activate(),e instanceof eM?h.setValue(e.x,e.y,e.z):h.setValue(e,t,i),s.applyTorque(h));}applyImpulse(e,t,i,s,r,a){let n=this._body;n&&(n.activate(),e instanceof eM?h.setValue(e.x,e.y,e.z):h.setValue(e,t,i),t instanceof eM?c.setValue(t.x,t.y,t.z):void 0!==s?c.setValue(s,r,a):c.setValue(0,0,0),n.applyImpulse(h,c));}applyTorqueImpulse(e,t,i){let s=this._body;s&&(s.activate(),e instanceof eM?h.setValue(e.x,e.y,e.z):h.setValue(e,t,i),s.applyTorqueImpulse(h));}isStatic(){return this._type===Ez}isStaticOrKinematic(){return this._type===Ez||this._type===EH}isKinematic(){return this._type===EH}_getEntityTransform(e){let t=this.entity,i=t.collision;if(i){let e=i.getShapePosition(),t=i.getShapeRotation();h.setValue(e.x,e.y,e.z),d.setValue(t.x,t.y,t.z,t.w);}else {let e=t.getPosition(),i=t.getRotation();h.setValue(e.x,e.y,e.z),d.setValue(i.x,i.y,i.z,i.w);}e.setOrigin(h),e.setRotation(d);}syncEntityToBody(){let e=this._body;if(e){if(this._getEntityTransform(l),e.setWorldTransform(l),this._type===EH){let t=e.getMotionState();t&&t.setWorldTransform(l);}e.activate();}}_updateDynamic(){let e=this._body;if(e.isActive()){let t=e.getMotionState();if(t){let e=this.entity;t.getWorldTransform(l);let i=l.getOrigin(),s=l.getRotation(),r=e.collision;if(r&&r._hasOffset){let t=r.data.linearOffset,a=r.data.angularOffset,n=b2.copy(a).invert(),o=b1.set(s.x(),s.y(),s.z(),s.w()).mul(n);o.transformVector(t,b3),e.setPosition(i.x()-b3.x,i.y()-b3.y,i.z()-b3.z),e.setRotation(o);}else e.setPosition(i.x(),i.y(),i.z()),e.setRotation(s.x(),s.y(),s.z(),s.w());}}}_updateKinematic(){let e=this._body.getMotionState();e&&(this._getEntityTransform(l),e.setWorldTransform(l));}teleport(e,t,i,s,r,a){e instanceof eM?this.entity.setPosition(e):this.entity.setPosition(e,t,i),t instanceof eH?this.entity.setRotation(t):t instanceof eM?this.entity.setEulerAngles(t):void 0!==s&&this.entity.setEulerAngles(s,r,a),this.syncEntityToBody();}onEnable(){this._body||this.createBody(),this.enableSimulation();}onDisable(){this.disableSimulation();}constructor(...e){super(...e),this._angularDamping=0,this._angularFactor=new eM(1,1,1),this._angularVelocity=new eM,this._body=null,this._friction=.5,this._group=E1,this._linearDamping=0,this._linearFactor=new eM(1,1,1),this._linearVelocity=new eM,this._mask=Al,this._mass=1,this._restitution=0,this._rollingFriction=0,this._simulationEnabled=false,this._type=Ez;}}class b5{constructor(){this.enabled=true;}}class b8{constructor(e,t,i,s){this.entity=e,this.point=t,this.normal=i,this.hitFraction=s;}}class b6{constructor(e,t,i){0!=arguments.length?(this.a=e,this.b=t,this.impulse=i.impulse,this.localPointA=i.localPoint,this.localPointB=i.localPointOther,this.pointA=i.point,this.pointB=i.pointOther,this.normal=i.normal):(this.a=null,this.b=null,this.impulse=0,this.localPointA=new eM,this.localPointB=new eM,this.pointA=new eM,this.pointB=new eM,this.normal=new eM);}}class b9{constructor(e=new eM,t=new eM,i=new eM,s=new eM,r=new eM,a=0){this.localPoint=e,this.localPointOther=t,this.point=i,this.pointOther=s,this.normal=r,this.impulse=a;}}class b7{constructor(e,t){this.other=e,this.contacts=t;}}let we=["enabled"];class wt extends Tm{static{this.EVENT_CONTACT="contact";}constructor(e){super(e),this.maxSubSteps=10,this.fixedTimeStep=1/60,this.gravity=new eM(0,-9.81,0),this._gravityFloat32=new Float32Array(3),this._dynamic=[],this._kinematic=[],this._triggers=[],this._compounds=[],this.id="rigidbody",this._stats=e.stats.frame,this.ComponentType=b4,this.DataType=b5,this.contactPointPool=null,this.contactResultPool=null,this.singleContactResultPool=null,this.schema=we,this.collisions={},this.frameCollisions={},this.on("beforeremove",this.onBeforeRemove,this);}onLibraryLoaded(){if("undefined"!=typeof Ammo){if(this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.overlappingPairCache=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.dynamicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.overlappingPairCache,this.solver,this.collisionConfiguration),this.dynamicsWorld.setInternalTickCallback){let e=Ammo.addFunction(this._checkForCollisions.bind(this),"vif");this.dynamicsWorld.setInternalTickCallback(e);}u=new Ammo.btVector3,f=new Ammo.btVector3,b4.onLibraryLoaded(),this.contactPointPool=new b0(b9,1),this.contactResultPool=new b0(b7,1),this.singleContactResultPool=new b0(b6,1),this.app.systems.on("update",this.onUpdate,this);}else this.app.systems.off("update",this.onUpdate,this);}initializeComponentData(e,t,i){for(let i of ["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"])if(t.hasOwnProperty(i)){let s=t[i];Array.isArray(s)?e[i]=new eM(s[0],s[1],s[2]):e[i]=s;}super.initializeComponentData(e,t,["enabled"]);}cloneComponent(e,t){let i=e.rigidbody,s={enabled:i.enabled,mass:i.mass,linearDamping:i.linearDamping,angularDamping:i.angularDamping,linearFactor:[i.linearFactor.x,i.linearFactor.y,i.linearFactor.z],angularFactor:[i.angularFactor.x,i.angularFactor.y,i.angularFactor.z],friction:i.friction,rollingFriction:i.rollingFriction,restitution:i.restitution,type:i.type,group:i.group,mask:i.mask};return this.addComponent(t,s)}onBeforeRemove(e,t){t.enabled&&(t.enabled=false),t.body&&(this.destroyBody(t.body),t.body=null);}addBody(e,t,i){ void 0!==t&&void 0!==i?this.dynamicsWorld.addRigidBody(e,t,i):this.dynamicsWorld.addRigidBody(e);}removeBody(e){this.dynamicsWorld.removeRigidBody(e);}createBody(e,t,i){let s=new Ammo.btVector3(0,0,0);0!==e&&t.calculateLocalInertia(e,s);let r=new Ammo.btDefaultMotionState(i),a=new Ammo.btRigidBodyConstructionInfo(e,r,t,s),n=new Ammo.btRigidBody(a);return Ammo.destroy(a),Ammo.destroy(s),n}destroyBody(e){let t=e.getMotionState();t&&Ammo.destroy(t),Ammo.destroy(e);}raycastFirst(e,t,i={}){if(i.filterTags||i.filterCallback)return i.sort=true,this.raycastAll(e,t,i)[0]||null;let s=null;u.setValue(e.x,e.y,e.z),f.setValue(t.x,t.y,t.z);let r=new Ammo.ClosestRayResultCallback(u,f);if("number"==typeof i.filterCollisionGroup&&r.set_m_collisionFilterGroup(i.filterCollisionGroup),"number"==typeof i.filterCollisionMask&&r.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(u,f,r),r.hasHit()){let e=r.get_m_collisionObject(),t=Ammo.castObject(e,Ammo.btRigidBody);if(t){let e=r.get_m_hitPointWorld(),i=r.get_m_hitNormalWorld();s=new b8(t.entity,new eM(e.x(),e.y(),e.z()),new eM(i.x(),i.y(),i.z()),r.get_m_closestHitFraction());}}return Ammo.destroy(r),s}raycastAll(e,t,i={}){let s=[];u.setValue(e.x,e.y,e.z),f.setValue(t.x,t.y,t.z);let r=new Ammo.AllHitsRayResultCallback(u,f);if("number"==typeof i.filterCollisionGroup&&r.set_m_collisionFilterGroup(i.filterCollisionGroup),"number"==typeof i.filterCollisionMask&&r.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(u,f,r),r.hasHit()){let e=r.get_m_collisionObjects(),t=r.get_m_hitPointWorld(),a=r.get_m_hitNormalWorld(),n=r.get_m_hitFractions(),o=e.size();for(let r=0;r<o;r++){let o=Ammo.castObject(e.at(r),Ammo.btRigidBody);if(o&&o.entity){if(i.filterTags&&!o.entity.tags.has(...i.filterTags)||i.filterCallback&&!i.filterCallback(o.entity))continue;let e=t.at(r),l=a.at(r),h=new b8(o.entity,new eM(e.x(),e.y(),e.z()),new eM(l.x(),l.y(),l.z()),n.at(r));s.push(h);}}i.sort&&s.sort((e,t)=>e.hitFraction-t.hitFraction);}return Ammo.destroy(r),s}_storeCollision(e,t){let i=false,s=e.getGuid();return this.collisions[s]=this.collisions[s]||{others:[],entity:e},0>this.collisions[s].others.indexOf(t)&&(this.collisions[s].others.push(t),i=true),this.frameCollisions[s]=this.frameCollisions[s]||{others:[],entity:e},this.frameCollisions[s].others.push(t),i}_createContactPointFromAmmo(e){let t=e.get_m_localPointA(),i=e.get_m_localPointB(),s=e.getPositionWorldOnA(),r=e.getPositionWorldOnB(),a=e.get_m_normalWorldOnB(),n=this.contactPointPool.allocate();return n.localPoint.set(t.x(),t.y(),t.z()),n.localPointOther.set(i.x(),i.y(),i.z()),n.point.set(s.x(),s.y(),s.z()),n.pointOther.set(r.x(),r.y(),r.z()),n.normal.set(a.x(),a.y(),a.z()),n.impulse=e.getAppliedImpulse(),n}_createReverseContactPointFromAmmo(e){let t=e.get_m_localPointA(),i=e.get_m_localPointB(),s=e.getPositionWorldOnA(),r=e.getPositionWorldOnB(),a=e.get_m_normalWorldOnB(),n=this.contactPointPool.allocate();return n.localPointOther.set(t.x(),t.y(),t.z()),n.localPoint.set(i.x(),i.y(),i.z()),n.pointOther.set(s.x(),s.y(),s.z()),n.point.set(r.x(),r.y(),r.z()),n.normal.set(a.x(),a.y(),a.z()),n.impulse=e.getAppliedImpulse(),n}_createSingleContactResult(e,t,i){let s=this.singleContactResultPool.allocate();return s.a=e,s.b=t,s.localPointA=i.localPoint,s.localPointB=i.localPointOther,s.pointA=i.point,s.pointB=i.pointOther,s.normal=i.normal,s.impulse=i.impulse,s}_createContactResult(e,t){let i=this.contactResultPool.allocate();return i.other=e,i.contacts=t,i}_cleanOldCollisions(){for(let e in this.collisions)if(this.collisions.hasOwnProperty(e)){let t=this.frameCollisions[e],i=this.collisions[e],s=i.entity,r=s.collision,a=s.rigidbody,n=i.others,o=n.length;for(;o--;){let e=n[o];(!t||0>t.others.indexOf(e))&&(n.splice(o,1),s.trigger?(r&&r.fire("triggerleave",e),e.rigidbody&&e.rigidbody.fire("triggerleave",s)):!e.trigger&&(a&&a.fire("collisionend",e),r&&r.fire("collisionend",e)));}0===n.length&&delete this.collisions[e];}}_hasContactEvent(e){let t=e.collision;if(t&&(t.hasEvent("collisionstart")||t.hasEvent("collisionend")||t.hasEvent("contact")))return true;let i=e.rigidbody;return i&&(i.hasEvent("collisionstart")||i.hasEvent("collisionend")||i.hasEvent("contact"))}_checkForCollisions(e,t){let i=Ammo.wrapPointer(e,Ammo.btDynamicsWorld).getDispatcher(),s=i.getNumManifolds();this.frameCollisions={};for(let e=0;e<s;e++){let t,s=i.getManifoldByIndexInternal(e),r=s.getBody0(),a=s.getBody1(),n=Ammo.castObject(r,Ammo.btRigidBody),o=Ammo.castObject(a,Ammo.btRigidBody),l=n.entity,h=o.entity;if(!l||!h)continue;let c=n.getCollisionFlags(),d=o.getCollisionFlags(),u=s.getNumContacts(),f=[],p=[];if(u>0)if(c&EY||d&EY){let e=l.collision&&(l.collision.hasEvent("triggerenter")||l.collision.hasEvent("triggerleave")),i=h.collision&&(h.collision.hasEvent("triggerenter")||h.collision.hasEvent("triggerleave")),s=l.rigidbody&&(l.rigidbody.hasEvent("triggerenter")||l.rigidbody.hasEvent("triggerleave")),r=h.rigidbody&&(h.rigidbody.hasEvent("triggerenter")||h.rigidbody.hasEvent("triggerleave"));e&&(t=this._storeCollision(l,h))&&!(d&EY)&&l.collision.fire("triggerenter",h),i&&(t=this._storeCollision(h,l))&&!(c&EY)&&h.collision.fire("triggerenter",l),s&&(t||(t=this._storeCollision(h,l)),t&&l.rigidbody.fire("triggerenter",h)),r&&(t||(t=this._storeCollision(l,h)),t&&h.rigidbody.fire("triggerenter",l));}else {let e=this._hasContactEvent(l),i=this._hasContactEvent(h),r=this.hasEvent("contact");if(r||e||i){for(let t=0;t<u;t++){let a=s.getContactPoint(t),n=this._createContactPointFromAmmo(a);if(e||i){f.push(n);let e=this._createReverseContactPointFromAmmo(a);p.push(e);}if(r){let e=this._createSingleContactResult(l,h,n);this.fire("contact",e);}}if(e){let e=this._createContactResult(h,f);t=this._storeCollision(l,h),l.collision&&(l.collision.fire("contact",e),t&&l.collision.fire("collisionstart",e)),l.rigidbody&&(l.rigidbody.fire("contact",e),t&&l.rigidbody.fire("collisionstart",e));}if(i){let e=this._createContactResult(l,p);t=this._storeCollision(h,l),h.collision&&(h.collision.fire("contact",e),t&&h.collision.fire("collisionstart",e)),h.rigidbody&&(h.rigidbody.fire("contact",e),t&&h.rigidbody.fire("collisionstart",e));}}}}this._cleanOldCollisions(),this.contactPointPool.freeAll(),this.contactResultPool.freeAll(),this.singleContactResultPool.freeAll();}onUpdate(e){let t,i;this._gravityFloat32[0]=this.gravity.x,this._gravityFloat32[1]=this.gravity.y,this._gravityFloat32[2]=this.gravity.z;let s=this.dynamicsWorld.getGravity();(s.x()!==this._gravityFloat32[0]||s.y()!==this._gravityFloat32[1]||s.z()!==this._gravityFloat32[2])&&(s.setValue(this.gravity.x,this.gravity.y,this.gravity.z),this.dynamicsWorld.setGravity(s));let r=this._triggers;for(t=0,i=r.length;t<i;t++)r[t].updateTransform();let a=this._compounds;for(t=0,i=a.length;t<i;t++)a[t]._updateCompound();let n=this._kinematic;for(t=0,i=n.length;t<i;t++)n[t]._updateKinematic();this.dynamicsWorld.stepSimulation(e,this.maxSubSteps,this.fixedTimeStep);let o=this._dynamic;for(t=0,i=o.length;t<i;t++)o[t]._updateDynamic();this.dynamicsWorld.setInternalTickCallback||this._checkForCollisions(Ammo.getPointer(this.dynamicsWorld),e);}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this),"undefined"!=typeof Ammo&&(Ammo.destroy(this.dynamicsWorld),Ammo.destroy(this.solver),Ammo.destroy(this.overlappingPairCache),Ammo.destroy(this.dispatcher),Ammo.destroy(this.collisionConfiguration),Ammo.destroy(u),Ammo.destroy(f),this.dynamicsWorld=null,this.solver=null,this.overlappingPairCache=null,this.dispatcher=null,this.collisionConfiguration=null,u=null,f=null,b4.onAppDestroy());}}Tp._buildAccessors(b4.prototype,we);let wi="none",ws="blend",wr=new eG;class wa extends Tp{constructor(e,t){super(e,t),this._resolution=new eN(640,320),this._referenceResolution=new eN(640,320),this._scaleMode=wi,this.scale=1,this._scaleBlend=.5,this._priority=0,this._screenSpace=false,this.cull=this._screenSpace,this._screenMatrix=new eG,this._elements=new Set,e.app.graphicsDevice.on("resizecanvas",this._onResize,this);}syncDrawOrder(){this.system.queueDrawOrderSync(this.entity.getGuid(),this._processDrawOrderSync,this);}_recurseDrawOrderSync(e,t){if(!(e instanceof x1))return t;if(e.element){let i=e.element.drawOrder;e.element.drawOrder=t++,e.element._batchGroupId>=0&&i!==e.element.drawOrder&&this.system.app.batcher?.markGroupDirty(e.element._batchGroupId);}e.particlesystem&&(e.particlesystem.drawOrder=t++);let i=e.children;for(let e=0;e<i.length;e++)t=this._recurseDrawOrderSync(i[e],t);return t}_processDrawOrderSync(){this._recurseDrawOrderSync(this.entity,1),this.fire("syncdraworder");}_calcProjectionMatrix(){let e=this._resolution.x/this.scale,t=this._resolution.y/this.scale;this._screenMatrix.setOrtho(0,e,-t,0,1,-1),this._screenSpace||(wr.setScale(.5*e,.5*t,1),this._screenMatrix.mul2(wr,this._screenMatrix));}_updateScale(){this.scale=this._calcScale(this._resolution,this.referenceResolution);}_calcScale(e,t){let i=Math.log2((e.x||1)/t.x),s=Math.log2((e.y||1)/t.y);return Math.pow(2,i*(1-this._scaleBlend)+s*this._scaleBlend)}_onResize(e,t){this._screenSpace&&(this._resolution.set(e,t),this.resolution=this._resolution);}_bindElement(e){this._elements.add(e);}_unbindElement(e){this._elements.delete(e);}onRemove(){this.system.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.fire("remove"),this._elements.forEach(e=>e._onScreenRemove()),this._elements.clear(),this.off();}set resolution(e){this._screenSpace?this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height):this._resolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:resolution",this._resolution),this._elements.forEach(e=>e._onScreenResize(this._resolution));}get resolution(){return this._resolution}set referenceResolution(e){this._referenceResolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:referenceresolution",this._resolution),this._elements.forEach(e=>e._onScreenResize(this._resolution));}get referenceResolution(){return this._scaleMode===wi?this._resolution:this._referenceResolution}set screenSpace(e){this._screenSpace=e,this._screenSpace&&this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height),this.resolution=this._resolution,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:screenspace",this._screenSpace),this._elements.forEach(e=>e._onScreenSpaceChange());}get screenSpace(){return this._screenSpace}set scaleMode(e){e!==wi&&e!==ws&&(e=wi),this._screenSpace||e===wi||(e=wi),this._scaleMode=e,this.resolution=this._resolution,this.fire("set:scalemode",this._scaleMode);}get scaleMode(){return this._scaleMode}set scaleBlend(e){this._scaleBlend=e,this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:scaleblend",this._scaleBlend),this._elements.forEach(e=>e._onScreenResize(this._resolution));}get scaleBlend(){return this._scaleBlend}set priority(e){e>255&&(e=255),this._priority!==e&&(this._priority=e,this.syncDrawOrder());}get priority(){return this._priority}}class wn{constructor(){this.enabled=true;}}let wo=["enabled"];class wl extends Tm{constructor(e){super(e),this.id="screen",this.ComponentType=wa,this.DataType=wn,this.schema=wo,this.windowResolution=new eN,this._drawOrderSyncQueue=new el,this.app.graphicsDevice.on("resizecanvas",this._onResize,this),this.app.systems.on("update",this._onUpdate,this),this.on("beforeremove",this.onRemoveComponent,this);}initializeComponentData(e,t,i){ void 0!==t.priority&&(e.priority=t.priority),void 0!==t.screenSpace&&(e.screenSpace=t.screenSpace),e.cull=e.screenSpace,void 0!==t.scaleMode&&(e.scaleMode=t.scaleMode),void 0!==t.scaleBlend&&(e.scaleBlend=t.scaleBlend),void 0!==t.resolution&&(t.resolution instanceof eN?e._resolution.copy(t.resolution):e._resolution.set(t.resolution[0],t.resolution[1]),e.resolution=e._resolution),void 0!==t.referenceResolution&&(t.referenceResolution instanceof eN?e._referenceResolution.copy(t.referenceResolution):e._referenceResolution.set(t.referenceResolution[0],t.referenceResolution[1]),e.referenceResolution=e._referenceResolution),e.syncDrawOrder(),super.initializeComponentData(e,t,wo);}destroy(){super.destroy(),this.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.app.systems.off("update",this._onUpdate,this);}_onUpdate(e){let t=this.store;for(let i in t)t[i].entity.screen.update&&t[i].entity.screen.update(e);}_onResize(e,t){this.windowResolution.x=e,this.windowResolution.y=t;}cloneComponent(e,t){let i=e.screen;return this.addComponent(t,{enabled:i.enabled,screenSpace:i.screenSpace,scaleMode:i.scaleMode,resolution:i.resolution.clone(),referenceResolution:i.referenceResolution.clone()})}onRemoveComponent(e,t){t.onRemove();}processDrawOrderSyncQueue(){let e=this._drawOrderSyncQueue.list();for(let t=0;t<e.length;t++){let i=e[t];i.callback.call(i.scope);}this._drawOrderSyncQueue.clear();}queueDrawOrderSync(e,t,i){this._drawOrderSyncQueue.list().length||this.app.once("prerender",this.processDrawOrderSyncQueue,this),this._drawOrderSyncQueue.has(e)||this._drawOrderSyncQueue.push(e,{callback:t,scope:i});}}Tp._buildAccessors(wa.prototype,wo);let wh=new eN,wc=new eM,wd=new e1,wu=new eJ,wf=new eM,wp=new eM,wm=new eH,w_={x:"y",y:"x"};class wg extends eo{static{this.EVENT_DRAGSTART="drag:start";}static{this.EVENT_DRAGEND="drag:end";}static{this.EVENT_DRAGMOVE="drag:move";}constructor(e,t){if(super(),!e||!(e instanceof A4))throw Error("Element was null or not an ElementComponent");if(t&&"x"!==t&&"y"!==t)throw Error(`Unrecognized axis: ${t}`);this._element=e,this._app=e.system.app,this._axis=t||null,this._enabled=true,this._dragScale=new eM,this._dragStartMousePosition=new eM,this._dragStartHandlePosition=new eM,this._deltaMousePosition=new eM,this._deltaHandlePosition=new eM,this._isDragging=false,this._toggleLifecycleListeners("on");}_toggleLifecycleListeners(e){this._element[e]("mousedown",this._onMouseDownOrTouchStart,this),this._element[e]("touchstart",this._onMouseDownOrTouchStart,this),this._element[e]("selectstart",this._onMouseDownOrTouchStart,this);}_toggleDragListeners(e){let t="on"===e;this._hasDragListeners&&t||(this._app.mouse&&(this._element[e]("mousemove",this._onMove,this),this._element[e]("mouseup",this._onMouseUpOrTouchEnd,this)),ee.touch&&(this._element[e]("touchmove",this._onMove,this),this._element[e]("touchend",this._onMouseUpOrTouchEnd,this),this._element[e]("touchcancel",this._onMouseUpOrTouchEnd,this)),this._element[e]("selectmove",this._onMove,this),this._element[e]("selectend",this._onMouseUpOrTouchEnd,this),this._hasDragListeners=t);}_onMouseDownOrTouchStart(e){if(this._element&&!this._isDragging&&this.enabled){this._dragCamera=e.camera,this._calculateDragScale();let t=this._screenToLocal(e);t&&(this._toggleDragListeners("on"),this._isDragging=true,this._dragStartMousePosition.copy(t),this._dragStartHandlePosition.copy(this._element.entity.getLocalPosition()),this.fire("drag:start"));}}_onMouseUpOrTouchEnd(){this._isDragging&&(this._isDragging=false,this._toggleDragListeners("off"),this.fire("drag:end"));}_screenToLocal(e){return (e.inputSource?wd.set(e.inputSource.getOrigin(),e.inputSource.getDirection()):(this._determineInputPosition(e),this._chooseRayOriginAndDirection()),wf.copy(this._element.entity.forward).mulScalar(-1),wu.setFromPointNormal(this._element.entity.getPosition(),wf),wu.intersectsRay(wd,wp))?(wm.copy(this._element.entity.getRotation()).invert().transformVector(wp,wp),wp.mul(this._dragScale),wp):null}_determineInputPosition(e){let t=this._app.graphicsDevice.maxPixelRatio;void 0!==e.x&&void 0!==e.y?(wh.x=e.x*t,wh.y=e.y*t):e.changedTouches&&(wh.x=e.changedTouches[0].x*t,wh.y=e.changedTouches[0].y*t);}_chooseRayOriginAndDirection(){this._element.screen&&this._element.screen.screen.screenSpace?(wd.origin.set(wh.x,-wh.y,0),wd.direction.copy(eM.FORWARD)):(wc.copy(this._dragCamera.screenToWorld(wh.x,wh.y,1)),wd.origin.copy(this._dragCamera.entity.getPosition()),wd.direction.copy(wc).sub(wd.origin).normalize());}_calculateDragScale(){let e=this._element.entity.parent,t=this._element.screen&&this._element.screen.screen,i=t&&t.screenSpace,s=i?t.scale:1,r=this._dragScale;for(r.set(s,s,s);e&&(r.mul(e.getLocalScale()),e=e.parent,!i||!e.screen););r.x=1/r.x,r.y=1/r.y,r.z=0;}_onMove(e){let{_element:t,_deltaMousePosition:i,_deltaHandlePosition:s,_axis:r}=this;if(t&&this._isDragging&&this.enabled&&t.enabled&&t.entity.enabled){let a=this._screenToLocal(e);if(a){if(i.sub2(a,this._dragStartMousePosition),s.add2(this._dragStartHandlePosition,i),r){let e=t.entity.getLocalPosition(),i=w_[r];s[i]=e[i];}t.entity.setLocalPosition(s),this.fire("drag:move",s);}}}destroy(){this._toggleLifecycleListeners("off"),this._toggleDragListeners("off");}set enabled(e){this._enabled=e;}get enabled(){return this._enabled}get isDragging(){return this._isDragging}}let wv=0,wS=1,wy=2,wx=0,wT=1,wE=new eN;class wA extends Tp{static{this.EVENT_SETSCROLL="set:scroll";}constructor(e,t){super(e,t),this._viewportEntity=null,this._contentEntity=null,this._horizontalScrollbarEntity=null,this._verticalScrollbarEntity=null,this._evtElementRemove=null,this._evtViewportElementRemove=null,this._evtViewportResize=null,this._evtContentEntityElementAdd=null,this._evtContentElementRemove=null,this._evtContentResize=null,this._evtHorizontalScrollbarAdd=null,this._evtHorizontalScrollbarRemove=null,this._evtHorizontalScrollbarValue=null,this._evtVerticalScrollbarAdd=null,this._evtVerticalScrollbarRemove=null,this._evtVerticalScrollbarValue=null,this._scrollbarUpdateFlags={},this._scrollbarEntities={},this._prevContentSizes={},this._prevContentSizes[pG]=null,this._prevContentSizes[pH]=null,this._scroll=new eN,this._velocity=new eM,this._dragStartPosition=new eM,this._disabledContentInput=false,this._disabledContentInputEntities=[],this._toggleLifecycleListeners("on"),this._toggleElementListeners("on");}get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){this._setValue("enabled",e);}get enabled(){return this.data.enabled}set horizontal(e){this._setValue("horizontal",e);}get horizontal(){return this.data.horizontal}set vertical(e){this._setValue("vertical",e);}get vertical(){return this.data.vertical}set scrollMode(e){this._setValue("scrollMode",e);}get scrollMode(){return this.data.scrollMode}set bounceAmount(e){this._setValue("bounceAmount",e);}get bounceAmount(){return this.data.bounceAmount}set friction(e){this._setValue("friction",e);}get friction(){return this.data.friction}set dragThreshold(e){this._setValue("dragThreshold",e);}get dragThreshold(){return this.data.dragThreshold}set useMouseWheel(e){this._setValue("useMouseWheel",e);}get useMouseWheel(){return this.data.useMouseWheel}set mouseWheelSensitivity(e){this._setValue("mouseWheelSensitivity",e);}get mouseWheelSensitivity(){return this.data.mouseWheelSensitivity}set horizontalScrollbarVisibility(e){this._setValue("horizontalScrollbarVisibility",e);}get horizontalScrollbarVisibility(){return this.data.horizontalScrollbarVisibility}set verticalScrollbarVisibility(e){this._setValue("verticalScrollbarVisibility",e);}get verticalScrollbarVisibility(){return this.data.verticalScrollbarVisibility}set viewportEntity(e){if(this._viewportEntity===e)return;let t="string"==typeof e;(!this._viewportEntity||!t||this._viewportEntity.getGuid()!==e)&&(this._viewportEntity&&this._viewportEntityUnsubscribe(),e instanceof _c?this._viewportEntity=e:t?this._viewportEntity=this.system.app.getEntityFromIndex(e)||null:this._viewportEntity=null,this._viewportEntity&&this._viewportEntitySubscribe(),this._viewportEntity?this.data.viewportEntity=this._viewportEntity.getGuid():t&&e&&(this.data.viewportEntity=e));}get viewportEntity(){return this._viewportEntity}set contentEntity(e){if(this._contentEntity===e)return;let t="string"==typeof e;(!this._contentEntity||!t||this._contentEntity.getGuid()!==e)&&(this._contentEntity&&this._contentEntityUnsubscribe(),e instanceof _c?this._contentEntity=e:t?this._contentEntity=this.system.app.getEntityFromIndex(e)||null:this._contentEntity=null,this._contentEntity&&this._contentEntitySubscribe(),this._contentEntity?this.data.contentEntity=this._contentEntity.getGuid():t&&e&&(this.data.contentEntity=e));}get contentEntity(){return this._contentEntity}set horizontalScrollbarEntity(e){if(this._horizontalScrollbarEntity===e)return;let t="string"==typeof e;(!this._horizontalScrollbarEntity||!t||this._horizontalScrollbarEntity.getGuid()!==e)&&(this._horizontalScrollbarEntity&&this._horizontalScrollbarEntityUnsubscribe(),e instanceof _c?this._horizontalScrollbarEntity=e:t?this._horizontalScrollbarEntity=this.system.app.getEntityFromIndex(e)||null:this._horizontalScrollbarEntity=null,this._scrollbarEntities[pG]=this._horizontalScrollbarEntity,this._horizontalScrollbarEntity&&this._horizontalScrollbarEntitySubscribe(),this._horizontalScrollbarEntity?this.data.horizontalScrollbarEntity=this._horizontalScrollbarEntity.getGuid():t&&e&&(this.data.horizontalScrollbarEntity=e));}get horizontalScrollbarEntity(){return this._horizontalScrollbarEntity}set verticalScrollbarEntity(e){if(this._verticalScrollbarEntity===e)return;let t="string"==typeof e;(!this._verticalScrollbarEntity||!t||this._verticalScrollbarEntity.getGuid()!==e)&&(this._verticalScrollbarEntity&&this._verticalScrollbarEntityUnsubscribe(),e instanceof _c?this._verticalScrollbarEntity=e:t?this._verticalScrollbarEntity=this.system.app.getEntityFromIndex(e)||null:this._verticalScrollbarEntity=null,this._scrollbarEntities[pH]=this._verticalScrollbarEntity,this._verticalScrollbarEntity&&this._verticalScrollbarEntitySubscribe(),this._verticalScrollbarEntity?this.data.verticalScrollbarEntity=this._verticalScrollbarEntity.getGuid():t&&e&&(this.data.verticalScrollbarEntity=e));}get verticalScrollbarEntity(){return this._verticalScrollbarEntity}set scroll(e){this._onSetScroll(e.x,e.y);}get scroll(){return this._scroll}_setValue(e,t){let i=this.data,s=i[e];i[e]=t,this.fire("set",e,s,t);}_toggleLifecycleListeners(e){this[e]("set_horizontal",this._onSetHorizontalScrollingEnabled,this),this[e]("set_vertical",this._onSetVerticalScrollingEnabled,this),this.entity[e]("element:add",this._onElementComponentAdd,this);}_toggleElementListeners(e){this.entity.element&&("on"===e&&this._hasElementListeners||(this.entity.element[e]("resize",this._syncAll,this),this.entity.element[e]("mousewheel",this._onMouseWheel,this),this._hasElementListeners="on"===e));}_onElementComponentAdd(e){this._evtElementRemove=this.entity.element.once("beforeremove",this._onElementComponentRemove,this),this._toggleElementListeners("on");}_onElementComponentRemove(e){this._evtElementRemove?.off(),this._evtElementRemove=null,this._toggleElementListeners("off");}_viewportEntitySubscribe(){this._evtViewportEntityElementAdd=this._viewportEntity.on("element:add",this._onViewportElementGain,this),this._viewportEntity.element&&this._onViewportElementGain();}_viewportEntityUnsubscribe(){this._evtViewportEntityElementAdd?.off(),this._evtViewportEntityElementAdd=null,this._viewportEntity?.element&&this._onViewportElementLose();}_viewportEntityElementSubscribe(){let e=this._viewportEntity.element;this._evtViewportElementRemove=e.once("beforeremove",this._onViewportElementLose,this),this._evtViewportResize=e.on("resize",this._syncAll,this);}_viewportEntityElementUnsubscribe(){this._evtViewportElementRemove?.off(),this._evtViewportElementRemove=null,this._evtViewportResize?.off(),this._evtViewportResize=null;}_onViewportElementGain(){this._viewportEntityElementSubscribe(),this._syncAll();}_onViewportElementLose(){this._viewportEntityElementUnsubscribe();}_contentEntitySubscribe(){this._evtContentEntityElementAdd=this._contentEntity.on("element:add",this._onContentElementGain,this),this._contentEntity.element&&this._onContentElementGain();}_contentEntityUnsubscribe(){this._evtContentEntityElementAdd?.off(),this._evtContentEntityElementAdd=null,this._contentEntity?.element&&this._onContentElementLose();}_contentEntityElementSubscribe(){let e=this._contentEntity.element;this._evtContentElementRemove=e.once("beforeremove",this._onContentElementLose,this),this._evtContentResize=e.on("resize",this._syncAll,this);}_contentEntityElementUnsubscribe(){this._evtContentElementRemove?.off(),this._evtContentElementRemove=null,this._evtContentResize?.off(),this._evtContentResize=null;}_onContentElementGain(){this._contentEntityElementSubscribe(),this._destroyDragHelper(),this._contentDragHelper=new wg(this._contentEntity.element),this._contentDragHelper.on("drag:start",this._onContentDragStart,this),this._contentDragHelper.on("drag:end",this._onContentDragEnd,this),this._contentDragHelper.on("drag:move",this._onContentDragMove,this),this._prevContentSizes[pG]=null,this._prevContentSizes[pH]=null,this._syncAll();}_onContentElementLose(){this._contentEntityElementUnsubscribe(),this._destroyDragHelper();}_onContentDragStart(){this._contentEntity&&this.enabled&&this.entity.enabled&&this._dragStartPosition.copy(this._contentEntity.getLocalPosition());}_onContentDragEnd(){this._prevContentDragPosition=null,this._enableContentInput();}_onContentDragMove(e){if(this._contentEntity&&this.enabled&&this.entity.enabled&&(this._wasDragged=true,this._setScrollFromContentPosition(e),this._setVelocityFromContentPositionDelta(e),!this._disabledContentInput)){let t=e.x-this._dragStartPosition.x,i=e.y-this._dragStartPosition.y;(Math.abs(t)>this.dragThreshold||Math.abs(i)>this.dragThreshold)&&this._disableContentInput();}}_horizontalScrollbarEntitySubscribe(){this._evtHorizontalScrollbarAdd=this._horizontalScrollbarEntity.on("scrollbar:add",this._onHorizontalScrollbarGain,this),this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarGain();}_verticalScrollbarEntitySubscribe(){this._evtVerticalScrollbarAdd=this._verticalScrollbarEntity.on("scrollbar:add",this._onVerticalScrollbarGain,this),this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarGain();}_horizontalScrollbarEntityUnsubscribe(){this._evtHorizontalScrollbarAdd?.off(),this._evtHorizontalScrollbarAdd=null,this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarLose();}_verticalScrollbarEntityUnsubscribe(){this._evtVerticalScrollbarAdd?.off(),this._evtVerticalScrollbarAdd=null,this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarLose();}_onSetHorizontalScrollbarValue(e){!this._scrollbarUpdateFlags[pG]&&this.enabled&&this.entity.enabled&&this._onSetScroll(e,null);}_onSetVerticalScrollbarValue(e){!this._scrollbarUpdateFlags[pH]&&this.enabled&&this.entity.enabled&&this._onSetScroll(null,e);}_onHorizontalScrollbarGain(){let e=this._horizontalScrollbarEntity?.scrollbar;this._evtHorizontalScrollbarRemove=e.on("beforeremove",this._onHorizontalScrollbarLose,this),this._evtHorizontalScrollbarValue=e.on("set:value",this._onSetHorizontalScrollbarValue,this),this._syncScrollbarEnabledState(pG),this._syncScrollbarPosition(pG);}_onVerticalScrollbarGain(){let e=this._verticalScrollbarEntity?.scrollbar;this._evtVerticalScrollbarRemove=e.on("beforeremove",this._onVerticalScrollbarLose,this),this._evtVerticalScrollbarValue=e.on("set:value",this._onSetVerticalScrollbarValue,this),this._syncScrollbarEnabledState(pH),this._syncScrollbarPosition(pH);}_onHorizontalScrollbarLose(){this._evtHorizontalScrollbarRemove?.off(),this._evtHorizontalScrollbarRemove=null,this._evtHorizontalScrollbarValue?.off(),this._evtHorizontalScrollbarValue=null;}_onVerticalScrollbarLose(){this._evtVerticalScrollbarRemove?.off(),this._evtVerticalScrollbarRemove=null,this._evtVerticalScrollbarValue?.off(),this._evtVerticalScrollbarValue=null;}_onSetHorizontalScrollingEnabled(){this._syncScrollbarEnabledState(pG);}_onSetVerticalScrollingEnabled(){this._syncScrollbarEnabledState(pH);}_onSetScroll(e,t,i){ false!==i&&this._velocity.set(0,0,0);let s=this._updateAxis(e,"x",pG),r=this._updateAxis(t,"y",pH);(s||r)&&this.fire("set:scroll",this._scroll);}_updateAxis(e,t,i){let s=null!==e&&Math.abs(e-this._scroll[t])>1e-5;return (s||this._isDragging()||0===e)&&(this._scroll[t]=this._determineNewScrollValue(e,t,i),this._syncContentPosition(i),this._syncScrollbarPosition(i)),s}_determineNewScrollValue(e,t,i){if(!this._getScrollingEnabled(i))return this._scroll[t];switch(this.scrollMode){case wv:return eA.clamp(e,0,this._getMaxScrollValue(i));case wS:return this._setVelocityFromOvershoot(e,t,i),e;default:return e}}_syncAll(){this._syncContentPosition(pG),this._syncContentPosition(pH),this._syncScrollbarPosition(pG),this._syncScrollbarPosition(pH),this._syncScrollbarEnabledState(pG),this._syncScrollbarEnabledState(pH);}_syncContentPosition(e){if(!this._contentEntity)return;let t=this._getAxis(e),i=this._getSign(e),s=this._prevContentSizes[e],r=this._getContentSize(e);if(null!==s&&Math.abs(s-r)>1e-4){let i=this._getMaxOffset(e,s),a=this._getMaxOffset(e,r);0===a?this._scroll[t]=1:this._scroll[t]=eA.clamp(this._scroll[t]*i/a,0,1);}let a=this._scroll[t]*this._getMaxOffset(e),n=this._contentEntity.getLocalPosition();n[t]=a*i,this._contentEntity.setLocalPosition(n),this._prevContentSizes[e]=r;}_syncScrollbarPosition(e){let t=this._scrollbarEntities[e];if(!t?.scrollbar)return;let i=this._getAxis(e);this._scrollbarUpdateFlags[e]=true,t.scrollbar.value=this._scroll[i],t.scrollbar.handleSize=this._getScrollbarHandleSize(i,e),this._scrollbarUpdateFlags[e]=false;}_syncScrollbarEnabledState(e){let t=this._scrollbarEntities[e];if(!t)return;let i=this._getScrollingEnabled(e);switch(this._getScrollbarVisibility(e)){case wx:t.enabled=i;return;case wT:t.enabled=i&&this._contentIsLargerThanViewport(e);return;default:t.enabled=i;}}_contentIsLargerThanViewport(e){return this._getContentSize(e)>this._getViewportSize(e)}_contentPositionToScrollValue(e){let t=this._getMaxOffset(pG),i=this._getMaxOffset(pH);return 0===t?wE.x=0:wE.x=e.x/t,0===i?wE.y=0:wE.y=-(e.y/i),wE}_getMaxOffset(e,t){t=void 0===t?this._getContentSize(e):t;let i=this._getViewportSize(e);return t<i?-this._getViewportSize(e):i-t}_getMaxScrollValue(e){return +!!this._contentIsLargerThanViewport(e)}_getScrollbarHandleSize(e,t){let i=this._getViewportSize(t),s=this._getContentSize(t);if(.001>Math.abs(s))return 1;let r=Math.min(i/s,1),a=this._toOvershoot(this._scroll[e],t);return 0===a?r:r/(1+Math.abs(a))}_getViewportSize(e){return this._getSize(e,this._viewportEntity)}_getContentSize(e){return this._getSize(e,this._contentEntity)}_getSize(e,t){return t?.element?t.element[this._getCalculatedDimension(e)]:0}_getScrollingEnabled(e){return e===pG?this.horizontal:e===pH?this.vertical:void 0}_getScrollbarVisibility(e){return e===pG?this.horizontalScrollbarVisibility:e===pH?this.verticalScrollbarVisibility:void 0}_getSign(e){return e===pG?1:-1}_getAxis(e){return e===pG?"x":"y"}_getCalculatedDimension(e){return e===pG?"calculatedWidth":"calculatedHeight"}_destroyDragHelper(){this._contentDragHelper&&this._contentDragHelper.destroy();}onUpdate(){this._contentEntity&&(this._updateVelocity(),this._syncScrollbarEnabledState(pG),this._syncScrollbarEnabledState(pH));}_updateVelocity(){if(!this._isDragging()){if(this.scrollMode===wS&&(this._hasOvershoot("x",pG)&&this._setVelocityFromOvershoot(this.scroll.x,"x",pG),this._hasOvershoot("y",pH)&&this._setVelocityFromOvershoot(this.scroll.y,"y",pH)),Math.abs(this._velocity.x)>1e-4||Math.abs(this._velocity.y)>1e-4){let e=this._contentEntity.getLocalPosition();e.x+=this._velocity.x,e.y+=this._velocity.y,this._contentEntity.setLocalPosition(e),this._setScrollFromContentPosition(e);}this._velocity.x*=1-this.friction,this._velocity.y*=1-this.friction;}}_hasOvershoot(e,t){return Math.abs(this._toOvershoot(this.scroll[e],t))>.001}_toOvershoot(e,t){let i=this._getMaxScrollValue(t);return e<0?e:e>i?e-i:0}_setVelocityFromOvershoot(e,t,i){let s=this._toOvershoot(e,i)*this._getMaxOffset(i)*this._getSign(i);Math.abs(s)>0&&(this._velocity[t]=-s/(50*this.bounceAmount+1));}_setVelocityFromContentPositionDelta(e){this._prevContentDragPosition?(this._velocity.sub2(e,this._prevContentDragPosition),this._prevContentDragPosition.copy(e)):(this._velocity.set(0,0,0),this._prevContentDragPosition=e.clone());}_setScrollFromContentPosition(e){let t=this._contentPositionToScrollValue(e);this._isDragging()&&(t=this._applyScrollValueTension(t)),this._onSetScroll(t.x,t.y,false);}_applyScrollValueTension(e){let t=this._getMaxScrollValue(pG),i=this._toOvershoot(e.x,pG);return i>0?e.x=t+ +Math.log10(1+i):i<0&&(e.x=-1*Math.log10(1-i)),t=this._getMaxScrollValue(pH),(i=this._toOvershoot(e.y,pH))>0?e.y=t+ +Math.log10(1+i):i<0&&(e.y=-1*Math.log10(1-i)),e}_isDragging(){return this._contentDragHelper&&this._contentDragHelper.isDragging}_setScrollbarComponentsEnabled(e){this._horizontalScrollbarEntity?.scrollbar&&(this._horizontalScrollbarEntity.scrollbar.enabled=e),this._verticalScrollbarEntity?.scrollbar&&(this._verticalScrollbarEntity.scrollbar.enabled=e);}_setContentDraggingEnabled(e){this._contentDragHelper&&(this._contentDragHelper.enabled=e);}_onMouseWheel(e){if(!this.useMouseWheel||!this._contentEntity?.element)return;let t=e.event,i=t.deltaX/this._contentEntity.element.calculatedWidth*this.mouseWheelSensitivity.x,s=t.deltaY/this._contentEntity.element.calculatedHeight*this.mouseWheelSensitivity.y,r=eA.clamp(this._scroll.x+i,0,this._getMaxScrollValue(pG)),a=eA.clamp(this._scroll.y+s,0,this._getMaxScrollValue(pH));this.scroll=new eN(r,a);}_enableContentInput(){for(;this._disabledContentInputEntities.length;){let e=this._disabledContentInputEntities.pop();e.element&&(e.element.useInput=true);}this._disabledContentInput=false;}_disableContentInput(){let e=t=>{t.element&&t.element.useInput&&(this._disabledContentInputEntities.push(t),t.element.useInput=false);let i=t.children;for(let t=0,s=i.length;t<s;t++)e(i[t]);};if(this._contentEntity){let t=this._contentEntity.children;for(let i=0,s=t.length;i<s;i++)e(t[i]);}this._disabledContentInput=true;}onEnable(){this._setScrollbarComponentsEnabled(true),this._setContentDraggingEnabled(true),this._syncAll();}onDisable(){this._setScrollbarComponentsEnabled(false),this._setContentDraggingEnabled(false);}onRemove(){this._toggleLifecycleListeners("off"),this._toggleElementListeners("off"),this._destroyDragHelper();}resolveDuplicatedEntityReferenceProperties(e,t){e.viewportEntity&&(this.viewportEntity=t[e.viewportEntity.getGuid()]),e.contentEntity&&(this.contentEntity=t[e.contentEntity.getGuid()]),e.horizontalScrollbarEntity&&(this.horizontalScrollbarEntity=t[e.horizontalScrollbarEntity.getGuid()]),e.verticalScrollbarEntity&&(this.verticalScrollbarEntity=t[e.verticalScrollbarEntity.getGuid()]);}}class wb{constructor(){this.enabled=true,this.dragThreshold=10,this.useMouseWheel=true,this.mouseWheelSensitivity=new eN(1,1),this.horizontalScrollbarVisibility=0,this.verticalScrollbarVisibility=0,this.viewportEntity=null,this.contentEntity=null,this.horizontalScrollbarEntity=null,this.verticalScrollbarEntity=null;}}let ww=[{name:"enabled",type:"boolean"},{name:"horizontal",type:"boolean"},{name:"vertical",type:"boolean"},{name:"scrollMode",type:"number"},{name:"bounceAmount",type:"number"},{name:"friction",type:"number"},{name:"dragThreshold",type:"number"},{name:"useMouseWheel",type:"boolean"},{name:"mouseWheelSensitivity",type:"vec2"},{name:"horizontalScrollbarVisibility",type:"number"},{name:"verticalScrollbarVisibility",type:"number"}];class wC extends Tm{constructor(e){super(e),this.id="scrollview",this.ComponentType=wA,this.DataType=wb,this.schema=ww,this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("update",this.onUpdate,this);}initializeComponentData(e,t,i){ void 0===t.dragThreshold&&(t.dragThreshold=10),void 0===t.useMouseWheel&&(t.useMouseWheel=true),void 0===t.mouseWheelSensitivity&&(t.mouseWheelSensitivity=new eN(1,1)),super.initializeComponentData(e,t,ww),e.viewportEntity=t.viewportEntity,e.contentEntity=t.contentEntity,e.horizontalScrollbarEntity=t.horizontalScrollbarEntity,e.verticalScrollbarEntity=t.verticalScrollbarEntity;}onUpdate(e){let t=this.store;for(let e in t){let i=t[e].entity,s=i.scrollview;s.enabled&&i.enabled&&s.onUpdate();}}_onRemoveComponent(e,t){t.onRemove();}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this);}}class wP extends Tp{static{this.EVENT_SETVALUE="set:value";}constructor(e,t){super(e,t),this._handleEntity=null,this._evtHandleEntityElementAdd=null,this._evtHandleEntityChanges=[],this._toggleLifecycleListeners("on");}get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){this._setValue("enabled",e);}get enabled(){return this.data.enabled}set orientation(e){this._setValue("orientation",e);}get orientation(){return this.data.orientation}set value(e){this._setValue("value",e);}get value(){return this.data.value}set handleSize(e){this._setValue("handleSize",e);}get handleSize(){return this.data.handleSize}set handleEntity(e){if(this._handleEntity===e)return;let t="string"==typeof e;(!this._handleEntity||!t||this._handleEntity.getGuid()!==e)&&(this._handleEntity&&this._handleEntityUnsubscribe(),e instanceof _c?this._handleEntity=e:t?this._handleEntity=this.system.app.getEntityFromIndex(e)||null:this._handleEntity=null,this._handleEntity&&this._handleEntitySubscribe(),this._handleEntity?this.data.handleEntity=this._handleEntity.getGuid():t&&e&&(this.data.handleEntity=e));}get handleEntity(){return this._handleEntity}_setValue(e,t){let i=this.data,s=i[e];i[e]=t,this.fire("set",e,s,t);}_toggleLifecycleListeners(e){this[e]("set_value",this._onSetValue,this),this[e]("set_handleSize",this._onSetHandleSize,this),this[e]("set_orientation",this._onSetOrientation,this);}_handleEntitySubscribe(){this._evtHandleEntityElementAdd=this._handleEntity.on("element:add",this._onHandleElementGain,this),this._handleEntity.element&&this._onHandleElementGain();}_handleEntityUnsubscribe(){this._evtHandleEntityElementAdd?.off(),this._evtHandleEntityElementAdd=null,this._handleEntity?.element&&this._onHandleElementLose();}_handleEntityElementSubscribe(){let e=this._handleEntity.element,t=this._evtHandleEntityChanges;t.push(e.once("beforeremove",this._onHandleElementLose,this)),t.push(e.on("set:anchor",this._onSetHandleAlignment,this)),t.push(e.on("set:margin",this._onSetHandleAlignment,this)),t.push(e.on("set:pivot",this._onSetHandleAlignment,this));}_handleEntityElementUnsubscribe(){for(let e=0;e<this._evtHandleEntityChanges.length;e++)this._evtHandleEntityChanges[e].off();this._evtHandleEntityChanges.length=0;}_onHandleElementGain(){this._handleEntityElementSubscribe(),this._destroyDragHelper(),this._handleDragHelper=new wg(this._handleEntity.element,this._getAxis()),this._handleDragHelper.on("drag:move",this._onHandleDrag,this),this._updateHandlePositionAndSize();}_onHandleElementLose(){this._handleEntityElementUnsubscribe(),this._destroyDragHelper();}_onHandleDrag(e){this._handleEntity&&this.enabled&&this.entity.enabled&&(this.value=this._handlePositionToScrollValue(e[this._getAxis()]));}_onSetValue(e,t,i){Math.abs(i-t)>1e-5&&(this.data.value=eA.clamp(i,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this.data.value));}_onSetHandleSize(e,t,i){Math.abs(i-t)>1e-5&&(this.data.handleSize=eA.clamp(i,0,1),this._updateHandlePositionAndSize());}_onSetHandleAlignment(){this._updateHandlePositionAndSize();}_onSetOrientation(e,t,i){i!==t&&this._handleEntity?.element&&(this._handleEntity.element[this._getOppositeDimension()]=0);}_updateHandlePositionAndSize(){let e=this._handleEntity,t=e?.element;if(e){let t=e.getLocalPosition();t[this._getAxis()]=this._getHandlePosition(),e.setLocalPosition(t);}t&&(t[this._getDimension()]=this._getHandleLength());}_handlePositionToScrollValue(e){return e*this._getSign()/this._getUsableTrackLength()}_scrollValueToHandlePosition(e){return e*this._getSign()*this._getUsableTrackLength()}_getUsableTrackLength(){return Math.max(this._getTrackLength()-this._getHandleLength(),.001)}_getTrackLength(){return this.entity.element?this.orientation===pG?this.entity.element.calculatedWidth:this.entity.element.calculatedHeight:0}_getHandleLength(){return this._getTrackLength()*this.handleSize}_getHandlePosition(){return this._scrollValueToHandlePosition(this.value)}_getSign(){return this.orientation===pG?1:-1}_getAxis(){return this.orientation===pG?"x":"y"}_getDimension(){return this.orientation===pG?"width":"height"}_getOppositeDimension(){return this.orientation===pG?"height":"width"}_destroyDragHelper(){this._handleDragHelper&&this._handleDragHelper.destroy();}_setHandleDraggingEnabled(e){this._handleDragHelper&&(this._handleDragHelper.enabled=e);}onEnable(){this._setHandleDraggingEnabled(true);}onDisable(){this._setHandleDraggingEnabled(false);}onRemove(){this._destroyDragHelper(),this._toggleLifecycleListeners("off");}resolveDuplicatedEntityReferenceProperties(e,t){e.handleEntity&&(this.handleEntity=t[e.handleEntity.getGuid()]);}}class wL{constructor(){this.enabled=true,this.orientation=pG,this.value=0,this.handleSize=0,this.handleEntity=null;}}let wI=[{name:"enabled",type:"boolean"},{name:"orientation",type:"number"},{name:"value",type:"number"},{name:"handleSize",type:"number"}];class wD extends Tm{constructor(e){super(e),this.id="scrollbar",this.ComponentType=wP,this.DataType=wL,this.schema=wI,this.on("add",this._onAddComponent,this),this.on("beforeremove",this._onRemoveComponent,this);}initializeComponentData(e,t,i){super.initializeComponentData(e,t,wI),e.handleEntity=t.handleEntity;}_onAddComponent(e){e.fire("scrollbar:add");}_onRemoveComponent(e,t){t.onRemove();}}let wR={volume:0,pitch:0,loop:false,startTime:0,duration:0,position:new eM,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null};class wM extends eo{static{this.EVENT_PLAY="play";}static{this.EVENT_PAUSE="pause";}static{this.EVENT_RESUME="resume";}static{this.EVENT_STOP="stop";}static{this.EVENT_END="end";}static{this.EVENT_LOAD="load";}constructor(e,t="Untitled",i={}){super(),this.instances=[],this._component=e,this._assets=e.system.app.assets,this._manager=e.system.manager,this.name=t,this._volume=void 0!==i.volume?eA.clamp(Number(i.volume)||0,0,1):1,this._pitch=void 0!==i.pitch?Math.max(.01,Number(i.pitch)||0):1,this._loop=!!(void 0!==i.loop&&i.loop),this._duration=i.duration>0?i.duration:null,this._startTime=Math.max(0,Number(i.startTime)||0),this._overlap=!!i.overlap,this._autoPlay=!!i.autoPlay,this._firstNode=null,this._lastNode=null,this._asset=i.asset,this._asset instanceof xF&&(this._asset=this._asset.id),this._onInstancePlayHandler=this._onInstancePlay.bind(this),this._onInstancePauseHandler=this._onInstancePause.bind(this),this._onInstanceResumeHandler=this._onInstanceResume.bind(this),this._onInstanceStopHandler=this._onInstanceStop.bind(this),this._onInstanceEndHandler=this._onInstanceEnd.bind(this);}play(){if(this.overlap||this.stop(),!this.isLoaded&&!this._hasAsset())return;let e=this._createInstance();if(this.instances.push(e),this.isLoaded)e.play();else {let t=function(t){let i=e._playWhenLoaded;e.sound=t,i&&e.play();};this.off("load",t),this.once("load",t),this.load();}return e}pause(){let e=false,t=this.instances;for(let i=0,s=t.length;i<s;i++)t[i].pause()&&(e=true);return e}resume(){let e=false,t=this.instances;for(let i=0,s=t.length;i<s;i++)t[i].resume()&&(e=true);return e}stop(){let e=false,t=this.instances,i=t.length;for(;i--;)t[i].stop(),e=true;return t.length=0,e}load(){if(!this._hasAsset())return;let e=this._assets.get(this._asset);if(!e){this._assets.off(`add:${this._asset}`,this._onAssetAdd,this),this._assets.once(`add:${this._asset}`,this._onAssetAdd,this);return}if(e.off("remove",this._onAssetRemoved,this),e.on("remove",this._onAssetRemoved,this),!e.resource){e.off("load",this._onAssetLoad,this),e.once("load",this._onAssetLoad,this),this._assets.load(e);return}this.fire("load",e.resource);}setExternalNodes(e,t){if(e&&(t||(t=e),this._firstNode=e,this._lastNode=t,!this._overlap)){let i=this.instances;for(let s=0,r=i.length;s<r;s++)i[s].setExternalNodes(e,t);}}clearExternalNodes(){if(this._firstNode=null,this._lastNode=null,!this._overlap){let e=this.instances;for(let t=0,i=e.length;t<i;t++)e[t].clearExternalNodes();}}getExternalNodes(){return [this._firstNode,this._lastNode]}_hasAsset(){return null!=this._asset}_createInstance(){let e=null,t=this._component,i=null;if(this._hasAsset()){let e=this._assets.get(this._asset);e&&(i=e.resource);}return wR.volume=this._volume*t.volume,wR.pitch=this._pitch*t.pitch,wR.loop=this._loop,wR.startTime=this._startTime,wR.duration=this._duration,wR.onPlay=this._onInstancePlayHandler,wR.onPause=this._onInstancePauseHandler,wR.onResume=this._onInstanceResumeHandler,wR.onStop=this._onInstanceStopHandler,wR.onEnd=this._onInstanceEndHandler,t.positional?(wR.position.copy(t.entity.getPosition()),wR.maxDistance=t.maxDistance,wR.refDistance=t.refDistance,wR.rollOffFactor=t.rollOffFactor,wR.distanceModel=t.distanceModel,e=new ui(this._manager,i,wR)):e=new ut(this._manager,i,wR),this._firstNode&&e.setExternalNodes(this._firstNode,this._lastNode),e}_onInstancePlay(e){this.fire("play",e),this._component.fire("play",this,e);}_onInstancePause(e){this.fire("pause",e),this._component.fire("pause",this,e);}_onInstanceResume(e){this.fire("resume",e),this._component.fire("resume",this,e);}_onInstanceStop(e){let t=this.instances.indexOf(e);-1!==t&&this.instances.splice(t,1),this.fire("stop",e),this._component.fire("stop",this,e);}_onInstanceEnd(e){let t=this.instances.indexOf(e);-1!==t&&this.instances.splice(t,1),this.fire("end",e),this._component.fire("end",this,e);}_onAssetAdd(e){this.load();}_onAssetLoad(e){this.load();}_onAssetRemoved(e){e.off("remove",this._onAssetRemoved,this),this._assets.off(`add:${e.id}`,this._onAssetAdd,this),this.stop();}updatePosition(e){let t=this.instances;for(let i=0,s=t.length;i<s;i++)t[i].position=e;}set asset(e){let t=this._asset;if(t){this._assets.off(`add:${t}`,this._onAssetAdd,this);let e=this._assets.get(t);e&&e.off("remove",this._onAssetRemoved,this);}this._asset=e,this._asset instanceof xF&&(this._asset=this._asset.id),this._hasAsset()&&this._component.enabled&&this._component.entity.enabled&&this.load();}get asset(){return this._asset}set autoPlay(e){this._autoPlay=!!e;}get autoPlay(){return this._autoPlay}set duration(e){if(this._duration=Math.max(0,Number(e)||0)||null,!this._overlap){let e=this.instances;for(let t=0,i=e.length;t<i;t++)e[t].duration=this._duration;}}get duration(){let e=0;if(this._hasAsset()){let t=this._assets.get(this._asset);e=t?.resource?t.resource.duration:0;}return null!=this._duration?this._duration%(e||1):e}get isLoaded(){if(this._hasAsset()){let e=this._assets.get(this._asset);if(e)return !!e.resource}return false}get isPaused(){let e=this.instances,t=e.length;if(0===t)return false;for(let i=0;i<t;i++)if(!e[i].isPaused)return false;return true}get isPlaying(){let e=this.instances;for(let t=0,i=e.length;t<i;t++)if(e[t].isPlaying)return true;return false}get isStopped(){let e=this.instances;for(let t=0,i=e.length;t<i;t++)if(!e[t].isStopped)return false;return true}set loop(e){this._loop=!!e;let t=this.instances;for(let e=0,i=t.length;e<i;e++)t[e].loop=this._loop;}get loop(){return this._loop}set overlap(e){this._overlap=!!e;}get overlap(){return this._overlap}set pitch(e){if(this._pitch=Math.max(Number(e)||0,.01),!this._overlap){let e=this.instances;for(let t=0,i=e.length;t<i;t++)e[t].pitch=this.pitch*this._component.pitch;}}get pitch(){return this._pitch}set startTime(e){if(this._startTime=Math.max(0,Number(e)||0),!this._overlap){let e=this.instances;for(let t=0,i=e.length;t<i;t++)e[t].startTime=this._startTime;}}get startTime(){return this._startTime}set volume(e){if(this._volume=eA.clamp(Number(e)||0,0,1),!this._overlap){let e=this.instances;for(let t=0,i=e.length;t<i;t++)e[t].volume=this._volume*this._component.volume;}}get volume(){return this._volume}}class wO extends Tp{static{this.EVENT_PLAY="play";}static{this.EVENT_PAUSE="pause";}static{this.EVENT_RESUME="resume";}static{this.EVENT_STOP="stop";}static{this.EVENT_END="end";}_updateSoundInstances(e,t,i){let s=this._slots;for(let r in s){let a=s[r];if(!a.overlap){let s=a.instances;for(let r=0,n=s.length;r<n;r++)s[r][e]=i?a[e]*t:t;}}}set distanceModel(e){this._distanceModel=e,this._updateSoundInstances("distanceModel",e,false);}get distanceModel(){return this._distanceModel}set maxDistance(e){this._maxDistance=e,this._updateSoundInstances("maxDistance",e,false);}get maxDistance(){return this._maxDistance}set refDistance(e){this._refDistance=e,this._updateSoundInstances("refDistance",e,false);}get refDistance(){return this._refDistance}set rollOffFactor(e){this._rollOffFactor=e,this._updateSoundInstances("rollOffFactor",e,false);}get rollOffFactor(){return this._rollOffFactor}set pitch(e){this._pitch=e,this._updateSoundInstances("pitch",e,true);}get pitch(){return this._pitch}set volume(e){this._volume=e,this._updateSoundInstances("volume",e,true);}get volume(){return this._volume}set positional(e){this._positional=e;let t=this._slots;for(let e in t){let i=t[e];if(!i.overlap){let e=i.instances,t=e.length;for(let s=t-1;s>=0;s--){let t=e[s].isPlaying||e[s].isSuspended,r=e[s].currentTime;t&&e[s].stop();let a=i._createInstance();t&&(a.play(),a.currentTime=r),e.push(a);}}}}get positional(){return this._positional}set slots(e){let t=this._slots;if(t)for(let e in t)t[e].stop();let i={};for(let t in e)e[t]instanceof wM?i[e[t].name]=e[t]:e[t].name&&(i[e[t].name]=new wM(this,e[t].name,e[t]));this._slots=i,this.enabled&&this.entity.enabled&&this.onEnable();}get slots(){return this._slots}onEnable(){if(this.system._inTools)return;let e=this._slots,t=this._playingBeforeDisable;for(let i in e){let s=e[i];s.autoPlay&&s.isStopped?s.play():t[i]?s.resume():s.isLoaded||s.load();}}onDisable(){let e=this._slots,t={};for(let i in e)!e[i].overlap&&e[i].isPlaying&&(e[i].pause(),t[i]=true);this._playingBeforeDisable=t;}onRemove(){this.off();}addSlot(e,t){let i=this._slots;if(i[e])return null;let s=new wM(this,e,t);return i[e]=s,s.autoPlay&&this.enabled&&this.entity.enabled&&s.play(),s}removeSlot(e){let t=this._slots;t[e]&&(t[e].stop(),delete t[e]);}slot(e){return this._slots[e]}_getSlotProperty(e,t){if(!this.enabled||!this.entity.enabled)return;let i=this._slots[e];if(i)return i[t]}isPlaying(e){return this._getSlotProperty(e,"isPlaying")||false}isLoaded(e){return this._getSlotProperty(e,"isLoaded")||false}isPaused(e){return this._getSlotProperty(e,"isPaused")||false}isStopped(e){return this._getSlotProperty(e,"isStopped")||false}play(e){if(!this.enabled||!this.entity.enabled)return null;let t=this._slots[e];return t?t.play():null}pause(e){let t=this._slots;if(e){let i=t[e];if(!i)return;i.pause();}else for(let e in t)t[e].pause();}resume(e){let t=this._slots;if(e){let i=t[e];if(!i)return;i.isPaused&&i.resume();}else for(let e in t)t[e].resume();}stop(e){let t=this._slots;if(e){let i=t[e];if(!i)return;i.stop();}else for(let e in t)t[e].stop();}constructor(...e){super(...e),this._volume=1,this._pitch=1,this._positional=true,this._refDistance=1,this._maxDistance=1e4,this._rollOffFactor=1,this._distanceModel=d2,this._slots={},this._playingBeforeDisable={};}}class wN{constructor(){this.enabled=true;}}let wF=["enabled"];class wB extends Tm{constructor(e){super(e),this.id="sound",this.ComponentType=wO,this.DataType=wN,this.schema=wF,this.manager=e.soundManager,this.app.systems.on("update",this.onUpdate,this),this.on("beforeremove",this.onBeforeRemove,this);}set volume(e){this.manager.volume=e;}get volume(){return this.manager.volume}get context(){return ue()?this.manager.context:null}initializeComponentData(e,t,i){i=["volume","pitch","positional","refDistance","maxDistance","rollOffFactor","distanceModel","slots"];for(let s=0;s<i.length;s++)t.hasOwnProperty(i[s])&&(e[i[s]]=t[i[s]]);super.initializeComponentData(e,t,["enabled"]);}cloneComponent(e,t){let i=e.sound,s=i.slots,r={};for(let e in s){let t=s[e];r[e]={name:t.name,volume:t.volume,pitch:t.pitch,loop:t.loop,duration:t.duration,startTime:t.startTime,overlap:t.overlap,autoPlay:t.autoPlay,asset:t.asset};}let a={distanceModel:i.distanceModel,enabled:i.enabled,maxDistance:i.maxDistance,pitch:i.pitch,positional:i.positional,refDistance:i.refDistance,rollOffFactor:i.rollOffFactor,slots:r,volume:i.volume};return this.addComponent(t,a)}onUpdate(e){let t=this.store;for(let e in t)if(t.hasOwnProperty(e)){let i=t[e].entity;if(i.enabled){let e=i.sound;if(e.enabled&&e.positional){let t=i.getPosition(),s=e.slots;for(let e in s)s[e].updatePosition(t);}}}}onBeforeRemove(e,t){let i=t.slots;for(let e in i)i[e].overlap||i[e].stop();t.onRemove();}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this);}}Tp._buildAccessors(wO.prototype,wF);let wU="simple",wk="animated";class wV extends eo{static{this.EVENT_PLAY="play";}static{this.EVENT_PAUSE="pause";}static{this.EVENT_RESUME="resume";}static{this.EVENT_STOP="stop";}static{this.EVENT_END="end";}static{this.EVENT_LOOP="loop";}constructor(e,t){super(),this._evtSetMeshes=null,this._component=e,this._frame=0,this._sprite=null,this._spriteAsset=null,this.spriteAsset=t.spriteAsset,this.name=t.name,this.fps=t.fps||0,this.loop=t.loop||false,this._playing=false,this._paused=false,this._time=0;}get duration(){if(this._sprite){let e=this.fps||Number.MIN_VALUE;return this._sprite.frameKeys.length/Math.abs(e)}return 0}set frame(e){this._setFrame(e);let t=this.fps||Number.MIN_VALUE;this._setTime(this._frame/t);}get frame(){return this._frame}get isPaused(){return this._paused}get isPlaying(){return this._playing}set sprite(e){if(this._sprite&&(this._evtSetMeshes?.off(),this._evtSetMeshes=null,this._sprite.off("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.off("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.off("set:texture",this._onSpriteMeshesChange,this)),this._sprite=e,this._sprite&&(this._evtSetMeshes=this._sprite.on("set:meshes",this._onSpriteMeshesChange,this),this._sprite.on("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.on("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.on("set:texture",this._onSpriteMeshesChange,this)),this._component.currentClip===this){let t;e&&e.atlas?(e.atlas.texture&&((t=this._component._meshInstance)&&(t.setParameter("texture_emissiveMap",e.atlas.texture),t.setParameter("texture_opacityMap",e.atlas.texture)),this._component.enabled&&this._component.entity.enabled&&this._component._showModel()),this.time&&this.fps?this.time=this.time:this.frame=this.frame):((t=this._component._meshInstance)&&(t.deleteParameter("texture_emissiveMap"),t.deleteParameter("texture_opacityMap")),this._component._hideModel());}}get sprite(){return this._sprite}set spriteAsset(e){let t=this._component.system.app.assets,i=e;if(e instanceof xF&&(i=e.id),this._spriteAsset!==i){if(this._spriteAsset){let e=t.get(this._spriteAsset);e&&this._unbindSpriteAsset(e);}if(this._spriteAsset=i,this._spriteAsset){let e=t.get(this._spriteAsset);e?this._bindSpriteAsset(e):(this.sprite=null,t.on(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this));}else this.sprite=null;}}get spriteAsset(){return this._spriteAsset}set time(e){this._setTime(e),this._sprite?this.frame=Math.min(this._sprite.frameKeys.length-1,Math.floor(this._time*Math.abs(this.fps))):this.frame=0;}get time(){return this._time}_onSpriteAssetAdded(e){this._component.system.app.assets.off(`add:${e.id}`,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e);}_bindSpriteAsset(e){e.on("load",this._onSpriteAssetLoad,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._component.system.app.assets.load(e);}_unbindSpriteAsset(e){e&&(e.off("load",this._onSpriteAssetLoad,this),e.off("remove",this._onSpriteAssetRemove,this),e.resource&&!e.resource.atlas&&this._component.system.app.assets.off(`load:${e.data.textureAtlasAsset}`,this._onTextureAtlasLoad,this));}_onSpriteAssetLoad(e){if(e.resource)if(e.resource.atlas)this.sprite=e.resource;else {let t=e.data.textureAtlasAsset,i=this._component.system.app.assets;i.off(`load:${t}`,this._onTextureAtlasLoad,this),i.once(`load:${t}`,this._onTextureAtlasLoad,this);}else this.sprite=null;}_onTextureAtlasLoad(e){let t=this._spriteAsset;t instanceof xF?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._component.system.app.assets.get(t));}_onSpriteAssetRemove(e){this.sprite=null;}_onSpriteMeshesChange(){this._component.currentClip===this&&this._component._showFrame(this.frame);}_onSpritePpuChanged(){this._component.currentClip===this&&this.sprite.renderMode!==pb&&this._component._showFrame(this.frame);}_update(e){if(0===this.fps||!this._playing||this._paused||!this._sprite)return;let t=this.fps<0?-1:1,i=this._time+e*this._component.speed*t,s=this.duration,r=i>s||i<0;this._setTime(i);let a=this.frame;(a=this._sprite?Math.floor(this._sprite.frameKeys.length*this._time/s):0)!==this._frame&&this._setFrame(a),r&&(this.loop?(this.fire("loop"),this._component.fire("loop",this)):(this._playing=false,this._paused=false,this.fire("end"),this._component.fire("end",this)));}_setTime(e){this._time=e;let t=this.duration;this._time<0?this.loop?this._time=this._time%t+t:this._time=0:this._time>t&&(this.loop?this._time%=t:this._time=t);}_setFrame(e){this._sprite?this._frame=eA.clamp(e,0,this._sprite.frameKeys.length-1):this._frame=e,this._component.currentClip===this&&this._component._showFrame(this._frame);}_destroy(){if(this._spriteAsset){let e=this._component.system.app.assets;this._unbindSpriteAsset(e.get(this._spriteAsset));}this._sprite&&(this.sprite=null),this._spriteAsset&&(this.spriteAsset=null);}play(){this._playing||(this._playing=true,this._paused=false,this.frame=0,this.fire("play"),this._component.fire("play",this));}pause(){this._playing&&!this._paused&&(this._paused=true,this.fire("pause"),this._component.fire("pause",this));}resume(){this._paused&&(this._paused=false,this.fire("resume"),this._component.fire("resume",this));}stop(){this._playing&&(this._playing=false,this._paused=false,this._time=0,this.frame=0,this.fire("stop"),this._component.fire("stop",this));}}let wz="texture_emissiveMap",wG="texture_opacityMap",wH="material_emissive",wW="material_opacity";class wX extends Tp{static{this.EVENT_PLAY="play";}static{this.EVENT_PAUSE="pause";}static{this.EVENT_RESUME="resume";}static{this.EVENT_STOP="stop";}static{this.EVENT_END="end";}static{this.EVENT_LOOP="loop";}constructor(e,t){super(e,t),this._evtLayersChanged=null,this._evtLayerAdded=null,this._evtLayerRemoved=null,this._type=wU,this._material=e.defaultMaterial,this._color=new eb(1,1,1,1),this._colorUniform=new Float32Array(3),this._speed=1,this._flipX=false,this._flipY=false,this._width=1,this._height=1,this._drawOrder=0,this._layers=[ub],this._outerScale=new eN(1,1),this._outerScaleUniform=new Float32Array(2),this._innerOffset=new eF,this._innerOffsetUniform=new Float32Array(4),this._atlasRect=new eF,this._atlasRectUniform=new Float32Array(4),this._batchGroupId=-1,this._batchGroup=null,this._node=new _c,this._model=new g5,this._model.graph=this._node,this._meshInstance=null,t.addChild(this._model.graph),this._model._entity=t,this._updateAabbFunc=this._updateAabb.bind(this),this._addedModel=false,this._autoPlayClip=null,this._clips={},this._defaultClip=new wV(this,{name:this.entity.name,fps:0,loop:false,spriteAsset:null}),this._currentClip=this._defaultClip;}set type(e){this._type!==e&&(this._type=e,this._type===wU?(this.stop(),this._currentClip=this._defaultClip,this.enabled&&this.entity.enabled&&(this._currentClip.frame=this.frame,this._currentClip.sprite?this._showModel():this._hideModel())):this._type===wk&&(this.stop(),this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.isPlaying&&this.enabled&&this.entity.enabled?this._showModel():this._hideModel()));}get type(){return this._type}set frame(e){this._currentClip.frame=e;}get frame(){return this._currentClip.frame}set spriteAsset(e){this._defaultClip.spriteAsset=e;}get spriteAsset(){return this._defaultClip._spriteAsset}set sprite(e){this._currentClip.sprite=e;}get sprite(){return this._currentClip.sprite}set material(e){this._material=e,this._meshInstance&&(this._meshInstance.material=e);}get material(){return this._material}set color(e){this._color.r=e.r,this._color.g=e.g,this._color.b=e.b,this._meshInstance&&(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(wH,this._colorUniform));}get color(){return this._color}set opacity(e){this._color.a=e,this._meshInstance&&this._meshInstance.setParameter(wW,e);}get opacity(){return this._color.a}set clips(e){if(!e){for(let e in this._clips)this.removeClip(e);return}for(let t in this._clips){let i=false;for(let s in e)if(e[s].name===t){i=true,this._clips[t].fps=e[s].fps,this._clips[t].loop=e[s].loop,e[s].hasOwnProperty("sprite")?this._clips[t].sprite=e[s].sprite:e[s].hasOwnProperty("spriteAsset")&&(this._clips[t].spriteAsset=e[s].spriteAsset);break}i||this.removeClip(t);}for(let t in e)this._clips[e[t].name]||this.addClip(e[t]);this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.sprite||this._hideModel();}get clips(){return this._clips}get currentClip(){return this._currentClip}set speed(e){this._speed=e;}get speed(){return this._speed}set flipX(e){this._flipX!==e&&(this._flipX=e,this._updateTransform());}get flipX(){return this._flipX}set flipY(e){this._flipY!==e&&(this._flipY=e,this._updateTransform());}get flipY(){return this._flipY}set width(e){e!==this._width&&(this._width=e,this._outerScale.x=this._width,this.sprite&&(this.sprite.renderMode===pC||this.sprite.renderMode===pw)&&this._updateTransform());}get width(){return this._width}set height(e){e!==this._height&&(this._height=e,this._outerScale.y=this.height,this.sprite&&(this.sprite.renderMode===pC||this.sprite.renderMode===pw)&&this._updateTransform());}get height(){return this._height}set batchGroupId(e){if(this._batchGroupId===e)return;let t=this._batchGroupId;this._batchGroupId=e,this.entity.enabled&&t>=0&&this.system.app.batcher?.remove(mS.SPRITE,t,this.entity),this.entity.enabled&&e>=0?this.system.app.batcher?.insert(mS.SPRITE,e,this.entity):t>=0&&this._currentClip&&this._currentClip.sprite&&this.enabled&&this.entity.enabled&&this._showModel();}get batchGroupId(){return this._batchGroupId}set autoPlayClip(e){this._autoPlayClip=e instanceof wV?e.name:e,this._tryAutoPlay();}get autoPlayClip(){return this._autoPlayClip}set drawOrder(e){this._drawOrder=e,this._meshInstance&&(this._meshInstance.drawOrder=e);}get drawOrder(){return this._drawOrder}set layers(e){this._addedModel&&this._hideModel(),this._layers=e,this._meshInstance&&this.enabled&&this.entity.enabled&&this._showModel();}get layers(){return this._layers}get aabb(){return this._meshInstance?this._meshInstance.aabb:null}onEnable(){let e=this.system.app,t=e.scene,i=t.layers;this._evtLayersChanged=t.on("set:layers",this._onLayersChanged,this),i&&(this._evtLayerAdded=i.on("add",this._onLayerAdded,this),this._evtLayerRemoved=i.on("remove",this._onLayerRemoved,this)),this._showModel(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0&&e.batcher?.insert(mS.SPRITE,this._batchGroupId,this.entity);}onDisable(){let e=this.system.app,t=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.stop(),this._hideModel(),this._batchGroupId>=0&&e.batcher?.remove(mS.SPRITE,this._batchGroupId,this.entity);}onDestroy(){for(let e in this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null),this._clips)this._clips[e]._destroy();this._clips=null,this._hideModel(),this._model=null,this._node?.remove(),this._node=null,this._meshInstance&&(this._meshInstance.material=null,this._meshInstance.mesh=null,this._meshInstance=null);}_showModel(){if(this._addedModel||!this._meshInstance)return;let e=[this._meshInstance];for(let t=0,i=this._layers.length;t<i;t++){let i=this.system.app.scene.layers.getLayerById(this._layers[t]);i&&i.addMeshInstances(e);}this._addedModel=true;}_hideModel(){if(!this._addedModel||!this._meshInstance)return;let e=[this._meshInstance];for(let t=0,i=this._layers.length;t<i;t++){let i=this.system.app.scene.layers.getLayerById(this._layers[t]);i&&i.removeMeshInstances(e);}this._addedModel=false;}_showFrame(e){let t;if(!this.sprite)return;let i=this.sprite.meshes[e];if(!i){this._meshInstance&&(this._meshInstance.mesh=null,this._meshInstance.visible=false);return}if(t=this.sprite.renderMode===pw?this.system.default9SlicedMaterialSlicedMode:this.sprite.renderMode===pC?this.system.default9SlicedMaterialTiledMode:this.system.defaultMaterial,!this._meshInstance&&(this._meshInstance=new mV(i,this._material,this._node),this._meshInstance.castShadow=false,this._meshInstance.receiveShadow=false,this._meshInstance.drawOrder=this._drawOrder,this._model.meshInstances.push(this._meshInstance),this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(wH,this._colorUniform),this._meshInstance.setParameter(wW,this._color.a),this.enabled&&this.entity.enabled&&this._showModel()),this._meshInstance.material!==t&&(this._meshInstance.material=t),this._meshInstance.mesh!==i&&(this._meshInstance.mesh=i,this._meshInstance.visible=true,this._meshInstance._aabbVer=-1),this.sprite.atlas&&this.sprite.atlas.texture?(this._meshInstance.setParameter(wz,this.sprite.atlas.texture),this._meshInstance.setParameter(wG,this.sprite.atlas.texture)):(this._meshInstance.deleteParameter(wz),this._meshInstance.deleteParameter(wG)),this.sprite.atlas&&(this.sprite.renderMode===pw||this.sprite.renderMode===pC)){this._meshInstance._updateAabbFunc=this._updateAabbFunc;let t=this.sprite.atlas.frames[this.sprite.frameKeys[e]];if(t){let e=2/t.rect.z,i=2/t.rect.w;this._innerOffset.set(t.border.x*e,t.border.y*i,t.border.z*e,t.border.w*i);let s=this.sprite.atlas.texture;this._atlasRect.set(t.rect.x/s.width,t.rect.y/s.height,t.rect.z/s.width,t.rect.w/s.height);}else this._innerOffset.set(0,0,0,0);this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._meshInstance.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._meshInstance.setParameter("atlasRect",this._atlasRectUniform);}else this._meshInstance._updateAabbFunc=null;this._updateTransform();}_updateTransform(){let e=this.flipX?-1:1,t=this.flipY?-1:1,i=0,s=0;if(this.sprite&&(this.sprite.renderMode===pw||this.sprite.renderMode===pC)){let r=1,a=1;if(this.sprite.atlas){let e=this.sprite.atlas.frames[this.sprite.frameKeys[this.frame]];e&&(r=e.rect.z,a=e.rect.w,i=(.5-e.pivot.x)*this._width,s=(.5-e.pivot.y)*this._height);}let n=r/this.sprite.pixelsPerUnit,o=a/this.sprite.pixelsPerUnit;this._outerScale.set(Math.max(this._width,this._innerOffset.x*n),Math.max(this._height,this._innerOffset.y*o)),e*=n,t*=o,this._outerScale.x/=n,this._outerScale.y/=o,e*=eA.clamp(this._width/(this._innerOffset.x*n),1e-4,1),t*=eA.clamp(this._height/(this._innerOffset.y*o),1e-4,1),this._meshInstance&&(this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._meshInstance.setParameter("outerScale",this._outerScaleUniform));}this._node.setLocalScale(e,t,1),this._node.setLocalPosition(i,s,0);}_updateAabb(e){return e.center.set(0,0,0),e.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),e.setFromTransformedAabb(e,this._node.getWorldTransform()),e}_tryAutoPlay(){if(!this._autoPlayClip||this.type!==wk)return;let e=this._clips[this._autoPlayClip];e&&!e.isPlaying&&(!this._currentClip||!this._currentClip.isPlaying)&&this.enabled&&this.entity.enabled&&this.play(e.name);}_onLayersChanged(e,t){e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this),this.enabled&&this.entity.enabled&&this._showModel();}_onLayerAdded(e){!(0>this.layers.indexOf(e.id))&&this._addedModel&&this.enabled&&this.entity.enabled&&this._meshInstance&&e.addMeshInstances([this._meshInstance]);}_onLayerRemoved(e){this._meshInstance&&(0>this.layers.indexOf(e.id)||e.removeMeshInstances([this._meshInstance]));}removeModelFromLayers(){for(let e=0;e<this.layers.length;e++){let t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.removeMeshInstances([this._meshInstance]);}}addClip(e){let t=new wV(this,{name:e.name,fps:e.fps,loop:e.loop,spriteAsset:e.spriteAsset});return this._clips[e.name]=t,t.name&&t.name===this._autoPlayClip&&this._tryAutoPlay(),t}removeClip(e){delete this._clips[e];}clip(e){return this._clips[e]}play(e){let t=this._clips[e],i=this._currentClip;return i&&i!==t&&(i._playing=false),this._currentClip=t,this._currentClip&&(this._currentClip=t,this._currentClip.play()),t}pause(){this._currentClip!==this._defaultClip&&this._currentClip.isPlaying&&this._currentClip.pause();}resume(){this._currentClip!==this._defaultClip&&this._currentClip.isPaused&&this._currentClip.resume();}stop(){this._currentClip!==this._defaultClip&&this._currentClip.stop();}}class wY{constructor(){this.enabled=true;}}let wq=["enabled"];class w$ extends Tm{constructor(e){super(e),this.id="sprite",this.ComponentType=wX,this.DataType=wY,this.schema=wq,this._defaultTexture=null,this._defaultMaterial=null,this._default9SlicedMaterialSlicedMode=null,this._default9SlicedMaterialTiledMode=null,this.app.systems.on("update",this.onUpdate,this),this.on("beforeremove",this.onBeforeRemove,this);}set defaultMaterial(e){this._defaultMaterial=e;}get defaultMaterial(){if(!this._defaultMaterial){let e=new ns(this.app.graphicsDevice,{width:1,height:1,format:ib,name:"sprite"}),t=new Uint8Array(e.lock());t[0]=t[1]=t[2]=t[3]=255,e.unlock();let i=new yo;i.diffuse.set(0,0,0),i.emissive.set(1,1,1),i.emissiveMap=e,i.opacityMap=e,i.opacityMapChannel="a",i.useLighting=false,i.useTonemap=false,i.useFog=false,i.useSkybox=false,i.blendType=uo,i.depthWrite=false,i.pixelSnap=false,i.cull=tY,i.update(),this._defaultTexture=e,this._defaultMaterial=i;}return this._defaultMaterial}set default9SlicedMaterialSlicedMode(e){this._default9SlicedMaterialSlicedMode=e;}get default9SlicedMaterialSlicedMode(){if(!this._default9SlicedMaterialSlicedMode){let e=this.defaultMaterial.clone();e.nineSlicedMode=pw,e.update(),this._default9SlicedMaterialSlicedMode=e;}return this._default9SlicedMaterialSlicedMode}set default9SlicedMaterialTiledMode(e){this._default9SlicedMaterialTiledMode=e;}get default9SlicedMaterialTiledMode(){if(!this._default9SlicedMaterialTiledMode){let e=this.defaultMaterial.clone();e.nineSlicedMode=pC,e.update(),this._default9SlicedMaterialTiledMode=e;}return this._default9SlicedMaterialTiledMode}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this),this._defaultTexture&&(this._defaultTexture.destroy(),this._defaultTexture=null);}initializeComponentData(e,t,i){if(void 0!==t.enabled&&(e.enabled=t.enabled),e.type=t.type,t.layers&&Array.isArray(t.layers)&&(e.layers=t.layers.slice(0)),void 0!==t.drawOrder&&(e.drawOrder=t.drawOrder),void 0!==t.color&&(t.color instanceof eb?e.color.set(t.color.r,t.color.g,t.color.b,t.opacity??1):e.color.set(t.color[0],t.color[1],t.color[2],t.opacity??1),e.color=e.color),void 0!==t.opacity&&(e.opacity=t.opacity),void 0!==t.flipX&&(e.flipX=t.flipX),void 0!==t.flipY&&(e.flipY=t.flipY),void 0!==t.width&&(e.width=t.width),void 0!==t.height&&(e.height=t.height),void 0!==t.spriteAsset&&(e.spriteAsset=t.spriteAsset),t.sprite&&(e.sprite=t.sprite),void 0!==t.frame&&(e.frame=t.frame),t.clips)for(let i in t.clips)e.addClip(t.clips[i]);void 0!==t.speed&&(e.speed=t.speed),t.autoPlayClip&&(e.autoPlayClip=t.autoPlayClip),e.batchGroupId=void 0===t.batchGroupId||null===t.batchGroupId?-1:t.batchGroupId,super.initializeComponentData(e,t,i);}cloneComponent(e,t){let i=e.sprite;return this.addComponent(t,{enabled:i.enabled,type:i.type,spriteAsset:i.spriteAsset,sprite:i.sprite,width:i.width,height:i.height,frame:i.frame,color:i.color.clone(),opacity:i.opacity,flipX:i.flipX,flipY:i.flipY,speed:i.speed,clips:i.clips,autoPlayClip:i.autoPlayClip,batchGroupId:i.batchGroupId,drawOrder:i.drawOrder,layers:i.layers.slice(0)})}onUpdate(e){let t=this.store;for(let i in t)if(t.hasOwnProperty(i)){let s=t[i];if(s.data.enabled&&s.entity.enabled){let t=s.entity.sprite;t._currentClip&&t._currentClip._update(e);}}}onBeforeRemove(e,t){t.onDestroy();}}Tp._buildAccessors(wX.prototype,wq);class wj extends Tp{static{this.EVENT_ENABLE="enable";}static{this.EVENT_DISABLE="disable";}static{this.EVENT_STATE="state";}static{this.EVENT_REMOVE="remove";}constructor(e,t){super(e,t),this._oldState=true,this._size=new eM,this.on("set_enabled",this._onSetEnabled,this);}set size(e){e instanceof eM?this._size.copy(e):e instanceof Array&&e.length>=3&&this.size.set(e[0],e[1],e[2]);}get size(){return this._size}onEnable(){this._checkState();}onDisable(){this._checkState();}_onSetEnabled(e,t,i){this._checkState();}_checkState(){let e=this.enabled&&this.entity.enabled;e!==this._oldState&&(this._oldState=e,this.fire("enable"),this.fire("state",this.enabled));}_onBeforeRemove(){this.fire("remove");}}class wK{constructor(){this.enabled=true;}}let wZ=["enabled"];class wQ extends Tm{constructor(e){super(e),this.id="zone",this.ComponentType=wj,this.DataType=wK,this.schema=wZ,this.on("beforeremove",this._onBeforeRemove,this);}initializeComponentData(e,t,i){e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,t.size&&(t.size instanceof eM?e.size.copy(t.size):t.size instanceof Array&&t.size.length>=3&&e.size.set(t.size[0],t.size[1],t.size[2]));}cloneComponent(e,t){let i={enabled:e.zone.enabled,size:e.zone.size};return this.addComponent(t,i)}_onBeforeRemove(e,t){t._onBeforeRemove();}}Tp._buildAccessors(wj.prototype,wZ);class wJ{constructor(e,t){this.effect=e,this.inputTarget=t,this.outputTarget=null,this.name=e.constructor.name;}}class w0{constructor(e,t){this.app=e,this.camera=t,this.destinationRenderTarget=null,this.effects=[],this.enabled=false,this.depthTarget=null,t.on("set:rect",this.onCameraRectChanged,this);}_allocateColorBuffer(e,t){let i=this.camera.rect,s=this.destinationRenderTarget,r=this.app.graphicsDevice,a=Math.floor(i.z*(s?.width??r.width)),n=Math.floor(i.w*(s?.height??r.height));return new ns(r,{name:t,format:e,width:a,height:n,mipmaps:false,minFilter:tK,magFilter:tK,addressU:tr,addressV:tr})}_createOffscreenTarget(e,t){let i=this.app.graphicsDevice,s=(this.destinationRenderTarget??i.backBuffer).isColorBufferSrgb(0),r=(t&&i.getRenderableHdrFormat([ig,iS],true))??(s?ib:id),a=`${this.camera.entity.name}-posteffect-${this.effects.length}`;return new nM({colorBuffer:this._allocateColorBuffer(r,a),depth:e,stencil:e&&this.app.graphicsDevice.supportsStencil,samples:e?i.samples:1})}_resizeOffscreenTarget(e){let t=e.colorBuffer.format,i=e.colorBuffer.name;e.destroyFrameBuffers(),e.destroyTextureBuffers(),e._colorBuffer=this._allocateColorBuffer(t,i),e._colorBuffers=[e._colorBuffer];}_destroyOffscreenTarget(e){e.destroyTextureBuffers(),e.destroy();}addEffect(e){let t=this.effects,i=0===t.length,s=this._createOffscreenTarget(i,e.hdr),r=new wJ(e,s);t.push(r),this._sourceTarget=r.inputTarget,t.length>1&&(t[t.length-2].outputTarget=r.inputTarget),this._newPostEffect=e,e.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0;}removeEffect(e){let t=-1;for(let i=0,s=this.effects.length;i<s;i++)if(this.effects[i].effect===e){t=i;break}t>=0&&(t>0?this.effects[t-1].outputTarget=t+1<this.effects.length?this.effects[t+1].inputTarget:null:this.effects.length>1&&(this.effects[1].inputTarget._depth||(this._destroyOffscreenTarget(this.effects[1].inputTarget),this.effects[1].inputTarget=this._createOffscreenTarget(true,this.effects[1].hdr),this._sourceTarget=this.effects[1].inputTarget),this.camera.renderTarget=this.effects[1].inputTarget),this._destroyOffscreenTarget(this.effects[t].inputTarget),this.effects.splice(t,1)),this.enabled&&e.needsDepthBuffer&&this._releaseDepthMap(),0===this.effects.length&&this.disable();}_requestDepthMaps(){for(let e=0,t=this.effects.length;e<t;e++){let t=this.effects[e].effect;this._newPostEffect!==t&&t.needsDepthBuffer&&this._requestDepthMap();}}_releaseDepthMaps(){for(let e=0,t=this.effects.length;e<t;e++)this.effects[e].effect.needsDepthBuffer&&this._releaseDepthMap();}_requestDepthMap(){let e=this.app.scene.layers.getLayerById(uw);e&&(e.incrementCounter(),this.camera.requestSceneDepthMap(true));}_releaseDepthMap(){let e=this.app.scene.layers.getLayerById(uw);e&&(e.decrementCounter(),this.camera.requestSceneDepthMap(false));}destroy(){for(let e=0,t=this.effects.length;e<t;e++)this.effects[e].inputTarget.destroy();this.effects.length=0,this.disable();}enable(){!this.enabled&&this.effects.length&&(this.enabled=true,this._requestDepthMaps(),this.app.graphicsDevice.on("resizecanvas",this._onCanvasResized,this),this.destinationRenderTarget=this.camera.renderTarget,this.camera.renderTarget=this.effects[0].inputTarget,this.camera.onPostprocessing=()=>{if(this.enabled){let e=null,t=this.effects.length;if(t)for(let i=0;i<t;i++){let s=this.effects[i],r=s.outputTarget;i===t-1&&(e=this.camera.rect,this.destinationRenderTarget&&(r=this.destinationRenderTarget)),s.effect.render(s.inputTarget,r,e);}}});}disable(){this.enabled&&(this.enabled=false,this.app.graphicsDevice.off("resizecanvas",this._onCanvasResized,this),this._releaseDepthMaps(),this._destroyOffscreenTarget(this._sourceTarget),this.camera.renderTarget=this.destinationRenderTarget,this.camera.onPostprocessing=null);}_onCanvasResized(e,t){let i=this.camera.rect,s=this.destinationRenderTarget;e=s?.width??e,t=s?.height??t,this.camera.camera.aspectRatio=e*i.z/(t*i.w),this.resizeRenderTargets();}resizeRenderTargets(){let e=this.app.graphicsDevice,t=this.destinationRenderTarget,i=t?.width??e.width,s=t?.height??e.height,r=this.camera.rect,a=Math.floor(r.z*i),n=Math.floor(r.w*s),o=this.effects;for(let e=0,t=o.length;e<t;e++){let t=o[e];(t.inputTarget.width!==a||t.inputTarget.height!==n)&&this._resizeOffscreenTarget(t.inputTarget);}}onCameraRectChanged(e,t,i){this.enabled&&this.resizeRenderTargets();}}class w1 extends Tp{constructor(e,t){super(e,t),this.onPostprocessing=null,this._renderSceneDepthMap=0,this._renderSceneColorMap=0,this._sceneDepthMapRequested=false,this._sceneColorMapRequested=false,this._priority=0,this._disablePostEffectsLayer=uL,this._camera=new m3,this._evtLayersChanged=null,this._evtLayerAdded=null,this._evtLayerRemoved=null,this._camera.node=t,this._postEffects=new w0(e.app,this);}setShaderPass(e){let t=mt.get(this.system.app.graphicsDevice),i=e?t.allocate(e,{isForward:true}):null;return this._camera.shaderPassInfo=i,i.index}getShaderPass(){return this._camera.shaderPassInfo?.name}set renderPasses(e){this._camera.renderPasses=e||[],this.dirtyLayerCompositionCameras(),this.system.app.scene.updateShaders=true;}get renderPasses(){return this._camera.renderPasses}get shaderParams(){return this._camera.shaderParams}set gammaCorrection(e){this.camera.shaderParams.gammaCorrection=e;}get gammaCorrection(){return this.camera.shaderParams.gammaCorrection}set toneMapping(e){this.camera.shaderParams.toneMapping=e;}get toneMapping(){return this.camera.shaderParams.toneMapping}set fog(e){this._camera.fogParams=e;}get fog(){return this._camera.fogParams}set aperture(e){this._camera.aperture=e;}get aperture(){return this._camera.aperture}set aspectRatio(e){this._camera.aspectRatio=e;}get aspectRatio(){return this._camera.aspectRatio}set aspectRatioMode(e){this._camera.aspectRatioMode=e;}get aspectRatioMode(){return this._camera.aspectRatioMode}set calculateProjection(e){this._camera.calculateProjection=e;}get calculateProjection(){return this._camera.calculateProjection}set calculateTransform(e){this._camera.calculateTransform=e;}get calculateTransform(){return this._camera.calculateTransform}get camera(){return this._camera}set clearColor(e){this._camera.clearColor=e;}get clearColor(){return this._camera.clearColor}set clearColorBuffer(e){this._camera.clearColorBuffer=e,this.dirtyLayerCompositionCameras();}get clearColorBuffer(){return this._camera.clearColorBuffer}set clearDepthBuffer(e){this._camera.clearDepthBuffer=e,this.dirtyLayerCompositionCameras();}get clearDepthBuffer(){return this._camera.clearDepthBuffer}set clearStencilBuffer(e){this._camera.clearStencilBuffer=e,this.dirtyLayerCompositionCameras();}get clearStencilBuffer(){return this._camera.clearStencilBuffer}set cullFaces(e){this._camera.cullFaces=e;}get cullFaces(){return this._camera.cullFaces}set disablePostEffectsLayer(e){this._disablePostEffectsLayer=e,this.dirtyLayerCompositionCameras();}get disablePostEffectsLayer(){return this._disablePostEffectsLayer}set farClip(e){this._camera.farClip=e;}get farClip(){return this._camera.farClip}set flipFaces(e){this._camera.flipFaces=e;}get flipFaces(){return this._camera.flipFaces}set fov(e){this._camera.fov=e;}get fov(){return this._camera.fov}get frustum(){return this._camera.frustum}set frustumCulling(e){this._camera.frustumCulling=e;}get frustumCulling(){return this._camera.frustumCulling}set horizontalFov(e){this._camera.horizontalFov=e;}get horizontalFov(){return this._camera.horizontalFov}set layers(e){let t=this._camera.layers,i=this.system.app.scene;t.forEach(e=>{let t=i.layers.getLayerById(e);t?.removeCamera(this);}),this._camera.layers=e,this.enabled&&this.entity.enabled&&e.forEach(e=>{let t=i.layers.getLayerById(e);t?.addCamera(this);}),this.fire("set:layers");}get layers(){return this._camera.layers}get layersSet(){return this._camera.layersSet}set jitter(e){this._camera.jitter=e;}get jitter(){return this._camera.jitter}set nearClip(e){this._camera.nearClip=e;}get nearClip(){return this._camera.nearClip}set orthoHeight(e){this._camera.orthoHeight=e;}get orthoHeight(){return this._camera.orthoHeight}get postEffects(){return this._postEffects}get postEffectsEnabled(){return this._postEffects.enabled}set priority(e){this._priority=e,this.dirtyLayerCompositionCameras();}get priority(){return this._priority}set projection(e){this._camera.projection=e;}get projection(){return this._camera.projection}get projectionMatrix(){return this._camera.projectionMatrix}set rect(e){this._camera.rect=e,this.fire("set:rect",this._camera.rect);}get rect(){return this._camera.rect}set renderSceneColorMap(e){e&&!this._sceneColorMapRequested?(this.requestSceneColorMap(true),this._sceneColorMapRequested=true):this._sceneColorMapRequested&&(this.requestSceneColorMap(false),this._sceneColorMapRequested=false);}get renderSceneColorMap(){return this._renderSceneColorMap>0}set renderSceneDepthMap(e){e&&!this._sceneDepthMapRequested?(this.requestSceneDepthMap(true),this._sceneDepthMapRequested=true):this._sceneDepthMapRequested&&(this.requestSceneDepthMap(false),this._sceneDepthMapRequested=false);}get renderSceneDepthMap(){return this._renderSceneDepthMap>0}set renderTarget(e){this._camera.renderTarget=e,this.dirtyLayerCompositionCameras();}get renderTarget(){return this._camera.renderTarget}set scissorRect(e){this._camera.scissorRect=e;}get scissorRect(){return this._camera.scissorRect}set sensitivity(e){this._camera.sensitivity=e;}get sensitivity(){return this._camera.sensitivity}set shutter(e){this._camera.shutter=e;}get shutter(){return this._camera.shutter}get viewMatrix(){return this._camera.viewMatrix}_enableDepthLayer(e){if(this.layers.find(e=>e===uw)){let t=this.system.app.scene.layers.getLayerById(uw);e?t?.incrementCounter():t?.decrementCounter();}else if(e)return false;return true}requestSceneColorMap(e){this._renderSceneColorMap+=e?1:-1,this._enableDepthLayer(e),this.camera._enableRenderPassColorGrab(this.system.app.graphicsDevice,this.renderSceneColorMap),this.system.app.scene.layers.markDirty();}requestSceneDepthMap(e){this._renderSceneDepthMap+=e?1:-1,this._enableDepthLayer(e),this.camera._enableRenderPassDepthGrab(this.system.app.graphicsDevice,this.system.app.renderer,this.renderSceneDepthMap),this.system.app.scene.layers.markDirty();}dirtyLayerCompositionCameras(){this.system.app.scene.layers._dirty=true;}screenToWorld(e,t,i,s){let{width:r,height:a}=this.system.app.graphicsDevice.clientRect;return this._camera.screenToWorld(e,t,i,r,a,s)}worldToScreen(e,t){let{width:i,height:s}=this.system.app.graphicsDevice.clientRect;return this._camera.worldToScreen(e,i,s,t)}onAppPrerender(){this._camera._viewMatDirty=true,this._camera._viewProjMatDirty=true;}addCameraToLayers(){let e=this.layers;for(let t=0;t<e.length;t++){let i=this.system.app.scene.layers.getLayerById(e[t]);i&&i.addCamera(this);}}removeCameraFromLayers(){let e=this.layers;for(let t=0;t<e.length;t++){let i=this.system.app.scene.layers.getLayerById(e[t]);i&&i.removeCamera(this);}}onLayersChanged(e,t){this.addCameraToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this);}onLayerAdded(e){0>this.layers.indexOf(e.id)||e.addCamera(this);}onLayerRemoved(e){0>this.layers.indexOf(e.id)||e.removeCamera(this);}onEnable(){let e=this.system.app.scene,t=e.layers;this.system.addCamera(this),this._evtLayersChanged?.off(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved?.off(),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addCameraToLayers(),this.postEffects.enable();}onDisable(){let e=this.system.app.scene.layers;this.postEffects.disable(),this.removeCameraFromLayers(),this._evtLayersChanged?.off(),this._evtLayersChanged=null,e&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.system.removeCamera(this);}onRemove(){this.onDisable(),this.off(),this.camera.destroy();}calculateAspectRatio(e){let t=this.system.app.graphicsDevice,i=e?e.width:t.width,s=e?e.height:t.height;return i*this.rect.z/(s*this.rect.w)}frameUpdate(e){this.aspectRatioMode===pV&&(this.aspectRatio=this.calculateAspectRatio(e));}startXr(e,t,i){this.system.app.xr.start(this,e,t,i);}endXr(e){if(!this._camera.xr){e&&e(Error("Camera is not in XR"));return}this._camera.xr.end(e);}copy(e){this.aperture=e.aperture,this.aspectRatio=e.aspectRatio,this.aspectRatioMode=e.aspectRatioMode,this.calculateProjection=e.calculateProjection,this.calculateTransform=e.calculateTransform,this.clearColor=e.clearColor,this.clearColorBuffer=e.clearColorBuffer,this.clearDepthBuffer=e.clearDepthBuffer,this.clearStencilBuffer=e.clearStencilBuffer,this.cullFaces=e.cullFaces,this.disablePostEffectsLayer=e.disablePostEffectsLayer,this.farClip=e.farClip,this.flipFaces=e.flipFaces,this.fov=e.fov,this.frustumCulling=e.frustumCulling,this.horizontalFov=e.horizontalFov,this.layers=e.layers,this.nearClip=e.nearClip,this.orthoHeight=e.orthoHeight,this.priority=e.priority,this.projection=e.projection,this.rect=e.rect,this.renderTarget=e.renderTarget,this.scissorRect=e.scissorRect,this.sensitivity=e.sensitivity,this.shutter=e.shutter;}}class w2{constructor(){this.enabled=true;}}let w3=["enabled"];class w4 extends Tm{constructor(e){super(e),this.cameras=[],this.id="camera",this.ComponentType=w1,this.DataType=w2,this.schema=w3,this.on("beforeremove",this.onBeforeRemove,this),this.app.on("prerender",this.onAppPrerender,this);}initializeComponentData(e,t,i){i=["aspectRatio","aspectRatioMode","calculateProjection","calculateTransform","clearColor","clearColorBuffer","clearDepthBuffer","clearStencilBuffer","renderSceneColorMap","renderSceneDepthMap","cullFaces","farClip","flipFaces","fog","fov","frustumCulling","horizontalFov","layers","renderTarget","nearClip","orthoHeight","projection","priority","rect","scissorRect","aperture","shutter","sensitivity","gammaCorrection","toneMapping"];for(let s=0;s<i.length;s++){let r=i[s];if(t.hasOwnProperty(r)){let i=t[r];switch(r){case "rect":case "scissorRect":Array.isArray(i)?e[r]=new eF(i[0],i[1],i[2],i[3]):e[r]=i;break;case "clearColor":Array.isArray(i)?e[r]=new eb(i[0],i[1],i[2],i[3]):e[r]=i;break;default:e[r]=i;}}}super.initializeComponentData(e,t,["enabled"]);}cloneComponent(e,t){let i=e.camera;return this.addComponent(t,{aspectRatio:i.aspectRatio,aspectRatioMode:i.aspectRatioMode,calculateProjection:i.calculateProjection,calculateTransform:i.calculateTransform,clearColor:i.clearColor,clearColorBuffer:i.clearColorBuffer,clearDepthBuffer:i.clearDepthBuffer,clearStencilBuffer:i.clearStencilBuffer,renderSceneDepthMap:i.renderSceneDepthMap,renderSceneColorMap:i.renderSceneColorMap,cullFaces:i.cullFaces,enabled:i.enabled,farClip:i.farClip,flipFaces:i.flipFaces,fov:i.fov,frustumCulling:i.frustumCulling,horizontalFov:i.horizontalFov,layers:i.layers,renderTarget:i.renderTarget,nearClip:i.nearClip,orthoHeight:i.orthoHeight,projection:i.projection,priority:i.priority,rect:i.rect,scissorRect:i.scissorRect,aperture:i.aperture,sensitivity:i.sensitivity,shutter:i.shutter,gammaCorrection:i.gammaCorrection,toneMapping:i.toneMapping})}onBeforeRemove(e,t){this.removeCamera(t),t.onRemove();}onAppPrerender(){for(let e=0,t=this.cameras.length;e<t;e++)this.cameras[e].onAppPrerender();}addCamera(e){this.cameras.push(e),gX(this.cameras);}removeCamera(e){let t=this.cameras.indexOf(e);t>=0&&(this.cameras.splice(t,1),gX(this.cameras));}destroy(){this.app.off("prerender",this.onAppPrerender,this),super.destroy();}}Tp._buildAccessors(w1.prototype,w3);class w5{constructor(){this.enabled=true,this.type="directional",this.color=new eb(1,1,1),this.intensity=1,this.luminance=0,this.shape=uB,this.affectSpecularity=true,this.castShadows=false,this.shadowDistance=40,this.shadowIntensity=1,this.shadowResolution=1024,this.shadowBias=.05,this.numCascades=1,this.cascadeBlend=0,this.bakeNumSamples=1,this.bakeArea=0,this.cascadeDistribution=.5,this.normalOffsetBias=0,this.range=10,this.innerConeAngle=40,this.outerConeAngle=45,this.falloffMode=uG,this.shadowType=uX,this.vsmBlurSize=11,this.vsmBlurMode=fi,this.vsmBias=.0025,this.cookieAsset=null,this.cookie=null,this.cookieIntensity=1,this.cookieFalloff=true,this.cookieChannel="rgb",this.cookieAngle=0,this.cookieScale=null,this.cookieOffset=null,this.shadowUpdateMode=pn,this.mask=1,this.affectDynamic=true,this.affectLightmapped=false,this.bake=false,this.bakeDir=true,this.isStatic=false,this.layers=[ub],this.penumbraSize=1,this.penumbraFalloff=1,this.shadowSamples=16,this.shadowBlockerSamples=16;}}let w8=Object.keys(new w5);class w6 extends Tp{get data(){let e=this.system.store[this.entity.getGuid()];return e?e.data:null}set enabled(e){this._setValue("enabled",e,function(e,t){this.onSetEnabled(null,t,e);});}get enabled(){return this.data.enabled}set light(e){this._setValue("light",e);}get light(){return this.data.light}set type(e){this._setValue("type",e,function(e,t){this.system.changeType(this,t,e),this.refreshProperties();});}get type(){return this.data.type}set color(e){this._setValue("color",e,function(e,t){this.light.setColor(e);},true);}get color(){return this.data.color}set intensity(e){this._setValue("intensity",e,function(e,t){this.light.intensity=e;});}get intensity(){return this.data.intensity}set luminance(e){this._setValue("luminance",e,function(e,t){this.light.luminance=e;});}get luminance(){return this.data.luminance}set shape(e){this._setValue("shape",e,function(e,t){this.light.shape=e;});}get shape(){return this.data.shape}set affectSpecularity(e){this._setValue("affectSpecularity",e,function(e,t){this.light.affectSpecularity=e;});}get affectSpecularity(){return this.data.affectSpecularity}set castShadows(e){this._setValue("castShadows",e,function(e,t){this.light.castShadows=e;});}get castShadows(){return this.data.castShadows}set shadowDistance(e){this._setValue("shadowDistance",e,function(e,t){this.light.shadowDistance=e;});}get shadowDistance(){return this.data.shadowDistance}set shadowIntensity(e){this._setValue("shadowIntensity",e,function(e,t){this.light.shadowIntensity=e;});}get shadowIntensity(){return this.data.shadowIntensity}set shadowResolution(e){this._setValue("shadowResolution",e,function(e,t){this.light.shadowResolution=e;});}get shadowResolution(){return this.data.shadowResolution}set shadowBias(e){this._setValue("shadowBias",e,function(e,t){this.light.shadowBias=-0.01*eA.clamp(e,0,1);});}get shadowBias(){return this.data.shadowBias}set numCascades(e){this._setValue("numCascades",e,function(e,t){this.light.numCascades=eA.clamp(Math.floor(e),1,4);});}get numCascades(){return this.data.numCascades}set cascadeBlend(e){this._setValue("cascadeBlend",e,function(e,t){this.light.cascadeBlend=eA.clamp(e,0,1);});}get cascadeBlend(){return this.data.cascadeBlend}set bakeNumSamples(e){this._setValue("bakeNumSamples",e,function(e,t){this.light.bakeNumSamples=eA.clamp(Math.floor(e),1,255);});}get bakeNumSamples(){return this.data.bakeNumSamples}set bakeArea(e){this._setValue("bakeArea",e,function(e,t){this.light.bakeArea=eA.clamp(e,0,180);});}get bakeArea(){return this.data.bakeArea}set cascadeDistribution(e){this._setValue("cascadeDistribution",e,function(e,t){this.light.cascadeDistribution=eA.clamp(e,0,1);});}get cascadeDistribution(){return this.data.cascadeDistribution}set normalOffsetBias(e){this._setValue("normalOffsetBias",e,function(e,t){this.light.normalOffsetBias=eA.clamp(e,0,1);});}get normalOffsetBias(){return this.data.normalOffsetBias}set range(e){this._setValue("range",e,function(e,t){this.light.attenuationEnd=e;});}get range(){return this.data.range}set innerConeAngle(e){this._setValue("innerConeAngle",e,function(e,t){this.light.innerConeAngle=e;});}get innerConeAngle(){return this.data.innerConeAngle}set outerConeAngle(e){this._setValue("outerConeAngle",e,function(e,t){this.light.outerConeAngle=e;});}get outerConeAngle(){return this.data.outerConeAngle}set falloffMode(e){this._setValue("falloffMode",e,function(e,t){this.light.falloffMode=e;});}get falloffMode(){return this.data.falloffMode}set shadowType(e){this._setValue("shadowType",e,function(e,t){this.light.shadowType=e;});}get shadowType(){return this.data.shadowType}set vsmBlurSize(e){this._setValue("vsmBlurSize",e,function(e,t){this.light.vsmBlurSize=e;});}get vsmBlurSize(){return this.data.vsmBlurSize}set vsmBlurMode(e){this._setValue("vsmBlurMode",e,function(e,t){this.light.vsmBlurMode=e;});}get vsmBlurMode(){return this.data.vsmBlurMode}set vsmBias(e){this._setValue("vsmBias",e,function(e,t){this.light.vsmBias=eA.clamp(e,0,1);});}get vsmBias(){return this.data.vsmBias}set cookieAsset(e){this._setValue("cookieAsset",e,function(e,t){if(!this._cookieAssetId||(!(e instanceof xF)||e.id!==this._cookieAssetId)&&e!==this._cookieAssetId){if(this.onCookieAssetRemove(),this._cookieAssetId=null,e instanceof xF)this.data.cookieAsset=e.id,this._cookieAssetId=e.id,this.onCookieAssetAdd(e);else if("number"==typeof e){this._cookieAssetId=e;let t=this.system.app.assets.get(e);t?this.onCookieAssetAdd(t):(this._cookieAssetAdd=true,this.system.app.assets.on(`add:${this._cookieAssetId}`,this.onCookieAssetAdd,this));}}});}get cookieAsset(){return this.data.cookieAsset}set cookie(e){this._setValue("cookie",e,function(e,t){this.light.cookie=e;});}get cookie(){return this.data.cookie}set cookieIntensity(e){this._setValue("cookieIntensity",e,function(e,t){this.light.cookieIntensity=eA.clamp(e,0,1);});}get cookieIntensity(){return this.data.cookieIntensity}set cookieFalloff(e){this._setValue("cookieFalloff",e,function(e,t){this.light.cookieFalloff=e;});}get cookieFalloff(){return this.data.cookieFalloff}set cookieChannel(e){this._setValue("cookieChannel",e,function(e,t){this.light.cookieChannel=e;});}get cookieChannel(){return this.data.cookieChannel}set cookieAngle(e){this._setValue("cookieAngle",e,function(e,t){if(0!==e||null!==this.cookieScale){this._cookieMatrix||(this._cookieMatrix=new eF);let t=1,i=1;this.cookieScale&&(t=this.cookieScale.x,i=this.cookieScale.y);let s=Math.cos(e*eA.DEG_TO_RAD),r=Math.sin(e*eA.DEG_TO_RAD);this._cookieMatrix.set(s/t,-r/t,r/i,s/i),this.light.cookieTransform=this._cookieMatrix;}else this.light.cookieTransform=null;});}get cookieAngle(){return this.data.cookieAngle}set cookieScale(e){this._setValue("cookieScale",e,function(e,t){if(null!==e||0!==this.cookieAngle){this._cookieMatrix||(this._cookieMatrix=new eF);let t=e.x,i=e.y,s=Math.cos(this.cookieAngle*eA.DEG_TO_RAD),r=Math.sin(this.cookieAngle*eA.DEG_TO_RAD);this._cookieMatrix.set(s/t,-r/t,r/i,s/i),this.light.cookieTransform=this._cookieMatrix;}else this.light.cookieTransform=null;},true);}get cookieScale(){return this.data.cookieScale}set cookieOffset(e){this._setValue("cookieOffset",e,function(e,t){this.light.cookieOffset=e;},true);}get cookieOffset(){return this.data.cookieOffset}set shadowUpdateMode(e){this._setValue("shadowUpdateMode",e,function(e,t){this.light.shadowUpdateMode=e;},true);}get shadowUpdateMode(){return this.data.shadowUpdateMode}set mask(e){this._setValue("mask",e,function(e,t){this.light.mask=e;});}get mask(){return this.data.mask}set affectDynamic(e){this._setValue("affectDynamic",e,function(e,t){e?this.light.mask|=po:this.light.mask&=-2,this.light.layersDirty();});}get affectDynamic(){return this.data.affectDynamic}set affectLightmapped(e){this._setValue("affectLightmapped",e,function(e,t){e?(this.light.mask|=pl,this.bake&&(this.light.mask&=-5)):(this.light.mask&=-3,this.bake&&(this.light.mask|=ph));});}get affectLightmapped(){return this.data.affectLightmapped}set bake(e){this._setValue("bake",e,function(e,t){e?(this.light.mask|=ph,this.affectLightmapped&&(this.light.mask&=-3)):(this.light.mask&=-5,this.affectLightmapped&&(this.light.mask|=pl)),this.light.layersDirty();});}get bake(){return this.data.bake}set bakeDir(e){this._setValue("bakeDir",e,function(e,t){this.light.bakeDir=e;});}get bakeDir(){return this.data.bakeDir}set isStatic(e){this._setValue("isStatic",e,function(e,t){this.light.isStatic=e;});}get isStatic(){return this.data.isStatic}set layers(e){this._setValue("layers",e,function(e,t){for(let e=0;e<t.length;e++){let i=this.system.app.scene.layers.getLayerById(t[e]);i&&(i.removeLight(this),this.light.removeLayer(i));}for(let t=0;t<e.length;t++){let i=this.system.app.scene.layers.getLayerById(e[t]);i&&this.enabled&&this.entity.enabled&&(i.addLight(this),this.light.addLayer(i));}});}get layers(){return this.data.layers}set shadowUpdateOverrides(e){this.light.shadowUpdateOverrides=e;}get shadowUpdateOverrides(){return this.light.shadowUpdateOverrides}set shadowSamples(e){this.light.shadowSamples=e;}get shadowSamples(){return this.light.shadowSamples}set shadowBlockerSamples(e){this.light.shadowBlockerSamples=e;}get shadowBlockerSamples(){return this.light.shadowBlockerSamples}set penumbraSize(e){this.light.penumbraSize=e;}get penumbraSize(){return this.light.penumbraSize}set penumbraFalloff(e){this.light.penumbraFalloff=e;}get penumbraFalloff(){return this.light.penumbraFalloff}_setValue(e,t,i,s){let r=this.data,a=r[e];(s||a!==t)&&(r[e]=t,i&&i.call(this,t,a));}addLightToLayers(){for(let e=0;e<this.layers.length;e++){let t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&(t.addLight(this),this.light.addLayer(t));}}removeLightFromLayers(){for(let e=0;e<this.layers.length;e++){let t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&(t.removeLight(this),this.light.removeLayer(t));}}onLayersChanged(e,t){this.enabled&&this.entity.enabled&&this.addLightToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this);}onLayerAdded(e){this.layers.indexOf(e.id)>=0&&this.enabled&&this.entity.enabled&&(e.addLight(this),this.light.addLayer(e));}onLayerRemoved(e){this.layers.indexOf(e.id)>=0&&(e.removeLight(this),this.light.removeLayer(e));}refreshProperties(){for(let e=0;e<w8.length;e++){let t=w8[e];this[t]=this[t];}this.enabled&&this.entity.enabled&&this.onEnable();}onCookieAssetSet(){let e=false;"cubemap"!==this._cookieAsset.type||this._cookieAsset.loadFaces||(this._cookieAsset.loadFaces=true,e=true),(!this._cookieAsset.resource||e)&&this.system.app.assets.load(this._cookieAsset),this._cookieAsset.resource&&this.onCookieAssetLoad();}onCookieAssetAdd(e){this._cookieAssetId===e.id&&(this._cookieAsset=e,this.light.enabled&&this.onCookieAssetSet(),this._cookieAsset.on("load",this.onCookieAssetLoad,this),this._cookieAsset.on("remove",this.onCookieAssetRemove,this));}onCookieAssetLoad(){this._cookieAsset&&this._cookieAsset.resource&&(this.cookie=this._cookieAsset.resource);}onCookieAssetRemove(){this._cookieAssetId&&(this._cookieAssetAdd&&(this.system.app.assets.off(`add:${this._cookieAssetId}`,this.onCookieAssetAdd,this),this._cookieAssetAdd=false),this._cookieAsset&&(this._cookieAsset.off("load",this.onCookieAssetLoad,this),this._cookieAsset.off("remove",this.onCookieAssetRemove,this),this._cookieAsset=null),this.cookie=null);}onEnable(){let e=this.system.app.scene,t=e.layers;this.light.enabled=true,this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addLightToLayers(),this._cookieAsset&&!this.cookie&&this.onCookieAssetSet();}onDisable(){let e=this.system.app.scene.layers;this.light.enabled=false,this._evtLayersChanged?.off(),this._evtLayersChanged=null,e&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.removeLightFromLayers();}onRemove(){this.onDisable(),this.light.destroy(),this.cookieAsset=null;}constructor(...e){super(...e),this._evtLayersChanged=null,this._evtLayerAdded=null,this._evtLayerRemoved=null,this._cookieAsset=null,this._cookieAssetId=null,this._cookieAssetAdd=false,this._cookieMatrix=null;}}class w9 extends Tm{constructor(e){super(e),this.id="light",this.ComponentType=w6,this.DataType=w5,this.on("beforeremove",this._onRemoveComponent,this);}initializeComponentData(e,t){let i={...t};i.type||(i.type=e.data.type),e.data.type=i.type,i.layers&&Array.isArray(i.layers)&&(i.layers=i.layers.slice(0)),i.color&&Array.isArray(i.color)&&(i.color=new eb(i.color[0],i.color[1],i.color[2])),i.cookieOffset&&i.cookieOffset instanceof Array&&(i.cookieOffset=new eN(i.cookieOffset[0],i.cookieOffset[1])),i.cookieScale&&i.cookieScale instanceof Array&&(i.cookieScale=new eN(i.cookieScale[0],i.cookieScale[1])),i.enable&&(i.enabled=i.enable),i.shape||(i.shape=uB);let s=new g2(this.app.graphicsDevice,this.app.scene.clusteredLightingEnabled);s.type=gZ[i.type],s._node=e.entity,e.data.light=s,super.initializeComponentData(e,i,w8);}_onRemoveComponent(e,t){t.onRemove();}cloneComponent(e,t){let i,s=e.light,r=[];for(let e=0;e<w8.length;e++)"light"!==(i=w8[e])&&(s[i]&&s[i].clone?r[i]=s[i].clone():r[i]=s[i]);return this.addComponent(t,r)}changeType(e,t,i){t!==i&&(e.light.type=gZ[i]);}}let w7=["x","y","z","w"],Ce=[void 0,void 0,eN,eM,eF];function Ct(e,t,i,s){switch(t.type){case "boolean":return !!i;case "number":if("number"==typeof i)break;if("string"==typeof i){let e=parseInt(i,10);if(isNaN(e))return null;return e}if("boolean"==typeof i)return 0+i;return null;case "json":{let s={};if(Array.isArray(t.schema)){i&&"object"==typeof i||(i={});for(let r=0;r<t.schema.length;r++){let a=t.schema[r];if(a.name)if(a.array){s[a.name]=[];let t=Array.isArray(i[a.name])?i[a.name]:[];for(let i=0;i<t.length;i++)s[a.name].push(Ct(e,a,t[i]));}else {let t=i.hasOwnProperty(a.name)?i[a.name]:a.default;s[a.name]=Ct(e,a,t);}}}return s}case "asset":if(i instanceof xF)break;if("number"==typeof i)return e.assets.get(i)||null;if("string"==typeof i)return e.assets.get(parseInt(i,10))||null;return null;case "entity":if(i instanceof _c)break;if("string"==typeof i)return e.getEntityFromIndex(i);return null;case "rgb":case "rgba":if(i instanceof eb){if(s instanceof eb)return s.copy(i),s;return i.clone()}if(i instanceof Array&&i.length>=3&&i.length<=4){for(let e=0;e<i.length;e++)if("number"!=typeof i[e])return null;return s||(s=new eb),s.r=i[0],s.g=i[1],s.b=i[2],s.a=3===i.length?1:i[3],s}if("string"==typeof i&&/#(?:[0-9a-f]{2}){3,4}/i.test(i))return s||(s=new eb),s.fromString(i),s;return null;case "vec2":case "vec3":case "vec4":{let e=parseInt(t.type.slice(3),10),r=Ce[e];if(i instanceof r){if(s instanceof r)return s.copy(i),s;return i.clone()}if(i instanceof Array&&i.length===e){for(let e=0;e<i.length;e++)if("number"!=typeof i[e])return null;s||(s=new r);for(let t=0;t<e;t++)s[w7[t]]=i[t];return s}return null}case "curve":if(i){let e;return i instanceof eC||i instanceof eP?e=i.clone():(e=new(i.keys[0]instanceof Array?eP:eC)(i.keys)).type=i.type,e}}return i}function Ci(e,t,i,s){return t.array?i.map((i,r)=>Ct(e,t,i,s?s[r]:null)):Ct(e,t,i,s)}function Cs(e,t,i,s){if(i)for(let r in t){let a=t[r],n=i[r];void 0!==n&&(s[r]=Ci(e,a,n,s[r]));}}class Cr{static{this.assignAttributesToScript=Cs;}static{this.attributeToValue=Ci;}constructor(e){this.scriptType=e,this.index={};}static{this.reservedNames=new Set(["app","entity","enabled","_enabled","_enabledOld","_destroyed","__attributes","__attributesRaw","__scriptType","__executionOrder","_callbacks","_callbackActive","has","get","on","off","fire","once","hasEvent"]);}add(e,t){if(!this.index[e])Cr.reservedNames.has(e)||(this.index[e]=t,Object.defineProperty(this.scriptType.prototype,e,{get:function(){return this.__attributes[e]},set:function(i){let s="attr",r=`attr:${e}`,a=this.__attributes[e],n=a;if(a&&"json"!==t.type&&"entity"!==t.type&&a.clone&&(this.hasEvent(s)||this.hasEvent(r))&&(n=a.clone()),t.array){if(this.__attributes[e]=[],i)for(let s=0,r=i.length;s<r;s++)this.__attributes[e].push(Ct(this.app,t,i[s],a?a[s]:null));}else this.__attributes[e]=Ct(this.app,t,i,a);this.fire(s,e,this.__attributes[e],n),this.fire(r,this.__attributes[e],n);}}));}remove(e){return !!this.index[e]&&(delete this.index[e],delete this.scriptType.prototype[e],true)}has(e){return !!this.index[e]}get(e){return this.index[e]||null}}let Ca="initialize",Cn="postInitialize";class Co extends eo{static{this.EVENT_ENABLE="enable";}static{this.EVENT_DISABLE="disable";}static{this.EVENT_STATE="state";}static{this.EVENT_DESTROY="destroy";}static{this.EVENT_ATTR="attr";}static{this.EVENT_ERROR="error";}constructor(e){super(),this.initScript(e);}set enabled(e){this._enabled=!!e,this.enabled!==this._enabledOld&&(this._enabledOld=this.enabled,this.fire(this.enabled?"enable":"disable"),this.fire("state",this.enabled),!this._initialized&&this.enabled&&(this._initialized=true,this.fire("preInitialize"),this.initialize&&this.entity.script._scriptMethod(this,Ca)),this._initialized&&!this._postInitialized&&this.enabled&&!this.entity.script._beingEnabled&&(this._postInitialized=true,this.postInitialize&&this.entity.script._scriptMethod(this,Cn)));}get enabled(){return this._enabled&&!this._destroyed&&this.entity.script.enabled&&this.entity.enabled}initScript(e){let t=this.constructor;this.app=e.app,this.entity=e.entity,this._enabled="boolean"!=typeof e.enabled||e.enabled,this._enabledOld=this.enabled,this.__destroyed=false,this.__scriptType=t,this.__executionOrder=-1;}static{this.__name=null;}static{this.__getScriptName=Ch;}static get scriptName(){return this.__name}}let Cl=/^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s\/]*)\s*/;function Ch(e){if("function"!=typeof e)return;if(e.scriptName)return e.scriptName;if("name"in Function.prototype)return e.name;if(e===Function||e===Function.prototype.constructor)return "Function";let t=`${e}`.match(Cl);return t?t[1]:void 0}class Cc extends Co{constructor(e){super(e),this.initScriptType(e);}static get attributes(){return this.hasOwnProperty("__attributes")||(this.__attributes=new Cr(this)),this.__attributes}initScript(e){Co.prototype.initScript.call(this,e),this.__attributes={},this.__attributesRaw=e.attributes||{};}initScriptType(e){this.initScript(e);}__initializeAttributes(e){if(e||this.__attributesRaw){for(let e in this.__scriptType.attributes.index)this.__attributesRaw&&this.__attributesRaw.hasOwnProperty(e)?this[e]=this.__attributesRaw[e]:this.__attributes.hasOwnProperty(e)||(this.__scriptType.attributes.index[e].hasOwnProperty("default")?this[e]=this.__scriptType.attributes.index[e].default:this[e]=null);this.__attributesRaw=null;}}static extend(e){for(let t in e)e.hasOwnProperty(t)&&(this.prototype[t]=e[t]);}}let Cd=e=>e[0].toLowerCase()+e.substring(1);class Cu extends Tp{static{this.EVENT_CREATE="create";}static{this.EVENT_DESTROY="destroy";}static{this.EVENT_ENABLE="enable";}static{this.EVENT_DISABLE="disable";}static{this.EVENT_REMOVE="remove";}static{this.EVENT_STATE="state";}static{this.EVENT_MOVE="move";}static{this.EVENT_ERROR="error";}constructor(e,t){super(e,t),this._attributeDataMap=new Map,this._scripts=[],this._updateList=new ef({sortBy:"__executionOrder"}),this._postUpdateList=new ef({sortBy:"__executionOrder"}),this._scriptsIndex={},this._destroyedScripts=[],this._destroyed=false,this._scriptsData=null,this._oldState=true,this._enabled=true,this._beingEnabled=false,this._isLoopingThroughScripts=false,this._executionOrder=-1,this.on("set_enabled",this._onSetEnabled,this);}set scripts(e){for(let t in this._scriptsData=e,e){if(!e.hasOwnProperty(t))continue;let i=this._scriptsIndex[t];if(i&&("boolean"==typeof e[t].enabled&&(i.once("preInitialize",()=>{this.initializeAttributes(i);}),i.enabled=!!e[t].enabled),"object"==typeof e[t].attributes)){for(let s in e[t].attributes)if(!Cr.reservedNames.has(s)){if(!i.__attributes.hasOwnProperty(s)){let e=this.system.app.scripts.get(t);e&&e.attributes.add(s,{});}i[s]=e[t].attributes[s];}}}}get scripts(){return this._scripts}set enabled(e){let t=this._enabled;this._enabled=e,this.fire("set","enabled",t,e);}get enabled(){return this._enabled}onEnable(){this._beingEnabled=true,this._checkState(),this.entity._beingEnabled||this.onPostStateChange(),this._beingEnabled=false;}onDisable(){this._checkState();}onPostStateChange(){let e=this._beginLooping();for(let e=0,t=this.scripts.length;e<t;e++){let t=this.scripts[e];t._initialized&&!t._postInitialized&&t.enabled&&(t._postInitialized=true,t.postInitialize&&this._scriptMethod(t,Cn));}this._endLooping(e);}_beginLooping(){let e=this._isLoopingThroughScripts;return this._isLoopingThroughScripts=true,e}_endLooping(e){this._isLoopingThroughScripts=e,this._isLoopingThroughScripts||this._removeDestroyedScripts();}_onSetEnabled(e,t,i){this._beingEnabled=true,this._checkState(),this._beingEnabled=false;}_checkState(){let e=this.enabled&&this.entity.enabled;if(e===this._oldState)return;this._oldState=e,this.fire(e?"enable":"disable"),this.fire("state",e),e?this.system._addComponentToEnabled(this):this.system._removeComponentFromEnabled(this);let t=this._beginLooping();for(let e=0,t=this.scripts.length;e<t;e++){let t=this.scripts[e];t.once("preInitialize",()=>{this.initializeAttributes(t);}),t.enabled=t._enabled;}this._endLooping(t);}_onBeforeRemove(){this.fire("remove");let e=this._beginLooping();for(let e=0;e<this.scripts.length;e++){let t=this.scripts[e];t&&this.destroy(t.__scriptType.__name);}this._endLooping(e);}_removeDestroyedScripts(){let e=this._destroyedScripts.length;if(e){for(let t=0;t<e;t++){let e=this._destroyedScripts[t];this._removeScriptInstance(e);}this._destroyedScripts.length=0,this._resetExecutionOrder(0,this._scripts.length);}}_onInitializeAttributes(){for(let e=0,t=this.scripts.length;e<t;e++){let t=this.scripts[e];this.initializeAttributes(t);}}initializeAttributes(e){if(e instanceof Cc)e.__initializeAttributes();else {let t=e.__scriptType.__name,i=this._attributeDataMap.get(t);if(!i)return;let s=this.system.app.scripts?.getSchema(t);Cs(this.system.app,s.attributes,i,e);}}_scriptMethod(e,t,i){e[t](i);}_onInitialize(){let e=this._scripts,t=this._beginLooping();for(let t=0,i=e.length;t<i;t++){let i=e[t];!i._initialized&&i.enabled&&(i._initialized=true,i.initialize&&this._scriptMethod(i,Ca));}this._endLooping(t);}_onPostInitialize(){this.onPostStateChange();}_onUpdate(e){let t=this._updateList;if(!t.length)return;let i=this._beginLooping();for(t.loopIndex=0;t.loopIndex<t.length;t.loopIndex++){let i=t.items[t.loopIndex];i.enabled&&this._scriptMethod(i,"update",e);}this._endLooping(i);}_onPostUpdate(e){let t=this._postUpdateList;if(!t.length)return;let i=this._beginLooping();for(t.loopIndex=0;t.loopIndex<t.length;t.loopIndex++){let i=t.items[t.loopIndex];i.enabled&&this._scriptMethod(i,"postUpdate",e);}this._endLooping(i);}_insertScriptInstance(e,t,i){ -1===t?(this._scripts.push(e),e.__executionOrder=i,e.update&&this._updateList.append(e),e.postUpdate&&this._postUpdateList.append(e)):(this._scripts.splice(t,0,e),e.__executionOrder=t,this._resetExecutionOrder(t+1,i+1),e.update&&this._updateList.insert(e),e.postUpdate&&this._postUpdateList.insert(e));}_removeScriptInstance(e){let t=this._scripts.indexOf(e);return -1===t||(this._scripts.splice(t,1),e.update&&this._updateList.remove(e),e.postUpdate&&this._postUpdateList.remove(e)),t}_resetExecutionOrder(e,t){for(let i=e;i<t;i++)this._scripts[i].__executionOrder=i;}_resolveEntityScriptAttribute(e,t,i,s,r,a){if(e.array){let e=i.length;if(!e)return;let n=i.slice();for(let t=0;t<e;t++){let e=n[t]instanceof x1?n[t].getGuid():n[t];a[e]&&(n[t]=s?a[e].getGuid():a[e]);}r[t]=n;}else {if(i instanceof x1)i=i.getGuid();else if("string"!=typeof i)return;a[i]&&(r[t]=a[i]);}}has(e){if("string"==typeof e)return !!this._scriptsIndex[e];if(!e)return false;let t=e.__name,i=this._scriptsIndex[t];return (i&&i.instance)instanceof e}get(e){if("string"==typeof e){let t=this._scriptsIndex[e];return t?t.instance:null}if(!e)return null;let t=e.__name,i=this._scriptsIndex[t],s=i&&i.instance;return s instanceof e?s:null}create(e,t={}){let i=this,s=e,r=e;if("string"==typeof s)s=this.system.app.scripts.get(s);else if(s){let e=Cd(Ch(s));s.prototype instanceof Cc||s.scriptName,s.__name??=s.scriptName??e,r=s.__name;}if(s){if(!this._scriptsIndex[r]||!this._scriptsIndex[r].instance){let e=new s({app:this.system.app,entity:this.entity,enabled:!t.hasOwnProperty("enabled")||t.enabled,attributes:t.attributes||{}});t.properties&&"object"==typeof t.properties&&Object.assign(e,t.properties),e instanceof Cc||this._attributeDataMap.set(r,t.attributes);let a=this._scripts.length,n=-1;return "number"==typeof t.ind&&-1!==t.ind&&a>t.ind&&(n=t.ind),this._insertScriptInstance(e,n,a),this._scriptsIndex[r]={instance:e,onSwap:function(){i.swap(r);}},this[r]=e,t.preloading||this.initializeAttributes(e),this.fire("create",r,e),this.fire(`create:${r}`,e),this.system.app.scripts.on(`swap:${r}`,this._scriptsIndex[r].onSwap),!t.preloading&&(e.enabled&&!e._initialized&&(e._initialized=true,e.initialize&&this._scriptMethod(e,Ca)),e.enabled&&!e._postInitialized&&(e._postInitialized=true,e.postInitialize&&this._scriptMethod(e,Cn))),e}}else this._scriptsIndex[r]={awaiting:true,ind:this._scripts.length};return null}destroy(e){let t=e,i=e;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(t=i.__name);let s=this._scriptsIndex[t];if(delete this._scriptsIndex[t],!s)return false;this._attributeDataMap.delete(t);let r=s.instance;if(r&&!r._destroyed)if(r.enabled=false,r._destroyed=true,this._isLoopingThroughScripts)this._destroyedScripts.push(r);else {let e=this._removeScriptInstance(r);e>=0&&this._resetExecutionOrder(e,this._scripts.length);}return this.system.app.scripts.off(`swap:${t}`,s.onSwap),delete this[t],this.fire("destroy",t,r||null),this.fire(`destroy:${t}`,r||null),r&&r.fire("destroy"),true}swap(e){let t=e,i=e;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(t=i.__name);let s=this._scriptsIndex[t];if(!s||!s.instance)return false;let r=s.instance,a=this._scripts.indexOf(r),n=new i({app:this.system.app,entity:this.entity,enabled:r.enabled,attributes:r.__attributes});return !!n.swap&&(this.initializeAttributes(n),this._scripts[a]=n,this._scriptsIndex[t].instance=n,this[t]=n,n.__executionOrder=a,r.update&&this._updateList.remove(r),r.postUpdate&&this._postUpdateList.remove(r),n.update&&this._updateList.insert(n),n.postUpdate&&this._postUpdateList.insert(n),this._scriptMethod(n,"swap",r),this.fire("swap",t,n),this.fire(`swap:${t}`,n),true)}resolveDuplicatedEntityReferenceProperties(e,t){let i=this.entity.script;for(let s in e._scriptsIndex){let r=this.system.app.scripts.get(s);if(!r)continue;let a=e._scriptsIndex[s];if(!a||!a.instance)continue;let n=i[s].__attributesRaw??i._attributeDataMap.get(s),o=i[s].__attributes;if(!n&&!o)continue;let l=!!n,h=a.instance.__attributes??i._attributeDataMap.get(s);for(let e in h){if(!h[e])continue;let i=r.attributes?.get(e)??this.system.app.scripts.getSchema(s)?.attributes?.[e];if(i){if("entity"===i.type)this._resolveEntityScriptAttribute(i,e,h[e],l,n||o,t);else if("json"===i.type&&Array.isArray(i.schema)){let s=h[e],r=n?n[e]:o[e];for(let e=0;e<i.schema.length;e++){let a=i.schema[e];if("entity"===a.type)if(i.array)for(let e=0;e<s.length;e++)this._resolveEntityScriptAttribute(a,a.name,s[e][a.name],l,r[e],t);else this._resolveEntityScriptAttribute(a,a.name,s[a.name],l,r,t);}}}}}}move(e,t){let i=this._scripts.length;if(t>=i||t<0)return false;let s=e,r=e;"string"!=typeof r?r=e.__name:s=null;let a=this._scriptsIndex[r];if(!a||!a.instance)return false;let n=a.instance;if(s&&!(n instanceof s))return false;let o=this._scripts.indexOf(n);return -1!==o&&o!==t&&(this._scripts.splice(t,0,this._scripts.splice(o,1)[0]),this._resetExecutionOrder(0,i),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",r,n,t,o),this.fire(`move:${r}`,n,t,o),true)}}class Cf{constructor(){this.enabled=true;}}let Cp=0;class Cm extends Tm{constructor(e){super(e),this.id="script",this.ComponentType=Cu,this.DataType=Cf,this._components=new ef({sortBy:"_executionOrder"}),this._enabledComponents=new ef({sortBy:"_executionOrder"}),this.preloading=true,this.on("beforeremove",this._onBeforeRemove,this),this.app.systems.on("initialize",this._onInitialize,this),this.app.systems.on("postInitialize",this._onPostInitialize,this),this.app.systems.on("update",this._onUpdate,this),this.app.systems.on("postUpdate",this._onPostUpdate,this);}initializeComponentData(e,t){if(e._executionOrder=Cp++,this._components.append(e),Cp>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,e.enabled&&e.entity.enabled&&this._enabledComponents.append(e),t.hasOwnProperty("order")&&t.hasOwnProperty("scripts")){e._scriptsData=t.scripts;for(let i=0;i<t.order.length;i++)e.create(t.order[i],{enabled:t.scripts[t.order[i]].enabled,attributes:t.scripts[t.order[i]].attributes,preloading:this.preloading});}}cloneComponent(e,t){let i=[],s={};for(let t=0;t<e.script._scripts.length;t++){let r=e.script._scripts[t],a=r.__scriptType.__name;i.push(a);let n=e.script._attributeDataMap?.get(a)||{};for(let e in r.__attributes)n[e]=r.__attributes[e];s[a]={enabled:r._enabled,attributes:n};}for(let t in e.script._scriptsIndex)t.awaiting&&i.splice(t.ind,0,t);let r={enabled:e.script.enabled,order:i,scripts:s};return this.addComponent(t,r)}_resetExecutionOrder(){Cp=0;for(let e=0,t=this._components.length;e<t;e++)this._components.items[e]._executionOrder=Cp++;}_callComponentMethod(e,t,i){for(e.loopIndex=0;e.loopIndex<e.length;e.loopIndex++)e.items[e.loopIndex][t](i);}_onInitialize(){this.preloading=false,this._callComponentMethod(this._components,"_onInitializeAttributes"),this._callComponentMethod(this._enabledComponents,"_onInitialize");}_onPostInitialize(){this._callComponentMethod(this._enabledComponents,"_onPostInitialize");}_onUpdate(e){this._callComponentMethod(this._enabledComponents,"_onUpdate",e);}_onPostUpdate(e){this._callComponentMethod(this._enabledComponents,"_onPostUpdate",e);}_addComponentToEnabled(e){this._enabledComponents.insert(e);}_removeComponentFromEnabled(e){this._enabledComponents.remove(e);}_onBeforeRemove(e,t){this._components.items.indexOf(t)>=0&&t._onBeforeRemove(),this._removeComponentFromEnabled(t),this._components.remove(t);}destroy(){super.destroy(),this.app.systems.off("initialize",this._onInitialize,this),this.app.systems.off("postInitialize",this._onPostInitialize,this),this.app.systems.off("update",this._onUpdate,this),this.app.systems.off("postUpdate",this._onPostUpdate,this);}}class C_ extends Tp{constructor(e,t){super(e,t),this._layers=[ub],this._instance=null,this._materialTmp=null,this._highQualitySH=true,this._customAabb=null,this._evtLayersChanged=null,this._evtLayerAdded=null,this._evtLayerRemoved=null,this._castShadows=false,this._assetReference=new b$("asset",this,e.app.assets,{add:this._onGSplatAssetAdded,load:this._onGSplatAssetLoad,remove:this._onGSplatAssetRemove,unload:this._onGSplatAssetUnload},this),t.on("remove",this.onRemoveChild,this),t.on("removehierarchy",this.onRemoveChild,this),t.on("insert",this.onInsertChild,this),t.on("inserthierarchy",this.onInsertChild,this);}set customAabb(e){this._customAabb=e,this._instance?.meshInstance?.setCustomAabb(this._customAabb);}get customAabb(){return this._customAabb}set instance(e){if(this.destroyInstance(),this._instance=e,this._instance){let e=this._instance.meshInstance;e.node||(e.node=this.entity),e.castShadow=this._castShadows,e.setCustomAabb(this._customAabb),this.enabled&&this.entity.enabled&&this.addToLayers();}}get instance(){return this._instance}set material(e){this._instance?this._instance.material=e:this._materialTmp=e;}get material(){return this._instance?.material??this._materialTmp??null}set highQualitySH(e){e!==this._highQualitySH&&(this._highQualitySH=e,this._instance&&this._instance.setHighQualitySH(e));}get highQualitySH(){return this._highQualitySH}set castShadows(e){if(this._castShadows!==e){let t=this.instance?.meshInstance;if(t){let i=this.layers,s=this.system.app.scene;if(this._castShadows&&!e)for(let e=0;e<i.length;e++){let i=s.layers.getLayerById(this.layers[e]);i&&i.removeShadowCasters([t]);}if(t.castShadow=e,!this._castShadows&&e)for(let e=0;e<i.length;e++){let r=s.layers.getLayerById(i[e]);r&&r.addShadowCasters([t]);}}this._castShadows=e;}}get castShadows(){return this._castShadows}set layers(e){this.removeFromLayers(),this._layers.length=0;for(let t=0;t<e.length;t++)this._layers[t]=e[t];this.enabled&&this.entity.enabled&&this.addToLayers();}get layers(){return this._layers}set asset(e){let t=e instanceof xF?e.id:e;this._assetReference.id!==t&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onGSplatAssetRemove(),this._assetReference.id=t,this._assetReference.asset&&this._onGSplatAssetAdded());}get asset(){return this._assetReference.id}destroyInstance(){this._instance&&(this.removeFromLayers(),this._instance?.destroy(),this._instance=null);}addToLayers(){let e=this.instance?.meshInstance;if(e){let t=this.system.app.scene.layers;for(let i=0;i<this._layers.length;i++)t.getLayerById(this._layers[i])?.addMeshInstances([e]);}}removeFromLayers(){let e=this.instance?.meshInstance;if(e){let t=this.system.app.scene.layers;for(let i=0;i<this._layers.length;i++)t.getLayerById(this._layers[i])?.removeMeshInstances([e]);}}onRemoveChild(){this.removeFromLayers();}onInsertChild(){this._instance&&this.enabled&&this.entity.enabled&&this.addToLayers();}onRemove(){this.destroyInstance(),this.asset=null,this._assetReference.id=null,this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this);}onLayersChanged(e,t){this.addToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this);}onLayerAdded(e){!(0>this.layers.indexOf(e.id))&&this._instance&&e.addMeshInstances(this._instance.meshInstance);}onLayerRemoved(e){!(0>this.layers.indexOf(e.id))&&this._instance&&e.removeMeshInstances(this._instance.meshInstance);}onEnable(){let e=this.system.app.scene,t=e.layers;this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this._instance?this.addToLayers():this.asset&&this._onGSplatAssetAdded();}onDisable(){let e=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,e&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.removeFromLayers();}hide(){this._instance&&(this._instance.meshInstance.visible=false);}show(){this._instance&&(this._instance.meshInstance.visible=true);}_onGSplatAssetAdded(){this._assetReference.asset&&(this._assetReference.asset.resource?this._onGSplatAssetLoad():this.enabled&&this.entity.enabled&&this.system.app.assets.load(this._assetReference.asset));}_onGSplatAssetLoad(){this.destroyInstance();let e=this._assetReference.asset;e&&(this.instance=new y8(e.resource,{material:this._materialTmp,highQualitySH:this._highQualitySH}),this._materialTmp=null,this.customAabb=this.instance.resource.aabb.clone());}_onGSplatAssetUnload(){this.destroyInstance();}_onGSplatAssetRemove(){this._onGSplatAssetUnload();}}class Cg{constructor(){this.enabled=true;}}let Cv=["enabled"],CS=["castShadows","material","highQualitySH","asset","layers"];class Cy extends Tm{constructor(e){super(e),this.id="gsplat",this.ComponentType=C_,this.DataType=Cg,this.schema=Cv,this.on("beforeremove",this.onRemove,this);}initializeComponentData(e,t,i){t.layers&&t.layers.length&&(t.layers=t.layers.slice(0));for(let i=0;i<CS.length;i++)t.hasOwnProperty(CS[i])&&(e[CS[i]]=t[CS[i]]);t.aabbCenter&&t.aabbHalfExtents&&(e.customAabb=new ej(new eM(t.aabbCenter),new eM(t.aabbHalfExtents))),super.initializeComponentData(e,t,Cv);}cloneComponent(e,t){let i=e.gsplat,s={};CS.forEach(e=>{"material"===e?s[e]=i[e].clone():s[e]=i[e];}),s.enabled=i.enabled;let r=this.addComponent(t,s);return i.customAabb&&(r.customAabb=i.customAabb.clone()),r}onRemove(e,t){t.onRemove();}}Tp._buildAccessors(C_.prototype,Cv);class Cx extends eo{static{this.EVENT_SETMESHES="set:meshes";}set meshes(e){this.decRefMeshes(),this._meshes=e,this.incRefMeshes(),this.fire("set:meshes",e);}get meshes(){return this._meshes}destroy(){this.meshes=null;}decRefMeshes(){this._meshes?.forEach((e,t)=>{e&&(e.decRefCount(),e.refCount<1&&(e.destroy(),this._meshes[t]=null));});}incRefMeshes(){this._meshes?.forEach(e=>{e?.incRefCount();});}constructor(...e){super(...e),this._meshes=null;}}function CT(e){if(!this.resource)return;let t=e.resource,i=t.renders&&t.renders[this.data.renderIndex];i&&(this.resource.meshes=i.resource.meshes);}function CE(e){this.registry.off(`load:${e.id}`,CT,this),this.registry.on(`load:${e.id}`,CT,this),this.registry.off(`remove:${e.id}`,CA,this),this.registry.once(`remove:${e.id}`,CA,this),e.resource?CT.call(this,e):this.registry.load(e);}function CA(e){this.registry.off(`load:${e.id}`,CT,this),this.resource&&this.resource.destroy();}class Cb extends xH{constructor(e){super(e,"render"),this._registry=e.assets;}open(e,t){return new Cx}patch(e,t){if(!e.data.containerAsset)return;let i=t.get(e.data.containerAsset);if(!i)return void t.once(`add:${e.data.containerAsset}`,CE,e);CE.call(e,i);}}class Cw{constructor(e,t,i,s){this._paths=e,this._input=t,this._output=i,this._interpolation=s;}get paths(){return this._paths}get input(){return this._input}get output(){return this._output}get interpolation(){return this._interpolation}}class CC{constructor(e,t){this._components=e,this._data=t;}get components(){return this._components}get data(){return this._data}}function CP(e,t){let i,s=(e,t)=>{switch(t){case i.DT_INT8:return new Int8Array(e.buffer,e.byteOffset,e.byteLength);case i.DT_INT16:return new Int16Array(e.buffer,e.byteOffset,e.byteLength/2);case i.DT_INT32:return new Int32Array(e.buffer,e.byteOffset,e.byteLength/4);case i.DT_UINT8:return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);case i.DT_UINT16:return new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2);case i.DT_UINT32:return new Uint32Array(e.buffer,e.byteOffset,e.byteLength/4);case i.DT_FLOAT32:return new Float32Array(e.buffer,e.byteOffset,e.byteLength/4)}return null},r=e=>{switch(e){case i.DT_INT8:break;case i.DT_INT16:return 2;case i.DT_INT32:return 4;case i.DT_UINT8:break;case i.DT_UINT16:return 2;case i.DT_UINT32:case i.DT_FLOAT32:return 4}return 1},a=e=>e.num_components()*r(e.data_type()),n={0:0,1:1,5:2,2:3,7:4,8:5,4:6,3:7},o=(e,t)=>{let i=(e,t,i)=>{e[0]=t[0]-i[0],e[1]=t[1]-i[1],e[2]=t[2]-i[2];},s=(e,t,i)=>{e[0]=t[1]*i[2]-i[1]*t[2],e[1]=t[2]*i[0]-i[2]*t[0],e[2]=t[0]*i[1]-i[0]*t[1];},r=(e,t)=>{let i=e[t+0],s=e[t+1],r=e[t+2],a=1/Math.sqrt(i*i+s*s+r*r);e[t+0]*=a,e[t+1]*=a,e[t+2]*=a;},a=(e,t,i)=>{for(let s=0;s<3;++s)e[s]=t[i+s];},n=t.length/3,o=e.length/3,l=new Float32Array(e.length),h=[0,0,0],c=[0,0,0],d=[0,0,0],u=[0,0,0],f=[0,0,0],p=[0,0,0];for(let o=0;o<n;++o){let n=3*t[3*o+0],m=3*t[3*o+1],_=3*t[3*o+2];a(h,e,n),a(c,e,m),a(d,e,_),i(u,c,h),i(f,d,h),s(p,u,f),r(p,0);for(let e=0;e<3;++e)l[n+e]+=p[e],l[m+e]+=p[e],l[_+e]+=p[e];}for(let e=0;e<o;++e)r(l,3*e);return new Uint8Array(l.buffer)},l=e=>{let t={},r=new i.DecoderBuffer;r.Init(e,e.length);let l=new i.Decoder;if(l.GetEncodedGeometryType(r)!==i.TRIANGULAR_MESH)return t.error="Failed to decode draco mesh: not a mesh",t;let h=new i.Mesh,c=l.DecodeBufferToMesh(r,h);if(!c||!c.ok()||0===i.getPointer(h))return t.error="Failed to decode draco asset",t;let d=3*h.num_faces(),u=65535>=h.num_points(),f=d*(u?2:4),p=i._malloc(f);u?(l.GetTrianglesUInt16Array(h,f,p),t.indices=new Uint16Array(i.HEAPU16.buffer,p,d).slice().buffer):(l.GetTrianglesUInt32Array(h,f,p),t.indices=new Uint32Array(i.HEAPU32.buffer,p,d).slice().buffer),i._free(p);let m=[];for(let e=0;e<h.num_attributes();++e)m.push(l.GetAttribute(h,e));m.sort((e,t)=>(n[e.attribute_type()]??n.length)-(n[t.attribute_type()]??n.length)),t.attributes=m.map(e=>e.unique_id());let _=0,g=m.map(e=>{let t=_;return _+=4*Math.ceil(a(e)/4),t}),v=m.some(e=>1===e.attribute_type()),S=g[1];if(!v){for(let e=1;e<g.length;++e)g[e]+=12;_+=12;}t.vertices=new ArrayBuffer(h.num_points()*_);let y=new Uint8Array(t.vertices);for(let e=0;e<h.num_attributes();++e){let r=m[e],n=a(r),c=h.num_points()*n,d=i._malloc(c);l.GetAttributeDataArrayForAllPoints(h,r,r.data_type(),c,d);let f=new Uint8Array(i.HEAPU8.buffer,d,c);for(let t=0;t<h.num_points();++t)for(let i=0;i<n;++i)y[t*_+g[e]+i]=f[t*n+i];if(!v&&0===r.attribute_type()){let e=o(s(f,r.data_type()),u?new Uint16Array(t.indices):new Uint32Array(t.indices));for(let t=0;t<h.num_points();++t)for(let i=0;i<12;++i)y[t*_+S+i]=e[12*t+i];}i._free(d);}return i.destroy(h),i.destroy(l),i.destroy(r),t},h=e=>{let t=l(new Uint8Array(e.buffer));self.postMessage({jobId:e.jobId,error:t.error,indices:t.indices,vertices:t.vertices,attributes:t.attributes},[t.indices,t.vertices].filter(e=>null!=e));},c=[];self.onmessage=e=>{let t=e.data;switch(t.type){case "init":self.DracoDecoderModule({instantiateWasm:(e,i)=>(WebAssembly.instantiate(t.module,e).then(e=>i(e)).catch(e=>void 0),{})}).then(e=>{i=e,c.forEach(e=>h(e));});break;case "decodeMesh":i?h(t):c.push(t);}};}class CL{constructor(){this.workers=[[],[],[]],this.jobId=0,this.jobQueue=[],this.jobCallbacks=new Map,this.run=(e,t)=>{e.postMessage({type:"decodeMesh",jobId:t.jobId,buffer:t.buffer},[t.buffer]);};}init(e){for(e.forEach(e=>{e.addEventListener("message",t=>{let i=t.data,s=this.jobCallbacks.get(i.jobId);if(s&&s(i.error,{indices:i.indices,vertices:i.vertices,attributes:i.attributes}),this.jobCallbacks.delete(i.jobId),this.jobQueue.length>0){let t=this.jobQueue.shift();this.run(e,t);}else {let t=this.workers[2].indexOf(e);if(-1!==t)this.workers[2].splice(t,1),this.workers[1].push(e);else {let t=this.workers[1].indexOf(e);-1!==t&&(this.workers[1].splice(t,1),this.workers[0].push(e));}}});}),this.workers[0]=e;this.jobQueue.length&&(this.workers[0].length||this.workers[1].length);){let e=this.jobQueue.shift();if(this.workers[0].length>0){let t=this.workers[0].shift();this.workers[1].push(t),this.run(t,e);}else {let t=this.workers[1].shift();this.workers[2].push(t),this.run(t,e);}}}enqueueJob(e,t){let i={jobId:this.jobId++,buffer:e};if(this.jobCallbacks.set(i.jobId,t),this.workers[0].length>0){let e=this.workers[0].shift();this.workers[1].push(e),this.run(e,i);}else if(this.workers[1].length>0){let e=this.workers[1].shift();this.workers[2].push(e),this.run(e,i);}else this.jobQueue.push(i);}}let CI=e=>new Promise((t,i)=>{d1.get(e,{cache:true,responseType:"text",retry:true,maxRetries:3},(e,s)=>{e?i(e):t(s);});}),CD=e=>{let t=()=>fetch(e).then(e=>e.arrayBuffer()).then(e=>WebAssembly.compile(e));return WebAssembly.compileStreaming?WebAssembly.compileStreaming(fetch(e)).catch(e=>t()):t()},CR=e=>{if(p)return true;if(!e)if(m)e=m;else {let t=ed.getConfig("DracoDecoderModule");e=t?{jsUrl:t.glueUrl,wasmUrl:t.wasmUrl,numWorkers:t.numWorkers}:{jsUrl:"draco.wasm.js",wasmUrl:"draco.wasm.wasm",numWorkers:1};}return !!e.jsUrl&&!!e.wasmUrl&&(p=new CL,Promise.all([CI(e.jsUrl),CD(e.wasmUrl)]).then(([t,i])=>{let s=new Blob([["/* draco */",t,"/* worker */",`(
${CP.toString()}
)()
`].join("\n")],{type:"application/javascript"}),r=URL.createObjectURL(s),a=Math.max(1,Math.min(16,e.numWorkers||1)),n=[];for(let e=0;e<a;++e){let e=new Worker(r);e.postMessage({type:"init",module:i}),n.push(e);}p.init(n);}),true)},CM=e=>{e?.lazyInit?m=e:CR(e);},CO=(e,t)=>!!CR()&&(p.enqueueJob(e,t),true);class CN{destroy(){this.renders&&this.renders.forEach(e=>{e.meshes=null;});}}let CF=e=>/^data:[^\n\r,\u2028\u2029]*,.*$/i.test(e),CB=e=>e.substring(e.indexOf(":")+1,e.indexOf(";")),CU=e=>{switch(e){case "SCALAR":return 1;case "VEC2":return 2;case "VEC3":default:return 3;case "VEC4":case "MAT2":return 4;case "MAT3":return 9;case "MAT4":return 16}},Ck=e=>{switch(e){case 5120:return rC;case 5121:return rP;case 5122:return rL;case 5123:return rI;case 5124:return rD;case 5125:return rR;case 5126:return rM;default:return 0}},CV=e=>{switch(e){case 5120:case 5121:return 1;case 5122:case 5123:return 2;case 5124:case 5125:case 5126:return 4;default:return 0}},Cz=e=>{switch(e){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:return null}},CG={POSITION:sT,NORMAL:sE,TANGENT:sA,COLOR_0:sC,JOINTS_0:sw,WEIGHTS_0:sb,TEXCOORD_0:sL,TEXCOORD_1:sI,TEXCOORD_2:sD,TEXCOORD_3:sR,TEXCOORD_4:sM,TEXCOORD_5:sO,TEXCOORD_6:sN,TEXCOORD_7:sF},CH={[sT]:0,[sE]:1,[sA]:2,[sC]:3,[sw]:4,[sb]:5,[sL]:6,[sI]:7,[sD]:8,[sR]:9,[sM]:10,[sO]:11,[sN]:12,[sF]:13},CW=e=>{switch(e){case rC:return e=>Math.max(e/127,-1);case rP:return e=>e/255;case rL:return e=>Math.max(e/32767,-1);case rI:return e=>e/65535;default:return e=>e}},CX=(e,t,i)=>{let s=CW(i),r=t.length;for(let i=0;i<r;++i)e[i]=s(t[i]);return e},CY=(e,t,i=false)=>{let s,r=CU(e.type),a=Cz(e.componentType);if(!a)return null;if(e.sparse){let i=e.sparse,n=CY(Object.assign({count:i.count,type:"SCALAR"},i.indices),t,true),o=CY(Object.assign({count:i.count,type:e.type,componentType:e.componentType},i.values),t,true);s=e.hasOwnProperty("bufferView")?CY({bufferView:e.bufferView,byteOffset:e.byteOffset,componentType:e.componentType,count:e.count,type:e.type},t,true).slice():new a(e.count*r);for(let e=0;e<i.count;++e){let t=n[e];for(let i=0;i<r;++i)s[t*r+i]=o[e*r+i];}}else if(e.hasOwnProperty("bufferView")){let n=t[e.bufferView];if(i&&n.hasOwnProperty("byteStride")){let t=r*a.BYTES_PER_ELEMENT,i=new ArrayBuffer(e.count*t),o=new Uint8Array(i),l=0;for(let i=0;i<e.count;++i){let s=(e.byteOffset||0)+i*n.byteStride;for(let e=0;e<t;++e)o[l++]=n[s++];}s=new a(i);}else s=new a(n.buffer,n.byteOffset+(e.byteOffset||0),e.count*r);}else s=new a(e.count*r);return s},Cq=(e,t)=>{let i=CY(e,t,true);if(i instanceof Float32Array||!e.normalized)return i;let s=new Float32Array(i.length);return CX(s,i,Ck(e.componentType)),s},C$=e=>{let t=e.min,i=e.max;if(!t||!i)return null;if(e.normalized){let s=Ck(e.componentType);t=CX([],t,s),i=CX([],i,s);}return new ej(new eM((i[0]+t[0])*.5,(i[1]+t[1])*.5,(i[2]+t[2])*.5),new eM((i[0]-t[0])*.5,(i[1]-t[1])*.5,(i[2]-t[2])*.5))},Cj=e=>{if(!e.hasOwnProperty("mode"))return sS;switch(e.mode){case 0:return sm;case 1:return s_;case 2:return sg;case 3:return sv;case 4:default:return sS;case 5:return sy;case 6:return sx}},CK=e=>{let t=new Uint16Array(e);for(let i=0;i<e;i++)t[i]=i;return t},CZ=(e,t)=>{let i,s=e[sT];if(!s||3!==s.components)return;if(s.size!==s.stride){let e=s.stride/aK[s.type],t=new aj[s.type](s.buffer,s.offset,s.count*e);i=new aj[s.type](3*s.count);for(let r=0;r<s.count;++r)i[3*r+0]=t[r*e+0],i[3*r+1]=t[r*e+1],i[3*r+2]=t[r*e+2];}else i=new aj[s.type](s.buffer,s.offset,3*s.count);let r=s.count;t||(t=CK(r));let a=vK(i,t),n=new Float32Array(a.length);n.set(a),e[sE]={buffer:n.buffer,size:12,offset:0,stride:12,count:r,components:3,type:rM};},CQ=e=>{let t=new ns(e.device,e);return t._levels=(e=>{let t=[];for(let i=0;i<e._levels.length;++i){let s=[];if(e.cubemap)for(let t=0;t<6;++t)s.push(e._levels[i][t]);else s=e._levels[i];t.push(s);}return t})(e),t},CJ=e=>{let t=new xF(`${e.name}_clone`,e.type,e.file,e.data,e.options);return t.loaded=true,t.resource=CQ(e.resource),e.registry.add(t),t},C0=(e,t)=>{let i,s,r,a,n,o,l,h=t[sT];if(!h)return null;let c=h.count,d=[];for(let i in t)if(t.hasOwnProperty(i)){let s={semantic:i,components:t[i].components,type:t[i].type,normalize:!!t[i].normalize};!nP.isElementValid(e,s)&&s.components++,d.push(s);}d.sort((e,t)=>CH[e.semantic]-CH[t.semantic]);let u=new nP(e,d),f=true;for(i=0;i<u.elements.length;++i)if(o=(a=t[(n=u.elements[i]).name]).offset-h.offset,a.buffer!==h.buffer||a.stride!==n.stride||a.size!==n.size||o!==n.offset){f=false;break}let p=new nT(e,u,c),m=new Uint32Array(p.lock());if(f)l=new Uint32Array(h.buffer,h.offset,c*p.format.size/4),m.set(l);else {let e,o;for(i=0;i<p.format.elements.length;++i){e=(n=p.format.elements[i]).stride/4,o=(a=t[n.name]).stride/4,l=new Uint32Array(a.buffer,a.offset,(a.count-1)*o+(a.size+3)/4);let h=0,d=n.offset/4,u=Math.floor((a.size+3)/4);for(s=0;s<c;++s){for(r=0;r<u;++r)m[d+r]=l[h+r];h+=o,d+=e;}}}return p.unlock(),p},C1=(e,t,i,s,r,a)=>{let n={},o=[];for(let e in t)t.hasOwnProperty(e)&&CG.hasOwnProperty(e)&&(n[e]=t[e],o.push(`${e}:${t[e]}`));o.sort();let l=o.join(),h=a[l];if(!h){let o={};for(let e in n){let i=s[t[e]],a=CY(i,r),n=r[i.bufferView],l=CG[e],h=CU(i.type)*CV(i.componentType),c=n&&n.hasOwnProperty("byteStride")?n.byteStride:h;o[l]={buffer:a.buffer,size:h,offset:a.byteOffset,stride:c,count:i.count,components:CU(i.type),type:Ck(i.componentType),normalize:i.normalized};}o.hasOwnProperty(sE)||CZ(o,i),h=C0(e,o),a[l]=h;}return h},C2=(e,t,i,s,r,a)=>{let n,o,l,h=t.joints,c=h.length,d=[];if(t.hasOwnProperty("inverseBindMatrices")){let e=CY(i[t.inverseBindMatrices],s,true),r=[];for(n=0;n<c;n++){for(o=0;o<16;o++)r[o]=e[16*n+o];(l=new eG).set(r),d.push(l);}}else for(n=0;n<c;n++)l=new eG,d.push(l);let u=[];for(n=0;n<c;n++)u[n]=r[h[n]].name;let f=u.join("#"),p=a.get(f);return p||(p=new SR(e,d,u),a.set(f,p)),p},C3=(e,t,i,s,r,a,n)=>{let o=new mw(e);o.aabb=C$(i[t.attributes.POSITION]);let l=[];for(let[e,s]of Object.entries(t.attributes)){let t=i[s],r=CG[e],a=Ck(t.componentType);l.push({semantic:r,components:CU(t.type),type:a,normalize:t.normalized??(r===sC&&(a===rP||a===rI))});}if(n.push(new Promise((i,r)=>{let a=t.extensions.KHR_draco_mesh_compression;CO(s[a.bufferView].slice().buffer,(s,n)=>{if(s)r(s);else {let s={};for(let[e,t]of Object.entries(a.attributes))s[CG[e]]=n.attributes.indexOf(t);l.sort((e,t)=>s[e.semantic]-s[t.semantic]),t.attributes?.NORMAL||l.splice(1,0,{semantic:"NORMAL",components:3,type:rM});let r=new nP(e,l),h=n.vertices.byteLength/r.size,c=h<=65535?it:ii,d=n.indices.byteLength/(h<=65535?2:4),u=new nT(e,r,h,{data:n.vertices}),f=new lJ(e,c,d,tM,n.indices);o.vertexBuffer=u,o.indexBuffer[0]=f,o.primitive[0].type=Cj(t),o.primitive[0].base=0,o.primitive[0].count=f?d:h,o.primitive[0].indexed=!!f,i();}});})),t?.extensions?.KHR_materials_variants){let e=t.extensions.KHR_materials_variants,i={};e.mappings.forEach(e=>{e.variants.forEach(t=>{i[t]=e.material;});}),r[o.id]=i;}return a[o.id]=t.material,o},C4=(e,t,i,s,r,a,n,o,l)=>{let h=[];return t.primitives.forEach(c=>{if(c.extensions?.KHR_draco_mesh_compression)h.push(C3(e,c,i,s,a,n,l));else {let l=c.hasOwnProperty("indices")?CY(i[c.indices],s,true):null,d=C1(e,c.attributes,l,i,s,r),u=Cj(c),f=new mw(e);if(f.vertexBuffer=d,f.primitive[0].type=u,f.primitive[0].base=0,f.primitive[0].indexed=null!==l,null!==l){let t;(t=l instanceof Uint8Array?ie:l instanceof Uint16Array?it:ii)===ie&&e.isWebGPU&&(t=it,l=new Uint16Array(l));let i=new lJ(e,t,l.length,tM,l);f.indexBuffer[0]=i,f.primitive[0].count=l.length;}else f.primitive[0].count=d.numVertices;if(c.hasOwnProperty("extensions")&&c.extensions.hasOwnProperty("KHR_materials_variants")){let e=c.extensions.KHR_materials_variants,t={};e.mappings.forEach(e=>{e.variants.forEach(i=>{t[i]=e.material;});}),a[f.id]=t;}n[f.id]=c.material;let p=i[c.attributes.POSITION];if(f.aabb=C$(p),c.hasOwnProperty("targets")){let r=[];c.targets.forEach((e,a)=>{let n={};e.hasOwnProperty("POSITION")&&(n.deltaPositions=Cq(p=i[e.POSITION],s),n.aabb=C$(p)),e.hasOwnProperty("NORMAL")&&(n.deltaNormals=Cq(p=i[e.NORMAL],s)),t.hasOwnProperty("extras")&&t.extras.hasOwnProperty("targetNames")?n.name=t.extras.targetNames[a]:n.name=a.toString(10),t.hasOwnProperty("weights")&&(n.defaultWeight=t.weights[a]),n.preserveData=o.morphPreserveData,r.push(new g6(n));}),f.morph=new g8(r,e,{preferHighPrecision:o.morphPreferHighPrecision});}h.push(f);}}),h},C5=(e,t,i)=>{let s,r=e.texCoord;if(r)for(s=0;s<i.length;++s)t[`${i[s]}MapUv`]=r;let a=e.extensions?.KHR_texture_transform;if(a){let e=a.offset||[0,0],r=a.scale||[1,1],n=a.rotation?-a.rotation*eA.RAD_TO_DEG:0,o=new eN(r[0],r[1]),l=new eN(e[0],1-r[1]-e[1]);for(s=0;s<i.length;++s)t[`${i[s]}MapTiling`]=o,t[`${i[s]}MapOffset`]=l,t[`${i[s]}MapRotation`]=n;}},C8=(e,t,i)=>{let s,r;if(e.hasOwnProperty("diffuseFactor")?(s=e.diffuseFactor,t.diffuse.set(Math.pow(s[0],1/2.2),Math.pow(s[1],1/2.2),Math.pow(s[2],1/2.2)),t.opacity=s[3]):(t.diffuse.set(1,1,1),t.opacity=1),e.hasOwnProperty("diffuseTexture")){let s=e.diffuseTexture;t.diffuseMap=r=i[s.index],t.diffuseMapChannel="rgb",t.opacityMap=r,t.opacityMapChannel="a",C5(s,t,["diffuse","opacity"]);}if(t.useMetalness=false,e.hasOwnProperty("specularFactor")?(s=e.specularFactor,t.specular.set(Math.pow(s[0],1/2.2),Math.pow(s[1],1/2.2),Math.pow(s[2],1/2.2))):t.specular.set(1,1,1),e.hasOwnProperty("glossinessFactor")?t.gloss=e.glossinessFactor:t.gloss=1,e.hasOwnProperty("specularGlossinessTexture")){let s=e.specularGlossinessTexture;t.specularMap=t.glossMap=i[s.index],t.specularMapChannel="rgb",t.glossMapChannel="a",C5(s,t,["gloss","metalness"]);}},C6=(e,t,i)=>{if(e.hasOwnProperty("clearcoatFactor")?t.clearCoat=.25*e.clearcoatFactor:t.clearCoat=0,e.hasOwnProperty("clearcoatTexture")){let s=e.clearcoatTexture;t.clearCoatMap=i[s.index],t.clearCoatMapChannel="r",C5(s,t,["clearCoat"]);}if(e.hasOwnProperty("clearcoatRoughnessFactor")?t.clearCoatGloss=e.clearcoatRoughnessFactor:t.clearCoatGloss=0,e.hasOwnProperty("clearcoatRoughnessTexture")){let s=e.clearcoatRoughnessTexture;t.clearCoatGlossMap=i[s.index],t.clearCoatGlossMapChannel="g",C5(s,t,["clearCoatGloss"]);}if(e.hasOwnProperty("clearcoatNormalTexture")){let s=e.clearcoatNormalTexture;t.clearCoatNormalMap=i[s.index],C5(s,t,["clearCoatNormal"]),s.hasOwnProperty("scale")?t.clearCoatBumpiness=s.scale:t.clearCoatBumpiness=1;}t.clearCoatGlossInvert=true;},C9=(e,t,i)=>{t.useLighting=false,t.emissive.copy(t.diffuse),t.emissiveMap=t.diffuseMap,t.emissiveMapUv=t.diffuseMapUv,t.emissiveMapTiling.copy(t.diffuseMapTiling),t.emissiveMapOffset.copy(t.diffuseMapOffset),t.emissiveMapRotation=t.diffuseMapRotation,t.emissiveMapChannel=t.diffuseMapChannel,t.emissiveVertexColor=t.diffuseVertexColor,t.emissiveVertexColorChannel=t.diffuseVertexColorChannel,t.useLighting=false,t.useSkybox=false,t.diffuse.set(1,1,1),t.diffuseMap=null,t.diffuseVertexColor=false;},C7=(e,t,i)=>{if(t.useMetalnessSpecularColor=true,e.hasOwnProperty("specularColorTexture")&&(t.specularMap=i[e.specularColorTexture.index],t.specularMapChannel="rgb",C5(e.specularColorTexture,t,["specular"])),e.hasOwnProperty("specularColorFactor")){let i=e.specularColorFactor;t.specular.set(Math.pow(i[0],1/2.2),Math.pow(i[1],1/2.2),Math.pow(i[2],1/2.2));}else t.specular.set(1,1,1);e.hasOwnProperty("specularFactor")?t.specularityFactor=e.specularFactor:t.specularityFactor=1,e.hasOwnProperty("specularTexture")&&(t.specularityFactorMapChannel="a",t.specularityFactorMap=i[e.specularTexture.index],C5(e.specularTexture,t,["specularityFactor"]));},Pe=(e,t,i)=>{e.hasOwnProperty("ior")&&(t.refractionIndex=1/e.ior);},Pt=(e,t,i)=>{e.hasOwnProperty("dispersion")&&(t.dispersion=e.dispersion);},Pi=(e,t,i)=>{t.blendType=ua,t.useDynamicRefraction=true,e.hasOwnProperty("transmissionFactor")&&(t.refraction=e.transmissionFactor),e.hasOwnProperty("transmissionTexture")&&(t.refractionMapChannel="r",t.refractionMap=i[e.transmissionTexture.index],C5(e.transmissionTexture,t,["refraction"]));},Ps=(e,t,i)=>{if(t.useSheen=true,e.hasOwnProperty("sheenColorFactor")){let i=e.sheenColorFactor;t.sheen.set(Math.pow(i[0],1/2.2),Math.pow(i[1],1/2.2),Math.pow(i[2],1/2.2));}else t.sheen.set(1,1,1);e.hasOwnProperty("sheenColorTexture")&&(t.sheenMap=i[e.sheenColorTexture.index],C5(e.sheenColorTexture,t,["sheen"])),t.sheenGloss=e.hasOwnProperty("sheenRoughnessFactor")?e.sheenRoughnessFactor:0,e.hasOwnProperty("sheenRoughnessTexture")&&(t.sheenGlossMap=i[e.sheenRoughnessTexture.index],t.sheenGlossMapChannel="a",C5(e.sheenRoughnessTexture,t,["sheenGloss"])),t.sheenGlossInvert=true;},Pr=(e,t,i)=>{if(t.blendType=ua,t.useDynamicRefraction=true,e.hasOwnProperty("thicknessFactor")&&(t.thickness=e.thicknessFactor),e.hasOwnProperty("thicknessTexture")&&(t.thicknessMap=i[e.thicknessTexture.index],t.thicknessMapChannel="g",C5(e.thicknessTexture,t,["thickness"])),e.hasOwnProperty("attenuationDistance")&&(t.attenuationDistance=e.attenuationDistance),e.hasOwnProperty("attenuationColor")){let i=e.attenuationColor;t.attenuation.set(Math.pow(i[0],1/2.2),Math.pow(i[1],1/2.2),Math.pow(i[2],1/2.2));}},Pa=(e,t,i)=>{e.hasOwnProperty("emissiveStrength")&&(t.emissiveIntensity=e.emissiveStrength);},Pn=(e,t,i)=>{t.useIridescence=true,e.hasOwnProperty("iridescenceFactor")&&(t.iridescence=e.iridescenceFactor),e.hasOwnProperty("iridescenceTexture")&&(t.iridescenceMapChannel="r",t.iridescenceMap=i[e.iridescenceTexture.index],C5(e.iridescenceTexture,t,["iridescence"])),e.hasOwnProperty("iridescenceIor")&&(t.iridescenceRefractionIndex=e.iridescenceIor),e.hasOwnProperty("iridescenceThicknessMinimum")&&(t.iridescenceThicknessMin=e.iridescenceThicknessMinimum),e.hasOwnProperty("iridescenceThicknessMaximum")&&(t.iridescenceThicknessMax=e.iridescenceThicknessMaximum),e.hasOwnProperty("iridescenceThicknessTexture")&&(t.iridescenceThicknessMapChannel="g",t.iridescenceThicknessMap=i[e.iridescenceThicknessTexture.index],C5(e.iridescenceThicknessTexture,t,["iridescenceThickness"]));},Po=(e,t,i)=>{if(t.enableGGXSpecular=true,e.hasOwnProperty("anisotropyStrength")?t.anisotropyIntensity=e.anisotropyStrength:t.anisotropyIntensity=0,e.hasOwnProperty("anisotropyTexture")){let s=e.anisotropyTexture;t.anisotropyMap=i[s.index],C5(s,t,["anisotropy"]);}e.hasOwnProperty("anisotropyRotation")?t.anisotropyRotation=e.anisotropyRotation*eA.RAD_TO_DEG:t.anisotropyRotation=0;},Pl=(e,t)=>{let i,s,r=new yo;if(e.hasOwnProperty("name")&&(r.name=e.name),r.occludeSpecular=fV,r.diffuseVertexColor=true,r.specularTint=true,r.specularVertexColor=true,r.specular.set(1,1,1),r.gloss=1,r.glossInvert=true,r.useMetalness=true,e.hasOwnProperty("pbrMetallicRoughness")){let a=e.pbrMetallicRoughness;if(a.hasOwnProperty("baseColorFactor")&&(i=a.baseColorFactor,r.diffuse.set(Math.pow(i[0],1/2.2),Math.pow(i[1],1/2.2),Math.pow(i[2],1/2.2)),r.opacity=i[3]),a.hasOwnProperty("baseColorTexture")){let e=a.baseColorTexture;r.diffuseMap=s=t[e.index],r.diffuseMapChannel="rgb",r.opacityMap=s,r.opacityMapChannel="a",C5(e,r,["diffuse","opacity"]);}if(a.hasOwnProperty("metallicFactor")&&(r.metalness=a.metallicFactor),a.hasOwnProperty("roughnessFactor")&&(r.gloss=a.roughnessFactor),a.hasOwnProperty("metallicRoughnessTexture")){let e=a.metallicRoughnessTexture;r.metalnessMap=r.glossMap=t[e.index],r.metalnessMapChannel="b",r.glossMapChannel="g",C5(e,r,["gloss","metalness"]);}}if(e.hasOwnProperty("normalTexture")){let i=e.normalTexture;r.normalMap=t[i.index],C5(i,r,["normal"]),i.hasOwnProperty("scale")&&(r.bumpiness=i.scale);}if(e.hasOwnProperty("occlusionTexture")){let i=e.occlusionTexture;r.aoMap=t[i.index],r.aoMapChannel="r",C5(i,r,["ao"]);}if(e.hasOwnProperty("emissiveFactor")&&(i=e.emissiveFactor,r.emissive.set(Math.pow(i[0],1/2.2),Math.pow(i[1],1/2.2),Math.pow(i[2],1/2.2))),e.hasOwnProperty("emissiveTexture")){let i=e.emissiveTexture;r.emissiveMap=t[i.index],C5(i,r,["emissive"]);}if(e.hasOwnProperty("alphaMode"))switch(e.alphaMode){case "MASK":r.blendType=un,e.hasOwnProperty("alphaCutoff")?r.alphaTest=e.alphaCutoff:r.alphaTest=.5;break;case "BLEND":r.blendType=ua,r.depthWrite=false;break;default:r.blendType=un;}else r.blendType=un;e.hasOwnProperty("doubleSided")?(r.twoSidedLighting=e.doubleSided,r.cull=e.doubleSided?tY:tq):(r.twoSidedLighting=false,r.cull=tq);let a={KHR_materials_clearcoat:C6,KHR_materials_emissive_strength:Pa,KHR_materials_ior:Pe,KHR_materials_dispersion:Pt,KHR_materials_iridescence:Pn,KHR_materials_pbrSpecularGlossiness:C8,KHR_materials_sheen:Ps,KHR_materials_specular:C7,KHR_materials_transmission:Pi,KHR_materials_unlit:C9,KHR_materials_volume:Pr,KHR_materials_anisotropy:Po};if(e.hasOwnProperty("extensions"))for(let i in e.extensions){let s=a[i];void 0!==s&&s(e.extensions[i],r,t);}return r.update(),r},Ph=(e,t,i,s,r,a,n)=>{let o,l,h=e=>new CC(CU(e.type),Cq(e,s)),c={STEP:T_,LINEAR:Tg,CUBICSPLINE:Tv},d={},u={},f={},p=1;for(o=0;o<e.samplers.length;++o){let t=e.samplers[o];d.hasOwnProperty(t.input)||(d[t.input]=h(i[t.input])),u.hasOwnProperty(t.output)||(u[t.output]=h(i[t.output]));let s=t.hasOwnProperty("interpolation")&&c.hasOwnProperty(t.interpolation)?c[t.interpolation]:Tg,r={paths:[],input:t.input,output:t.output,interpolation:s};f[o]=r;}let m=[],_={translation:"localPosition",rotation:"localRotation",scale:"localScale"},g=e=>{let t=[];for(;e;)t.unshift(e.name),e=e.parent;return t},v=(e,t,i)=>{let s,r=u[e.output];if(!r)return;if(a&&a[t.mesh]){let e=a[t.mesh];e.hasOwnProperty("extras")&&e.extras.hasOwnProperty("targetNames")&&(s=e.extras.targetNames);}let n=r.data,l=n.length/d[e.input].data.length,h=n.length/l,c=4*h,m=new ArrayBuffer(c*l);for(let t=0;t<l;t++){let r=new Float32Array(m,c*t,h);for(let e=0;e<h;e++)r[e]=n[e*l+t];let a=new CC(1,r),d=s?.[t]?`name.${s[t]}`:t;u[-p]=a;let _={paths:[{entityPath:i,component:"graph",propertyPath:[`weight.${d}`]}],input:e.input,output:-p,interpolation:e.interpolation};p++,f[`morphCurve-${o}-${t}`]=_;}};for(o=0;o<e.channels.length;++o){let t=e.channels[o],i=t.target,s=f[t.sampler],a=r[i.node],l=n[i.node],h=g(a);i.path.startsWith("weights")?(v(s,l,h),f[t.sampler].morphCurve=true):s.paths.push({entityPath:h,component:"graph",propertyPath:[_[i.path]]});}let S=[],y=[],x=[];for(let e in d)S.push(d[e]),d[e]=S.length-1;for(let e in u)y.push(u[e]),u[e]=y.length-1;for(let e in f){let t=f[e];!t.morphCurve&&(x.push(new Cw(t.paths,d[t.input],u[t.output],t.interpolation)),t.paths.length>0&&"localRotation"===t.paths[0].propertyPath[0]&&t.interpolation!==Tv&&m.push(x[x.length-1].output));}m.sort();let T=null;for(o=0;o<m.length;++o){let e=m[o];if(0===o||e!==T){if(4===(l=y[e]).components){let e=l.data,t=e.length-4;for(let i=0;i<t;i+=4)e[i+0]*e[i+4]+e[i+1]*e[i+5]+e[i+2]*e[i+6]+e[i+3]*e[i+7]<0&&(e[i+4]*=-1,e[i+5]*=-1,e[i+6]*=-1,e[i+7]*=-1);}T=e;}}let E=0;for(o=0;o<S.length;o++)E=Math.max(E,0===(l=S[o]._data).length?0:l[l.length-1]);return new TZ(e.hasOwnProperty("name")?e.name:`animation_${t}`,E,S,y,x)},Pc=new eG,Pd=new eM,Pu=(e,t,i)=>{let s=new _c;if(e.hasOwnProperty("name")&&e.name.length>0?s.name=e.name:s.name=`node_${t}`,e.hasOwnProperty("matrix")&&(Pc.data.set(e.matrix),Pc.getTranslation(Pd),s.setLocalPosition(Pd),Pc.getEulerAngles(Pd),s.setLocalEulerAngles(Pd),Pc.getScale(Pd),s.setLocalScale(Pd)),e.hasOwnProperty("rotation")){let t=e.rotation;s.setLocalRotation(t[0],t[1],t[2],t[3]);}if(e.hasOwnProperty("translation")){let t=e.translation;s.setLocalPosition(t[0],t[1],t[2]);}if(e.hasOwnProperty("scale")){let t=e.scale;s.setLocalScale(t[0],t[1],t[2]);}return e.hasOwnProperty("extensions")&&e.extensions.EXT_mesh_gpu_instancing&&i.set(e,{ext:e.extensions.EXT_mesh_gpu_instancing}),s},Pf=(e,t)=>{let i="orthographic"===e.type?fm:fp,s=i===fm?e.orthographic:e.perspective,r={enabled:false,projection:i,nearClip:s.znear,aspectRatioMode:pV};s.zfar&&(r.farClip=s.zfar),i===fm?(r.orthoHeight=.5*s.ymag,s.ymag&&(r.aspectRatioMode=pz,r.aspectRatio=s.xmag/s.ymag)):(r.fov=s.yfov*eA.RAD_TO_DEG,s.aspectRatio&&(r.aspectRatioMode=pz,r.aspectRatio=s.aspectRatio));let a=new x1(e.name);return a.addComponent("camera",r),a},Pp=(e,t)=>{let i={enabled:false,type:"point"===e.type?"omni":e.type,color:e.hasOwnProperty("color")?new eb(e.color):eb.WHITE,range:e.hasOwnProperty("range")?e.range:9999,falloffMode:uH,intensity:e.hasOwnProperty("intensity")?eA.clamp(e.intensity,0,2):1};e.hasOwnProperty("spot")&&(i.innerConeAngle=e.spot.hasOwnProperty("innerConeAngle")?e.spot.innerConeAngle*eA.RAD_TO_DEG:0,i.outerConeAngle=e.spot.hasOwnProperty("outerConeAngle")?e.spot.outerConeAngle*eA.RAD_TO_DEG:Math.PI/4),e.hasOwnProperty("intensity")&&(i.luminance=e.intensity*g2.getLightUnitConversion(gZ[i.type],i.outerConeAngle,i.innerConeAngle));let s=new x1(t.name);return s.rotateLocal(90,0,0),s.addComponent("light",i),s},Pm=(e,t,i,s)=>{if(!t.hasOwnProperty("skins")||0===t.skins.length)return [];let r=new Map;return t.skins.map(a=>C2(e,a,t.accessors,s,i,r))},P_=(e,t,i,s)=>{let r={},a={},n={},o=[];return {meshes:!s.skipMeshes&&t?.meshes?.length&&t?.accessors?.length&&t?.bufferViews?.length?t.meshes.map(l=>C4(e,l,t.accessors,i,r,a,n,s,o)):[],meshVariants:a,meshDefaultMaterials:n,promises:o}},Pg=(e,t,i)=>{if(!e.hasOwnProperty("materials")||0===e.materials.length)return [];let s=i?.material?.preprocess,r=i?.material?.process??Pl,a=i?.material?.postprocess;return e.materials.map(e=>{s&&s(e);let i=r(e,t);return a&&a(e,i),i})},Pv=e=>{if(!e.hasOwnProperty("extensions")||!e.extensions.hasOwnProperty("KHR_materials_variants"))return null;let t=e.extensions.KHR_materials_variants.variants,i={};for(let e=0;e<t.length;e++)i[t[e].name]=e;return i},PS=(e,t,i,s)=>{if(!e.hasOwnProperty("animations")||0===e.animations.length)return [];let r=s?.animation?.preprocess,a=s?.animation?.postprocess;return e.animations.map((s,n)=>{r&&r(s);let o=Ph(s,n,e.accessors,i,t,e.meshes,e.nodes);return a&&a(s,o),o})},Py=(e,t,i,s)=>{let r=t.accessors;i.forEach((e,t)=>{let i,a,n,o=e.ext.attributes;o.hasOwnProperty("TRANSLATION")&&(i=Cq(r[o.TRANSLATION],s)),o.hasOwnProperty("ROTATION")&&(a=Cq(r[o.ROTATION],s)),o.hasOwnProperty("SCALE")&&(n=Cq(r[o.SCALE],s));let l=(i?i.length/3:0)||(a?a.length/4:0)||(n?n.length/3:0);if(l){let t=new Float32Array(16*l),s=new eM,r=new eH,o=new eM(1,1,1),h=new eG,c=0;for(let e=0;e<l;e++){let l=3*e;if(i&&s.set(i[l],i[l+1],i[l+2]),a){let t=4*e;r.set(a[t],a[t+1],a[t+2],a[t+3]);}n&&o.set(n[l],n[l+1],n[l+2]),h.setTRS(s,r,o);for(let e=0;e<16;e++)t[c++]=h.data[e];}e.matrices=t;}});},Px=(e,t,i)=>{if(!e.hasOwnProperty("nodes")||0===e.nodes.length)return [];let s=t?.node?.preprocess,r=t?.node?.process??Pu,a=t?.node?.postprocess,n=e.nodes.map((e,t)=>{s&&s(e);let n=r(e,t,i);return a&&a(e,n),n});for(let t=0;t<e.nodes.length;++t){let i=e.nodes[t];if(i.hasOwnProperty("children")){let e=n[t],s={};for(let t=0;t<i.children.length;++t){let r=n[i.children[t]];r.parent||(s.hasOwnProperty(r.name)?r.name+=s[r.name]++:s[r.name]=1,e.addChild(r));}}}return n},PT=(e,t)=>{let i=[],s=e.scenes.length;if(1===s&&e.scenes[0].nodes?.length===1){let s=e.scenes[0].nodes[0];i.push(t[s]);}else for(let r=0;r<s;r++){let s=e.scenes[r];if(s.nodes){let e=new _c(s.name);for(let i=0;i<s.nodes.length;i++){let r=t[s.nodes[i]];e.addChild(r);}i.push(e);}}return i},PE=(e,t,i)=>{let s=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("cameras")&&e.cameras.length>0){let r=i?.camera?.preprocess,a=i?.camera?.process??Pf,n=i?.camera?.postprocess;e.nodes.forEach((i,o)=>{if(i.hasOwnProperty("camera")){let l=e.cameras[i.camera];if(l){r&&r(l);let e=a(l,t[o]);n&&n(l,e),e&&(s||(s=new Map),s.set(i,e));}}});}return s},PA=(e,t,i)=>{let s=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("lights")){let r=e.extensions.KHR_lights_punctual.lights;if(r.length){let a=i?.light?.preprocess,n=i?.light?.process??Pp,o=i?.light?.postprocess;e.nodes.forEach((e,i)=>{if(e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("light")){let l=r[e.extensions.KHR_lights_punctual.light];if(l){a&&a(l);let r=n(l,t[i]);o&&o(l,r),r&&(s||(s=new Map),s.set(e,r));}}});}}return s},Pb=(e,t,i)=>{e.nodes.forEach(e=>{e.hasOwnProperty("mesh")&&e.hasOwnProperty("skin")&&t[e.mesh].meshes.forEach(t=>{t.skin=i[e.skin];});});},Pw=async(e,t,i,s,r)=>{let a=r?.global?.preprocess,n=r?.global?.postprocess;a&&a(t),t.asset&&t.asset.generator;let o=new Map,l=Px(t,r,o),h=PT(t,l),c=PA(t,l,r),d=PE(t,l,r),u=Pv(t),f=await Promise.all(i),{meshes:p,meshVariants:m,meshDefaultMaterials:_,promises:g}=P_(e,t,f,r),v=PS(t,l,f,r);Py(e,t,o,f);let S=await Promise.all(s),y=Pg(t,S.map(e=>e.resource),r),x=Pm(e,t,l,f),T=[];for(let e=0;e<p.length;e++)T[e]=new Cx,T[e].meshes=p[e];Pb(t,T,x);let E=new CN;return E.gltf=t,E.nodes=l,E.scenes=h,E.animations=v,E.textures=S,E.materials=y,E.variants=u,E.meshVariants=m,E.meshDefaultMaterials=_,E.renders=T,E.skins=x,E.lights=c,E.cameras=d,E.nodeInstancingMap=o,n&&n(t,E),await Promise.all(g),E},PC=(e,t)=>{let i=(e,t)=>{switch(e){case 9728:return tK;case 9729:return tZ;case 9984:return tQ;case 9985:return t0;case 9986:return tJ;case 9987:return t1;default:return t}},s=(e,t)=>{switch(e){case 33071:return tr;case 33648:return ta;case 10497:return ts;default:return t}};e&&(e.minFilter=i((t=t??{}).minFilter,t1),e.magFilter=i(t.magFilter,tZ),e.addressU=s(t.wrapS,ts),e.addressV=s(t.wrapT,ts));},PP=0,PL=e=>e.extensions?.KHR_texture_basisu?.source??e.extensions?.EXT_texture_webp?.source??e.source,PI=(e,t,i,s,r)=>{if(!e.images||0===e.images.length)return [];let a=r?.image?.preprocess,n=r?.image?.processAsync,o=r?.image?.postprocess,l={"image/png":"png","image/jpeg":"jpg","image/basis":"basis","image/ktx":"ktx","image/ktx2":"ktx2","image/vnd-ms.dds":"dds"},h=(e,t,i,r,a,n)=>new Promise((o,h)=>{let c=i=>{let c=`${e.name||"gltf-texture"}-${PP++}`,d={url:t||c};if(i&&(d.contents=i.slice(0).buffer),r){let e=l[r];e&&(d.filename=`${d.url}.${e}`);}let u=new xF(c,"texture",d,{srgb:n},a);u.on("load",e=>o(e)),u.on("error",e=>h(e)),s.add(u),s.load(u);};i?i.then(e=>c(e)):c(null);}),c=(e=>{let t=new Set;return e.hasOwnProperty("materials")&&e.materials.forEach(i=>{if(i.hasOwnProperty("pbrMetallicRoughness")){let s=i.pbrMetallicRoughness;if(s.hasOwnProperty("baseColorTexture")){let i=e.textures[s.baseColorTexture.index];t.add(PL(i));}}if(i.hasOwnProperty("emissiveTexture")){let s=e.textures[i.emissiveTexture.index];t.add(PL(s));}if(i.hasOwnProperty("extensions")){let s=i.extensions.KHR_materials_sheen;if(s&&s.hasOwnProperty("sheenColorTexture")){let i=e.textures[s.sheenColorTexture.index];t.add(PL(i));}let r=i.extensions.KHR_materials_pbrSpecularGlossiness;if(r&&r.hasOwnProperty("specularGlossinessTexture")){let i=e.textures[r.specularGlossinessTexture.index];t.add(PL(i));}let a=i.extensions.KHR_materials_specular;if(a&&a.hasOwnProperty("specularColorTexture")){let i=e.textures[a.specularColorTexture.index];t.add(PL(i));}}}),t})(e);return e.images.map((e,s)=>{let r;return a&&a(e),r=(r=new Promise(n?(t,i)=>{n(e,(e,s)=>{e?i(e):t(s);});}:e=>{e(null);})).then(r=>{let a=c.has(s);return r?r:e.hasOwnProperty("uri")?CF(e.uri)?h(e,e.uri,null,CB(e.uri),null,a):h(e,x_.test(e.uri)?e.uri:W.join(i,e.uri),null,null,{crossOrigin:"anonymous"},a):e.hasOwnProperty("bufferView")&&e.hasOwnProperty("mimeType")?h(e,null,t[e.bufferView],e.mimeType,null,a):Promise.reject(Error(`Invalid image found in gltf (neither uri or bufferView found). index=${s}`))}),o&&(r=r.then(t=>(o(e,t),t))),r})},PD=(e,t,i)=>{if(!e?.images?.length||!e?.textures?.length)return [];let s=i?.texture?.preprocess,r=i?.texture?.processAsync,a=i?.texture?.postprocess,n=new Set;return e.textures.map(i=>{let o;return s&&s(i),o=(o=new Promise(r?(t,s)=>{r(i,e.images,(e,i)=>{e?s(e):t(i);});}:e=>{e(null);})).then(s=>{s=s??PL(i);let r=n.has(s);return n.add(s),t[s].then(t=>{let s=r?CJ(t):t;return PC(s.resource,(e.samplers??[])[i.sampler]),s})}),a&&(o=o.then(e=>(a(i,e),e))),o})},PR=(e,t,i,s)=>{if(!e.buffers||0===e.buffers.length)return [];let r=s?.buffer?.preprocess,a=s?.buffer?.processAsync,n=s?.buffer?.postprocess;return e.buffers.map((s,o)=>{let l;return r&&r(s),l=(l=new Promise(a?(e,t)=>{a(s,(i,s)=>{i?t(i):e(s);});}:e=>{e(null);})).then(e=>{if(e)return e;if(s.hasOwnProperty("uri")){if(CF(s.uri)){let e=atob(s.uri.split(",")[1]),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}return new Promise((e,t)=>{d1.get(x_.test(s.uri)?s.uri:W.join(i,s.uri),{cache:true,responseType:"arraybuffer",retry:false},(i,s)=>{i?t(i):e(new Uint8Array(s));});})}return t}),n&&(l=l.then(t=>(n(e.buffers[o],t),t))),l})},PM=(e,t)=>{let i=JSON.parse((e=>{if("undefined"!=typeof TextDecoder)return new TextDecoder().decode(e);let t="";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return decodeURIComponent(escape(t))})(e));if(i.asset&&i.asset.version&&2>parseFloat(i.asset.version))return void t(`Invalid gltf version. Expected version 2.0 or above but found version '${i.asset.version}'.`);t(null,i);},PO=(e,t)=>{let i=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),s=i.getUint32(0,true),r=i.getUint32(4,true),a=i.getUint32(8,true);if(0x46546c67!==s)return void t(`Invalid magic number found in glb header. Expected 0x46546C67, found 0x${s.toString(16)}`);if(2!==r)return void t(`Invalid version number found in glb header. Expected 2, found ${r}`);if(a<=0||a>i.byteLength)return void t(`Invalid length found in glb header. Found ${a}`);let n=[],o=12;for(;o<a;){let e=i.getUint32(o,true);o+e+8>i.byteLength&&t(`Invalid chunk length found in glb. Found ${e}`);let s=i.getUint32(o+4,true),r=new Uint8Array(i.buffer,i.byteOffset+o+8,e);n.push({length:e,type:s,data:r}),o+=e+8;}return 1!==n.length&&2!==n.length?void t("Invalid number of chunks found in glb file."):0x4e4f534a!==n[0].type?void t(`Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x${n[0].type.toString(16)}`):n.length>1&&5130562!==n[1].type?void t(`Invalid chunk type found in glb file. Expected 0x004E4942, found 0x${n[1].type.toString(16)}`):void t(null,{gltfChunk:n[0].data,binaryChunk:2===n.length?n[1].data:null})},PN=(e,t,i)=>{e&&e.toLowerCase().endsWith(".glb")||(()=>{let e=new Uint8Array(t);return 103===e[0]&&108===e[1]&&84===e[2]&&70===e[3]})()?PO(t,i):i(null,{gltfChunk:t,binaryChunk:null});},PF=(e,t,i)=>{let s=[],r=i?.bufferView?.preprocess,a=i?.bufferView?.processAsync,n=i?.bufferView?.postprocess;if(!e.bufferViews?.length)return s;for(let i=0;i<e.bufferViews.length;++i){let o,l=e.bufferViews[i];r&&r(l),o=(o=new Promise(a?(e,i)=>{a(l,t,(t,s)=>{t?i(t):e(s);});}:e=>{e(null);})).then(e=>e||t[l.buffer].then(e=>new Uint8Array(e.buffer,e.byteOffset+(l.byteOffset||0),l.byteLength))),l.hasOwnProperty("byteStride")&&(o=o.then(e=>(e.byteStride=l.byteStride,e))),n&&(o=o.then(e=>(n(l,e),e))),s.push(o);}return s};class PB{static parse(e,t,i,s,r,a,n){PN(e,i,(e,i)=>{if(e)return void n(e);PM(i.gltfChunk,(e,o)=>{if(e)return void n(e);let l=PR(o,i.binaryChunk,t,a),h=PF(o,l,a),c=PI(o,h,t,r,a),d=PD(o,c,a);Pw(s,o,h,d,a).then(e=>n(null,e)).catch(e=>n(e));});});}static createDefaultMaterial(){return Pl({name:"defaultGlbMaterial"},[])}}class PU extends xH{constructor(e){super(e,"animation"),this.device=e.graphicsDevice,this.assets=e.assets;}load(e,t,i){"string"==typeof e&&(e={load:e,original:e});let s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===W.getExtension(e.original).toLowerCase()?s.responseType=d0.ResponseType.ARRAY_BUFFER:s.responseType=d0.ResponseType.JSON),d1.get(e.load,s,(s,r)=>{s?t(`Error loading animation resource: ${e.original} [${s}]`):".glb"===W.getExtension(e.original).toLowerCase()?PB.parse("filename.glb","",r,this.device,this.assets,i?.options??{},(e,s)=>{if(e)t(e);else {let e=s.animations;if(i?.data?.events)for(let t=0;t<e.length;t++)e[t].events=new TK(Object.values(i.data.events));s.destroy(),t(null,e);}}):t(null,this[`_parseAnimationV${r.animation.version}`](r));});}open(e,t,i){return t}_parseAnimationV3(e){let t=e.animation,i=new Sk;i.name=t.name,i.duration=t.duration;for(let e=0;e<t.nodes.length;e++){let s=new SU,r=t.nodes[e];s._name=r.name;for(let e=0;e<r.keys.length;e++){let t=r.keys[e],i=t.time,a=t.pos,n=t.rot,o=t.scale,l=new eM(a[0],a[1],a[2]),h=new SB(i,l,new eH().setFromEulerAngles(n[0],n[1],n[2]),new eM(o[0],o[1],o[2]));s._keys.push(h);}i.addNode(s);}return i}_parseAnimationV4(e){let t=e.animation,i=new Sk;i.name=t.name,i.duration=t.duration;for(let e=0;e<t.nodes.length;e++){let s=new SU,r=t.nodes[e];s._name=r.name;let a=r.defaults.p,n=r.defaults.r,o=r.defaults.s;for(let e=0;e<r.keys.length;e++){let t=r.keys[e],i=t.t,l=a||t.p,h=n||t.r,c=o||t.s,d=new eM(l[0],l[1],l[2]),u=new SB(i,d,new eH().setFromEulerAngles(h[0],h[1],h[2]),new eM(c[0],c[1],c[2]));s._keys.push(u);}i.addNode(s);}return i}}class Pk extends xH{constructor(e){super(e,"animclip");}load(e,t){"string"==typeof e&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=d0.ResponseType.JSON),d1.get(e.load,i,(i,s)=>{i?t(`Error loading animation clip resource: ${e.original} [${i}]`):t(null,s);});}open(e,t){let i=t.name,s=t.duration,r=t.inputs.map(e=>new CC(1,e));return new TZ(i,s,r,t.outputs.map(e=>new CC(e.components,e.data)),t.curves.map(e=>new Cw([e.path],e.inputIndex,e.outputIndex,e.interpolation)))}}class PV extends xH{constructor(e){super(e,"animstategraph");}load(e,t){"string"==typeof e&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=d0.ResponseType.JSON),d1.get(e.load,i,(i,s)=>{i?t(`Error loading animation state graph resource: ${e.original} [${i}]`):t(null,s);});}open(e,t){return new Ed(t)}}let Pz=function(){if("undefined"==typeof window)return false;let e=window.navigator.userAgent,t=e.indexOf("MSIE ");if(t>0)return parseInt(e.substring(t+5,e.indexOf(".",t)),10);if(e.indexOf("Trident/")>0){let t=e.indexOf("rv:");return parseInt(e.substring(t+3,e.indexOf(".",t)),10)}return false}(),PG=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"];class PH extends xH{constructor(e){super(e,"audio"),this.manager=e.soundManager;}_isSupported(e){let t=W.getExtension(e);return PG.indexOf(t)>-1}load(e,t){"string"==typeof e&&(e={load:e,original:e});let i=function(i){let s=`Error loading audio url: ${e.original}`;i&&(s+=`: ${i.message||i}`),t(s);};if(this._createSound){if(!this._isSupported(e.original))return void i(`Audio format for ${e.original} not supported`);this._createSound(e.load,function(e){t(null,new d7(e));},i);}else i(null);}_createSound(e,t,i){if(ue()){let s=this.manager;if(!s.context)return void i("Audio manager has no audio context");let r={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.startsWith("blob:")||e.startsWith("data:"))&&(r.responseType=d0.ResponseType.ARRAY_BUFFER),d1.get(e,r,(e,r)=>{if(e)return void i(e);s.context.decodeAudioData(r,t,i);});}else {let s=null;try{s=new Audio;}catch(e){i("No support for Audio element");return}Pz&&document.body.appendChild(s);let r=function(){s.removeEventListener("canplaythrough",r),Pz&&document.body.removeChild(s),t(s);};s.onerror=function(){s.onerror=null,Pz&&document.body.removeChild(s),i();},s.addEventListener("canplaythrough",r),s.src=e;}}}class PW extends xH{constructor(e){super(e,"binary");}load(e,t){"string"==typeof e&&(e={load:e,original:e}),d1.get(e.load,{responseType:d0.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t(`Error loading binary resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return e.buffer}}class PX{constructor(e,t,i,s){let r=function(e,s,r){let a=PX.createAsset(t.name,e,s,r);return i.add(a),a},a=[];for(let t=0;t<e.renders.length;++t)a.push(r("render",e.renders[t],t));let n=[];for(let t=0;t<e.materials.length;++t)n.push(r("material",e.materials[t],t));let o=[];for(let t=0;t<e.animations.length;++t)o.push(r("animation",e.animations[t],t));this.data=e,this._model=null,this._assetName=t.name,this._assets=i,this._defaultMaterial=s,this.renders=a,this.materials=n,this.textures=e.textures,this.animations=o;}get model(){if(!this._model){let e=PX.createModel(this.data,this._defaultMaterial),t=PX.createAsset(this._assetName,"model",e,0);this._assets.add(t),this._model=t;}return this._model}static createAsset(e,t,i,s){let r=new xF(`${e}/${t}/${s}`,t,{url:""});return r.resource=i,r.loaded=true,r}instantiateModelEntity(e){let t=new x1(void 0,this._assets._loader._app);return t.addComponent("model",Object.assign({type:"asset",asset:this.model},e)),t}instantiateRenderEntity(e){let t=this._defaultMaterial,i=[],s=function(e,s,r,a,n,o,l,h){let c=n[r.id],d=new mV(r,void 0===c?t:a[c]);r.morph&&(d.morphInstance=new g4(r.morph)),l.hasOwnProperty("skin")&&i.push({meshInstance:d,rootBone:e,entity:s});let u=h.get(l);if(u){let e=u.matrices,t=nP.getDefaultInstancingFormat(r.device),i=new nT(r.device,t,e.length/16,{data:e});d.setInstancing(i),d.instancingData._destroyVertexBuffer=true;}return d},r=(t,i,a)=>{let n=new x1(void 0,this._assets._loader._app);i._cloneInternal(n),t||(t=n);let o=null,l=null;for(let e=0;e<a.nodes.length;e++)if(a.nodes[e]===i){let i=a.gltf.nodes[e];if(i.hasOwnProperty("mesh")){let e=a.renders[i.mesh].meshes;l=this.renders[i.mesh];for(let r=0;r<e.length;r++){let l=e[r];if(l){let e=s(t,n,l,a.materials,a.meshDefaultMaterials,a.skins,i,a.nodeInstancingMap);o||(o=[]),o.push(e);}}}if(a.lights){let e=a.lights.get(i);e&&n.addChild(e.clone());}if(a.cameras){let e=a.cameras.get(i);e&&e.camera.system.cloneComponent(e,n);}}o&&(n.addComponent("render",Object.assign({type:"asset",meshInstances:o},e)),n.render.assignAsset(l));let h=i.children;for(let e=0;e<h.length;e++){let i=r(t,h[e],a);n.addChild(i);}return n},a=[];for(let e of this.data.scenes)a.push(r(null,e,this.data));return i.forEach(e=>{e.meshInstance.skinInstance=bq.createCachedSkinInstance(e.meshInstance.mesh.skin,e.rootBone,e.entity),e.meshInstance.node.render.rootBone=e.rootBone;}),PX.createSceneHierarchy(a,x1)}getMaterialVariants(){return this.data.variants?Object.keys(this.data.variants):[]}applyMaterialVariant(e,t){let i=t?this.data.variants[t]:null;if(void 0===i)return;let s=e.findComponents("render");for(let e=0;e<s.length;e++){let t=s[e];this._applyMaterialVariant(i,t.meshInstances);}}applyMaterialVariantInstances(e,t){let i=t?this.data.variants[t]:null;void 0!==i&&this._applyMaterialVariant(i,e);}_applyMaterialVariant(e,t){t.forEach(t=>{if(null===e)t.material=this._defaultMaterial;else {let i=this.data.meshVariants[t.mesh.id];i&&(t.material=this.data.materials[i[e]]);}});}static createSceneHierarchy(e,t){let i=null;if(1===e.length)i=e[0];else for(let s of(i=new t("SceneGroup"),e))i.addChild(s);return i}static createModel(e,t){let i=new g5,s=[];for(let t of e.skins){let e=new mx(t);e.bones=t.bones,s.push(e);}i.graph=PX.createSceneHierarchy(e.scenes,_c);for(let r=0;r<e.nodes.length;r++){let a=e.nodes[r];if(a.root===i.graph){let n=e.gltf.nodes[r];if(n.hasOwnProperty("mesh")){let r=e.renders[n.mesh].meshes;for(let o=0;o<r.length;o++){let l=r[o];l&&function(i,s,r,a,n,o,l){let h=e.meshDefaultMaterials[s.id],c=new mV(s,void 0===h?t:n[h],o);if(s.morph){let e=new g4(s.morph);c.morphInstance=e,i.morphInstances.push(e);}if(l.hasOwnProperty("skin")){let e=l.skin;s.skin=r[e];let t=a[e];c.skinInstance=t,i.skinInstances.push(t);}i.meshInstances.push(c);}(i,l,e.skins,s,e.materials,a,n);}}}}return i}destroy(){let e=this._assets,t=function(t){e.remove(t),t.unload();},i=function(e){e.forEach(e=>{t(e);});};this.animations&&(i(this.animations),this.animations=null),this.textures&&(i(this.textures),this.textures=null),this.materials&&(i(this.materials),this.materials=null),this.renders&&(i(this.renders),this.renders=null),this._model&&(t(this._model),this._model=null),this.data=null,this.assets=null;}}class PY{constructor(e,t,i){this._device=e,this._assets=t,this._defaultMaterial=PB.createDefaultMaterial(),this.maxRetries=i;}_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}load(e,t,i){xF.fetchArrayBuffer(e.load,(s,r)=>{s?t(s):PB.parse(this._getUrlWithoutParams(e.original),W.extractPath(e.load),r,this._device,i.registry,i.options,(e,s)=>{e?t(e):t(null,new PX(s,i,this._assets,this._defaultMaterial));});},i,this.maxRetries);}open(e,t,i){return t}patch(e,t){}}class Pq{instantiateModelEntity(e){return null}instantiateRenderEntity(e){return null}getMaterialVariants(){return null}applyMaterialVariant(e,t){}applyMaterialVariantInstances(e,t){}}class P$ extends xH{constructor(e){super(e,"container"),this.glbContainerParser=new PY(e.graphicsDevice,e.assets,0),this.parsers={};}set maxRetries(e){for(let t in this.glbContainerParser.maxRetries=e,this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e);}get maxRetries(){return this.glbContainerParser.maxRetries}_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}_getParser(e){let t=e?W.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".",""):null;return this.parsers[t]||this.glbContainerParser}load(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i);}open(e,t,i){return this._getParser(e).open(e,t,i)}}class Pj extends xH{constructor(e){super(e,"css"),this.decoder=null;}load(e,t){"string"==typeof e&&(e={load:e,original:e}),d1.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t(`Error loading css resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return this.decoder??=new TextDecoder("utf-8"),this.decoder.decode(e)}}class PK extends xH{constructor(e){super(e,"cubemap"),this._device=e.graphicsDevice,this._registry=e.assets,this._loader=e.loader;}load(e,t,i){this.loadAssets(i,t);}open(e,t,i){return i?i.resource:null}patch(e,t){this.loadAssets(e,(i,s)=>{i&&(t.fire("error",e),t.fire(`error:${e.id}`,i,e),e.fire("error",e));});}getAssetIds(e){let t=[];if(t[0]=e.file,(e.loadFaces||!e.file)&&e.data&&e.data.textures)for(let i=0;i<6;++i)t[i+1]=e.data.textures[i];else t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=null;return t}compareAssetIds(e,t){return e&&t?parseInt(e,10)===e||"string"==typeof e?e===t:e.url===t.url:null!==e==(null!==t)}update(e,t,i){let s,r,a,n=e.data||{},o=e._handlerState.assets,l=e._resources,h=[null,null,null,null,null,null,null],c=function(){return n.hasOwnProperty("type")?n.type:n.hasOwnProperty("rgbm")?n.rgbm?ri:rt:null};if(e.loaded&&i[0]===o[0])h[1]=l[1]||null,h[2]=l[2]||null,h[3]=l[3]||null,h[4]=l[4]||null,h[5]=l[5]||null,h[6]=l[6]||null;else if(i[0])if((s=i[0].resource).cubemap)for(a=0;a<6;++a)h[a+1]=new ns(this._device,{name:`${e.name}_prelitCubemap${s.width>>a}`,cubemap:true,type:c()||s.type,width:s.width>>a,height:s.height>>a,format:s.format,levels:[s._levels[a]],addressU:tr,addressV:tr,mipmaps:0===a});else h[1]=s;let d=i.slice(1);if(e.loaded&&this.cmpArrays(d,o.slice(1)))h[0]=l[0]||null;else if(-1===d.indexOf(null)){let t=d.map(e=>e.resource),i=[];for(r=0;r<t[0]._levels.length;++r)i.push(t.map(e=>e._levels[r]));let s=t[0].format,a=new ns(this._device,{name:`${e.name}_faces`,cubemap:true,type:c()||t[0].type,width:t[0].width,height:t[0].height,format:s===ic?id:s,mipmaps:n.mipmaps??true,levels:i,minFilter:n.hasOwnProperty("minFilter")?n.minFilter:t[0].minFilter,magFilter:n.hasOwnProperty("magFilter")?n.magFilter:t[0].magFilter,anisotropy:n.hasOwnProperty("anisotropy")?n.anisotropy:1,addressU:tr,addressV:tr});h[0]=a;}if(!this.cmpArrays(h,l))for(a=0,e.resources=h,e._handlerState.assetIds=t,e._handlerState.assets=i;a<l.length;++a)null!==l[a]&&-1===h.indexOf(l[a])&&l[a].destroy();for(a=0;a<o.length;++a)null!==o[a]&&-1===i.indexOf(o[a])&&o[a].unload();}cmpArrays(e,t){if(e.length!==t.length)return false;for(let i=0;i<e.length;++i)if(e[i]!==t[i])return false;return true}resolveId(e){let t=parseInt(e,10);return t===e||t.toString()===e?t:e}loadAssets(e,t){let i;e.hasOwnProperty("_handlerState")||(e._handlerState={assetIds:[null,null,null,null,null,null,null],assets:[null,null,null,null,null,null,null]});let s=this,r=s.getAssetIds(e),a=[null,null,null,null,null,null,null],n=e._handlerState.assetIds,o=e._handlerState.assets,l=s._registry,h=7,c=function(i,n){a[i]=n,0==--h&&(s.update(e,r,a),t(null,e.resources));},d=function(e,i,s){t(i);},u=function(e,t){t.loaded?c(e,t):(l.once(`load:${t.id}`,c.bind(s,e)),l.once(`error:${t.id}`,d.bind(s,e)),t.loading||l.load(t));};for(let t=0;t<7;++t){let a=this.resolveId(r[t]);if(a)if(s.compareAssetIds(a,n[t]))u(t,o[t]);else if(parseInt(a,10)===a)(i=l.get(a))?u(t,i):setTimeout(((e,t)=>{let i=l.get(t);i?u(e,i):d(e,`failed to find dependent cubemap asset=${t}`);}).bind(null,t,a));else {let s="string"==typeof a?{url:a,filename:a}:a,r=-1===s.url.search(".dds")?{type:"rgbp",addressu:"clamp",addressv:"clamp",mipmaps:false}:null;i=new xF(`${e.name}_part_${t}`,"texture",s,r),l.add(i),u(t,i);}else c(t,null);}}}class PZ extends xH{constructor(e){super(e,"folder");}load(e,t){t(null,null);}}class PQ{constructor(e,t){this.type=t&&t.type||AD,this.em=1,this.textures=e,this.intensity=0,this._data=null,this.data=t;}set data(e){if(this._data=e,e&&(void 0!==this._data.intensity&&(this.intensity=this._data.intensity),this._data.info||(this._data.info={}),!this._data.version||this._data.version<2)&&(this._data.info.maps=[{width:this._data.info.width,height:this._data.info.height}],this._data.chars))for(let e in this._data.chars)this._data.chars[e].map=0;}get data(){return this._data}}function PJ(e){return e.version<3&&(e.version<2&&(e.info.maps=e.info.maps||[{width:e.info.width,height:e.info.height}]),e.chars=Object.keys(e.chars||{}).reduce((t,i)=>{let s=e.chars[i],r=void 0!==s.letter?s.letter:ea.fromCodePoint(i);return e.version<2&&(s.map=s.map||0),t[r]=s,t},{}),e.version=3),e}class P0 extends xH{constructor(e){super(e,"font"),this._loader=e.loader,this.maxRetries=0;}load(e,t,i){"string"==typeof e&&(e={load:e,original:e});let s=this;".json"===W.getExtension(e.original)?d1.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,r)=>{if(i)t(`Error loading font resource: ${e.original} [${i}]`);else {let i=PJ(r);s._loadTextures(e.load.replace(".json",".png"),i,(e,s)=>{e?t(e):t(null,{data:i,textures:s});});}}):(i&&i.data&&(i.data=PJ(i.data)),this._loadTextures(e.load,i&&i.data,t));}_loadTextures(e,t,i){let s=t.info.maps.length,r=0,a=null,n=Array(s),o=this._loader,l=function(t){let l=function(e,o){if(!a){if(e){a=e,i(e);return}o.upload(),n[t]=o,++r===s&&i(null,n);}};0===t?o.load(e,"texture",l):o.load(e.replace(".png",`${t}.png`),"texture",l);};for(let e=0;e<s;e++)l(e);}open(e,t,i){return t.textures?new PQ(t.textures,t.data):new PQ(t,null)}patch(e,t){let i=e.resource;!i.data&&e.data?i.data=e.data:!e.data&&i.data&&(e.data=i.data),e.data&&(e.data=PJ(e.data));}}class P1{constructor(e,t,i,s,r,a){let n=(e,t)=>{let i=(1<<t)-1;return (e&i)/i},o=(e,t)=>{e.x=n(t>>>21,11),e.y=n(t>>>11,10),e.z=n(t,11);},l=(e,t)=>{e.x=n(t>>>24,8),e.y=n(t>>>16,8),e.z=n(t>>>8,8),e.w=n(t,8);},h=(e,t)=>{let i=1/(.5*Math.sqrt(2)),s=(n(t>>>20,10)-.5)*i,r=(n(t>>>10,10)-.5)*i,a=(n(t,10)-.5)*i,o=Math.sqrt(1-(s*s+r*r+a*a));switch(t>>>30){case 0:e.set(s,r,a,o);break;case 1:e.set(o,r,a,s);break;case 2:e.set(r,o,a,s);break;case 3:e.set(r,a,o,s);}},c=(e,t,i)=>e*(1-i)+t*i,{chunkData:d,chunkSize:u,vertexData:f,shData0:p,shData1:m,shData2:_,shBands:g}=e,v=[3,8,15][g-1];this.read=e=>{let n=Math.floor(e/256)*u;if(t&&(o(t,f[4*e+0]),t.x=c(d[n+0],d[n+3],t.x),t.y=c(d[n+1],d[n+4],t.y),t.z=c(d[n+2],d[n+5],t.z)),i&&h(i,f[4*e+1]),s&&(o(s,f[4*e+2]),s.x=c(d[n+6],d[n+9],s.x),s.y=c(d[n+7],d[n+10],s.y),s.z=c(d[n+8],d[n+11],s.z)),r&&(l(r,f[4*e+3]),u>12&&(r.x=c(d[n+12],d[n+15],r.x),r.y=c(d[n+13],d[n+16],r.y),r.z=c(d[n+14],d[n+17],r.z))),a&&g>0){let t=[p,m,_];for(let i=0;i<3;++i)for(let s=0;s<15;++s)a[15*i+s]=s<v?t[i][16*e+s]*(8/255)-4:0;}};}}class P2{createIter(e,t,i,s,r){return new P1(this,e,t,i,s,r)}calcAabb(e){let{chunkData:t,numChunks:i,chunkSize:s}=this,r=Math.exp(Math.max(t[9],t[10],t[11])),a=t[0]-r,n=t[1]-r,o=t[2]-r,l=t[3]+r,h=t[4]+r,c=t[5]+r;for(let e=1;e<i;++e){let i=e*s;r=Math.exp(Math.max(t[i+9],t[i+10],t[i+11])),a=Math.min(a,t[i+0]-r),n=Math.min(n,t[i+1]-r),o=Math.min(o,t[i+2]-r),l=Math.max(l,t[i+3]+r),h=Math.max(h,t[i+4]+r),c=Math.max(c,t[i+5]+r);}return e.center.set((a+l)*.5,(n+h)*.5,(o+c)*.5),e.halfExtents.set((l-a)*.5,(h-n)*.5,(c-o)*.5),true}getCenters(e){let t,i,s,r,a,n,{vertexData:o,chunkData:l,numChunks:h,chunkSize:c}=this;for(let d=0;d<h;++d){let h=d*c;t=l[h+0],i=l[h+1],s=l[h+2],r=l[h+3],a=l[h+4],n=l[h+5];let u=Math.min(this.numSplats,(d+1)*256);for(let l=256*d;l<u;++l){let h=o[4*l],c=(h>>>21)/2047,d=(h>>>11&1023)/1023,u=(2047&h)/2047;e[3*l+0]=(1-c)*t+c*r,e[3*l+1]=(1-d)*i+d*a,e[3*l+2]=(1-u)*s+u*n;}}}getChunks(e){let t,i,s,r,a,n,{chunkData:o,numChunks:l,chunkSize:h}=this;for(let c=0;c<l;++c){let l=c*h;t=o[l+0],i=o[l+1],s=o[l+2],r=o[l+3],a=o[l+4],n=o[l+5],e[6*c+0]=t,e[6*c+1]=i,e[6*c+2]=s,e[6*c+3]=r,e[6*c+4]=a,e[6*c+5]=n;}}calcFocalPoint(e){let{chunkData:t,numChunks:i,chunkSize:s}=this;e.x=0,e.y=0,e.z=0;for(let r=0;r<i;++r){let i=r*s;e.x+=t[i+0]+t[i+3],e.y+=t[i+1]+t[i+4],e.z+=t[i+2]+t[i+5];}e.mulScalar(.5/i);}get isCompressed(){return true}get numChunks(){return Math.ceil(this.numSplats/256)}get chunkSize(){return this.chunkData.length/this.numChunks}decompress(){let e=["x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3"],{shBands:t}=this;if(t>0){let t=[];for(let e=0;e<45;++e)t.push(`f_rest_${e}`);e.splice(e.indexOf("f_dc_0")+1,0,...t);}let i={};e.forEach(e=>{i[e]=new Float32Array(this.numSplats);});let s=new eM,r=new eH,a=new eM,n=new eF,o=t>0?new Float32Array(45):null,l=this.createIter(s,r,a,n,o);for(let e=0;e<this.numSplats;++e)if(l.read(e),i.x[e]=s.x,i.y[e]=s.y,i.z[e]=s.z,i.rot_1[e]=r.x,i.rot_2[e]=r.y,i.rot_3[e]=r.z,i.rot_0[e]=r.w,i.scale_0[e]=a.x,i.scale_1[e]=a.y,i.scale_2[e]=a.z,i.f_dc_0[e]=(n.x-.5)/.28209479177387814,i.f_dc_1[e]=(n.y-.5)/.28209479177387814,i.f_dc_2[e]=(n.z-.5)/.28209479177387814,i.opacity[e]=n.w<=0?-40:n.w>=1?40:-Math.log(1/n.w-1),o)for(let t=0;t<45;++t)i[`f_rest_${t}`][e]=o[t];return new yM([{name:"vertex",count:this.numSplats,properties:e.map(e=>({name:e,type:"float",byteSize:4,storage:i[e]}))}],this.comments)}}let P3=(e,t,i,s,r)=>{for(let a=0;a<r;++a)for(let r=0;r<s;++r)e[a*t+r]=i[a*s+r];};class P4 extends yO{constructor(e,t){super(e,t);let{chunkData:i,chunkSize:s,numChunks:r,numSplats:a,vertexData:n,shBands:o}=t;this.chunks=new Float32Array(6*r),t.getChunks(this.chunks),this.packedTexture=this.createTexture("packedData",i0,this.evalTextureSize(a),n);let l=this.evalTextureSize(r);l.x*=5,this.chunkTexture=this.createTexture("chunkData",iS,l);let h=this.chunkTexture.lock();if(P3(h,20,i,s,r),12===s)for(let e=0;e<r;++e)h[20*e+15]=1,h[20*e+16]=1,h[20*e+17]=1;if(this.chunkTexture.unlock(),o>0){let e=this.evalTextureSize(a);this.shTexture0=this.createTexture("shTexture0",i0,e,new Uint32Array(t.shData0.buffer)),this.shTexture1=this.createTexture("shTexture1",i0,e,new Uint32Array(t.shData1.buffer)),this.shTexture2=this.createTexture("shTexture2",i0,e,new Uint32Array(t.shData2.buffer));}else this.shTexture0=null,this.shTexture1=null,this.shTexture2=null;}destroy(){this.packedTexture?.destroy(),this.chunkTexture?.destroy(),this.shTexture0?.destroy(),this.shTexture1?.destroy(),this.shTexture2?.destroy(),super.destroy();}configureMaterial(e){e.setDefine("GSPLAT_COMPRESSED_DATA",true),e.setParameter("packedTexture",this.packedTexture),e.setParameter("chunkTexture",this.chunkTexture),this.shTexture0?(e.setDefine("SH_BANDS",3),e.setParameter("shTexture0",this.shTexture0),e.setParameter("shTexture1",this.shTexture1),e.setParameter("shTexture2",this.shTexture2)):e.setDefine("SH_BANDS",0);}evalTextureSize(e){let t=Math.ceil(Math.sqrt(e)),i=Math.ceil(e/t);return new eN(t,i)}}let P5=new Uint8Array([112,108,121,10]),P8=new Uint8Array([10,101,110,100,95,104,101,97,100,101,114,10]),P6=new Map([["char",Int8Array],["uchar",Uint8Array],["short",Int16Array],["ushort",Uint16Array],["int",Int32Array],["uint",Uint32Array],["float",Float32Array],["double",Float64Array]]);class P9{constructor(e,t){this.head=0,this.tail=0,this.reader=e,this.progressFunc=t;}async read(){let{value:e,done:t}=await this.reader.read();if(t)throw Error("Stream finished before end of header");this.push(e),this.progressFunc?.(e.byteLength);}push(e){if(this.data){let t=this.tail-this.head,i=t+e.length;if(this.data.length>=i)this.head>0?(this.data.copyWithin(0,this.head,this.tail),this.data.set(e,t),this.head=0,this.tail=i):(this.data.set(e,this.tail),this.tail+=e.length);else {let s=new Uint8Array(i);this.head>0||this.tail<this.data.length?s.set(this.data.subarray(this.head,this.tail),0):s.set(this.data,0),s.set(e,t),this.data=s,this.view=new DataView(this.data.buffer),this.head=0,this.tail=i;}}else this.data=e,this.view=new DataView(this.data.buffer),this.tail=e.length;}compact(){this.head>0&&(this.data.copyWithin(0,this.head,this.tail),this.tail-=this.head,this.head=0);}get remaining(){return this.tail-this.head}getInt8(){let e=this.view.getInt8(this.head);return this.head++,e}getUint8(){let e=this.view.getUint8(this.head);return this.head++,e}getInt16(){let e=this.view.getInt16(this.head,true);return this.head+=2,e}getUint16(){let e=this.view.getUint16(this.head,true);return this.head+=2,e}getInt32(){let e=this.view.getInt32(this.head,true);return this.head+=4,e}getUint32(){let e=this.view.getUint32(this.head,true);return this.head+=4,e}getFloat32(){let e=this.view.getFloat32(this.head,true);return this.head+=4,e}getFloat64(){let e=this.view.getFloat64(this.head,true);return this.head+=8,e}}let P7=e=>{let t,i=[],s=[];for(let r=1;r<e.length;++r){let a=e[r].split(" ");switch(a[0]){case "comment":s.push(a.slice(1).join(" "));break;case "format":t=a[1];break;case "element":i.push({name:a[1],count:parseInt(a[2],10),properties:[]});break;case "property":if(!P6.has(a[1]))throw Error(`Unrecognized property data type '${a[1]}' in ply header`);i[i.length-1].properties.push({type:a[1],name:a[2],storage:null,byteSize:P6.get(a[1]).BYTES_PER_ELEMENT});break;default:throw Error(`Unrecognized header value '${a[0]}' in ply header`)}}return {elements:i,format:t,comments:s}},Le=e=>{let t=["min_x","min_y","min_z","max_x","max_y","max_z","min_scale_x","min_scale_y","min_scale_z","max_scale_x","max_scale_y","max_scale_z","min_r","min_g","min_b","max_r","max_g","max_b"],i=["packed_position","packed_rotation","packed_scale","packed_color"],s=Array(45).fill("").map((e,t)=>`f_rest_${t}`),r=()=>"chunk"===e[0].name&&e[0].properties.every((e,i)=>e.name===t[i]&&"float"===e.type)&&"vertex"===e[1].name&&e[1].properties.every((e,t)=>e.name===i[t]&&"uint"===e.type);return 2===e.length&&r()||3===e.length&&r()&&"sh"===e[2].name&&-1!==[9,24,45].indexOf(e[2].properties.length)&&e[2].properties.every((e,t)=>e.name===s[t]&&"uchar"===e.type)},Lt=e=>1===e.length&&"vertex"===e[0].name&&e[0].properties.every(e=>"float"===e.type),Li=async(e,t,i)=>{let s=new P2;s.comments=i;let r=t[0].count,a=t[0].properties.length,n=t[1].count,o=(e=>{let t=Math.ceil(Math.sqrt(e)),i=Math.ceil(e/t);return t*i})(n);s.numSplats=n,s.chunkData=new Float32Array(r*a),s.vertexData=new Uint32Array(4*o);let l=async(t,i)=>{let s=new Uint8Array(t),r=0;for(;r<i;){for(;0===e.remaining;)await e.read();let t=Math.min(i-r,e.remaining),a=e.data;for(let i=0;i<t;++i)s[r++]=a[e.head++];}};if(await l(s.chunkData.buffer,r*a*4),await l(s.vertexData.buffer,4*n*4),3===t.length){let e=16*o,i=new Uint8Array(e),r=new Uint8Array(e),a=new Uint8Array(e),n=t[2].properties.length/3,h=new Uint8Array(1024*n*3);for(let e=0;e<s.numSplats;e+=1024){let t=Math.min(1024,s.numSplats-e);await l(h.buffer,t*n*3);for(let s=0;s<t;++s)for(let t=0;t<15;++t){let o=(e+s)*16+t;t<n?(i[o]=h[(3*s+0)*n+t],r[o]=h[(3*s+1)*n+t],a[o]=h[(3*s+2)*n+t]):(i[o]=127,r[o]=127,a[o]=127);}}s.shData0=i,s.shData1=r,s.shData2=a,s.shBands=({3:1,8:2,15:3})[n];}else s.shBands=0;return s},Ls=async(e,t,i)=>{let s,r=t[0],a=r.properties,n=a.length,o=a.map(e=>e.storage),l=a.reduce((e,t)=>e+t.byteSize,0),h=0,c=()=>{let t=e.data.buffer;s?.buffer!==t&&(s=new Float32Array(t,0,t.byteLength/4));};for(c();h<r.count;){for(;e.remaining<l;)await e.read(),c();let t=Math.min(r.count-h,Math.floor(e.remaining/l));for(let e=0;e<n;++e){let i=o[e];for(let r=0;r<t;++r)i[r+h]=s[r*n+e];}h+=t,e.head+=t*l;}return new yM(t,i)},Lr=async(e,t,i)=>{for(let i=0;i<t.length;++i){let s=t[i],r=s.properties.reduce((e,t)=>e+t.byteSize,0),a=s.properties.map(e=>{if(!e.storage)return t=>{t.head+=e.byteSize;};switch(e.type){case "char":return (t,i)=>{e.storage[i]=t.getInt8();};case "uchar":return (t,i)=>{e.storage[i]=t.getUint8();};case "short":return (t,i)=>{e.storage[i]=t.getInt16();};case "ushort":return (t,i)=>{e.storage[i]=t.getUint16();};case "int":return (t,i)=>{e.storage[i]=t.getInt32();};case "uint":return (t,i)=>{e.storage[i]=t.getUint32();};case "float":return (t,i)=>{e.storage[i]=t.getFloat32();};case "double":return (t,i)=>{e.storage[i]=t.getFloat64();};default:throw Error(`Unsupported property data type '${e.type}' in ply header`)}}),n=0;for(;n<s.count;){for(;e.remaining<r;)await e.read();let t=Math.min(s.count-n,Math.floor(e.remaining/r));for(let i=0;i<t;++i){for(let t=0;t<s.properties.length;++t)a[t](e,n);n++;}}}return new yM(t,i)},La=async(e,t=null,i=null)=>{let s,r=(e,t)=>{let i,s,r=e.length-t.length;for(i=0;i<=r;++i){for(s=0;s<t.length&&e[i+s]===t[s];++s);if(s===t.length)return i}return -1},a=(e,t)=>{if(e.length<t.length)return false;for(let i=0;i<t.length;++i)if(e[i]!==t[i])return false;return true},n=new P9(e,i);for(;;){if(await n.read(),n.tail>=P5.length&&!a(n.data,P5))throw Error("Invalid ply header");if(-1!==(s=r(n.data,P8)))break}let{elements:o,format:l,comments:h}=P7(new TextDecoder("ascii").decode(n.data.subarray(0,s)).split("\n"));if("binary_little_endian"!==l)throw Error("Unsupported ply format");n.head=s+P8.length,n.compact();let c=async()=>Le(o)?await Li(n,o,h):(o.forEach(e=>{e.properties.forEach(i=>{let s=P6.get(i.type);if(s){let r=!t||t(i.name)?new s(e.count):null;i.storage=r;}});}),Lt(o))?await Ls(n,o,h):await Lr(n,o,h);return await c()},Ln=e=>true;class Lo{constructor(e,t){this.app=e,this.maxRetries=t;}async load(e,t,i){try{let s=await (i.file?.contents??fetch(e.load));if(s&&s.body){let e=parseInt(s.headers.get("content-length")??"0",10),r=0,a=await La(s.body.getReader(),i.data.elementFilter??Ln,t=>{r+=t,i&&i.fire("progress",r,e);});i.fire("load:data",a),!a.isCompressed&&(i.data.reorder??!0)&&a.reorderData();let n=a.isCompressed&&!i.data.decompress?new P4(this.app.graphicsDevice,a):new yF(this.app.graphicsDevice,a.isCompressed?a.decompress():a);t(null,n);}else t("Error loading resource",null);}catch(e){t(e,null);}}open(e,t){return t}}let Ll=(e,t)=>{let i=new Map,s=()=>{let t=0,s=0;i.forEach(e=>{t+=e.loaded,s+=e.total;}),e.fire("progress",t,s);};t.forEach(e=>{let t=(t,r)=>{i.set(e,{loaded:t,total:r}),s();},r=()=>{e.off("progress",t),e.off("load",r),e.off("error",r);};e.on("progress",t),e.on("load",r),e.on("error",r);});};class Lh{constructor(e,t){this.app=e,this.maxRetries=t;}async loadTextures(e,t,i,s){let{assets:r}=this.app,a=["means","quats","scales","sh0","shN"],n={},o=[];a.forEach(t=>{let a=s[t]?.files??[];n[t]=a.map(t=>{let s=new xF(t,"texture",{url:i.options?.mapUrl?.(t)??new URL(t,new URL(e.load,window.location.href).toString()).toString(),filename:t},{mipmaps:false}),a=new Promise((e,t)=>{s.on("load",()=>e(null)),s.on("error",e=>t(e));});return r.add(s),o.push(a),s});});let l=a.map(e=>n[e]).flat();Ll(i,l),l.forEach(e=>r.load(e)),await Promise.allSettled(o);let h=new y1;h.meta=s,h.numSplats=s.means.shape[0],h.means_l=n.means[0].resource,h.means_u=n.means[1].resource,h.quats=n.quats[0].resource,h.scales=n.scales[0].resource,h.sh0=n.sh0[0].resource,h.sh_centroids=n.shN?.[0]?.resource,h.sh_labels=n.shN?.[1]?.resource;let c=i.data?.decompress;c||await h.prepareGpuData(),t(null,c?new yF(this.app.graphicsDevice,await h.decompress()):new y6(this.app.graphicsDevice,h));}load(e,t,i){if(i.data?.means)this.loadTextures(e,t,i,i.data);else {"string"==typeof e&&(e={load:e,original:e});let s={retry:this.maxRetries>0,maxRetries:this.maxRetries,responseType:d0.ResponseType.JSON};d1.get(e.load,s,(s,r)=>{s?t(`Error loading gsplat meta: ${e.original} [${s}]`):this.loadTextures(e,t,i,r);});}}}class Lc extends xH{constructor(e){super(e,"gsplat"),this.parsers={ply:new Lo(e,3),json:new Lh(e,3)};}_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}_getParser(e){let t=W.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".","");return this.parsers[t]||this.parsers.ply}load(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i);}open(e,t,i){return t}}class Ld{static setCompressedPRS(e,t,i){let s,r,a=i.singleVecs,n=t.___1;n||(s=i.tripleVecs,r=t.___2);let o=n?n[0]:s[r];e.setLocalPosition(a[o],a[o+1],a[o+2]),o=n?n[1]:s[r+1],e.setLocalEulerAngles(a[o],a[o+1],a[o+2]),o=n?n[2]:s[r+2],e.setLocalScale(a[o],a[o+1],a[o+2]);}static oneCharToKey(e,t){let i=e.charCodeAt(0)-t.fieldFirstCode;return t.fieldArray[i]}static multCharToKey(e,t){let i=0;for(let s=0;s<e.length;s++)i=i*t.fieldCodeBase+e.charCodeAt(s)-t.fieldFirstCode;return t.fieldArray[i]}}class Lu{constructor(e,t){this._node=e,this._data=t;}run(){let e=Object.prototype.toString.call(this._node);return "[object Object]"===e?this._handleMap():"[object Array]"===e?this._handleArray():this._result=this._node,this._result}_handleMap(){this._result={},Object.keys(this._node).forEach(this._handleKey,this);}_handleKey(e){let t=e,i=e.length;1===i?t=Ld.oneCharToKey(e,this._data):2===i&&(t=Ld.multCharToKey(e,this._data)),this._result[t]=new Lu(this._node[e],this._data).run();}_handleArray(){this._result=[],this._node.forEach(this._handleArElt,this);}_handleArElt(e){let t=new Lu(e,this._data).run();this._result.push(t);}}class Lf{constructor(e,t){this._app=e,this._isTemplate=t;}parse(e){let t={},i=null,s=e.compressedFormat;for(let r in s&&!e.entDecompressed&&(e.entDecompressed=true,e.entities=new Lu(e.entities,s).run()),e.entities){let a=e.entities[r],n=this._createEntity(a,s);t[r]=n,null===a.parent&&(i=n);}for(let i in e.entities){let s=t[i],r=e.entities[i].children,a=r.length;for(let e=0;e<a;e++){let i=t[r[e]];i&&s.addChild(i);}}return this._openComponentData(i,e.entities),i}_createEntity(e,t){let i=new x1(e.name,this._app);if(i.setGuid(e.resource_id),this._setPosRotScale(i,e,t),i._enabled=e.enabled??true,this._isTemplate?i._template=true:i._enabledInHierarchy=i._enabled,i.template=e.template,e.tags)for(let t=0;t<e.tags.length;t++)i.tags.add(e.tags[t]);return i}_setPosRotScale(e,t,i){if(i)Ld.setCompressedPRS(e,t,i);else {let i=t.position,s=t.rotation,r=t.scale;e.setLocalPosition(i[0],i[1],i[2]),e.setLocalEulerAngles(s[0],s[1],s[2]),e.setLocalScale(r[0],r[1],r[2]);}}_openComponentData(e,t){let i=this._app.systems.list,s=i.length,r=t[e.getGuid()];for(let t=0;t<s;t++){let s=i[t],a=r.components[s.id];a&&s.addComponent(e,a);}s=r.children.length;let a=e._children;for(let e=0;e<s;e++)a[e]&&(a[e]=this._openComponentData(a[e],t));return e}}class Lp{static load(e,t,i){"string"==typeof e&&(e={load:e,original:e}),d1.get(e.load,{retry:t>0,maxRetries:t},(t,s)=>{if(t){let s=`Error while loading scene JSON ${e.original}`;t.message?(s+=`: ${t.message}`,t.stack&&(s+=`
${t.stack}`)):s+=`: ${t}`,i(s);}else i(t,s);});}}class Lm extends xH{constructor(e){super(e,"hierarchy");}load(e,t){Lp.load(e,this.maxRetries,t);}open(e,t){this._app.systems.script.preloading=true;let i=new Lf(this._app,false).parse(t);return this._app.systems.script.preloading=false,i}}class L_ extends xH{constructor(e){super(e,"html"),this.decoder=null;}load(e,t){"string"==typeof e&&(e={load:e,original:e}),d1.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t(`Error loading html resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return this.decoder??=new TextDecoder("utf-8"),this.decoder.decode(e)}}class Lg extends xH{constructor(e){super(e,"json"),this.decoder=null;}load(e,t){"string"==typeof e&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=d0.ResponseType.JSON),d1.get(e.load,i,(i,s)=>{i?t(`Error loading JSON resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return this.decoder??=new TextDecoder("utf-8"),JSON.parse(this.decoder.decode(e))}}class Lv{constructor(){this.removeInvalid=true,this.valid=true,this.enumValidators={occludeSpecular:this._createEnumValidator([fk,fV,fz]),cull:this._createEnumValidator([tY,tq,t$,tj]),blendType:this._createEnumValidator([us,ur,ua,un,uo,ul,uh,uc,ud,uu,uf]),depthFunc:this._createEnumValidator([t2,t3,t4,t5,t8,t6,t9,t7])};}setInvalid(e,t){this.valid=false,this.removeInvalid&&delete t[e];}validate(e){let t="path"===e.mappingFormat;for(let i in e){let s=S7[i];if(!s){yi[i]?delete e[i]:this.valid=false;continue}if(s.startsWith("enum")){let t=s.split(":")[1];this.enumValidators[t]&&!this.enumValidators[t](e[i])&&this.setInvalid(i,e);}else if("number"===s)"number"!=typeof e[i]&&this.setInvalid(i,e);else if("boolean"===s)"boolean"!=typeof e[i]&&this.setInvalid(i,e);else if("string"===s)"string"!=typeof e[i]&&this.setInvalid(i,e);else if("vec2"===s)e[i]instanceof Array&&2===e[i].length||this.setInvalid(i,e);else if("rgb"===s)e[i]instanceof Array&&3===e[i].length||this.setInvalid(i,e);else if("texture"===s)t?"string"==typeof e[i]||null===e[i]||e[i]instanceof ns||this.setInvalid(i,e):"number"==typeof e[i]||null===e[i]||e[i]instanceof ns||this.setInvalid(i,e);else if("boundingbox"===s)e[i].center&&e[i].center instanceof Array&&3===e[i].center.length||this.setInvalid(i,e),e[i].halfExtents&&e[i].halfExtents instanceof Array&&3===e[i].halfExtents.length||this.setInvalid(i,e);else if("cubemap"===s)"number"==typeof e[i]||null===e[i]||void 0===e[i]||e[i]instanceof ns&&e[i].cubemap||this.setInvalid(i,e);else if("chunks"===s){let t=Object.keys(e[i]);for(let s=0;s<t.length;s++)"string"!=typeof e[i][t[s]]&&this.setInvalid(t[s],e[i]);}}return e.validated=true,this.valid}_createEnumValidator(e){return function(t){return e.indexOf(t)>=0}}}class LS{constructor(){this._validator=null;}parse(e){let t=this.migrate(e),i=this._validate(t),s=new yo;return this.initialize(s,i),s}initialize(e,t){if(t.validated||(t=this._validate(t)),t.chunks&&t.chunks&&Object.keys(t.chunks).length>0){let i=e.shaderChunks.glsl;Object.entries(t.chunks).forEach(([e,t])=>i.set(e,t));}for(let i in t){let s=S7[i],r=t[i];if("vec2"===s)e[i]=new eN(r[0],r[1]);else if("rgb"===s)e[i]=new eb(r[0],r[1],r[2]);else if("texture"===s)r instanceof ns?e[i]=r:e[i]instanceof ns&&"number"==typeof r&&r>0||(e[i]=null);else if("cubemap"===s)r instanceof ns?e[i]=r:e[i]instanceof ns&&"number"==typeof r&&r>0||(e[i]=null),"cubeMap"!==i||r||(e.prefilteredCubemaps=null);else if("boundingbox"===s){let t=new eM(r.center[0],r.center[1],r.center[2]),s=new eM(r.halfExtents[0],r.halfExtents[1],r.halfExtents[2]);e[i]=new ej(t,s);}else e[i]=t[i];}e.update();}migrate(e){let t;e.shader&&delete e.shader,e.mapping_format&&(e.mappingFormat=e.mapping_format,delete e.mapping_format);let i=[["bumpMapFactor","bumpiness"],["aoUvSet","aoMapUv"],["aoMapVertexColor","aoVertexColor"],["diffuseMapVertexColor","diffuseVertexColor"],["emissiveMapVertexColor","emissiveVertexColor"],["specularMapVertexColor","specularVertexColor"],["metalnessMapVertexColor","metalnessVertexColor"],["opacityMapVertexColor","opacityVertexColor"],["glossMapVertexColor","glossVertexColor"],["lightMapVertexColor","lightVertexColor"],["specularMapTint","specularTint"],["metalnessMapTint","metalnessTint"],["clearCoatGlossiness","clearCoatGloss"]];for(t=0;t<i.length;t++){let s=i[t][0],r=i[t][1];void 0!==e[s]&&(void 0===e[r]&&(e[r]=e[s]),delete e[s]);}let s=["fresnelFactor","shadowSampleType"];for(t=0;t<s.length;t++){let i=s[t];e.hasOwnProperty(i)&&delete e[i];}return e}_validate(e){return e.validated||(this._validator||(this._validator=new Lv),this._validator.validate(e)),e}}let Ly={aoMap:"white",aoDetailMap:"white",diffuseMap:"gray",diffuseDetailMap:"gray",specularMap:"gray",specularityFactorMap:"white",metalnessMap:"black",glossMap:"gray",sheenMap:"black",sheenGlossMap:"gray",clearCoatMap:"black",clearCoatGlossMap:"gray",clearCoatNormalMap:"normal",refractionMap:"white",emissiveMap:"gray",normalMap:"normal",normalDetailMap:"normal",heightMap:"gray",opacityMap:"gray",sphereMap:"gray",lightMap:"white",thicknessMap:"black",iridescenceMap:"black",iridescenceThicknessMap:"black",envAtlas:"black",anisotropyMap:"black"};class Lx extends xH{constructor(e){super(e,"material"),this._assets=e.assets,this._device=e.graphicsDevice,this._parser=new LS;}load(e,t){"string"==typeof e&&(e={load:e,original:e}),d1.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t&&t(`Error loading material: ${e.original} [${i}]`):t&&(s._engine=true,t(null,s));});}open(e,t){let i=this._parser.parse(t);return t._engine&&(i._data=t,delete t._engine),i}patch(e,t){e.resource._data&&(e._data=e.resource._data,delete e.resource._data),e.data.name=e.name,e.resource.name=e.name,this._bindAndAssignAssets(e,t),e.off("unload",this._onAssetUnload,this),e.on("unload",this._onAssetUnload,this);}_onAssetUnload(e){delete e.data.parameters,delete e.data.chunks,delete e.data.name;}_assignTexture(e,t,i){t.resource[e]=i;}_getPlaceholderTexture(e){let t=Ly[e];return no(this._device,t)}_assignPlaceholderTexture(e,t){t.resource[e]=this._getPlaceholderTexture(e);}_onTextureLoad(e,t,i){this._assignTexture(e,t,i.resource),t.resource.update();}_onTextureAdd(e,t,i){this._assets.load(i);}_onTextureRemoveOrUnload(e,t,i){let s=t.resource;s&&t.resource[e]===i.resource&&(this._assignPlaceholderTexture(e,t),s.update());}_assignCubemap(e,t,i){if(t.resource[e]=i[0],"cubeMap"===e){let e=i.slice(1);e.every(e=>e)?t.resource.prefilteredCubemaps=e:e[0]&&(t.resource.envAtlas=e[0]);}}_onCubemapLoad(e,t,i){this._assignCubemap(e,t,i.resources),this._parser.initialize(t.resource,t.data);}_onCubemapAdd(e,t,i){this._assets.load(i);}_onCubemapRemoveOrUnload(e,t,i){let s=t.resource;t.data.prefilteredCubeMap128===i.resources[1]&&(this._assignCubemap(e,t,[null,null,null,null,null,null,null]),s.update());}_bindAndAssignAssets(e,t){let i,s,r,a=this._parser.migrate(e.data),n=e.resource,o="path"===a.mappingFormat;for(i=0;i<ye.length;i++){s=ye[i],r=n._assetReferences[s];let l=a[s],h=n[s],c=h===this._getPlaceholderTexture(s),d=a.validated;l&&(!h||!d||c)?(r||(r=new b$(s,e,t,{load:this._onTextureLoad,add:this._onTextureAdd,remove:this._onTextureRemoveOrUnload,unload:this._onTextureRemoveOrUnload},this),n._assetReferences[s]=r),o?r.url=e.getAbsoluteUrl(l):r.id=l,r.asset&&(r.asset.resource?this._assignTexture(s,e,r.asset.resource):this._assignPlaceholderTexture(s,e),t.load(r.asset))):r&&(o?r.url=null:r.id=null);}for(i=0;i<yt.length;i++)s=yt[i],r=n._assetReferences[s],a[s]&&!e.data.prefilteredCubeMap128&&(r||(r=new b$(s,e,t,{load:this._onCubemapLoad,add:this._onCubemapAdd,remove:this._onCubemapRemoveOrUnload,unload:this._onCubemapRemoveOrUnload},this),n._assetReferences[s]=r),o?r.url=a[s]:r.id=a[s],r.asset&&(r.asset.loaded&&this._assignCubemap(s,e,r.asset.resources),t.load(r.asset)));this._parser.initialize(n,a);}}class LT{constructor(e){this._device=e.device,this._defaultMaterial=e.defaultMaterial,this._assets=e.assets;}parse(e,t,i){PB.parse("filename.glb","",e,this._device,this._assets,i?.options??{},(e,i)=>{if(e)t(e);else {let e=PX.createModel(i,this._defaultMaterial);i.destroy(),t(null,e);}});}}let LE={points:sm,lines:s_,lineloop:sg,linestrip:sv,triangles:sS,trianglestrip:sy,trianglefan:sx},LA={int8:rC,uint8:rP,int16:rL,uint16:rI,int32:rD,uint32:rR,float32:rM};class Lb{constructor(e){this._device=e.device,this._defaultMaterial=e.defaultMaterial;}parse(e,t){let i=e.model;if(!i)return void t(null,null);if(i.version<=1)return void t("JsonModelParser#parse: Trying to parse unsupported model format.");let s=this._parseNodes(e),r=this._parseSkins(e,s),a=this._parseVertexBuffers(e),n=this._parseIndexBuffers(e,a),o=this._parseMorphs(e,s,a),l=this._parseMeshes(e,r.skins,o.morphs,a,n.buffer,n.data),h=this._parseMeshInstances(e,s,l,r.skins,r.instances,o.morphs,o.instances),c=new g5;c.graph=s[0],c.meshInstances=h,c.skinInstances=r.instances,c.morphInstances=o.instances,c.getGraph().syncHierarchy(),t(null,c);}_parseNodes(e){let t,i=e.model,s=[];for(t=0;t<i.nodes.length;t++){let e=i.nodes[t],r=new _c(e.name);r.setLocalPosition(e.position[0],e.position[1],e.position[2]),r.setLocalEulerAngles(e.rotation[0],e.rotation[1],e.rotation[2]),r.setLocalScale(e.scale[0],e.scale[1],e.scale[2]),r.scaleCompensation=!!e.scaleCompensation,s.push(r);}for(t=1;t<i.parents.length;t++)s[i.parents[t]].addChild(s[t]);return s}_parseSkins(e,t){let i,s,r=e.model,a=[],n=[];for(i=0;i<r.skins.length;i++){let e=r.skins[i],o=[];for(s=0;s<e.inverseBindMatrices.length;s++){let t=e.inverseBindMatrices[s];o[s]=new eG().set(t);}let l=new SR(this._device,o,e.boneNames);a.push(l);let h=new mx(l),c=[];for(s=0;s<l.boneNames.length;s++){let e=l.boneNames[s],i=t[0].findByName(e);c.push(i);}h.bones=c,n.push(h);}return {skins:a,instances:n}}_getMorphVertexCount(e,t,i){for(let s=0;s<e.meshes.length;s++){let r=e.meshes[s];if(r.morph===t)return i[r.vertices].numVertices}}_parseMorphs(e,t,i){let s,r,a,n,o,l,h=e.model,c=[],d=[];if(h.morphs){let e=function(e,t,i){let s=new Float32Array(3*i);for(let i=0;i<t.length;i++){let r=3*t[i];s[r]=e[3*i],s[r+1]=e[3*i+1],s[r+2]=e[3*i+2];}return s};for(s=0;s<h.morphs.length;s++){for(r=0,n=h.morphs[s].targets,l=[],a=this._getMorphVertexCount(h,s,i);r<n.length;r++){let t=n[r].aabb,i=t.min,s=t.max,h=new ej(new eM((s[0]+i[0])*.5,(s[1]+i[1])*.5,(s[2]+i[2])*.5),new eM((s[0]-i[0])*.5,(s[1]-i[1])*.5,(s[2]-i[2])*.5)),c=n[r].indices,d=n[r].deltaPositions,u=n[r].deltaNormals;c&&(d=e(d,c,a),u=e(u,c,a)),o=new g6({deltaPositions:d,deltaNormals:u,name:n[r].name,aabb:h}),l.push(o);}let t=new g8(l,this._device);c.push(t);let u=new g4(t);d.push(u);}}return {morphs:c,instances:d}}_parseVertexBuffers(e){let t=e.model,i=[],s={position:sT,normal:sE,tangent:sA,blendWeight:sb,blendIndices:sw,color:sC,texCoord0:sL,texCoord1:sI,texCoord2:sD,texCoord3:sR,texCoord4:sM,texCoord5:sO,texCoord6:sN,texCoord7:sF};for(let e=0;e<t.vertices.length;e++){let r=t.vertices[e],a=[];for(let e in r){let t=r[e];a.push({semantic:s[e],components:t.components,type:LA[t.type],normalize:s[e]===sC});}let n=new nP(this._device,a),o=r.position.data.length/r.position.components,l=new nT(this._device,n,o),h=new ho(l);for(let e=0;e<o;e++){for(let t in r){let i=r[t];switch(i.components){case 1:h.element[s[t]].set(i.data[e]);break;case 2:h.element[s[t]].set(i.data[2*e],1-i.data[2*e+1]);break;case 3:h.element[s[t]].set(i.data[3*e],i.data[3*e+1],i.data[3*e+2]);break;case 4:h.element[s[t]].set(i.data[4*e],i.data[4*e+1],i.data[4*e+2],i.data[4*e+3]);}}h.next();}h.end(),i.push(l);}return i}_parseIndexBuffers(e,t){let i,s=e.model,r=null,a=null,n=0;for(i=0;i<s.meshes.length;i++){let e=s.meshes[i];void 0!==e.indices&&(n+=e.indices.length);}let o=0;for(i=0;i<t.length;i++)o=Math.max(o,t[i].numVertices);return n>0&&(a=o>65535?new Uint32Array((r=new lJ(this._device,ii,n)).lock()):new Uint16Array((r=new lJ(this._device,it,n)).lock())),{buffer:r,data:a}}_parseMeshes(e,t,i,s,r,a){let n=e.model,o=[],l=0;for(let e=0;e<n.meshes.length;e++){let h=n.meshes[e],c=h.aabb,d=c.min,u=c.max,f=new ej(new eM((u[0]+d[0])*.5,(u[1]+d[1])*.5,(u[2]+d[2])*.5),new eM((u[0]-d[0])*.5,(u[1]-d[1])*.5,(u[2]-d[2])*.5)),p=void 0!==h.indices,m=new mw(this._device);m.vertexBuffer=s[h.vertices],m.indexBuffer[0]=p?r:null,m.primitive[0].type=LE[h.type],m.primitive[0].base=p?h.base+l:h.base,m.primitive[0].count=h.count,m.primitive[0].indexed=p,m.skin=void 0!==h.skin?t[h.skin]:null,m.morph=void 0!==h.morph?i[h.morph]:null,m.aabb=f,p&&(a.set(h.indices,l),l+=h.indices.length),o.push(m);}return null!==r&&r.unlock(),o}_parseMeshInstances(e,t,i,s,r,a,n){let o,l=e.model,h=[];for(o=0;o<l.meshInstances.length;o++){let e=l.meshInstances[o],c=t[e.node],d=i[e.mesh],u=new mV(d,this._defaultMaterial,c);d.skin&&(u.skinInstance=r[s.indexOf(d.skin)]),d.morph&&(u.morphInstance=n[a.indexOf(d.morph)]),h.push(u);}return h}}class Lw extends xH{constructor(e){super(e,"model"),this._parsers=[],this.device=e.graphicsDevice,this.assets=e.assets,this.defaultMaterial=mP(this.device),this.addParser(new Lb(this),(e,t)=>".json"===W.getExtension(e)),this.addParser(new LT(this),(e,t)=>".glb"===W.getExtension(e));}load(e,t,i){"string"==typeof e&&(e={load:e,original:e});let s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===W.getExtension(e.original).toLowerCase()?s.responseType=d0.ResponseType.ARRAY_BUFFER:s.responseType=d0.ResponseType.JSON),d1.get(e.load,s,(s,r)=>{if(t)if(s)t(`Error loading model: ${e.original} [${s}]`);else {for(let s=0;s<this._parsers.length;s++){let a=this._parsers[s];if(a.decider(e.original,r))return void a.parser.parse(r,(e,i)=>{e?t(e):t(null,i);},i)}t("No parsers found");}});}open(e,t){return t}patch(e,t){if(!e.resource)return;let i=e.data,s=this;e.resource.meshInstances.forEach((r,a)=>{if(i.mapping){let n,o=function(e){e.resource?r.material=e.resource:(e.once("load",o),t.load(e)),e.once("remove",e=>{r.material===e.resource&&(r.material=s.defaultMaterial);});};if(!i.mapping[a]){r.material=s.defaultMaterial;return}let l=i.mapping[a].material,h=i.mapping[a].path;if(void 0!==l)l?(n=t.get(l))?o(n):t.once(`add:${l}`,o):r.material=s.defaultMaterial;else if(h){let s=e.getAbsoluteUrl(i.mapping[a].path);(n=t.getByUrl(s))?o(n):t.once(`add:url:${s}`,o);}}});}addParser(e,t){this._parsers.push({parser:e,decider:t});}}class LC extends xH{constructor(e){super(e,"scene");}load(e,t){Lp.load(e,this.maxRetries,t);}open(e,t){this._app.systems.script.preloading=true;let i=new Lf(this._app,false).parse(t),s=this._app.scene;return s.root=i,this._app.applySceneSettings(t.settings),this._app.systems.script.preloading=false,s}}class LP{static{this._types=[];}static push(e){LP._types.push(e);}}let LL=new Set(["system","entity","create","destroy","swap","move","data","scripts","_scripts","_scriptsIndex","_scriptsData","enabled","_oldState","onEnable","onDisable","onPostStateChange","_onSetEnabled","_checkState","_onBeforeRemove","_onInitializeAttributes","_onInitialize","_onPostInitialize","_onUpdate","_onPostUpdate","_callbacks","_callbackActive","has","get","on","off","fire","once","hasEvent"]);function LI(){return LL}function LD(e,t){if(LL.has(e))throw Error(`Script name '${e}' is reserved, please rename the script`);let i=function(e){eo.prototype.initEventHandler.call(this),Cc.prototype.initScriptType.call(this,e);};return i.prototype=Object.create(Cc.prototype),i.prototype.constructor=i,i.extend=Cc.extend,i.attributes=new Cr(i),LM(i,e,t),i}let LR={};function LM(e,t,i){if("function"!=typeof e)throw Error(`script class: '${e}' must be a constructor function (i.e. class).`);if(!(e.prototype instanceof Co))throw Error(`script class: '${Cc.__getScriptName(e)}' does not extend pc.Script.`);if(t=t||e.__name||Cc.__getScriptName(e),LL.has(t))throw Error(`script name: '${t}' is reserved, please change script name`);e.__name=t,(i?i.scripts:x9.getApplication().scripts).add(e),LP.push(e);}Cr.reservedNames.forEach((e,t,i)=>{LR[e]=1;}),LD.reservedAttributes=LR;let LO=e=>e[0].toLowerCase()+e.substring(1);class LN extends xH{constructor(e){super(e,"script"),this._scripts={},this._cache={};}clearCache(){for(let e in this._cache){let t=this._cache[e],i=t.parentNode;i&&i.removeChild(t);}this._cache={};}load(e,t){"string"==typeof e&&(e={load:e,original:e});let i=this;xr.app=this._app;let s=(e.load,(e,s,r)=>{if(e)t(e);else {let e={};for(let t=0;t<LP._types.length;t++)e[LP._types[t].name]=LP._types[t];LP._types.length=0,t(null,e,r);let a=s.split("&hash=")[0];delete i._loader._cache[xX.makeKey(a,"script")];}}),[r]=e.load.split("?");r.endsWith(".mjs")?this._loadModule(r,s):this._loadScript(e.load,s);}open(e,t){return t}patch(e,t){}_loadScript(e,t){let i=document.head,s=document.createElement("script");this._cache[e]=s,s.async=false,s.addEventListener("error",e=>{t(`Script: ${e.target.src} failed to load`);},false);let r=false;s.onload=s.onreadystatechange=function(){r||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(r=true,t(null,e,s));},s.src=e,i.appendChild(s);}_loadModule(e,t){let i=new URL(e,ee.browser&&"null"!==window.location.origin?window.location.origin+window.location.pathname:import.meta.url);import(i.toString()).then(s=>{let r=i.pathname.split("/").pop(),a=this._app.assets.find(r,"script")?.data?.scripts;for(let e in s){let t=s[e];if(t.prototype instanceof Co){let e=LO(t.name);t.scriptName;let i=t.scriptName??e;LM(t,i),a&&this._app.scripts.addSchema(i,a[i]);}}t(null,e,null);}).catch(e=>{t(e);});}}class LF extends xH{constructor(e){super(e,"shader"),this.decoder=null;}load(e,t){"string"==typeof e&&(e={load:e,original:e}),d1.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t(`Error loading shader resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return this.decoder??=new TextDecoder("utf-8"),this.decoder.decode(e)}}function LB(e){this.resource&&(this.resource.atlas=e.resource);}function LU(e){this.registry.load(e);}class Lk extends xH{constructor(e){super(e,"sprite"),this._assets=e.assets,this._device=e.graphicsDevice;}load(e,t){"string"==typeof e&&(e={load:e,original:e}),".json"===W.getExtension(e.original)&&d1.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(e,i)=>{e?t(e):t(null,i);});}open(e,t){let i=new SN(this._device);return e&&(i.__data=t),i}patch(e,t){let i=e.resource;if(i.__data&&(e.data.pixelsPerUnit=i.__data.pixelsPerUnit,e.data.renderMode=i.__data.renderMode,e.data.frameKeys=i.__data.frameKeys,i.__data.textureAtlasAsset)){let s=t.getByUrl(i.__data.textureAtlasAsset);s&&(e.data.textureAtlasAsset=s.id);}i.startUpdate(),i.renderMode=e.data.renderMode,i.pixelsPerUnit=e.data.pixelsPerUnit,i.frameKeys=e.data.frameKeys,this._updateAtlas(e),i.endUpdate(),e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this);}_updateAtlas(e){let t=e.resource;if(!e.data.textureAtlasAsset){t.atlas=null;return}this._assets.off(`load:${e.data.textureAtlasAsset}`,LB,e),this._assets.on(`load:${e.data.textureAtlasAsset}`,LB,e);let i=this._assets.get(e.data.textureAtlasAsset);i&&i.resource?t.atlas=i.resource:i?this._assets.load(i):(this._assets.off(`add:${e.data.textureAtlasAsset}`,LU,e),this._assets.on(`add:${e.data.textureAtlasAsset}`,LU,e));}_onAssetChange(e,t,i,s){"data"===t&&i&&i.textureAtlasAsset&&s&&i.textureAtlasAsset!==s.textureAtlasAsset&&(this._assets.off(`load:${s.textureAtlasAsset}`,LB,e),this._assets.off(`add:${s.textureAtlasAsset}`,LU,e));}}class LV{constructor(e,t){this._templateRoot=null,this._app=e,this._data=t;}instantiate(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()}_parseTemplate(){let e=new Lf(this._app,true);this._templateRoot=e.parse(this._data);}}class Lz extends xH{constructor(e){super(e,"template"),this.decoder=null;}load(e,t){"string"==typeof e&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};d1.get(e.load,i,(i,s)=>{i?t(`Error requesting template: ${e.original}`):t(i,s);});}open(e,t){return new LV(this._app,t)}openBinary(e){return this.decoder??=new TextDecoder("utf-8"),new LV(this._app,JSON.parse(this.decoder.decode(e)))}}class LG extends xH{constructor(e){super(e,"text"),this.decoder=null;}load(e,t){"string"==typeof e&&(e={load:e,original:e}),d1.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,s)=>{i?t(`Error loading text resource: ${e.original} [${i}]`):t(null,s);});}openBinary(e){return this.decoder??=new TextDecoder("utf-8"),this.decoder.decode(e)}}let LH={repeat:ts,clamp:tr,mirror:ta},LW={nearest:tK,linear:tZ,nearest_mip_nearest:tQ,linear_mip_nearest:t0,nearest_mip_linear:tJ,linear_mip_linear:t1},LX=/^data\.frames\.(\d+)$/;class LY extends xH{constructor(e){super(e,"textureatlas"),this._loader=e.loader;}load(e,t){"string"==typeof e&&(e={load:e,original:e});let i=this,s=this._loader.getHandler("texture");".json"===W.getExtension(e.original)?d1.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,r)=>{if(s)t(s);else {let s=e.original.replace(".json",".png");i._loader.load(s,"texture",(e,i)=>{e?t(e):t(null,{data:r,texture:i});});}}):s.load(e,t);}open(e,t,i){let s=new SF;if(t.texture&&t.data)s.texture=t.texture,s.__data=t.data;else {let r=this._loader.getHandler("texture").open(e,t,i);if(!r)return null;s.texture=r;}return s}patch(e,t){if(!e.resource)return;e.resource.__data&&(void 0!==e.resource.__data.minfilter&&(e.data.minfilter=e.resource.__data.minfilter),void 0!==e.resource.__data.magfilter&&(e.data.magfilter=e.resource.__data.magfilter),void 0!==e.resource.__data.addressu&&(e.data.addressu=e.resource.__data.addressu),void 0!==e.resource.__data.addressv&&(e.data.addressv=e.resource.__data.addressv),void 0!==e.resource.__data.mipmaps&&(e.data.mipmaps=e.resource.__data.mipmaps),void 0!==e.resource.__data.anisotropy&&(e.data.anisotropy=e.resource.__data.anisotropy),void 0!==e.resource.__data.rgbm&&(e.data.rgbm=!!e.resource.__data.rgbm),e.data.frames=e.resource.__data.frames,delete e.resource.__data);let i=e.resource.texture;if(i&&(i.name=e.name,e.data.hasOwnProperty("minfilter")&&i.minFilter!==LW[e.data.minfilter]&&(i.minFilter=LW[e.data.minfilter]),e.data.hasOwnProperty("magfilter")&&i.magFilter!==LW[e.data.magfilter]&&(i.magFilter=LW[e.data.magfilter]),e.data.hasOwnProperty("addressu")&&i.addressU!==LH[e.data.addressu]&&(i.addressU=LH[e.data.addressu]),e.data.hasOwnProperty("addressv")&&i.addressV!==LH[e.data.addressv]&&(i.addressV=LH[e.data.addressv]),e.data.hasOwnProperty("mipmaps")&&i.mipmaps!==e.data.mipmaps&&(i.mipmaps=e.data.mipmaps),e.data.hasOwnProperty("anisotropy")&&i.anisotropy!==e.data.anisotropy&&(i.anisotropy=e.data.anisotropy),e.data.hasOwnProperty("rgbm"))){let t=e.data.rgbm?ri:rt;i.type!==t&&(i.type=t);}e.resource.texture=i;let s={};for(let t in e.data.frames){let i=e.data.frames[t];s[t]={rect:new eF(i.rect),pivot:new eN(i.pivot),border:new eF(i.border)};}e.resource.frames=s,e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this);}_onAssetChange(e,t,i){let s;if("data"===t||"data.frames"===t){let t={};for(let e in i.frames)s=i.frames[e],t[e]={rect:new eF(s.rect),pivot:new eN(s.pivot),border:new eF(s.border)};e.resource.frames=t;}else {let r=t.match(LX);if(r){let t=r[1];i?(e.resource.frames[t]?((s=e.resource.frames[t]).rect.set(i.rect[0],i.rect[1],i.rect[2],i.rect[3]),s.pivot.set(i.pivot[0],i.pivot[1]),s.border.set(i.border[0],i.border[1],i.border[2],i.border[3])):e.resource.frames[t]={rect:new eF(i.rect),pivot:new eN(i.pivot),border:new eF(i.border)},e.resource.fire("set:frame",t,e.resource.frames[t])):e.resource.frames[t]&&(delete e.resource.frames[t],e.resource.fire("remove:frame",t));}}}}function Lq(){let e,t,i,s={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFRGBA4444:16},r={astc:s.cTFASTC_4x4,dxt:s.cTFBC1,etc1:s.cTFETC1,etc2:s.cTFETC1,pvr:s.cTFPVRTC1_4_RGB,atc:s.cTFATC_RGB,none:s.cTFRGB565},a={astc:s.cTFASTC_4x4,dxt:s.cTFBC3,etc1:s.cTFRGBA4444,etc2:s.cTFETC2,pvr:s.cTFPVRTC1_4_RGBA,atc:s.cTFATC_RGBA_INTERPOLATED_ALPHA,none:s.cTFRGBA4444},n={ETC1:21,ETC2_RGB:22,ETC2_RGBA:23,DXT1:8,DXT5:10,PVRTC_4BPP_RGB_1:26,PVRTC_4BPP_RGBA_1:27,ASTC_4x4:28,ATC_RGB:29,ATC_RGBA:30,R8_G8_B8_A8:7,R5_G6_B5:3,R4_G4_B4_A4:5},o=(e,t)=>{switch(e){case s.cTFETC1:return t.formats.etc2?n.ETC2_RGB:n.ETC1;case s.cTFETC2:return n.ETC2_RGBA;case s.cTFBC1:return n.DXT1;case s.cTFBC3:return n.DXT5;case s.cTFPVRTC1_4_RGB:return n.PVRTC_4BPP_RGB_1;case s.cTFPVRTC1_4_RGBA:return n.PVRTC_4BPP_RGBA_1;case s.cTFASTC_4x4:return n.ASTC_4x4;case s.cTFATC_RGB:return n.ATC_RGB;case s.cTFATC_RGBA_INTERPOLATED_ALPHA:return n.ATC_RGBA;case s.cTFRGBA32:return n.R8_G8_B8_A8;case s.cTFRGB565:return n.R5_G6_B5;case s.cTFRGBA4444:return n.R4_G4_B4_A4}},l=e=>{for(let t=0;t<e.length;t+=4){let i=e[t+3],s=e[t+1];e[t+0]=i,e[t+2]=function(e,t){let i=2/255*e-1,s=2/255*t-1;return Math.max(0,Math.min(255,Math.floor((Math.sqrt(1-Math.min(1,i*i+s*s))+1)*127.5)))}(i,s),e[t+3]=255;}return e},h=e=>{let t=new Uint16Array(e.length/4);for(let i=0;i<e.length;i+=4){let s=e[i+0],r=e[i+1],a=e[i+2];t[i/4]=(248&s)<<8|(252&r)<<3|a>>3;}return t},c=(e,t)=>(e&e-1)==0&&(t&t-1)==0,d=()=>"undefined"!=typeof performance?performance.now():0,u=(e,s,r)=>{if(r){if(e.formats.astc)return "astc"}else if(s){if(e.formats.etc2)return "etc2"}else {if(e.formats.etc2)return "etc2";if(e.formats.etc1)return "etc1"}var a=s?i:t;for(let t=0;t<a.length;++t){let i=a[t];if(e.formats[i])return i}return "none"},f=(e,t,i)=>{switch(i){case s.cTFETC1:case s.cTFETC2:return true;case s.cTFBC1:case s.cTFBC3:return (3&e)==0&&(3&t)==0;case s.cTFPVRTC1_4_RGB:case s.cTFPVRTC1_4_RGBA:return c(e,t);case s.cTFASTC_4x4:case s.cTFATC_RGB:case s.cTFATC_RGBA_INTERPOLATED_ALPHA:return true}return false},p=(t,i,n)=>{let c,p;if(!e.KTX2File)throw Error("Basis transcoder module does not include support for KTX2.");let m=d(),_=new e.KTX2File(new Uint8Array(i)),g=_.getWidth(),v=_.getHeight(),S=_.getLevels(),y=!!_.getHasAlpha(),x=_.isUASTC&&_.isUASTC();if(!g||!v||!S)throw _.close(),_.delete(),Error(`Invalid image dimensions url=${t} width=${g} height=${v} levels=${S}`);let T=u(n.deviceDetails,y,x),E=!!n.isGGGR&&"pvr"===T;if(E?c=s.cTFRGBA32:f(g,v,c=y?a[T]:r[T])||(c=y?s.cTFRGBA32:s.cTFRGB565),!_.startTranscoding())throw _.close(),_.delete(),Error(`Failed to start transcoding url=${t}`);let A=[];for(let e=0;e<S;++e){let i=new Uint8Array(_.getImageTranscodedSizeInBytes(e,0,0,c));if(!_.transcodeImage(i,e,0,0,c,0,-1,-1))throw _.close(),_.delete(),Error(`Failed to transcode image url=${t}`);let r=c===s.cTFRGB565||c===s.cTFRGBA4444;A.push(r?new Uint16Array(i.buffer):i);}if(_.close(),_.delete(),E)for(p=0,c=s.cTFRGB565;p<A.length;++p)A[p]=h(l(A[p]));return {format:o(c,n.deviceDetails),width:g,height:v,levels:A,cubemap:false,transcodeTime:d()-m,url:t,unswizzledGGGR:E}},m=(t,i,n)=>{let c,p,m=d(),_=new e.BasisFile(new Uint8Array(i)),g=_.getImageWidth(0,0),v=_.getImageHeight(0,0),S=_.getNumImages(),y=_.getNumLevels(0),x=!!_.getHasAlpha(),T=_.isUASTC&&_.isUASTC();if(!g||!v||!S||!y)throw _.close(),_.delete(),Error(`Invalid image dimensions url=${t} width=${g} height=${v} images=${S} levels=${y}`);let E=u(n.deviceDetails,x,T),A=!!n.isGGGR&&"pvr"===E;if(A?c=s.cTFRGBA32:f(g,v,c=x?a[E]:r[E])||(c=x?s.cTFRGBA32:s.cTFRGB565),!_.startTranscoding())throw _.close(),_.delete(),Error(`Failed to start transcoding url=${t}`);let b=[];for(let e=0;e<y;++e){let i=_.getImageTranscodedSizeInBytes(0,e,c),r=new Uint8Array(i);if(!_.transcodeImage(r,0,e,c,0,0))if(e===y-1&&i===b[e-1].buffer.byteLength)r.set(new Uint8Array(b[e-1].buffer));else throw _.close(),_.delete(),Error(`Failed to transcode image url=${t}`);let a=c===s.cTFRGB565||c===s.cTFRGBA4444;b.push(a?new Uint16Array(r.buffer):r);}if(_.close(),_.delete(),A)for(p=0,c=s.cTFRGB565;p<b.length;++p)b[p]=h(l(b[p]));return {format:o(c,n.deviceDetails),width:g,height:v,levels:b,cubemap:false,transcodeTime:d()-m,url:t,unswizzledGGGR:A}},_=(e,t,i)=>i.isKTX2?p(e,t,i):m(e,t,i),g=(e,t,i)=>{try{let s=_(e,t,i);s.levels=s.levels.map(e=>e.buffer),self.postMessage({url:e,data:s},s.levels);}catch(t){self.postMessage({url:e,err:t},null);}},v=(s,r)=>{self.BASIS(s.module?{instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.module,e).then(e=>{t(e);}).catch(e=>{}),{})}:null).then(a=>{a.initializeBasis(),e=a,t=s.rgbPriority,i=s.rgbaPriority,r(null);});},S=[];self.onmessage=t=>{let i=t.data;switch(i.type){case "init":v(i.config,()=>{for(let e=0;e<S.length;++e)g(S[e].url,S[e].data,S[e].options);S.length=0;});break;case "transcode":e?g(i.url,i.data,i.options):S.push(i);}};}let L$=e=>({astc:!!e.extCompressedTextureASTC,atc:!!e.extCompressedTextureATC,dxt:!!e.extCompressedTextureS3TC,etc1:!!e.extCompressedTextureETC1,etc2:!!e.extCompressedTextureETC,pvr:!!e.extCompressedTexturePVRTC}),Lj=(e,t)=>{let i=e=>new Blob([["/* basis */",e,"",`(${Lq.toString()})()
`].join("\n")],{type:"application/javascript"}),s=(s,r)=>{t(null,{workerUrl:URL.createObjectURL(i(s)),module:r,rgbPriority:e.rgbPriority,rgbaPriority:e.rgbaPriority});},r={cache:true,responseType:"text",retry:e.maxRetries>0,maxRetries:e.maxRetries};if(e.glueUrl&&e.wasmUrl&&(()=>{try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){let e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return false})()){let i=null,a=null;d1.get(e.glueUrl,r,(e,r)=>{e?t(e):a?s(r,a):i=r;});let n=fetch(e.wasmUrl),o=()=>{n.then(e=>e.arrayBuffer()).then(e=>WebAssembly.compile(e)).then(e=>{i?s(i,e):a=e;}).catch(e=>{t(e,null);});};WebAssembly.compileStreaming?WebAssembly.compileStreaming(n).then(e=>{i?s(i,e):a=e;}).catch(e=>{o();}):o();}else d1.get(e.fallbackUrl,r,(e,i)=>{e?t(e,null):s(i,null);});};class LK{constructor(e,t,i){this.queue=e,this.worker=new Worker(t.workerUrl),this.worker.addEventListener("message",e=>{let t=e.data;this.queue.handleResponse(t.url,t.err,t.data),this.eager||this.queue.enqueueClient(this);}),this.worker.postMessage({type:"init",config:t}),this.eager=i;}run(e){let t=[];e.data instanceof ArrayBuffer&&t.push(e.data),this.worker.postMessage({type:"transcode",url:e.url,format:e.format,data:e.data,options:e.options},t),this.eager&&this.queue.enqueueClient(this);}}let LZ=["etc2","etc1","astc","dxt","pvr","atc"],LQ=["astc","dxt","etc2","pvr","atc"],LJ=new class{constructor(){this.callbacks={},this.queue=[],this.clients=[];}enqueueJob(e,t,i,s){if(this.callbacks.hasOwnProperty(e))this.callbacks[e].push(i);else {this.callbacks[e]=[i];let r={url:e,data:t,options:s};this.clients.length>0?this.clients.shift().run(r):this.queue.push(r);}}enqueueClient(e){this.queue.length>0?e.run(this.queue.shift()):this.clients.push(e);}handleResponse(e,t,i){let s=this.callbacks[e];if(t)for(let e=0;e<s.length;++e)s[e](t);else {i.format===io||i.format===ih?i.levels=i.levels.map(e=>new Uint16Array(e)):i.levels=i.levels.map(e=>new Uint8Array(e));for(let e=0;e<s.length;++e)s[e](null,i);}delete this.callbacks[e];}},L0=null,L1=false;function L2(e){if(!L1){if(e){if(e.lazyInit){L0=e;return}}else e=L0||{};if(!e.glueUrl||!e.wasmUrl||!e.fallbackUrl){let t=ed.getConfig("BASIS");t&&(e={glueUrl:t.glueUrl,wasmUrl:t.wasmUrl,fallbackUrl:t.fallbackUrl,numWorkers:t.numWorkers});}if(e.glueUrl||e.wasmUrl||e.fallbackUrl){L1=true;let t=Math.max(1,Math.min(16,e.numWorkers||1)),i=1===e.numWorkers||!e.hasOwnProperty("eagerWorkers")||e.eagerWorkers;e.rgbPriority=e.rgbPriority||LZ,e.rgbaPriority=e.rgbaPriority||LQ,e.maxRetries=e.hasOwnProperty("maxRetries")?e.maxRetries:5,Lj(e,(e,s)=>{if(e);else for(let e=0;e<t;++e)LJ.enqueueClient(new LK(LJ,s,i));});}}}let L3=null;function L4(e,t,i,s,r){return L2(),L3||(L3={formats:L$(e)}),LJ.enqueueJob(t,i,s,{deviceDetails:L3,isGGGR:!!r?.isGGGR,isKTX2:!!r?.isKTX2}),L1}class L5{load(e,t,i){throw Error("not implemented")}open(e,t,i){throw Error("not implemented")}}class L8 extends L5{constructor(e,t){super(),this.device=t,this.maxRetries=0;}load(e,t,i){let s=this.device,r=r=>{L4(s,e.load,r,t,{isGGGR:(i?.file?.variants?.basis?.opt&8)!=0})||t(`Basis module not found. Asset [${i.name}](${i.getFileUrl()}) basis texture variant will not be loaded.`);};xF.fetchArrayBuffer(e.load,(e,i)=>{e?t(e):r(i);},i,this.maxRetries);}open(e,t,i,s={}){let r=s.srgb?sd(t.format):t.format,a=new ns(i,{name:e,addressU:t.cubemap?tr:ts,addressV:t.cubemap?tr:ts,width:t.width,height:t.height,format:r,cubemap:t.cubemap,levels:t.levels,...s});return a.upload(),a}}class L6 extends L5{constructor(e,t){super(),this.crossOrigin=e.prefix?"anonymous":null,this.maxRetries=0,this.device=t;}load(e,t,i){let s,r=!!i?.file?.contents;if(r){if(this.device.supportsImageBitmap)return void this._loadImageBitmapFromBlob(new Blob([i.file.contents]),t);e={load:URL.createObjectURL(new Blob([i.file.contents])),original:e.original};}let a=(i,s)=>{r&&URL.revokeObjectURL(e.load),t(i,s);};i&&i.options&&i.options.hasOwnProperty("crossOrigin")?s=i.options.crossOrigin:x_.test(e.load)&&(s=this.crossOrigin),this.device.supportsImageBitmap?this._loadImageBitmap(e.load,e.original,s,a,i):this._loadImage(e.load,e.original,s,a,i);}open(e,t,i,s={}){let r=new ns(i,{name:e,width:t.width,height:t.height,format:s.srgb?ib:id,...s});return r.setSource(t),r}_loadImage(e,t,i,s,r){let a,n=new Image;i&&(n.crossOrigin=i);let o=0,l=this.maxRetries;r?.fire("progress",0,1048576),n.onload=function(){r?.fire("progress",1048576,1048576),s(null,n);},n.onerror=function(){if(!a)if(l>0&&++o<=l){let t=100*Math.pow(2,o),i=e.indexOf("?")>=0?"&":"?";a=setTimeout(()=>{n.src=`${e+i}retry=${Date.now()}`,a=null;},t);}else s(`Error loading Texture from: '${t}'`);},n.src=e;}_loadImageBitmap(e,t,i,s,r){let a={cache:true,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries,progress:r};d1.get(e,a,(e,t)=>{e?s(e):this._loadImageBitmapFromBlob(t,s);});}_loadImageBitmapFromBlob(e,t){createImageBitmap(e,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(e=>t(null,e)).catch(e=>t(e));}}let L9={33776:iu,33778:ip,33779:im,36196:iw,37492:iC,37496:iP,35840:iD,35841:iL,35842:iR,35843:iI,32849:ic,32856:id,35905:iA,35907:ib,35898:iE,34843:i_,34842:ig};class L7 extends L5{constructor(e){super(),this.maxRetries=0;}load(e,t,i){xF.fetchArrayBuffer(e.load,t,i,this.maxRetries);}open(e,t,i,s={}){let r=this.parse(t);if(!r)return null;let a=s.srgb?sd(r.format):r.format,n=new ns(i,{name:e,addressU:r.cubemap?tr:ts,addressV:r.cubemap?tr:ts,width:r.width,height:r.height,format:a,cubemap:r.cubemap,levels:r.levels,...s});return n.upload(),n}parse(e){let t=new Uint32Array(e);if(0x58544bab!==t[0]||0xbb313120!==t[1]||0xa1a0a0d!==t[2])return null;let i={endianness:t[3],glType:t[4],glTypeSize:t[5],glFormat:t[6],glInternalFormat:t[7],glBaseInternalFormat:t[8],pixelWidth:t[9],pixelHeight:t[10],pixelDepth:t[11],numberOfArrayElements:t[12],numberOfFaces:t[13],numberOfMipmapLevels:t[14],bytesOfKeyValueData:t[15]};if(i.pixelDepth>1||0!==i.numberOfArrayElements)return null;let s=L9[i.glInternalFormat];if(void 0===s)return null;let r=16+i.bytesOfKeyValueData/4,a=i.numberOfFaces>1,n=[];for(let l=0;l<(i.numberOfMipmapLevels||1);l++){let i=t[r++];a&&n.push([]);let h=a?n[l]:n;for(let t=0;t<(a?6:1);++t){var o;h.push((o=4*r,s===iE?new Uint32Array(e,o,i/4):new Uint8Array(e,o,i))),r+=i+3>>2;}}return {format:s,width:i.pixelWidth,height:i.pixelHeight,levels:n,cubemap:a}}}let Ie={KHR_DF_MODEL_UASTC:166};class It extends L5{constructor(e,t){super(),this.maxRetries=0,this.device=t;}load(e,t,i){xF.fetchArrayBuffer(e.load,(s,r)=>{s?t(s,r):this.parse(r,e,t,i);},i,this.maxRetries);}open(e,t,i,s={}){let r=s.srgb?sd(t.format):t.format,a=new ns(i,{name:e,addressU:t.cubemap?tr:ts,addressV:t.cubemap?tr:ts,width:t.width,height:t.height,format:r,cubemap:t.cubemap,levels:t.levels,...s});return a.upload(),a}parse(e,t,i,s){let r=new eu(e),a=[r.readU32be(),r.readU32be(),r.readU32be()];if(0xab4b5458!==a[0]||0x203230bb!==a[1]||0xd0a1a0a!==a[2])return null;let n={vkFormat:r.readU32(),typeSize:r.readU32(),pixelWidth:r.readU32(),pixelHeight:r.readU32(),pixelDepth:r.readU32(),layerCount:r.readU32(),faceCount:r.readU32(),levelCount:r.readU32(),supercompressionScheme:r.readU32()},o={dfdByteOffset:r.readU32(),dfdByteLength:r.readU32(),kvdByteOffset:r.readU32(),kvdByteLength:r.readU32(),sgdByteOffset:r.readU64(),sgdByteLength:r.readU64()},l=[];for(let e=0;e<Math.max(1,n.levelCount);++e)l.push({byteOffset:r.readU64(),byteLength:r.readU64(),uncompressedByteLength:r.readU64()});if(r.readU32()!==o.kvdByteOffset-o.dfdByteOffset)return null;r.skip(8);let h=r.readU8();r.skip(o.dfdByteLength-9),r.skip(o.kvdByteLength),1===n.supercompressionScheme||h===Ie.KHR_DF_MODEL_UASTC?L4(this.device,t.load,e,i,{isGGGR:(s?.file?.variants?.basis?.opt&8)!=0,isKTX2:true})||i(`Basis module not found. Asset [${s.name}](${s.getFileUrl()}) basis texture variant will not be loaded.`):i("unsupported KTX2 pixel format");}}class Ii extends L5{constructor(e){super(),this.maxRetries=0;}load(e,t,i){xF.fetchArrayBuffer(e.load,t,i,this.maxRetries);}open(e,t,i,s={}){let r,a,n=new Uint32Array(t,0,32),o=n[4],l=n[3],h=Math.max(n[7],1),c=4===n[20],d=n[21],u=n[22],f=65024===n[28],p=false,m=false,_=false,g=false,v=null,S=1;if(c?0x31545844===d?(v=iu,p=true):0x35545844===d?(v=im,p=true):113===d?(v=ig,S=2):116===d?(v=iS,S=4):0x31435445===d?(v=iw,p=true,m=true):0x31333250===d||0x31343250===d?(v=0x31333250===d?iL:iI,p=true,_=true):(0x31333450===d||0x31343450===d)&&(v=0x31333450===d?iD:iR,p=true,g=true):32===u&&(v=id),!v)return new ns(i,{width:4,height:4,format:ic,name:"dds-legacy-empty"});r=new ns(i,{name:e,addressU:f?tr:ts,addressV:f?tr:ts,width:o,height:l,format:v,cubemap:f,mipmaps:h>1,...s});let y=128,x=f?6:1,T=0x31545844===d?8:16;for(let e=0;e<x;e++){let i=o,s=l;for(let n=0;n<h;n++){a=p?m?Math.floor((i+3)/4)*Math.floor((s+3)/4)*8:_?Math.max(i,16)*Math.max(s,8)/4:g?Math.max(i,8)*Math.max(s,8)/2:Math.floor((i+4-1)/4)*Math.floor((s+4-1)/4)*T:i*s*4;let o=v===iS?new Float32Array(t,y,a):v===ig?new Uint16Array(t,y,a):new Uint8Array(t,y,a);f?(r._levels[n]||(r._levels[n]=[]),r._levels[n][e]=o):r._levels[n]=o,y+=a*S,i=Math.max(.5*i,1),s=Math.max(.5*s,1);}}return r.upload(),r}}class Is extends L5{constructor(e){super(),this.maxRetries=0;}load(e,t,i){xF.fetchArrayBuffer(e.load,t,i,this.maxRetries),i.data&&!i.data.type&&(i.data.type=rs);}open(e,t,i,s={}){let r=this.parse(t);if(!r)return null;let a=new ns(i,{name:e,addressU:ts,addressV:tr,minFilter:tK,magFilter:tK,width:r.width,height:r.height,levels:r.levels,format:id,type:rs,mipmaps:false,...s});return a.upload(),a}parse(e){let t=new eu(e);if(!t.readLine().startsWith("#?RADIANCE"))return null;let i={};for(;;){let e=t.readLine();if(0===e.length)break;{let t=e.split("=");2===t.length&&(i[t[0]]=t[1]);}}if(!i.hasOwnProperty("FORMAT"))return null;let s=t.readLine().split(" ");if(4!==s.length)return null;let r=parseInt(s[1],10),a=parseInt(s[3],10),n=this._readPixels(t,a,r,"-Y"===s[0]);return n?{width:a,height:r,levels:[n]}:null}_readPixels(e,t,i,s){let r,a,n,o,l,h;if(t<8||t>32767)return this._readPixelsFlat(e,t,i);let c=[0,0,0,0];if(e.readArray(c),2!==c[0]||2!==c[1]||(128&c[2])!=0)return e.skip(-4),this._readPixelsFlat(e,t,i);let d=new Uint8Array(new ArrayBuffer(t*i*4)),u=s?0:4*t*(i-1);for(a=0;a<i;++a){if(a&&e.readArray(c),(c[2]<<8)+c[3]!==t)return null;for(o=0;o<4;++o)for(r=0;r<t;)if((l=e.readU8())>128){if(r+(l-=128)>t)return null;for(n=0,h=e.readU8();n<l;++n)d[u+o+4*r++]=h;}else {if(0===l||r+l>t)return null;for(n=0;n<l;++n)d[u+o+4*r++]=e.readU8();}u+=4*t*(s?1:-1);}return d}_readPixelsFlat(e,t,i){return e.remainingBytes===t*i*4?new Uint8Array(e.arraybuffer,e.offset):null}}let Ir={repeat:ts,clamp:tr,mirror:ta},Ia={nearest:tK,linear:tZ,nearest_mip_nearest:tQ,linear_mip_nearest:t0,nearest_mip_linear:tJ,linear_mip_linear:t1},In={default:rt,rgbm:ri,rgbe:rs,rgbp:rr,swizzleGGGR:ra},Io=function(e){var t;let i=nt.calcMipLevelsCount(e._width,e._height);if(e._format!==id&&e._format!==iS||e._volume||e._compressed||1===e._levels.length||e._levels.length===i||(t=e._cubemap?e._levels[0][0]:e._levels[0])instanceof HTMLCanvasElement||t instanceof HTMLImageElement||t instanceof HTMLVideoElement)return;let s=function(e,t,i){let s=Math.max(1,e>>1),r=Math.max(1,t>>1),a=new i.constructor(s*r*4),n=Math.floor(e/s),o=Math.floor(t/r),l=n*o;for(let t=0;t<r;++t)for(let r=0;r<s;++r)for(let h=0;h<4;++h){let c=0;for(let s=0;s<o;++s)for(let a=0;a<n;++a)c+=i[(r*n+a+(t*o+s)*e)*4+h];a[(r+t*s)*4+h]=c/l;}return a};for(let t=e._levels.length;t<i;++t){let i=Math.max(1,e._width>>t-1),r=Math.max(1,e._height>>t-1);if(e._cubemap){let a=[];for(let n=0;n<6;++n)a.push(s(i,r,e._levels[t-1][n]));e._levels.push(a);}else e._levels.push(s(i,r,e._levels[t-1]));}e._levelsUpdated=e._cubemap?[[true,true,true,true,true,true]]:[true];};class Il extends xH{constructor(e){super(e,"texture");let t=e.assets,i=e.graphicsDevice;this._device=i,this._assets=t,this.imgParser=new L6(t,i),this.parsers={dds:new Ii(t),ktx:new L7(t),ktx2:new It(t,i),basis:new L8(t,i),hdr:new Is(t)};}set crossOrigin(e){this.imgParser.crossOrigin=e;}get crossOrigin(){return this.imgParser.crossOrigin}set maxRetries(e){for(let t in this.imgParser.maxRetries=e,this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e);}get maxRetries(){return this.imgParser.maxRetries}_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}_getParser(e){let t=W.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".","");return this.parsers[t]||this.imgParser}_getTextureOptions(e){let t={};if(e){e.name?.length>0&&(t.name=e.name);let i=e.data;i.hasOwnProperty("minfilter")&&(t.minFilter=Ia[i.minfilter]),i.hasOwnProperty("magfilter")&&(t.magFilter=Ia[i.magfilter]),i.hasOwnProperty("addressu")&&(t.addressU=Ir[i.addressu]),i.hasOwnProperty("addressv")&&(t.addressV=Ir[i.addressv]),i.hasOwnProperty("mipmaps")&&(t.mipmaps=i.mipmaps),i.hasOwnProperty("anisotropy")&&(t.anisotropy=i.anisotropy),i.hasOwnProperty("flipY")&&(t.flipY=!!i.flipY),i.hasOwnProperty("srgb")&&(t.srgb=!!i.srgb),t.type=rt,i.hasOwnProperty("type")?t.type=In[i.type]:i.hasOwnProperty("rgbm")&&i.rgbm?t.type=ri:e.file&&(8&e.file.opt)!=0&&(t.type=ra);}return t}load(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i);}open(e,t,i){if(!e)return;let s=this._getTextureOptions(i),r=this._getParser(e).open(e,t,this._device,s);return null===r?r=new ns(this._device,{width:4,height:4,format:ic}):(Io(r),t.unswizzledGGGR&&(i.file.variants.basis.opt&=-9)),r}patch(e,t){let i=e.resource;if(!i)return;let s=this._getTextureOptions(e);for(let e of Object.keys(s))i[e]=s[e];}}let Ih="inline",Ic="immersive-vr",Id="immersive-ar",Iu="viewer",If="local",Ip="local-floor",Im="bounded-floor",I_="unbounded",Ig="gaze",Iv="screen",IS="tracked-pointer",Iy="none",Ix="left",IT="right",IE="none",IA="left",Ib="right",Iw="point",IC="plane",IP="mesh",IL="cpu-optimized",II="gpu-optimized",ID="luminance-alpha",IR="unsigned-short",IM="float32";class IO{constructor(e){this._supported=ee.browser&&!!window.XRDOMOverlayState,this._root=null,this._manager=e;}get supported(){return this._supported}get available(){return this._supported&&this._manager.active&&null!==this._manager._session.domOverlayState}get state(){return this._supported&&this._manager.active&&this._manager._session.domOverlayState?this._manager._session.domOverlayState.type:null}set root(e){this._supported&&!this._manager.active&&(this._root=e);}get root(){return this._root}}let IN=[],IF=[];class IB extends eo{static{this.EVENT_REMOVE="remove";}static{this.EVENT_RESULT="result";}constructor(e,t,i,s=null){super(),this.manager=e,this._xrHitTestSource=t,this._transient=i,this._inputSource=s;}remove(){if(!this._xrHitTestSource)return;let e=this.manager.hitTest.sources,t=e.indexOf(this);-1!==t&&e.splice(t,1),this.onStop();}onStop(){this._xrHitTestSource.cancel(),this._xrHitTestSource=null,this.fire("remove"),this.manager.hitTest.fire("remove",this);}update(e){if(this._transient){let t=e.getHitTestResultsForTransientInput(this._xrHitTestSource);for(let e=0;e<t.length;e++){let i,s=t[e];s.results.length&&(s.inputSource&&(i=this.manager.input._getByInputSource(s.inputSource)),this.updateHitResults(s.results,i));}}else {let t=e.getHitTestResults(this._xrHitTestSource);if(!t.length)return;this.updateHitResults(t);}}updateHitResults(e,t){if(this._inputSource&&this._inputSource!==t)return;let i=IN.pop()??new eM;t?i.copy(t.getOrigin()):i.copy(this.manager.camera.getPosition());let s=1/0,r=null,a=IN.pop()??new eM,n=IF.pop()??new eH;for(let t=0;t<e.length;t++){let o=e[t].getPose(this.manager._referenceSpace),l=i.distance(o.transform.position);l>=s||(s=l,r=e[t],a.copy(o.transform.position),n.copy(o.transform.orientation));}this.fire("result",a,n,t||this._inputSource,r),this.manager.hitTest.fire("result",this,a,n,t||this._inputSource,r),IN.push(i),IN.push(a),IF.push(n);}}class IU extends eo{static{this.EVENT_AVAILABLE="available";}static{this.EVENT_UNAVAILABLE="unavailable";}static{this.EVENT_ADD="add";}static{this.EVENT_REMOVE="remove";}static{this.EVENT_RESULT="result";}static{this.EVENT_ERROR="error";}constructor(e){super(),this._supported=ee.browser&&!!(window.XRSession&&window.XRSession.prototype.requestHitTestSource),this._available=false,this._checkingAvailability=false,this.sources=[],this.manager=e,this._supported&&(this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this));}_onSessionStart(){if(this.manager.session.enabledFeatures){let e=-1!==this.manager.session.enabledFeatures.indexOf("hit-test");e&&(this._available=e,this.fire("available"));}else this._checkingAvailability||(this._checkingAvailability=true,this.manager.session.requestReferenceSpace(Iu).then(e=>{this.manager.session.requestHitTestSource({space:e}).then(e=>{e.cancel(),this.manager.active&&(this._available=true,this.fire("available"));}).catch(()=>{});}).catch(()=>{}));}_onSessionEnd(){if(this._available){this._available=false;for(let e=0;e<this.sources.length;e++)this.sources[e].onStop();this.sources=[],this.fire("unavailable");}}start(e={}){let t;if(!this._supported)return void e.callback?.(Error("XR HitTest is not supported"),null);if(!this._available)return void e.callback?.(Error("XR HitTest is not available"),null);e.profile||e.spaceType||(e.spaceType=Iu);let i=e.offsetRay;i&&(t=new XRRay(new DOMPoint(i.origin.x,i.origin.y,i.origin.z,1),new DOMPoint(i.direction.x,i.direction.y,i.direction.z,0)));let s=e.callback;e.spaceType?this.manager.session.requestReferenceSpace(e.spaceType).then(i=>{if(!this.manager.session){let e=Error("XR Session is not started (2)");s&&s(e),this.fire("error",e);return}this.manager.session.requestHitTestSource({space:i,entityTypes:e.entityTypes||void 0,offsetRay:t}).then(t=>{this._onHitTestSource(t,false,e.inputSource,s);}).catch(e=>{s&&s(e),this.fire("error",e);});}).catch(e=>{s&&s(e),this.fire("error",e);}):this.manager.session.requestHitTestSourceForTransientInput({profile:e.profile,entityTypes:e.entityTypes||void 0,offsetRay:t}).then(t=>{this._onHitTestSource(t,true,e.inputSource,s);}).catch(e=>{s&&s(e),this.fire("error",e);});}_onHitTestSource(e,t,i,s){if(!this.manager.session){e.cancel();let t=Error("XR Session is not started (3)");s&&s(t),this.fire("error",t);return}let r=new IB(this.manager,e,t,i??null);this.sources.push(r),s&&s(null,r),this.fire("add",r);}update(e){if(this._available)for(let t=0;t<this.sources.length;t++)this.sources[t].update(e);}get supported(){return this._supported}get available(){return this._available}}class Ik extends eo{static{this.EVENT_TRACKED="tracked";}static{this.EVENT_UNTRACKED="untracked";}constructor(e,t){super(),this._bitmap=null,this._measuredWidth=0,this._trackable=false,this._tracking=false,this._emulated=false,this._pose=null,this._position=new eM,this._rotation=new eH,this._image=e,this._width=t;}get image(){return this._image}set width(e){this._width=e;}get width(){return this._width}get trackable(){return this._trackable}get tracking(){return this._tracking}get emulated(){return this._emulated}prepare(){return this._bitmap?{image:this._bitmap,widthInMeters:this._width}:createImageBitmap(this._image).then(e=>(this._bitmap=e,{image:this._bitmap,widthInMeters:this._width}))}destroy(){this._image=null,this._pose=null,this._bitmap&&(this._bitmap.close(),this._bitmap=null);}getPosition(){return this._pose&&this._position.copy(this._pose.transform.position),this._position}getRotation(){return this._pose&&this._rotation.copy(this._pose.transform.orientation),this._rotation}}class IV extends eo{static{this.EVENT_ERROR="error";}constructor(e){super(),this._supported=ee.browser&&!!window.XRImageTrackingResult,this._available=false,this._images=[],this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this));}add(e,t){if(!this._supported||this._manager.active)return null;let i=new Ik(e,t);return this._images.push(i),i}remove(e){if(this._manager.active)return;let t=this._images.indexOf(e);-1!==t&&(e.destroy(),this._images.splice(t,1));}_onSessionStart(){this._manager.session.getTrackedImageScores().then(e=>{this._available=true;for(let t=0;t<e.length;t++)this._images[t]._trackable="trackable"===e[t];}).catch(e=>{this._available=false,this.fire("error",e);});}_onSessionEnd(){this._available=false;for(let e=0;e<this._images.length;e++){let t=this._images[e];t._pose=null,t._measuredWidth=0,t._tracking&&(t._tracking=false,t.fire("untracked"));}}prepareImages(e){this._images.length?Promise.all(this._images.map(e=>e.prepare())).then(t=>{e(null,t);}).catch(t=>{e(t,null);}):e(null,null);}update(e){if(!this._available)return;let t=e.getImageTrackingResults(),i={};for(let s=0;s<t.length;s++){i[t[s].index]=t[s];let r=this._images[t[s].index];r._emulated="emulated"===t[s].trackingState,r._measuredWidth=t[s].measuredWidthInMeters,r._pose=e.getPose(t[s].imageSpace,this._manager._referenceSpace);}for(let e=0;e<this._images.length;e++)this._images[e]._tracking&&!i[e]?(this._images[e]._tracking=false,this._images[e].fire("untracked")):!this._images[e]._tracking&&i[e]&&(this._images[e]._tracking=true,this._images[e].fire("tracked"));}get supported(){return this._supported}get available(){return this._available}get images(){return this._images}}class Iz{constructor(e,t){this._joints=[],this._tip=null,this._index=e,this._hand=t,this._hand._fingers.push(this);}get index(){return this._index}get hand(){return this._hand}get joints(){return this._joints}get tip(){return this._tip}}let IG=ee.browser&&window.XRHand?["thumb-tip","index-finger-tip","middle-finger-tip","ring-finger-tip","pinky-finger-tip"]:[],IH={};for(let e=0;e<IG.length;e++)IH[IG[e]]=true;class IW{constructor(e,t,i,s=null){this._radius=null,this._localTransform=new eG,this._worldTransform=new eG,this._localPosition=new eM,this._localRotation=new eH,this._position=new eM,this._rotation=new eH,this._dirtyLocal=true,this._index=e,this._id=t,this._hand=i,this._finger=s,this._wrist="wrist"===t,this._tip=this._finger&&!!IH[t];}update(e){this._dirtyLocal=true,this._radius=e.radius,this._localPosition.copy(e.transform.position),this._localRotation.copy(e.transform.orientation);}_updateTransforms(){this._dirtyLocal&&(this._dirtyLocal=false,this._localTransform.setTRS(this._localPosition,this._localRotation,eM.ONE));let e=this._hand._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform);}getPosition(){return this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position}getRotation(){return this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation}get id(){return this._id}get index(){return this._index}get hand(){return this._hand}get finger(){return this._finger}get wrist(){return this._wrist}get tip(){return this._tip}get radius(){return this._radius||.005}}let IX=[],IY=new eM,Iq=new eM,I$=new eM;ee.browser&&window.XRHand&&(IX=[["thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip"],["index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip"],["middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip"],["ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip"],["pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"]]);class Ij extends eo{static{this.EVENT_TRACKING="tracking";}static{this.EVENT_TRACKINGLOST="trackinglost";}constructor(e){super(),this._tracking=false,this._fingers=[],this._joints=[],this._jointsById={},this._tips=[],this._wrist=null;let t=e._xrInputSource.hand;if(this._manager=e._manager,this._inputSource=e,t.get("wrist")){let e=new IW(0,"wrist",this,null);this._wrist=e,this._joints.push(e),this._jointsById.wrist=e;}for(let e=0;e<IX.length;e++){let i=new Iz(e,this);for(let s=0;s<IX[e].length;s++){let r=IX[e][s];if(!t.get(r))continue;let a=new IW(s,r,this,i);this._joints.push(a),this._jointsById[r]=a,a.tip&&(this._tips.push(a),i._tip=a),i._joints.push(a);}}}update(e){let t=this._inputSource._xrInputSource;for(let i=0;i<this._joints.length;i++){let s=this._joints[i],r=t.hand.get(s._id);if(r){let t;if("hidden"!==e.session.visibilityState&&(t=e.getJointPose(r,this._manager._referenceSpace)),t)s.update(t),s.wrist&&!this._tracking&&(this._tracking=true,this.fire("tracking"));else if(s.wrist){this._tracking&&(this._tracking=false,this.fire("trackinglost"));break}}}let i=this._jointsById["thumb-metacarpal"],s=this._jointsById["thumb-tip"],r=this._jointsById["index-finger-phalanx-proximal"],a=this._jointsById["index-finger-tip"],n=this._jointsById["ring-finger-phalanx-proximal"],o=this._jointsById["pinky-finger-phalanx-proximal"];if(i&&s&&r&&a&&n&&o){this._inputSource._dirtyRay=true,this._inputSource._rayLocal.origin.lerp(s._localPosition,a._localPosition,.5);let e=i,t=o;if(this._inputSource.handedness===IA){let i=e;e=t,t=i;}IY.sub2(e._localPosition,this._wrist._localPosition),Iq.sub2(t._localPosition,this._wrist._localPosition),I$.cross(IY,Iq).normalize(),IY.lerp(r._localPosition,n._localPosition,.5),IY.sub(this._wrist._localPosition).normalize(),this._inputSource._rayLocal.direction.lerp(I$,IY,.5).normalize();}this._fingerIsClosed(1)&&this._fingerIsClosed(2)&&this._fingerIsClosed(3)&&this._fingerIsClosed(4)?this._inputSource._squeezing||(this._inputSource._squeezing=true,this._inputSource.fire("squeezestart"),this._manager.input.fire("squeezestart",this._inputSource)):this._inputSource._squeezing&&(this._inputSource._squeezing=false,this._inputSource.fire("squeeze"),this._manager.input.fire("squeeze",this._inputSource),this._inputSource.fire("squeezeend"),this._manager.input.fire("squeezeend",this._inputSource));}_fingerIsClosed(e){let t=this._fingers[e];return IY.sub2(t.joints[0]._localPosition,t.joints[1]._localPosition).normalize(),Iq.sub2(t.joints[2]._localPosition,t.joints[3]._localPosition).normalize(),-0.8>IY.dot(Iq)}getJointById(e){return this._jointsById[e]||null}get fingers(){return this._fingers}get joints(){return this._joints}get tips(){return this._tips}get wrist(){return this._wrist}get tracking(){return this._tracking}}let IK=new eM,IZ=new eH,IQ=0;class IJ extends eo{static{this.EVENT_REMOVE="remove";}static{this.EVENT_SELECT="select";}static{this.EVENT_SELECTSTART="selectstart";}static{this.EVENT_SELECTEND="selectend";}static{this.EVENT_SQUEEZE="squeeze";}static{this.EVENT_SQUEEZESTART="squeezestart";}static{this.EVENT_SQUEEZEEND="squeezeend";}static{this.EVENT_HITTESTADD="hittest:add";}static{this.EVENT_HITTESTREMOVE="hittest:remove";}static{this.EVENT_HITTESTRESULT="hittest:result";}constructor(e,t){super(),this._ray=new e1,this._rayLocal=new e1,this._grip=false,this._hand=null,this._velocitiesAvailable=false,this._velocitiesTimestamp=em(),this._localTransform=null,this._worldTransform=null,this._position=new eM,this._rotation=new eH,this._localPosition=null,this._localPositionLast=null,this._localRotation=null,this._linearVelocity=null,this._dirtyLocal=true,this._dirtyRay=false,this._selecting=false,this._squeezing=false,this._elementInput=true,this._elementEntity=null,this._hitTestSources=[],this._id=++IQ,this._manager=e,this._xrInputSource=t,t.hand&&(this._hand=new Ij(this));}get id(){return this._id}get inputSource(){return this._xrInputSource}get targetRayMode(){return this._xrInputSource.targetRayMode}get handedness(){return this._xrInputSource.handedness}get profiles(){return this._xrInputSource.profiles}get grip(){return this._grip}get hand(){return this._hand}get gamepad(){return this._xrInputSource.gamepad||null}get selecting(){return this._selecting}get squeezing(){return this._squeezing}set elementInput(e){this._elementInput!==e&&(this._elementInput=e,this._elementInput||(this._elementEntity=null));}get elementInput(){return this._elementInput}get elementEntity(){return this._elementEntity}get hitTestSources(){return this._hitTestSources}update(e){if(this._hand)this._hand.update(e);else {let t=this._xrInputSource.gripSpace;if(t){let i=e.getPose(t,this._manager._referenceSpace);if(i){this._grip||(this._grip=true,this._localTransform=new eG,this._worldTransform=new eG,this._localPositionLast=new eM,this._localPosition=new eM,this._localRotation=new eH,this._linearVelocity=new eM);let e=em(),t=(e-this._velocitiesTimestamp)/1e3;this._velocitiesTimestamp=e,this._dirtyLocal=true,this._localPositionLast.copy(this._localPosition),this._localPosition.copy(i.transform.position),this._localRotation.copy(i.transform.orientation),this._velocitiesAvailable=true,this._manager.input.velocitiesSupported&&i.linearVelocity?this._linearVelocity.copy(i.linearVelocity):t>0&&(IK.sub2(this._localPosition,this._localPositionLast).divScalar(t),this._linearVelocity.lerp(this._linearVelocity,IK,.15));}else this._velocitiesAvailable=false;}let i=e.getPose(this._xrInputSource.targetRaySpace,this._manager._referenceSpace);i&&(this._dirtyRay=true,this._rayLocal.origin.copy(i.transform.position),this._rayLocal.direction.set(0,0,-1),IZ.copy(i.transform.orientation),IZ.transformVector(this._rayLocal.direction,this._rayLocal.direction));}}_updateTransforms(){this._dirtyLocal&&(this._dirtyLocal=false,this._localTransform.setTRS(this._localPosition,this._localRotation,eM.ONE));let e=this._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform);}_updateRayTransforms(){let e=this._dirtyRay;if(this._dirtyRay=false,this._manager.camera.parent){let e=this._manager.camera.parent.getWorldTransform();e.getTranslation(this._position),this._rotation.setFromMat4(e),this._rotation.transformVector(this._rayLocal.origin,this._ray.origin),this._ray.origin.add(this._position),this._rotation.transformVector(this._rayLocal.direction,this._ray.direction);}else e&&(this._ray.origin.copy(this._rayLocal.origin),this._ray.direction.copy(this._rayLocal.direction));}getPosition(){return this._position?(this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position):null}getLocalPosition(){return this._localPosition}getRotation(){return this._rotation?(this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation):null}getLocalRotation(){return this._localRotation}getLinearVelocity(){return this._velocitiesAvailable?this._linearVelocity:null}getOrigin(){return this._updateRayTransforms(),this._ray.origin}getDirection(){return this._updateRayTransforms(),this._ray.direction}hitTestStart(e={}){e.inputSource=this,e.profile=this._xrInputSource.profiles[0];let t=e.callback;e.callback=(e,i)=>{i&&this.onHitTestSourceAdd(i),t&&t(e,i);},this._manager.hitTest.start(e);}onHitTestSourceAdd(e){this._hitTestSources.push(e),this.fire("hittest:add",e),e.on("result",(t,i,s,r)=>{s===this&&this.fire("hittest:result",e,t,i,r);}),e.once("remove",()=>{this.onHitTestSourceRemove(e),this.fire("hittest:remove",e);});}onHitTestSourceRemove(e){let t=this._hitTestSources.indexOf(e);-1!==t&&this._hitTestSources.splice(t,1);}}class I0 extends eo{static{this.EVENT_ADD="add";}static{this.EVENT_REMOVE="remove";}static{this.EVENT_SELECT="select";}static{this.EVENT_SELECTSTART="selectstart";}static{this.EVENT_SELECTEND="selectend";}static{this.EVENT_SQUEEZE="squeeze";}static{this.EVENT_SQUEEZESTART="squeezestart";}static{this.EVENT_SQUEEZEEND="squeezeend";}constructor(e){super(),this._inputSources=[],this.velocitiesSupported=false,this.manager=e,this.velocitiesSupported=!!(ee.browser&&window.XRPose?.prototype?.hasOwnProperty("linearVelocity")),this._onInputSourcesChangeEvt=e=>{this._onInputSourcesChange(e);},this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this);}_onSessionStart(){let e=this.manager.session;e.addEventListener("inputsourceschange",this._onInputSourcesChangeEvt),e.addEventListener("select",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t.fire("select",e),this.fire("select",t,e);}),e.addEventListener("selectstart",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t._selecting=true,t.fire("selectstart",e),this.fire("selectstart",t,e);}),e.addEventListener("selectend",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t._selecting=false,t.fire("selectend",e),this.fire("selectend",t,e);}),e.addEventListener("squeeze",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t.fire("squeeze",e),this.fire("squeeze",t,e);}),e.addEventListener("squeezestart",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t._squeezing=true,t.fire("squeezestart",e),this.fire("squeezestart",t,e);}),e.addEventListener("squeezeend",e=>{let t=this._getByInputSource(e.inputSource);t.update(e.frame),t._squeezing=false,t.fire("squeezeend",e),this.fire("squeezeend",t,e);});let t=e.inputSources;for(let e=0;e<t.length;e++)this._addInputSource(t[e]);}_onSessionEnd(){let e=this._inputSources.length;for(;e--;){let t=this._inputSources[e];this._inputSources.splice(e,1),t.fire("remove"),this.fire("remove",t);}this.manager.session.removeEventListener("inputsourceschange",this._onInputSourcesChangeEvt);}_onInputSourcesChange(e){for(let t=0;t<e.removed.length;t++)this._removeInputSource(e.removed[t]);for(let t=0;t<e.added.length;t++)this._addInputSource(e.added[t]);}_getByInputSource(e){for(let t=0;t<this._inputSources.length;t++)if(this._inputSources[t].inputSource===e)return this._inputSources[t];return null}_addInputSource(e){if(this._getByInputSource(e))return;let t=new IJ(this.manager,e);this._inputSources.push(t),this.fire("add",t);}_removeInputSource(e){for(let t=0;t<this._inputSources.length;t++){if(this._inputSources[t].inputSource!==e)continue;let i=this._inputSources[t];this._inputSources.splice(t,1);let s=i.hitTestSources.length;for(;s--;)i.hitTestSources[s].remove();i.fire("remove"),this.fire("remove",i);return}}update(e){for(let t=0;t<this._inputSources.length;t++)this._inputSources[t].update(e);}get inputSources(){return this._inputSources}}let I1=new eM,I2=new eM,I3=new eG,I4=new eG;class I5 extends eo{static{this.EVENT_AVAILABLE="available";}static{this.EVENT_ERROR="error";}constructor(e){super(),this._supported=false,this._available=false,this._lightProbeRequested=false,this._lightProbe=null,this._intensity=0,this._rotation=new eH,this._color=new eb,this._sphericalHarmonics=new Float32Array(27),this._manager=e,this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this);}_onSessionStart(){this._manager.session.requestLightProbe&&(this._supported=true);}_onSessionEnd(){this._supported=false,this._available=false,this._lightProbeRequested=false,this._lightProbe=null;}start(){let e;if(this._manager.session||(e=Error("XR session is not running")),e||this._manager.type===Id||(e=Error("XR session type is not AR")),e||this._supported||(e=Error("light-estimation is not supported")),(!e&&this._lightProbe||this._lightProbeRequested)&&(e=Error("light estimation is already requested")),e)return void this.fire("error",e);this._lightProbeRequested=true,this._manager.session.requestLightProbe().then(e=>{let t=this._lightProbeRequested;this._lightProbeRequested=false,this._manager.active?t&&(this._lightProbe=e):this.fire("error",Error("XR session is not active"));}).catch(e=>{this._lightProbeRequested=false,this.fire("error",e);});}end(){this._lightProbeRequested=false,this._lightProbe=null,this._available=false;}update(e){if(!this._lightProbe)return;let t=e.getLightEstimate(this._lightProbe);if(!t)return;this._available||(this._available=true,this.fire("available"));let i=t.primaryLightIntensity;this._intensity=Math.max(1,Math.max(i.x,Math.max(i.y,i.z))),I1.copy(i).mulScalar(1/this._intensity),this._color.set(I1.x,I1.y,I1.z),I1.set(0,0,0),I2.copy(t.primaryLightDirection),I3.setLookAt(I2,I1,eM.UP),I4.setFromAxisAngle(eM.RIGHT,90),I3.mul(I4),this._rotation.setFromMat4(I3),this._sphericalHarmonics.set(t.sphericalHarmonicsCoefficients);}get supported(){return this._supported}get available(){return this._available}get intensity(){return this._available?this._intensity:null}get color(){return this._available?this._color:null}get rotation(){return this._available?this._rotation:null}get sphericalHarmonics(){return this._available?this._sphericalHarmonics:null}}let I8=0;class I6 extends eo{static{this.EVENT_REMOVE="remove";}static{this.EVENT_CHANGE="change";}constructor(e,t){super(),this._position=new eM,this._rotation=new eH,this._id=++I8,this._planeDetection=e,this._xrPlane=t,this._lastChangedTime=t.lastChangedTime,this._orientation=t.orientation;}destroy(){this._xrPlane&&(this._xrPlane=null,this.fire("remove"));}update(e){let t=this._planeDetection._manager,i=e.getPose(this._xrPlane.planeSpace,t._referenceSpace);i&&(this._position.copy(i.transform.position),this._rotation.copy(i.transform.orientation)),this._lastChangedTime!==this._xrPlane.lastChangedTime&&(this._lastChangedTime=this._xrPlane.lastChangedTime,this.fire("change"));}getPosition(){return this._position}getRotation(){return this._rotation}get id(){return this._id}get orientation(){return this._orientation}get points(){return this._xrPlane.polygon}get label(){return this._xrPlane.semanticLabel||""}}class I9 extends eo{static{this.EVENT_AVAILABLE="available";}static{this.EVENT_UNAVAILABLE="unavailable";}static{this.EVENT_ADD="add";}static{this.EVENT_REMOVE="remove";}constructor(e){super(),this._supported=ee.browser&&!!window.XRPlane,this._available=false,this._planesIndex=new Map,this._planes=[],this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this));}_onSessionStart(){this._manager.session.enabledFeatures&&-1!==this._manager.session.enabledFeatures.indexOf("plane-detection")&&(this._available=true,this.fire("available"));}_onSessionEnd(){for(let e=0;e<this._planes.length;e++)this._planes[e].destroy(),this.fire("remove",this._planes[e]);this._planesIndex.clear(),this._planes.length=0,this._available&&(this._available=false,this.fire("unavailable"));}update(e){if(!this._available)if(this._manager.session.enabledFeatures||!e.detectedPlanes.size)return;else this._available=true,this.fire("available");let t=e.detectedPlanes;for(let[e,i]of this._planesIndex)t.has(e)||(this._planesIndex.delete(e),this._planes.splice(this._planes.indexOf(i),1),i.destroy(),this.fire("remove",i));for(let i of t){let t=this._planesIndex.get(i);t?t.update(e):(t=new I6(this,i),this._planesIndex.set(i,t),this._planes.push(t),t.update(e),this.fire("add",t));}}get supported(){return this._supported}get available(){return this._available}get planes(){return this._planes}}class I7 extends eo{static{this.EVENT_DESTROY="destroy";}static{this.EVENT_CHANGE="change";}static{this.EVENT_PERSIST="persist";}static{this.EVENT_FORGET="forget";}constructor(e,t,i=null){super(),this._position=new eM,this._rotation=new eH,this._uuid=null,this._uuidRequests=null,this._anchors=e,this._xrAnchor=t,this._uuid=i;}destroy(){if(!this._xrAnchor)return;let e=this._xrAnchor;this._xrAnchor.delete(),this._xrAnchor=null,this.fire("destroy",e,this);}update(e){if(!this._xrAnchor)return;let t=e.getPose(this._xrAnchor.anchorSpace,this._anchors.manager._referenceSpace);if(t){if(this._position.equals(t.transform.position)&&this._rotation.equals(t.transform.orientation))return;this._position.copy(t.transform.position),this._rotation.copy(t.transform.orientation),this.fire("change");}}getPosition(){return this._position}getRotation(){return this._rotation}persist(e){if(!this._anchors.persistence)return void e?.(Error("Persistent Anchors are not supported"),null);if(this._uuid)return void e?.(null,this._uuid);if(this._uuidRequests){e&&this._uuidRequests.push(e);return}this._uuidRequests=[],this._xrAnchor.requestPersistentHandle().then(t=>{for(let i of(this._uuid=t,this._anchors._indexByUuid.set(this._uuid,this),e?.(null,t),this._uuidRequests))i(null,t);this._uuidRequests=null,this.fire("persist",t);}).catch(t=>{for(let i of(e?.(t,null),this._uuidRequests))i(t,null);this._uuidRequests=null;});}forget(e){if(!this._uuid)return void e?.(Error("Anchor is not persistent"));this._anchors.forget(this._uuid,t=>{this._uuid=null,e?.(t),this.fire("forget");});}get uuid(){return this._uuid}get persistent(){return !!this._uuid}}class De extends eo{static{this.EVENT_AVAILABLE="available";}static{this.EVENT_UNAVAILABLE="unavailable";}static{this.EVENT_ERROR="error";}static{this.EVENT_ADD="add";}static{this.EVENT_DESTROY="destroy";}constructor(e){super(),this._supported=ee.browser&&!!window.XRAnchor,this._available=false,this._checkingAvailability=false,this._persistence=ee.browser&&!!window?.XRSession?.prototype.restorePersistentAnchor,this._creationQueue=[],this._index=new Map,this._indexByUuid=new Map,this._list=[],this._callbacksAnchors=new Map,this.manager=e,this._supported&&(this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this));}_onSessionStart(){let e=this.manager.session.enabledFeatures?.indexOf("anchors")>=0;e&&(this._available=e,this.fire("available"));}_onSessionEnd(){if(!this._available)return;this._available=false;for(let e=0;e<this._creationQueue.length;e++)this._creationQueue[e].callback&&this._creationQueue[e].callback(Error("session ended"),null);this._creationQueue.length=0,this._index.clear(),this._indexByUuid.clear();let e=this._list.length;for(;e--;)this._list[e].destroy();this._list.length=0,this.fire("unavailable");}_createAnchor(e,t=null){let i=new I7(this,e,t);return this._index.set(e,i),t&&this._indexByUuid.set(t,i),this._list.push(i),i.once("destroy",this._onAnchorDestroy,this),i}_onAnchorDestroy(e,t){this._index.delete(e),t.uuid&&this._indexByUuid.delete(t.uuid);let i=this._list.indexOf(t);-1!==i&&this._list.splice(i,1),this.fire("destroy",t);}create(e,t,i){if(!this._available)return void i?.(Error("Anchors API is not available"),null);if(window.XRHitTestResult&&e instanceof XRHitTestResult){if(i=t,!this._supported)return void i?.(Error("Anchors API is not supported"),null);if(!e.createAnchor)return void i?.(Error("Creating Anchor from Hit Test is not supported"),null);e.createAnchor().then(e=>{let t=this._createAnchor(e);i?.(null,t),this.fire("add",t);}).catch(e=>{i?.(e,null),this.fire("error",e);});}else this._creationQueue.push({transform:new XRRigidTransform(e,t),callback:i});}restore(e,t){return this._available?this._persistence?this.manager.active?void this.manager.session.restorePersistentAnchor(e).then(i=>{let s=this._createAnchor(i,e);t?.(null,s),this.fire("add",s);}).catch(e=>{t?.(e,null),this.fire("error",e);}):void t?.(Error("WebXR session is not active"),null):void t?.(Error("Anchor Persistence is not supported"),null):void t?.(Error("Anchors API is not available"),null)}forget(e,t){return this._available?this._persistence?this.manager.active?void this.manager.session.deletePersistentAnchor(e).then(()=>{t?.(null);}).catch(e=>{t?.(e),this.fire("error",e);}):void t?.(Error("WebXR session is not active")):void t?.(Error("Anchor Persistence is not supported")):void t?.(Error("Anchors API is not available"))}update(e){if(!this._available){this.manager.session.enabledFeatures||this._checkingAvailability||(this._checkingAvailability=true,e.createAnchor(new XRRigidTransform,this.manager._referenceSpace).then(e=>{e.delete(),this.manager.active&&(this._available=true,this.fire("available"));}).catch(()=>{}));return}if(this._creationQueue.length){for(let t=0;t<this._creationQueue.length;t++){let i=this._creationQueue[t];e.createAnchor(i.transform,this.manager._referenceSpace).then(e=>{i.callback&&this._callbacksAnchors.set(e,i.callback);}).catch(e=>{i.callback&&i.callback(e,null),this.fire("error",e);});}this._creationQueue.length=0;}for(let[t,i]of this._index)e.trackedAnchors.has(t)||(this._index.delete(t),i.destroy());for(let t=0;t<this._list.length;t++)this._list[t].update(e);for(let t of e.trackedAnchors){if(this._index.has(t))continue;try{t.anchorSpace;}catch(e){continue}let i=this._createAnchor(t);i.update(e);let s=this._callbacksAnchors.get(t);s&&(this._callbacksAnchors.delete(t),s(null,i)),this.fire("add",i);}}get supported(){return this._supported}get available(){return this._available}get persistence(){return this._persistence}get uuids(){return this._available&&this._persistence&&this.manager.active?this.manager.session.persistentAnchors:null}get list(){return this._list}}class Dt extends eo{static{this.EVENT_REMOVE="remove";}static{this.EVENT_CHANGE="change";}constructor(e,t){super(),this._lastChanged=0,this._position=new eM,this._rotation=new eH,this._meshDetection=e,this._xrMesh=t,this._lastChanged=this._xrMesh.lastChangedTime;}get xrMesh(){return this._xrMesh}get label(){return this._xrMesh.semanticLabel||""}get vertices(){return this._xrMesh.vertices}get indices(){return this._xrMesh.indices}destroy(){this._xrMesh&&(this._xrMesh=null,this.fire("remove"));}update(e){let t=this._meshDetection._manager,i=e.getPose(this._xrMesh.meshSpace,t._referenceSpace);i&&(this._position.copy(i.transform.position),this._rotation.copy(i.transform.orientation)),this._lastChanged!==this._xrMesh.lastChangedTime&&(this._lastChanged=this._xrMesh.lastChangedTime,this.fire("change"));}getPosition(){return this._position}getRotation(){return this._rotation}}class Di extends eo{static{this.EVENT_AVAILABLE="available";}static{this.EVENT_UNAVAILABLE="unavailable";}static{this.EVENT_ADD="add";}static{this.EVENT_REMOVE="remove";}constructor(e){super(),this._supported=ee.browser&&!!window.XRMesh,this._available=false,this._index=new Map,this._list=[],this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this));}update(e){if(!this._available)if(this._manager.session.enabledFeatures||!e.detectedMeshes.size)return;else this._available=true,this.fire("available");for(let t of e.detectedMeshes){let i=this._index.get(t);i?i.update(e):(i=new Dt(this,t),this._index.set(t,i),this._list.push(i),i.update(e),this.fire("add",i));}for(let t of this._index.values())e.detectedMeshes.has(t.xrMesh)||this._removeMesh(t);}_removeMesh(e){this._index.delete(e.xrMesh),this._list.splice(this._list.indexOf(e),1),e.destroy(),this.fire("remove",e);}_onSessionStart(){if(this._manager.session.enabledFeatures){let e=-1!==this._manager.session.enabledFeatures.indexOf("mesh-detection");e&&(this._available=e,this.fire("available"));}}_onSessionEnd(){if(this._available){for(let e of(this._available=false,this._index.values()))this._removeMesh(e);this.fire("unavailable");}}get supported(){return this._supported}get available(){return this._available}get meshes(){return this._list}}class Ds extends eo{static{this.EVENT_DEPTHRESIZE="depth:resize";}constructor(e,t,i){super(),this._positionData=new Float32Array(3),this._viewport=new eF,this._projMat=new eG,this._projViewOffMat=new eG,this._viewMat=new eG,this._viewOffMat=new eG,this._viewMat3=new eO,this._viewInvMat=new eG,this._viewInvOffMat=new eG,this._xrCamera=null,this._textureColor=null,this._textureDepth=null,this._depthInfo=null,this._emptyDepthBuffer=new Uint8Array(32),this._depthMatrix=new eG,this._manager=e,this._xrView=t;let s=this._manager.app.graphicsDevice;if(this._manager.views.supportedColor&&(this._xrCamera=this._xrView.camera,this._manager.views.availableColor&&this._xrCamera&&(this._textureColor=new ns(s,{format:ic,mipmaps:false,addressU:tr,addressV:tr,minFilter:tZ,magFilter:tZ,width:this._xrCamera.width,height:this._xrCamera.height,name:`XrView-${this._xrView.eye}-Color`}))),this._manager.views.supportedDepth&&this._manager.views.availableDepth){let e=this._manager.views.depthGpuOptimized?tK:tZ;this._textureDepth=new ns(s,{format:this._manager.views.depthPixelFormat,arrayLength:1===i?0:i,mipmaps:false,addressU:tr,addressV:tr,minFilter:e,magFilter:e,width:4,height:4,name:`XrView-${this._xrView.eye}-Depth`});for(let e=0;e<this._textureDepth._levels.length;e++)this._textureDepth._levels[e]=this._emptyDepthBuffer;this._textureDepth.upload();}(this._textureColor||this._textureDepth)&&s.on("devicelost",this._onDeviceLost,this);}get textureColor(){return this._textureColor}get textureDepth(){return this._textureDepth}get depthUvMatrix(){return this._depthMatrix}get depthValueToMeters(){return this._depthInfo?.rawValueToMeters||0}get eye(){return this._xrView.eye}get viewport(){return this._viewport}get projMat(){return this._projMat}get projViewOffMat(){return this._projViewOffMat}get viewOffMat(){return this._viewOffMat}get viewInvOffMat(){return this._viewInvOffMat}get viewMat3(){return this._viewMat3}get positionData(){return this._positionData}update(e,t){this._xrView=t,this._manager.views.availableColor&&(this._xrCamera=this._xrView.camera);let i=e.session.renderState.baseLayer.getViewport(this._xrView);this._viewport.x=i.x,this._viewport.y=i.y,this._viewport.z=i.width,this._viewport.w=i.height,this._projMat.set(this._xrView.projectionMatrix),this._viewMat.set(this._xrView.transform.inverse.matrix),this._viewInvMat.set(this._xrView.transform.matrix),this._updateTextureColor(),this._updateDepth(e);}_updateTextureColor(){if(!this._manager.views.availableColor||!this._xrCamera||!this._textureColor)return;let e=this._manager.webglBinding;if(!e)return;let t=e.getCameraImage(this._xrCamera);if(!t)return;let i=this._manager.app.graphicsDevice,s=i.gl;if(this._frameBufferSource){let e=s.COLOR_ATTACHMENT0,r=this._xrCamera.width,a=this._xrCamera.height;i.setFramebuffer(this._frameBufferSource),s.framebufferTexture2D(s.FRAMEBUFFER,e,s.TEXTURE_2D,t,0),i.setFramebuffer(this._frameBuffer),s.framebufferTexture2D(s.FRAMEBUFFER,e,s.TEXTURE_2D,this._textureColor.impl._glTexture,0),s.bindFramebuffer(s.READ_FRAMEBUFFER,this._frameBufferSource),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,this._frameBuffer),s.blitFramebuffer(0,a,r,0,0,0,r,a,s.COLOR_BUFFER_BIT,s.NEAREST);}else this._frameBufferSource=s.createFramebuffer(),this._frameBuffer=s.createFramebuffer();}_updateDepth(e){if(!this._manager.views.availableDepth||!this._textureDepth)return;let t=this._manager.views.depthGpuOptimized,i=t?this._manager.webglBinding:e;if(!i){this._depthInfo=null;return}let s=i.getDepthInformation(this._xrView);if(!s){this._depthInfo=null;return}let r=!this._depthInfo!=!s;this._depthInfo=s;let a=this._depthInfo?.width||4,n=this._depthInfo?.height||4,o=false;if((this._textureDepth.width!==a||this._textureDepth.height!==n)&&(this._textureDepth._width=a,this._textureDepth._height=n,r=true,o=true),r&&(this._depthInfo?this._depthMatrix.data.set(this._depthInfo.normDepthBufferFromNormView.matrix):this._depthMatrix.setIdentity()),this._depthInfo)if(t){if(this._depthInfo.texture){let e=this._manager.app.graphicsDevice.gl;switch(this._textureDepth.impl._glTexture=this._depthInfo.texture,"texture-array"===this._depthInfo.textureType?this._textureDepth.impl._glTarget=e.TEXTURE_2D_ARRAY:this._textureDepth.impl._glTarget=e.TEXTURE_2D,this._manager.views.depthPixelFormat){case iy:this._textureDepth.impl._glInternalFormat=e.R32F,this._textureDepth.impl._glPixelType=e.FLOAT,this._textureDepth.impl._glFormat=e.RED;break;case ix:this._textureDepth.impl._glInternalFormat=e.DEPTH_COMPONENT16,this._textureDepth.impl._glPixelType=e.UNSIGNED_SHORT,this._textureDepth.impl._glFormat=e.DEPTH_COMPONENT;}this._textureDepth.impl._glCreated=true;}}else this._textureDepth._levels[0]=new Uint8Array(this._depthInfo.data),this._textureDepth.upload();else this._textureDepth._levels[0]=this._emptyDepthBuffer,this._textureDepth.upload();o&&this.fire("depth:resize",a,n);}updateTransforms(e){e?(this._viewInvOffMat.mul2(e,this._viewInvMat),this.viewOffMat.copy(this._viewInvOffMat).invert()):(this._viewInvOffMat.copy(this._viewInvMat),this.viewOffMat.copy(this._viewMat)),this._viewMat3.setFromMat4(this._viewOffMat),this._projViewOffMat.mul2(this._projMat,this._viewOffMat),this._positionData[0]=this._viewInvOffMat.data[12],this._positionData[1]=this._viewInvOffMat.data[13],this._positionData[2]=this._viewInvOffMat.data[14];}_onDeviceLost(){this._frameBufferSource=null,this._frameBuffer=null,this._depthInfo=null;}getDepth(e,t){return this._manager.views.depthGpuOptimized?null:this._depthInfo?.getDepthInMeters(e,t)??null}destroy(){if(this._depthInfo=null,this._textureColor&&(this._textureColor.destroy(),this._textureColor=null),this._textureDepth&&(this._textureDepth.destroy(),this._textureDepth=null),this._frameBufferSource){let e=this._manager.app.graphicsDevice.gl;e.deleteFramebuffer(this._frameBufferSource),this._frameBufferSource=null,e.deleteFramebuffer(this._frameBuffer),this._frameBuffer=null;}}}class Dr extends eo{static{this.EVENT_ADD="add";}static{this.EVENT_REMOVE="remove";}constructor(e){super(),this._index=new Map,this._indexTmp=new Map,this._list=[],this._supportedColor=ee.browser&&!!window.XRCamera&&!!window.XRWebGLBinding,this._supportedDepth=ee.browser&&!!window.XRDepthInformation,this._availableColor=false,this._availableDepth=false,this._depthUsage="",this._depthFormat="",this._depthFormats={[ID]:ia,[IR]:ix,[IM]:iy},this._manager=e,this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this);}get list(){return this._list}get supportedColor(){return this._supportedColor}get supportedDepth(){return this._supportedDepth}get availableColor(){return this._availableColor}get availableDepth(){return this._availableDepth}get depthUsage(){return this._depthUsage}get depthGpuOptimized(){return this._depthUsage===II}get depthFormat(){return this._depthFormat}get depthPixelFormat(){return this._depthFormats[this._depthFormat]??null}update(e,t){for(let e=0;e<t.length;e++)this._indexTmp.set(t[e].eye,t[e]);for(let[i,s]of this._indexTmp){let r=this._index.get(i);r?r.update(e,s):(r=new Ds(this._manager,s,t.length),this._index.set(i,r),this._list.push(r),r.update(e,s),this.fire("add",r));}for(let[e,t]of this._index){if(this._indexTmp.has(e))continue;t.destroy(),this._index.delete(e);let i=this._list.indexOf(t);-1!==i&&this._list.splice(i,1),this.fire("remove",t);}this._indexTmp.clear();}get(e){return this._index.get(e)||null}_onSessionStart(){if(this._manager.type===Id&&this._manager.session.enabledFeatures&&(this._availableColor=-1!==this._manager.session.enabledFeatures.indexOf("camera-access"),this._availableDepth=-1!==this._manager.session.enabledFeatures.indexOf("depth-sensing"),this._availableDepth)){let e=this._manager.session;this._depthUsage=e.depthUsage,this._depthFormat=e.depthDataFormat;}}_onSessionEnd(){for(let e of this._index.values())e.destroy();this._index.clear(),this._availableColor=false,this._availableDepth=false,this._depthUsage="",this._depthFormat="",this._list.length=0;}}class Da extends eo{static{this.EVENT_AVAILABLE="available";}static{this.EVENT_START="start";}static{this.EVENT_END="end";}static{this.EVENT_UPDATE="update";}static{this.EVENT_ERROR="error";}constructor(e){super(),this._supported=ee.browser&&!!navigator.xr,this._available={},this._type=null,this._spaceType=null,this._session=null,this._baseLayer=null,this.webglBinding=null,this._referenceSpace=null,this._camera=null,this._localPosition=new eM,this._localRotation=new eH,this._depthNear=.1,this._depthFar=1e3,this._supportedFrameRates=null,this._width=0,this._height=0,this._framebufferScaleFactor=1,this.app=e,this._available[Ih]=false,this._available[Ic]=false,this._available[Id]=false,this.views=new Dr(this),this.domOverlay=new IO(this),this.hitTest=new IU(this),this.imageTracking=new IV(this),this.planeDetection=new I9(this),this.meshDetection=new Di(this),this.input=new I0(this),this.lightEstimation=new I5(this),this.anchors=new De(this),this.views=new Dr(this),this._supported&&(navigator.xr.addEventListener("devicechange",()=>{this._deviceAvailabilityCheck();}),this._deviceAvailabilityCheck(),this.app.graphicsDevice.on("devicelost",this._onDeviceLost,this),this.app.graphicsDevice.on("devicerestored",this._onDeviceRestored,this));}destroy(){}start(e,t,i,s){let r=s;if("object"==typeof s&&(r=s.callback),!this._available[t]){r&&r(Error("XR is not available"));return}if(this._session){r&&r(Error("XR session is already started"));return}this._camera=e,this._camera.camera.xr=this,this._type=t,this._spaceType=i,this._framebufferScaleFactor=s?.framebufferScaleFactor??1,this._setClipPlanes(e.nearClip,e.farClip);let a={requiredFeatures:[i],optionalFeatures:[]},n=this.app.graphicsDevice;n?.isWebGPU&&a.requiredFeatures.push("webgpu");let o=n?.isWebGL2;if(t===Id){if(a.optionalFeatures.push("light-estimation"),a.optionalFeatures.push("hit-test"),s&&(s.imageTracking&&this.imageTracking.supported&&a.optionalFeatures.push("image-tracking"),s.planeDetection&&a.optionalFeatures.push("plane-detection"),s.meshDetection&&a.optionalFeatures.push("mesh-detection")),this.domOverlay.supported&&this.domOverlay.root&&(a.optionalFeatures.push("dom-overlay"),a.domOverlay={root:this.domOverlay.root}),s&&s.anchors&&this.anchors.supported&&a.optionalFeatures.push("anchors"),s&&s.depthSensing&&this.views.supportedDepth){a.optionalFeatures.push("depth-sensing");let e=[],t=[];if(e.push(II,IL),t.push(IM,ID,IR),s.depthSensing.usagePreference){let t=e.indexOf(s.depthSensing.usagePreference);-1!==t&&e.splice(t,1),e.unshift(s.depthSensing.usagePreference);}if(s.depthSensing.dataFormatPreference){let e=t.indexOf(s.depthSensing.dataFormatPreference);-1!==e&&t.splice(e,1),t.unshift(s.depthSensing.dataFormatPreference);}a.depthSensing={usagePreference:e,dataFormatPreference:t};}o&&s&&s.cameraColor&&this.views.supportedColor&&a.optionalFeatures.push("camera-access");}a.optionalFeatures.push("hand-tracking"),s&&s.optionalFeatures&&(a.optionalFeatures=a.optionalFeatures.concat(s.optionalFeatures)),this.imageTracking.supported&&this.imageTracking.images.length?this.imageTracking.prepareImages((e,s)=>{if(e){r&&r(e),this.fire("error",e);return}null!==s&&(a.trackedImages=s),this._onStartOptionsReady(t,i,a,r);}):this._onStartOptionsReady(t,i,a,r);}_onStartOptionsReady(e,t,i,s){navigator.xr.requestSession(e,i).then(e=>{this._onSessionStart(e,t,s);}).catch(e=>{this._camera.camera.xr=null,this._camera=null,this._type=null,this._spaceType=null,s&&s(e),this.fire("error",e);});}end(e){if(!this._session){e&&e(Error("XR Session is not initialized"));return}this.webglBinding=null,e&&this.once("end",e),this._session.end();}isAvailable(e){return this._available[e]}_deviceAvailabilityCheck(){for(let e in this._available)this._sessionSupportCheck(e);}initiateRoomCapture(e){return this._session?this._session.initiateRoomCapture?void this._session.initiateRoomCapture().then(()=>{e&&e(null);}).catch(t=>{e&&e(t);}):void e(Error("Session does not support manual room capture")):void e(Error("Session is not active"))}updateTargetFrameRate(e,t){if(!this._session?.updateTargetFrameRate)return void t?.(Error("unable to update frameRate"));this._session.updateTargetFrameRate(e).then(()=>{t?.();}).catch(e=>{t?.(e);});}_sessionSupportCheck(e){navigator.xr.isSessionSupported(e).then(t=>{this._available[e]!==t&&(this._available[e]=t,this.fire("available",e,t),this.fire(`available:${e}`,t));}).catch(e=>{this.fire("error",e);});}_onSessionStart(e,t,i){let s=false;this._session=e;let r=()=>{this.fire("visibility:change",e.visibilityState);},a=()=>{this._setClipPlanes(this._camera.nearClip,this._camera.farClip);},n=()=>{this._camera&&(this._camera.off("set_nearClip",a),this._camera.off("set_farClip",a),this._camera.camera.xr=null,this._camera=null),e.removeEventListener("end",n),e.removeEventListener("visibilitychange",r),s||this.fire("end"),this._session=null,this._referenceSpace=null,this._width=0,this._height=0,this._type=null,this._spaceType=null,this.app.systems&&this.app.tick();};e.addEventListener("end",n),e.addEventListener("visibilitychange",r),this._camera.on("set_nearClip",a),this._camera.on("set_farClip",a),this._createBaseLayer(),this.session.supportedFrameRates?this._supportedFrameRates=Array.from(this.session.supportedFrameRates):this._supportedFrameRates=null,this._session.addEventListener("frameratechange",()=>{this.fire("frameratechange",this._session?.frameRate);}),e.requestReferenceSpace(t).then(e=>{this._referenceSpace=e,this.app.tick(),i&&i(null),this.fire("start");}).catch(t=>{s=true,e.end(),i&&i(t),this.fire("error",t);});}_setClipPlanes(e,t){(this._depthNear!==e||this._depthFar!==t)&&(this._depthNear=e,this._depthFar=t,this._session&&this._session.updateRenderState({depthNear:this._depthNear,depthFar:this._depthFar}));}_createBaseLayer(){let e=this.app.graphicsDevice,t=e.maxPixelRatio/window.devicePixelRatio*this._framebufferScaleFactor;if(this._baseLayer=new XRWebGLLayer(this._session,e.gl,{alpha:true,depth:true,stencil:true,framebufferScaleFactor:t,antialias:false}),e?.isWebGL2&&window.XRWebGLBinding)try{this.webglBinding=new XRWebGLBinding(this._session,e.gl);}catch(e){this.fire("error",e);}this._session.updateRenderState({baseLayer:this._baseLayer,depthNear:this._depthNear,depthFar:this._depthFar});}_onDeviceLost(){this._session&&(this.webglBinding&&(this.webglBinding=null),this._baseLayer=null,this._session.updateRenderState({baseLayer:this._baseLayer,depthNear:this._depthNear,depthFar:this._depthFar}));}_onDeviceRestored(){this._session&&setTimeout(()=>{this.app.graphicsDevice.gl.makeXRCompatible().then(()=>{this._createBaseLayer();}).catch(e=>{this.fire("error",e);});},0);}update(e){if(!this._session)return false;let t=e.session.renderState.baseLayer.framebufferWidth,i=e.session.renderState.baseLayer.framebufferHeight;(this._width!==t||this._height!==i)&&(this._width=t,this._height=i,this.app.graphicsDevice.setResolution(t,i));let s=e.getViewerPose(this._referenceSpace);if(!s)return false;let r=this.views.list.length;this.views.update(e,s.views);let a=s.transform.position,n=s.transform.orientation;if(this._localPosition.set(a.x,a.y,a.z),this._localRotation.set(n.x,n.y,n.z,n.w),0===r&&this.views.list.length>0){let e=new eG,t=this.views.list[0];e.copy(t.projMat);let i=e.data,s=2*Math.atan(1/i[5])*180/Math.PI,r=i[5]/i[0],a=i[14]/(i[10]+1),n=i[14]/(i[10]-1);this._camera.camera.setXrProperties({aspectRatio:r,farClip:a,fov:s,horizontalFov:false,nearClip:n});}return this._camera.camera._node.setLocalPosition(this._localPosition),this._camera.camera._node.setLocalRotation(this._localRotation),this.input.update(e),this._type===Id&&(this.hitTest.supported&&this.hitTest.update(e),this.lightEstimation.supported&&this.lightEstimation.update(e),this.imageTracking.supported&&this.imageTracking.update(e),this.anchors.supported&&this.anchors.update(e),this.planeDetection.supported&&this.planeDetection.update(e),this.meshDetection.supported&&this.meshDetection.update(e)),this.fire("update",e),true}get supported(){return this._supported}get active(){return !!this._session}get type(){return this._type}get spaceType(){return this._spaceType}get session(){return this._session}get frameRate(){return this._session?.frameRate??null}get supportedFrameRates(){return this._supportedFrameRates}get framebufferScaleFactor(){return this._framebufferScaleFactor}set fixedFoveation(e){(this._baseLayer?.fixedFoveation??null)!==null&&(this.app.graphicsDevice.samples,this._baseLayer.fixedFoveation=e);}get fixedFoveation(){return this._baseLayer?.fixedFoveation??null}get camera(){return this._camera?this._camera.entity:null}get visibilityState(){return this._session?this._session.visibilityState:null}}class Dn extends x9{constructor(e,t={}){super(e);let i=new Te;i.graphicsDevice=t.graphicsDevice??this.createDevice(e,t),this.addComponentSystems(i),this.addResourceHandles(i),i.elementInput=t.elementInput,i.keyboard=t.keyboard,i.mouse=t.mouse,i.touch=t.touch,i.gamepads=t.gamepads,i.scriptPrefix=t.scriptPrefix,i.assetPrefix=t.assetPrefix,i.scriptsOrder=t.scriptsOrder,i.soundManager=new d9,i.lightmapper=Tf,i.batchManager=mY,i.xr=Da,this.init(i);}createDevice(e,t){return t.graphicsDeviceOptions||(t.graphicsDeviceOptions={}),ee.browser&&navigator.xr&&(t.graphicsDeviceOptions.xrCompatible=true),t.graphicsDeviceOptions.alpha=t.graphicsDeviceOptions.alpha||false,new lG(e,t.graphicsDeviceOptions)}addComponentSystems(e){e.componentSystems=[wt,Ab,bn,T4,Em,bN,bJ,w4,w9,Cm,wB,ES,bX,wl,A6,EF,wC,wD,w$,bP,bc,wQ,Cy];}addResourceHandles(e){e.resourceHandlers=[Cb,PU,Pk,PV,Lw,Lx,Il,LG,Lg,PH,LN,LC,PK,L_,Pj,LF,Lm,PZ,P0,PW,LY,Lk,Lz,P$,Lc];}}class Do extends eo{constructor(e,t){super(),this._assets=new Set,this._loadingAssets=new Set,this._waitingAssets=new Set,this._loading=false,this._loaded=false,this._failed=[],this._registry=t,e.forEach(e=>{if(e instanceof xF)e.registry||(e.registry=t),this._assets.add(e);else {let i=t.get(e);i?this._assets.add(i):this._waitForAsset(e);}});}destroy(){this._registry.off("load",this._onLoad),this._registry.off("error",this._onError),this._waitingAssets.forEach(e=>{this._registry.off(`add:${e}`,this._onAddAsset);}),this.off("progress"),this.off("load");}_assetHasDependencies(e){return "model"===e.type&&e.file?.url&&e.file.url&&e.file.url.match(/.json$/g)}load(e,t){if(this._loading)return;this._loading=true,this._callback=e,this._scope=t,this._registry.on("load",this._onLoad,this),this._registry.on("error",this._onError,this);let i=false;this._assets.forEach(e=>{e.loaded||(i=true,this._assetHasDependencies(e)&&this._registry.loadFromUrl(e.file.url,e.type,(t,i)=>{if(t)return void this._onError(t,e);this._onLoad(e);}),this._loadingAssets.add(e),this._registry.add(e));}),this._loadingAssets.forEach(e=>{this._assetHasDependencies(e)||this._registry.load(e);}),i||0!==this._waitingAssets.size||this._loadingComplete();}ready(e,t=this){this._loaded?e.call(t,Array.from(this._assets)):this.once("load",i=>{e.call(t,i);});}_loadingComplete(){this._loaded||(this._loaded=true,this._registry.off("load",this._onLoad,this),this._registry.off("error",this._onError,this),this._failed.length?(this._callback&&this._callback.call(this._scope,"Failed to load some assets",this._failed),this.fire("error",this._failed)):(this._callback&&this._callback.call(this._scope),this.fire("load",Array.from(this._assets))));}_onLoad(e){this._loadingAssets.has(e)&&(this.fire("progress",e),this._loadingAssets.delete(e)),0===this._loadingAssets.size&&setTimeout(()=>{this._loadingComplete();},0);}_onError(e,t){this._loadingAssets.has(t)&&(this._failed.push(t),this._loadingAssets.delete(t)),0===this._loadingAssets.size&&setTimeout(()=>{this._loadingComplete();},0);}_onAddAsset(e){this._waitingAssets.delete(e),this._assets.add(e),e.loaded||(this._loadingAssets.add(e),this._registry.load(e));}_waitForAsset(e){this._waitingAssets.add(e),this._registry.once(`add:${e}`,this._onAddAsset,this);}}class Dl{constructor(e,t,i,s){this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=i,this.texture=new ns(e,{name:s,format:ib,width:t,height:i,mipmaps:true,minFilter:t1,magFilter:tZ,addressU:tr,addressV:tr,levels:[this.canvas]}),this.ctx=this.canvas.getContext("2d",{alpha:true});}destroy(){this.texture.destroy();}clear(e){let{width:t,height:i}=this.canvas;this.ctx.clearRect(0,0,t,i),this.ctx.fillStyle=e,this.ctx.fillRect(0,0,t,i);}}class Dh extends eo{constructor(e,t={}){super(),this.type="bitmap",this.app=e,this.intensity=0,this.fontWeight=t.fontWeight||"normal",this.fontSize=parseInt(t.fontSize,10),this.glyphSize=this.fontSize,this.fontName=t.fontName||"Arial",this.color=t.color||new eb(1,1,1),this.padding=t.padding||0,this.width=Math.min(4096,t.width||512),this.height=Math.min(4096,t.height||512),this.atlases=[],this.chars="",this.data={};}createTextures(e){let t=this._normalizeCharsSet(e);if(t.length!==this.chars.length)return void this._renderAtlas(t);for(let e=0;e<t.length;e++)if(t[e]!==this.chars[e])return void this._renderAtlas(t)}updateTextures(e){let t=this._normalizeCharsSet(e),i=[];for(let e=0;e<t.length;e++){let s=t[e];this.data.chars[s]||i.push(s);}i.length>0&&this._renderAtlas(this.chars.concat(i));}destroy(){this.atlases.forEach(e=>e.destroy()),this.chars=null,this.color=null,this.data=null,this.fontName=null,this.fontSize=null,this.glyphSize=null,this.intensity=null,this.atlases=null,this.type=null,this.fontWeight=null;}_colorToRgbString(e,t){let s=Math.round(255*e.r),r=Math.round(255*e.g),a=Math.round(255*e.b);return t?`rgba(${s}, ${r}, ${a}, ${e.a})`:`rgb(${s}, ${r}, ${a})`}renderCharacter(e,t,i,s,r){e.fillStyle=r,e.fillText(t,i,s);}_getAtlas(e){return e>=this.atlases.length&&(this.atlases[e]=new Dl(this.app.graphicsDevice,this.width,this.height,`font-atlas-${this.fontName}-${e}`)),this.atlases[e]}_renderAtlas(e){this.chars=e;let t=this.width,i=this.height,s=this._colorToRgbString(this.color,false),r=this.color.a;this.color.a=1/255;let a=this._colorToRgbString(this.color,true);this.color.a=r;let n=0,o=this._getAtlas(n++);o.clear(a),this.data=this._createJson(this.chars,this.fontName,t,i);let l=ea.getSymbols(this.chars.join("")),h=0,c=0,d={};for(let e=0;e<l.length;e++){let t=l[e];d[t]=this._getTextMetrics(t),h=Math.max(h,d[t].height),c=Math.max(c,d[t].descent);}this.glyphSize=Math.max(this.glyphSize,h);let u=this.glyphSize+2*this.padding,f=this.glyphSize+2*this.padding,p=this.glyphSize/2+this.padding,m=f-c-this.padding,_=0,g=0;for(let e=0;e<l.length;e++){let r=l[e],h=ea.getCodePoint(l[e]),v=this.fontSize;o.ctx.font=`${this.fontWeight} ${v.toString()}px ${this.fontName}`,o.ctx.textAlign="center",o.ctx.textBaseline="alphabetic";let S=o.ctx.measureText(r).width;S>v&&(v=this.fontSize*this.fontSize/S,o.ctx.font=`${this.fontWeight} ${v.toString()}px ${this.fontName}`,S=this.fontSize),this.renderCharacter(o.ctx,r,_+p,g+m,s);let y=this.padding+(this.glyphSize-S)/2,x=-this.padding+d[r].descent-c,T=S;this._addChar(this.data,r,h,_,g,u,f,y,x,T,n-1,t,i),(_+=u)+u>t&&(_=0,(g+=f)+f>i&&((o=this._getAtlas(n++)).clear(a),g=0));}this.atlases.splice(n).forEach(e=>e.destroy()),this.atlases.forEach(e=>e.texture.upload()),this.fire("render");}_createJson(e,t,i,s){return {version:3,intensity:this.intensity,info:{face:t,width:i,height:s,maps:[{width:i,height:s}]},chars:{}}}_addChar(e,t,i,s,r,a,n,o,l,h,c,d,u){e.info.maps.length<c+1&&e.info.maps.push({width:d,height:u});let f=this.fontSize/32;e.chars[t]={id:i,letter:t,x:s,y:r,width:a,height:n,xadvance:h/f,xoffset:o/f,yoffset:(l+this.padding)/f,scale:f,range:1,map:c,bounds:[0,0,a/f,n/f]};}_normalizeCharsSet(e){let t=this.app.systems.element.getUnicodeConverter();t&&(e=t(e));let i={},s=ea.getSymbols(e);for(let e=0;e<s.length;e++){let t=s[e];i[t]||(i[t]=t);}return Object.keys(i).sort()}_getTextMetrics(e){let t=document.createElement("span");t.id="content-span",t.innerHTML=e;let i=document.createElement("div");i.id="content-block",i.style.display="inline-block",i.style.width="1px",i.style.height="0px";let s=document.createElement("div");s.appendChild(t),s.appendChild(i),s.style.font=`${this.fontSize}px ${this.fontName}`,document.body.appendChild(s);let r=-1,a=-1,n=-1;try{i.style["vertical-align"]="baseline",r=i.offsetTop-t.offsetTop,i.style["vertical-align"]="bottom",a=(n=i.offsetTop-t.offsetTop)-r;}finally{document.body.removeChild(s);}return {ascent:r,descent:a,height:n}}get textures(){return this.atlases.map(e=>e.texture)}}let Dc=[],Dd=[[],[],[]];class Du extends l2{constructor(e,t){super(e),this.viewBindGroups=[],this.renderer=t;}destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;}update(e,t,i,s){this.camera=e,this.scene=t,this.layers=i,this.mapping=s;}execute(){let e=this.device,{renderer:t,camera:i,scene:s,layers:r,mapping:a,renderTarget:n}=this,o=s.layers.layerList,l=s.layers.subLayerEnabled,h=s.layers.subLayerList;for(let c=0;c<o.length;c++){let d=o[c];if(!(r&&0>r.indexOf(d))&&d.enabled&&l[c]&&d.camerasSet.has(i.camera)){let r=h[c];d._clearDepthBuffer&&t.clear(i.camera,false,true,false);let o=d.meshInstances;for(let e=0;e<o.length;e++){let t=o[e];t.pick&&t.transparent===r&&(Dc.push(t),a.set(t.id,t));}Dc.length>0&&(s.clusteredLightingEnabled&&t.worldClustersAllocator.empty.activate(),t.setCameraUniforms(i.camera,n),e.supportsUniformBuffers&&t.setupViewUniformBuffers(this.viewBindGroups,t.viewUniformFormat,t.viewBindGroupFormat,null),t.renderForward(i.camera,n,Dc,Dd,pf,t=>{e.setBlendState(nu.NOBLEND);}),Dc.length=0);}}}}let Df=new Set,Dp=new eF;class Dm{constructor(e,t,i){this.renderTarget=null,this.mapping=new Map,this.deviceValid=true,this.renderer=e.renderer,this.device=e.graphicsDevice,this.renderPass=new Du(this.device,e.renderer),this.width=0,this.height=0,this.resize(t,i),this.device.on("destroy",()=>{this.deviceValid=false;});}getSelection(e,t,i=1,s=1){let r=this.device;if(r.isWebGPU)return [];t=this.renderTarget.height-(t+s);let a=this.sanitizeRect(e,t,i,s);r.setRenderTarget(this.renderTarget),r.updateBegin();let n=new Uint8Array(4*a.z*a.w);return r.readPixels(a.x,a.y,a.z,a.w,n),r.updateEnd(),this.decodePixels(n,this.mapping)}getSelectionAsync(e,t,i=1,s=1){this.device?.isWebGL2&&(t=this.renderTarget.height-(t+s));let r=this.sanitizeRect(e,t,i,s);return this.renderTarget.colorBuffer.read(r.x,r.y,r.z,r.w,{renderTarget:this.renderTarget,immediate:true}).then(e=>this.decodePixels(e,this.mapping))}sanitizeRect(e,t,i,s){let r=this.renderTarget.width,a=this.renderTarget.height;return e=eA.clamp(Math.floor(e),0,r-1),t=eA.clamp(Math.floor(t),0,a-1),i=Math.min(i=Math.floor(Math.max(i,1)),r-e),s=Math.min(s=Math.floor(Math.max(s,1)),a-t),Dp.set(e,t,i,s)}decodePixels(e,t){let i=[];if(this.deviceValid){let s=e.length;for(let i=0;i<s;i+=4){let s=e[i+0],r=e[i+1],a=e[i+2],n=(e[i+3]<<24|s<<16|r<<8|a)>>>0;0xffffffff!==n&&Df.add(t.get(n));}Df.forEach(e=>{e&&i.push(e);}),Df.clear();}return i}allocateRenderTarget(){let e=new ns(this.device,{format:id,width:this.width,height:this.height,mipmaps:false,minFilter:tK,magFilter:tK,addressU:tr,addressV:tr,name:"pick"});this.renderTarget=new nM({colorBuffer:e,depth:true});}releaseRenderTarget(){this.renderTarget&&(this.renderTarget.destroyTextureBuffers(),this.renderTarget.destroy(),this.renderTarget=null);}prepare(e,t,i){i instanceof gH&&(i=[i]),this.renderTarget&&this.width===this.renderTarget.width&&this.height===this.renderTarget.height||(this.releaseRenderTarget(),this.allocateRenderTarget()),this.mapping.clear();let s=this.renderPass;s.init(this.renderTarget),s.colorOps.clearValue=eb.WHITE,s.colorOps.clear=true,s.depthStencilOps.clearDepth=true,s.update(e,t,i,this.mapping),s.render();}resize(e,t){this.width=Math.floor(e),this.height=Math.floor(t);}}class D_ extends xH{constructor(e){super(e,"scenesettings");}load(e,t){Lp.load(e,this.maxRetries,t);}open(e,t){return t.settings}}let Dg=new eM,Dv=new eM,DS=new e1,Dy=new e1,Dx=new e1;DS.end=new eM,Dy.end=new eM,Dx.end=new eM;let DT=new eM,DE=new eM,DA=new eM,Db=new eM,Dw=new eM,DC=new eM,DP=new eM,DL=new eM,DI=new eM,DD=new eM,DR=new eM,DM=new eM,DO=new eM,DN=new eM,DF=new eM,DB=new eM,DU=new eM,Dk=new eM,DV=new eM,Dz=new eM,DG=new eF;function DH(e,t,i){return DR.cross(e,t).dot(i)}class DW{constructor(e,t,i){this.event=e,this.element=t,this.camera=i,this._stopPropagation=false;}stopPropagation(){this._stopPropagation=true,this.event&&(this.event.stopImmediatePropagation(),this.event.stopPropagation());}}class DX extends DW{constructor(e,t,i,s,r,a,n){super(e,t,i),this.x=s,this.y=r,this.ctrlKey=e.ctrlKey||false,this.altKey=e.altKey||false,this.shiftKey=e.shiftKey||false,this.metaKey=e.metaKey||false,this.button=e.button,dN.isPointerLocked()?(this.dx=e.movementX||e.webkitMovementX||e.mozMovementX||0,this.dy=e.movementY||e.webkitMovementY||e.mozMovementY||0):(this.dx=s-a,this.dy=r-n),this.wheelDelta=0,"wheel"===e.type&&(e.deltaY>0?this.wheelDelta=1:e.deltaY<0&&(this.wheelDelta=-1));}}class DY extends DW{constructor(e,t,i,s,r,a){super(e,t,i),this.touches=e.touches,this.changedTouches=e.changedTouches,this.x=s,this.y=r,this.touch=a;}}class Dq extends DW{constructor(e,t,i,s){super(e,t,i),this.inputSource=s;}}class D${constructor(e,t){this._app=null,this._attached=false,this._target=null,this._enabled=true,this._lastX=0,this._lastY=0,this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._touchstartHandler=this._handleTouchStart.bind(this),this._touchendHandler=this._handleTouchEnd.bind(this),this._touchcancelHandler=this._touchendHandler,this._touchmoveHandler=this._handleTouchMove.bind(this),this._sortHandler=this._sortElements.bind(this),this._elements=[],this._hoveredElement=null,this._pressedElement=null,this._touchedElements={},this._touchesForWhichTouchLeaveHasFired={},this._selectedElements={},this._selectedPressedElements={},this._useMouse=!t||false!==t.useMouse,this._useTouch=!t||false!==t.useTouch,this._useXr=!t||false!==t.useXr,this._selectEventsAttached=false,ee.touch&&(this._clickedEntities={}),this.attach(e);}set enabled(e){this._enabled=e;}get enabled(){return this._enabled}set app(e){this._app=e;}get app(){return this._app||s}attach(e){this._attached&&(this._attached=false,this.detach()),this._target=e,this._attached=true;let t=!!ee.passiveEvents&&{passive:true};this._useMouse&&(window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t)),this._useTouch&&ee.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,t),this._target.addEventListener("touchend",this._touchendHandler,false),this._target.addEventListener("touchmove",this._touchmoveHandler,false),this._target.addEventListener("touchcancel",this._touchcancelHandler,false)),this.attachSelectEvents();}attachSelectEvents(){!this._selectEventsAttached&&this._useXr&&this.app&&this.app.xr&&this.app.xr.supported&&(this._clickedEntities||(this._clickedEntities={}),this._selectEventsAttached=true,this.app.xr.on("start",this._onXrStart,this));}detach(){if(!this._attached)return;this._attached=false;let e=!!ee.passiveEvents&&{passive:true};this._useMouse&&(window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e)),this._useTouch&&(this._target.removeEventListener("touchstart",this._touchstartHandler,e),this._target.removeEventListener("touchend",this._touchendHandler,false),this._target.removeEventListener("touchmove",this._touchmoveHandler,false),this._target.removeEventListener("touchcancel",this._touchcancelHandler,false)),this._selectEventsAttached&&(this._selectEventsAttached=false,this.app.xr.off("start",this._onXrStart,this),this.app.xr.off("end",this._onXrEnd,this),this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)),this._target=null;}addElement(e){ -1===this._elements.indexOf(e)&&this._elements.push(e);}removeElement(e){let t=this._elements.indexOf(e);-1!==t&&this._elements.splice(t,1);}_handleUp(e){this._enabled&&(dN.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mouseup",e)));}_handleDown(e){this._enabled&&(dN.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mousedown",e)));}_handleMove(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousemove",e),this._lastX=_,this._lastY=g);}_handleWheel(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousewheel",e));}_determineTouchedElements(e){let t={},i=this.app.systems.camera.cameras;for(let s=i.length-1;s>=0;s--){let r=i[s],a=0,n=e.changedTouches.length;for(let i=0;i<n;i++){if(t[e.changedTouches[i].identifier]){a++;continue}let s=dK(e.changedTouches[i]),n=this._getTargetElementByCoords(r,s.x,s.y);n&&(a++,t[e.changedTouches[i].identifier]={element:n,camera:r,x:s.x,y:s.y});}if(a===n)break}return t}_handleTouchStart(e){if(!this._enabled)return;let t=this._determineTouchedElements(e);for(let i=0,s=e.changedTouches.length;i<s;i++){let s=e.changedTouches[i],r=t[s.identifier],a=this._touchedElements[s.identifier];r&&(!a||r.element!==a.element)&&(this._fireEvent(e.type,new DY(e,r.element,r.camera,r.x,r.y,s)),this._touchesForWhichTouchLeaveHasFired[s.identifier]=false);}for(let e in t)this._touchedElements[e]=t[e];}_handleTouchEnd(e){if(!this._enabled)return;let t=this.app.systems.camera.cameras;for(let e in this._clickedEntities)delete this._clickedEntities[e];for(let i=0,s=e.changedTouches.length;i<s;i++){let s=e.changedTouches[i],r=this._touchedElements[s.identifier];if(!r)continue;let a=r.element,n=r.camera,o=r.x,l=r.y;delete this._touchedElements[s.identifier],delete this._touchesForWhichTouchLeaveHasFired[s.identifier];let h=dK(s);for(let i=t.length-1;i>=0;i--)this._getTargetElementByCoords(t[i],h.x,h.y)!==a||this._clickedEntities[a.entity.getGuid()]||(this._fireEvent("click",new DY(e,a,n,o,l,s)),this._clickedEntities[a.entity.getGuid()]=Date.now());this._fireEvent(e.type,new DY(e,a,n,o,l,s));}}_handleTouchMove(e){if(e.preventDefault(),!this._enabled)return;let t=this._determineTouchedElements(e);for(let i=0,s=e.changedTouches.length;i<s;i++){let s=e.changedTouches[i],r=t[s.identifier],a=this._touchedElements[s.identifier];if(a){let t=dK(s);r&&r.element===a.element||this._touchesForWhichTouchLeaveHasFired[s.identifier]||(this._fireEvent("touchleave",new DY(e,a.element,a.camera,t.x,t.y,s)),this._touchesForWhichTouchLeaveHasFired[s.identifier]=true),this._fireEvent("touchmove",new DY(e,a.element,a.camera,t.x,t.y,s));}}}_onElementMouseEvent(e,t){let i,s=null,r=this._hoveredElement;this._hoveredElement=null;let a=this.app.systems.camera.cameras;for(let e=a.length-1;e>=0&&(i=a[e],!(s=this._getTargetElementByCoords(i,_,g)));e--);if(this._hoveredElement=s,("mousemove"===e||"mouseup"===e)&&this._pressedElement?this._fireEvent(e,new DX(t,this._pressedElement,i,_,g,this._lastX,this._lastY)):s&&(this._fireEvent(e,new DX(t,s,i,_,g,this._lastX,this._lastY)),"mousedown"===e&&(this._pressedElement=s)),r!==this._hoveredElement&&(r&&this._fireEvent("mouseleave",new DX(t,r,i,_,g,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new DX(t,this._hoveredElement,i,_,g,this._lastX,this._lastY))),"mouseup"===e&&this._pressedElement){if(this._pressedElement===this._hoveredElement){let e=this._hoveredElement.entity.getGuid(),s=!this._clickedEntities;if(this._clickedEntities){let t=this._clickedEntities[e]||0;s=Date.now()-t>300,delete this._clickedEntities[e];}s&&this._fireEvent("click",new DX(t,this._hoveredElement,i,_,g,this._lastX,this._lastY));}this._pressedElement=null;}}_onXrStart(){this.app.xr.on("end",this._onXrEnd,this),this.app.xr.on("update",this._onXrUpdate,this),this.app.xr.input.on("selectstart",this._onSelectStart,this),this.app.xr.input.on("selectend",this._onSelectEnd,this),this.app.xr.input.on("remove",this._onXrInputRemove,this);}_onXrEnd(){this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this);}_onXrUpdate(){if(!this._enabled)return;let e=this.app.xr.input.inputSources;for(let t=0;t<e.length;t++)this._onElementSelectEvent("selectmove",e[t],null);}_onXrInputRemove(e){let t=this._selectedElements[e.id];t&&(e._elementEntity=null,this._fireEvent("selectleave",new Dq(null,t,null,e))),delete this._selectedElements[e.id],delete this._selectedPressedElements[e.id];}_onSelectStart(e,t){this._enabled&&this._onElementSelectEvent("selectstart",e,t);}_onSelectEnd(e,t){this._enabled&&this._onElementSelectEvent("selectend",e,t);}_onElementSelectEvent(e,t,i){let s,r,a,n=this._selectedElements[t.id],o=this.app.systems.camera.cameras;if(t.elementInput){Dx.set(t.getOrigin(),t.getDirection());for(let e=o.length-1;e>=0&&(a=o[e],!(s=this._getTargetElementByRay(Dx,a)));e--);}t._elementEntity=s||null,s?(this._selectedElements[t.id]=s,r=s):delete this._selectedElements[t.id],n!==r&&(n&&this._fireEvent("selectleave",new Dq(i,n,a,t)),r&&this._fireEvent("selectenter",new Dq(i,r,a,t)));let l=this._selectedPressedElements[t.id];"selectmove"===e&&l&&this._fireEvent("selectmove",new Dq(i,l,a,t)),"selectstart"===e&&(this._selectedPressedElements[t.id]=r,r&&this._fireEvent("selectstart",new Dq(i,r,a,t))),!t.elementInput&&l&&(delete this._selectedPressedElements[t.id],n&&this._fireEvent("selectend",new Dq(i,l,a,t))),"selectend"===e&&t.elementInput&&(delete this._selectedPressedElements[t.id],l&&this._fireEvent("selectend",new Dq(i,l,a,t)),l&&l===n&&this._fireEvent("click",new Dq(i,l,a,t)));}_fireEvent(e,t){let i=t.element;for(;i.fire(e,t),!t._stopPropagation&&i.entity.parent&&(i=i.entity.parent.element););}_calcMouseCoords(e){let t=this._target.getBoundingClientRect(),i=Math.floor(t.left),s=Math.floor(t.top);_=e.clientX-i,g=e.clientY-s;}_sortElements(e,t){let i=this.app.scene.layers.sortTransparentLayers(e.layers,t.layers);return 0!==i?i:e.screen&&!t.screen?-1:!e.screen&&t.screen?1:e.screen||t.screen?e.screen.screen.screenSpace&&!t.screen.screen.screenSpace?-1:t.screen.screen.screenSpace&&!e.screen.screen.screenSpace?1:t.drawOrder-e.drawOrder:0}_getTargetElementByCoords(e,t,i){let s=this._calculateRayScreen(t,i,e,DS)?DS:null,r=this._calculateRay3d(t,i,e,Dy)?Dy:null;return this._getTargetElement(e,s,r)}_getTargetElementByRay(e,t){DS.origin.copy(e.origin),DS.direction.copy(e.direction),DS.end.copy(DS.direction).mulScalar(2*t.farClip).add(DS.origin);let i=t.worldToScreen(DS.origin,Dg),s=this._calculateRayScreen(i.x,i.y,t,Dy)?Dy:null;return this._getTargetElement(t,s,DS)}_getTargetElement(e,t,i){let s=null,r=1/0;this._elements.sort(this._sortHandler);for(let a=0,n=this._elements.length;a<n;a++){let n=this._elements[a];if(n.layers.some(t=>e.layersSet.has(t)))if(n.screen&&n.screen.screen.screenSpace){if(!t)continue;if(this._checkElement(t,n,true)>=0){s=n;break}}else {if(!i)continue;let e=this._checkElement(i,n,false);if(e>=0&&(e<r&&(s=n,r=e),n.screen)){s=n;break}}}return s}_calculateRayScreen(e,t,i,s){let r=this.app.graphicsDevice.width,a=this.app.graphicsDevice.height,n=i.rect.z*r,o=i.rect.w*a,l=i.rect.x*r,h=(1-i.rect.y)*a,c=h-o,d=e*r/this._target.clientWidth,u=t*a/this._target.clientHeight;return d>=l&&d<=l+n&&u<=h&&u>=c&&(d=r*(d-l)/n,u=a*(u-c)/o,u=a-u,s.origin.set(d,u,1),s.direction.set(0,0,-1),s.end.copy(s.direction).mulScalar(2).add(s.origin),true)}_calculateRay3d(e,t,i,s){let r=this._target.clientWidth,a=this._target.clientHeight,n=i.rect.z*r,o=i.rect.w*a,l=i.rect.x*r,h=(1-i.rect.y)*a,c=h-o,d=e,u=t;return e>=l&&e<=l+n&&t<=h&&u>=c&&(d=r*(d-l)/n,u=a*(u-c)/o,i.screenToWorld(d,u,i.nearClip,Dg),i.screenToWorld(d,u,i.farClip,Dv),s.origin.copy(Dg),s.direction.set(0,0,-1),s.end.copy(Dv),true)}_checkElement(e,t,i){let s;if(t.maskedBy&&0>this._checkElement(e,t.maskedBy.element,i))return -1;s=i?D$.calculateScaleToScreen(t):D$.calculateScaleToWorld(t);let r=D$.buildHitCorners(t,i?t.screenCorners:t.worldCorners,s);return function(e,t,i){let s,r;DT.sub2(t,e),DE.sub2(i[0],e),DA.sub2(i[1],e),Db.sub2(i[2],e),DC.cross(Db,DT);let a=DE.dot(DC);if(a>=0){if((s=-DA.dot(DC))<0||(r=DH(DT,DA,DE))<0)return -1;let e=1/(s+a+r);DP.copy(i[0]).mulScalar(s*e),DL.copy(i[1]).mulScalar(a*e),DI.copy(i[2]).mulScalar(r*e),DD.copy(DP).add(DL).add(DI);}else {if(Dw.sub2(i[3],e),(s=Dw.dot(DC))<0||(r=DH(DT,DE,Dw))<0)return -1;let t=1/(s+(a=-a)+r);DP.copy(i[0]).mulScalar(s*t),DL.copy(i[3]).mulScalar(a*t),DI.copy(i[2]).mulScalar(r*t),DD.copy(DP).add(DL).add(DI);}return 1e-8>DT.sub2(i[0],i[2]).lengthSq()||1e-8>DT.sub2(i[1],i[3]).lengthSq()?-1:DD.sub(e).lengthSq()}(e.origin,e.end,r)}static buildHitCorners(e,t,i){let s=t;if(e.entity&&e.entity.button){let t=e.entity.button.hitPadding||DG;DO.copy(e.entity.up),DN.copy(DO).mulScalar(-1),DB.copy(e.entity.right),DF.copy(DB).mulScalar(-1),DO.mulScalar(t.w*i.y),DN.mulScalar(t.y*i.y),DB.mulScalar(t.z*i.x),DF.mulScalar(t.x*i.x),DU.copy(s[0]).add(DN).add(DF),Dk.copy(s[1]).add(DN).add(DB),DV.copy(s[2]).add(DO).add(DB),Dz.copy(s[3]).add(DO).add(DF),s=[DU,Dk,DV,Dz];}if(i.x<0){let e=s[2].x,t=s[0].x;s[0].x=e,s[1].x=t,s[2].x=t,s[3].x=e;}if(i.y<0){let e=s[2].y,t=s[0].y;s[0].y=e,s[1].y=e,s[2].y=t,s[3].y=t;}if(i.z<0){let e=s[2].x,t=s[2].y,i=s[2].z;s[2].x=s[0].x,s[2].y=s[0].y,s[2].z=s[0].z,s[0].x=e,s[0].y=t,s[0].z=i;}return s}static calculateScaleToScreen(e){let t=e.entity,i=e.screen.screen.scale;for(DM.set(i,i,i);t&&!t.screen;)DM.mul(t.getLocalScale()),t=t.parent;return DM}static calculateScaleToWorld(e){let t=e.entity;for(DM.set(1,1,1);t;)DM.mul(t.getLocalScale()),t=t.parent;return DM}}eN.prototype.scale=eN.prototype.mulScalar,eM.prototype.scale=eM.prototype.mulScalar,eF.prototype.scale=eF.prototype.mulScalar;let Dj=ia,DK=io,DZ=il,DQ=ih,DJ=ic,D0=id,D1=iA,D2=ib,D3=tg,D4=tv,D5=tg,D8=tv,D6="1.51",D9="1.55",D7="1.56",Re="1.57",Rt="1.58",Ri="1.60",Rs="1.62",Rr="1.65",Ra="1.70",Rn="2.1",Ro="2.3",Rl="2.5",Rh="2.6",Rc="2.7",Rd="2.8",Ru=new eF;function Rf(e,t){return mw.fromGeometry(e,new v0(t))}function Rp(e,t){return mw.fromGeometry(e,new yE(t))}function Rm(e,t){return mw.fromGeometry(e,new vJ(t))}function R_(e,t){return mw.fromGeometry(e,new yA(t))}function Rg(e,t){return mw.fromGeometry(e,new yy(t))}function Rv(e,t){return mw.fromGeometry(e,new yx(t))}function RS(e,t){return mw.fromGeometry(e,new yT(t))}function Ry(e,t,i={}){let s=new vQ;return s.positions=t,s.normals=i.normals,s.tangents=i.tangents,s.colors=i.colors,s.uvs=i.uvs,s.uvs1=i.uvs1,s.blendIndices=i.blendIndices,s.blendWeights=i.blendWeights,s.indices=i.indices,mw.fromGeometry(e,s,i)}function Rx(e,t,i,s,r){let a;if(r){let i=t?t.width:e.width,s=t?t.height:e.height;a=Ru.set(r.x*i,r.y*s,r.z*i,r.w*s);}mg(e,t,s,a);}Object.defineProperties(nM.prototype,{_glFrameBuffer:{get:function(){return this.impl._glFrameBuffer},set:function(e){}}}),Object.defineProperty(nP,"defaultInstancingFormat",{get:function(){return null}}),Object.defineProperties(ns.prototype,{rgbm:{get:function(){return this.type===ri},set:function(e){this.type=e?ri:rt;}},swizzleGGGR:{get:function(){return this.type===ra},set:function(e){this.type=e?ra:rt;}},_glTexture:{get:function(){return this.impl._glTexture}}}),Object.defineProperty(nD.prototype,"boneLimit",{get:function(){return 1024}}),Object.defineProperty(nD.prototype,"webgl2",{get:function(){return this.isWebGL2}}),Object.defineProperty(nD.prototype,"textureFloatHighPrecision",{get:function(){return true}}),Object.defineProperty(nD.prototype,"extBlendMinmax",{get:function(){return true}}),Object.defineProperty(nD.prototype,"extTextureHalfFloat",{get:function(){return true}}),Object.defineProperty(nD.prototype,"extTextureLod",{get:function(){return true}}),Object.defineProperty(nD.prototype,"textureHalfFloatFilterable",{get:function(){return true}}),Object.defineProperty(nD.prototype,"supportsMrt",{get:function(){return true}}),Object.defineProperty(nD.prototype,"supportsVolumeTextures",{get:function(){return true}}),Object.defineProperty(nD.prototype,"supportsInstancing",{get:function(){return true}}),Object.defineProperty(nD.prototype,"textureHalfFloatUpdatable",{get:function(){return true}}),Object.defineProperty(nD.prototype,"extTextureFloat",{get:function(){return true}}),Object.defineProperty(nD.prototype,"extStandardDerivatives",{get:function(){return true}}),nu.DEFAULT=Object.freeze(new nu);let RT=new nu,RE=new nm;nD.prototype.setBlendFunction=function(e,t){let i=this.blendState;RT.copy(i),RT.setColorBlend(i.colorOp,e,t),RT.setAlphaBlend(i.alphaOp,e,t),this.setBlendState(RT);},nD.prototype.setBlendFunctionSeparate=function(e,t,i,s){let r=this.blendState;RT.copy(r),RT.setColorBlend(r.colorOp,e,t),RT.setAlphaBlend(r.alphaOp,i,s),this.setBlendState(RT);},nD.prototype.setBlendEquation=function(e){let t=this.blendState;RT.copy(t),RT.setColorBlend(e,t.colorSrcFactor,t.colorDstFactor),RT.setAlphaBlend(e,t.alphaSrcFactor,t.alphaDstFactor),this.setBlendState(RT);},nD.prototype.setBlendEquationSeparate=function(e,t){let i=this.blendState;RT.copy(i),RT.setColorBlend(e,i.colorSrcFactor,i.colorDstFactor),RT.setAlphaBlend(t,i.alphaSrcFactor,i.alphaDstFactor),this.setBlendState(RT);},nD.prototype.setColorWrite=function(e,t,i,s){let r=this.blendState;RT.copy(r),RT.setColorWrite(e,t,i,s),this.setBlendState(RT);},nD.prototype.getBlending=function(){return this.blendState.blend},nD.prototype.setBlending=function(e){RT.copy(this.blendState),RT.blend=e,this.setBlendState(RT);},nD.prototype.setDepthWrite=function(e){RE.copy(this.depthState),RE.write=e,this.setDepthState(RE);},nD.prototype.setDepthFunc=function(e){RE.copy(this.depthState),RE.func=e,this.setDepthState(RE);},nD.prototype.setDepthTest=function(e){RE.copy(this.depthState),RE.test=e,this.setDepthState(RE);},nD.prototype.getCullMode=function(){return this.cullMode};let RA=SB,Rb=SU,Rw=SX,RC=new Proxy({},{get:(e,t)=>mr.get(s.graphicsDevice,rb).get(t),set:(e,t,i)=>(mr.get(s.graphicsDevice,rb).set(t,i),true)});function RP(e,t,i=""){Object.defineProperty(e.prototype,t,{set:function(e){},get:function(){}});}function RL(e,t){Object.defineProperty(yo.prototype,t,{get:function(){return this[e]},set:function(t){this[e]=t;}});}function RI(e){Object.defineProperty(yo.prototype,e,{get:function(){return true},set:function(e){}});}function RD(e,t){"pass"!==e&&Object.defineProperty(S0.prototype,e,{get:function(){return this.litOptions[t||e]},set:function(i){this.litOptions[t||e]=i;}});}Object.defineProperty(SD.prototype,"defaultMaterial",{get:function(){return mP(s.graphicsDevice)}}),Object.defineProperty(SD.prototype,"fogColor",{set:function(e){this.fog.color=e;},get:function(){return this.fog.color}}),Object.defineProperty(SD.prototype,"fogEnd",{set:function(e){this.fog.end=e;},get:function(){return this.fog.end}}),Object.defineProperty(SD.prototype,"fogStart",{set:function(e){this.fog.start=e;},get:function(){return this.fog.start}}),Object.defineProperty(SD.prototype,"fogDensity",{set:function(e){this.fog.density=e;},get:function(){return this.fog.density}}),Object.defineProperty(SD.prototype,"toneMapping",{set:function(e){},get:function(){}}),Object.defineProperty(SD.prototype,"gammaCorrection",{set:function(e){},get:function(){}}),Object.defineProperty(SD.prototype,"rendering",{set:function(e){},get:function(){}}),Object.defineProperty(gY.prototype,"_meshInstances",{get:function(){return null}}),Object.defineProperty(SD.prototype,"drawCalls",{get:function(){return null}}),["128","64","32","16","8","4"].forEach((e,t)=>{Object.defineProperty(SD.prototype,`skyboxPrefiltered${e}`,{get:function(){return this._prefilteredCubemaps[t]},set:function(e){this._prefilteredCubemaps[t]=e,this.updateShaders=true;}});}),Object.defineProperty(SD.prototype,"models",{get:function(){return this._models||(this._models=[]),this._models}}),RP(gH,"renderTarget"),RP(gH,"onPreCull"),RP(gH,"onPreRender"),RP(gH,"onPreRenderOpaque"),RP(gH,"onPreRenderTransparent"),RP(gH,"onPostCull"),RP(gH,"onPostRender"),RP(gH,"onPostRenderOpaque"),RP(gH,"onPostRenderTransparent"),RP(gH,"onDrawCall"),RP(gH,"layerReference"),RP(w1,"onPreCull","Use Scene#EVENT_PRECULL event instead."),RP(w1,"onPostCull","Use Scene#EVENT_POSTCULL event instead."),RP(w1,"onPreRender","Use Scene#EVENT_PRERENDER event instead."),RP(w1,"onPostRender","Use Scene#EVENT_POSTRENDER event instead."),RP(w1,"onPreRenderLayer","Use Scene#EVENT_PRERENDER_LAYER event instead."),RP(w1,"onPostRenderLayer","Use Scene#EVENT_POSTRENDER_LAYER event instead."),gB.prototype.renderComposition=function(e){s.renderComposition(e);},mV.prototype.syncAabb=function(){},g8.prototype.getTarget=function(e){return this.targets[e]},_c.prototype.getChildren=function(){return this.children},_c.prototype.getName=function(){return this.name},_c.prototype.getPath=function(){return this.path},_c.prototype.getRoot=function(){return this.root},_c.prototype.getParent=function(){return this.parent},_c.prototype.setName=function(e){this.name=e;},Object.defineProperty(_$.prototype,"shader",{set:function(e){},get:function(){return null}}),Object.defineProperty(_$.prototype,"blend",{set:function(e){this.blendState.blend=e;},get:function(){return this.blendState.blend}}),Object.defineProperty(yo.prototype,"shininess",{get:function(){return 100*this.gloss},set:function(e){this.gloss=.01*e;}}),Object.defineProperty(yo.prototype,"useGammaTonemap",{get:function(){return this.useTonemap},set:function(e){this.useTonemap=e;}}),Object.defineProperty(yo.prototype,"anisotropy",{get:function(){let e=Math.sign(Math.cos(this.anisotropyRotation*eA.DEG_TO_RAD*2));return this.anisotropyIntensity*e},set:function(e){this.anisotropyIntensity=Math.abs(e),e>=0?this.anisotropyRotation=0:this.anisotropyRotation=90;}}),RI("sheenTint"),RI("diffuseTint"),RI("emissiveTint"),RI("ambientTint"),RL("specularTint","specularMapTint"),RL("aoVertexColor","aoMapVertexColor"),RL("diffuseVertexColor","diffuseMapVertexColor"),RL("specularVertexColor","specularMapVertexColor"),RL("emissiveVertexColor","emissiveMapVertexColor"),RL("metalnessVertexColor","metalnessMapVertexColor"),RL("glossVertexColor","glossMapVertexColor"),RL("opacityVertexColor","opacityMapVertexColor"),RL("lightVertexColor","lightMapVertexColor"),RL("sheenGloss","sheenGlossiess"),RL("clearCoatGloss","clearCostGlossiness"),RD("refraction","useRefraction");let RR=Object.getOwnPropertyNames(new SX);for(let e in RR)RD(RR[e]);xU.prototype.getAssetById=function(e){return this.get(e)},Object.defineProperty(IJ.prototype,"ray",{get:function(){return this._rayLocal}}),Object.defineProperty(IJ.prototype,"position",{get:function(){return this._localPosition}}),Object.defineProperty(IJ.prototype,"rotation",{get:function(){return this._localRotation}});let RM="keydown",RO="keyup",RN="mousedown",RF="mousemove",RB="mouseup",RU="mousewheel",Rk="touchstart",RV="touchend",Rz="touchmove",RG="touchcancel",RH="gamepadconnected",RW="gamepaddisconnected",RX="select",RY="selectstart",Rq="selectend";Object.defineProperty(D$.prototype,"wheel",{get:function(){return -2*this.wheelDelta}}),Object.defineProperty(dO.prototype,"wheel",{get:function(){return -2*this.wheelDelta}});let R$=Ez,Rj=EG,RK=EH,RZ=EW,RQ=EX,RJ=EY,R0=Eq,R1=E$,R2=Ej,R3=EK,R4=EZ;x9.prototype.isFullscreen=function(){return !!document.fullscreenElement},x9.prototype.enableFullscreen=function(e,t,i){e=e||this.graphicsDevice.canvas;let s=function(){t(),document.removeEventListener("fullscreenchange",s);},r=function(){i(),document.removeEventListener("fullscreenerror",r);};t&&document.addEventListener("fullscreenchange",s,false),i&&document.addEventListener("fullscreenerror",r,false),e.requestFullscreen?e.requestFullscreen(Element.ALLOW_KEYBOARD_INPUT):i();},x9.prototype.disableFullscreen=function(e){let t=function(){e(),document.removeEventListener("fullscreenchange",t);};e&&document.addEventListener("fullscreenchange",t,false),document.exitFullscreen();},x9.prototype.getSceneUrl=function(e){let t=this.scenes.find(e);return t?t.url:null},x9.prototype.loadScene=function(e,t){this.scenes.loadScene(e,t);},x9.prototype.loadSceneHierarchy=function(e,t){this.scenes.loadSceneHierarchy(e,t);},x9.prototype.loadSceneSettings=function(e,t){this.scenes.loadSceneSettings(e,t);},bR.prototype.setVisible=function(e){this.enabled=e;},Object.defineProperty(b4.prototype,"bodyType",{get:function(){return this.type},set:function(e){this.type=e;}}),b4.prototype.syncBodyToEntity=function(){this._updateDynamic();},wt.prototype.setGravity=function(){1==arguments.length?this.gravity.copy(arguments[0]):this.gravity.set(arguments[0],arguments[1],arguments[2]);};class R5{constructor(e){this._frameIndex=0,this._frameTimings=[],this._timings=[],this._prevTimings=[],this.unitsName="ms",this.decimalPlaces=1,this.enabled=true,e.on("frameupdate",this.begin.bind(this,"update")),e.on("framerender",this.mark.bind(this,"render")),e.on("frameend",this.mark.bind(this,"other"));}begin(e){if(!this.enabled)return;this._frameIndex<this._frameTimings.length&&this._frameTimings.splice(this._frameIndex);let t=this._prevTimings;this._prevTimings=this._timings,this._timings=this._frameTimings,this._frameTimings=t,this._frameIndex=0,this.mark(e);}mark(e){if(!this.enabled)return;let t=em();if(this._frameIndex>0){let e=this._frameTimings[this._frameIndex-1];e[1]=t-e[1];}else if(this._timings.length>0){let e=this._timings[this._timings.length-1];e[1]=t-e[1];}if(this._frameIndex>=this._frameTimings.length)this._frameTimings.push([e,t]);else {let i=this._frameTimings[this._frameIndex];i[0]=e,i[1]=t;}this._frameIndex++;}get timings(){return this._timings.slice(0,-1).map(e=>e[1])}}class R8{constructor(e){this.device=e,e.gpuProfiler.enabled=true,this.enabled=true,this.unitsName="ms",this.decimalPlaces=1,this._timings=[];}get timings(){return this._timings[0]=this.device.gpuProfiler._frameTime,this._timings}}class R6{constructor(e,t,i,s,r){this.app=e,this.values=[],this.statNames=t,this.statNames.length>3&&(this.statNames.length=3),this.unitsName=s,this.decimalPlaces=i,this.multiplier=r||1;let a=(e,t)=>e.split(".").reduce((e,t)=>e?e[t]:null,t||this);e.on("frameupdate",e=>{for(let e=0;e<this.statNames.length;e++)this.values[e]=a(this.statNames[e],this.app.stats)*this.multiplier;});}get timings(){return this.values}}class R9{constructor(e,t,i,s,r){this.app=t,this.name=e,this.device=t.graphicsDevice,this.timer=r,this.watermark=i,this.enabled=false,this.textRefreshRate=s,this.avgTotal=0,this.avgTimer=0,this.avgCount=0,this.timingText="",this.texture=null,this.yOffset=0,this.cursor=0,this.sample=new Uint8ClampedArray(4),this.sample.set([0,0,0,255]),this.counter=0,this.app.on("frameupdate",this.update,this);}destroy(){this.app.off("frameupdate",this.update,this);}loseContext(){this.timer&&"function"==typeof this.timer.loseContext&&this.timer.loseContext();}update(e){let t=this.timer.timings,i=t.reduce((e,t)=>e+t,0);if(this.avgTotal+=i,this.avgTimer+=e,this.avgCount++,this.avgTimer>this.textRefreshRate&&(this.timingText=(this.avgTotal/this.avgCount).toFixed(this.timer.decimalPlaces),this.avgTimer=0,this.avgTotal=0,this.avgCount=0),this.enabled){let e=0,i=1.5*this.watermark;for(let s=0;s<t.length;++s)e+=Math.floor(t[s]/i*255),this.sample[s]=e;this.sample[3]=this.watermark/i*255,this.texture.lock().set(this.sample,(this.cursor+this.yOffset*this.texture.width)*4),this.texture.unlock(),this.cursor++,this.cursor===this.texture.width&&(this.cursor=0);}}render(e,t,i,s,r){e.quad(t+s,i,-s,r,this.enabled?this.cursor:0,this.enabled?.5+this.yOffset:this.texture.height-1,-s,0,this.texture,0);}}class R7{constructor(e,t){let i=e=>{e.font='10px "Lucida Console", Monaco, monospace',e.textAlign="left",e.textBaseline="alphabetic";},s=e=>"."===e||1===e.length&&e.charCodeAt(0)>=48&&57>=e.charCodeAt(0),r=document.createElement("canvas"),a=r.getContext("2d",{alpha:true});i(a);let n=new Map,o=5,l=5;t.forEach(e=>{let t=a.measureText(e),i=Math.ceil(-t.actualBoundingBoxLeft),s=Math.ceil(t.actualBoundingBoxRight),r=Math.ceil(t.actualBoundingBoxAscent),h=Math.ceil(t.actualBoundingBoxDescent),c=i+s;o+c+5>=512&&(o=5,l+=16),n.set(e,{l:i,r:s,a:r,d:h,w:c,h:r+h,x:o,y:l}),o+=c+5;}),r.width=512,r.height=eA.nextPowerOfTwo(l+16+5),i(a),a.fillStyle="rgb(0, 0, 0)",a.fillRect(0,0,r.width,r.height),n.forEach((e,t)=>{a.fillStyle=s(t)?"rgb(255, 255, 255)":"rgb(170, 170, 170)",a.fillText(t,e.x-e.l,e.y+e.a);}),this.placements=n;let h=a.getImageData(0,0,r.width,r.height).data;for(let e=0;e<h.length;e+=4)h[e+3]=h[e+0],h[e+0]=255,h[e+1]=255,h[e+2]=255;this.texture=new ns(e,{name:"mini-stats-word-atlas",width:r.width,height:r.height,mipmaps:false,minFilter:tK,magFilter:tK,levels:[h]});}destroy(){this.texture.destroy(),this.texture=null;}render(e,t,i,s){let r=this.placements.get(t);return r?(e.quad(i+r.l-1,s-r.d+1,r.w+2,r.h+2,r.x-1,this.texture.height-r.y-r.h-1,void 0,void 0,this.texture,1),r.w):0}}let Me=`
attribute vec3 vertex_position;
attribute vec4 vertex_texCoord0;
varying vec4 uv0;
varying float wordFlag;
void main(void) {
gl_Position = vec4(vertex_position.xy * 2.0 - 1.0, 0.5, 1.0);
uv0 = vertex_texCoord0;
wordFlag = vertex_position.z;
}
`,Mt=`
attribute vertex_position: vec3f;
attribute vertex_texCoord0: vec4f;
varying uv0: vec4f;
varying wordFlag: f32;
@vertex fn vertexMain(input : VertexInput) -> VertexOutput {
var output : VertexOutput;
output.position = vec4(input.vertex_position.xy * 2.0 - 1.0, 0.5, 1.0);
output.uv0 = input.vertex_texCoord0;
output.wordFlag = input.vertex_position.z;
return output;
}
`,Mi=`
varying vec4 uv0;
varying float wordFlag;
uniform vec4 clr;
uniform sampler2D graphTex;
uniform sampler2D wordsTex;
void main (void) {
vec4 graphSample = texture2D(graphTex, uv0.xy);
vec4 graph;
if (uv0.w < graphSample.r)
graph = vec4(0.7, 0.2, 0.2, 1.0);
else if (uv0.w < graphSample.g)
graph = vec4(0.2, 0.7, 0.2, 1.0);
else if (uv0.w < graphSample.b)
graph = vec4(0.2, 0.2, 0.7, 1.0);
else
graph = vec4(0.0, 0.0, 0.0, 1.0 - 0.25 * sin(uv0.w * 3.14159));
vec4 words = texture2D(wordsTex, vec2(uv0.x, 1.0 - uv0.y));
gl_FragColor = mix(graph, words, wordFlag) * clr;
}
`,Ms=`
varying uv0: vec4f;
varying wordFlag: f32;
uniform clr: vec4f;
var graphTex : texture_2d<f32>;
var graphTex_sampler : sampler;
var wordsTex : texture_2d<f32>;
var wordsTex_sampler : sampler;
@fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var uv0: vec4f = input.uv0;
var graphSample: vec4f = textureSample(graphTex, graphTex_sampler, uv0.xy);
var graph: vec4f;
if (uv0.w < graphSample.r) {
graph = vec4f(0.7, 0.2, 0.2, 1.0);
} else if (uv0.w < graphSample.g) {
graph = vec4f(0.2, 0.7, 0.2, 1.0);
} else if (uv0.w < graphSample.b) {
graph = vec4f(0.2, 0.2, 0.7, 1.0);
} else {
graph = vec4f(0.0, 0.0, 0.0, 1.0 - 0.25 * sin(uv0.w * 3.14159));
}
var words: vec4f = textureSample(wordsTex, wordsTex_sampler, vec2f(uv0.x, 1.0 - uv0.y));
var output: FragmentOutput;
output.color = mix(graph, words, input.wordFlag) * uniform.clr;
return output;
}
`;class Mr{constructor(e,t=512){let i=new nP(e,[{semantic:sT,components:3,type:rM},{semantic:sL,components:4,type:rM}]),s=new Uint16Array(6*t);for(let e=0;e<t;++e)s[6*e+0]=4*e,s[6*e+1]=4*e+1,s[6*e+2]=4*e+2,s[6*e+3]=4*e,s[6*e+4]=4*e+2,s[6*e+5]=4*e+3;this.device=e,this.buffer=new nT(e,i,4*t,{usage:tN}),this.data=new Float32Array(this.buffer.numBytes/4),this.indexBuffer=new lJ(e,it,6*t,tM,s),this.prim={type:sS,indexed:true,base:0,baseVertex:0,count:0},this.quads=0,this.mesh=new mw(e),this.mesh.vertexBuffer=this.buffer,this.mesh.indexBuffer[0]=this.indexBuffer,this.mesh.primitive=[this.prim];let r=new vY({uniqueName:"MiniStats",vertexGLSL:Me,fragmentGLSL:Mi,vertexWGSL:Mt,fragmentWGSL:Ms,attributes:{vertex_position:sT,vertex_texCoord0:sL}});this.material=r,r.cull=tY,r.depthState=nm.NODEPTH,r.blendState=new nu(true,tS,tu,tp,tS,to,to),r.update(),this.meshInstance=new mV(this.mesh,r,new _c("MiniStatsMesh")),this.uniforms={clr:new Float32Array(4)},this.targetSize={width:e.width,height:e.height};}quad(e,t,i,s,r,a,n,o,l,h=0){let c=this.targetSize.width,d=this.targetSize.height,u=e/c,f=t/d,p=(e+i)/c,m=(t+s)/d,_=l.width,g=l.height,v=r/_,S=a/g,y=(r+(n??i))/_,x=(a+(o??s))/g;this.data.set([u,f,h,v,S,0,0,p,f,h,y,S,1,0,p,m,h,y,x,1,1,u,m,h,v,x,0,1],28*this.quads),this.quads++,this.prim.count+=6;}startFrame(){this.quads=0,this.prim.count=0,this.targetSize.width=this.device.canvas.scrollWidth,this.targetSize.height=this.device.canvas.scrollHeight;}render(e,t,i,s,r,a){this.buffer.setData(this.data.buffer),this.uniforms.clr.set(r,0),this.material.setParameter("clr",this.uniforms.clr),this.material.setParameter("graphTex",i),this.material.setParameter("wordsTex",s),e.drawMeshInstance(this.meshInstance,t);}}class Ma{constructor(e,t){let i=e.graphicsDevice;t=t||Ma.getDefaultOptions(),this.initGraphs(e,i,t);let s=new Set(["","ms","0","1","2","3","4","5","6","7","8","9","."].concat(this.graphs.map(e=>e.name)).concat(t.stats?t.stats.map(e=>e.unitsName):[]).filter(e=>!!e));this.wordAtlas=new R7(i,s),this.sizes=t.sizes,this._activeSizeIndex=t.startSizeIndex;let r=document.createElement("div");r.setAttribute("id","mini-stats"),r.style.cssText="position:fixed;bottom:0;left:0;background:transparent;",document.body.appendChild(r),r.addEventListener("mouseenter",e=>{this.opacity=1;}),r.addEventListener("mouseleave",e=>{this.opacity=.7;}),r.addEventListener("click",e=>{e.preventDefault(),this._enabled&&(this.activeSizeIndex=(this.activeSizeIndex+1)%this.sizes.length,this.resize(this.sizes[this.activeSizeIndex].width,this.sizes[this.activeSizeIndex].height,this.sizes[this.activeSizeIndex].graphs));}),i.on("resizecanvas",this.updateDiv,this),i.on("losecontext",this.loseContext,this),e.on("postrender",this.postRender,this),this.app=e,this.drawLayer=e.scene.layers.getLayerById(uL),this.device=i,this.render2d=new Mr(i),this.div=r,this.width=0,this.height=0,this.gspacing=2,this.clr=[1,1,1,.5],this._enabled=true,this.activeSizeIndex=this._activeSizeIndex;}destroy(){this.device.off("resizecanvas",this.updateDiv,this),this.device.off("losecontext",this.loseContext,this),this.app.off("postrender",this.postRender,this),this.graphs.forEach(e=>e.destroy()),this.wordAtlas.destroy(),this.texture.destroy();}static getDefaultOptions(){return {sizes:[{width:100,height:16,spacing:0,graphs:false},{width:128,height:32,spacing:2,graphs:true},{width:256,height:64,spacing:2,graphs:true}],startSizeIndex:0,textRefreshRate:500,cpu:{enabled:true,watermark:33},gpu:{enabled:true,watermark:33},stats:[{name:"Frame",stats:["frame.ms"],decimalPlaces:1,unitsName:"ms",watermark:33},{name:"DrawCalls",stats:["drawCalls.total"],watermark:1e3}]}}set activeSizeIndex(e){this._activeSizeIndex=e,this.gspacing=this.sizes[e].spacing,this.resize(this.sizes[e].width,this.sizes[e].height,this.sizes[e].graphs);}get activeSizeIndex(){return this._activeSizeIndex}set opacity(e){this.clr[3]=e;}get opacity(){return this.clr[3]}get overallHeight(){let e=this.graphs,t=this.gspacing;return this.height*e.length+t*(e.length-1)}set enabled(e){if(e!==this._enabled){this._enabled=e;for(let t=0;t<this.graphs.length;++t)this.graphs[t].enabled=e,this.graphs[t].timer.enabled=e;}}get enabled(){return this._enabled}initGraphs(e,t,i){if(this.graphs=[],i.cpu.enabled){let t=new R5(e),s=new R9("CPU",e,i.cpu.watermark,i.textRefreshRate,t);this.graphs.push(s);}if(i.gpu.enabled){let s=new R8(t),r=new R9("GPU",e,i.gpu.watermark,i.textRefreshRate,s);this.graphs.push(r);}i.stats&&i.stats.forEach(t=>{let s=new R6(e,t.stats,t.decimalPlaces,t.unitsName,t.multiplier),r=new R9(t.name,e,t.watermark,i.textRefreshRate,s);this.graphs.push(r);});let s=i.sizes.reduce((e,t)=>t.width>e?t.width:e,0);this.texture=new ns(t,{name:"mini-stats-graph-texture",width:eA.nextPowerOfTwo(s),height:eA.nextPowerOfTwo(this.graphs.length),mipmaps:false,minFilter:tK,magFilter:tK,addressU:ts,addressV:ts}),this.graphs.forEach((e,t)=>{e.texture=this.texture,e.yOffset=t;});}render(){let e=this.graphs,t=this.wordAtlas,i=this.render2d,s=this.width,r=this.height,a=this.gspacing;i.startFrame();for(let n=0;n<e.length;++n){let o=e[n],l=n*(r+a);o.render(i,0,l,s,r);let h=1;l+=r-13,h+=t.render(i,o.name,h,l)+10;let c=o.timingText;for(let e=0;e<c.length;++e)h+=t.render(i,c[e],h,l);o.timer.unitsName&&(h+=3,t.render(i,o.timer.unitsName,h,l));}i.render(this.app,this.drawLayer,this.texture,this.wordAtlas.texture,this.clr,r);}resize(e,t,i){let s=this.graphs;for(let e=0;e<s.length;++e)s[e].enabled=i;this.width=e,this.height=t,this.updateDiv();}updateDiv(){let e=this.device.canvas.getBoundingClientRect();this.div.style.left=`${e.left}px`,this.div.style.bottom=`${window.innerHeight-e.bottom}px`,this.div.style.width=`${this.width}px`,this.div.style.height=`${this.overallHeight}px`;}loseContext(){this.graphs.forEach(e=>e.loseContext());}postRender(){this._enabled&&this.render();}}let Mn=`
varying vec2 vUv0;
uniform vec2 uOffset;
uniform float uSrcMultiplier;
uniform sampler2D source;
void main(void)
{
vec4 pixel;
vec4 texel = texture2D(source, vUv0);
vec4 firstTexel = texel;
float diff = texel.a * uSrcMultiplier;
pixel = texture2D(source, vUv0 + uOffset * -2.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
pixel = texture2D(source, vUv0 + uOffset * -1.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
pixel = texture2D(source, vUv0 + uOffset * 1.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
pixel = texture2D(source, vUv0 + uOffset * 2.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
gl_FragColor = vec4(texel.rgb, min(diff, 1.0));
}
`,Mo=new Float32Array(2),Ml=new eb;class Mh{constructor(e,t,i=-1){this.app=e,this.renderingLayer=t??e.scene.layers.getLayerByName("Immediate"),this.rt=this.createRenderTarget("OutlineTexture",1,1,true),this.outlineCameraEntity=new x1("OutlineCamera"),this.outlineCameraEntity.addComponent("camera",{layers:[this.renderingLayer.id],priority:i,clearColor:new eb(0,0,0,0),renderTarget:this.rt}),this.outlineShaderPass=this.outlineCameraEntity.camera.setShaderPass("OutlineShaderPass"),this.postRender=e=>{this.outlineCameraEntity.camera===e&&this.onPostRender();},e.scene.on("postrender",this.postRender),this.app.root.addChild(this.outlineCameraEntity),this.tempRt=this.createRenderTarget("OutlineTempTexture",1,1,false),this.blendState=new nu(true,tS,tu,tp);let s=this.app.graphicsDevice;this.shaderExtend=mo.createShader(s,{uniqueName:"OutlineExtendShader",attributes:{vertex_position:sT},vertexGLSL:mr.get(s,rb).get("fullscreenQuadVS"),fragmentGLSL:Mn}),this.shaderBlend=mo.createShader(s,{uniqueName:"OutlineBlendShader",attributes:{vertex_position:sT},vertexChunk:"fullscreenQuadVS",fragmentChunk:"outputTex2DPS"}),this.quadRenderer=new mp(this.shaderBlend),this.whiteTex=new ns(s,{name:"OutlineWhiteTexture",width:1,height:1,format:ib,mipmaps:false}),this.whiteTex.lock().set(new Uint8Array([255,255,255,255])),this.whiteTex.unlock();}destroy(){this.whiteTex.destroy(),this.whiteTex=null,this.outlineCameraEntity.destroy(),this.outlineCameraEntity=null,this.rt.destroyTextureBuffers(),this.rt.destroy(),this.rt=null,this.tempRt.destroyTextureBuffers(),this.tempRt.destroy(),this.tempRt=null,this.app.scene.off("postrender",this.postRender),this.quadRenderer?.destroy(),this.quadRenderer=null;}getMeshInstances(e,t){let i=[];return e&&((t?e.findComponents("render"):e.render?[e.render]:[]).forEach(e=>{e.meshInstances&&i.push(...e.meshInstances);}),(t?e.findComponents("model"):e.model?[e.model]:[]).forEach(e=>{e.meshInstances&&i.push(...e.meshInstances);})),i}addEntity(e,t,i=true){let s=this.getMeshInstances(e,i);s.forEach(e=>{if(e.material instanceof yo){let i=this.outlineShaderPass;e.material.onUpdateShader=e=>{if(e.pass===i){let t=new S0;return t.defines=e.defines,t.opacityMap=e.opacityMap,t.opacityMapUv=e.opacityMapUv,t.opacityMapChannel=e.opacityMapChannel,t.opacityMapTransform=e.opacityMapTransform,t.opacityVertexColor=e.opacityVertexColor,t.opacityVertexColorChannel=e.opacityVertexColorChannel,t.litOptions.vertexColors=e.litOptions.vertexColors,t.litOptions.alphaTest=e.litOptions.alphaTest,t.litOptions.skin=e.litOptions.skin,t.litOptions.batch=e.litOptions.batch,t.litOptions.useInstancing=e.litOptions.useInstancing,t.litOptions.useMorphPosition=e.litOptions.useMorphPosition,t.litOptions.useMorphNormal=e.litOptions.useMorphNormal,t.litOptions.useMorphTextureBasedInt=e.litOptions.useMorphTextureBasedInt,t.litOptions.opacityFadesSpecular=e.litOptions.opacityFadesSpecular,t}return e},Ml.linear(t);let s=new Float32Array([Ml.r,Ml.g,Ml.b]);e.setParameter("material_emissive",s,1<<this.outlineShaderPass),e.setParameter("texture_emissiveMap",this.whiteTex,1<<this.outlineShaderPass);}}),this.renderingLayer.addMeshInstances(s,true);}removeEntity(e,t=true){let i=this.getMeshInstances(e,t);this.renderingLayer.removeMeshInstances(i),i.forEach(e=>{e.material instanceof yo&&(e.material.onUpdateShader=null,e.deleteParameter("material_emissive"));});}removeAllEntities(){this.renderingLayer.clearMeshInstances();}blendOutlines(){let e=this.app.graphicsDevice;e.scope.resolve("source").setValue(this.rt.colorBuffer),e.setDepthState(nm.NODEPTH),e.setCullMode(tY),e.setBlendState(this.blendState),this.quadRenderer.render();}onPostRender(){let e=this.app.graphicsDevice,t=e.scope.resolve("uOffset"),i=e.scope.resolve("source"),s=e.scope.resolve("uSrcMultiplier"),{rt:r,tempRt:a,shaderExtend:n}=this,{width:o,height:l}=r;Mo[0]=1/o/2,Mo[1]=0,t.setValue(Mo),i.setValue(r.colorBuffer),s.setValue(0),mg(e,a,n),Mo[0]=0,Mo[1]=1/l/2,t.setValue(Mo),i.setValue(a.colorBuffer),s.setValue(1),mg(e,r,n);}createRenderTarget(e,t,i,s){return new nM({colorBuffer:new ns(this.app.graphicsDevice,{name:e,width:t,height:i,format:ib,mipmaps:false,addressU:tr,addressV:tr,minFilter:t1,magFilter:tZ}),depth:s,flipY:this.app.graphicsDevice.isWebGPU})}updateRenderTarget(e){let t=e.renderTarget?.width??this.app.graphicsDevice.width,i=e.renderTarget?.height??this.app.graphicsDevice.height,s=this.outlineCameraEntity.camera;s.renderTarget&&s.renderTarget.width===t&&s.renderTarget.height===i||(this.rt.resize(t,i),this.tempRt.resize(t,i));}frameUpdate(e,t,i){let s=e.camera;this.updateRenderTarget(s);let r=this.app.scene.on("prerender:layer",(e,a,n)=>{s===e&&n===i&&a===t&&(this.blendOutlines(),r.off());});this.outlineCameraEntity.setLocalPosition(e.getPosition()),this.outlineCameraEntity.setLocalRotation(e.getRotation());let a=this.outlineCameraEntity.camera;a.projection=s.projection,a.horizontalFov=s.horizontalFov,a.fov=s.fov,a.orthoHeight=s.orthoHeight,a.nearClip=s.nearClip,a.farClip=s.farClip;}}class Mc{constructor(){}textureToCanvas(e,t={}){let i=e.getSource();if("undefined"!=typeof HTMLImageElement&&i instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&i instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&i instanceof OffscreenCanvas||"undefined"!=typeof ImageBitmap&&i instanceof ImageBitmap){let{width:e,height:s}=this.calcTextureSize(i.width,i.height,t.maxTextureSize),r=document.createElement("canvas");r.width=e,r.height=s;let a=r.getContext("2d");if(null===a)return Promise.resolve(void 0);if(a.drawImage(i,0,0,r.width,r.height),t.color){let{r:i,g:r,b:n}=t.color,o=a.getImageData(0,0,e,s),l=o.data;for(let e=0;e<l.length;e+=4)l[e+0]=l[e+0]*i,l[e+1]=l[e+1]*r,l[e+2]=l[e+2]*n;a.putImageData(o,0,0);}return Promise.resolve(r)}let s=e.device,{width:r,height:a}=this.calcTextureSize(e.width,e.height,t.maxTextureSize),n=new ns(s,{name:"ExtractedTexture",width:r,height:a,format:sl(e.format)?id:e.format,cubemap:false,mipmaps:false,minFilter:tZ,magFilter:tZ,addressU:tr,addressV:tr}),o=new nM({colorBuffer:n,depth:false}),l=mo.createShader(s,{uniqueName:"ShaderCoreExporterBlit",attributes:{vertex_position:sT},vertexChunk:"fullscreenQuadVS",fragmentChunk:"outputTex2DPS"});return s.scope.resolve("source").setValue(e),s.setBlendState(nu.NOBLEND),mg(s,o,l),n.read(0,0,r,a,{renderTarget:o,immediate:true}).then(e=>{n.destroy(),o.destroy();let t=new Uint8ClampedArray(r*a*4);t.set(e);let i=new ImageData(t,r,a),s=document.createElement("canvas");s.width=r,s.height=a;let l=s.getContext("2d");return l?(l.putImageData(i,0,0),Promise.resolve(s)):Promise.resolve(void 0)})}calcTextureSize(e,t,i){if(i){let s=Math.min(i/Math.max(e,t),1);e=Math.round(e*s),t=Math.round(t*s);}return {width:e,height:t}}}var Md=Uint8Array,Mu=Uint16Array,Mf=Int32Array,Mp=new Md([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Mm=new Md([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),M_=new Md([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Mg=function(e,t){for(var i=new Mu(31),s=0;s<31;++s)i[s]=t+=1<<e[s-1];for(var r=new Mf(i[30]),s=1;s<30;++s)for(var a=i[s];a<i[s+1];++a)r[a]=a-i[s]<<5|s;return {b:i,r:r}},Mv=Mg(Mp,2),MS=Mv.b,My=Mv.r;MS[28]=258,My[258]=28;for(var Mx=Mg(Mm,0).r,MT=new Mu(32768),ME=0;ME<32768;++ME){var MA=(43690&ME)>>1|(21845&ME)<<1;MA=(61680&(MA=(52428&MA)>>2|(13107&MA)<<2))>>4|(3855&MA)<<4,MT[ME]=((65280&MA)>>8|(255&MA)<<8)>>1;}for(var Mb=function(e,t,i){for(var s,r=e.length,a=0,n=new Mu(t);a<r;++a)e[a]&&++n[e[a]-1];var o=new Mu(t);for(a=1;a<t;++a)o[a]=o[a-1]+n[a-1]<<1;if(i){s=new Mu(1<<t);var l=15-t;for(a=0;a<r;++a)if(e[a])for(var h=a<<4|e[a],c=t-e[a],d=o[e[a]-1]++<<c,u=d|(1<<c)-1;d<=u;++d)s[MT[d]>>l]=h;}else for(a=0,s=new Mu(r);a<r;++a)e[a]&&(s[a]=MT[o[e[a]-1]++]>>15-e[a]);return s},Mw=new Md(288),ME=0;ME<144;++ME)Mw[ME]=8;for(var ME=144;ME<256;++ME)Mw[ME]=9;for(var ME=256;ME<280;++ME)Mw[ME]=7;for(var ME=280;ME<288;++ME)Mw[ME]=8;for(var MC=new Md(32),ME=0;ME<32;++ME)MC[ME]=5;var MP=Mb(Mw,9,0);Mb(Mw,9,1);var ML=Mb(MC,5,0);Mb(MC,5,1);var MI=function(e){return (e+7)/8|0},MD=function(e,t,i){return (null==i||i>e.length)&&(i=e.length),new Md(e.subarray(t,i))},MR=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],MM=function(e,t,i){var s=Error(t||MR[e]);if(s.code=e,Error.captureStackTrace&&Error.captureStackTrace(s,MM),!i)throw s;return s},MO=function(e,t,i){i<<=7&t;var s=t/8|0;e[s]|=i,e[s+1]|=i>>8;},MN=function(e,t,i){i<<=7&t;var s=t/8|0;e[s]|=i,e[s+1]|=i>>8,e[s+2]|=i>>16;},MF=function(e,t){for(var i=[],s=0;s<e.length;++s)e[s]&&i.push({s:s,f:e[s]});var r=i.length,a=i.slice();if(!r)return {t:MH,l:0};if(1==r){var n=new Md(i[0].s+1);return n[i[0].s]=1,{t:n,l:1}}i.sort(function(e,t){return e.f-t.f}),i.push({s:-1,f:25001});var o=i[0],l=i[1],h=0,c=1,d=2;for(i[0]={s:-1,f:o.f+l.f,l:o,r:l};c!=r-1;)o=i[i[h].f<i[d].f?h++:d++],l=i[h!=c&&i[h].f<i[d].f?h++:d++],i[c++]={s:-1,f:o.f+l.f,l:o,r:l};for(var u=a[0].s,s=1;s<r;++s)a[s].s>u&&(u=a[s].s);var f=new Mu(u+1),p=MB(i[c-1],f,0);if(p>t){var s=0,m=0,_=p-t,g=1<<_;for(a.sort(function(e,t){return f[t.s]-f[e.s]||e.f-t.f});s<r;++s){var v=a[s].s;if(f[v]>t)m+=g-(1<<p-f[v]),f[v]=t;else break}for(m>>=_;m>0;){var S=a[s].s;f[S]<t?m-=1<<t-f[S]++-1:++s;}for(;s>=0&&m;--s){var y=a[s].s;f[y]==t&&(--f[y],++m);}p=t;}return {t:new Md(f),l:p}},MB=function(e,t,i){return -1==e.s?Math.max(MB(e.l,t,i+1),MB(e.r,t,i+1)):t[e.s]=i},MU=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new Mu(++t),s=0,r=e[0],a=1,n=function(e){i[s++]=e;},o=1;o<=t;++o)if(e[o]==r&&o!=t)++a;else {if(!r&&a>2){for(;a>138;a-=138)n(32754);a>2&&(n(a>10?a-11<<5|28690:a-3<<5|12305),a=0);}else if(a>3){for(n(r),--a;a>6;a-=6)n(8304);a>2&&(n(a-3<<5|8208),a=0);}for(;a--;)n(r);a=1,r=e[o];}return {c:i.subarray(0,s),n:t}},Mk=function(e,t){for(var i=0,s=0;s<t.length;++s)i+=e[s]*t[s];return i},MV=function(e,t,i){var s=i.length,r=MI(t+2);e[r]=255&s,e[r+1]=s>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var a=0;a<s;++a)e[r+a+4]=i[a];return (r+4+s)*8},Mz=function(e,t,i,s,r,a,n,o,l,h,c){MO(t,c++,i),++r[256];for(var d,u,f,p,m=MF(r,15),_=m.t,g=m.l,v=MF(a,15),S=v.t,y=v.l,x=MU(_),T=x.c,E=x.n,A=MU(S),b=A.c,w=A.n,C=new Mu(19),P=0;P<T.length;++P)++C[31&T[P]];for(var P=0;P<b.length;++P)++C[31&b[P]];for(var L=MF(C,7),I=L.t,D=L.l,R=19;R>4&&!I[M_[R-1]];--R);var M=h+5<<3,O=Mk(r,Mw)+Mk(a,MC)+n,N=Mk(r,_)+Mk(a,S)+n+14+3*R+Mk(C,I)+2*C[16]+3*C[17]+7*C[18];if(l>=0&&M<=O&&M<=N)return MV(t,c,e.subarray(l,l+h));if(MO(t,c,1+(N<O)),c+=2,N<O){d=Mb(_,g,0),u=_,f=Mb(S,y,0),p=S;var F=Mb(I,D,0);MO(t,c,E-257),MO(t,c+5,w-1),MO(t,c+10,R-4),c+=14;for(var P=0;P<R;++P)MO(t,c+3*P,I[M_[P]]);c+=3*R;for(var B=[T,b],U=0;U<2;++U)for(var k=B[U],P=0;P<k.length;++P){var V=31&k[P];MO(t,c,F[V]),c+=I[V],V>15&&(MO(t,c,k[P]>>5&127),c+=k[P]>>12);}}else d=MP,u=Mw,f=ML,p=MC;for(var P=0;P<o;++P){var z=s[P];if(z>255){var V=z>>18&31;MN(t,c,d[V+257]),c+=u[V+257],V>7&&(MO(t,c,z>>23&31),c+=Mp[V]);var G=31&z;MN(t,c,f[G]),c+=p[G],G>3&&(MN(t,c,z>>5&8191),c+=Mm[G]);}else MN(t,c,d[z]),c+=u[z];}return MN(t,c,d[256]),c+u[256]},MG=new Mf([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),MH=new Md(0),MW=function(e,t,i,s,r,a){var n=a.z||e.length,o=new Md(s+n+5*(1+Math.ceil(n/7e3))+r),l=o.subarray(s,o.length-r),h=a.l,c=7&(a.r||0);if(t){c&&(l[0]=a.r>>3);for(var d=MG[t-1],u=d>>13,f=8191&d,p=(1<<i)-1,m=a.p||new Mu(32768),_=a.h||new Mu(p+1),g=Math.ceil(i/3),v=2*g,S=function(t){return (e[t]^e[t+1]<<g^e[t+2]<<v)&p},y=new Mf(25e3),x=new Mu(288),T=new Mu(32),E=0,A=0,b=a.i||0,w=0,C=a.w||0,P=0;b+2<n;++b){var L=S(b),I=32767&b,D=_[L];if(m[I]=D,_[L]=I,C<=b){var R=n-b;if((E>7e3||w>24576)&&(R>423||!h)){c=Mz(e,l,0,y,x,T,A,w,P,b-P,c),w=E=A=0,P=b;for(var M=0;M<286;++M)x[M]=0;for(var M=0;M<30;++M)T[M]=0;}var O=2,N=0,F=f,B=I-D&32767;if(R>2&&L==S(b-B))for(var U=Math.min(u,R)-1,k=Math.min(32767,b),V=Math.min(258,R);B<=k&&--F&&I!=D;){if(e[b+O]==e[b+O-B]){for(var z=0;z<V&&e[b+z]==e[b+z-B];++z);if(z>O){if(O=z,N=B,z>U)break;for(var G=Math.min(B,z-2),H=0,M=0;M<G;++M){var W=b-B+M&32767,X=m[W],Y=W-X&32767;Y>H&&(H=Y,D=W);}}}D=m[I=D],B+=I-D&32767;}if(N){y[w++]=0x10000000|My[O]<<18|Mx[N];var q=31&My[O],$=31&Mx[N];A+=Mp[q]+Mm[$],++x[257+q],++T[$],C=b+O,++E;}else y[w++]=e[b],++x[e[b]];}}for(b=Math.max(b,C);b<n;++b)y[w++]=e[b],++x[e[b]];c=Mz(e,l,h,y,x,T,A,w,P,b-P,c),h||(a.r=7&c|l[c/8|0]<<3,c-=7,a.h=_,a.p=m,a.i=b,a.w=C);}else {for(var b=a.w||0;b<n+h;b+=65535){var j=b+65535;j>=n&&(l[c/8|0]=h,j=n),c=MV(l,c+1,e.subarray(b,j));}a.i=n;}return MD(o,0,s+MI(c)+r)},MX=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var i=t,s=9;--s;)i=(1&i&&-306674912)^i>>>1;e[t]=i;}return e}(),MY=function(){var e=-1;return {p:function(t){for(var i=e,s=0;s<t.length;++s)i=MX[255&i^t[s]]^i>>>8;e=i;},d:function(){return ~e}}},Mq=function(e,t,i,s,r){if(!r&&(r={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),n=new Md(a.length+e.length);n.set(a),n.set(e,a.length),e=n,r.w=a.length;}return MW(e,null==t.level?6:t.level,null==t.mem?r.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,i,s,r)},M$=function(e,t){var i={};for(var s in e)i[s]=e[s];for(var s in t)i[s]=t[s];return i},Mj=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8;},MK=function(e,t,i,s){for(var r in e){var a=e[r],n=t+r,o=s;Array.isArray(a)&&(o=M$(s,a[1]),a=a[0]),a instanceof Md?i[n]=[a,o]:(i[n+="/"]=[new Md(0),o],MK(a,n,i,s));}},MZ="undefined"!=typeof TextEncoder&&new TextEncoder,MQ="undefined"!=typeof TextDecoder&&new TextDecoder;try{MQ.decode(MH,{stream:!0});}catch(e){}function MJ(e,t){if(MZ)return MZ.encode(e);for(var i,s=e.length,r=new Md(e.length+(e.length>>1)),a=0,n=function(e){r[a++]=e;},i=0;i<s;++i){if(a+5>r.length){var o=new Md(a+8+(s-i<<1));o.set(r),r=o;}var l=e.charCodeAt(i);l<128||t?n(l):(l<2048?n(192|l>>6):(l>55295&&l<57344?(n(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++i))>>18),n(128|l>>12&63)):n(224|l>>12),n(128|l>>6&63)),n(128|63&l));}return MD(r,0,a)}var M0=function(e){var t=0;if(e)for(var i in e){var s=e[i].length;s>65535&&MM(9),t+=s+4;}return t},M1=function(e,t,i,s,r,a,n,o){var l=s.length,h=i.extra,c=o&&o.length,d=M0(h);Mj(e,t,null!=n?0x2014b50:0x4034b50),t+=4,null!=n&&(e[t++]=20,e[t++]=i.os),e[t]=20,t+=2,e[t++]=i.flag<<1|(a<0&&8),e[t++]=r&&8,e[t++]=255&i.compression,e[t++]=i.compression>>8;var u=new Date(null==i.mtime?Date.now():i.mtime),f=u.getFullYear()-1980;if((f<0||f>119)&&MM(10),Mj(e,t,f<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),t+=4,-1!=a&&(Mj(e,t,i.crc),Mj(e,t+4,a<0?-a-2:a),Mj(e,t+8,i.size)),Mj(e,t+12,l),Mj(e,t+14,d),t+=16,null!=n&&(Mj(e,t,c),Mj(e,t+6,i.attrs),Mj(e,t+10,n),t+=14),e.set(s,t),t+=l,d)for(var p in h){var m=h[p],_=m.length;Mj(e,t,+p),Mj(e,t+2,_),e.set(m,t+4),t+=4+_;}return c&&(e.set(o,t),t+=c),t},M2=function(e,t,i,s,r){Mj(e,t,0x6054b50),Mj(e,t+8,i),Mj(e,t+10,i),Mj(e,t+12,s),Mj(e,t+16,r);};let M3="root",M4=`#usda 1.0
(
customLayerData = {
string creator = "PlayCanvas UsdzExporter"
}
metersPerUnit = 1
upAxis = "Y"
)
`,M5=e=>`
def "Materials"
{
${e.join("\n")}
}
`,M8=(e,t,i,s,r,a)=>`
def "Mesh"
{
def Mesh "Mesh"
{
int[] faceVertexCounts = [${e}]
int[] faceVertexIndices = [${t}]
normal3f[] normals = [${i}] (
interpolation = "vertex"
)
point3f[] points = [${s}]
texCoord2f[] primvars:st = [${r}] (
interpolation = "vertex"
)
texCoord2f[] primvars:st1 = [${a}] (
interpolation = "vertex"
)
uniform token subdivisionScheme = "none"
}
}
`,M6=(e,t,i,s)=>`
def Xform "${e}" (
prepend references = ${t}
)
{
matrix4d xformOp:transform = ${i}
uniform token[] xformOpOrder = ["xformOp:transform"]
rel material:binding = ${s}
}
`,M9=(e,t,i)=>` ${e} inputs:${t} = ${i}`;class M7 extends Mc{init(){this.meshMap=new Map,this.textureMap=new Map,this.materialMap=new Map,this.materials=[],this.files={},this.nodeNames=new Set;}done(){this.meshMap=null,this.textureMap=null,this.materialMap=null,this.materials=null,this.files=null,this.nodeNames=null;}build(e,t={}){this.init(),this.addFile(null,M3);let i=[];e&&e.findComponents("render").forEach(e=>{i.push(...e.meshInstances);});let s="";i.forEach(e=>{s+=this.buildMeshInstance(e);}),s+=M5(this.materials),this.addFile(null,M3,"",s);let r={maxTextureSize:t.maxTextureSize},a=Array.from(this.textureMap.keys()),n=[];for(let e=0;e<a.length;e++){let t=a[e],i=this.textureToCanvas(t,r).then(e=>e?new Promise(t=>e.toBlob(t,"image/png",1)).then(e=>e.arrayBuffer()):new Promise(e=>e(null)));n.push(i);}return Promise.all(n).then(e=>{e.forEach((e,t)=>{let i=a[t],s=this.getTextureFileIds(i);this.files[s.fileName]=new Uint8Array(e);}),this.alignFiles();let t=function(e,t){t||(t={});var i={},s=[];MK(e,"",i,t);var r=0,a=0;for(var n in i){var o=i[n],l=o[0],h=o[1],c=8*(0!=h.level),d=MJ(n),u=d.length,f=h.comment,p=f&&MJ(f),m=p&&p.length,_=M0(h.extra);u>65535&&MM(11);var g=c?Mq(l,h||{},0,0):l,v=g.length,S=MY();S.p(l),s.push(M$(h,{size:l.length,crc:S.d(),c:g,f:d,m:p,u:u!=n.length||p&&f.length!=m,o:r,compression:c})),r+=30+u+_+v,a+=76+2*(u+_)+(m||0)+v;}for(var y=new Md(a+22),x=r,T=a-r,E=0;E<s.length;++E){var d=s[E];M1(y,d.o,d,d.f,d.u,d.c.length);var A=30+d.f.length+M0(d.extra);y.set(d.c,d.o+A),M1(y,r,d,d.f,d.u,d.c.length,d.o,d.m),r+=16+A+(d.m?d.m.length:0);}return M2(y,r,s.length,T,x),y}(this.files,{level:0});return this.done(),t})}alignFiles(){let e=0;for(let t in this.files){let i=this.files[t],s=63&(e+=34+t.length);if(4!==s){let e=new Uint8Array(64-s);this.files[t]=[i,{extra:{12345:e}}];}e=i.length;}}getFileIds(e,t,i,s="usda"){let r=`${e?`${e}/`:""}${t}.${s}`,a=`@./${r}@</${i}>`;return {name:t,fileName:r,refName:a}}getTextureFileIds(e){return this.getFileIds("texture",`Texture_${e.id}`,"Texture","png")}addFile(e,t,i="",s=""){let r=null;s&&(r=MJ(s=`${M4}
${s}`));let a=this.getFileIds(e,t,i);return this.files[a.fileName]=r,a.refName}getMaterialRef(e){let t=this.materialMap.get(e);return t||(t=this.buildMaterial(e),this.materialMap.set(e,t)),t}getMeshRef(e){let t=this.meshMap.get(e);return t||(t=this.buildMesh(e),this.meshMap.set(e,t)),t}buildArray2(e){let t=[],i=e.length;for(let s=0;s<i;s+=2)t.push(`(${e[s]}, ${1-e[s+1]})`);return t.join(", ")}buildArray3(e){let t=[],i=e.length;for(let s=0;s<i;s+=3)t.push(`(${e[s]}, ${e[s+1]}, ${e[s+2]})`);return t.join(", ")}buildMat4(e){let t=e.data,i=[];for(let e=0;e<16;e+=4)i.push(`(${t[e]}, ${t[e+1]}, ${t[e+2]}, ${t[e+3]})`);return `( ${i.join(", ")} )`}buildMaterial(e){let t=`Material_${e.id}`,i=`/Materials/${t}`,s=e=>`<${i}${e}>`,r=(e,t,i,r,a,n,o,l)=>`
def Shader "Transform2d_${i}" (
sdrMetadata = {
string role = "math"
}
)
{
uniform token info:id = "UsdTransform2d"
float2 inputs:in.connect = ${s(`/uvReader_${r}.outputs:result`)}
float inputs:rotation = ${o}
float2 inputs:scale = (${a.x}, ${a.y})
float2 inputs:translation = (${n.x}, ${n.y})
float2 outputs:result
}
def Shader "Texture_${e.id}_${i}"
{
uniform token info:id = "UsdUVTexture"
asset inputs:file = @${t.fileName}@
float2 inputs:st.connect = ${s(`/Transform2d_${i}.outputs:result`)}
token inputs:wrapS = "repeat"
token inputs:wrapT = "repeat"
float4 inputs:scale = (${l.r}, ${l.g}, ${l.b}, ${l.a})
float outputs:r
float outputs:g
float outputs:b
float3 outputs:rgb
float outputs:a
}
`,a=[],n=[],o=(t,i,o,l,h,c=false,d=false)=>{let u=e[t];if(u){let f=this.getTextureFileIds(u);this.textureMap.set(u,f.refName);let p=e[`${t}Channel`]||"rgb",m=s(`/${f.name}_${h}.outputs:${p}`);a.push(M9(o,`${l}.connect`,m)),c&&e.alphaTest;let _=e[`${t}Tiling`],g=e[`${t}Offset`],v=e[`${t}Rotation`],S=1===e[`${t}Uv`]?"st1":"st",y=d&&i?i:eb.WHITE;n.push(r(u,f,h,S,_,g,v,y));}else if(i){let e="float"===o?`${i}`:`(${i.r}, ${i.g}, ${i.b})`;a.push(M9(o,l,e));}};o("diffuseMap",e.diffuse,"color3f","diffuseColor","diffuse",false,true),(e.transparent||e.alphaTest>0)&&o("opacityMap",e.opacity,"float","opacity","opacity",true),o("normalMap",null,"normal3f","normal","normal"),o("emissiveMap",e.emissive,"color3f","emissiveColor","emissive",false,true),o("aoMap",null,"float","occlusion","occlusion"),o("metalnessMap",e.metalness,"float","metallic","metallic"),o("glossMap",e.gloss,"float","roughness","roughness");let l=`
def Material "${t}"
{
def Shader "PreviewSurface"
{
uniform token info:id = "UsdPreviewSurface"
${a.join("\n")}
int inputs:useSpecularWorkflow = 0
token outputs:surface
}
token outputs:surface.connect = ${s("/PreviewSurface.outputs:surface")}
def Shader "uvReader_st"
{
uniform token info:id = "UsdPrimvarReader_float2"
token inputs:varname = "st"
float2 inputs:fallback = (0.0, 0.0)
float2 outputs:result
}
def Shader "uvReader_st1"
{
uniform token info:id = "UsdPrimvarReader_float2"
token inputs:varname = "st1"
float2 inputs:fallback = (0.0, 0.0)
float2 outputs:result
}
${n.join("\n")}
}
`;return this.materials.push(l),s("")}buildMesh(e){let t=[],i=[],s=[],r=[],a=[];e.getVertexStream(sT,t),e.getVertexStream(sE,s),e.getVertexStream(sL,r),e.getVertexStream(sI,a),e.getIndices(i);let n=i.length||t.length,o=Array(n/3).fill(3).join(", ");if(!i.length)for(let e=0;e<n;e++)i[e]=e;let l=t.length/3;s=s.length?s:Array(3*l).fill(0),r=r.length?r:Array(2*l).fill(0),a=a.length?a:Array(2*l).fill(0),t=this.buildArray3(t),s=this.buildArray3(s);let h=M8(o,i,s,t,r=this.buildArray2(r),a=this.buildArray2(a));return this.addFile("mesh",`Mesh_${e.id}`,"Mesh",h)}buildMeshInstance(e){let t=this.getMeshRef(e.mesh),i=this.getMaterialRef(e.material),s=this.buildMat4(e.node.getWorldTransform()),r=e.node.name.replace(/[^a-z0-9]/gi,"_"),a=r;for(;this.nodeNames.has(a);)a=`${r}_${Math.random().toString(36).slice(2,7)}`;return this.nodeNames.add(a),M6(a,t,s,i)}}let Oe=e=>{switch(e){case ie:return 5121;case it:return 5123;case ii:return 5125}return 0},Ot=e=>{switch(e){case rC:return 5120;case rP:return 5121;case rL:return 5122;case rI:return 5123;case rD:return 5124;case rR:return 5125;case rM:return 5126}return 0},Oi=e=>{switch(e){case 1:return "SCALAR";case 2:return "VEC2";case 3:return "VEC3";case 4:return "VEC4"}return 0},Os=e=>{switch(e){case sT:return "POSITION";case sE:return "NORMAL";case sA:return "TANGENT";case sC:return "COLOR_0";case sw:return "JOINTS_0";case sb:return "WEIGHTS_0";case sL:return "TEXCOORD_0";case sI:return "TEXCOORD_1";case sD:return "TEXCOORD_2";case sR:return "TEXCOORD_3";case sM:return "TEXCOORD_4";case sO:return "TEXCOORD_5";case sN:return "TEXCOORD_6";case sF:return "TEXCOORD_7"}return ""},Or=function(e){switch(e){case tK:return 9728;case tZ:return 9729;case tQ:return 9984;case t0:return 9985;case tJ:return 9986;case t1:return 9987}return 0},Oa=function(e){switch(e){case tr:return 33071;case ta:return 33648;case ts:return 10497}return 0},On=["diffuseMap","colorMap","normalMap","metalnessMap","emissiveMap"];class Oo extends Mc{collectResources(e){let t={buffers:[],cameras:[],entities:[],materials:[],skins:[],textures:[],entityMeshInstances:[],bufferViewMap:new Map,compressableTexture:new Set},{materials:i,buffers:s,entityMeshInstances:r,textures:a}=t;e.forEach(e=>{t.entities.push(e);});let n=e=>{e.forEach(e=>{let n=e.material;0>i.indexOf(n)&&(t.materials.push(n),On.forEach(e=>{let i=n[e];i&&0>a.indexOf(i)&&("normalMap"!==e&&t.compressableTexture.add(i),a.push(i));}));let o=e.node,l=r.find(e=>e.node===o);l||(l={node:o,meshInstances:[]},r.push(l)),l.meshInstances.push(e);let h=e.mesh,c=h.vertexBuffer;0>s.indexOf(c)&&s.unshift(c);let d=h.indexBuffer[0];0>s.indexOf(d)&&s.push(d),h.skin&&0>t.skins.indexOf(h.skin)&&t.skins.push(h.skin);});};return t.entities.forEach(e=>{e.camera&&t.cameras.push(e.camera),e.render&&e.render.enabled&&n(e.render.meshInstances),e.model&&e.model.enabled&&e.model.meshInstances&&n(e.model.meshInstances);}),t}writeBufferViews(e,t){for(let i of(t.bufferViews=[],e.buffers))Oo.writeBufferView(e,t,i);}static writeBufferView(e,t,i){let s;t.buffers=t.buffers??[],t.buffers[0]=t.buffers[0]??{byteLength:0};let r=t.buffers[0];r.byteLength=eA.roundUp(r.byteLength,4);let a=r.byteLength,n=(e,i,s,r)=>{let a={buffer:0,byteLength:i,byteOffset:s};return (34962===e||34963===e)&&(a.target=e),void 0!==r&&(a.byteStride=r),t.bufferViews.push(a)-1};if(i instanceof nT){s=i.lock();let t=i.getFormat();if(t.interleaved){let r=n(34962,s.byteLength,a,t.size);e.bufferViewMap.set(i,[r]);}else {let s=[];for(let e of t.elements){let i=n(34962,e.size*t.vertexCount,a+e.offset,e.size);s.push(i);}e.bufferViewMap.set(i,s);}}else if(i instanceof lJ){let t=n(34963,(s=i.lock()).byteLength,a);e.bufferViewMap.set(i,[t]);}else {let t=n(void 0,(s=i).byteLength,a);e.bufferViewMap.set(i,[t]);}r.byteLength+=s.byteLength;}writeCameras(e,t){e.cameras.length>0&&(t.cameras=e.cameras.map(e=>{let t=e.projection,i=e.nearClip,s=e.farClip,r={};if(t===fm)r.type="orthographic",r.orthographic={xmag:1,ymag:1,znear:i,zfar:s};else {let t=e.fov;r.type="perspective",r.perspective={yfov:t*Math.PI/180,znear:i,zfar:s};}return r}));}attachTexture(e,t,i,s,r,a){let n=t[r];if(n){let o=e.textures.indexOf(n);i[s]={index:o};let l=t[`${r}Tiling`],h=t[`${r}Offset`],c=t[`${r}Rotation`];(l&&!l.equals(eN.ONE)||h&&!h.equals(eN.ZERO)||0!==c)&&(i[s].extensions={KHR_texture_transform:{}},a.extensionsUsed=a.extensionsUsed??[],0>a.extensionsUsed.indexOf("KHR_texture_transform")&&a.extensionsUsed.push("KHR_texture_transform"),a.extensionsRequired=a.extensionsRequired??[],0>a.extensionsRequired.indexOf("KHR_texture_transform")&&a.extensionsRequired.push("KHR_texture_transform"),l&&!l.equals(eN.ONE)&&(i[s].extensions.KHR_texture_transform.scale=[l.x,l.y]),h&&!h.equals(eN.ZERO)&&(i[s].extensions.KHR_texture_transform.offset=[h.x,h.y-1+l.y]),0!==c&&(i[s].extensions.KHR_texture_transform.rotation=c*eA.DEG_TO_RAD));}}writeStandardMaterial(e,t,i,s){let{diffuse:r,emissive:a,opacity:n,metalness:o,gloss:l,glossInvert:h}=t,c=i.pbrMetallicRoughness;r.equals(eb.WHITE)&&1===n||(c.baseColorFactor=[r.r,r.g,r.b,n]),1!==o&&(c.metallicFactor=o);let d=h?l:1-l;1!==d&&(c.roughnessFactor=d),this.attachTexture(e,t,c,"baseColorTexture","diffuseMap",s),this.attachTexture(e,t,c,"metallicRoughnessTexture","metalnessMap",s),a.equals(eb.BLACK)||(i.emissiveFactor=[a.r,a.g,a.b]);}writeMaterials(e,t){e.materials.length>0&&(t.materials=e.materials.map(i=>{let{name:s,blendType:r,cull:a,alphaTest:n}=i,o={pbrMetallicRoughness:{}};return s&&s.length>0&&(o.name=s),i instanceof yo&&this.writeStandardMaterial(e,i,o,t),r===ua?o.alphaMode="BLEND":r===un&&0!==n&&(o.alphaMode="MASK",o.alphaCutoff=n),a===tY&&(o.doubleSided=true),this.attachTexture(e,i,o,"normalTexture","normalMap",t),this.attachTexture(e,i,o,"occlusionTexture","aoMap",t),this.attachTexture(e,i,o,"emissiveTexture","emissiveMap",t),o}));}writeNodes(e,t){e.entities.length>0&&(t.nodes=e.entities.map(t=>{let i=t.name,s=t.getLocalPosition(),r=t.getLocalRotation(),a=t.getLocalScale(),n={};i&&i.length>0&&(n.name=i),s.equals(eM.ZERO)||(n.translation=[s.x,s.y,s.z]),r.equals(eH.IDENTITY)||(n.rotation=[r.x,r.y,r.z,r.w]),a.equals(eM.ONE)||(n.scale=[a.x,a.y,a.z]),t.camera&&t.camera.enabled&&(n.camera=e.cameras.indexOf(t.camera));let o=e.entityMeshInstances.find(e=>e.node===t);if(o){n.mesh=e.entityMeshInstances.indexOf(o);let t=o.meshInstances[0];t&&t.mesh.skin&&(n.skin=e.skins.indexOf(t.mesh.skin));}return t.children.length>0&&(n.children=[],t.children.forEach(t=>{n.children.push(e.entities.indexOf(t));})),n}));}writeMeshes(e,t,i){e.entityMeshInstances.length>0&&(t.accessors=[],t.meshes=[],e.entityMeshInstances.forEach(s=>{let r={primitives:[]};s.meshInstances.forEach(s=>{let a=Oo.createPrimitive(e,t,s.mesh,i);a.material=e.materials.indexOf(s.material),r.primitives.push(a);}),t.meshes.push(r);}));}static createPrimitive(e,t,i,s={}){let r={attributes:{}},{vertexBuffer:a}=i,{format:n}=a,{interleaved:o,elements:l}=n,h=a.getNumVertices();l.forEach((n,l)=>{let c=Os(n.name);if(s.stripUnusedAttributes){let t=true;if(c.startsWith("TEXCOORD_")){let i=parseInt(c.split("_")[1],10);t=e.materials.some(e=>On.some(t=>e[t]&&(0===i||e[`${t}Tiling`]?.uv===i)));}if("COLOR_0"===c&&(t=e.materials.some(e=>e.vertexColors)),"TANGENT"===c&&(t=e.materials.some(e=>e.normalMap)),("JOINTS_0"===c||"WEIGHTS_0"===c)&&(t=e.entityMeshInstances.some(e=>e.meshInstances.some(e=>e.mesh.skin))),!t)return}let d=e.bufferViewMap.get(a);d||(Oo.writeBufferView(e,t,a),e.buffers.push(a),d=e.bufferViewMap.get(a));let u={bufferView:d[o?0:l],byteOffset:o?n.offset:0,componentType:Ot(n.dataType),type:Oi(n.numComponents),count:h},f=t.accessors.push(u)-1;if(r.attributes[c]=f,n.name===sT){let e=[];i.getPositions(e);let t=new eM,s=new eM;ej.computeMinMax(e,t,s),u.min=[t.x,t.y,t.z],u.max=[s.x,s.y,s.z];}});let c=i.indexBuffer[0];if(c){let i=e.bufferViewMap.get(c);i||(Oo.writeBufferView(e,t,c),e.buffers.push(c),i=e.bufferViewMap.get(c));let s={bufferView:i[0],componentType:Oe(c.getFormat()),count:c.getNumIndices(),type:"SCALAR"};r.indices=t.accessors.push(s)-1;}return r}writeSkins(e,t){e.skins.length>0&&(t.skins=e.skins.map(i=>{let s=new Float32Array(16*i.inverseBindPose.length);for(let e=0;e<i.inverseBindPose.length;e++){let t=i.inverseBindPose[e];s.set(t.data,16*e);}let r=s.buffer;Oo.writeBufferView(e,t,r),e.buffers.push(r);let a={bufferView:e.bufferViewMap.get(r)[0],componentType:Ot(rM),count:i.inverseBindPose.length,type:"MAT4"};return {inverseBindMatrices:t.accessors.push(a)-1,joints:i.boneNames.map(t=>{let i=e.entities.find(e=>e.name===t);return e.entities.indexOf(i)})}}));}convertTextures(e,t){let i={maxTextureSize:t.maxTextureSize},s=[];return e.forEach(e=>{let t=this.textureToCanvas(e,i);t.then(e=>new Promise(t=>t(e))),s.push(t);}),s}writeTextures(e,t,i,s){let r=e.textures,a=[];for(let s=0;s<t.length;s++){let n=r[s],o=t[s],l=function(e){let t=e.getContext("2d").getImageData(0,0,e.width,e.height).data;for(let e=3;e<t.length;e+=4)if(t[e]<255)return true;return false}(o)||!e.compressableTexture.has(n)?"image/png":"image/jpeg";a.push(this.getBlob(o,l).then(e=>{let t=new FileReader;return t.readAsArrayBuffer(e),new Promise(e=>{t.onloadend=()=>{e(t);};})}).then(t=>{let r=this.getPaddedArrayBuffer(t.result);Oo.writeBufferView(e,i,r),e.buffers.push(r);let a=e.bufferViewMap.get(r);i.images[s]={mimeType:l,bufferView:a[0]},i.samplers[s]={minFilter:Or(n.minFilter),magFilter:Or(n.magFilter),wrapS:Oa(n.addressU),wrapT:Oa(n.addressV)},i.textures[s]={sampler:s,source:s};}));}return Promise.all(a)}getBlob(e,t){if(void 0!==e.toBlob)return new Promise(i=>{e.toBlob(i,t);});let i=1;return "image/jpeg"===t&&(i=.92),e.convertToBlob({type:t,quality:i})}getPaddedArrayBuffer(e,t=0){let i=eA.roundUp(e.byteLength,4);if(i!==e.byteLength){let s=new Uint8Array(i);if(s.set(new Uint8Array(e)),0!==t)for(let r=e.byteLength;r<i;r++)s[r]=t;return s.buffer}return e}buildJson(e,t){return Promise.all(this.convertTextures(e.textures,t)).then(async i=>{let s={asset:{version:"2.0",generator:"PlayCanvas GltfExporter"},scenes:[{nodes:[0]}],images:[],samplers:[],textures:[],scene:0};return this.writeBufferViews(e,s),this.writeCameras(e,s),this.writeMeshes(e,s,t),this.writeMaterials(e,s),this.writeNodes(e,s,t),this.writeSkins(e,s),await this.writeTextures(e,i,s,t),s.images.length||delete s.images,s.samplers.length||delete s.samplers,s.textures.length||delete s.textures,s})}build(e,t={}){let i=this.collectResources(e);return this.buildJson(i,t).then(e=>{let t=new TextEncoder().encode(JSON.stringify(e)),s=t.length,r=4-(3&s)&3,a=e.buffers.reduce((e,t)=>eA.roundUp(e+t.byteLength,4),0),n=20+s+r;a>0&&(n+=8+a);let o=new ArrayBuffer(n),l=new DataView(o);l.setUint32(0,0x46546c67,true),l.setUint32(4,2,true),l.setUint32(8,n,true),l.setUint32(12,s+r,true),l.setUint32(16,0x4e4f534a,true);let h=20;new Uint8Array(o,20,s).set(t),h+=s;for(let e=0;e<r;e++)l.setUint8(h+e,32);return h+=r,a>0&&(l.setUint32(h,a,true),l.setUint32(h+4,5130562,true),h+=8,i.buffers.forEach(t=>{let s,r=i.bufferViewMap.get(t)[0],a=e.bufferViews[r].byteOffset;if(t instanceof ArrayBuffer)s=new Uint8Array(t);else {let e=t.lock();s=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);}new Uint8Array(o,h+a,s.byteLength).set(s);})),Promise.resolve(o)})}}let Ol="none",Oh="lighting",Oc="combine";var Od=`
uniform sampler2D sourceTexture;
uniform vec2 sourceInvResolution;
varying vec2 uv0;
#ifdef PREMULTIPLY
uniform sampler2D premultiplyTexture;
#endif
void main()
{
vec3 e = texture2D (sourceTexture, uv0).rgb;
#ifdef BOXFILTER
vec3 value = e;
#ifdef PREMULTIPLY
float premultiply = texture2D(premultiplyTexture, uv0).{PREMULTIPLY_SRC_CHANNEL};
value *= vec3(premultiply);
#endif
#else
float x = sourceInvResolution.x;
float y = sourceInvResolution.y;
vec3 a = texture2D(sourceTexture, vec2 (uv0.x - 2.0 * x, uv0.y + 2.0 * y)).rgb;
vec3 b = texture2D(sourceTexture, vec2 (uv0.x, uv0.y + 2.0 * y)).rgb;
vec3 c = texture2D(sourceTexture, vec2 (uv0.x + 2.0 * x, uv0.y + 2.0 * y)).rgb;
vec3 d = texture2D(sourceTexture, vec2 (uv0.x - 2.0 * x, uv0.y)).rgb;
vec3 f = texture2D(sourceTexture, vec2 (uv0.x + 2.0 * x, uv0.y)).rgb;
vec3 g = texture2D(sourceTexture, vec2 (uv0.x - 2.0 * x, uv0.y - 2.0 * y)).rgb;
vec3 h = texture2D(sourceTexture, vec2 (uv0.x, uv0.y - 2.0 * y)).rgb;
vec3 i = texture2D(sourceTexture, vec2 (uv0.x + 2.0 * x, uv0.y - 2.0 * y)).rgb;
vec3 j = texture2D(sourceTexture, vec2 (uv0.x - x, uv0.y + y)).rgb;
vec3 k = texture2D(sourceTexture, vec2 (uv0.x + x, uv0.y + y)).rgb;
vec3 l = texture2D(sourceTexture, vec2 (uv0.x - x, uv0.y - y)).rgb;
vec3 m = texture2D(sourceTexture, vec2 (uv0.x + x, uv0.y - y)).rgb;
vec3 value = e * 0.125;
value += (a + c + g + i) * 0.03125;
value += (b + d + f + h) * 0.0625;
value += (j + k + l + m) * 0.125;
#endif
#ifdef REMOVE_INVALID
value = max(value, vec3(0.0));
#endif
gl_FragColor = vec4(value, 1.0);
}
`,Ou=`
var sourceTexture: texture_2d<f32>;
var sourceTextureSampler: sampler;
uniform sourceInvResolution: vec2f;
varying uv0: vec2f;
#ifdef PREMULTIPLY
var premultiplyTexture: texture_2d<f32>;
var premultiplyTextureSampler: sampler;
#endif
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let e: vec3f = textureSample(sourceTexture, sourceTextureSampler, input.uv0).rgb;
#ifdef BOXFILTER
var value: vec3f = e;
#ifdef PREMULTIPLY
let premultiply: f32 = textureSample(premultiplyTexture, premultiplyTextureSampler, input.uv0).{PREMULTIPLY_SRC_CHANNEL};
value = value * vec3f(premultiply);
#endif
#else
let x: f32 = uniform.sourceInvResolution.x;
let y: f32 = uniform.sourceInvResolution.y;
let a: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - 2.0 * x, input.uv0.y + 2.0 * y)).rgb;
let b: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x, input.uv0.y + 2.0 * y)).rgb;
let c: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + 2.0 * x, input.uv0.y + 2.0 * y)).rgb;
let d: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - 2.0 * x, input.uv0.y)).rgb;
let f: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + 2.0 * x, input.uv0.y)).rgb;
let g: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - 2.0 * x, input.uv0.y - 2.0 * y)).rgb;
let h: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x, input.uv0.y - 2.0 * y)).rgb;
let i: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + 2.0 * x, input.uv0.y - 2.0 * y)).rgb;
let j: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - x, input.uv0.y + y)).rgb;
let k: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + x, input.uv0.y + y)).rgb;
let l: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - x, input.uv0.y - y)).rgb;
let m: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + x, input.uv0.y - y)).rgb;
var value: vec3f = e * 0.125;
value = value + (a + c + g + i) * 0.03125;
value = value + (b + d + f + h) * 0.0625;
value = value + (j + k + l + m) * 0.125;
#endif
#ifdef REMOVE_INVALID
value = max(value, vec3f(0.0));
#endif
output.color = vec4f(value, 1.0);
return output;
}
`;class Of extends SW{constructor(e,t,i={}){super(e),this.sourceTexture=t,this.premultiplyTexture=i.premultiplyTexture,mr.get(e,rb).set("downsamplePS",Od),mr.get(e,rw).set("downsamplePS",Ou);let s=i.boxFilter??false,r=`${s?"Box":""}-${i.premultiplyTexture?"Premultiply":""}-${i.premultiplySrcChannel??""}-${i.removeInvalid?"RemoveInvalid":""}`,a=new Map;s&&a.set("BOXFILTER",""),i.premultiplyTexture&&a.set("PREMULTIPLY",""),i.removeInvalid&&a.set("REMOVE_INVALID",""),a.set("{PREMULTIPLY_SRC_CHANNEL}",i.premultiplySrcChannel??"x"),this.shader=mo.createShader(e,{uniqueName:`DownSampleShader:${r}`,attributes:{aPosition:sT},vertexChunk:"quadVS",fragmentChunk:"downsamplePS",fragmentDefines:a}),this.sourceTextureId=e.scope.resolve("sourceTexture"),this.premultiplyTextureId=e.scope.resolve("premultiplyTexture"),this.sourceInvResolutionId=e.scope.resolve("sourceInvResolution"),this.sourceInvResolutionValue=new Float32Array(2);}setSourceTexture(e){this._sourceTexture=e,this.options.resizeSource=e;}execute(){this.sourceTextureId.setValue(this.sourceTexture),this.premultiplyTexture&&this.premultiplyTextureId.setValue(this.premultiplyTexture),this.sourceInvResolutionValue[0]=1/this.sourceTexture.width,this.sourceInvResolutionValue[1]=1/this.sourceTexture.height,this.sourceInvResolutionId.setValue(this.sourceInvResolutionValue),super.execute();}}var Op=`
uniform sampler2D sourceTexture;
uniform vec2 sourceInvResolution;
varying vec2 uv0;
void main()
{
float x = sourceInvResolution.x;
float y = sourceInvResolution.y;
vec3 a = texture2D (sourceTexture, vec2 (uv0.x - x, uv0.y + y)).rgb;
vec3 b = texture2D (sourceTexture, vec2 (uv0.x, uv0.y + y)).rgb;
vec3 c = texture2D (sourceTexture, vec2 (uv0.x + x, uv0.y + y)).rgb;
vec3 d = texture2D (sourceTexture, vec2 (uv0.x - x, uv0.y)).rgb;
vec3 e = texture2D (sourceTexture, vec2 (uv0.x, uv0.y)).rgb;
vec3 f = texture2D (sourceTexture, vec2 (uv0.x + x, uv0.y)).rgb;
vec3 g = texture2D (sourceTexture, vec2 (uv0.x - x, uv0.y - y)).rgb;
vec3 h = texture2D (sourceTexture, vec2 (uv0.x, uv0.y - y)).rgb;
vec3 i = texture2D (sourceTexture, vec2 (uv0.x + x, uv0.y - y)).rgb;
vec3 value = e * 4.0;
value += (b + d + f + h) * 2.0;
value += (a + c + g + i);
value *= 1.0 / 16.0;
gl_FragColor = vec4(value, 1.0);
}
`,Om=`
var sourceTexture: texture_2d<f32>;
var sourceTextureSampler: sampler;
uniform sourceInvResolution: vec2f;
varying uv0: vec2f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let x: f32 = uniform.sourceInvResolution.x;
let y: f32 = uniform.sourceInvResolution.y;
let a: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - x, input.uv0.y + y)).rgb;
let b: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x, input.uv0.y + y)).rgb;
let c: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + x, input.uv0.y + y)).rgb;
let d: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - x, input.uv0.y)).rgb;
let e: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x, input.uv0.y)).rgb;
let f: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + x, input.uv0.y)).rgb;
let g: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - x, input.uv0.y - y)).rgb;
let h: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x, input.uv0.y - y)).rgb;
let i: vec3f = textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + x, input.uv0.y - y)).rgb;
var value: vec3f = e * 4.0;
value = value + (b + d + f + h) * 2.0;
value = value + (a + c + g + i);
value = value * (1.0 / 16.0);
output.color = vec4f(value, 1.0);
return output;
}
`;class O_ extends SW{constructor(e,t){super(e),this.sourceTexture=t,mr.get(e,rb).set("upsamplePS",Op),mr.get(e,rw).set("upsamplePS",Om),this.shader=mo.createShader(e,{uniqueName:"UpSampleShader",attributes:{aPosition:sT},vertexChunk:"quadVS",fragmentChunk:"upsamplePS"}),this.sourceTextureId=e.scope.resolve("sourceTexture"),this.sourceInvResolutionId=e.scope.resolve("sourceInvResolution"),this.sourceInvResolutionValue=new Float32Array(2);}execute(){this.sourceTextureId.setValue(this.sourceTexture),this.sourceInvResolutionValue[0]=1/this.sourceTexture.width,this.sourceInvResolutionValue[1]=1/this.sourceTexture.height,this.sourceInvResolutionId.setValue(this.sourceInvResolutionValue),super.execute();}}class Og extends l2{constructor(e,t,i){super(e),this.blurLevel=16,this.renderTargets=[],this._sourceTexture=t,this.textureFormat=i,this.bloomRenderTarget=this.createRenderTarget(0),this.bloomTexture=this.bloomRenderTarget.colorBuffer;}destroy(){this.destroyRenderPasses(),this.destroyRenderTargets();}destroyRenderTargets(e=0){for(let t=e;t<this.renderTargets.length;t++){let e=this.renderTargets[t];e.destroyTextureBuffers(),e.destroy();}this.renderTargets.length=0;}destroyRenderPasses(){for(let e=0;e<this.beforePasses.length;e++)this.beforePasses[e].destroy();this.beforePasses.length=0;}createRenderTarget(e){return new nM({depth:false,colorBuffer:new ns(this.device,{name:`BloomTexture${e}`,width:1,height:1,format:this.textureFormat,mipmaps:false,minFilter:tZ,magFilter:tZ,addressU:tr,addressV:tr})})}createRenderTargets(e){for(let t=0;t<e;t++){let e=0===t?this.bloomRenderTarget:this.createRenderTarget(t);this.renderTargets.push(e);}}calcMipLevels(e,t,i){return Math.floor(Math.log2(Math.min(e,t))-Math.log2(i))}createRenderPasses(e){let t=this.device,i=this._sourceTexture;for(let s=0;s<e;s++){let e=new Of(t,i),r=this.renderTargets[s];e.init(r,{resizeSource:i,scaleX:.5,scaleY:.5}),e.setClearColor(eb.BLACK),this.beforePasses.push(e),i=r.colorBuffer;}i=this.renderTargets[e-1].colorBuffer;for(let s=e-2;s>=0;s--){let e=new O_(t,i),r=this.renderTargets[s];e.init(r),e.blendState=nu.ADDBLEND,this.beforePasses.push(e),i=r.colorBuffer;}}onDisable(){this.renderTargets[0]?.resize(1,1),this.destroyRenderPasses(),this.destroyRenderTargets(1);}frameUpdate(){super.frameUpdate();let e=this.calcMipLevels(this._sourceTexture.width,this._sourceTexture.height,1),t=eA.clamp(e,1,this.blurLevel);this.renderTargets.length!==t&&(this.destroyRenderPasses(),this.destroyRenderTargets(1),this.createRenderTargets(t),this.createRenderPasses(t));}}let Ov={composePS:`
#include "tonemappingPS"
#include "gammaPS"
varying vec2 uv0;
uniform sampler2D sceneTexture;
uniform vec2 sceneTextureInvRes;
#include "composeBloomPS"
#include "composeDofPS"
#include "composeSsaoPS"
#include "composeGradingPS"
#include "composeVignettePS"
#include "composeFringingPS"
#include "composeCasPS"
#include "composeColorLutPS"
void main() {
vec2 uv = uv0;
#ifdef TAA
#ifdef WEBGPU
uv.y = 1.0 - uv.y;
#endif
#endif
vec4 scene = texture2DLod(sceneTexture, uv, 0.0);
vec3 result = scene.rgb;
#ifdef CAS
result = applyCas(result, uv, sharpness);
#endif
#ifdef DOF
result = applyDof(result, uv0);
#endif
#ifdef SSAO_TEXTURE
result = applySsao(result, uv0);
#endif
#ifdef FRINGING
result = applyFringing(result, uv);
#endif
#ifdef BLOOM
result = applyBloom(result, uv0);
#endif
#ifdef GRADING
result = applyGrading(result);
#endif
result = toneMap(max(vec3(0.0), result));
#ifdef COLOR_LUT
result = applyColorLUT(result);
#endif
#ifdef VIGNETTE
result = applyVignette(result, uv);
#endif
#ifdef DEBUG_COMPOSE
#if DEBUG_COMPOSE == scene
result = scene.rgb;
#elif defined(BLOOM) && DEBUG_COMPOSE == bloom
result = dBloom * bloomIntensity;
#elif defined(DOF) && DEBUG_COMPOSE == dofcoc
result = vec3(dCoc, 0.0);
#elif defined(DOF) && DEBUG_COMPOSE == dofblur
result = dBlur;
#elif defined(SSAO_TEXTURE) && DEBUG_COMPOSE == ssao
result = vec3(dSsao);
#elif defined(VIGNETTE) && DEBUG_COMPOSE == vignette
result = vec3(dVignette);
#endif
#endif
result = gammaCorrectOutput(result);
gl_FragColor = vec4(result, scene.a);
}
`,composeBloomPS:`
#ifdef BLOOM
uniform sampler2D bloomTexture;
uniform float bloomIntensity;
vec3 dBloom;
vec3 applyBloom(vec3 color, vec2 uv) {
dBloom = texture2DLod(bloomTexture, uv, 0.0).rgb;
return color + dBloom * bloomIntensity;
}
#endif
`,composeDofPS:`
#ifdef DOF
uniform sampler2D cocTexture;
uniform sampler2D blurTexture;
vec2 dCoc;
vec3 dBlur;
vec3 getDofBlur(vec2 uv) {
dCoc = texture2DLod(cocTexture, uv, 0.0).rg;
#if DOF_UPSCALE
vec2 blurTexelSize = 1.0 / vec2(textureSize(blurTexture, 0));
vec3 bilinearBlur = vec3(0.0);
float totalWeight = 0.0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
vec2 offset = vec2(i, j) * blurTexelSize;
vec2 cocSample = texture2DLod(cocTexture, uv + offset, 0.0).rg;
vec3 blurSample = texture2DLod(blurTexture, uv + offset, 0.0).rgb;
float cocWeight = clamp(cocSample.r + cocSample.g, 0.0, 1.0);
bilinearBlur += blurSample * cocWeight;
totalWeight += cocWeight;
}
}
if (totalWeight > 0.0) {
bilinearBlur /= totalWeight;
}
dBlur = bilinearBlur;
return bilinearBlur;
#else
dBlur = texture2DLod(blurTexture, uv, 0.0).rgb;
return dBlur;
#endif
}
vec3 applyDof(vec3 color, vec2 uv) {
vec3 blur = getDofBlur(uv);
return mix(color, blur, dCoc.r + dCoc.g);
}
#endif
`,composeSsaoPS:`
#ifdef SSAO
#define SSAO_TEXTURE
#endif
#if DEBUG_COMPOSE == ssao
#define SSAO_TEXTURE
#endif
#ifdef SSAO_TEXTURE
uniform sampler2D ssaoTexture;
float dSsao;
vec3 applySsao(vec3 color, vec2 uv) {
dSsao = texture2DLod(ssaoTexture, uv, 0.0).r;
#ifdef SSAO
return color * dSsao;
#else
return color;
#endif
}
#endif
`,composeGradingPS:`
#ifdef GRADING
uniform vec3 brightnessContrastSaturation;
uniform vec3 tint;
vec3 colorGradingHDR(vec3 color, float brt, float sat, float con) {
color *= tint;
color = color * brt;
float grey = dot(color, vec3(0.3, 0.59, 0.11));
grey = grey / max(1.0, max(color.r, max(color.g, color.b)));
color = mix(vec3(grey), color, sat);
return mix(vec3(0.5), color, con);
}
vec3 applyGrading(vec3 color) {
return colorGradingHDR(color,
brightnessContrastSaturation.x,
brightnessContrastSaturation.z,
brightnessContrastSaturation.y);
}
#endif
`,composeVignettePS:`
#ifdef VIGNETTE
uniform vec4 vignetterParams;
float dVignette;
float calcVignette(vec2 uv) {
float inner = vignetterParams.x;
float outer = vignetterParams.y;
float curvature = vignetterParams.z;
float intensity = vignetterParams.w;
vec2 curve = pow(abs(uv * 2.0 -1.0), vec2(1.0 / curvature));
float edge = pow(length(curve), curvature);
dVignette = 1.0 - intensity * smoothstep(inner, outer, edge);
return dVignette;
}
vec3 applyVignette(vec3 color, vec2 uv) {
return color * calcVignette(uv);
}
#endif
`,composeFringingPS:`
#ifdef FRINGING
uniform float fringingIntensity;
vec3 applyFringing(vec3 color, vec2 uv) {
vec2 centerDistance = uv - 0.5;
vec2 offset = fringingIntensity * pow(centerDistance, vec2(2.0, 2.0));
color.r = texture2D(sceneTexture, uv - offset).r;
color.b = texture2D(sceneTexture, uv + offset).b;
return color;
}
#endif
`,composeCasPS:`
#ifdef CAS
uniform float sharpness;
float maxComponent(float x, float y, float z) { return max(x, max(y, z)); }
vec3 toSDR(vec3 c) { return c / (1.0 + maxComponent(c.r, c.g, c.b)); }
vec3 toHDR(vec3 c) { return c / (1.0 - maxComponent(c.r, c.g, c.b)); }
vec3 applyCas(vec3 color, vec2 uv, float sharpness) {
float x = sceneTextureInvRes.x;
float y = sceneTextureInvRes.y;
vec3 a = toSDR(texture2DLod(sceneTexture, uv + vec2(0.0, -y), 0.0).rgb);
vec3 b = toSDR(texture2DLod(sceneTexture, uv + vec2(-x, 0.0), 0.0).rgb);
vec3 c = toSDR(color.rgb);
vec3 d = toSDR(texture2DLod(sceneTexture, uv + vec2(x, 0.0), 0.0).rgb);
vec3 e = toSDR(texture2DLod(sceneTexture, uv + vec2(0.0, y), 0.0).rgb);
float min_g = min(a.g, min(b.g, min(c.g, min(d.g, e.g))));
float max_g = max(a.g, max(b.g, max(c.g, max(d.g, e.g))));
float sharpening_amount = sqrt(min(1.0 - max_g, min_g) / max_g);
float w = sharpening_amount * sharpness;
vec3 res = (w * (a + b + d + e) + c) / (4.0 * w + 1.0);
res = max(res, 0.0);
return toHDR(res);
}
#endif
`,composeColorLutPS:`
#ifdef COLOR_LUT
uniform sampler2D colorLUT;
uniform vec4 colorLUTParams;
vec3 applyColorLUT(vec3 color) {
vec3 c = clamp(color, 0.0, 1.0);
float width = colorLUTParams.x;
float height = colorLUTParams.y;
float maxColor = colorLUTParams.z;
float cell = c.b * maxColor;
float cell_l = floor(cell);
float cell_h = ceil(cell);
float half_px_x = 0.5 / width;
float half_px_y = 0.5 / height;
float r_offset = half_px_x + c.r / height * (maxColor / height);
float g_offset = half_px_y + c.g * (maxColor / height);
vec2 uv_l = vec2(cell_l / height + r_offset, g_offset);
vec2 uv_h = vec2(cell_h / height + r_offset, g_offset);
vec3 color_l = texture2DLod(colorLUT, uv_l, 0.0).rgb;
vec3 color_h = texture2DLod(colorLUT, uv_h, 0.0).rgb;
vec3 lutColor = mix(color_l, color_h, fract(cell));
return mix(color, lutColor, colorLUTParams.w);
}
#endif
`},OS={composePS:`
#include "tonemappingPS"
#include "gammaPS"
varying uv0: vec2f;
var sceneTexture: texture_2d<f32>;
var sceneTextureSampler: sampler;
uniform sceneTextureInvRes: vec2f;
#include "composeBloomPS"
#include "composeDofPS"
#include "composeSsaoPS"
#include "composeGradingPS"
#include "composeVignettePS"
#include "composeFringingPS"
#include "composeCasPS"
#include "composeColorLutPS"
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
var uv = uv0;
#ifdef TAA
uv.y = 1.0 - uv.y;
#endif
let scene = textureSampleLevel(sceneTexture, sceneTextureSampler, uv, 0.0);
var result = scene.rgb;
#ifdef CAS
result = applyCas(result, uv, uniform.sharpness);
#endif
#ifdef DOF
result = applyDof(result, uv0);
#endif
#ifdef SSAO_TEXTURE
result = applySsao(result, uv0);
#endif
#ifdef FRINGING
result = applyFringing(result, uv);
#endif
#ifdef BLOOM
result = applyBloom(result, uv0);
#endif
#ifdef GRADING
result = applyGrading(result);
#endif
result = toneMap(max(vec3f(0.0), result));
#ifdef COLOR_LUT
result = applyColorLUT(result);
#endif
#ifdef VIGNETTE
result = applyVignette(result, uv);
#endif
#ifdef DEBUG_COMPOSE
#if DEBUG_COMPOSE == scene
result = scene.rgb;
#elif defined(BLOOM) && DEBUG_COMPOSE == bloom
result = dBloom * uniform.bloomIntensity;
#elif defined(DOF) && DEBUG_COMPOSE == dofcoc
result = vec3f(dCoc, 0.0);
#elif defined(DOF) && DEBUG_COMPOSE == dofblur
result = dBlur;
#elif defined(SSAO_TEXTURE) && DEBUG_COMPOSE == ssao
result = vec3f(dSsao);
#elif defined(VIGNETTE) && DEBUG_COMPOSE == vignette
result = vec3f(dVignette);
#endif
#endif
result = gammaCorrectOutput(result);
output.color = vec4f(result, scene.a);
return output;
}
`,composeBloomPS:`
#ifdef BLOOM
var bloomTexture: texture_2d<f32>;
var bloomTextureSampler: sampler;
uniform bloomIntensity: f32;
var<private> dBloom: vec3f;
fn applyBloom(color: vec3f, uv: vec2f) -> vec3f {
dBloom = textureSampleLevel(bloomTexture, bloomTextureSampler, uv, 0.0).rgb;
return color + dBloom * uniform.bloomIntensity;
}
#endif
`,composeDofPS:`
#ifdef DOF
var cocTexture: texture_2d<f32>;
var cocTextureSampler: sampler;
var blurTexture: texture_2d<f32>;
var blurTextureSampler: sampler;
var<private> dCoc: vec2f;
var<private> dBlur: vec3f;
fn getDofBlur(uv: vec2f) -> vec3f {
dCoc = textureSampleLevel(cocTexture, cocTextureSampler, uv, 0.0).rg;
#if DOF_UPSCALE
let blurTexelSize = 1.0 / vec2f(textureDimensions(blurTexture, 0));
var bilinearBlur = vec3f(0.0);
var totalWeight = 0.0;
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
let offset = vec2f(f32(i), f32(j)) * blurTexelSize;
let cocSample = textureSampleLevel(cocTexture, cocTextureSampler, uv + offset, 0.0).rg;
let blurSample = textureSampleLevel(blurTexture, blurTextureSampler, uv + offset, 0.0).rgb;
let cocWeight = clamp(cocSample.r + cocSample.g, 0.0, 1.0);
bilinearBlur += blurSample * cocWeight;
totalWeight += cocWeight;
}
}
if (totalWeight > 0.0) {
bilinearBlur /= totalWeight;
}
dBlur = bilinearBlur;
return bilinearBlur;
#else
dBlur = textureSampleLevel(blurTexture, blurTextureSampler, uv, 0.0).rgb;
return dBlur;
#endif
}
fn applyDof(color: vec3f, uv: vec2f) -> vec3f {
let blur = getDofBlur(uv);
return mix(color, blur, dCoc.r + dCoc.g);
}
#endif
`,composeSsaoPS:`
#ifdef SSAO
#define SSAO_TEXTURE
#endif
#if DEBUG_COMPOSE == ssao
#define SSAO_TEXTURE
#endif
#ifdef SSAO_TEXTURE
var ssaoTexture: texture_2d<f32>;
var ssaoTextureSampler: sampler;
var<private> dSsao: f32;
fn applySsao(color: vec3f, uv: vec2f) -> vec3f {
dSsao = textureSampleLevel(ssaoTexture, ssaoTextureSampler, uv, 0.0).r;
#ifdef SSAO
return color * dSsao;
#else
return color;
#endif
}
#endif
`,composeGradingPS:`
#ifdef GRADING
uniform brightnessContrastSaturation: vec3f;
uniform tint: vec3f;
fn colorGradingHDR(color: vec3f, brt: f32, sat: f32, con: f32) -> vec3f {
var colorOut = color * uniform.tint;
colorOut = colorOut * brt;
let grey = dot(colorOut, vec3f(0.3, 0.59, 0.11));
let normalizedGrey = grey / max(1.0, max(colorOut.r, max(colorOut.g, colorOut.b)));
colorOut = mix(vec3f(normalizedGrey), colorOut, sat);
return mix(vec3f(0.5), colorOut, con);
}
fn applyGrading(color: vec3f) -> vec3f {
return colorGradingHDR(color,
uniform.brightnessContrastSaturation.x,
uniform.brightnessContrastSaturation.z,
uniform.brightnessContrastSaturation.y);
}
#endif
`,composeVignettePS:`
#ifdef VIGNETTE
uniform vignetterParams: vec4f;
var<private> dVignette: f32;
fn calcVignette(uv: vec2f) -> f32 {
let inner = uniform.vignetterParams.x;
let outer = uniform.vignetterParams.y;
let curvature = uniform.vignetterParams.z;
let intensity = uniform.vignetterParams.w;
let curve = pow(abs(uv * 2.0 - 1.0), vec2f(1.0 / curvature));
let edge = pow(length(curve), curvature);
dVignette = 1.0 - intensity * smoothstep(inner, outer, edge);
return dVignette;
}
fn applyVignette(color: vec3f, uv: vec2f) -> vec3f {
return color * calcVignette(uv);
}
#endif
`,composeFringingPS:`
#ifdef FRINGING
uniform fringingIntensity: f32;
fn applyFringing(color: vec3f, uv: vec2f) -> vec3f {
let centerDistance = uv - 0.5;
let offset = uniform.fringingIntensity * pow(centerDistance, vec2f(2.0));
var colorOut = color;
colorOut.r = textureSample(sceneTexture, sceneTextureSampler, uv - offset).r;
colorOut.b = textureSample(sceneTexture, sceneTextureSampler, uv + offset).b;
return colorOut;
}
#endif
`,composeCasPS:`
#ifdef CAS
uniform sharpness: f32;
fn maxComponent(x: f32, y: f32, z: f32) -> f32 { return max(x, max(y, z)); }
fn toSDR(c: vec3f) -> vec3f { return c / (1.0 + maxComponent(c.r, c.g, c.b)); }
fn toHDR(c: vec3f) -> vec3f { return c / (1.0 - maxComponent(c.r, c.g, c.b)); }
fn applyCas(color: vec3f, uv: vec2f, sharpness: f32) -> vec3f {
let x = uniform.sceneTextureInvRes.x;
let y = uniform.sceneTextureInvRes.y;
let a = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(0.0, -y), 0.0).rgb);
let b = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(-x, 0.0), 0.0).rgb);
let c = toSDR(color.rgb);
let d = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(x, 0.0), 0.0).rgb);
let e = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(0.0, y), 0.0).rgb);
let min_g = min(a.g, min(b.g, min(c.g, min(d.g, e.g))));
let max_g = max(a.g, max(b.g, max(c.g, max(d.g, e.g))));
let sharpening_amount = sqrt(min(1.0 - max_g, min_g) / max_g);
let w = sharpening_amount * uniform.sharpness;
var res = (w * (a + b + d + e) + c) / (4.0 * w + 1.0);
res = max(res, vec3f(0.0));
return toHDR(res);
}
#endif
`,composeColorLutPS:`
#ifdef COLOR_LUT
var colorLUT: texture_2d<f32>;
var colorLUTSampler: sampler;
uniform colorLUTParams: vec4f;
fn applyColorLUT(color: vec3f) -> vec3f {
var c: vec3f = clamp(color, vec3f(0.0), vec3f(1.0));
let width: f32 = uniform.colorLUTParams.x;
let height: f32 = uniform.colorLUTParams.y;
let maxColor: f32 = uniform.colorLUTParams.z;
let cell: f32 = c.b * maxColor;
let cell_l: f32 = floor(cell);
let cell_h: f32 = ceil(cell);
let half_px_x: f32 = 0.5 / width;
let half_px_y: f32 = 0.5 / height;
let r_offset: f32 = half_px_x + c.r / height * (maxColor / height);
let g_offset: f32 = half_px_y + c.g * (maxColor / height);
let uv_l: vec2f = vec2f(cell_l / height + r_offset, g_offset);
let uv_h: vec2f = vec2f(cell_h / height + r_offset, g_offset);
let color_l: vec3f = textureSampleLevel(colorLUT, colorLUTSampler, uv_l, 0.0).rgb;
let color_h: vec3f = textureSampleLevel(colorLUT, colorLUTSampler, uv_h, 0.0).rgb;
let lutColor: vec3f = mix(color_l, color_h, fract(cell));
return mix(color, lutColor, uniform.colorLUTParams.w);
}
#endif
`};class Oy extends SW{constructor(e){super(e),this.sceneTexture=null,this.bloomIntensity=.01,this._bloomTexture=null,this._cocTexture=null,this.blurTexture=null,this.blurTextureUpscale=false,this._ssaoTexture=null,this._toneMapping=fD,this._gradingEnabled=false,this.gradingSaturation=1,this.gradingContrast=1,this.gradingBrightness=1,this.gradingTint=new eb(1,1,1,1),this._shaderDirty=true,this._vignetteEnabled=false,this.vignetteInner=.5,this.vignetteOuter=1,this.vignetteCurvature=.5,this.vignetteIntensity=.3,this._fringingEnabled=false,this.fringingIntensity=10,this._taaEnabled=false,this._sharpness=.5,this._gammaCorrection=fL,this._colorLUT=null,this.colorLUTIntensity=1,this._key="",this._debug=null,mr.get(e,rb).add(Ov),mr.get(e,rw).add(OS);let{scope:t}=e;this.sceneTextureId=t.resolve("sceneTexture"),this.bloomTextureId=t.resolve("bloomTexture"),this.cocTextureId=t.resolve("cocTexture"),this.ssaoTextureId=t.resolve("ssaoTexture"),this.blurTextureId=t.resolve("blurTexture"),this.bloomIntensityId=t.resolve("bloomIntensity"),this.bcsId=t.resolve("brightnessContrastSaturation"),this.tintId=t.resolve("tint"),this.vignetterParamsId=t.resolve("vignetterParams"),this.fringingIntensityId=t.resolve("fringingIntensity"),this.sceneTextureInvResId=t.resolve("sceneTextureInvRes"),this.sceneTextureInvResValue=new Float32Array(2),this.sharpnessId=t.resolve("sharpness"),this.colorLUTId=t.resolve("colorLUT"),this.colorLUTParams=new Float32Array(4),this.colorLUTParamsId=t.resolve("colorLUTParams");}set debug(e){this._debug!==e&&(this._debug=e,this._shaderDirty=true);}get debug(){return this._debug}set colorLUT(e){this._colorLUT!==e&&(this._colorLUT=e,this._shaderDirty=true);}get colorLUT(){return this._colorLUT}set bloomTexture(e){this._bloomTexture!==e&&(this._bloomTexture=e,this._shaderDirty=true);}get bloomTexture(){return this._bloomTexture}set cocTexture(e){this._cocTexture!==e&&(this._cocTexture=e,this._shaderDirty=true);}get cocTexture(){return this._cocTexture}set ssaoTexture(e){this._ssaoTexture!==e&&(this._ssaoTexture=e,this._shaderDirty=true);}get ssaoTexture(){return this._ssaoTexture}set taaEnabled(e){this._taaEnabled!==e&&(this._taaEnabled=e,this._shaderDirty=true);}get taaEnabled(){return this._taaEnabled}set gradingEnabled(e){this._gradingEnabled!==e&&(this._gradingEnabled=e,this._shaderDirty=true);}get gradingEnabled(){return this._gradingEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._shaderDirty=true);}get vignetteEnabled(){return this._vignetteEnabled}set fringingEnabled(e){this._fringingEnabled!==e&&(this._fringingEnabled=e,this._shaderDirty=true);}get fringingEnabled(){return this._fringingEnabled}set toneMapping(e){this._toneMapping!==e&&(this._toneMapping=e,this._shaderDirty=true);}get toneMapping(){return this._toneMapping}set sharpness(e){this._sharpness!==e&&(this._sharpness=e,this._shaderDirty=true);}get sharpness(){return this._sharpness}get isSharpnessEnabled(){return this._sharpness>0}postInit(){this.setClearColor(eb.BLACK),this.setClearDepth(1),this.setClearStencil(0);}frameUpdate(){let e=(this.renderTarget??this.device.backBuffer).isColorBufferSrgb(0)?fP:fL;if(this._gammaCorrection!==e&&(this._gammaCorrection=e,this._shaderDirty=true),this._shaderDirty){this._shaderDirty=false;let e=fI[this._gammaCorrection],t=`${this.toneMapping}-${e}-${this.bloomTexture?"bloom":"nobloom"}-${this.cocTexture?"dof":"nodof"}-${this.blurTextureUpscale?"dofupscale":""}-${this.ssaoTexture?"ssao":"nossao"}-${this.gradingEnabled?"grading":"nograding"}-${this.colorLUT?"colorlut":"nocolorlut"}-${this.vignetteEnabled?"vignette":"novignette"}-${this.fringingEnabled?"fringing":"nofringing"}-${this.taaEnabled?"taa":"notaa"}-${this.isSharpnessEnabled?"cas":"nocas"}-${this._debug??""}`;if(this._key!==t){this._key=t;let i=new Map;i.set("TONEMAP",fU[this.toneMapping]),i.set("GAMMA",e),this.bloomTexture&&i.set("BLOOM",true),this.cocTexture&&i.set("DOF",true),this.blurTextureUpscale&&i.set("DOF_UPSCALE",true),this.ssaoTexture&&i.set("SSAO",true),this.gradingEnabled&&i.set("GRADING",true),this.colorLUT&&i.set("COLOR_LUT",true),this.vignetteEnabled&&i.set("VIGNETTE",true),this.fringingEnabled&&i.set("FRINGING",true),this.taaEnabled&&i.set("TAA",true),this.isSharpnessEnabled&&i.set("CAS",true),this._debug&&i.set("DEBUG_COMPOSE",this._debug);let s=new Map(mr.get(this.device,this.device.isWebGPU?rw:rb));this.shader=mo.createShader(this.device,{uniqueName:`ComposeShader-${t}`,attributes:{aPosition:sT},vertexChunk:"quadVS",fragmentChunk:"composePS",fragmentDefines:i,fragmentIncludes:s});}}}execute(){this.sceneTextureId.setValue(this.sceneTexture),this.sceneTextureInvResValue[0]=1/this.sceneTexture.width,this.sceneTextureInvResValue[1]=1/this.sceneTexture.height,this.sceneTextureInvResId.setValue(this.sceneTextureInvResValue),this._bloomTexture&&(this.bloomTextureId.setValue(this._bloomTexture),this.bloomIntensityId.setValue(this.bloomIntensity)),this._cocTexture&&(this.cocTextureId.setValue(this._cocTexture),this.blurTextureId.setValue(this.blurTexture)),this._ssaoTexture&&this.ssaoTextureId.setValue(this._ssaoTexture),this._gradingEnabled&&(this.bcsId.setValue([this.gradingBrightness,this.gradingContrast,this.gradingSaturation]),this.tintId.setValue([this.gradingTint.r,this.gradingTint.g,this.gradingTint.b]));let e=this._colorLUT;e&&(this.colorLUTParams[0]=e.width,this.colorLUTParams[1]=e.height,this.colorLUTParams[2]=e.height-1,this.colorLUTParams[3]=this.colorLUTIntensity,this.colorLUTParamsId.setValue(this.colorLUTParams),this.colorLUTId.setValue(e)),this._vignetteEnabled&&this.vignetterParamsId.setValue([this.vignetteInner,this.vignetteOuter,this.vignetteCurvature,this.vignetteIntensity]),this._fringingEnabled&&this.fringingIntensityId.setValue(this.fringingIntensity/1024),this.isSharpnessEnabled&&this.sharpnessId.setValue(eA.lerp(-0.125,-0.2,this.sharpness)),super.execute();}}var Ox=`
vec4 SampleTextureCatmullRom(TEXTURE_ACCEPT(tex), vec2 uv, vec2 texSize) {
vec2 samplePos = uv * texSize;
vec2 texPos1 = floor(samplePos - 0.5) + 0.5;
vec2 f = samplePos - texPos1;
vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f));
vec2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f);
vec2 w2 = f * (0.5 + f * (2.0 - 1.5 * f));
vec2 w3 = f * f * (-0.5 + 0.5 * f);
vec2 w12 = w1 + w2;
vec2 offset12 = w2 / (w1 + w2);
vec2 texPos0 = (texPos1 - 1.0) / texSize;
vec2 texPos3 = (texPos1 + 2.0) / texSize;
vec2 texPos12 = (texPos1 + offset12) / texSize;
vec4 result = vec4(0.0);
result += texture2DLod(tex, vec2(texPos0.x, texPos0.y), 0.0) * w0.x * w0.y;
result += texture2DLod(tex, vec2(texPos12.x, texPos0.y), 0.0) * w12.x * w0.y;
result += texture2DLod(tex, vec2(texPos3.x, texPos0.y), 0.0) * w3.x * w0.y;
result += texture2DLod(tex, vec2(texPos0.x, texPos12.y), 0.0) * w0.x * w12.y;
result += texture2DLod(tex, vec2(texPos12.x, texPos12.y), 0.0) * w12.x * w12.y;
result += texture2DLod(tex, vec2(texPos3.x, texPos12.y), 0.0) * w3.x * w12.y;
result += texture2DLod(tex, vec2(texPos0.x, texPos3.y), 0.0) * w0.x * w3.y;
result += texture2DLod(tex, vec2(texPos12.x, texPos3.y), 0.0) * w12.x * w3.y;
result += texture2DLod(tex, vec2(texPos3.x, texPos3.y), 0.0) * w3.x * w3.y;
return result;
}
`,OT=`
fn SampleTextureCatmullRom(tex: texture_2d<f32>, texSampler: sampler, uv: vec2f, texSize: vec2f) -> vec4f {
let samplePos: vec2f = uv * texSize;
let texPos1: vec2f = floor(samplePos - 0.5) + 0.5;
let f: vec2f = samplePos - texPos1;
let w0: vec2f = f * (-0.5 + f * (1.0 - 0.5 * f));
let w1: vec2f = 1.0 + f * f * (-2.5 + 1.5 * f);
let w2: vec2f = f * (0.5 + f * (2.0 - 1.5 * f));
let w3: vec2f = f * f * (-0.5 + 0.5 * f);
let w12: vec2f = w1 + w2;
let offset12: vec2f = w2 / w12;
let texPos0: vec2f = (texPos1 - 1.0) / texSize;
let texPos3: vec2f = (texPos1 + 2.0) / texSize;
let texPos12: vec2f = (texPos1 + offset12) / texSize;
var result: vec4f = vec4f(0.0);
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos0.x, texPos0.y), 0.0) * w0.x * w0.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos12.x, texPos0.y), 0.0) * w12.x * w0.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos3.x, texPos0.y), 0.0) * w3.x * w0.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos0.x, texPos12.y), 0.0) * w0.x * w12.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos12.x, texPos12.y), 0.0) * w12.x * w12.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos3.x, texPos12.y), 0.0) * w3.x * w12.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos0.x, texPos3.y), 0.0) * w0.x * w3.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos12.x, texPos3.y), 0.0) * w12.x * w3.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos3.x, texPos3.y), 0.0) * w3.x * w3.y;
return result;
}
`,OE=`
#include "sampleCatmullRomPS"
#include "screenDepthPS"
uniform sampler2D sourceTexture;
uniform sampler2D historyTexture;
uniform mat4 matrix_viewProjectionPrevious;
uniform mat4 matrix_viewProjectionInverse;
uniform vec4 jitters;
uniform vec2 textureSize;
varying vec2 uv0;
vec2 reproject(vec2 uv, float depth) {
#ifndef WEBGPU
depth = depth * 2.0 - 1.0;
#endif
vec4 ndc = vec4(uv * 2.0 - 1.0, depth, 1.0);
ndc.xy -= jitters.xy;
vec4 worldPosition = matrix_viewProjectionInverse * ndc;
worldPosition /= worldPosition.w;
vec4 screenPrevious = matrix_viewProjectionPrevious * worldPosition;
return (screenPrevious.xy / screenPrevious.w) * 0.5 + 0.5;
}
vec4 colorClamp(vec2 uv, vec4 historyColor) {
vec3 minColor = vec3(9999.0);
vec3 maxColor = vec3(-9999.0);
for(float x = -1.0; x <= 1.0; ++x) {
for(float y = -1.0; y <= 1.0; ++y) {
vec3 color = texture2D(sourceTexture, uv + vec2(x, y) / textureSize).rgb;
minColor = min(minColor, color);
maxColor = max(maxColor, color);
}
}
vec3 clamped = clamp(historyColor.rgb, minColor, maxColor);
return vec4(clamped, historyColor.a);
}
void main()
{
vec2 uv = uv0;
#ifdef WEBGPU
uv.y = 1.0 - uv.y;
#endif
vec4 srcColor = texture2D(sourceTexture, uv);
float linearDepth = getLinearScreenDepth(uv0);
float depth = delinearizeDepth(linearDepth);
vec2 historyUv = reproject(uv0, depth);
#ifdef QUALITY_HIGH
vec4 historyColor = SampleTextureCatmullRom(TEXTURE_PASS(historyTexture), historyUv, textureSize);
#else
vec4 historyColor = texture2D(historyTexture, historyUv);
#endif
vec4 historyColorClamped = colorClamp(uv, historyColor);
float mixFactor = (historyUv.x < 0.0 || historyUv.x > 1.0 || historyUv.y < 0.0 || historyUv.y > 1.0) ?
1.0 : 0.05;
gl_FragColor = mix(historyColorClamped, srcColor, mixFactor);
}
`,OA=`
#include "sampleCatmullRomPS"
#include "screenDepthPS"
var sourceTexture: texture_2d<f32>;
var sourceTextureSampler: sampler;
var historyTexture: texture_2d<f32>;
var historyTextureSampler: sampler;
uniform matrix_viewProjectionPrevious: mat4x4f;
uniform matrix_viewProjectionInverse: mat4x4f;
uniform jitters: vec4f;
uniform textureSize: vec2f;
varying uv0: vec2f;
fn reproject(uv: vec2f, depth: f32) -> vec2f {
var ndc = vec4f(uv * 2.0 - 1.0, depth, 1.0);
ndc = vec4f(ndc.xy - uniform.jitters.xy, ndc.zw);
var worldPosition = uniform.matrix_viewProjectionInverse * ndc;
worldPosition = worldPosition / worldPosition.w;
let screenPrevious = uniform.matrix_viewProjectionPrevious * worldPosition;
return (screenPrevious.xy / screenPrevious.w) * 0.5 + 0.5;
}
fn colorClamp(uv: vec2f, historyColor: vec4f) -> vec4f {
var minColor = vec3f(9999.0);
var maxColor = vec3f(-9999.0);
for (var ix: i32 = -1; ix <= 1; ix = ix + 1) {
for (var iy: i32 = -1; iy <= 1; iy = iy + 1) {
let color_sample = textureSample(sourceTexture, sourceTextureSampler, uv + vec2f(f32(ix), f32(iy)) / uniform.textureSize).rgb;
minColor = min(minColor, color_sample);
maxColor = max(maxColor, color_sample);
}
}
let clamped = clamp(historyColor.rgb, minColor, maxColor);
return vec4f(clamped, historyColor.a);
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
var uv = input.uv0;
uv.y = 1.0 - uv.y;
let srcColor = textureSample(sourceTexture, sourceTextureSampler, uv);
let linearDepth = getLinearScreenDepth(uv0);
let depth = delinearizeDepth(linearDepth);
let historyUv = reproject(uv0, depth);
#ifdef QUALITY_HIGH
var historyColor: vec4f = SampleTextureCatmullRom(historyTexture, historyTextureSampler, historyUv, uniform.textureSize);
#else
var historyColor: vec4f = textureSample(historyTexture, historyTextureSampler, historyUv);
#endif
let historyColorClamped = colorClamp(uv, historyColor);
let mixFactor_condition = historyUv.x < 0.0 || historyUv.x > 1.0 || historyUv.y < 0.0 || historyUv.y > 1.0;
let mixFactor = select(0.05, 1.0, mixFactor_condition);
output.color = mix(historyColorClamped, srcColor, mixFactor);
return output;
}
`;class Ob extends SW{constructor(e,t,i){super(e),this.historyIndex=0,this.historyTexture=null,this.historyTextures=[],this.historyRenderTargets=[],this.sourceTexture=t,this.cameraComponent=i,mr.get(e,rb).set("sampleCatmullRomPS",Ox),mr.get(e,rw).set("sampleCatmullRomPS",OT),mr.get(e,rb).set("taaResolvePS",OE),mr.get(e,rw).set("taaResolvePS",OA);let s=new Map;s.set("QUALITY_HIGH",true),mo.addScreenDepthChunkDefines(e,i.shaderParams,s),this.shader=mo.createShader(e,{uniqueName:"TaaResolveShader",attributes:{aPosition:sT},vertexChunk:"quadVS",fragmentChunk:"taaResolvePS",fragmentDefines:s});let{scope:r}=e;this.sourceTextureId=r.resolve("sourceTexture"),this.textureSizeId=r.resolve("textureSize"),this.textureSize=new Float32Array(2),this.historyTextureId=r.resolve("historyTexture"),this.viewProjPrevId=r.resolve("matrix_viewProjectionPrevious"),this.viewProjInvId=r.resolve("matrix_viewProjectionInverse"),this.jittersId=r.resolve("jitters"),this.cameraParams=new Float32Array(4),this.cameraParamsId=r.resolve("camera_params"),this.setup();}destroy(){this.renderTarget&&(this.renderTarget.destroyTextureBuffers(),this.renderTarget.destroy(),this.renderTarget=null);}setup(){for(let e=0;e<2;++e)this.historyTextures[e]=new ns(this.device,{name:`TAA-History-${e}`,width:4,height:4,format:this.sourceTexture.format,mipmaps:false,minFilter:tZ,magFilter:tZ,addressU:tr,addressV:tr}),this.historyRenderTargets[e]=new nM({colorBuffer:this.historyTextures[e],depth:false});this.historyTexture=this.historyTextures[0],this.init(this.historyRenderTargets[0],{resizeSource:this.sourceTexture});}before(){this.sourceTextureId.setValue(this.sourceTexture),this.historyTextureId.setValue(this.historyTextures[1-this.historyIndex]),this.textureSize[0]=this.sourceTexture.width,this.textureSize[1]=this.sourceTexture.height,this.textureSizeId.setValue(this.textureSize);let e=this.cameraComponent.camera;this.viewProjPrevId.setValue(e._viewProjPrevious.data),this.viewProjInvId.setValue(e._viewProjInverse.data),this.jittersId.setValue(e._jitters);let t=e._farClip;this.cameraParams[0]=1/t,this.cameraParams[1]=t,this.cameraParams[2]=e._nearClip,this.cameraParams[3]=+(e.projection===fm),this.cameraParamsId.setValue(this.cameraParams);}update(){return this.historyIndex=1-this.historyIndex,this.historyTexture=this.historyTextures[this.historyIndex],this.renderTarget=this.historyRenderTargets[this.historyIndex],this.historyTexture}}var Ow=`
#include "screenDepthPS"
varying vec2 uv0;
uniform vec3 params;
void main()
{
float depth = getLinearScreenDepth(uv0);
float focusDistance = params.x;
float focusRange = params.y;
float invRange = params.z;
float farRange = focusDistance + focusRange * 0.5;
float cocFar = min((depth - farRange) * invRange, 1.0);
#ifdef NEAR_BLUR
float nearRange = focusDistance - focusRange * 0.5;
float cocNear = min((nearRange - depth) * invRange, 1.0);
#else
float cocNear = 0.0;
#endif
gl_FragColor = vec4(cocFar, cocNear, 0.0, 0.0);
}
`,OC=`
#include "screenDepthPS"
varying uv0: vec2f;
uniform params: vec3f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let depth: f32 = getLinearScreenDepth(uv0);
let focusDistance: f32 = uniform.params.x;
let focusRange: f32 = uniform.params.y;
let invRange: f32 = uniform.params.z;
let farRange: f32 = focusDistance + focusRange * 0.5;
let cocFar: f32 = min((depth - farRange) * invRange, 1.0);
#ifdef NEAR_BLUR
let nearRange: f32 = focusDistance - focusRange * 0.5;
var cocNear: f32 = min((nearRange - depth) * invRange, 1.0);
#else
var cocNear: f32 = 0.0;
#endif
output.color = vec4f(cocFar, cocNear, 0.0, 0.0);
return output;
}
`;class OP extends SW{constructor(e,t,i){super(e),this.cameraComponent=t,mr.get(e,rb).set("cocPS",Ow),mr.get(e,rw).set("cocPS",OC);let s=new Map;i&&s.set("NEAR_BLUR",""),mo.addScreenDepthChunkDefines(e,t.shaderParams,s),this.shader=mo.createShader(e,{uniqueName:`CocShader-${i}`,attributes:{aPosition:sT},vertexChunk:"quadVS",fragmentChunk:"cocPS",fragmentDefines:s}),this.paramsId=e.scope.resolve("params"),this.paramsValue=new Float32Array(3),this.cameraParams=new Float32Array(4),this.cameraParamsId=e.scope.resolve("camera_params");}execute(){let{paramsValue:e,focusRange:t}=this;e[0]=this.focusDistance+.001,e[1]=t,e[2]=1/t,this.paramsId.setValue(e);let i=this.cameraComponent.camera,s=i._farClip;this.cameraParams[0]=1/s,this.cameraParams[1]=s,this.cameraParams[2]=i._nearClip,this.cameraParams[3]=+(i.projection===fm),this.cameraParamsId.setValue(this.cameraParams),super.execute();}}var OL=`
#if defined(NEAR_BLUR)
uniform sampler2D nearTexture;
#endif
uniform sampler2D farTexture;
uniform sampler2D cocTexture;
uniform vec2 kernel[{KERNEL_COUNT}];
uniform float blurRadiusNear;
uniform float blurRadiusFar;
varying vec2 uv0;
void main()
{
vec2 coc = texture2D(cocTexture, uv0).rg;
float cocFar = coc.r;
vec3 sum = vec3(0.0, 0.0, 0.0);
#if defined(NEAR_BLUR)
float cocNear = coc.g;
if (cocNear > 0.0001) {
ivec2 nearTextureSize = textureSize(nearTexture, 0);
vec2 step = cocNear * blurRadiusNear / vec2(nearTextureSize);
for (int i = 0; i < {KERNEL_COUNT}; i++) {
vec2 uv = uv0 + step * kernel[i];
vec3 tap = texture2DLod(nearTexture, uv, 0.0).rgb;
sum += tap.rgb;
}
sum *= float({INV_KERNEL_COUNT});
} else
#endif
if (cocFar > 0.0001) {
ivec2 farTextureSize = textureSize(farTexture, 0);
vec2 step = cocFar * blurRadiusFar / vec2(farTextureSize);
float sumCoC = 0.0;
for (int i = 0; i < {KERNEL_COUNT}; i++) {
vec2 uv = uv0 + step * kernel[i];
vec3 tap = texture2DLod(farTexture, uv, 0.0).rgb;
float cocThis = texture2DLod(cocTexture, uv, 0.0).r;
tap *= cocThis;
sumCoC += cocThis;
sum += tap;
}
if (sumCoC > 0.0)
sum /= sumCoC;
sum /= cocFar;
}
pcFragColor0 = vec4(sum, 1.0);
}
`,OI=`
#if defined(NEAR_BLUR)
var nearTexture: texture_2d<f32>;
var nearTextureSampler: sampler;
#endif
var farTexture: texture_2d<f32>;
var farTextureSampler: sampler;
var cocTexture: texture_2d<f32>;
var cocTextureSampler: sampler;
uniform kernel: array<vec2f, {KERNEL_COUNT}>;
uniform blurRadiusNear: f32;
uniform blurRadiusFar: f32;
varying uv0: vec2f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let coc: vec2f = textureSample(cocTexture, cocTextureSampler, input.uv0).rg;
let cocFar: f32 = coc.r;
var sum: vec3f = vec3f(0.0, 0.0, 0.0);
#if defined(NEAR_BLUR)
let cocNear: f32 = coc.g;
if (cocNear > 0.0001) {
let nearTextureSize: vec2f = vec2f(textureDimensions(nearTexture, 0));
let step: vec2f = cocNear * uniform.blurRadiusNear / nearTextureSize;
for (var i: i32 = 0; i < {KERNEL_COUNT}; i = i + 1) {
let uv: vec2f = uv0 + step * uniform.kernel[i].element;
let tap: vec3f = textureSampleLevel(nearTexture, nearTextureSampler, uv, 0.0).rgb;
sum = sum + tap;
}
sum = sum * f32({INV_KERNEL_COUNT});
} else
#endif
if (cocFar > 0.0001) {
let farTextureSize: vec2f = vec2f(textureDimensions(farTexture, 0));
let step: vec2f = cocFar * uniform.blurRadiusFar / farTextureSize;
var sumCoC: f32 = 0.0;
for (var i: i32 = 0; i < {KERNEL_COUNT}; i = i + 1) {
let uv: vec2f = uv0 + step * uniform.kernel[i].element;
var tap: vec3f = textureSampleLevel(farTexture, farTextureSampler, uv, 0.0).rgb;
let cocThis: f32 = textureSampleLevel(cocTexture, cocTextureSampler, uv, 0.0).r;
tap = tap * cocThis;
sumCoC = sumCoC + cocThis;
sum = sum + tap;
}
if (sumCoC > 0.0) {
sum = sum / sumCoC;
}
sum = sum / cocFar;
}
output.color = vec4f(sum, 1.0);
return output;
}
`;class OD extends SW{constructor(e,t,i,s){super(e),this.blurRadiusNear=1,this.blurRadiusFar=1,this._blurRings=3,this._blurRingPoints=3,this.nearTexture=t,this.farTexture=i,this.cocTexture=s,mr.get(e,rb).set("dofBlurPS",OL),mr.get(e,rw).set("dofBlurPS",OI);let{scope:r}=e;this.kernelId=r.resolve("kernel[0]"),this.kernelCountId=r.resolve("kernelCount"),this.blurRadiusNearId=r.resolve("blurRadiusNear"),this.blurRadiusFarId=r.resolve("blurRadiusFar"),this.nearTextureId=r.resolve("nearTexture"),this.farTextureId=r.resolve("farTexture"),this.cocTextureId=r.resolve("cocTexture");}set blurRings(e){this._blurRings!==e&&(this._blurRings=e,this.shader=null);}get blurRings(){return this._blurRings}set blurRingPoints(e){this._blurRingPoints!==e&&(this._blurRingPoints=e,this.shader=null);}get blurRingPoints(){return this._blurRingPoints}createShader(){this.kernel=new Float32Array(eR.concentric(this.blurRings,this.blurRingPoints));let e=this.kernel.length>>1,t=null!==this.nearTexture,i=new Map;i.set("{KERNEL_COUNT}",e),i.set("{INV_KERNEL_COUNT}",1/e),t&&i.set("NEAR_BLUR",""),this.shader=mo.createShader(this.device,{uniqueName:`DofBlurShader-${e}-${t?"nearBlur":"noNearBlur"}`,attributes:{aPosition:sT},vertexChunk:"quadVS",fragmentChunk:"dofBlurPS",fragmentDefines:i});}execute(){this.shader||this.createShader(),this.nearTextureId.setValue(this.nearTexture),this.farTextureId.setValue(this.farTexture),this.cocTextureId.setValue(this.cocTexture),this.kernelId.setValue(this.kernel),this.kernelCountId.setValue(this.kernel.length>>1),this.blurRadiusNearId.setValue(this.blurRadiusNear),this.blurRadiusFarId.setValue(this.blurRadiusFar),super.execute();}}class OR extends l2{constructor(e,t,i,s,r,a){super(e),this.focusDistance=100,this.focusRange=50,this.blurRadius=1,this.blurRings=3,this.blurRingPoints=3,this.highQuality=true,this.cocTexture=null,this.blurTexture=null,this.cocPass=null,this.farPass=null,this.blurPass=null,this.highQuality=r,this.cocPass=this.setupCocPass(e,t,i,a),this.beforePasses.push(this.cocPass);let n=r?i:s;this.farPass=this.setupFarPass(e,n,.5),this.beforePasses.push(this.farPass),this.blurPass=this.setupBlurPass(e,s,a,r?2:.5),this.beforePasses.push(this.blurPass);}destroy(){this.destroyRenderPasses(),this.cocPass=null,this.farPass=null,this.blurPass=null,this.destroyRT(this.cocRT),this.destroyRT(this.farRt),this.destroyRT(this.blurRt),this.cocRT=null,this.farRt=null,this.blurRt=null;}destroyRenderPasses(){for(let e=0;e<this.beforePasses.length;e++)this.beforePasses[e].destroy();this.beforePasses.length=0;}destroyRT(e){e&&(e.destroyTextureBuffers(),e.destroy());}setupCocPass(e,t,i,s){this.cocRT=this.createRenderTarget("CoCTexture",s?i4:i3),this.cocTexture=this.cocRT.colorBuffer;let r=new OP(e,t,s);return r.init(this.cocRT,{resizeSource:i}),r.setClearColor(eb.BLACK),r}setupFarPass(e,t,i){this.farRt=this.createRenderTarget("FarDofTexture",t.format);let s=new Of(e,t,{boxFilter:true,premultiplyTexture:this.cocTexture,premultiplySrcChannel:"r"});return s.init(this.farRt,{resizeSource:t,scaleX:i,scaleY:i}),s.setClearColor(eb.BLACK),s}setupBlurPass(e,t,i,s){let r=this.farRt?.colorBuffer;this.blurRt=this.createRenderTarget("DofBlurTexture",t.format),this.blurTexture=this.blurRt.colorBuffer;let a=new OD(e,i?t:null,r,this.cocTexture);return a.init(this.blurRt,{resizeSource:t,scaleX:s,scaleY:s}),a.setClearColor(eb.BLACK),a}createTexture(e,t){return new ns(this.device,{name:e,width:1,height:1,format:t,mipmaps:false,minFilter:tZ,magFilter:tZ,addressU:tr,addressV:tr})}createRenderTarget(e,t){return new nM({colorBuffer:this.createTexture(e,t),depth:false,stencil:false})}frameUpdate(){super.frameUpdate(),this.cocPass.focusDistance=this.focusDistance,this.cocPass.focusRange=this.focusRange,this.blurPass.blurRadiusNear=this.blurRadius,this.blurPass.blurRadiusFar=this.blurRadius*(this.highQuality?1:.5),this.blurPass.blurRings=this.blurRings,this.blurPass.blurRingPoints=this.blurRingPoints;}}let OM=[];class OO extends l2{constructor(e,t,i,s,r){super(e),this.viewBindGroups=[],this.linearDepthClearValue=new eb(0,0,0,0),this.scene=t,this.renderer=i,this.camera=s,this.setupRenderTarget(r);}destroy(){super.destroy(),this.renderTarget?.destroy(),this.renderTarget=null,this.linearDepthTexture?.destroy(),this.linearDepthTexture=null,this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;}setupRenderTarget(e){let{device:t}=this;this.linearDepthFormat=t.textureFloatRenderable?iy:id,this.linearDepthTexture=new ns(t,{name:"SceneLinearDepthTexture",width:1,height:1,format:this.linearDepthFormat,mipmaps:false,minFilter:tK,magFilter:tK,addressU:tr,addressV:tr});let i=new nM({name:"PrepassRT",colorBuffer:this.linearDepthTexture,depth:true,samples:1});this.camera.shaderParams.sceneDepthMapLinear=true,this.init(i,e);}after(){this.device.scope.resolve("uSceneDepthMap").setValue(this.linearDepthTexture);}execute(){let{renderer:e,scene:t,renderTarget:i}=this,s=this.camera.camera,r=t.layers.layerList,a=t.layers.subLayerEnabled,n=t.layers.subLayerList;for(let t=0;t<r.length;t++){let o=r[t];if(o.id===uw)break;if(o.enabled&&a[t]&&o.camerasSet.has(s)){let r=o.getCulledInstances(s),a=n[t]?r.transparent:r.opaque;for(let e=0;e<a.length;e++){let t=a[e];t.material?.depthWrite&&OM.push(t);}e.renderForwardLayer(s,i,null,void 0,pd,this.viewBindGroups,{meshInstances:OM}),OM.length=0;}}}frameUpdate(){let e;super.frameUpdate();let{camera:t}=this;if(this.setClearDepth(t.clearDepthBuffer?1:void 0),t.clearDepthBuffer){let i=t.farClip-Number.MIN_VALUE;e=this.linearDepthClearValue,this.linearDepthFormat===iy?e.r=i:eD.float2RGBA8(i,e);}this.setClearColor(e);}}var ON=`
#include "screenDepthPS"
varying vec2 uv0;
uniform sampler2D sourceTexture;
uniform vec2 sourceInvResolution;
uniform int filterSize;
float random(const highp vec2 w) {
const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);
return fract(m.z * fract(dot(w, m.xy)));
}
mediump float bilateralWeight(in mediump float depth, in mediump float sampleDepth) {
mediump float diff = (sampleDepth - depth);
return max(0.0, 1.0 - diff * diff);
}
void tap(inout float sum, inout float totalWeight, float weight, float depth, vec2 position) {
mediump float color = texture2D(sourceTexture, position).r;
mediump float textureDepth = -getLinearScreenDepth(position);
mediump float bilateral = bilateralWeight(depth, textureDepth);
bilateral *= weight;
sum += color * bilateral;
totalWeight += bilateral;
}
void main() {
mediump float depth = -getLinearScreenDepth(uv0);
mediump float totalWeight = 1.0;
mediump float color = texture2D(sourceTexture, uv0 ).r;
mediump float sum = color * totalWeight;
for (mediump int i = -filterSize; i <= filterSize; i++) {
mediump float weight = 1.0;
#ifdef HORIZONTAL
vec2 offset = vec2(i, 0) * sourceInvResolution;
#else
vec2 offset = vec2(0, i) * sourceInvResolution;
#endif
tap(sum, totalWeight, weight, depth, uv0 + offset);
}
mediump float ao = sum / totalWeight;
gl_FragColor.r = ao;
}
`,OF=`
#include "screenDepthPS"
varying uv0: vec2f;
var sourceTexture: texture_2d<f32>;
var sourceTextureSampler: sampler;
uniform sourceInvResolution: vec2f;
uniform filterSize: i32;
fn random(w: vec2f) -> f32 {
const m: vec3f = vec3f(0.06711056, 0.00583715, 52.9829189);
return fract(m.z * fract(dot(w, m.xy)));
}
fn bilateralWeight(depth: f32, sampleDepth: f32) -> f32 {
let diff: f32 = (sampleDepth - depth);
return max(0.0, 1.0 - diff * diff);
}
fn tap(sum_ptr: ptr<function, f32>, totalWeight_ptr: ptr<function, f32>, weight: f32, depth: f32, position: vec2f) {
let color: f32 = textureSample(sourceTexture, sourceTextureSampler, position).r;
let textureDepth: f32 = -getLinearScreenDepth(position);
let bilateral: f32 = bilateralWeight(depth, textureDepth) * weight;
*sum_ptr = *sum_ptr + color * bilateral;
*totalWeight_ptr = *totalWeight_ptr + bilateral;
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let depth: f32 = -getLinearScreenDepth(input.uv0);
var totalWeight: f32 = 1.0;
let color: f32 = textureSample(sourceTexture, sourceTextureSampler, input.uv0 ).r;
var sum: f32 = color * totalWeight;
for (var i: i32 = -uniform.filterSize; i <= uniform.filterSize; i = i + 1) {
let weight: f32 = 1.0;
#ifdef HORIZONTAL
var offset: vec2f = vec2f(f32(i), 0.0) * uniform.sourceInvResolution;
#else
var offset: vec2f = vec2f(0.0, f32(i)) * uniform.sourceInvResolution;
#endif
tap(&sum, &totalWeight, weight, depth, input.uv0 + offset);
}
let ao: f32 = sum / totalWeight;
output.color = vec4f(ao, ao, ao, 1.0);
return output;
}
`;class OB extends SW{constructor(e,t,i,s){super(e),this.sourceTexture=t,mr.get(e,rb).set("depthAwareBlurPS",ON),mr.get(e,rw).set("depthAwareBlurPS",OF);let r=new Map;s&&r.set("HORIZONTAL",""),mo.addScreenDepthChunkDefines(e,i.shaderParams,r),this.shader=mo.createShader(e,{uniqueName:`DepthAware${s?"Horizontal":"Vertical"}BlurShader`,attributes:{aPosition:sT},vertexChunk:"quadVS",fragmentChunk:"depthAwareBlurPS",fragmentDefines:r});let a=this.device.scope;this.sourceTextureId=a.resolve("sourceTexture"),this.sourceInvResolutionId=a.resolve("sourceInvResolution"),this.sourceInvResolutionValue=new Float32Array(2),this.filterSizeId=a.resolve("filterSize");}execute(){this.filterSizeId.setValue(4),this.sourceTextureId.setValue(this.sourceTexture);let{width:e,height:t}=this.sourceTexture;this.sourceInvResolutionValue[0]=1/e,this.sourceInvResolutionValue[1]=1/t,this.sourceInvResolutionId.setValue(this.sourceInvResolutionValue),super.execute();}}var OU=`
#include "screenDepthPS"
varying vec2 uv0;
uniform vec2 uInvResolution;
uniform float uAspect;
#define saturate(x) clamp(x,0.0,1.0)
highp float getWFromProjectionMatrix(const mat4 p, const vec3 v) {
return -v.z;
}
highp float getViewSpaceZFromW(const mat4 p, const float w) {
return -w;
}
const float kLog2LodRate = 3.0;
float random(const highp vec2 w) {
const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);
return fract(m.z * fract(dot(w, m.xy)));
}
highp vec2 getFragCoord() {
return gl_FragCoord.xy;
}
highp vec3 computeViewSpacePositionFromDepth(highp vec2 uv, highp float linearDepth) {
return vec3((0.5 - uv) * vec2(uAspect, 1.0) * linearDepth, linearDepth);
}
highp vec3 faceNormal(highp vec3 dpdx, highp vec3 dpdy) {
return normalize(cross(dpdx, dpdy));
}
highp vec3 computeViewSpaceNormal(const highp vec3 position) {
return faceNormal(dFdx(position), dFdy(position));
}
highp vec3 computeViewSpaceNormal(const highp vec3 position, const highp vec2 uv) {
highp vec2 uvdx = uv + vec2(uInvResolution.x, 0.0);
highp vec2 uvdy = uv + vec2(0.0, uInvResolution.y);
highp vec3 px = computeViewSpacePositionFromDepth(uvdx, -getLinearScreenDepth(uvdx));
highp vec3 py = computeViewSpacePositionFromDepth(uvdy, -getLinearScreenDepth(uvdy));
highp vec3 dpdx = px - position;
highp vec3 dpdy = py - position;
return faceNormal(dpdx, dpdy);
}
uniform vec2 uSampleCount;
uniform float uSpiralTurns;
#define PI (3.14159)
mediump vec3 tapLocation(mediump float i, const mediump float noise) {
mediump float offset = ((2.0 * PI) * 2.4) * noise;
mediump float angle = ((i * uSampleCount.y) * uSpiralTurns) * (2.0 * PI) + offset;
mediump float radius = (i + noise + 0.5) * uSampleCount.y;
return vec3(cos(angle), sin(angle), radius * radius);
}
highp vec2 startPosition(const float noise) {
float angle = ((2.0 * PI) * 2.4) * noise;
return vec2(cos(angle), sin(angle));
}
uniform vec2 uAngleIncCosSin;
highp mat2 tapAngleStep() {
highp vec2 t = uAngleIncCosSin;
return mat2(t.x, t.y, -t.y, t.x);
}
mediump vec3 tapLocationFast(mediump float i, mediump vec2 p, const mediump float noise) {
mediump float radius = (i + noise + 0.5) * uSampleCount.y;
return vec3(p, radius * radius);
}
uniform float uMaxLevel;
uniform float uInvRadiusSquared;
uniform float uMinHorizonAngleSineSquared;
uniform float uBias;
uniform float uPeak2;
void computeAmbientOcclusionSAO(inout mediump float occlusion, mediump float i, mediump float ssDiskRadius,
const highp vec2 uv, const highp vec3 origin, const mediump vec3 normal,
const mediump vec2 tapPosition, const float noise) {
mediump vec3 tap = tapLocationFast(i, tapPosition, noise);
mediump float ssRadius = max(1.0, tap.z * ssDiskRadius);
mediump vec2 uvSamplePos = uv + vec2(ssRadius * tap.xy) * uInvResolution;
mediump float level = clamp(floor(log2(ssRadius)) - kLog2LodRate, 0.0, float(uMaxLevel));
highp float occlusionDepth = -getLinearScreenDepth(uvSamplePos);
highp vec3 p = computeViewSpacePositionFromDepth(uvSamplePos, occlusionDepth);
vec3 v = p - origin;
float vv = dot(v, v);
float vn = dot(v, normal);
mediump float w = max(0.0, 1.0 - vv * uInvRadiusSquared);
w = w * w;
w *= step(vv * uMinHorizonAngleSineSquared, vn * vn);
occlusion += w * max(0.0, vn + origin.z * uBias) / (vv + uPeak2);
}
uniform float uProjectionScaleRadius;
uniform float uIntensity;
uniform float uRandomize;
float scalableAmbientObscurance(highp vec2 uv, highp vec3 origin, vec3 normal) {
float noise = random(getFragCoord()) + uRandomize;
highp vec2 tapPosition = startPosition(noise);
highp mat2 angleStep = tapAngleStep();
float ssDiskRadius = -(uProjectionScaleRadius / origin.z);
float occlusion = 0.0;
for (float i = 0.0; i < uSampleCount.x; i += 1.0) {
computeAmbientOcclusionSAO(occlusion, i, ssDiskRadius, uv, origin, normal, tapPosition, noise);
tapPosition = angleStep * tapPosition;
}
return occlusion;
}
uniform float uPower;
void main() {
highp vec2 uv = uv0;
highp float depth = -getLinearScreenDepth(uv0);
highp vec3 origin = computeViewSpacePositionFromDepth(uv, depth);
vec3 normal = computeViewSpaceNormal(origin, uv);
float occlusion = 0.0;
if (uIntensity > 0.0) {
occlusion = scalableAmbientObscurance(uv, origin, normal);
}
float ao = max(0.0, 1.0 - occlusion * uIntensity);
ao = pow(ao, uPower);
gl_FragColor = vec4(ao, ao, ao, 1.0);
}
`,Ok=`
#include "screenDepthPS"
varying uv0: vec2f;
uniform uInvResolution: vec2f;
uniform uAspect: f32;
fn getWFromProjectionMatrix(p: mat4x4f, v: vec3f) -> f32 {
return -v.z;
}
fn getViewSpaceZFromW(p: mat4x4f, w: f32) -> f32 {
return -w;
}
const kLog2LodRate: f32 = 3.0;
fn random(w: vec2f) -> f32 {
const m: vec3f = vec3f(0.06711056, 0.00583715, 52.9829189);
return fract(m.z * fract(dot(w, m.xy)));
}
fn getFragCoord() -> vec2f {
return pcPosition.xy;
}
fn computeViewSpacePositionFromDepth(uv: vec2f, linearDepth: f32) -> vec3f {
return vec3f((0.5 - uv) * vec2f(uniform.uAspect, 1.0) * linearDepth, linearDepth);
}
fn faceNormal(dpdx: vec3f, dpdy: vec3f) -> vec3f {
return normalize(cross(dpdx, dpdy));
}
fn computeViewSpaceNormalDeriv(position: vec3f) -> vec3f {
return faceNormal(dpdx(position), dpdy(position));
}
fn computeViewSpaceNormalDepth(position: vec3f, uv: vec2f) -> vec3f {
let uvdx: vec2f = uv + vec2f(uniform.uInvResolution.x, 0.0);
let uvdy: vec2f = uv + vec2f(0.0, uniform.uInvResolution.y);
let px: vec3f = computeViewSpacePositionFromDepth(uvdx, -getLinearScreenDepth(uvdx));
let py: vec3f = computeViewSpacePositionFromDepth(uvdy, -getLinearScreenDepth(uvdy));
let dpdx: vec3f = px - position;
let dpdy: vec3f = py - position;
return faceNormal(dpdx, dpdy);
}
uniform uSampleCount: vec2f;
uniform uSpiralTurns: f32;
const PI: f32 = 3.14159;
fn tapLocation(i: f32, noise: f32) -> vec3f {
let offset: f32 = ((2.0 * PI) * 2.4) * noise;
let angle: f32 = ((i * uniform.uSampleCount.y) * uniform.uSpiralTurns) * (2.0 * PI) + offset;
let radius: f32 = (i + noise + 0.5) * uniform.uSampleCount.y;
return vec3f(cos(angle), sin(angle), radius * radius);
}
fn startPosition(noise: f32) -> vec2f {
let angle: f32 = ((2.0 * PI) * 2.4) * noise;
return vec2f(cos(angle), sin(angle));
}
uniform uAngleIncCosSin: vec2f;
fn tapAngleStep() -> mat2x2f {
let t: vec2f = uniform.uAngleIncCosSin;
return mat2x2f(vec2f(t.x, t.y), vec2f(-t.y, t.x));
}
fn tapLocationFast(i: f32, p: vec2f, noise_in: f32) -> vec3f {
let radius: f32 = (i + noise_in + 0.5) * uniform.uSampleCount.y;
return vec3f(p.x, p.y, radius * radius);
}
uniform uMaxLevel: f32;
uniform uInvRadiusSquared: f32;
uniform uMinHorizonAngleSineSquared: f32;
uniform uBias: f32;
uniform uPeak2: f32;
fn computeAmbientOcclusionSAO(occlusion_ptr: ptr<function, f32>, i: f32, ssDiskRadius: f32,
uv: vec2f, origin: vec3f, normal: vec3f,
tapPosition: vec2f, noise: f32) {
let tap: vec3f = tapLocationFast(i, tapPosition, noise);
let ssRadius: f32 = max(1.0, tap.z * ssDiskRadius);
let uvSamplePos: vec2f = uv + (ssRadius * tap.xy) * uniform.uInvResolution;
let level: f32 = clamp(floor(log2(ssRadius)) - kLog2LodRate, 0.0, uniform.uMaxLevel);
let occlusionDepth: f32 = -getLinearScreenDepth(uvSamplePos);
let p: vec3f = computeViewSpacePositionFromDepth(uvSamplePos, occlusionDepth);
let v: vec3f = p - origin;
let vv: f32 = dot(v, v);
let vn: f32 = dot(v, normal);
var w_val: f32 = max(0.0, 1.0 - vv * uniform.uInvRadiusSquared);
w_val = w_val * w_val;
w_val = w_val * step(vv * uniform.uMinHorizonAngleSineSquared, vn * vn);
*occlusion_ptr = *occlusion_ptr + w_val * max(0.0, vn + origin.z * uniform.uBias) / (vv + uniform.uPeak2);
}
uniform uProjectionScaleRadius: f32;
uniform uIntensity: f32;
uniform uRandomize: f32;
fn scalableAmbientObscurance(uv: vec2f, origin: vec3f, normal: vec3f) -> f32 {
let noise: f32 = random(getFragCoord()) + uniform.uRandomize;
var tapPosition: vec2f = startPosition(noise);
let angleStep: mat2x2f = tapAngleStep();
let ssDiskRadius: f32 = -(uniform.uProjectionScaleRadius / origin.z);
var occlusion: f32 = 0.0;
for (var i: i32 = 0; i < i32(uniform.uSampleCount.x); i = i + 1) {
computeAmbientOcclusionSAO(&occlusion, f32(i), ssDiskRadius, uv, origin, normal, tapPosition, noise);
tapPosition = angleStep * tapPosition;
}
return occlusion;
}
uniform uPower: f32;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let uv: vec2f = input.uv0;
let depth: f32 = -getLinearScreenDepth(input.uv0);
let origin: vec3f = computeViewSpacePositionFromDepth(uv, depth);
let normal: vec3f = computeViewSpaceNormalDepth(origin, uv);
var occlusion: f32 = 0.0;
if (uniform.uIntensity > 0.0) {
occlusion = scalableAmbientObscurance(uv, origin, normal);
}
var ao: f32 = max(0.0, 1.0 - occlusion * uniform.uIntensity);
ao = pow(ao, uniform.uPower);
output.color = vec4f(ao, ao, ao, 1.0);
return output;
}
`;class OV extends SW{constructor(e,t,i,s){super(e),this.radius=5,this.intensity=1,this.power=1,this.sampleCount=10,this.minAngle=5,this.randomize=false,this._scale=1,this._blueNoise=new _M(19),this.sourceTexture=t,this.cameraComponent=i,mr.get(e,rb).set("ssaoPS",OU),mr.get(e,rw).set("ssaoPS",Ok);let r=new Map;mo.addScreenDepthChunkDefines(e,i.shaderParams,r),this.shader=mo.createShader(e,{uniqueName:"SsaoShader",attributes:{aPosition:sT},vertexChunk:"quadVS",fragmentChunk:"ssaoPS",fragmentDefines:r});let a=this.createRenderTarget("SsaoFinalTexture");this.ssaoTexture=a.colorBuffer,this.init(a,{resizeSource:this.sourceTexture});let n=new eb(0,0,0,0);if(this.setClearColor(n),s){let t=this.createRenderTarget("SsaoTempTexture"),s=new OB(e,a.colorBuffer,i,true);s.init(t,{resizeSource:a.colorBuffer}),s.setClearColor(n);let r=new OB(e,t.colorBuffer,i,false);r.init(a,{resizeSource:a.colorBuffer}),r.setClearColor(n),this.afterPasses.push(s),this.afterPasses.push(r);}this.ssaoTextureId=e.scope.resolve("ssaoTexture"),this.ssaoTextureSizeInvId=e.scope.resolve("ssaoTextureSizeInv");}destroy(){if(this.renderTarget?.destroyTextureBuffers(),this.renderTarget?.destroy(),this.renderTarget=null,this.afterPasses.length>0){let e=this.afterPasses[0].renderTarget;e?.destroyTextureBuffers(),e?.destroy();}this.afterPasses.forEach(e=>e.destroy()),this.afterPasses.length=0,super.destroy();}set scale(e){this._scale=e,this.scaleX=e,this.scaleY=e;}get scale(){return this._scale}createRenderTarget(e){return new nM({depth:false,colorBuffer:new ns(this.device,{name:e,width:1,height:1,format:i3,mipmaps:false,minFilter:tK,magFilter:tK,addressU:tr,addressV:tr})})}execute(){let{device:e,sourceTexture:t,sampleCount:i,minAngle:s,scale:r}=this,{width:a,height:n}=this.renderTarget.colorBuffer,o=e.scope;o.resolve("uAspect").setValue(a/n),o.resolve("uInvResolution").setValue([1/a,1/n]),o.resolve("uSampleCount").setValue([i,1/i]);let l=Math.sin(s*Math.PI/180);o.resolve("uMinHorizonAngleSineSquared").setValue(l*l);let h=1/(i-.5)*62.82,c=this.radius/r,d=.1*c,u=2*d*6.282*this.intensity/i,f=.5*t.height;o.resolve("uSpiralTurns").setValue(10),o.resolve("uAngleIncCosSin").setValue([Math.cos(h),Math.sin(h)]),o.resolve("uMaxLevel").setValue(0),o.resolve("uInvRadiusSquared").setValue(1/(c*c)),o.resolve("uBias").setValue(.001),o.resolve("uPeak2").setValue(d*d),o.resolve("uIntensity").setValue(u),o.resolve("uPower").setValue(this.power),o.resolve("uProjectionScaleRadius").setValue(f*c),o.resolve("uRandomize").setValue(this.randomize?this._blueNoise.value():0),super.execute();}after(){this.ssaoTextureId.setValue(this.ssaoTexture);let e=this.sourceTexture;this.ssaoTextureSizeInvId.setValue([1/e.width,1/e.height]);}}class Oz{constructor(){this.stencil=false,this.samples=1,this.sceneColorMap=false,this.lastGrabLayerId=uC,this.lastGrabLayerIsTransparent=false,this.lastSceneLayerId=uP,this.lastSceneLayerIsTransparent=true,this.taaEnabled=false,this.bloomEnabled=false,this.ssaoType=Ol,this.ssaoBlurEnabled=true,this.prepassEnabled=false,this.dofEnabled=false,this.dofNearBlur=false,this.dofHighQuality=true;}}let OG=new Oz;class OH extends l2{constructor(e,t,i,s={}){super(e.graphicsDevice),this._renderTargetScale=1,this.layersDirty=false,this.rt=null,this.app=e,this.cameraComponent=i,this.cameraFrame=t,this.options=this.sanitizeOptions(s),this.setupRenderPasses(this.options);}destroy(){this.reset();}reset(){this.sceneTexture=null,this.sceneTextureHalf=null,this.rt&&(this.rt.destroyTextureBuffers(),this.rt.destroy(),this.rt=null),this.rtHalf&&(this.rtHalf.destroyTextureBuffers(),this.rtHalf.destroy(),this.rtHalf=null),this.beforePasses.forEach(e=>e.destroy()),this.beforePasses.length=0,this.prePass=null,this.scenePass=null,this.scenePassTransparent=null,this.colorGrabPass=null,this.composePass=null,this.bloomPass=null,this.ssaoPass=null,this.taaPass=null,this.afterPass=null,this.scenePassHalf=null,this.dofPass=null;}sanitizeOptions(e){return ((e=Object.assign({},OG,e)).taaEnabled||e.ssaoType!==Ol||e.dofEnabled)&&(e.prepassEnabled=true),e}set renderTargetScale(e){this._renderTargetScale=e,this.scenePass&&(this.scenePass.scaleX=e,this.scenePass.scaleY=e);}get renderTargetScale(){return this._renderTargetScale}needsReset(e){let t,i,s=this.options;return e.ssaoType!==s.ssaoType||e.ssaoBlurEnabled!==s.ssaoBlurEnabled||e.taaEnabled!==s.taaEnabled||e.samples!==s.samples||e.stencil!==s.stencil||e.bloomEnabled!==s.bloomEnabled||e.prepassEnabled!==s.prepassEnabled||e.sceneColorMap!==s.sceneColorMap||e.dofEnabled!==s.dofEnabled||e.dofNearBlur!==s.dofNearBlur||e.dofHighQuality!==s.dofHighQuality||(t=e.formats)!==(i=s.formats)&&(!(Array.isArray(t)&&Array.isArray(i))||t.length!==i.length||!t.every((e,t)=>e===i[t]))}update(e){e=this.sanitizeOptions(e),(this.needsReset(e)||this.layersDirty)&&(this.layersDirty=false,this.reset()),this.options=e,this.sceneTexture||this.setupRenderPasses(this.options);}createRenderTarget(e,t,i,s,r){return new nM({colorBuffer:new ns(this.device,{name:e,width:4,height:4,format:this.hdrFormat,mipmaps:false,minFilter:tZ,magFilter:tZ,addressU:tr,addressV:tr}),depth:t,stencil:i,samples:s,flipY:r})}setupRenderPasses(e){let{device:t}=this,i=this.cameraComponent,s=i.renderTarget;this.hdrFormat=t.getRenderableHdrFormat(e.formats,true,e.samples)||id,this._bloomEnabled=e.bloomEnabled&&this.hdrFormat!==id,this._sceneHalfEnabled=this._bloomEnabled||e.dofEnabled,i.shaderParams.ssaoEnabled=e.ssaoType===Oh;let r=!!s?.flipY;this.rt=this.createRenderTarget("SceneColor",true,e.stencil,e.samples,r),this.sceneTexture=this.rt.colorBuffer,this._sceneHalfEnabled&&(this.rtHalf=this.createRenderTarget("SceneColorHalf",false,false,1,r),this.sceneTextureHalf=this.rtHalf.colorBuffer),this.sceneOptions={resizeSource:s,scaleX:this.renderTargetScale,scaleY:this.renderTargetScale},this.createPasses(e);let a=this.collectPasses();this.beforePasses=a.filter(e=>null!=e);}collectPasses(){return [this.prePass,this.ssaoPass,this.scenePass,this.colorGrabPass,this.scenePassTransparent,this.taaPass,this.scenePassHalf,this.bloomPass,this.dofPass,this.composePass,this.afterPass]}createPasses(e){this.setupScenePrepass(e),this.setupSsaoPass(e);let t=this.setupScenePass(e),i=this.setupTaaPass(e);this.setupSceneHalfPass(e,i),this.setupBloomPass(e,this.sceneTextureHalf),this.setupDofPass(e,this.sceneTexture,this.sceneTextureHalf),this.setupComposePass(e),this.setupAfterPass(e,t);}setupScenePrepass(e){if(e.prepassEnabled){let{app:e,device:t,cameraComponent:i}=this,{scene:s,renderer:r}=e;this.prePass=new OO(t,s,r,i,this.sceneOptions);}}setupScenePassSettings(e){e.gammaCorrection=fP,e.toneMapping=fB;}setupScenePass(e){let{app:t,device:i,cameraComponent:s}=this,{scene:r,renderer:a}=t,n=r.layers;this.scenePass=new gR(i,n,r,a),this.setupScenePassSettings(this.scenePass),this.scenePass.init(this.rt,this.sceneOptions);let o=e.sceneColorMap?e.lastGrabLayerId:e.lastSceneLayerId,l=e.sceneColorMap?e.lastGrabLayerIsTransparent:e.lastSceneLayerIsTransparent,h={lastAddedIndex:0,clearRenderTarget:true};return h.lastAddedIndex=this.scenePass.addLayers(n,s,h.lastAddedIndex,h.clearRenderTarget,o,l),h.clearRenderTarget=false,e.sceneColorMap&&(this.colorGrabPass=new m$(i),this.colorGrabPass.source=this.rt,this.scenePassTransparent=new gR(i,n,r,a),this.setupScenePassSettings(this.scenePassTransparent),this.scenePassTransparent.init(this.rt),h.lastAddedIndex=this.scenePassTransparent.addLayers(n,s,h.lastAddedIndex,h.clearRenderTarget,e.lastSceneLayerId,e.lastSceneLayerIsTransparent),this.scenePassTransparent.rendersAnything||(this.scenePassTransparent.destroy(),this.scenePassTransparent=null),this.scenePassTransparent&&e.prepassEnabled&&(this.scenePassTransparent.depthStencilOps.storeDepth=true)),h}setupSsaoPass(e){let{ssaoBlurEnabled:t,ssaoType:i}=e,{device:s,cameraComponent:r}=this;i!==Ol&&(this.ssaoPass=new OV(s,this.sceneTexture,r,t));}setupSceneHalfPass(e,t){this._sceneHalfEnabled&&(this.scenePassHalf=new Of(this.device,this.sceneTexture,{boxFilter:true,removeInvalid:true}),this.scenePassHalf.name="RenderPassSceneHalf",this.scenePassHalf.init(this.rtHalf,{resizeSource:t,scaleX:.5,scaleY:.5}),this.scenePassHalf.setClearColor(eb.BLACK));}setupBloomPass(e,t){this._bloomEnabled&&(this.bloomPass=new Og(this.device,t,this.hdrFormat));}setupDofPass(e,t,i){e.dofEnabled&&(this.dofPass=new OR(this.device,this.cameraComponent,t,i,e.dofHighQuality,e.dofNearBlur));}setupTaaPass(e){let t=this.sceneTexture;return e.taaEnabled&&(this.taaPass=new Ob(this.device,this.sceneTexture,this.cameraComponent),t=this.taaPass.historyTexture),t}setupComposePass(e){this.composePass=new Oy(this.device),this.composePass.bloomTexture=this.bloomPass?.bloomTexture,this.composePass.taaEnabled=e.taaEnabled,this.composePass.cocTexture=this.dofPass?.cocTexture,this.composePass.blurTexture=this.dofPass?.blurTexture,this.composePass.blurTextureUpscale=!this.dofPass?.highQuality;let t=this.cameraComponent.renderTarget;this.composePass.init(t),this.composePass.ssaoTexture=e.ssaoType===Oc?this.ssaoPass.ssaoTexture:null;}setupAfterPass(e,t){let{app:i,cameraComponent:s}=this,{scene:r,renderer:a}=i,n=r.layers,o=s.renderTarget;this.afterPass=new gR(this.device,n,r,a),this.afterPass.init(o),this.afterPass.addLayers(n,s,t.lastAddedIndex,t.clearRenderTarget);}frameUpdate(){this.layersDirty&&this.cameraFrame.update(),super.frameUpdate();let e=this.taaPass?.update()??this.rt.colorBuffer;this.composePass.sceneTexture=e,this.scenePassHalf?.setSourceTexture(e);}}class OW{constructor(e,t){this._enabled=true,this.rendering={renderFormats:[iE,ig,iS],stencil:false,renderTargetScale:1,samples:1,sceneColorMap:false,sceneDepthMap:false,toneMapping:0,sharpness:0},this.ssao={type:Ol,blurEnabled:true,randomize:false,intensity:.5,radius:30,samples:12,power:6,minAngle:10,scale:1},this.bloom={intensity:0,blurLevel:16},this.grading={enabled:false,brightness:1,contrast:1,saturation:1,tint:new eb(1,1,1,1)},this.colorLUT={texture:null,intensity:1},this.vignette={intensity:0,inner:.5,outer:1,curvature:.5},this.taa={enabled:false,jitter:1},this.fringing={intensity:0},this.dof={enabled:false,nearBlur:false,focusDistance:100,focusRange:10,blurRadius:3,blurRings:4,blurRingPoints:5,highQuality:true},this.debug=null,this.options=new Oz,this.renderPassCamera=null,this.app=e,this.cameraComponent=t,this.updateOptions(),this.enable(),this.cameraLayersChanged=t.on("set:layers",()=>{this.renderPassCamera&&(this.renderPassCamera.layersDirty=true);});}destroy(){this.disable(),this.cameraLayersChanged.off();}enable(){this.renderPassCamera=this.createRenderPass(),this.cameraComponent.renderPasses=[this.renderPassCamera];}disable(){let e=this.cameraComponent;e.renderPasses?.forEach(e=>{e.destroy();}),e.renderPasses=[],e.rendering=null,e.jitter=0,e.shaderParams.ssaoEnabled=false,this.renderPassCamera=null;}createRenderPass(){return new OH(this.app,this,this.cameraComponent,this.options)}set enabled(e){this._enabled!==e&&(e?this.enable():this.disable(),this._enabled=e);}get enabled(){return this._enabled}updateOptions(){let{options:e,rendering:t,bloom:i,taa:s,ssao:r}=this;e.stencil=t.stencil,e.samples=t.samples,e.sceneColorMap=t.sceneColorMap,e.prepassEnabled=t.sceneDepthMap,e.bloomEnabled=i.intensity>0,e.taaEnabled=s.enabled,e.ssaoType=r.type,e.ssaoBlurEnabled=r.blurEnabled,e.formats=t.renderFormats.slice(),e.dofEnabled=this.dof.enabled,e.dofNearBlur=this.dof.nearBlur,e.dofHighQuality=this.dof.highQuality;}update(){if(!this._enabled)return;let e=this.cameraComponent,{options:t,renderPassCamera:i,rendering:s,bloom:r,grading:a,vignette:n,fringing:o,taa:l,ssao:h}=this;this.updateOptions(),i.update(t);let{composePass:c,bloomPass:d,ssaoPass:u,dofPass:f}=i;i.renderTargetScale=eA.clamp(s.renderTargetScale,.1,1),c.toneMapping=s.toneMapping,c.sharpness=s.sharpness,t.bloomEnabled&&d&&(c.bloomIntensity=r.intensity,d.blurLevel=r.blurLevel),t.dofEnabled&&(f.focusDistance=this.dof.focusDistance,f.focusRange=this.dof.focusRange,f.blurRadius=this.dof.blurRadius,f.blurRings=this.dof.blurRings,f.blurRingPoints=this.dof.blurRingPoints),t.ssaoType!==Ol&&(u.intensity=h.intensity,u.power=h.power,u.radius=h.radius,u.sampleCount=h.samples,u.minAngle=h.minAngle,u.scale=h.scale,u.randomize=h.randomize),c.gradingEnabled=a.enabled,a.enabled&&(c.gradingSaturation=a.saturation,c.gradingBrightness=a.brightness,c.gradingContrast=a.contrast,c.gradingTint=a.tint),c.colorLUT=this.colorLUT.texture,c.colorLUTIntensity=this.colorLUT.intensity,c.vignetteEnabled=n.intensity>0,c.vignetteEnabled&&(c.vignetteInner=n.inner,c.vignetteOuter=n.outer,c.vignetteCurvature=n.curvature,c.vignetteIntensity=n.intensity),c.fringingEnabled=o.intensity>0,c.fringingEnabled&&(c.fringingIntensity=o.intensity),e.jitter=l.enabled?l.jitter:0,c.debug=this.debug,"ssao"===c.debug&&t.ssaoType===Ol&&(c.debug=null),"vignette"!==c.debug||c.vignetteEnabled||(c.debug=null);}}let OX=new eM,OY=new eH;class Oq{constructor(e=eM.ZERO,t=eM.ZERO,i=0){this.position=new eM,this.angles=new eM,this.distance=0,this.pitchRange=new eN(-1/0,1/0),this.yawRange=new eN(-1/0,1/0),this.xRange=new eN(-1/0,1/0),this.yRange=new eN(-1/0,1/0),this.zRange=new eN(-1/0,1/0),this.set(e,t,i);}copy(e){return this.set(e.position,e.angles,e.distance)}clone(){return new Oq(this.position.clone(),this.angles.clone(),this.distance)}equalsApprox(e,t=1e-6){return this.position.equalsApprox(e.position,t)&&this.angles.equalsApprox(e.angles,t)&&Math.abs(this.distance-e.distance)<t}lerp(e,t,i,s=i,r=i){return this.position.lerp(e.position,t.position,i),this.angles.x=eA.lerpAngle(e.angles.x,t.angles.x,s)%360,this.angles.y=eA.lerpAngle(e.angles.y,t.angles.y,s)%360,this.angles.z=eA.lerpAngle(e.angles.z,t.angles.z,s)%360,this.distance=eA.lerp(e.distance,t.distance,r),this}move(e){return this.position.add(e),this.position.x=eA.clamp(this.position.x,this.xRange.x,this.xRange.y),this.position.y=eA.clamp(this.position.y,this.yRange.x,this.yRange.y),this.position.z=eA.clamp(this.position.z,this.zRange.x,this.zRange.y),this}rotate(e){return this.angles.add(e),this.angles.x%=360,this.angles.y%=360,this.angles.z%=360,this.angles.x=eA.clamp(this.angles.x,this.pitchRange.x,this.pitchRange.y),this.angles.y=eA.clamp(this.angles.y,this.yawRange.x,this.yawRange.y),this}set(e,t,i){return this.position.copy(e),this.angles.copy(t),this.distance=i,this}look(e,t){this.position.copy(e),this.distance=e.distance(t);let i=OX.sub2(t,e).normalize(),s=Math.atan2(-i.y,Math.sqrt(i.x*i.x+i.z*i.z))*eA.RAD_TO_DEG,r=Math.atan2(-i.x,-i.z)*eA.RAD_TO_DEG;return this.angles.set(-s,r,0),this}getFocus(e){return OY.setFromEulerAngles(this.angles).transformVector(eM.FORWARD,e).mulScalar(this.distance).add(this.position)}}class O${constructor(e){Array.isArray(e)?this._value=e.slice():this._value=Array(+e).fill(0);}add(e){for(let t=0;t<this._value.length;t++)this._value[t]+=e._value[t]||0;return this}append(e){for(let t=0;t<this._value.length;t++)this._value[t]+=e[t]||0;return this}copy(e){for(let t=0;t<this._value.length;t++)this._value[t]=e._value[t]||0;return this}length(){let e=0;for(let t of this._value)e+=t*t;return Math.sqrt(e)}read(){let e=this._value.slice();return this._value.fill(0),e}}class Oj{constructor(e){for(let t in this.deltas={},e)this.deltas[t]=new O$(e[t]);}read(){let e={};for(let t in this.deltas)e[t]=this.deltas[t].read();return e}}class OK extends Oj{on(e,t){this._events.on(e,t);}off(e,t){this._events.off(e,t);}fire(e,...t){this._events.fire(e,...t);}attach(e){this._element&&this.detach(),this._element=e;}detach(){this._element&&(this._element=null,this.read());}destroy(){this.detach(),this._events.off();}constructor(...e){super(...e),this._element=null,this._events=new eo;}}class OZ{update(e,t){e.read();}}class OQ extends OZ{attach(e,t=true){}detach(){}update(e,t){return super.update(e,t),this._pose}destroy(){this.detach();}constructor(...e){super(...e),this._pose=new Oq;}}let OJ=new eN;class O0{constructor({range:e}={}){this._range=70,this._position=new eN,this._value=new eN,this._range=e??this._range;}get value(){return this._value}down(e,t){return this._position.set(e,t),this._value.set(0,0),[e,t,e,t]}move(e,t){OJ.set(e-this._position.x,t-this._position.y),OJ.length()>this._range&&OJ.normalize().mulScalar(this._range),this._value.set(eA.clamp(OJ.x/this._range,-1,1),eA.clamp(OJ.y/this._range,-1,1));let{x:i,y:s}=this._position;return [i,s,i+OJ.x,s+OJ.y]}up(){return this._position.set(0,0),this._value.set(0,0),[-1,-1,-1,-1]}}class O1 extends OK{constructor(){super({input:[0,0],doubleTap:[0]}),this._layout="joystick",this._pointerData=new Map,this._lastPointer={x:0,y:0,time:0},this._joystick=new O0,this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this);}set layout(e){this._layout!==e&&(this._layout=e,this.read(),this._pointerData.clear());}get layout(){return this._layout}get joystick(){return this._joystick}_onPointerDown(e){let{pointerType:t,pointerId:i,clientX:s,clientY:r}=e;if("touch"!==t)return;this._element?.setPointerCapture(i),this._pointerData.set(i,{x:s,y:r});let a=Date.now();(this._lastPointer.x-s)**2+(this._lastPointer.y-r)**2<100&&a-this._lastPointer.time<250&&this.deltas.doubleTap.append([1]),this._lastPointer.x=s,this._lastPointer.y=r,this._lastPointer.time=a,"joystick"===this._layout&&this.fire("joystick:position",this._joystick.down(s,r));}_onPointerMove(e){let{pointerType:t,pointerId:i,target:s,clientX:r,clientY:a,movementX:n,movementY:o}=e;if("touch"!==t||s!==this._element)return;let l=this._pointerData.get(i);l&&(l.x=r,l.y=a,"joystick"===this._layout?this.fire("joystick:position",this._joystick.move(r,a)):this.deltas.input.append([n,o]));}_onPointerUp(e){let{pointerType:t,pointerId:i}=e;"touch"===t&&(this._element?.releasePointerCapture(i),this._pointerData.get(i)&&(this._pointerData.delete(i),"joystick"===this._layout&&this.fire("joystick:position",this._joystick.up())));}attach(e){super.attach(e),this._element=e,this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp);}detach(){this._element&&(this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._pointerData.clear(),super.detach());}read(){return this.deltas.input.append([this._joystick.value.x,this._joystick.value.y]),super.read()}destroy(){this._joystick.up(),super.destroy();}}let O2=(e,t)=>0===e.indexOf(t),O3=(e,t)=>-1!==e.indexOf(t,e.length-t.length);class O4 extends OK{constructor(e){super({leftInput:[0,0],rightInput:[0,0],doubleTap:[0]}),this._layout="joystick-touch",this._pointerData=new Map,this._lastPointer={x:0,y:0,time:0},e&&(this.layout=e),this._leftJoystick=new O0,this._rightJoystick=new O0,this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this);}set layout(e){this._layout!==e&&(this._layout=e,this.read(),this._pointerData.clear());}get layout(){return this._layout}get leftJoystick(){return this._leftJoystick}get rightJoystick(){return this._rightJoystick}_onPointerDown(e){let{pointerType:t,pointerId:i,clientX:s,clientY:r}=e;if("touch"!==t)return;this._element?.setPointerCapture(i);let a=s<.5*window.innerWidth;this._pointerData.set(i,{x:s,y:r,left:a});let n=Date.now();(this._lastPointer.x-s)**2+(this._lastPointer.y-r)**2<100&&n-this._lastPointer.time<250&&this.deltas.doubleTap.append([1]),this._lastPointer.x=s,this._lastPointer.y=r,this._lastPointer.time=n,a&&O2(this._layout,"joystick")&&this.fire("joystick:position:left",this._leftJoystick.down(s,r)),!a&&O3(this._layout,"joystick")&&this.fire("joystick:position:right",this._rightJoystick.down(s,r));}_onPointerMove(e){let{pointerType:t,pointerId:i,target:s,clientX:r,clientY:a,movementX:n,movementY:o}=e;if("touch"!==t||s!==this._element)return;let l=this._pointerData.get(i);if(!l)return;let{left:h}=l;l.x=r,l.y=a,h?O2(this._layout,"joystick")?this.fire("joystick:position:left",this._leftJoystick.move(r,a)):this.deltas.leftInput.append([n,o]):O3(this._layout,"joystick")?this.fire("joystick:position:right",this._rightJoystick.move(r,a)):this.deltas.rightInput.append([n,o]);}_onPointerUp(e){let{pointerType:t,pointerId:i}=e;if("touch"!==t)return;this._element?.releasePointerCapture(i);let s=this._pointerData.get(i);if(!s)return;let{left:r}=s;this._pointerData.delete(i),r&&O2(this._layout,"joystick")&&this.fire("joystick:position:left",this._leftJoystick.up()),!r&&O3(this._layout,"joystick")&&this.fire("joystick:position:right",this._rightJoystick.up());}attach(e){super.attach(e),this._element=e,this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp);}detach(){this._element&&(this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._pointerData.clear(),super.detach());}read(){return this.deltas.leftInput.append([this._leftJoystick.value.x,this._leftJoystick.value.y]),this.deltas.rightInput.append([this._rightJoystick.value.x,this._rightJoystick.value.y]),super.read()}destroy(){this._leftJoystick.up(),this._rightJoystick.up(),super.destroy();}}let O5=new eN;class O8 extends OK{constructor(){super({touch:[0,0],count:[0],pinch:[0]}),this._pointerEvents=new Map,this._pointerPos=new eN,this._pinchDist=-1,this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onContextMenu=this._onContextMenu.bind(this);}_onPointerDown(e){let{pointerId:t,pointerType:i}=e;"touch"===i&&(this._element?.setPointerCapture(t),this._pointerEvents.set(t,e),this.deltas.count.append([1]),this._pointerEvents.size>1&&(this._getMidPoint(this._pointerPos),this._pinchDist=this._getPinchDist()));}_onPointerMove(e){let{pointerType:t,target:i,pointerId:s,movementX:r,movementY:a}=e;if("touch"===t&&i===this._element&&0!==this._pointerEvents.size)if(this._pointerEvents.set(s,e),this._pointerEvents.size>1){let e=this._getMidPoint(O5);this.deltas.touch.append([e.x-this._pointerPos.x,e.y-this._pointerPos.y]),this._pointerPos.copy(e);let t=this._getPinchDist();this._pinchDist>0&&this.deltas.pinch.append([this._pinchDist-t]),this._pinchDist=t;}else this.deltas.touch.append([r,a]);}_onPointerUp(e){let{pointerType:t,pointerId:i}=e;"touch"===t&&(this._element?.releasePointerCapture(i),this._pointerEvents.delete(i),this.deltas.count.append([-1]),this._pointerEvents.size<2&&(this._pinchDist=-1),this._pointerPos.set(0,0));}_onContextMenu(e){e.preventDefault();}_getMidPoint(e){if(this._pointerEvents.size<2)return e.set(0,0);let[t,i]=this._pointerEvents.values(),s=t.clientX-i.clientX,r=t.clientY-i.clientY;return e.set(i.clientX+.5*s,i.clientY+.5*r)}_getPinchDist(){if(this._pointerEvents.size<2)return 0;let[e,t]=this._pointerEvents.values(),i=e.clientX-t.clientX,s=e.clientY-t.clientY;return Math.sqrt(i*i+s*s)}attach(e){super.attach(e),this._element=e,this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp),this._element.addEventListener("contextmenu",this._onContextMenu);}detach(){this._element&&(this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._element.removeEventListener("contextmenu",this._onContextMenu),this._pointerEvents.clear(),super.detach());}}let O6={passive:false},O9={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,0:26,1:27,2:28,3:29,4:30,5:31,6:32,7:33,8:34,9:35,UP:36,DOWN:37,LEFT:38,RIGHT:39,SPACE:40,SHIFT:41,CTRL:42},O7=Object.keys(O9).length,Ne=Array(O7).fill(0);class Nt extends OK{static{this.keyCode=O9;}constructor({pointerLock:e=false}={}){super({key:Array(O7).fill(0),button:[0,0,0],mouse:[0,0],wheel:[0]}),this._pointerId=0,this._keyMap=new Map,this._keyPrev=Array(O7).fill(0),this._keyNow=Array(O7).fill(0),this._button=[,,,].fill(0),this._pointerLock=e??false;let{keyCode:t}=Nt;for(let e=0;e<26;e++){let i=`Key${String.fromCharCode(65+e)}`;this._keyMap.set(i,t.A+e);}for(let e=0;e<10;e++){let i=`Digit${e}`;this._keyMap.set(i,t["0"]+e);}this._keyMap.set("ArrowUp",t.UP),this._keyMap.set("ArrowDown",t.DOWN),this._keyMap.set("ArrowLeft",t.LEFT),this._keyMap.set("ArrowRight",t.RIGHT),this._keyMap.set("Space",t.SPACE),this._keyMap.set("ShiftLeft",t.SHIFT),this._keyMap.set("ShiftRight",t.SHIFT),this._keyMap.set("ControlLeft",t.CTRL),this._keyMap.set("ControlRight",t.CTRL),this._onWheel=this._onWheel.bind(this),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onKeyUp=this._onKeyUp.bind(this);}_onWheel(e){e.preventDefault(),this.deltas.wheel.append([e.deltaY]);}_onPointerDown(e){"mouse"===e.pointerType&&(this._pointerLock?document.pointerLockElement!==this._element&&this._element?.requestPointerLock():this._element?.setPointerCapture(e.pointerId),this._clearButtons(),this._button[e.button]=1,this.deltas.button.append(this._button),this._pointerId||(this._pointerId=e.pointerId));}_onPointerMove(e){if("mouse"===e.pointerType&&e.target===this._element){if(this._pointerLock){if(document.pointerLockElement!==this._element)return}else if(this._pointerId!==e.pointerId)return;this.deltas.mouse.append([e.movementX,e.movementY]);}}_onPointerUp(e){"mouse"===e.pointerType&&(this._pointerLock||this._element?.releasePointerCapture(e.pointerId),this._clearButtons(),this.deltas.button.append(this._button),this._pointerId===e.pointerId&&(this._pointerId=0));}_onContextMenu(e){e.preventDefault();}_onKeyDown(e){this._pointerLock&&document.pointerLockElement!==this._element||(e.stopPropagation(),this._setKey(e.code,1));}_onKeyUp(e){e.stopPropagation(),this._setKey(e.code,0);}_clearButtons(){for(let e=0;e<this._button.length;e++){if(1===this._button[e]){this._button[e]=-1;continue}this._button[e]=0;}}_setKey(e,t){this._keyMap.has(e)&&(this._keyNow[this._keyMap.get(e)??0]=t);}attach(e){super.attach(e),this._element=e,this._element.addEventListener("wheel",this._onWheel,O6),this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp),this._element.addEventListener("contextmenu",this._onContextMenu),window.addEventListener("keydown",this._onKeyDown,false),window.addEventListener("keyup",this._onKeyUp,false);}detach(){this._element&&(this._element.removeEventListener("wheel",this._onWheel,O6),this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._element.removeEventListener("contextmenu",this._onContextMenu),window.removeEventListener("keydown",this._onKeyDown,false),window.removeEventListener("keyup",this._onKeyUp,false),this._keyNow.fill(0),this._keyPrev.fill(0),super.detach());}read(){for(let e=0;e<Ne.length;e++)Ne[e]=this._keyNow[e]-this._keyPrev[e],this._keyPrev[e]=this._keyNow[e];return this.deltas.key.append(Ne),super.read()}}let Ni={A:0,B:1,X:2,Y:3,LB:4,RB:5,LT:6,RT:7,SELECT:8,START:9,LEFT_STICK:10,RIGHT_STICK:11},Ns=Object.keys(Ni).length;class Nr extends OK{static{this.buttonCode=Ni;}constructor(){super({buttons:Array(Ns).fill(0),leftStick:[0,0],rightStick:[0,0]}),this._buttonPrev=Array(Ns).fill(0);}read(){let e=navigator.getGamepads();for(let t=0;t<e.length;t++){let i=e[t];if(!i||"standard"!==i.mapping||i.axes.length<4||i.buttons.length<Ns)continue;let{buttons:s,axes:r}=i;for(let e=0;e<this._buttonPrev.length;e++){let t=+s[e].pressed;this.deltas.buttons[e]=t-this._buttonPrev[e],this._buttonPrev[e]=t;}this.deltas.leftStick.append([r[0],r[1]]),this.deltas.rightStick.append([r[2],r[3]]);}return super.read()}}let Na=(e,t)=>1-Math.pow(e,1e3*t),Nn=new eM,No=new eM,Nl=new eM,Nh=new eM,Nc=new eM,Nd=new eH;class Nu extends OQ{set pitchRange(e){this._targetPose.pitchRange.copy(e),this._pose.copy(this._targetPose.rotate(eM.ZERO));}get pitchRange(){return this._targetPose.pitchRange}set yawRange(e){this._targetPose.yawRange.copy(e),this._pose.copy(this._targetPose.rotate(eM.ZERO));}get yawRange(){return this._targetPose.yawRange}attach(e,t=true){this._targetPose.copy(e),t||this._pose.copy(this._targetPose);}detach(){this._targetPose.copy(this._pose);}update(e,t){let{move:i,rotate:s}=e.read();return this._targetPose.rotate(No.set(-s[1],-s[0],0)),Nd.setFromEulerAngles(this._pose.angles),Nd.transformVector(eM.FORWARD,Nl),Nd.transformVector(eM.RIGHT,Nh),Nd.transformVector(eM.UP,Nc),Nn.set(0,0,0),Nn.add(Nl.mulScalar(i[2])),Nn.add(Nh.mulScalar(i[0])),Nn.add(Nc.mulScalar(i[1])),this._targetPose.move(Nn),this._pose.lerp(this._pose,this._targetPose,Na(this.moveDamping,t),Na(this.rotateDamping,t))}destroy(){this.detach();}constructor(...e){super(...e),this._targetPose=new Oq,this.rotateDamping=.98,this.moveDamping=.98;}}let Nf=new eM,Np=new eM,Nm=new eM,N_=new eH;class Ng extends OQ{set pitchRange(e){this._targetRootPose.pitchRange.copy(e),this._rootPose.copy(this._targetRootPose.rotate(eM.ZERO));}get pitchRange(){return this._targetRootPose.pitchRange}set yawRange(e){this._targetRootPose.yawRange.copy(e),this._rootPose.copy(this._targetRootPose.rotate(eM.ZERO));}get yawRange(){return this._targetRootPose.yawRange}set zoomRange(e){this._targetChildPose.zRange.copy(e),this._childPose.copy(this._targetChildPose.move(eM.ZERO));}get zoomRange(){return this._targetRootPose.zRange}attach(e,t=true){this._targetRootPose.set(e.getFocus(Nf),e.angles,0),this._targetChildPose.position.set(0,0,e.distance),t||(this._rootPose.copy(this._targetRootPose),this._childPose.copy(this._targetChildPose));}detach(){this._targetRootPose.copy(this._rootPose),this._targetChildPose.copy(this._childPose);}update(e,t){let{move:i,rotate:s}=e.read();Np.set(i[0],i[1],0),N_.setFromEulerAngles(this._rootPose.angles).transformVector(Np,Np),this._targetRootPose.move(Np);let{z:r}=this._targetChildPose.position;return this._targetChildPose.move(Np.set(0,0,r*(1+i[2])-r)),this._targetRootPose.rotate(Nm.set(-s[1],-s[0],0)),this._rootPose.lerp(this._rootPose,this._targetRootPose,Na(this.moveDamping,t),Na(this.rotateDamping,t),1),this._childPose.lerp(this._childPose,this._targetChildPose,Na(this.zoomDamping,t),1,1),N_.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position,Np).add(this._rootPose.position),this._pose.set(Np,this._rootPose.angles,this._childPose.position.z)}destroy(){this.detach();}constructor(...e){super(...e),this._targetRootPose=new Oq,this._rootPose=new Oq,this._targetChildPose=new Oq,this._childPose=new Oq,this.rotateDamping=.98,this.moveDamping=.98,this.zoomDamping=.98;}}let Nv=new eM,NS=new eM,Ny=new eH;class Nx extends OQ{attach(e,t=true){this._targetRootPose.set(e.getFocus(Nv),e.angles,0),this._targetChildPose.position.set(0,0,e.distance),t||(this._rootPose.copy(this._targetRootPose),this._childPose.copy(this._targetChildPose));}detach(){this._targetRootPose.copy(this._rootPose),this._targetChildPose.copy(this._childPose);}complete(){return this._targetRootPose.equalsApprox(this._rootPose,.001)&&this._targetChildPose.equalsApprox(this._childPose,.001)}update(e,t){return e.read(),this._rootPose.lerp(this._rootPose,this._targetRootPose,Na(this.focusDamping,t),Na(this.focusDamping,t),1),this._childPose.lerp(this._childPose,this._targetChildPose,Na(this.focusDamping,t),1,1),Ny.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position,NS).add(this._rootPose.position),this._pose.set(NS,this._rootPose.angles,this._childPose.position.length())}destroy(){this.detach();}constructor(...e){super(...e),this._targetRootPose=new Oq,this._rootPose=new Oq,this._targetChildPose=new Oq,this._childPose=new Oq,this.focusDamping=.98;}}let NT="local",NE="world",NA="x",Nb="y",Nw="z",NC="yz",NP="xz",NL="xy",NI="xyz",ND="face",NR=new eM,NM=new eM,NO=new eG,NN=new eG,NF=new e1,NB="Gizmo";class NU extends eo{static{this.EVENT_POINTERDOWN="pointer:down";}static{this.EVENT_POINTERMOVE="pointer:move";}static{this.EVENT_POINTERUP="pointer:up";}static{this.EVENT_POSITIONUPDATE="position:update";}static{this.EVENT_ROTATIONUPDATE="rotation:update";}static{this.EVENT_SCALEUPDATE="scale:update";}static{this.EVENT_NODESATTACH="nodes:attach";}static{this.EVENT_NODESDETACH="nodes:detach";}static{this.EVENT_RENDERUPDATE="render:update";}static createLayer(e,t=NB,i){let s=new gH({name:t,clearDepthBuffer:true,opaqueSortMode:pO,transparentSortMode:pO});return e.scene.layers.insert(s,i??e.scene.layers.layerList.length),s}constructor(e,t){super(),this._size=1,this._scale=1,this._coordSpace=NE,this.nodes=[],this.intersectShapes=[],this._camera=e,this._app=e.system.app,this._device=this._app.graphicsDevice,this._layer=t,e.layers=e.layers.concat(t.id),this.root=new x1("gizmo"),this._app.root.addChild(this.root),this.root.enabled=false,this._updateScale(),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._device.canvas.addEventListener("pointerdown",this._onPointerDown),this._device.canvas.addEventListener("pointermove",this._onPointerMove),this._device.canvas.addEventListener("pointerup",this._onPointerUp),this._app.on("update",()=>{this._updatePosition(),this._updateRotation(),this._updateScale();}),this._app.on("destroy",()=>this.destroy());}get layer(){return this._layer}set coordSpace(e){this._coordSpace=e??NE,this._updateRotation();}get coordSpace(){return this._coordSpace}set size(e){this._size=e,this._updateScale();}get size(){return this._size}get facing(){if(this._camera.projection===fp){let e=this.root.getPosition(),t=this._camera.entity.getPosition();return NM.sub2(t,e).normalize()}return NM.copy(this._camera.entity.forward).mulScalar(-1)}_onPointerDown(e){if(!this.root.enabled||document.pointerLockElement)return;let t=this._getSelection(e.offsetX,e.offsetY);t[0]&&(e.preventDefault(),e.stopPropagation());let{canvas:i}=this._device;i.setPointerCapture(e.pointerId),this.fire(NU.EVENT_POINTERDOWN,e.offsetX,e.offsetY,t[0]);}_onPointerMove(e){if(!this.root.enabled||document.pointerLockElement)return;let t=this._getSelection(e.offsetX,e.offsetY);t[0]&&(e.preventDefault(),e.stopPropagation()),this.fire(NU.EVENT_POINTERMOVE,e.offsetX,e.offsetY,t[0]);}_onPointerUp(e){if(!this.root.enabled||document.pointerLockElement)return;let t=this._getSelection(e.offsetX,e.offsetY);t[0]&&(e.preventDefault(),e.stopPropagation());let{canvas:i}=this._device;i.releasePointerCapture(e.pointerId),this.fire(NU.EVENT_POINTERUP,e.offsetX,e.offsetY,t[0]);}_updatePosition(){NR.set(0,0,0);for(let e=0;e<this.nodes.length;e++){let t=this.nodes[e];NR.add(t.getPosition());}NR.mulScalar(1/(this.nodes.length||1)),1e-6>NR.distance(this.root.getPosition())||(this.root.setPosition(NR),this.fire(NU.EVENT_POSITIONUPDATE,NR));}_updateRotation(){NR.set(0,0,0),this._coordSpace===NT&&0!==this.nodes.length&&NR.copy(this.nodes[this.nodes.length-1].getEulerAngles()),1e-6>NR.distance(this.root.getEulerAngles())||(this.root.setEulerAngles(NR),this.fire(NU.EVENT_ROTATIONUPDATE,NR));}_updateScale(){if(this._camera.projection===fp){let e=this.root.getPosition(),t=this._camera.entity.getPosition(),i=e.distance(t);this._scale=Math.tan(.5*this._camera.fov*eA.DEG_TO_RAD)*i*.3;}else this._scale=.32*this._camera.orthoHeight;this._scale=Math.max(this._scale*this._size,1e-4),1e-6>Math.abs(this._scale-this.root.getLocalScale().x)||(this.root.setLocalScale(this._scale,this._scale,this._scale),this.fire(NU.EVENT_SCALEUPDATE,this._scale));}_getSelection(e,t){let i=this._camera.screenToWorld(e,t,0),s=this._camera.screenToWorld(e,t,this._camera.farClip-this._camera.nearClip),r=NR.copy(s).sub(i).normalize(),a=[];for(let e=0;e<this.intersectShapes.length;e++){let t=this.intersectShapes[e];if(t.disabled||!t.entity.enabled)continue;let s=t.entity.getWorldTransform();for(let e=0;e<t.triData.length;e++){let{tris:n,transform:o,priority:l}=t.triData[e],h=NO.copy(s).mul(o),c=NN.copy(h).invert();c.transformPoint(i,NF.origin),c.transformVector(r,NF.direction),NF.direction.normalize();for(let e=0;e<n.length;e++)n[e].intersectsRay(NF,NR)&&a.push({dist:h.transformPoint(NR).sub(i).length(),meshInstances:t.meshInstances,priority:l});}}return a.length?(a.sort((e,t)=>0!==e.priority&&0!==t.priority?t.priority-e.priority:e.dist-t.dist),a[0].meshInstances):[]}attach(e=[]){if(Array.isArray(e)){if(0===e.length)return;this.nodes=e;}else this.nodes=[e];this._updatePosition(),this._updateRotation(),this._updateScale(),this.fire(NU.EVENT_NODESATTACH),this.root.enabled=true,this.fire(NU.EVENT_RENDERUPDATE);}detach(){this.root.enabled=false,this.fire(NU.EVENT_RENDERUPDATE),this.fire(NU.EVENT_NODESDETACH),this.nodes=[];}destroy(){this.detach(),this._device.canvas.removeEventListener("pointerdown",this._onPointerDown),this._device.canvas.removeEventListener("pointermove",this._onPointerMove),this._device.canvas.removeEventListener("pointerup",this._onPointerUp),this.root.destroy();}}let Nk=Object.freeze(new eb(1,.3,.3)),NV=Object.freeze(new eb(.3,1,.3)),Nz=Object.freeze(new eb(.3,.3,1)),NG=Object.freeze(new eb(1,1,.5)),NH=Object.freeze(new eb(.5,.5,.5,.5)),NW=e=>new eb(e.r,e.g,e.b),NX=(e,t)=>new eb(e.r,e.g,e.b,t),NY=new eM,Nq=new eM,N$=new eH,Nj=new e1,NK=new eJ,NZ=Object.keys(NY);class NQ extends NU{static{this.EVENT_TRANSFORMSTART="transform:start";}static{this.EVENT_TRANSFORMMOVE="transform:move";}static{this.EVENT_TRANSFORMEND="transform:end";}constructor(e,t){super(e,t),this._colorAlpha=.6,this._meshColors={axis:{x:this._colorSemi(Nk),y:this._colorSemi(NV),z:this._colorSemi(Nz),xyz:this._colorSemi(eb.WHITE),f:this._colorSemi(eb.WHITE)},hover:{x:Nk.clone(),y:NV.clone(),z:Nz.clone(),xyz:eb.WHITE.clone(),f:NG.clone()},disabled:NH.clone()},this._guideColors={x:Nk.clone(),y:NV.clone(),z:Nz.clone(),f:NG.clone()},this._rootStartPos=new eM,this._rootStartRot=new eH,this._shading=false,this._shapes={},this._shapeMap=new Map,this._hoverShape=null,this._hoverAxis="",this._hoverIsPlane=false,this._noSelection=false,this._selectedAxis="",this._selectedIsPlane=false,this._selectionStartPoint=new eM,this._dragging=false,this._snap=false,this.snapIncrement=1,this._app.on("prerender",()=>{this.root.enabled&&this._drawGuideLines();}),this.on(NU.EVENT_POINTERDOWN,(e,t,i)=>{let s=this._shapeMap.get(i);if(s?.disabled||this._dragging)return;if(!i){this._noSelection=true;return}this._selectedAxis=this._getAxis(i),this._selectedIsPlane=this._getIsPlane(i),this._rootStartPos.copy(this.root.getPosition()),this._rootStartRot.copy(this.root.getRotation());let r=this._screenToPoint(e,t);this._selectionStartPoint.copy(r),this._dragging=true,this.fire(NQ.EVENT_TRANSFORMSTART,r,e,t);}),this.on(NU.EVENT_POINTERMOVE,(e,t,i)=>{let s=this._shapeMap.get(i);if(s?.disabled||(this._noSelection||this._hover(i),!this._dragging))return;let r=this._screenToPoint(e,t);this.fire(NQ.EVENT_TRANSFORMMOVE,r,e,t),this._hoverAxis="",this._hoverIsPlane=false;}),this.on(NU.EVENT_POINTERUP,(e,t,i)=>{this._noSelection=false,this._hover(i),this._dragging&&(this._dragging=false,this.fire(NQ.EVENT_TRANSFORMEND),this._selectedAxis="",this._selectedIsPlane=false);}),this.on(NU.EVENT_NODESDETACH,()=>{this.snap=false,this._hoverAxis="",this._hoverIsPlane=false,this._hover(),this.fire(NU.EVENT_POINTERUP);});}set shading(e){for(let t in this._shading=this.root.enabled&&e,this._shapes)this._shapes[t].shading=this._shading;}get shading(){return this._shading}set snap(e){this._snap=this.root.enabled&&e;}get snap(){return this._snap}set xAxisColor(e){this._updateAxisColor(NA,e);}get xAxisColor(){return this._meshColors.axis.x}set yAxisColor(e){this._updateAxisColor(Nb,e);}get yAxisColor(){return this._meshColors.axis.y}set zAxisColor(e){this._updateAxisColor(Nw,e);}get zAxisColor(){return this._meshColors.axis.z}set colorAlpha(e){for(let t in this._colorAlpha=eA.clamp(e,0,1),this._meshColors.axis.x.copy(this._colorSemi(this._meshColors.axis.x)),this._meshColors.axis.y.copy(this._colorSemi(this._meshColors.axis.y)),this._meshColors.axis.z.copy(this._colorSemi(this._meshColors.axis.z)),this._meshColors.axis.xyz.copy(this._colorSemi(this._meshColors.axis.xyz)),this._meshColors.axis.f.copy(this._colorSemi(this._meshColors.axis.f)),this._shapes)this._shapes[t].hover(!!this._hoverAxis);}get colorAlpha(){return this._colorAlpha}_colorSemi(e){return NX(e,this._colorAlpha)}_updateAxisColor(e,t){let i=NW(t),s=this._colorSemi(t);for(let t in this._guideColors[e].copy(i),this._meshColors.axis[e].copy(s),this._meshColors.hover[e].copy(i),this._shapes)this._shapes[t].hover(!!this._hoverAxis);}_getAxis(e){return e?e.node.name.split(":")[1]:""}_getIsPlane(e){return !!e&&-1!==e.node.name.indexOf("plane")}_hover(e){if(this._dragging)return;this._hoverAxis=this._getAxis(e),this._hoverIsPlane=this._getIsPlane(e);let t=e?this._shapeMap.get(e)??null:null;t!==this._hoverShape&&(this._hoverShape&&(this._hoverShape.hover(false),this._hoverShape=null),t&&(t.hover(true),this._hoverShape=t),this.fire(NU.EVENT_RENDERUPDATE));}_createRay(e){if(this._camera.projection===fp)return Nj.origin.copy(this._camera.entity.getPosition()),Nj.direction.sub2(e,Nj.origin).normalize(),Nj;let t=this._camera.farClip-this._camera.nearClip;return Nj.origin.sub2(e,NY.copy(this._camera.entity.forward).mulScalar(t)),Nj.direction.copy(this._camera.entity.forward),Nj}_createPlane(e,t,i){let s=NY.copy(this.facing),r=NK.normal.set(0,0,0);return t?r.copy(s):(r[e]=1,this._rootStartRot.transformVector(r,r),i&&(Nq.cross(r,s).normalize(),r.cross(Nq,r).normalize())),NK.setFromPointNormal(this._rootStartPos,r)}_dirFromAxis(e,t){return e===ND?t.copy(this._camera.entity.forward).mulScalar(-1):(t.set(0,0,0),t[e]=1),t}_projectToAxis(e,t){NY.set(0,0,0),NY[t]=1,e.copy(NY.mulScalar(NY.dot(e)));let i=e[t];e.set(0,0,0),e[t]=i;}_screenToPoint(e,t,i=false,s=false){let r=this._camera.screenToWorld(e,t,1),a=this._selectedAxis,n=this._createRay(r),o=this._createPlane(a,i,s),l=new eM;return o.intersectsRay(n,l),l}_drawGuideLines(){let e=this.root.getPosition(),t=N$.copy(this.root.getRotation()),i=this._hoverAxis||this._selectedAxis,s=this._hoverIsPlane||this._selectedIsPlane;for(let r=0;r<NZ.length;r++){let a=NZ[r];if(i===NI){this._drawSpanLine(e,t,a);continue}s?a!==i&&this._drawSpanLine(e,t,a):a===i&&this._drawSpanLine(e,t,a);}}_drawSpanLine(e,t,i){NY.set(0,0,0),NY[i]=1,NY.mulScalar(this._camera.farClip-this._camera.nearClip),Nq.copy(NY).mulScalar(-1),t.transformVector(NY,NY),t.transformVector(Nq,Nq),this._app.drawLine(NY.add(e),Nq.add(e),this._guideColors[i],true);}_createTransform(){for(let e in this._shapes){let t=this._shapes[e];this.root.addChild(t.entity),this.intersectShapes.push(t);for(let e=0;e<t.meshInstances.length;e++)this._shapeMap.set(t.meshInstances[e],t);}}enableShape(e,t){this._shapes.hasOwnProperty(e)&&(this._shapes[e].disabled=!t);}isShapeEnabled(e){return !!this._shapes.hasOwnProperty(e)&&!this._shapes[e].disabled}destroy(){for(let e in super.destroy(),this._shapes)this._shapes[e].destroy();}}let NJ=new eM,N0=new eM,N1=new eM;class N2{constructor(e,t=0){this._priority=0,this._transform=new eG,this.tris=[],this.fromGeometry(e),this._priority=t;}get transform(){return this._transform}get priority(){return this._priority}setTransform(e=new eM,t=new eH,i=new eM){this.transform.setTRS(e,t,i);}fromGeometry(e){if(!e||!(e instanceof vQ))throw Error("No geometry provided.");let t=e.positions??[],i=e.indices??[];this.tris=[];for(let e=0;e<i.length;e+=3){let s=i[e],r=i[e+1],a=i[e+2];NJ.set(t[3*s],t[3*s+1],t[3*s+2]),N0.set(t[3*r],t[3*r+1],t[3*r+2]),N1.set(t[3*a],t[3*a+1],t[3*a+2]);let n=new ti(NJ,N0,N1);this.tris.push(n);}}}let N3=new eM(1,2,3),N4={box:vJ,cone:yx,cylinder:yT,plane:yE,sphere:v0,torus:yA},N5={uniqueName:"axis-shape",attributes:{vertex_position:sT,vertex_color:sC},vertexGLSL:`
attribute vec3 vertex_position;
attribute vec4 vertex_color;
varying vec4 vColor;
uniform mat4 matrix_model;
uniform mat4 matrix_viewProjection;
void main(void) {
gl_Position = matrix_viewProjection * matrix_model * vec4(vertex_position, 1.0);
gl_Position.z = clamp(gl_Position.z, -abs(gl_Position.w), abs(gl_Position.w));
vColor = vertex_color;
}
`,fragmentGLSL:`
#include "gammaPS"
precision highp float;
varying vec4 vColor;
void main(void) {
gl_FragColor = vec4(gammaCorrectOutput(decodeGamma(vColor)), vColor.w);
}
`,vertexWGSL:`
attribute vertex_position: vec3f;
attribute vertex_color: vec4f;
uniform matrix_model: mat4x4f;
uniform matrix_viewProjection: mat4x4f;
varying vColor: vec4f;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.vColor = input.vertex_color;
let pos = vec4f(input.vertex_position, 1.0);
output.position = uniform.matrix_viewProjection * uniform.matrix_model * pos;
output.position.z = clamp(output.position.z, -abs(output.position.w), abs(output.position.w));
return output;
}
`,fragmentWGSL:`
#include "gammaPS"
varying vColor: vec4f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
output.color = vec4f(gammaCorrectOutput(decodeGamma(input.vColor)), input.vColor.w);
return output;
}
`},N8=new Map,N6=new eM,N9=new eM,N7=new eG,Fe=new vQ;Fe.positions=[],Fe.normals=[];let Ft=(e,t,i)=>{let s;if(!e.normals||!e.positions)return [];i&&(s=N7.copy(i).invert().transformVector(N6.copy(N3),N6).normalize()),e.colors=[];let r=[],a=e.positions.length/3;for(let i=0;i<a;i++){let a=1;if(s){let t=e.normals[3*i],r=e.normals[3*i+1],n=e.normals[3*i+2],o=N9.set(t,r,n);a=.25*s.dot(o)+.75;}r.push(a),e.colors.push(a*t.r*255,a*t.g*255,a*t.b*255,255*t.a);}return r},Fi=(e,t)=>{let i=N8.get(e),s=[];for(let e=0;e<i.length;e++)s.push(i[e]*t.r*255,i[e]*t.g*255,i[e]*t.b*255,255*t.a);e.setColors32(s),e.update();};class Fs{constructor(e,t){this._layers=[],this._shading=true,this._defaultColor=eb.WHITE,this._hoverColor=eb.BLACK,this._disabledColor=NH,this._cull=tq,this.triData=[],this.meshInstances=[],this.device=e,this.axis=t.axis??"x",this._position=t.position??new eM,this._rotation=t.rotation??new eM,this._scale=t.scale??new eM(1,1,1),this._disabled=t.disabled??false,this._layers=t.layers??this._layers,this._shading=t.shading??this._shading,t.defaultColor instanceof eb&&(this._defaultColor=t.defaultColor),t.hoverColor instanceof eb&&(this._hoverColor=t.hoverColor),t.disabledColor instanceof eb&&(this._disabledColor=t.disabledColor);}set disabled(e){for(let t=0;t<this.meshInstances.length;t++)Fi(this.meshInstances[t].mesh,e?this._disabledColor:this._defaultColor);this._disabled=e??false;}get disabled(){return this._disabled}set shading(e){this._shading=e??true;let t=this._disabled?this._disabledColor:this._defaultColor;for(let e=0;e<this.meshInstances.length;e++){let i=this.meshInstances[e].mesh;i.getPositions(Fe.positions),i.getNormals(Fe.normals);let s=Ft(Fe,t,this._shading?this.entity.getWorldTransform():void 0);N8.set(i,s),Fi(i,t);}}get shading(){return this._shading}_createRoot(e){this.entity=new x1(`${e}:${this.axis}`),this.entity.setLocalPosition(this._position),this.entity.setLocalEulerAngles(this._rotation),this.entity.setLocalScale(this._scale);}_createMesh(e,t=true){let i=Ft(e,this._disabled?this._disabledColor:this._defaultColor,t?this.entity.getWorldTransform():void 0),s=mw.fromGeometry(this.device,e);return N8.set(s,i),s}_createRenderComponent(e,t){let i=new vY(N5);i.cull=this._cull,i.blendType=ua,i.update();let s=[];for(let e=0;e<t.length;e++){let r=new mV(t[e],i);r.cull=false,s.push(r),this.meshInstances.push(r);}e.addComponent("render",{meshInstances:s,layers:this._layers,castShadows:false});}_addRenderMesh(e,t,i){let s=N4[t];if(!s)throw Error("Invalid primitive type.");this._createRenderComponent(e,[this._createMesh(new s,i)]);}hover(e){if(!this._disabled)for(let t=0;t<this.meshInstances.length;t++){let i=e?this._hoverColor:this._defaultColor;Fi(this.meshInstances[t].mesh,i);}}destroy(){this.entity.destroy();}}class Fr extends Fs{constructor(e,t={}){super(e,t),this._cull=tY,this._size=.2,this._gap=.1,this._flipped=new eM,this.triData=[new N2(new yE)],this._createPlane();}set size(e){this._size=e??1,this._updateTransform();}get size(){return this._size}set gap(e){this._gap=e??0,this._updateTransform();}get gap(){return this._gap}set flipped(e){1e-6>this._flipped.distance(e)||(this._flipped.copy(e),this.entity.setLocalPosition(this._getPosition()));}get flipped(){return this._flipped}_getPosition(){let e=this._size/2+this._gap,t=new eM(this._flipped.x?-e:e,this._flipped.y?-e:e,this._flipped.z?-e:e);return t[this.axis]=0,t}_createPlane(){this._createRoot("plane"),this._updateTransform(),this._addRenderMesh(this.entity,"plane",this._shading);}_updateTransform(){this.entity.setLocalPosition(this._getPosition()),this.entity.setLocalEulerAngles(this._rotation),this.entity.setLocalScale(this._size,this._size,this._size);}}let Fa=new eM,Fn=new eM,Fo=new eH;class Fl extends Fs{constructor(e,t={}){super(e,t),this._gap=0,this._lineThickness=.02,this._lineLength=.5,this._arrowThickness=.12,this._arrowLength=.18,this._tolerance=.1,this._flipped=false,this.triData=[new N2(new yx),new N2(new yT,1)],this._createArrow();}set gap(e){this._gap=e??0,this._updateHead(),this._updateLine();}get gap(){return this._gap}set lineThickness(e){this._lineThickness=e??1,this._updateHead(),this._updateLine();}get lineThickness(){return this._lineThickness}set lineLength(e){this._lineLength=e??1,this._updateHead(),this._updateLine();}get lineLength(){return this._lineLength}set arrowThickness(e){this._arrowThickness=e??1,this._updateHead();}get arrowThickness(){return this._arrowThickness}set arrowLength(e){this._arrowLength=e??1,this._updateHead();}get arrowLength(){return this._arrowLength}set tolerance(e){this._tolerance=e,this._updateLine();}get tolerance(){return this._tolerance}set flipped(e){this._flipped!==e&&(this._flipped=e,this._rotation.equals(eM.ZERO)?Fa.set(0,0,180*!!this._flipped):Fa.copy(this._rotation).mulScalar(this._flipped?-1:1),this._line.enabled=!this._flipped,this.entity.setLocalEulerAngles(Fa));}get flipped(){return this._flipped}_createArrow(){this._createRoot("arrow"),this._head=new x1(`head:${this.axis}`),this.entity.addChild(this._head),this._updateHead(),this._addRenderMesh(this._head,"cone",this._shading),this._line=new x1(`line:${this.axis}`),this.entity.addChild(this._line),this._updateLine(),this._addRenderMesh(this._line,"cylinder",this._shading);}_updateHead(){Fa.set(0,this._gap+.5*this._arrowLength+this._lineLength,0),Fo.set(0,0,0,1),Fn.set(this._arrowThickness,this._arrowLength,this._arrowThickness),this.triData[0].setTransform(Fa,Fo,Fn),this._head.setLocalPosition(0,this._gap+.5*this._arrowLength+this._lineLength,0),this._head.setLocalScale(this._arrowThickness,this._arrowLength,this._arrowThickness);}_updateLine(){Fa.set(0,this._gap+.5*this._lineLength,0),Fo.set(0,0,0,1),Fn.set(this._lineThickness+this._tolerance,this._lineLength,this._lineThickness+this._tolerance),this.triData[1].setTransform(Fa,Fo,Fn),this._line.setLocalPosition(0,this._gap+.5*this._lineLength,0),this._line.setLocalScale(this._lineThickness,this._lineLength,this._lineThickness);}}class Fh extends Fs{constructor(e,t={}){super(e,t),this._size=.12,this._tolerance=.05,this.triData=[new N2(new v0,2)],this._createCenter();}_createCenter(){this._createRoot("sphereCenter"),this._updateTransform(),this._addRenderMesh(this.entity,"sphere",this._shading);}set size(e){this._size=e??1,this._updateTransform();}get size(){return this._size}set tolerance(e){this._tolerance=e,this._updateTransform();}get tolerance(){return this._tolerance}_updateTransform(){this.entity.setLocalScale(this._size,this._size,this._size);}}let Fc=new eM,Fd=new eM,Fu=new eM,Ff=new eH;class Fp extends NQ{constructor(e,t){super(e,t),this._shapes={face:new Fh(this._device,{axis:ND,layers:[this._layer.id],shading:this._shading,defaultColor:this._meshColors.axis.xyz,hoverColor:this._meshColors.hover.xyz}),yz:new Fr(this._device,{axis:NA,layers:[this._layer.id],shading:this._shading,rotation:new eM(0,0,-90),defaultColor:this._meshColors.axis.x,hoverColor:this._meshColors.hover.x}),xz:new Fr(this._device,{axis:Nb,layers:[this._layer.id],shading:this._shading,rotation:new eM(0,0,0),defaultColor:this._meshColors.axis.y,hoverColor:this._meshColors.hover.y}),xy:new Fr(this._device,{axis:Nw,layers:[this._layer.id],shading:this._shading,rotation:new eM(90,0,0),defaultColor:this._meshColors.axis.z,hoverColor:this._meshColors.hover.z}),x:new Fl(this._device,{axis:NA,layers:[this._layer.id],shading:this._shading,rotation:new eM(0,0,-90),defaultColor:this._meshColors.axis.x,hoverColor:this._meshColors.hover.x}),y:new Fl(this._device,{axis:Nb,layers:[this._layer.id],shading:this._shading,rotation:new eM(0,0,0),defaultColor:this._meshColors.axis.y,hoverColor:this._meshColors.hover.y}),z:new Fl(this._device,{axis:Nw,layers:[this._layer.id],shading:this._shading,rotation:new eM(90,0,0),defaultColor:this._meshColors.axis.z,hoverColor:this._meshColors.hover.z})},this._nodeLocalPositions=new Map,this._nodePositions=new Map,this.snapIncrement=1,this.flipShapes=true,this._createTransform(),this.on(NQ.EVENT_TRANSFORMSTART,()=>{this._storeNodePositions();}),this.on(NQ.EVENT_TRANSFORMMOVE,e=>{let t=Fu.copy(e).sub(this._selectionStartPoint);this.snap&&(t.mulScalar(1/this.snapIncrement),t.round(),t.mulScalar(this.snapIncrement)),this._setNodePositions(t);}),this.on(NQ.EVENT_NODESDETACH,()=>{this._nodeLocalPositions.clear(),this._nodePositions.clear();}),this._app.on("prerender",()=>{this._shapesLookAtCamera();});}set axisGap(e){this._setArrowProp("gap",e);}get axisGap(){return this._shapes.x.gap}set axisLineThickness(e){this._setArrowProp("lineThickness",e);}get axisLineThickness(){return this._shapes.x.lineThickness}set axisLineLength(e){this._setArrowProp("lineLength",e);}get axisLineLength(){return this._shapes.x.lineLength}set axisLineTolerance(e){this._setArrowProp("tolerance",e);}get axisLineTolerance(){return this._shapes.x.tolerance}set axisArrowThickness(e){this._setArrowProp("arrowThickness",e);}get axisArrowThickness(){return this._shapes.x.arrowThickness}set axisArrowLength(e){this._setArrowProp("arrowLength",e);}get axisArrowLength(){return this._shapes.x.arrowLength}set axisPlaneSize(e){this._setPlaneProp("size",e);}get axisPlaneSize(){return this._shapes.yz.size}set axisPlaneGap(e){this._setPlaneProp("gap",e);}get axisPlaneGap(){return this._shapes.yz.gap}set axisCenterSize(e){this._shapes.face.size=e;}get axisCenterSize(){return this._shapes.face.size}set axisCenterTolerance(e){this._shapes.face.tolerance=e;}get axisCenterTolerance(){return this._shapes.face.tolerance}_setArrowProp(e,t){this._shapes.x[e]=t,this._shapes.y[e]=t,this._shapes.z[e]=t;}_setPlaneProp(e,t){this._shapes.yz[e]=t,this._shapes.xz[e]=t,this._shapes.xy[e]=t;}_shapesLookAtCamera(){let e=this.facing,t=e.dot(this.root.right);this._shapes.x.entity.enabled=.98>Math.abs(t),this.flipShapes&&(this._shapes.x.flipped=t<0),t=e.dot(this.root.up),this._shapes.y.entity.enabled=.98>Math.abs(t),this.flipShapes&&(this._shapes.y.flipped=t<0),t=e.dot(this.root.forward),this._shapes.z.entity.enabled=.98>Math.abs(t),this.flipShapes&&(this._shapes.z.flipped=t>0),Fc.cross(e,this.root.right),this._shapes.yz.entity.enabled=.98>Fc.length(),this.flipShapes&&(this._shapes.yz.flipped=Fd.set(0,+(0>Fc.dot(this.root.forward)),+(0>Fc.dot(this.root.up)))),Fc.cross(e,this.root.forward),this._shapes.xy.entity.enabled=.98>Fc.length(),this.flipShapes&&(this._shapes.xy.flipped=Fd.set(+(0>Fc.dot(this.root.up)),+(Fc.dot(this.root.right)>0),0)),Fc.cross(e,this.root.up),this._shapes.xz.entity.enabled=.98>Fc.length(),this.flipShapes&&(this._shapes.xz.flipped=Fd.set(+(Fc.dot(this.root.forward)>0),0,+(Fc.dot(this.root.right)>0)));}_storeNodePositions(){for(let e=0;e<this.nodes.length;e++){let t=this.nodes[e];this._nodeLocalPositions.set(t,t.getLocalPosition().clone()),this._nodePositions.set(t,t.getPosition().clone());}}_setNodePositions(e){for(let t=0;t<this.nodes.length;t++){let i=this.nodes[t];if(this._coordSpace===NT){let t=this._nodeLocalPositions.get(i);if(!t)continue;Fc.copy(e),i.parent?.getWorldTransform().getScale(Fd),Fd.x=1/Fd.x,Fd.y=1/Fd.y,Fd.z=1/Fd.z,Ff.copy(i.getLocalRotation()).transformVector(Fc,Fc),Fc.mul(Fd),i.setLocalPosition(Fc.add(t));}else {let t=this._nodePositions.get(i);if(!t)continue;i.setPosition(Fc.copy(e).add(t));}}this._updatePosition();}_screenToPoint(e,t){let i=this._camera.screenToWorld(e,t,1),s=this._selectedAxis,r=this._selectedIsPlane,a=this._createRay(i),n=this._createPlane(s,s===ND,!r),o=new eM;return n.intersectsRay(a,o),Ff.copy(this._rootStartRot).invert().transformVector(o,o),r||s===ND||this._projectToAxis(o,s),o}}class Fm extends Fs{constructor(e,t={}){super(e,t),this._tubeRadius=.01,this._ringRadius=.5,this._tolerance=.05,this._tubeRadius=t.tubeRadius??this._tubeRadius,this._ringRadius=t.ringRadius??this._ringRadius,this._sectorAngle=t.sectorAngle??this._sectorAngle,this.triData=[new N2(this._createTorusGeometry())],this._createDisk();}_createTorusGeometry(){return new yA({tubeRadius:this._tubeRadius+this._tolerance,ringRadius:this._ringRadius,sectorAngle:this._sectorAngle,segments:20})}_createTorusMesh(e){let t=new yA({tubeRadius:this._tubeRadius,ringRadius:this._ringRadius,sectorAngle:e,segments:80});return this._createMesh(t,this._shading)}_createDisk(){this._createRoot("disk"),this._createRenderComponent(this.entity,[this._createTorusMesh(this._sectorAngle),this._createTorusMesh(360)]),this.drag(false);}set tubeRadius(e){this._tubeRadius=e??.1,this._updateTransform();}get tubeRadius(){return this._tubeRadius}set ringRadius(e){this._ringRadius=e??.1,this._updateTransform();}get ringRadius(){return this._ringRadius}set tolerance(e){this._tolerance=e,this._updateTransform();}get tolerance(){return this._tolerance}_updateTransform(){this.triData[0].fromGeometry(this._createTorusGeometry()),this.meshInstances[0].mesh=this._createTorusMesh(this._sectorAngle),this.meshInstances[1].mesh=this._createTorusMesh(360);}drag(e){this.meshInstances[0].visible=!e,this.meshInstances[1].visible=e;}hide(e){if(e){this.meshInstances[0].visible=false,this.meshInstances[1].visible=false;return}this.drag(false);}}let F_=new eM,Fg=new eM,Fv=new eM,FS=new eM,Fy=new eG,Fx=new eH,FT=new eH,FE=new eb(0,0,0,.3);class FA extends NQ{constructor(e,t){super(e,t),this._shapes={z:new Fm(this._device,{axis:Nw,layers:[this._layer.id],shading:this._shading,rotation:new eM(90,0,90),defaultColor:this._meshColors.axis.z,hoverColor:this._meshColors.hover.z,sectorAngle:180}),x:new Fm(this._device,{axis:NA,layers:[this._layer.id],shading:this._shading,rotation:new eM(0,0,-90),defaultColor:this._meshColors.axis.x,hoverColor:this._meshColors.hover.x,sectorAngle:180}),y:new Fm(this._device,{axis:Nb,layers:[this._layer.id],shading:this._shading,rotation:new eM(0,0,0),defaultColor:this._meshColors.axis.y,hoverColor:this._meshColors.hover.y,sectorAngle:180}),face:new Fm(this._device,{axis:ND,layers:[this._layer.id],shading:this._shading,rotation:this._getLookAtEulerAngles(this._camera.entity.getPosition()),defaultColor:this._meshColors.axis.f,hoverColor:this._meshColors.hover.f,ringRadius:.55})},this._selectionStartAngle=0,this._nodeLocalRotations=new Map,this._nodeRotations=new Map,this._nodeOffsets=new Map,this._guideAngleStartColor=FE.clone(),this._guideAngleStart=new eM,this._guideAngleEnd=new eM,this.snapIncrement=5,this.orbitRotation=false,this._createTransform(),this.on(NQ.EVENT_TRANSFORMSTART,(e,t,i)=>{this._selectionStartAngle=this._calculateAngle(e,t,i),this._storeNodeRotations(),this._storeGuidePoints(),this._drag(true);}),this.on(NQ.EVENT_TRANSFORMMOVE,(e,t,i)=>{let s=this._selectedAxis,r=this._calculateAngle(e,t,i)-this._selectionStartAngle;this.snap&&(r=Math.round(r/this.snapIncrement)*this.snapIncrement),this._setNodeRotations(s,r),this._updateGuidePoints(r);}),this.on(NQ.EVENT_TRANSFORMEND,()=>{this._drag(false);}),this.on(NQ.EVENT_NODESDETACH,()=>{this._nodeLocalRotations.clear(),this._nodeRotations.clear(),this._nodeOffsets.clear();}),this._app.on("prerender",()=>{if(this._shapesLookAtCamera(),this._dragging){let e=this.root.getPosition();this._drawGuideAngleLine(e,this._selectedAxis,this._guideAngleStart,this._guideAngleStartColor),this._drawGuideAngleLine(e,this._selectedAxis,this._guideAngleEnd);}});}set xyzTubeRadius(e){this._setDiskProp("tubeRadius",e);}get xyzTubeRadius(){return this._shapes.x.tubeRadius}set xyzRingRadius(e){this._setDiskProp("ringRadius",e);}get xyzRingRadius(){return this._shapes.x.ringRadius}set faceTubeRadius(e){this._shapes.face.tubeRadius=e;}get faceTubeRadius(){return this._shapes.face.tubeRadius}set faceRingRadius(e){this._shapes.face.ringRadius=e;}get faceRingRadius(){return this._shapes.face.ringRadius}set ringTolerance(e){this._setDiskProp("tolerance",e),this._shapes.face.tolerance=e;}get ringTolerance(){return this._shapes.x.tolerance}_setDiskProp(e,t){this._shapes.x[e]=t,this._shapes.y[e]=t,this._shapes.z[e]=t;}_storeGuidePoints(){let e=this.root.getPosition(),t=this._selectedAxis===ND?this.faceRingRadius:this.xyzRingRadius;this._guideAngleStart.copy(this._selectionStartPoint).sub(e).normalize(),this._guideAngleStart.mulScalar(t),this._guideAngleEnd.copy(this._guideAngleStart);}_updateGuidePoints(e){let t=this._selectedAxis;t===ND?F_.copy(this.facing):(F_.set(0,0,0),F_[t]=1,this._rootStartRot.transformVector(F_,F_)),Fx.setFromAxisAngle(F_,e),Fx.transformVector(this._guideAngleStart,this._guideAngleEnd);}_drawGuideAngleLine(e,t,i,s=this._guideColors[t]){F_.set(0,0,0),Fg.copy(i).mulScalar(this._scale),this._app.drawLine(F_.add(e),Fg.add(e),s,false,this._layer);}_getLookAtEulerAngles(e){return F_.set(0,0,0),Fy.setLookAt(F_,e,eM.UP),Fx.setFromMat4(Fy),Fx.getEulerAngles(F_),F_.x+=90,F_}_shapesLookAtCamera(){this._camera.projection===fp?(this._shapes.face.entity.lookAt(this._camera.entity.getPosition()),this._shapes.face.entity.rotateLocal(90,0,0)):(Fx.copy(this._camera.entity.getRotation()).getEulerAngles(F_),this._shapes.face.entity.setEulerAngles(F_),this._shapes.face.entity.rotateLocal(-90,0,0));let e=F_.copy(this.facing);Fx.copy(this.root.getRotation()).invert().transformVector(e,e);let t=Math.atan2(e.z,e.y)*eA.RAD_TO_DEG;this._shapes.x.entity.setLocalEulerAngles(0,t-90,-90),t=Math.atan2(e.x,e.z)*eA.RAD_TO_DEG,this._shapes.y.entity.setLocalEulerAngles(0,t,0),t=Math.atan2(e.y,e.x)*eA.RAD_TO_DEG,this._shapes.z.entity.setLocalEulerAngles(90,0,t+90);}_drag(e){for(let t in this._shapes){let i=this._shapes[t];t===this._selectedAxis?i.drag(e):i.hide(e);}this.fire(NQ.EVENT_RENDERUPDATE);}_storeNodeRotations(){let e=this.root.getPosition();for(let t=0;t<this.nodes.length;t++){let i=this.nodes[t];this._nodeLocalRotations.set(i,i.getLocalRotation().clone()),this._nodeRotations.set(i,i.getRotation().clone()),this._nodeOffsets.set(i,i.getPosition().clone().sub(e));}}_setNodeRotations(e,t){let i=this.root.getPosition(),s=e===ND;Fx.setFromAxisAngle(this._dirFromAxis(e,F_),t);for(let e=0;e<this.nodes.length;e++){let t=this.nodes[e];if(s||this._coordSpace!==NT){let e=this._nodeRotations.get(t);if(!e)continue;let s=this._nodeOffsets.get(t);if(!s)continue;F_.copy(s),Fx.transformVector(F_,F_),FT.copy(Fx).mul(e),t.setEulerAngles(FT.getEulerAngles()),t.setPosition(F_.add(i));}else {let e=this._nodeLocalRotations.get(t);if(!e)continue;FT.copy(e).mul(Fx),t.setLocalRotation(FT);}}this._coordSpace===NT&&this._updateRotation();}_screenToPoint(e,t){let i=this._camera.screenToWorld(e,t,1),s=this._selectedAxis,r=this._createRay(i),a=this._createPlane(s,s===ND,false),n=new eM;return a.intersectsRay(r,n),n}_calculateAngle(e,t,i){let s=this.root.getPosition(),r=this._selectedAxis,a=this._createPlane(r,r===ND,false),n=0,o=Fg.copy(this.facing),l=a.normal.dot(o);return this.orbitRotation||Math.abs(l)>.9?(F_.sub2(e,s),Fx.copy(this._camera.entity.getRotation()).invert().transformVector(F_,F_),n=Math.sign(l)*Math.atan2(F_.y,F_.x)*eA.RAD_TO_DEG):(F_.copy(s),Fg.cross(a.normal,o).normalize().add(s),this._camera.worldToScreen(F_,Fv),this._camera.worldToScreen(Fg,FS),F_.sub2(FS,Fv).normalize(),Fg.set(t,i,0),n=F_.dot(Fg)),n}}class Fb extends Fs{constructor(e,t={}){super(e,t),this._size=.12,this._tolerance=.05,this.triData=[new N2(new vJ,2)],this._createCenter();}_createCenter(){this._createRoot("boxCenter"),this._updateTransform(),this._addRenderMesh(this.entity,"box",this._shading);}set size(e){this._size=e??1,this._updateTransform();}get size(){return this._size}set tolerance(e){this._tolerance=e,this._updateTransform();}get tolerance(){return this._tolerance}_updateTransform(){this.entity.setLocalScale(this._size,this._size,this._size);}}let Fw=new eM,FC=new eM,FP=new eH;class FL extends Fs{constructor(e,t={}){super(e,t),this._gap=0,this._lineThickness=.02,this._lineLength=.5,this._boxSize=.12,this._tolerance=.1,this._flipped=false,this.triData=[new N2(new vJ),new N2(new yT,1)],this._createBoxLine();}set gap(e){this._gap=e??0,this._updateLine(),this._updateBox();}get gap(){return this._gap}set lineThickness(e){this._lineThickness=e??1,this._updateLine(),this._updateBox();}get lineThickness(){return this._lineThickness}set lineLength(e){this._lineLength=e??1,this._updateLine(),this._updateBox();}get lineLength(){return this._lineLength}set boxSize(e){this._boxSize=e??1,this._updateBox();}get boxSize(){return this._boxSize}set tolerance(e){this._tolerance=e,this._updateLine();}get tolerance(){return this._tolerance}set flipped(e){this._flipped!==e&&(this._flipped=e,this._rotation.equals(eM.ZERO)?Fw.set(0,0,180*!!this._flipped):Fw.copy(this._rotation).mulScalar(this._flipped?-1:1),this._line.enabled=!this._flipped,this.entity.setLocalEulerAngles(Fw));}get flipped(){return this._flipped}_createBoxLine(){this._createRoot("boxLine"),this._box=new x1(`box:${this.axis}`),this.entity.addChild(this._box),this._updateBox(),this._addRenderMesh(this._box,"box",this._shading),this._line=new x1(`line:${this.axis}`),this.entity.addChild(this._line),this._updateLine(),this._addRenderMesh(this._line,"cylinder",this._shading);}_updateBox(){Fw.set(0,this._gap+.5*this._boxSize+this._lineLength,0),FP.set(0,0,0,1),FC.set(this._boxSize,this._boxSize,this._boxSize),this.triData[0].setTransform(Fw,FP,FC),this._box.setLocalPosition(0,this._gap+.5*this._boxSize+this._lineLength,0),this._box.setLocalScale(this._boxSize,this._boxSize,this._boxSize);}_updateLine(){Fw.set(0,this._gap+.5*this._lineLength,0),FP.set(0,0,0,1),FC.set(this._lineThickness+this._tolerance,this._lineLength,this._lineThickness+this._tolerance),this.triData[1].setTransform(Fw,FP,FC),this._line.setLocalPosition(0,this._gap+.5*this._lineLength,0),this._line.setLocalScale(this._lineThickness,this._lineLength,this._lineThickness);}}let FI=new eM,FD=new eM,FR=new eM,FM=new eH;class FO extends NQ{constructor(e,t){super(e,t),this._shapes={xyz:new Fb(this._device,{axis:NI,layers:[this._layer.id],shading:this._shading,defaultColor:this._meshColors.axis.xyz,hoverColor:this._meshColors.hover.xyz}),yz:new Fr(this._device,{axis:NA,layers:[this._layer.id],shading:this._shading,rotation:new eM(0,0,-90),defaultColor:this._meshColors.axis.x,hoverColor:this._meshColors.hover.x}),xz:new Fr(this._device,{axis:Nb,layers:[this._layer.id],shading:this._shading,rotation:new eM(0,0,0),defaultColor:this._meshColors.axis.y,hoverColor:this._meshColors.hover.y}),xy:new Fr(this._device,{axis:Nw,layers:[this._layer.id],shading:this._shading,rotation:new eM(90,0,0),defaultColor:this._meshColors.axis.z,hoverColor:this._meshColors.hover.z}),x:new FL(this._device,{axis:NA,layers:[this._layer.id],shading:this._shading,rotation:new eM(0,0,-90),defaultColor:this._meshColors.axis.x,hoverColor:this._meshColors.hover.x}),y:new FL(this._device,{axis:Nb,layers:[this._layer.id],shading:this._shading,rotation:new eM(0,0,0),defaultColor:this._meshColors.axis.y,hoverColor:this._meshColors.hover.y}),z:new FL(this._device,{axis:Nw,layers:[this._layer.id],shading:this._shading,rotation:new eM(90,0,0),defaultColor:this._meshColors.axis.z,hoverColor:this._meshColors.hover.z})},this._coordSpace=NT,this._nodeScales=new Map,this._useUniformScaling=false,this.snapIncrement=1,this.flipShapes=true,this.lowerBoundScale=new eM(-1/0,-1/0,-1/0),this._createTransform(),this.on(NQ.EVENT_TRANSFORMSTART,()=>{this._storeNodeScales();}),this.on(NQ.EVENT_TRANSFORMMOVE,e=>{let t=FR.copy(e).sub(this._selectionStartPoint);this.snap&&(t.mulScalar(1/this.snapIncrement),t.round(),t.mulScalar(this.snapIncrement)),t.mulScalar(1/this._scale),this._setNodeScales(t.add(eM.ONE));}),this.on(NQ.EVENT_NODESDETACH,()=>{this._nodeScales.clear();}),this._app.on("prerender",()=>{this._shapesLookAtCamera();});}set coordSpace(e){}get coordSpace(){return this._coordSpace}set uniform(e){this._useUniformScaling=e??true;}get uniform(){return this._useUniformScaling}set axisGap(e){this._setArrowProp("gap",e);}get axisGap(){return this._shapes.x.gap}set axisLineThickness(e){this._setArrowProp("lineThickness",e);}get axisLineThickness(){return this._shapes.x.lineThickness}set axisLineLength(e){this._setArrowProp("lineLength",e);}get axisLineLength(){return this._shapes.x.lineLength}set axisLineTolerance(e){this._setArrowProp("tolerance",e);}get axisLineTolerance(){return this._shapes.x.tolerance}set axisBoxSize(e){this._setArrowProp("boxSize",e);}get axisBoxSize(){return this._shapes.x.boxSize}set axisPlaneSize(e){this._setPlaneProp("size",e);}get axisPlaneSize(){return this._shapes.yz.size}set axisPlaneGap(e){this._setPlaneProp("gap",e);}get axisPlaneGap(){return this._shapes.yz.gap}set axisCenterSize(e){this._shapes.xyz.size=e;}get axisCenterSize(){return this._shapes.xyz.size}set axisCenterTolerance(e){this._shapes.xyz.tolerance=e;}get axisCenterTolerance(){return this._shapes.xyz.tolerance}_setArrowProp(e,t){this._shapes.x[e]=t,this._shapes.y[e]=t,this._shapes.z[e]=t;}_setPlaneProp(e,t){this._shapes.yz[e]=t,this._shapes.xz[e]=t,this._shapes.xy[e]=t;}_shapesLookAtCamera(){let e=this.facing,t=e.dot(this.root.right);this._shapes.x.entity.enabled=.98>Math.abs(t),this.flipShapes&&(this._shapes.x.flipped=t<0),t=e.dot(this.root.up),this._shapes.y.entity.enabled=.98>Math.abs(t),this.flipShapes&&(this._shapes.y.flipped=t<0),t=e.dot(this.root.forward),this._shapes.z.entity.enabled=.98>Math.abs(t),this.flipShapes&&(this._shapes.z.flipped=t>0),FI.cross(e,this.root.right),this._shapes.yz.entity.enabled=.98>FI.length(),this.flipShapes&&(this._shapes.yz.flipped=FD.set(0,+(0>FI.dot(this.root.forward)),+(0>FI.dot(this.root.up)))),FI.cross(e,this.root.forward),this._shapes.xy.entity.enabled=.98>FI.length(),this.flipShapes&&(this._shapes.xy.flipped=FD.set(+(0>FI.dot(this.root.up)),+(FI.dot(this.root.right)>0),0)),FI.cross(e,this.root.up),this._shapes.xz.entity.enabled=.98>FI.length(),this.flipShapes&&(this._shapes.xz.flipped=FD.set(+(FI.dot(this.root.forward)>0),0,+(FI.dot(this.root.right)>0)));}_storeNodeScales(){for(let e=0;e<this.nodes.length;e++){let t=this.nodes[e];this._nodeScales.set(t,t.getLocalScale().clone());}}_setNodeScales(e){for(let t=0;t<this.nodes.length;t++){let i=this.nodes[t],s=this._nodeScales.get(i);s&&i.setLocalScale(FI.copy(s).mul(e).max(this.lowerBoundScale));}}_screenToPoint(e,t){let i=this.root.getPosition(),s=this._camera.screenToWorld(e,t,1),r=this._selectedAxis,a=this._selectedIsPlane,n=this._useUniformScaling&&a||r===NI,o=this._createRay(s),l=this._createPlane(r,n,!a),h=new eM;if(l.intersectsRay(o,h),n){switch(r){case NA:FI.copy(this.root.up),FD.copy(this.root.forward).mulScalar(-1);break;case Nb:FI.copy(this.root.right),FD.copy(this.root.forward).mulScalar(-1);break;case Nw:FI.copy(this.root.up),FD.copy(this.root.right);break;default:FI.copy(this._camera.entity.up),FD.copy(this._camera.entity.right);}FD.add(FI).normalize(),FI.sub2(h,i);let e=FI.length()*FI.normalize().dot(FD);return h.set(e,e,e),r!==NI&&(h[r]=1),h}return FM.copy(this._rootStartRot).invert().transformVector(h,h),a||this._projectToAxis(h,r),h}}let FN=new eM,FF=new eM,FB=new eM,FU=new eG;class Fk extends eo{static{this.EVENT_CAMERAALIGN="camera:align";}constructor(e){super(),this._size=0,this._anchor=new eF(1,1,1,1),this._colorX=Nk.clone(),this._colorY=NV.clone(),this._colorZ=Nz.clone(),this._colorNeg=new eb(.3,.3,.3),this._radius=10,this._textSize=10,this._lineThickness=2,this._lineLength=40,this.dom=document.createElement("div"),this.dom.id="view-cube-container",this.dom.style.cssText="position: absolute;margin: auto;pointer-events: none",document.body.appendChild(this.dom),this.anchor=e??this._anchor,this._svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this._svg.id="view-cube-svg",this._group=document.createElementNS(this._svg.namespaceURI,"g"),this._svg.appendChild(this._group),this._resize();let t=this._colorX.toString(false),i=this._colorY.toString(false),s=this._colorZ.toString(false);this._shapes={nx:this._circle(t),ny:this._circle(i),nz:this._circle(s),px:this._circle(t,true,"X"),py:this._circle(i,true,"Y"),pz:this._circle(s,true,"Z"),xaxis:this._line(t),yaxis:this._line(i),zaxis:this._line(s)},this._shapes.px.children[0].addEventListener("pointerdown",()=>{this.fire(Fk.EVENT_CAMERAALIGN,eM.RIGHT);}),this._shapes.py.children[0].addEventListener("pointerdown",()=>{this.fire(Fk.EVENT_CAMERAALIGN,eM.UP);}),this._shapes.pz.children[0].addEventListener("pointerdown",()=>{this.fire(Fk.EVENT_CAMERAALIGN,eM.BACK);}),this._shapes.nx.children[0].addEventListener("pointerdown",()=>{this.fire(Fk.EVENT_CAMERAALIGN,eM.LEFT);}),this._shapes.ny.children[0].addEventListener("pointerdown",()=>{this.fire(Fk.EVENT_CAMERAALIGN,eM.DOWN);}),this._shapes.nz.children[0].addEventListener("pointerdown",()=>{this.fire(Fk.EVENT_CAMERAALIGN,eM.FORWARD);}),this.dom.appendChild(this._svg);}set anchor(e){this._anchor.copy(e),this.dom.style.top=this._anchor.x?"0px":"auto",this.dom.style.right=this._anchor.y?"0px":"auto",this.dom.style.bottom=this._anchor.z?"0px":"auto",this.dom.style.left=this._anchor.w?"0px":"auto";}get anchor(){return this._anchor}set colorX(e){this._colorX.copy(e),this._shapes.px.children[0].setAttribute("fill",this._colorX.toString(false)),this._shapes.px.children[0].setAttribute("stroke",this._colorX.toString(false)),this._shapes.nx.children[0].setAttribute("stroke",this._colorX.toString(false)),this._shapes.xaxis.setAttribute("stroke",this._colorX.toString(false));}get colorX(){return this._colorX}set colorY(e){this._colorY.copy(e),this._shapes.py.children[0].setAttribute("fill",this._colorY.toString(false)),this._shapes.py.children[0].setAttribute("stroke",this._colorY.toString(false)),this._shapes.ny.children[0].setAttribute("stroke",this._colorY.toString(false)),this._shapes.yaxis.setAttribute("stroke",this._colorY.toString(false));}get colorY(){return this._colorY}set colorZ(e){this._colorZ.copy(e),this._shapes.pz.children[0].setAttribute("fill",this._colorZ.toString(false)),this._shapes.pz.children[0].setAttribute("stroke",this._colorZ.toString(false)),this._shapes.nz.children[0].setAttribute("stroke",this._colorZ.toString(false)),this._shapes.zaxis.setAttribute("stroke",this._colorZ.toString(false));}get colorZ(){return this._colorZ}set colorNeg(e){this._colorNeg.copy(e),this._shapes.px.children[0].setAttribute("fill",this._colorNeg.toString(false)),this._shapes.py.children[0].setAttribute("fill",this._colorNeg.toString(false)),this._shapes.pz.children[0].setAttribute("fill",this._colorNeg.toString(false));}get colorNeg(){return this._colorNeg}set radius(e){this._radius=e,this._shapes.px.children[0].setAttribute("r",`${e}`),this._shapes.py.children[0].setAttribute("r",`${e}`),this._shapes.pz.children[0].setAttribute("r",`${e}`),this._shapes.nx.children[0].setAttribute("r",`${e}`),this._shapes.ny.children[0].setAttribute("r",`${e}`),this._shapes.nz.children[0].setAttribute("r",`${e}`),this._resize();}get radius(){return this._radius}set textSize(e){this._textSize=e,this._shapes.px.children[1].setAttribute("font-size",`${e}`),this._shapes.py.children[1].setAttribute("font-size",`${e}`),this._shapes.pz.children[1].setAttribute("font-size",`${e}`);}get textSize(){return this._textSize}set lineThickness(e){this._lineThickness=e,this._shapes.xaxis.setAttribute("stroke-width",`${e}`),this._shapes.yaxis.setAttribute("stroke-width",`${e}`),this._shapes.zaxis.setAttribute("stroke-width",`${e}`),this._shapes.px.children[0].setAttribute("stroke-width",`${e}`),this._shapes.py.children[0].setAttribute("stroke-width",`${e}`),this._shapes.pz.children[0].setAttribute("stroke-width",`${e}`),this._shapes.nx.children[0].setAttribute("stroke-width",`${e}`),this._shapes.ny.children[0].setAttribute("stroke-width",`${e}`),this._shapes.nz.children[0].setAttribute("stroke-width",`${e}`),this._resize();}get lineThickness(){return this._lineThickness}set lineLength(e){this._lineLength=e,this._resize();}get lineLength(){return this._lineLength}_resize(){this._size=2*(this.lineLength+this.radius+this.lineThickness),this.dom.style.width=`${this._size}px`,this.dom.style.height=`${this._size}px`,this._svg.setAttribute("width",`${this._size}`),this._svg.setAttribute("height",`${this._size}`),this._group.setAttribute("transform",`translate(${.5*this._size}, ${.5*this._size})`);}_transform(e,t,i){e.setAttribute("transform",`translate(${t*this._lineLength}, ${i*this._lineLength})`);}_x2y2(e,t,i){e.setAttribute("x2",`${t*this._lineLength}`),e.setAttribute("y2",`${i*this._lineLength}`);}_line(e){let t=document.createElementNS(this._svg.namespaceURI,"line");return t.setAttribute("stroke",e),t.setAttribute("stroke-width",`${this._lineThickness}`),this._group.appendChild(t),t}_circle(e,t=false,i){let s=document.createElementNS(this._svg.namespaceURI,"g"),r=document.createElementNS(this._svg.namespaceURI,"circle");if(r.setAttribute("fill",t?e:this._colorNeg.toString(false)),r.setAttribute("stroke",e),r.setAttribute("stroke-width",`${this._lineThickness}`),r.setAttribute("r",`${this._radius}`),r.setAttribute("cx","0"),r.setAttribute("cy","0"),r.setAttribute("pointer-events","all"),s.appendChild(r),i){let e=document.createElementNS(this._svg.namespaceURI,"text");e.setAttribute("font-size",`${this._textSize}`),e.setAttribute("font-family","Arial"),e.setAttribute("font-weight","bold"),e.setAttribute("text-anchor","middle"),e.setAttribute("alignment-baseline","central"),e.textContent=i,s.appendChild(e);}return s.setAttribute("cursor","pointer"),this._group.appendChild(s),s}update(e){if(!this._size)return;FU.invert(e),FU.getX(FN),FU.getY(FF),FU.getZ(FB),this._transform(this._shapes.px,FN.x,-FN.y),this._transform(this._shapes.nx,-FN.x,FN.y),this._transform(this._shapes.py,FF.x,-FF.y),this._transform(this._shapes.ny,-FF.x,FF.y),this._transform(this._shapes.pz,FB.x,-FB.y),this._transform(this._shapes.nz,-FB.x,FB.y),this._x2y2(this._shapes.xaxis,FN.x,-FN.y),this._x2y2(this._shapes.yaxis,FF.x,-FF.y),this._x2y2(this._shapes.zaxis,FB.x,-FB.y);let t=[{n:["xaxis","px"],value:FN.z},{n:["yaxis","py"],value:FF.z},{n:["zaxis","pz"],value:FB.z},{n:["nx"],value:-FN.z},{n:["ny"],value:-FF.z},{n:["nz"],value:-FB.z}].sort((e,t)=>e.value-t.value),i=document.createDocumentFragment();t.forEach(e=>{e.n.forEach(e=>{i.appendChild(this._shapes[e]);});}),this._group.appendChild(i);}destroy(){this.dom.remove(),this.off();}}
export { x_ as ABSOLUTE_URL, hc as ACTION_GAMEPAD, hh as ACTION_KEYBOARD, hl as ACTION_MOUSE, tr as ADDRESS_CLAMP_TO_EDGE, ta as ADDRESS_MIRRORED_REPEAT, ts as ADDRESS_REPEAT, fj as AMBIENTSRC_AMBIENTSH, fZ as AMBIENTSRC_CONSTANT, fK as AMBIENTSRC_ENVALATLAS, TB as ANIM_BLEND_1D, Tk as ANIM_BLEND_2D_CARTESIAN, TU as ANIM_BLEND_2D_DIRECTIONAL, TV as ANIM_BLEND_DIRECT, TW as ANIM_CONTROL_STATES, TD as ANIM_EQUAL_TO, TC as ANIM_GREATER_THAN, TL as ANIM_GREATER_THAN_EQUAL_TO, TA as ANIM_INTERRUPTION_NEXT, Tw as ANIM_INTERRUPTION_NEXT_PREV, TT as ANIM_INTERRUPTION_NONE, TE as ANIM_INTERRUPTION_PREV, Tb as ANIM_INTERRUPTION_PREV_NEXT, TY as ANIM_LAYER_ADDITIVE, TX as ANIM_LAYER_OVERWRITE, TP as ANIM_LESS_THAN, TI as ANIM_LESS_THAN_EQUAL_TO, TR as ANIM_NOT_EQUAL_TO, TN as ANIM_PARAMETER_BOOLEAN, TO as ANIM_PARAMETER_FLOAT, TM as ANIM_PARAMETER_INTEGER, TF as ANIM_PARAMETER_TRIGGER, TH as ANIM_STATE_ANY, TG as ANIM_STATE_END, Tz as ANIM_STATE_START, pV as ASPECT_AUTO, pz as ASPECT_MANUAL, xg as ASSET_ANIMATION, xv as ASSET_AUDIO, xD as ASSET_CONTAINER, xP as ASSET_CSS, xw as ASSET_CUBEMAP, xL as ASSET_HTML, xS as ASSET_IMAGE, xy as ASSET_JSON, xT as ASSET_MATERIAL, xx as ASSET_MODEL, xI as ASSET_SCRIPT, xC as ASSET_SHADER, xE as ASSET_TEXT, xA as ASSET_TEXTURE, xb as ASSET_TEXTUREATLAS, hg as AXIS_KEY, hd as AXIS_MOUSE_X, hu as AXIS_MOUSE_Y, hf as AXIS_PAD_L_X, hp as AXIS_PAD_L_Y, hm as AXIS_PAD_R_X, h_ as AXIS_PAD_R_Y, TQ as AnimBinder, Tx as AnimClip, Pk as AnimClipHandler, Eu as AnimComponent, Ec as AnimComponentLayer, Em as AnimComponentSystem, Es as AnimController, Cw as AnimCurve, CC as AnimData, Tj as AnimEvaluator, TK as AnimEvents, Ty as AnimSnapshot, Ed as AnimStateGraph, PV as AnimStateGraphHandler, TJ as AnimTarget, TZ as AnimTrack, Sk as Animation, T1 as AnimationComponent, T4 as AnimationComponentSystem, PU as AnimationHandler, SB as AnimationKey, SU as AnimationNode, x9 as AppBase, Te as AppOptions, Dn as Application, xF as Asset, Do as AssetListLoader, b$ as AssetReference, xU as AssetRegistry, PH as AudioHandler, E_ as AudioListenerComponent, ES as AudioListenerComponentSystem, pL as BAKE_COLOR, pI as BAKE_COLORDIR, aW as BINDGROUP_MESH, aX as BINDGROUP_MESH_UB, aH as BINDGROUP_VIEW, tS as BLENDEQUATION_ADD, tE as BLENDEQUATION_MAX, tT as BLENDEQUATION_MIN, tx as BLENDEQUATION_REVERSE_SUBTRACT, ty as BLENDEQUATION_SUBTRACT, tg as BLENDMODE_CONSTANT, D5 as BLENDMODE_CONSTANT_ALPHA, D3 as BLENDMODE_CONSTANT_COLOR, tm as BLENDMODE_DST_ALPHA, tc as BLENDMODE_DST_COLOR, to as BLENDMODE_ONE, tv as BLENDMODE_ONE_MINUS_CONSTANT, D8 as BLENDMODE_ONE_MINUS_CONSTANT_ALPHA, D4 as BLENDMODE_ONE_MINUS_CONSTANT_COLOR, t_ as BLENDMODE_ONE_MINUS_DST_ALPHA, td as BLENDMODE_ONE_MINUS_DST_COLOR, tp as BLENDMODE_ONE_MINUS_SRC_ALPHA, th as BLENDMODE_ONE_MINUS_SRC_COLOR, tu as BLENDMODE_SRC_ALPHA, tf as BLENDMODE_SRC_ALPHA_SATURATE, tl as BLENDMODE_SRC_COLOR, tn as BLENDMODE_ZERO, ur as BLEND_ADDITIVE, uh as BLEND_ADDITIVEALPHA, uf as BLEND_MAX, uu as BLEND_MIN, ul as BLEND_MULTIPLICATIVE, uc as BLEND_MULTIPLICATIVE2X, un as BLEND_NONE, ua as BLEND_NORMAL, uo as BLEND_PREMULTIPLIED, ud as BLEND_SCREEN, us as BLEND_SUBTRACTIVE, ft as BLUR_BOX, fi as BLUR_GAUSSIAN, EX as BODYFLAG_KINEMATIC_OBJECT, EY as BODYFLAG_NORESPONSE_OBJECT, EW as BODYFLAG_STATIC_OBJECT, EJ as BODYGROUP_DEFAULT, E0 as BODYGROUP_DYNAMIC, E3 as BODYGROUP_ENGINE_1, E5 as BODYGROUP_ENGINE_2, E8 as BODYGROUP_ENGINE_3, E2 as BODYGROUP_KINEMATIC, EQ as BODYGROUP_NONE, E1 as BODYGROUP_STATIC, E4 as BODYGROUP_TRIGGER, E6 as BODYGROUP_USER_1, E9 as BODYGROUP_USER_2, E7 as BODYGROUP_USER_3, Ae as BODYGROUP_USER_4, At as BODYGROUP_USER_5, Ai as BODYGROUP_USER_6, As as BODYGROUP_USER_7, Ar as BODYGROUP_USER_8, An as BODYMASK_ALL, Aa as BODYMASK_NONE, Al as BODYMASK_NOT_STATIC, Ah as BODYMASK_NOT_STATIC_KINEMATIC, Ao as BODYMASK_STATIC, Eq as BODYSTATE_ACTIVE_TAG, EK as BODYSTATE_DISABLE_DEACTIVATION, EZ as BODYSTATE_DISABLE_SIMULATION, E$ as BODYSTATE_ISLAND_SLEEPING, Ej as BODYSTATE_WANTS_DEACTIVATION, EG as BODYTYPE_DYNAMIC, EH as BODYTYPE_KINEMATIC, Ez as BODYTYPE_STATIC, tC as BUFFERUSAGE_COPY_DST, tw as BUFFERUSAGE_COPY_SRC, tP as BUFFERUSAGE_INDEX, tR as BUFFERUSAGE_INDIRECT, tA as BUFFERUSAGE_READ, tD as BUFFERUSAGE_STORAGE, tI as BUFFERUSAGE_UNIFORM, tL as BUFFERUSAGE_VERTEX, tb as BUFFERUSAGE_WRITE, tO as BUFFER_DYNAMIC, tF as BUFFER_GPUDYNAMIC, tM as BUFFER_STATIC, tN as BUFFER_STREAM, Ex as BUTTON_TRANSITION_MODE_SPRITE_CHANGE, Ey as BUTTON_TRANSITION_MODE_TINT, mv as Batch, mS as BatchGroup, mY as BatchManager, PW as BinaryHandler, a7 as BindGroupFormat, a8 as BindStorageBufferFormat, a9 as BindStorageTextureFormat, a6 as BindTextureFormat, a5 as BindUniformBufferFormat, nu as BlendState, ej as BoundingBox, eQ as BoundingSphere, vJ as BoxGeometry, xz as Bundle, xW as BundleHandler, xk as BundleRegistry, ER as ButtonComponent, EF as ButtonComponentSystem, D6 as CHUNKAPI_1_51, D9 as CHUNKAPI_1_55, D7 as CHUNKAPI_1_56, Re as CHUNKAPI_1_57, Rt as CHUNKAPI_1_58, Ri as CHUNKAPI_1_60, Rs as CHUNKAPI_1_62, Rr as CHUNKAPI_1_65, Ra as CHUNKAPI_1_70, Rn as CHUNKAPI_2_1, Ro as CHUNKAPI_2_3, Rl as CHUNKAPI_2_5, Rh as CHUNKAPI_2_6, Rc as CHUNKAPI_2_7, Rd as CHUNKAPI_2_8, tB as CLEARFLAG_COLOR, tU as CLEARFLAG_DEPTH, tk as CLEARFLAG_STENCIL, tz as CUBEFACE_NEGX, tH as CUBEFACE_NEGY, tX as CUBEFACE_NEGZ, tV as CUBEFACE_POSX, tG as CUBEFACE_POSY, tW as CUBEFACE_POSZ, fy as CUBEPROJ_BOX, fS as CUBEPROJ_NONE, tq as CULLFACE_BACK, t$ as CULLFACE_FRONT, tj as CULLFACE_FRONTANDBACK, tY as CULLFACE_NONE, ey as CURVE_LINEAR, ex as CURVE_SMOOTHSTEP, eT as CURVE_SPLINE, eE as CURVE_STEP, m3 as Camera, w1 as CameraComponent, w4 as CameraComponentSystem, OW as CameraFrame, Oz as CameraFrameOptions, Dh as CanvasFont, yy as CapsuleGeometry, vj as ChunkUtils, Ek as CollisionComponent, Ab as CollisionComponentSystem, eb as Color, Tp as Component, Tm as ComponentSystem, xV as ComponentSystemRegistry, lZ as Compute, yx as ConeGeometry, b9 as ContactPoint, b7 as ContactResult, P$ as ContainerHandler, Pq as ContainerResource, dF as Controller, Pj as CssHandler, PK as CubemapHandler, eC as Curve, eP as CurveSet, yT as CylinderGeometry, fE as DETAILMODE_ADD, fC as DETAILMODE_MAX, fw as DETAILMODE_MIN, fT as DETAILMODE_MUL, fb as DETAILMODE_OVERLAY, fA as DETAILMODE_SCREEN, aC as DEVICETYPE_NULL, ab as DEVICETYPE_WEBGL2, aw as DEVICETYPE_WEBGPU, aM as DISPLAYFORMAT_HDR, aD as DISPLAYFORMAT_LDR, aR as DISPLAYFORMAT_LDR_SRGB, d4 as DISTANCE_EXPONENTIAL, d3 as DISTANCE_INVERSE, d2 as DISTANCE_LINEAR, p$ as DITHER_BAYER8, pj as DITHER_BLUENOISE, pK as DITHER_IGNNOISE, pq as DITHER_NONE, T0 as DefaultAnimBinder, nm as DepthState, v1 as DomeGeometry, O4 as DualGestureSource, ET as ELEMENTTYPE_GROUP, EE as ELEMENTTYPE_IMAGE, EA as ELEMENTTYPE_TEXT, fh as EMITTERSHAPE_BOX, fc as EMITTERSHAPE_SPHERE, p4 as EVENT_CULL_END, RH as EVENT_GAMEPADCONNECTED, RW as EVENT_GAMEPADDISCONNECTED, RM as EVENT_KEYDOWN, RO as EVENT_KEYUP, RN as EVENT_MOUSEDOWN, RF as EVENT_MOUSEMOVE, RB as EVENT_MOUSEUP, RU as EVENT_MOUSEWHEEL, p3 as EVENT_POSTCULL, pJ as EVENT_POSTRENDER, p1 as EVENT_POSTRENDER_LAYER, p2 as EVENT_PRECULL, pQ as EVENT_PRERENDER, p0 as EVENT_PRERENDER_LAYER, RX as EVENT_SELECT, Rq as EVENT_SELECTEND, RY as EVENT_SELECTSTART, RG as EVENT_TOUCHCANCEL, RV as EVENT_TOUCHEND, Rz as EVENT_TOUCHMOVE, Rk as EVENT_TOUCHSTART, A4 as ElementComponent, A6 as ElementComponentSystem, wg as ElementDragHelper, D$ as ElementInput, DW as ElementInputEvent, DX as ElementMouseEvent, Dq as ElementSelectEvent, DY as ElementTouchEvent, x1 as Entity, SL as EnvLighting, en as EventHandle, eo as EventHandler, y7 as FILLMODE_FILL_WINDOW, xe as FILLMODE_KEEP_ASPECT, y9 as FILLMODE_NONE, tZ as FILTER_LINEAR, t1 as FILTER_LINEAR_MIPMAP_LINEAR, t0 as FILTER_LINEAR_MIPMAP_NEAREST, tK as FILTER_NEAREST, tJ as FILTER_NEAREST_MIPMAP_LINEAR, tQ as FILTER_NEAREST_MIPMAP_NEAREST, Ew as FITMODE_CONTAIN, EC as FITMODE_COVER, Eb as FITMODE_STRETCH, bp as FITTING_BOTH, bd as FITTING_NONE, bf as FITTING_SHRINK, bu as FITTING_STRETCH, ug as FOG_EXP, uv as FOG_EXP2, u_ as FOG_LINEAR, um as FOG_NONE, AR as FONT_BITMAP, AD as FONT_MSDF, uS as FRESNEL_NONE, uy as FRESNEL_SCHLICK, t7 as FUNC_ALWAYS, t4 as FUNC_EQUAL, t8 as FUNC_GREATER, t9 as FUNC_GREATEREQUAL, t3 as FUNC_LESS, t5 as FUNC_LESSEQUAL, t2 as FUNC_NEVER, t6 as FUNC_NOTEQUAL, eD as FloatPacking, Nu as FlyController, Nx as FocusController, SI as FogParams, PZ as FolderHandler, PQ as Font, P0 as FontHandler, gB as ForwardRenderer, e0 as Frustum, fP as GAMMA_NONE, fL as GAMMA_SRGB, ND as GIZMOAXIS_FACE, NA as GIZMOAXIS_X, NL as GIZMOAXIS_XY, NI as GIZMOAXIS_XYZ, NP as GIZMOAXIS_XZ, Nb as GIZMOAXIS_Y, NC as GIZMOAXIS_YZ, Nw as GIZMOAXIS_Z, NT as GIZMOSPACE_LOCAL, NE as GIZMOSPACE_WORLD, C_ as GSplatComponent, Cy as GSplatComponentSystem, yM as GSplatData, Lc as GSplatHandler, y8 as GSplatInstance, yF as GSplatResource, yO as GSplatResourceBase, y1 as GSplatSogsData, y6 as GSplatSogsResource, dj as GamePads, Nr as GamepadSource, vQ as Geometry, NU as Gizmo, Oo as GltfExporter, _c as GraphNode, nD as GraphicsDevice, Lm as HierarchyHandler, L_ as HtmlHandler, d0 as Http, xq as I18n, it as INDEXFORMAT_UINT16, ii as INDEXFORMAT_UINT32, ie as INDEXFORMAT_UINT8, Tv as INTERPOLATION_CUBIC, Tg as INTERPOLATION_LINEAR, T_ as INTERPOLATION_STEP, AL as ImageElement, lJ as IndexBuffer, el as IndexedList, OZ as InputConsumer, OQ as InputController, O$ as InputDelta, Oj as InputFrame, OK as InputSource, bi as JointComponent, bn as JointComponentSystem, Lg as JsonHandler, LS as JsonStandardMaterialParser, hV as KEY_0, hz as KEY_1, hG as KEY_2, hH as KEY_3, hW as KEY_4, hX as KEY_5, hY as KEY_6, hq as KEY_7, h$ as KEY_8, hj as KEY_9, hQ as KEY_A, cC as KEY_ADD, hA as KEY_ALT, hJ as KEY_B, hv as KEY_BACKSPACE, c$ as KEY_BACK_SLASH, h0 as KEY_C, hw as KEY_CAPS_LOCK, cj as KEY_CLOSE_BRACKET, cW as KEY_COMMA, cm as KEY_CONTEXT_MENU, hE as KEY_CONTROL, h1 as KEY_D, cI as KEY_DECIMAL, hk as KEY_DELETE, cD as KEY_DIVIDE, hF as KEY_DOWN, h2 as KEY_E, hD as KEY_END, hx as KEY_ENTER, hZ as KEY_EQUAL, hC as KEY_ESCAPE, h3 as KEY_F, cR as KEY_F1, cz as KEY_F10, cG as KEY_F11, cH as KEY_F12, cM as KEY_F2, cO as KEY_F3, cN as KEY_F4, cF as KEY_F5, cB as KEY_F6, cU as KEY_F7, ck as KEY_F8, cV as KEY_F9, h4 as KEY_G, h5 as KEY_H, hR as KEY_HOME, h8 as KEY_I, hU as KEY_INSERT, h6 as KEY_J, h9 as KEY_K, h7 as KEY_L, hM as KEY_LEFT, ce as KEY_M, cK as KEY_META, cw as KEY_MULTIPLY, ct as KEY_N, c_ as KEY_NUMPAD_0, cg as KEY_NUMPAD_1, cv as KEY_NUMPAD_2, cS as KEY_NUMPAD_3, cy as KEY_NUMPAD_4, cx as KEY_NUMPAD_5, cT as KEY_NUMPAD_6, cE as KEY_NUMPAD_7, cA as KEY_NUMPAD_8, cb as KEY_NUMPAD_9, ci as KEY_O, cq as KEY_OPEN_BRACKET, cs as KEY_P, hI as KEY_PAGE_DOWN, hL as KEY_PAGE_UP, hb as KEY_PAUSE, cX as KEY_PERIOD, hB as KEY_PRINT_SCREEN, cr as KEY_Q, ca as KEY_R, hy as KEY_RETURN, hN as KEY_RIGHT, cn as KEY_S, hK as KEY_SEMICOLON, cP as KEY_SEPARATOR, hT as KEY_SHIFT, cY as KEY_SLASH, hP as KEY_SPACE, cL as KEY_SUBTRACT, co as KEY_T, hS as KEY_TAB, cl as KEY_U, hO as KEY_UP, ch as KEY_V, cc as KEY_W, cp as KEY_WINDOWS, cd as KEY_X, cu as KEY_Y, cf as KEY_Z, eR as Kernel, RA as Key, dR as Keyboard, dC as KeyboardEvent, Nt as KeyboardMouseSource, uw as LAYERID_DEPTH, uP as LAYERID_IMMEDIATE, uC as LAYERID_SKYBOX, uL as LAYERID_UI, ub as LAYERID_WORLD, uE as LAYER_GIZMO, uT as LAYER_HUD, uA as LAYER_WORLD, uH as LIGHTFALLOFF_INVERSESQUARED, uG as LIGHTFALLOFF_LINEAR, uk as LIGHTSHAPE_DISK, uB as LIGHTSHAPE_PUNCTUAL, uU as LIGHTSHAPE_RECT, uV as LIGHTSHAPE_SPHERE, uO as LIGHTTYPE_COUNT, uI as LIGHTTYPE_DIRECTIONAL, uD as LIGHTTYPE_OMNI, uR as LIGHTTYPE_POINT, uM as LIGHTTYPE_SPOT, uF as LIGHT_COLOR_DIVIDER, gH as Layer, gY as LayerComposition, bT as LayoutCalculator, bo as LayoutChildComponent, bc as LayoutChildComponentSystem, bb as LayoutGroupComponent, bP as LayoutGroupComponentSystem, g2 as Light, w6 as LightComponent, w9 as LightComponentSystem, g3 as LightingParams, Tf as Lightmapper, SJ as LitMaterial, Rw as LitOptions, SX as LitShaderOptions, AI as LocalizedAsset, po as MASK_AFFECT_DYNAMIC, pl as MASK_AFFECT_LIGHTMAPPED, ph as MASK_BAKE, A9 as MOTION_FREE, A7 as MOTION_LIMITED, be as MOTION_LOCKED, cQ as MOUSEBUTTON_LEFT, cJ as MOUSEBUTTON_MIDDLE, cZ as MOUSEBUTTON_NONE, c0 as MOUSEBUTTON_RIGHT, eO as Mat3, eG as Mat4, _$ as Material, Lx as MaterialHandler, mw as Mesh, mV as MeshInstance, Ma as MiniStats, g5 as Model, bR as ModelComponent, bN as ModelComponentSystem, Lw as ModelHandler, g8 as Morph, g4 as MorphInstance, g6 as MorphTarget, dN as Mouse, dO as MouseEvent, O8 as MultiTouchSource, Rb as Node, l$ as NullGraphicsDevice, pG as ORIENTATION_HORIZONTAL, pH as ORIENTATION_VERTICAL, Ng as OrbitController, e8 as OrientedBox, Mh as OutlineRenderer, c1 as PAD_1, c2 as PAD_2, c3 as PAD_3, c4 as PAD_4, dh as PAD_DOWN, c5 as PAD_FACE_1, c8 as PAD_FACE_2, c6 as PAD_FACE_3, c9 as PAD_FACE_4, dc as PAD_LEFT, c7 as PAD_L_SHOULDER_1, dt as PAD_L_SHOULDER_2, da as PAD_L_STICK_BUTTON, df as PAD_L_STICK_X, dp as PAD_L_STICK_Y, dd as PAD_RIGHT, de as PAD_R_SHOULDER_1, di as PAD_R_SHOULDER_2, dn as PAD_R_STICK_BUTTON, dm as PAD_R_STICK_X, d_ as PAD_R_STICK_Y, ds as PAD_SELECT, dr as PAD_START, dl as PAD_UP, du as PAD_VENDOR, fl as PARTICLEMODE_CPU, fo as PARTICLEMODE_GPU, ff as PARTICLEORIENTATION_EMITTER, fd as PARTICLEORIENTATION_SCREEN, fu as PARTICLEORIENTATION_WORLD, fr as PARTICLESORT_DISTANCE, fa as PARTICLESORT_NEWER_FIRST, fs as PARTICLESORT_NONE, fn as PARTICLESORT_OLDER_FIRST, iE as PIXELFORMAT_111110F, is as PIXELFORMAT_A8, iM as PIXELFORMAT_ASTC_4x4, se as PIXELFORMAT_ASTC_4x4_SRGB, iO as PIXELFORMAT_ATC_RGB, iN as PIXELFORMAT_ATC_RGBA, si as PIXELFORMAT_BC6F, ss as PIXELFORMAT_BC6UF, sr as PIXELFORMAT_BC7, sa as PIXELFORMAT_BC7_SRGBA, iF as PIXELFORMAT_BGRA8, ix as PIXELFORMAT_DEPTH, sn as PIXELFORMAT_DEPTH16, iT as PIXELFORMAT_DEPTHSTENCIL, iu as PIXELFORMAT_DXT1, i5 as PIXELFORMAT_DXT1_SRGB, ip as PIXELFORMAT_DXT3, i8 as PIXELFORMAT_DXT3_SRGBA, im as PIXELFORMAT_DXT5, i6 as PIXELFORMAT_DXT5_SRGBA, iw as PIXELFORMAT_ETC1, iC as PIXELFORMAT_ETC2_RGB, iP as PIXELFORMAT_ETC2_RGBA, i9 as PIXELFORMAT_ETC2_SRGB, i7 as PIXELFORMAT_ETC2_SRGBA, ir as PIXELFORMAT_L8, Dj as PIXELFORMAT_L8_A8, ia as PIXELFORMAT_LA8, iI as PIXELFORMAT_PVRTC_2BPP_RGBA_1, iL as PIXELFORMAT_PVRTC_2BPP_RGB_1, iR as PIXELFORMAT_PVRTC_4BPP_RGBA_1, iD as PIXELFORMAT_PVRTC_4BPP_RGB_1, i1 as PIXELFORMAT_R16F, ik as PIXELFORMAT_R16I, iV as PIXELFORMAT_R16U, iy as PIXELFORMAT_R32F, iz as PIXELFORMAT_R32I, iG as PIXELFORMAT_R32U, DQ as PIXELFORMAT_R4_G4_B4_A4, DZ as PIXELFORMAT_R5_G5_B5_A1, DK as PIXELFORMAT_R5_G6_B5, i3 as PIXELFORMAT_R8, iB as PIXELFORMAT_R8I, iU as PIXELFORMAT_R8U, DJ as PIXELFORMAT_R8_G8_B8, D0 as PIXELFORMAT_R8_G8_B8_A8, i2 as PIXELFORMAT_RG16F, iX as PIXELFORMAT_RG16I, iY as PIXELFORMAT_RG16U, iq as PIXELFORMAT_RG32I, i$ as PIXELFORMAT_RG32U, i4 as PIXELFORMAT_RG8, iH as PIXELFORMAT_RG8I, iW as PIXELFORMAT_RG8U, i_ as PIXELFORMAT_RGB16F, iv as PIXELFORMAT_RGB32F, io as PIXELFORMAT_RGB565, ic as PIXELFORMAT_RGB8, ig as PIXELFORMAT_RGBA16F, iZ as PIXELFORMAT_RGBA16I, iQ as PIXELFORMAT_RGBA16U, iS as PIXELFORMAT_RGBA32F, iJ as PIXELFORMAT_RGBA32I, i0 as PIXELFORMAT_RGBA32U, ih as PIXELFORMAT_RGBA4, il as PIXELFORMAT_RGBA5551, id as PIXELFORMAT_RGBA8, ij as PIXELFORMAT_RGBA8I, iK as PIXELFORMAT_RGBA8U, st as PIXELFORMAT_SBGRA8, D1 as PIXELFORMAT_SRGB, iA as PIXELFORMAT_SRGB8, D2 as PIXELFORMAT_SRGBA, ib as PIXELFORMAT_SRGBA8, sg as PRIMITIVE_LINELOOP, s_ as PRIMITIVE_LINES, sv as PRIMITIVE_LINESTRIP, sm as PRIMITIVE_POINTS, sS as PRIMITIVE_TRIANGLES, sx as PRIMITIVE_TRIFAN, sy as PRIMITIVE_TRISTRIP, fm as PROJECTION_ORTHOGRAPHIC, fp as PROJECTION_PERSPECTIVE, vW as ParticleEmitter, bV as ParticleSystemComponent, bX as ParticleSystemComponentSystem, Dm as Picker, eJ as Plane, yE as PlaneGeometry, Oq as Pose, SH as PostEffect, w0 as PostEffectQueue, yb as ProgramLibrary, mp as QuadRender, eH as Quat, fY as REFLECTIONSRC_CUBEMAP, fW as REFLECTIONSRC_ENVATLAS, fX as REFLECTIONSRC_ENVATLASHQ, fH as REFLECTIONSRC_NONE, fq as REFLECTIONSRC_SPHEREMAP, fv as RENDERSTYLE_POINTS, f_ as RENDERSTYLE_SOLID, fg as RENDERSTYLE_WIREFRAME, xt as RESOLUTION_AUTO, xi as RESOLUTION_FIXED, R0 as RIGIDBODY_ACTIVE_TAG, RQ as RIGIDBODY_CF_KINEMATIC_OBJECT, RJ as RIGIDBODY_CF_NORESPONSE_OBJECT, RZ as RIGIDBODY_CF_STATIC_OBJECT, R3 as RIGIDBODY_DISABLE_DEACTIVATION, R4 as RIGIDBODY_DISABLE_SIMULATION, R1 as RIGIDBODY_ISLAND_SLEEPING, Rj as RIGIDBODY_TYPE_DYNAMIC, RK as RIGIDBODY_TYPE_KINEMATIC, R$ as RIGIDBODY_TYPE_STATIC, R2 as RIGIDBODY_WANTS_DEACTIVATION, e1 as Ray, b8 as RaycastResult, eu as ReadStream, bj as RenderComponent, bJ as RenderComponentSystem, Cb as RenderHandler, l2 as RenderPass, Og as RenderPassBloom, OH as RenderPassCameraFrame, m$ as RenderPassColorGrab, Oy as RenderPassCompose, OB as RenderPassDepthAwareBlur, OR as RenderPassDof, Of as RenderPassDownsample, gR as RenderPassForward, OO as RenderPassPrepass, SW as RenderPassShaderQuad, OV as RenderPassSsao, Ob as RenderPassTAA, O_ as RenderPassUpsample, nM as RenderTarget, xH as ResourceHandler, xX as ResourceLoader, b4 as RigidBodyComponent, wt as RigidBodyComponentSystem, FA as RotateGizmo, rv as SAMPLETYPE_DEPTH, r_ as SAMPLETYPE_FLOAT, rS as SAMPLETYPE_INT, ry as SAMPLETYPE_UINT, rg as SAMPLETYPE_UNFILTERABLE_FLOAT, ws as SCALEMODE_BLEND, wi as SCALEMODE_NONE, wx as SCROLLBAR_VISIBILITY_SHOW_ALWAYS, wT as SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED, wS as SCROLL_MODE_BOUNCE, wv as SCROLL_MODE_CLAMP, wy as SCROLL_MODE_INFINITE, sB as SEMANTIC_ATTR0, sU as SEMANTIC_ATTR1, sq as SEMANTIC_ATTR10, s$ as SEMANTIC_ATTR11, sj as SEMANTIC_ATTR12, sK as SEMANTIC_ATTR13, sZ as SEMANTIC_ATTR14, sQ as SEMANTIC_ATTR15, sk as SEMANTIC_ATTR2, sV as SEMANTIC_ATTR3, sz as SEMANTIC_ATTR4, sG as SEMANTIC_ATTR5, sH as SEMANTIC_ATTR6, sW as SEMANTIC_ATTR7, sX as SEMANTIC_ATTR8, sY as SEMANTIC_ATTR9, sw as SEMANTIC_BLENDINDICES, sb as SEMANTIC_BLENDWEIGHT, sC as SEMANTIC_COLOR, sE as SEMANTIC_NORMAL, sT as SEMANTIC_POSITION, sA as SEMANTIC_TANGENT, sP as SEMANTIC_TEXCOORD, sL as SEMANTIC_TEXCOORD0, sI as SEMANTIC_TEXCOORD1, sD as SEMANTIC_TEXCOORD2, sR as SEMANTIC_TEXCOORD3, sM as SEMANTIC_TEXCOORD4, sO as SEMANTIC_TEXCOORD5, sN as SEMANTIC_TEXCOORD6, sF as SEMANTIC_TEXCOORD7, ps as SHADERDEF_BATCH, f8 as SHADERDEF_DIRLM, f4 as SHADERDEF_INSTANCING, f5 as SHADERDEF_LM, pt as SHADERDEF_LMAMBIENT, pe as SHADERDEF_MORPH_NORMAL, f7 as SHADERDEF_MORPH_POSITION, pi as SHADERDEF_MORPH_TEXTURE_BASED_INT, fJ as SHADERDEF_NOSHADOW, f6 as SHADERDEF_SCREENSPACE, f0 as SHADERDEF_SKIN, f9 as SHADERDEF_TANGENTS, f1 as SHADERDEF_UV0, f2 as SHADERDEF_UV1, f3 as SHADERDEF_VCOLOR, rb as SHADERLANGUAGE_GLSL, rw as SHADERLANGUAGE_WGSL, pm as SHADERPASS_ALBEDO, px as SHADERPASS_AO, pT as SHADERPASS_EMISSION, pp as SHADERPASS_FORWARD, pS as SHADERPASS_GLOSS, pE as SHADERPASS_LIGHTING, py as SHADERPASS_METALNESS, pg as SHADERPASS_OPACITY, pv as SHADERPASS_SPECULARITY, pA as SHADERPASS_UV0, p_ as SHADERPASS_WORLDNORMAL, aI as SHADERSTAGE_COMPUTE, aL as SHADERSTAGE_FRAGMENT, aP as SHADERSTAGE_VERTEX, sJ as SHADERTAG_MATERIAL, pc as SHADER_FORWARD, pf as SHADER_PICK, pd as SHADER_PREPASS, pu as SHADER_SHADOW, pr as SHADOWUPDATE_NONE, pn as SHADOWUPDATE_REALTIME, pa as SHADOWUPDATE_THISFRAME, u8 as SHADOW_CASCADE_0, u6 as SHADOW_CASCADE_1, u9 as SHADOW_CASCADE_2, u7 as SHADOW_CASCADE_3, fe as SHADOW_CASCADE_ALL, u0 as SHADOW_PCF1, u2 as SHADOW_PCF1_16F, uJ as SHADOW_PCF1_32F, uY as SHADOW_PCF3, u3 as SHADOW_PCF3_16F, uX as SHADOW_PCF3_32F, uQ as SHADOW_PCF5, u4 as SHADOW_PCF5_16F, uZ as SHADOW_PCF5_32F, u1 as SHADOW_PCSS_32F, u$ as SHADOW_VSM16, uK as SHADOW_VSM32, uq as SHADOW_VSM_16F, uj as SHADOW_VSM_32F, pX as SKYTYPE_BOX, pY as SKYTYPE_DOME, pW as SKYTYPE_INFINITE, pB as SORTMODE_BACK2FRONT, pk as SORTMODE_CUSTOM, pU as SORTMODE_FRONT2BACK, pN as SORTMODE_MANUAL, pF as SORTMODE_MATERIALMESH, pO as SORTMODE_NONE, fV as SPECOCC_AO, fz as SPECOCC_GLOSSDEPENDENT, fk as SPECOCC_NONE, wk as SPRITETYPE_ANIMATED, wU as SPRITETYPE_SIMPLE, pb as SPRITE_RENDERMODE_SIMPLE, pw as SPRITE_RENDERMODE_SLICED, pC as SPRITE_RENDERMODE_TILED, Oc as SSAOTYPE_COMBINE, Oh as SSAOTYPE_LIGHTING, Ol as SSAOTYPE_NONE, s5 as STENCILOP_DECREMENT, s8 as STENCILOP_DECREMENTWRAP, s3 as STENCILOP_INCREMENT, s4 as STENCILOP_INCREMENTWRAP, s6 as STENCILOP_INVERT, s0 as STENCILOP_KEEP, s2 as STENCILOP_REPLACE, s1 as STENCILOP_ZERO, FO as ScaleGizmo, SD as Scene, LC as SceneHandler, x3 as SceneRegistry, x2 as SceneRegistryItem, D_ as SceneSettingsHandler, nS as ScopeId, ny as ScopeSpace, wa as ScreenComponent, wl as ScreenComponentSystem, Co as Script, Cr as ScriptAttributes, Cu as ScriptComponent, Cm as ScriptComponentSystem, LN as ScriptHandler, x$ as ScriptRegistry, Cc as ScriptType, wA as ScrollViewComponent, wC as ScrollViewComponentSystem, wP as ScrollbarComponent, wD as ScrollbarComponentSystem, la as Shader, mr as ShaderChunks, LF as ShaderHandler, vY as ShaderMaterial, mt as ShaderPass, mo as ShaderUtils, b6 as SingleContactResult, O1 as SingleGestureSource, Sz as Skeleton, SR as Skin, mT as SkinBatchInstance, mx as SkinInstance, v4 as Sky, ef as SortedLoopArray, d7 as Sound, wO as SoundComponent, wB as SoundComponentSystem, ut as SoundInstance, ui as SoundInstance3d, d9 as SoundManager, wM as SoundSlot, v0 as SphereGeometry, SN as Sprite, wV as SpriteAnimationClip, wX as SpriteComponent, w$ as SpriteComponentSystem, Lk as SpriteHandler, yo as StandardMaterial, S0 as StandardMaterialOptions, nI as StencilParameters, lE as StorageBuffer, rl as TEXHINT_ASSET, rh as TEXHINT_LIGHTMAP, rn as TEXHINT_NONE, ro as TEXHINT_SHADOWMAP, aF as TEXPROPERTY_ADDRESS_U, aB as TEXPROPERTY_ADDRESS_V, aU as TEXPROPERTY_ADDRESS_W, aG as TEXPROPERTY_ALL, az as TEXPROPERTY_ANISOTROPY, aV as TEXPROPERTY_COMPARE_FUNC, ak as TEXPROPERTY_COMPARE_ON_READ, aN as TEXPROPERTY_MAG_FILTER, aO as TEXPROPERTY_MIN_FILTER, rc as TEXTUREDIMENSION_1D, rd as TEXTUREDIMENSION_2D, ru as TEXTUREDIMENSION_2D_ARRAY, rm as TEXTUREDIMENSION_3D, rf as TEXTUREDIMENSION_CUBE, rp as TEXTUREDIMENSION_CUBE_ARRAY, s9 as TEXTURELOCK_NONE, s7 as TEXTURELOCK_READ, re as TEXTURELOCK_WRITE, rT as TEXTUREPROJECTION_CUBE, rE as TEXTUREPROJECTION_EQUIRECT, rx as TEXTUREPROJECTION_NONE, rA as TEXTUREPROJECTION_OCTAHEDRAL, rt as TEXTURETYPE_DEFAULT, rs as TEXTURETYPE_RGBE, ri as TEXTURETYPE_RGBM, rr as TEXTURETYPE_RGBP, ra as TEXTURETYPE_SWIZZLEGGGR, fO as TONEMAP_ACES, fN as TONEMAP_ACES2, fR as TONEMAP_FILMIC, fM as TONEMAP_HEJL, fD as TONEMAP_LINEAR, fF as TONEMAP_NEUTRAL, fB as TONEMAP_NONE, R as TRACEID_BINDGROUPFORMAT_ALLOC, D as TRACEID_BINDGROUP_ALLOC, O as TRACEID_COMPUTEPIPELINE_ALLOC, F as TRACEID_ELEMENT, k as TRACEID_GPU_TIMINGS, N as TRACEID_PIPELINELAYOUT_ALLOC, M as TRACEID_RENDERPIPELINE_ALLOC, T as TRACEID_RENDER_ACTION, v as TRACEID_RENDER_FRAME, S as TRACEID_RENDER_FRAME_TIME, y as TRACEID_RENDER_PASS, x as TRACEID_RENDER_PASS_DETAIL, U as TRACEID_RENDER_QUEUE, E as TRACEID_RENDER_TARGET_ALLOC, b as TRACEID_SHADER_ALLOC, w as TRACEID_SHADER_COMPILE, B as TRACEID_TEXTURES, A as TRACEID_TEXTURE_ALLOC, L as TRACEID_VRAM_IB, I as TRACEID_VRAM_SB, C as TRACEID_VRAM_TEXTURE, P as TRACEID_VRAM_VB, rO as TYPE_FLOAT16, rM as TYPE_FLOAT32, rL as TYPE_INT16, rD as TYPE_INT32, rC as TYPE_INT8, rI as TYPE_UINT16, rR as TYPE_UINT32, rP as TYPE_UINT8, ep as Tags, LV as Template, Lz as TemplateHandler, Aj as TextElement, LG as TextHandler, ns as Texture, SF as TextureAtlas, LY as TextureAtlasHandler, Il as TextureHandler, nt as TextureUtils, yA as TorusGeometry, dZ as Touch, dJ as TouchDevice, dQ as TouchEvent, eS as Tracing, l3 as TransformFeedback, NQ as TransformGizmo, Fp as TranslateGizmo, ti as Tri, rN as UNIFORMTYPE_BOOL, as as UNIFORMTYPE_BOOLARRAY, rW as UNIFORMTYPE_BVEC2, an as UNIFORMTYPE_BVEC2ARRAY, rX as UNIFORMTYPE_BVEC3, ah as UNIFORMTYPE_BVEC3ARRAY, rY as UNIFORMTYPE_BVEC4, au as UNIFORMTYPE_BVEC4ARRAY, rB as UNIFORMTYPE_FLOAT, rQ as UNIFORMTYPE_FLOATARRAY, rF as UNIFORMTYPE_INT, at as UNIFORMTYPE_INTARRAY, af as UNIFORMTYPE_ITEXTURE2D, aS as UNIFORMTYPE_ITEXTURE2D_ARRAY, ag as UNIFORMTYPE_ITEXTURE3D, am as UNIFORMTYPE_ITEXTURECUBE, rz as UNIFORMTYPE_IVEC2, ar as UNIFORMTYPE_IVEC2ARRAY, rG as UNIFORMTYPE_IVEC3, ao as UNIFORMTYPE_IVEC3ARRAY, rH as UNIFORMTYPE_IVEC4, ac as UNIFORMTYPE_IVEC4ARRAY, rq as UNIFORMTYPE_MAT2, r$ as UNIFORMTYPE_MAT3, rj as UNIFORMTYPE_MAT4, r5 as UNIFORMTYPE_MAT4ARRAY, rK as UNIFORMTYPE_TEXTURE2D, r8 as UNIFORMTYPE_TEXTURE2D_ARRAY, rJ as UNIFORMTYPE_TEXTURE2D_SHADOW, r1 as UNIFORMTYPE_TEXTURE3D, rZ as UNIFORMTYPE_TEXTURECUBE, r0 as UNIFORMTYPE_TEXTURECUBE_SHADOW, r6 as UNIFORMTYPE_UINT, ai as UNIFORMTYPE_UINTARRAY, ap as UNIFORMTYPE_UTEXTURE2D, ay as UNIFORMTYPE_UTEXTURE2D_ARRAY, av as UNIFORMTYPE_UTEXTURE3D, a_ as UNIFORMTYPE_UTEXTURECUBE, r9 as UNIFORMTYPE_UVEC2, aa as UNIFORMTYPE_UVEC2ARRAY, r7 as UNIFORMTYPE_UVEC3, al as UNIFORMTYPE_UVEC3ARRAY, ae as UNIFORMTYPE_UVEC4, ad as UNIFORMTYPE_UVEC4ARRAY, rU as UNIFORMTYPE_VEC2, r2 as UNIFORMTYPE_VEC2ARRAY, rk as UNIFORMTYPE_VEC3, r3 as UNIFORMTYPE_VEC3ARRAY, rV as UNIFORMTYPE_VEC4, r4 as UNIFORMTYPE_VEC4ARRAY, aq as UNIFORM_BUFFER_DEFAULT_SLOT_NAME, a$ as UNUSED_UNIFORM_NAME, ev as URI, on as UniformBufferFormat, oa as UniformFormat, M7 as UsdzExporter, pD as VIEW_CENTER, pR as VIEW_LEFT, pM as VIEW_RIGHT, eN as Vec2, eM as Vec3, eF as Vec4, nT as VertexBuffer, nP as VertexFormat, ho as VertexIterator, Fk as ViewCube, ed as WasmModule, lG as WebglGraphicsDevice, lb as WebgpuGraphicsDevice, _L as WorldClusters, IM as XRDEPTHSENSINGFORMAT_F32, ID as XRDEPTHSENSINGFORMAT_L8A8, IR as XRDEPTHSENSINGFORMAT_R16U, IL as XRDEPTHSENSINGUSAGE_CPU, II as XRDEPTHSENSINGUSAGE_GPU, Ix as XREYE_LEFT, Iy as XREYE_NONE, IT as XREYE_RIGHT, IA as XRHAND_LEFT, IE as XRHAND_NONE, Ib as XRHAND_RIGHT, db as XRPAD_A, dw as XRPAD_B, dE as XRPAD_SQUEEZE, dA as XRPAD_STICK_BUTTON, dS as XRPAD_STICK_X, dy as XRPAD_STICK_Y, dx as XRPAD_TOUCHPAD_BUTTON, dg as XRPAD_TOUCHPAD_X, dv as XRPAD_TOUCHPAD_Y, dT as XRPAD_TRIGGER, Im as XRSPACE_BOUNDEDFLOOR, If as XRSPACE_LOCAL, Ip as XRSPACE_LOCALFLOOR, I_ as XRSPACE_UNBOUNDED, Iu as XRSPACE_VIEWER, Ig as XRTARGETRAY_GAZE, IS as XRTARGETRAY_POINTER, Iv as XRTARGETRAY_SCREEN, IP as XRTRACKABLE_MESH, IC as XRTRACKABLE_PLANE, Iw as XRTRACKABLE_POINT, Id as XRTYPE_AR, Ih as XRTYPE_INLINE, Ic as XRTYPE_VR, I7 as XrAnchor, De as XrAnchors, IO as XrDomOverlay, Iz as XrFinger, Ij as XrHand, IU as XrHitTest, IB as XrHitTestSource, IV as XrImageTracking, I0 as XrInput, IJ as XrInputSource, IW as XrJoint, I5 as XrLightEstimation, Da as XrManager, Di as XrMeshDetection, I6 as XrPlane, I9 as XrPlaneDetection, Ik as XrTrackedImage, Ds as XrView, Dr as XrViews, wj as ZoneComponent, wQ as ZoneComponentSystem, fQ as ambientSrcNames, x6 as app, L2 as basisInitialize, aY as bindGroupNames, up as blendNames, vK as calculateNormals, vZ as calculateTangents, Rm as createBox, Rg as createCapsule, Rv as createCone, RS as createCylinder, lj as createGraphicsDevice, Ry as createMesh, Rp as createPlane, LD as createScript, ml as createShader, mh as createShaderFromCode, Rf as createSphere, R_ as createTorus, e_ as createURI, fx as cubemaProjectionNames, pZ as ditherNames, CM as dracoInitialize, Rx as drawFullscreenQuad, mg as drawQuadWithShader, G as extend, ux as fresnelNames, fI as gammaNames, sp as getPixelFormatArrayType, LI as getReservedScriptNames, dK as getTouchTargetCoords, H as guid, d1 as http, sl as isCompressedPixelFormat, sc as isIntegerPixelFormat, sh as isSrgbPixelFormat, uW as lightFalloffNames, uz as lightShapeNames, uN as lightTypeNames, eA as math, em as now, W as path, su as pixelFormatGammaToLinear, so as pixelFormatInfo, sd as pixelFormatLinearToGamma, ee as platform, a1 as primitiveGlslToWgslTypeMap, f$ as reflectionSrcNames, LM as registerScript, ST as reprojectTexture, sf as requiresManualGamma, z as revision, xr as script, a2 as semanticToLocation, RC as shaderChunks, u5 as shadowTypeInfo, fG as specularOcclusionNames, pP as spriteRenderModeNames, ea as string, fU as tonemapNames, aJ as typedArrayIndexFormats, a0 as typedArrayIndexFormatsByteSize, aQ as typedArrayToType, aj as typedArrayTypes, aK as typedArrayTypesByteSize, ax as uniformTypeToName, aE as uniformTypeToNameMapWGSL, aT as uniformTypeToNameWGSL, aA as uniformTypeToStorage, V as version, aZ as vertexTypesNames };